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
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" ]
import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n = int(input()) p = [0] + list(map(int, input().split())) inf = pow(10, 9) + 1 dp1 = [[inf] * (n + 1) for _ in range(n + 1)] dp2 = [[inf] * (n + 1) for _ in range(n + 1)] dp1[0][0] = 0 dp2[0][0] = 0 for i in range(1, n + 1): ...
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" ]
# zdjfhdaskjfhjsdkahfjkdskfjsdkjfhsdfdsfsdfdfd t = int(input()) for _ in range(t): a, b, c = map(int, input().split()) ans = 0 if a > 0: a -= 1 ans += 1 if b > 0: b -= 1 ans += 1 if c > 0: c -= 1 ans += 1 cDown = False if c > 1: if c > 0 and b > 0: c -= 1 b -= 1 ...
py
1291
A
A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne num...
[ "greedy", "math", "strings" ]
for _ in range(int(input())): n = int(input()) s = list(map(int, input())) e = [d for d in s if d & 1] print(-1 if len(e) < 2 else f"{e[0]}{e[1]}")
py
1141
E
E. Superhero Battletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA superhero fights with a monster. The battle consists of rounds; each of which lasts exactly nn minutes. After a round ends, the next round starts immediately. This is repeated over and over again.E...
[ "math" ]
h,n=input().split(' ') h=int(h) n=int(n) a=input().split(' ') for i in range(n): a[i]=int(a[i]) sum=h flag=False cur=0 for i in range(n): if(sum<=0): print(i) exit(0) sum+=a[i] cur+=a[i] if(sum>=h): print(-1) exit(0) sum=cur l=0 r=1000000000008 ans=2**100 wh...
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" ]
class RMQMIN(): #for MIN queries def __init__(self,arr): self.arr=arr MAXN=len(arr) # build log table for fast lookup self.log2=[0]*(MAXN+1) i=0 while 2**i<(MAXN+1): self.log2[2**i]=i;i+=1 for i in range(1,MAXN+1): if self.l...
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" ]
num=int(input()) for i in range(num): a,b,c,n=[int(i) for i in input().split()] d=max(a,b,c) s=0 for j in range(1): if d!=a: s=s+(d-a) if d!=b: s=s+(d-b) if d!=c: s=s+(d-c) if (n-s)%3==0 and (n-s)>=0: print("YES") ...
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" ]
for _ in range(int(input())): n = int(input()) nums = list(map(int, input().split())) total = sum(nums) f = 0 mx = nums[1] if mx >= total: print("NO") continue for i in range(2, len(nums)): mx = max(mx + nums[i], nums[i]) if mx >= total: f = 1 break if f: ...
py
1303
E
E. Erase Subsequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. You can build new string pp from ss using the following operation no more than two times: choose any subsequence si1,si2,…,siksi1,si2,…,sik where 1≤i1<i2<⋯<ik≤|s|1≤i1<i...
[ "dp", "strings" ]
# by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO,IOBase from math import inf,isinf def solve(s,t): if len(t) == 1: if s.count(t[0]): return 'YES' return 'NO' for i in range(1,len(t)): dp = [[-inf]*(i+1) for _ in r...
py
1313
C1
C1. Skyscrapers (easy version)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem. In this version n≤1000n≤1000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the constructio...
[ "brute force", "data structures", "dp", "greedy" ]
import sys from math import sqrt, gcd, factorial, ceil, floor, pi, inf, isqrt, lcm from collections import deque, Counter, OrderedDict, defaultdict from heapq import heapify, heappush, heappop #sys.setrecursionlimit(10**5) from functools import lru_cache #@lru_cache(None) #=====================================...
py
1304
F2
F2. Animal Observation (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on kk.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The ...
[ "data structures", "dp", "greedy" ]
import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def update(l, r, s): q, lr, i = [1], [(0, l1 - 1)], 0 while len(q) ^ i: j = q[i] l0, r0 = lr[i] if l <= l0 and r0 <= r: lazy[j] += s i += 1 continue m0...
py
1141
C
C. Polycarp Restores Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array of integers p1,p2,…,pnp1,p2,…,pn is called a permutation if it contains each number from 11 to nn exactly once. For example, the following arrays are permutations: [3,1,2][3,1,2...
[ "math" ]
n=int(input()) qs=list(map(int,input().split())) perm=[None for i in range(n)] decrease=0 increase=0 diff=0 firstind=0 lastind=0 for i in range(n-1): q=qs[i] if q>0 and q>decrease: decrease=0 else: decrease-=q if q<0 and -q>increase: increase=0 else: increase+=q if decrease>abs(d...
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" ]
from collections import defaultdict, deque from string import ascii_lowercase for _ in range(int(input())): password = input() graph = defaultdict(set) for i in range(1,len(password)): graph[password[i - 1]].add(password[i]) graph[password[i]].add(password[i - 1]) ...
py
1325
D
D. Ehab the Xorcisttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven 2 integers uu and vv, find the shortest array such that bitwise-xor of its elements is uu, and the sum of its elements is vv.InputThe only line contains 2 integers uu and vv (0≤u,v≤1018)(0≤u,v≤1...
[ "bitmasks", "constructive algorithms", "greedy", "number theory" ]
import sys input = lambda: sys.stdin.readline().rstrip() u, v = map(int, input().split()) def distinctBits(a, b): return a & b == 0 if u > v or v % 2 != u % 2: print(-1) elif u == v: if u == 0: print(0) else: print(1) print(u) elif distinctBits(u, (v-u)//2): ...
py
1311
E
E. Construct the Binary Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and dd. You need to construct a rooted binary tree consisting of nn vertices with a root at the vertex 11 and the sum of depths of all vertices equals to dd.A t...
[ "brute force", "constructive algorithms", "trees" ]
from sys import stdin input=lambda :stdin.readline()[:-1] memo=set() def f(n,m,d): if (n,m,d) in memo: return [-1] memo.add((n,m,d)) for i in range(1,2*m+1): n2=n-i d2=d-n if n2>=0 and d2>=0: if n2==0 and d2==0: return [i] res=f(n2,i,d2) if res[0]!=-1: ...
py
1300
B
B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,…,a2k+1][a1,a2,…,a2k+1] of odd number of elements is defined as follows: let [b1,b2,…,b2k+1][b1,b2,…,b2k+1] be the elements of the array in the sorted ord...
[ "greedy", "implementation", "sortings" ]
n=int(input()) t=1 while(t<=n): no=int(input()) arr=[int(k) for k in input().split()] arr.sort() print(arr[no]-arr[no-1]) t+=1
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" ]
n = int(input()) k = input() l = k.count("L") r = k.count("R") print(l+r+1)
py
1305
F
F. Kuroni and the Punishmenttime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is very angry at the other setters for using him as a theme! As a punishment; he forced them to solve the following problem:You have an array aa consisting of nn positive integers. ...
[ "math", "number theory", "probabilities" ]
import random prime = [1] * (10**6 + 100) div = 2 while div < 1002: i = 2 while div * i <= 10**6+99: prime[div*i] = 0 i += 1 div += 1 while prime[div] == 0 and div < 1002: div += 1 prim = [] for i in range(2,10**6+100): if prime[i] == 1: prim.append(i) def primes(a): odp = set() aa = a ...
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" ]
# Thank God that I'm not you. from itertools import permutations, combinations; import heapq; from collections import Counter, deque; import math; import sys; m, mod = map(int, input().split()) array = list(map(int, input().split())); for i, num in enumerate(array): array[i] = [(num %...
py
1284
A
A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (경자년; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Ko...
[ "implementation", "strings" ]
n, m = map(int, input().split()) s = input().split() t = input().split() for _ in range(int(input())): y = int(input()) print(s[y%n-1], end="") print(t[y%m-1])
py
13
A
A. Numberstime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.Now he wonders what is an average value of ...
[ "implementation", "math" ]
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
1299
B
B. Aerodynamictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon PP which is defined by coordinates of its vertices. Define P(x,y)P...
[ "geometry" ]
n = int(input()) if n % 2 == 1: print('no') else: s = [] for i in range(n): x, y = list(map(int, input().split())) s.append([x, y]) f = True for i in range(0, n // 2 - 1): a11 = s[i] a1 = s[i + 1] dx1 = a1[0] - a11[0] dy1 = a1[1] - a11[1] ...
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" ]
t = int(input()) for _ in range(t): n, s, k = map(int, input().split()) a = list(map(int, input().split())) for i in range(0, k+1): if s-i >= 1 and not s-i in a: print(i) break if s+i <= n and not s+i in a: print(i) break else: a...
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 sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def bfs(s): q, k = [s], 0 inf = pow(10, 9) + 1 dist = [inf] * (n + 1) dist[s] = 0 while len(q) ^ k: i = q[k] di = dist[i] for j in G[i]: if dist[j] == inf: ...
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" ]
from sys import stdin,stdout input = stdin.readline from math import inf # from collections import Counter # from heapq import heapify,heappop,heappush for _ in range(int(input())): n,m=map(int,input().split()) a=list(map(int,input().split())) b=list(map(int,input().split())) d=0 for...
py
1292
B
B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIVΛ - 漂流 KIVΛ & Nikki Simmons - PerspectivesWith a new body; our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can...
[ "brute force", "constructive algorithms", "geometry", "greedy", "implementation" ]
x0, y0, ax, ay, bx, by = map(int, input().split()) xs, ys, t = map(int, input().split()) def dist(x1, y1, x2, y2): return abs(x1-x2)+abs(y1-y2) n = 70 x = [0]*n y = [0]*n x[0] = x0 y[0] = y0 for i in range(1, n): x[i] = ax*x[i-1]+bx y[i] = ay*y[i-1]+by ans = 0 for i in range(n): res = 0 time = ...
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" ]
for _ in range(int(input())): n=int(input()) s=input() k=1 res=s for j in range(1,n+1): mov=n-j+1 t=s[:j-1] final=s[j-1:] if mov%2==0: final+=t else: final=final+t[::-1] if res>final: k=j r...
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= 0 for i in range(n): if int(s[i])%2 == 1: odd += 1 if odd <= 1: print(-1) else: even= str() for k in range(n): if int(s[k])%2 == 1: even += s[k] ...
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 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
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 = input() a = list(map(int,input().split())) print(len(set(a)))
py
1141
B
B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a1,a2,…,ana1,a2,…,an (each aiai is either 00 or 11)...
[ "implementation" ]
n = int(input()) a = [int(x) for x in input().split()] cnt, ans = 0, 0 start_cnt, end_cnt = 0, 0 check = False for i in range(n): if a[i] == 1: cnt += 1 if check == False: start_cnt += 1 else: cnt = 0 check = True if cnt > ans: ans = cnt for i in range(n - 1, -1, ...
py
1300
A
A. Non-zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas have an array aa of nn integers [a1,a2,…,ana1,a2,…,an]. In one step they can add 11 to any element of the array. Formally, in one step they can choose any integer index ii (1≤i≤n1≤i≤n) a...
[ "implementation", "math" ]
for cases in range(int(input())): n=int(input()) a=list(map(int,input().split())) z=a.count(0) s=z+sum(a) if s==0: print(z+1) else: print(z)
py
1304
B
B. Longest Palindrometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputReturning back to problem solving; Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "...
[ "brute force", "constructive algorithms", "greedy", "implementation", "strings" ]
n,m = tuple(map(int,input().split())) l=[] for i in range(n): s = input() l.append(s) ans = [] flag = True for i in range(len(l)): if (l[i]=="#"): continue try: x = l.index(l[i][::-1],i+1) except: x=-1 if (x==-1): if (flag): if(l[i]==...
py
1288
A
A. Deadlinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdilbek was assigned to a special project. For Adilbek it means that he has nn days to run a special program and provide its results. But there is a problem: the program needs to run for dd days to calculate...
[ "binary search", "brute force", "math", "ternary search" ]
import math n = int(input()) for _ in range(n): n, d = map(int, input().split()) bot = int(math.sqrt(d)) + 10 x = 0 while x < bot: if x + (d + x) // (x + 1) <= n: break x += 1 if x < bot: print("YES") else: print("NO")
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" ]
for _ in range(int(input())): n,m,k=map(int,input().split()) a=list(map(int,input().split())) if k>=m: ans=0 for i in range(m): ans=max(ans,a[i],a[n-i-1]) print(ans) else: bmax=0 for x in range(k+1): bmin=float('inf') ...
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()) array1 = list(map(int, input().split())) array2 = list(map(int, input().split())) array = [] for i in range(n): array.append(array1[i] - array2[i]) array.sort() cnt = 0 for i in range(n - 1): l, r = i, n - 1 while r - l > 1: m = (l + r) // 2 if array[i]...
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" ]
for i in range(int(input())): n=int(input()) values=list(map(int,input().split())) total=sum(values) su=0 hey=0 for val in values[:n-1]: su+=val if su<=0: print("NO") hey=1 break elif su>=total: print("NO") ...
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" ]
n, m = [int(_) for _ in input().split()] moves = 0 if m % n != 0: print(-1) else: x = m//n while x % 2 == 0: x = x//2 moves += 1 while x % 3 == 0: x = x//3 moves += 1 if x == 1: print(moves) else: print(-1)
py
1305
C
C. Kuroni and Impossible Calculationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo become the king of Codeforces; Kuroni has to solve the following problem.He is given nn numbers a1,a2,…,ana1,a2,…,an. Help Kuroni to calculate ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj|. As re...
[ "brute force", "combinatorics", "math", "number theory" ]
n , m = map(int, input().split()) l = list(map(int, input().split())) pr = 1 if n > m: exit(print(0)) for i in range(n): for j in range(i+1,n): pr=pr*abs(l[i]-l[j]) pr = pr%m print(pr)
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() import time a = time.time() ke = (int(a*2**20) % (2**20)) + (2**20) pp = 100001000000000000021 def rand(): global ke ke = ke ** 2 % pp return ((ke >> 30) % (1<<15)) + (1<<15) N = int(input()) W = [rand() for _ in range(N)] A = [] ...
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" ]
#!/usr/bin/python3 import sys nc = 0 cases = [] for i, line in enumerate(sys.stdin.readlines()): if i == 0: nc = int(line.strip()) else: case = list([int(x) for x in line.strip().split()]) cases.append(case) defaultDishes = [(1, 0, 0), (1, 1, 0), (1, 0, 1), (1, 1, 1), \ ...
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" ]
def ceil(a,b): if a%b==0:return a//b return a//b+1 import sys input=sys.stdin.readline t=int(input()) for _ in range(t): n,g,b=map(int,input().split()) tar=ceil(n,2) if tar<=g: print(n) else: if tar%g==0: mnd=tar//g #print(mnd) ...
py
1295
C
C. Obtain The Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings ss and tt consisting of lowercase Latin letters. Also you have a string zz which is initially empty. You want string zz to be equal to string tt. You can perform the followi...
[ "dp", "greedy", "strings" ]
from bisect import bisect_right as br from collections import defaultdict from sys import stdin input = stdin.readline for _ in range(int(input())): s = list(input()) t = input() d = defaultdict(list) for i, c in enumerate(s): d[c].append(i) res = 1 prev = -1 for i in t: ...
py
1313
E
E. Concatenation with intersectiontime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVasya had three strings aa, bb and ss, which consist of lowercase English letters. The lengths of strings aa and bb are equal to nn, the length of the string ss is equal to mm. Vasya d...
[ "data structures", "hashing", "strings", "two pointers" ]
import sys, logging logging.basicConfig(level=logging.INFO) logging.disable(logging.INFO) def build(S, n): Z = [0 for i in range(3 * n + 3)] #logging.info(S) n = len(S) L = 0 R = 0 Z[0] = n for i in range(1, n): if(i > R): L = R = i while(R < n ...
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" ]
# https://codeforces.com/problemset/problem/1312/D def f1(n, m): # C(m, n-1) * (n-2) * 2^(n-3) mod = 998244353 def power(base, exp): val = 1 while exp: if exp & 1: val = val * base % mod base = base * base % mod exp >>= 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" ]
from math import log2 for t in range(int(input())): n, m = map(int, input().split()) c = [0] * 61 s = 0 for x in map(int, input().split()): c[int(log2(x))] += 1 s += x if s < n: print(-1) continue i, res = 0, 0 while i < 60: if (1<<i...
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" ]
# author: cholebhature lover from collections import * from bisect import * from heapq import * from math import * import sys def input(): return sys.stdin.readline().rstrip('\r\n') def f(a, b): if a == b: return a else: if a == "S" and b == "T": return "E" ...
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 sys, collections, math, bisect, heapq, random, functools input = sys.stdin.readline out = sys.stdout.flush def dp(a): n = len(a) d = [1] * n pre = [-1] * n for i in range(1,n): for j in range(i): if a[i][0] > a[j][1]: if d[j] + 1 > d[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" ]
import math import sys input = sys.stdin.readline from collections import * def li():return [int(i) for i in input().rstrip('\n').split()] def st():return input().rstrip('\n') def val():return int(input().rstrip('\n')) def li2():return [i for i in input().rstrip('\n')] def li3():return [int(i) for i in input().rstrip('...
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" ]
from sys import stdin input=lambda :stdin.readline()[:-1] class segtree(): def __init__(self,init,func,ide): self.n=len(init) self.func=func self.ide=ide self.size=1<<(self.n-1).bit_length() self.tree=[self.ide for i in range(2*self.size)] for i in range(self.n): self.tree[se...
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: break if cnt > m_cnt: m_cnt = cnt for j in range(n - 2, 0, -1): if lst[j] == 1: cnt += 1 else: ...
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" ]
def f(x): return x%2 t=int(input()) for i in range(t): n=int(input()) l=list(map(int,list(input()))) if n==1: print(-1) else: ll=list(map(f,l)) if ll.count(1)<=1: print(-1) else: s="" k=0 for j in range(len(ll)): if...
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" ]
import sys input=sys.stdin.readline t=int(input()) for _ in range(t): n,m=map(int,input().split()) s=input().rstrip() p=list(map(int,input().strip().split())) a=[0]*n for x in p: a[x-1]+=1 a[-1]+=1 c=0 for i in range(n-1,-1,-1): c+=a[i] a[i]=c d...
py
1285
F
F. Classical?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an array aa, consisting of nn integers, find:max1≤i<j≤nLCM(ai,aj),max1≤i<j≤nLCM(ai,aj),where LCM(x,y)LCM(x,y) is the smallest positive integer that is divisible by both xx and yy. For example, LCM(6,8...
[ "binary search", "combinatorics", "number theory" ]
import math N = 10**5 + 10 u = [-1]*N divi = [ [] for i in range(N) ] pd = [ [] for i in range(N) ] mark = [0]*N def precalc(): for i in range(1,N) : for j in range(i,N,i) : divi[j].append(i) for i in range(2,N) : if mark[i] == 1 : continue for j in range(i...
py
13
B
B. Letter Atime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.You are given three segments on the plane. Th...
[ "geometry", "implementation" ]
__author__ = 'Darren' def solve(): t = int(input()) while t: run() t -= 1 def run(): def check_condition_1(): record = {} common, first, second = None, -1, -1 found = False for i in range(3): for j in range(2): ...
py
13
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" ]
n = int(input()) a = list(map(int, input().split())) ordered = sorted(set(a)) m = len(ordered) dp = [0] * m for i in range(n): min_prev = 10 ** 18 for j in range(m): min_prev = min(min_prev, dp[j]) dp[j] = min_prev + abs(a[i] - ordered[j]) print(min(dp))
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" ]
def solve(): n, x = read_ints() aseq = read_ints() return 1 if x in aseq else max(2, 0--x // max(aseq)) def main(): t = int(input()) output = [] for _ in range(t): ans = solve() output.append(ans) print_lines(output) def read_ints(): return [int(c) fo...
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 bisect import bisect_left, bisect_right from collections import Counter, deque # from functools import lru_cache # from math import factorial, comb, sqrt, gcd, lcm # from copy import deepcopy # import heapq # # from sys import stdin, stdout # 加快读入速度, 但是注意后面的换行符(\n) # 如果是使用 input().split() 或者 int(input...
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" ]
M=998244353 n,m=map(int,input().split()) f=[] f.append(1) for i in range(1,m+1): f.append( (f[i-1]*i)%M ) print( ( (f[m]*pow(f[n-1]*f[m-n+1],M-2,M)) * (n-2) * pow(2,n-3,M) ) %M )
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" ]
a = int(input()) for i in range(a): q = int(input()) *s, = map(int, input().split(' ')) w = [] d = False for j in range(q): if s[j] % 2 == 0: w = j + 1 d = True break else: w.append(j + 1) if d: print(1) ...
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" ]
from math import ceil t = int(input()) for _ in range(t): n, x = map(int, input().split()) a = list(map(int, input().split())) m = max(a) if x in a: print(1) else: print(max(2, ceil(x/m)))
py
1321
C
C. Remove Adjacenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss consisting of lowercase Latin letters. Let the length of ss be |s||s|. You may perform several operations on this string.In one operation, you can choose some index ii and re...
[ "brute force", "constructive algorithms", "greedy", "strings" ]
import sys input = sys.stdin.readline n = int(input()) s = list(input()[:-1]) c = 0 for i in range(122, 97, -1): n = len(s) j = 0 while j < n: if s[j] != chr(i): j += 1 else: if (j != 0 and s[j-1] == chr(i-1)) or (j != len(s)-1 and s[j+1] == chr(i-1)): ...
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" ]
# Defines lmp = lambda:list(map(int, input().split())) mp = lambda:map(int, input().split()) intp = lambda:int(input()) inp = lambda:input() finp = lambda:float(input()) linp = lambda:input().split() # Input n, m = mp() s = linp() t = linp() q = intp() for i in range(q): y = intp() # Slove ...
py
1307
D
D. Cow and Fieldstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is out grazing on the farm; which consists of nn fields connected by mm bidirectional roads. She is currently at field 11, and will return to her home at field nn at the end of the day.The Cowfe...
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "shortest paths", "sortings" ]
import sys from collections import deque def solve(): n, m, k = map(int, input().split()) alist = map(int, sys.stdin.readline().split()) graph = [] for _ in range(n + 1): graph.append([]) dis_from_start = [-1] * (n + 1) dis_from_end = [-1] * (n + 1) for _ in range...
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" ]
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] rg = dp1[mid][r] ...
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
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" ]
times = int(input()) answer = list() for i in range(times): a, b = map(int, input().split()) if a%b == 0: answer.append('YES') else: answer.append('NO') for i in answer: print(i)
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
B
B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a1,a2,…,ana1,a2,…,an (each aiai is either 00 or 11)...
[ "implementation" ]
n = int(input()) a = [int(x) for x in input().split()][:n] count, max = 0, 0 check1, check2 = False, False start, end = 0, 0 for i in range(n): if a[i] == 1: count += 1 if check1 == False: start += 1 else: count = 0 check1 = True if count > max: max = count for i in reversed(range(n)): if a[i] == 1 a...
py
1303
E
E. Erase Subsequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. You can build new string pp from ss using the following operation no more than two times: choose any subsequence si1,si2,…,siksi1,si2,…,sik where 1≤i1<i2<⋯<ik≤|s|1≤i1<i...
[ "dp", "strings" ]
from sys import stdin, stdout def solve(s1, s2, next): # i => s1, j => s2 dp = [[INF for _ in range(len(s2)+1)] for _ in range(len(s1)+1)] dp[0][0] = 0 for i in range(len(s1)+1): for j in range(len(s2)+1): if dp[i][j] == INF: continue if i <...
py
1291
F
F. Coffee Varieties (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. You can find the hard version in the Div. 1 contest. Both versions only differ in the number of times you can ask your friend to taste coffee.Th...
[ "graphs", "interactive" ]
import sys def ask(s): print(s) sys.stdout.flush() def solve(): n, k = map(int, input().split()) head = [True] * (n+1) head[0] = False if k == 1: N = 2*int(n/(k+1)) else: N = 2*int(n/k) #print(N) for i in range(1,N+1): cl = (i-1)*...
py
1296
F
F. Berland Beautytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn railway stations in Berland. They are connected to each other by n−1n−1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of ...
[ "constructive algorithms", "dfs and similar", "greedy", "sortings", "trees" ]
import sys class graph: def __init__(self, n): self.n, self.gdict = n, [[] for _ in range(n + 1)] def add_edge(self, node1, node2, w=None): self.gdict[node1].append(node2) self.gdict[node2].append(node1) def subtree(self, v): queue, vis = [v], [False] * (n + 1...
py
1296
F
F. Berland Beautytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn railway stations in Berland. They are connected to each other by n−1n−1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of ...
[ "constructive algorithms", "dfs and similar", "greedy", "sortings", "trees" ]
import 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
1141
C
C. Polycarp Restores Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array of integers p1,p2,…,pnp1,p2,…,pn is called a permutation if it contains each number from 11 to nn exactly once. For example, the following arrays are permutations: [3,1,2][3,1,2...
[ "math" ]
n = int(input()) li = list(map(int, input().split())) n_loc = -1 cumul = 0 for i in range(n - 1): cumul += li[i] if cumul == n - 1: n_loc = i + 1 break if cumul < 0: cumul = 0 if n_loc == -1: cumul = 0 for i in range(n - 2, -1, -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" ]
#Mock contest 4 Round #4 #Problem H import sys, collections, functools input = lambda: sys.stdin.readline()[:-1] get_int = lambda: int(input()) get_int_iter = lambda: map(int, input().split()) get_int_list = lambda: list(get_int_iter()) flush = lambda: sys.stdout.flush() #Hi #DEBUG DEBUG = False def debu...
py
1311
B
B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,…,pmp1,p2,…,pm, where 1≤pi<n1≤pi<n. The position pipi means that you can swap elements a[pi]a[pi] and a[pi+1]a[pi+...
[ "dfs and similar", "sortings" ]
for t in range(int(input())): n, m = map(int, input().split()) a = list(map(int, input().split())) p = list(map(int, input().split())) while True: state = False for i in p: if a[i - 1] > a[i]: state = True a[i - 1], a[i] = a[i], ...
py
1313
B
B. Different Rulestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikolay has only recently started in competitive programming; but already qualified to the finals of one prestigious olympiad. There going to be nn participants, one of whom is Nikolay. Like any good o...
[ "constructive algorithms", "greedy", "implementation", "math" ]
import bisect import collections import heapq import io import math import os import random import sys LO = 'abcdefghijklmnopqrstuvwxyz' # Mod = 1000000007 Mod = 998244353 def gcd(x, y): while y: x, y = y, x % y return x # _input = lambda: io.BytesIO(os.read(0, os.fstat(0).st_size))...
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" ]
a=int(input()) s=0 for i in range(a): b,c=map(int,input().split()) if b==c: s=0 elif b>c: d=b-c if d%2==0: s=1 else: s=2 else: d=c-b if d%2!=0: s=1 else: s=2 print(s) s=0 #
py
1300
A
A. Non-zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas have an array aa of nn integers [a1,a2,…,ana1,a2,…,an]. In one step they can add 11 to any element of the array. Formally, in one step they can choose any integer index ii (1≤i≤n1≤i≤n) a...
[ "implementation", "math" ]
for _ in range(int(input())): n = int(input()) a = list(map(int, input().split(' '))) b = a.count(0) if sum(a) + b: print(b) else: print(b + 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 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, input().split())) def GMI(): return map(lambda x: int(x) - 1, input().split()) def LGMI(): r...
py
1296
C
C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially; the robot is located at the point (0,0)(0,0). Its path is described as a string ss of length nn consisting of characters 'L', 'R', 'U', 'D'....
[ "data structures", "implementation" ]
# 11:59- import sys input = lambda: sys.stdin.readline().rstrip() from collections import defaultdict for _ in range(int(input())): N = int(input()) S = input() cur = float('inf') ans = [] lib = {} lib[(0,0)] = -1 r,l = 0,0 for i,c in enumerate(S): if c=='U': r+=1 elif c=='D': ...
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" ]
import sys, threading import math from os import path from collections import deque, Counter, defaultdict from bisect import * from string import ascii_lowercase from functools import cmp_to_key from random import randint import heapq def readInts(): x = list(map(int, (sys.stdin.readline().rstrip()....
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): n = int(input()) s = list(input()) count = 0 mx = 0 for i in range(len(s)): if s[i] == "A": for j in range(i+1, len(s)): if s[j] == "P": count += 1 else: break ...
py
1312
C
C. Adding Powerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you are performing the following algorithm. There is an array v1,v2,…,vnv1,v2,…,vn filled with zeroes at start. The following operation is applied to the array several times — at ii-th step (00-...
[ "bitmasks", "greedy", "implementation", "math", "number theory", "ternary search" ]
from collections import Counter import os import sys # import math, bisect, heapq, random # from functools import lru_cache, reduce, cmp_to_key # from itertools import accumulate, combinations, permutations from io import BytesIO, IOBase inf = float('inf') mod = 10**9 + 7 # region fastio BUFSIZE = 8192 c...
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 bisect import collections import heapq import io import math import os import sys LO = 'abcdefghijklmnopqrstuvwxyz' Mod = 1000000007 def gcd(x, y): while y: x, y = y, x % y return x # _input = lambda: io.BytesIO(os.read(0, os.fstat(0).st_size)).readline().decode() _input = lam...
py
1294
F
F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such t...
[ "dfs and similar", "dp", "greedy", "trees" ]
from collections import deque from sys import stdin input = stdin.readline II = lambda :int(input()) MI = lambda :map(int,input().split()) MI0 = lambda:map(lambda x:int(x)-1,input().split()) LI = lambda :list(map(int,input().split())) LI0 = lambda :list(map(lambda x:int(x)-1,input().split())) ANS = [] #文字列出力はL...
py
1141
F2
F2. Same Sum Blocks (Hard)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence ...
[ "data structures", "greedy" ]
from collections import defaultdict n = int(input()) nums = list(map(int, input().split())) cnt = defaultdict(list) for l in range(n): cur = 0 for r in range(l, n): cur += nums[r] cnt[cur].append((l + 1, r + 1)) ans = 0 path = [] for arr in cnt.values(): arr.sort(key=lambda x: x[...
py
1288
E
E. Messenger Simulatortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has nn friends, numbered from 11 to nn.Recall that a permutation of size nn is an array o...
[ "data structures" ]
import sys input = sys.stdin.readline def make_tree(n): tree = [0] * (n + 1) return tree def get_sum(i): s = 0 while i > 0: s += tree[i] i -= i & -i return s def get_sum_segment(s, t): ans = get_sum(t) - get_sum(s - 1) return ans def add(i, x): whil...
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" ]
print(int(input())+1)
py
1305
D
D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortun...
[ "constructive algorithms", "dfs and similar", "interactive", "trees" ]
import sys from collections import deque class graph: def __init__(self, n): self.n, self.gdict = n, [[] for _ in range(n + 1)] self.l = [0] * (n + 1) def addEdge(self, node1, node2, w=None): self.gdict[node1].append(node2) self.gdict[node2].append(node1) s...
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" ]
from sys import stdin,stdout input = stdin.readline # from math import inf # from collections import Counter # from heapq import heapify,heappop,heappush # from time import time # from bisect import bisect, bisect_left n,m = map(int,input().split()) ans = 1 if n > 1000: print(0) else: a = l...
py
1295
E
E. Permutation Separationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p1,p2,…,pnp1,p2,…,pn (an array where each integer from 11 to nn appears exactly once). The weight of the ii-th element of this permutation is aiai.At first, you sepa...
[ "data structures", "divide and conquer" ]
import sys from itertools import accumulate input = sys.stdin.readline n=int(input()) P=tuple(map(int,input().split())) A=tuple(map(int,input().split())) seg_el=1<<((n+1).bit_length()) SEGMIN=[0]*(2*seg_el) SEGADD=[0]*(2*seg_el) for i in range(n): SEGMIN[P[i]+seg_el]=A[i] SEGMIN=list(accumulate...
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" ]
n, q = map(int, input().split()) lava = [[0 for i in range(n)] for j in range(2)] blocked = 0 for i in range(q): r, c = map(lambda x: int(x)-1, input().split()) delta = 1 if lava[r][c] == 0 else -1 lava[r][c] = 1 - lava[r][c] ri = 0 if r == 1 else 1 for j in [-1, 0, 1]: ci = c + j ...
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()) while(t>0): n,m=map(int,input().split()) if (n%m==0): print("YES") else: print("NO") t-=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 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) sys.stdout.flush() if (cmd...
py
1288
A
A. Deadlinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdilbek was assigned to a special project. For Adilbek it means that he has nn days to run a special program and provide its results. But there is a problem: the program needs to run for dd days to calculate...
[ "binary search", "brute force", "math", "ternary search" ]
import math t = int(input()) while t: n, d = map(int, input().split()) if (n + 1) ** 2 >= 4 * d: print("YES") else: print("NO") t -= 1
py
1304
B
B. Longest Palindrometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputReturning back to problem solving; Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "...
[ "brute force", "constructive algorithms", "greedy", "implementation", "strings" ]
import collections import sys input = sys.stdin.readline n, m = map(int, input().split()) data = [input().rstrip() for _ in range(n)] sdata = set(data) f = [] s = [] spi = -1 sp = '' for i in range(n): tmp = False for j in range(i + 1, n): if data[i] == data[j][::-1]: t...
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" ]
#! /bin/env python3 # please follow ATshayu def main(): N = int(1e5) + 5 A = 26 + 5 s = '#' + input() # solve n = len(s) - 1 c = [[0 for i in range(A)] for j in range(N)] for i in range(n-1, 0, -1): for j in range(A): c[i][j] = c[i+1][j] val = ord(s[i+1]) - 97 ...
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" ]
from __future__ import print_function def gcd(a,b): while b: a,b = b, a%b return a def cal(i,n): temp = 0 while n > 0: temp += n%i n = n// i return temp n=int(input()) sum = 0 for base in range(2,n): sum += cal(base,n) n -= 2 print(sum//gcd(sum,n),n//gcd(sum,n),sep='/')
py
1320
C
C. World of Darkraft: Battle for Azathothtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRoma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.Roma has a choice to buy exactly one of nn diff...
[ "brute force", "data structures", "sortings" ]
import sys from array import array from bisect import * input = lambda: sys.stdin.readline().rstrip("\r\n") inp = lambda dtype: [dtype(x) for x in input().split()] debug = lambda *x: print(*x, file=sys.stderr) ceil1 = lambda a, b: (a + b - 1) // b out, tests = [], 1 max_ = 10 ** 6 + 1 class range_sum: ...
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" ]
num=int(input()) for i in range(num): n,m=[int(i) for i in input().split()] c=0 f=m-n if f==0: print("0") for j in range(1): if f>0: if f%2!=0: print("1") else: print("2") elif f<0: if f%2==0: ...
py