index
int64
0
5.16k
difficulty
int64
7
12
question
stringlengths
126
7.12k
solution
stringlengths
30
18.6k
test_cases
dict
300
8
Coming up with a new problem isn't as easy as many people think. Sometimes it is hard enough to name it. We'll consider a title original if it doesn't occur as a substring in any titles of recent Codeforces problems. You've got the titles of n last problems β€” the strings, consisting of lowercase English letters. Your...
n=int(input()) alph="abcdefghijklmnopqrstuvwxyz" ch="" for x in range(n): ch+=" "+input() def f(): ch1="" j=0 for k in range(26): for i in range(26): if ch1+alph[i] not in ch: print(ch1+alph[i]) return ch1=alph[j] j+=1 f()
{ "input": [ "4\naa\nbdefghijklmn\nopqrstuvwxyz\nc\n", "5\nthreehorses\ngoodsubstrings\nsecret\nprimematrix\nbeautifulyear\n" ], "output": [ "ab\n", "j\n" ] }
301
7
Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: 1. The product of all numbers in the first set is less than zero ( < 0). 2. The product of all numbers in the second set is greater than zero ( > 0). 3. The product of a...
def main(): n = int(input()) a = set(map(int, input().split())) print(1, min(a)) a -= {min(a)} if max(a) > 0: s = {max(a)} a -= s else: s = {min(a)} a -= s s.add(min(a)) a -= {min(a)} print(len(s), ' '.join(map(str, s))) print(len(a), ' '.join(map(str, a))) if __name__ == '__main__': main()
{ "input": [ "4\n-1 -2 -3 0\n", "3\n-1 2 0\n" ], "output": [ "1 -1\n2 -3 -2\n1 0\n", "1 -1\n1 2\n1 0\n" ] }
302
7
There are n kangaroos with pockets. Each kangaroo has a size (integer number). A kangaroo can go into another kangaroo's pocket if and only if the size of kangaroo who hold the kangaroo is at least twice as large as the size of kangaroo who is held. Each kangaroo can hold at most one kangaroo, and the kangaroo who is ...
import sys def sol(a,n): a.sort() i = 0 j = n//2 ans = n while i < n//2 and j < n: if 2*a[i] <= a[j]: ans-=1 i+=1 j+=1 else: j+=1 return ans n = int(input()) a = [int(i) for i in sys.stdin] print(sol(a,n))
{ "input": [ "8\n2\n5\n7\n6\n9\n8\n4\n2\n", "8\n9\n1\n6\n2\n6\n5\n8\n3\n" ], "output": [ "5\n", "5\n" ] }
303
8
Kolya got string s for his birthday, the string consists of small English letters. He immediately added k more characters to the right of the string. Then Borya came and said that the new string contained a tandem repeat of length l as a substring. How large could l be? See notes for definition of a tandem repeat. I...
def max_len(s): N = len(s) for L in range(N // 2, 0, -1): for i in range(N - 2 * L + 1): if all(ch2 in ch1 + '_' for ch1, ch2 in zip(s[i:i+L], s[i+L:i+2*L])): return 2 * L print(max_len(input() + '_' * int(input())))
{ "input": [ "aaabbbb\n2\n", "aaba\n2\n", "abracadabra\n10\n" ], "output": [ "6\n", "6\n", "20\n" ] }
304
9
Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more. Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable st...
def trans(c): return chr(ord(c) + 1) n, p = list(map(int, input().split())) s = list(input()) s[n-1] = trans(s[n-1]) i = n - 1 while i >= 0 and i < n: if ord(s[i]) >= ord('a') + p: s[i] = 'a' i -= 1 s[i] = trans(s[i]) elif i > 0 and s[i] == s[i-1] or i > 1 and s[i] == s[i-2]: s[i] ...
{ "input": [ "3 4\ncba\n", "3 3\ncba\n", "4 4\nabcd\n" ], "output": [ "cbd\n", "NO\n", "abda\n" ] }
305
8
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves. We know that several boy&girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair m...
def I(): return(sorted(list(map(int,input().split())))) n=I()[0] b=I() m=I()[0] g=I() i,j,k=[0]*3 while i<n and j<m: if abs(b[i]-g[j])<2:k+=1;i+=1;j+=1 elif b[i]<g[j]:i+=1 else:j+=1 print(k)
{ "input": [ "4\n1 2 3 4\n4\n10 11 12 13\n", "4\n1 4 6 2\n5\n5 1 5 7 9\n", "5\n1 1 1 1 1\n3\n1 2 3\n" ], "output": [ "0\n", "3\n", "2\n" ] }
306
7
Two players play a simple game. Each player is provided with a box with balls. First player's box contains exactly n1 balls and second player's box contains exactly n2 balls. In one move first player can take from 1 to k1 balls from his box and throw them away. Similarly, the second player can take from 1 to k2 balls f...
def mod(): n,m,k,s=list(map(int,input().split(" "))) if n>m: print("First") else: print("Second") mod()
{ "input": [ "2 1 1 1\n", "2 2 1 2\n" ], "output": [ "First\n", "Second\n" ] }
307
8
A number is called quasibinary if its decimal representation contains only digits 0 or 1. For example, numbers 0, 1, 101, 110011 β€” are quasibinary and numbers 2, 12, 900 are not. You are given a positive integer n. Represent it as a sum of minimum number of quasibinary numbers. Input The first line contains a single...
def qBinary(n): a = list(str(n)) a = list(map(int,a)) b = [0]*max(a) for i in range(len(a)): j = 0 while(a[i] > 0): b[j] += 10**(len(a)-i-1) j += 1 a[i] -= 1 print(len(b)) for i in b: print(i,end = ' ') n = int(input()) qBinary(n)
{ "input": [ "32\n", "9\n" ], "output": [ "3\n11 11 10\n", "9\n1 1 1 1 1 1 1 1 1\n" ] }
308
11
Developing tools for creation of locations maps for turn-based fights in a new game, Petya faced the following problem. A field map consists of hexagonal cells. Since locations sizes are going to be big, a game designer wants to have a tool for quick filling of a field part with identical enemy units. This action will...
def main(): x1, y1, x2, y2 = map(int, input().split()) print((y2 - y1 + 2) // 2 * (x2 - x1 + 1) - (x2 - x1) // 2) if __name__ == '__main__': main()
{ "input": [ "1 1 5 5\n" ], "output": [ "13" ] }
309
8
Limak is a little polar bear. He loves connecting with other bears via social networks. He has n friends and his relation with the i-th of them is described by a unique integer ti. The bigger this value is, the better the friendship is. No two friends have the same value ti. Spring is starting and the Winter sleep is ...
def p1(): n,k,q = [int(i) for i in input().split()] l = [int(i) for i in input().split()] s = [] for i in range(q): a,b = [int(i) for i in input().split()] if a == 1: s.append(l[b-1]) s.sort() if len(s) > k: s.remove(s[0]) if a == 2: if l[b-1] in s: print('YES') else: print('NO') p1...
{ "input": [ "6 3 9\n50 20 51 17 99 24\n1 3\n1 4\n1 5\n1 2\n2 4\n2 2\n1 1\n2 4\n2 3\n", "4 2 8\n300 950 500 200\n1 3\n2 4\n2 3\n1 1\n1 2\n2 1\n2 2\n2 3\n" ], "output": [ "NO\nYES\nNO\nYES\n", "NO\nYES\nNO\nYES\nYES\n" ] }
310
10
Limak is a little polar bear. He plays by building towers from blocks. Every block is a cube with positive integer length of side. Limak has infinitely many blocks of each side length. A block with side a has volume a3. A tower consisting of blocks with sides a1, a2, ..., ak has the total volume a13 + a23 + ... + ak3....
def g(m, n, s): if not m: return n, s k = int(m ** (1 / 3)) x, y = k ** 3, (k - 1) ** 3 return max(g(m - x, n + 1, s + x), g(x - y - 1, n + 1, s + y)) print(*g(int(input()), 0, 0))
{ "input": [ "6\n", "48\n" ], "output": [ "6 6\n", "9 42\n" ] }
311
9
And while Mishka is enjoying her trip... Chris is a little brown bear. No one knows, where and when he met Mishka, but for a long time they are together (excluding her current trip). However, best friends are important too. John is Chris' best friend. Once walking with his friend, John gave Chris the following proble...
import sys input = sys.stdin.readline def solve(): n, w, v, u = map(int, input().split()) mx = int(1e13) Mx = int(-1e13) for i in range(n): x, y = map(int, input().split()) xx = x * u - v * y mx = min(mx, xx) Mx = max(Mx, xx) if mx >= 0 or Mx <= 0: print(w/u) else: print((Mx+w*v)/(v*u)) solve()
{ "input": [ "5 5 1 2\n1 2\n3 1\n4 3\n3 4\n1 4\n" ], "output": [ "5.0000000000\n" ] }
312
9
Let’s define a grid to be a set of tiles with 2 rows and 13 columns. Each tile has an English letter written in it. The letters don't have to be unique: there might be two or more tiles with the same letter written on them. Here is an example of a grid: ABCDEFGHIJKLM NOPQRSTUVWXYZ We say that two t...
def main(): l, d = [], {} for i, c in enumerate(input()): if c in d: u, v = d[c], i else: d[c] = i l.append(c) if v - u == 1: print("Impossible") return l *= 2 w = (u + v + 1) // 2 print(''.join(l[w:w + 13])) print(''.join(l...
{ "input": [ "BUVTYZFQSNRIWOXXGJLKACPEMDH\n", "ABCDEFGHIJKLMNOPQRSGTUVWXYZ\n" ], "output": [ "Impossible\n", "ABCDEFGHIJKLM\nZYXWVUTSRQPON\n" ] }
313
9
There are n servers in a laboratory, each of them can perform tasks. Each server has a unique id β€” integer from 1 to n. It is known that during the day q tasks will come, the i-th of them is characterized with three integers: ti β€” the moment in seconds in which the task will come, ki β€” the number of servers needed to ...
import math import sys def solve(n, q): servers = [0] * n res = [None]*q for j, line in enumerate(sys.stdin): t, k, d = map(int, line.split()) S, m = k, k logs = servers[:] for i, s in enumerate(servers): if s <= t: servers[i] = t + d ...
{ "input": [ "8 6\n1 3 20\n4 2 1\n6 5 5\n10 1 1\n15 3 6\n21 8 8\n", "4 3\n1 3 2\n2 2 1\n3 4 3\n", "3 2\n3 2 3\n5 1 2\n" ], "output": [ "6\n9\n30\n-1\n15\n36\n", "6\n-1\n10\n", "3\n3\n" ] }
314
9
Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company. To settle this problem, they've decided to play a game. The company name will consist of n letters. Oleg and Igor ea...
def main(): from collections import deque import sys input = sys.stdin.readline s = list(input())[:-1] t = list(input())[:-1] n = len(s) s.sort() t.sort(reverse=True) s = deque(s[:(n + 1) // 2]) t = deque(t[:n // 2]) f = 0 al, ar = "", "" for i in range(n): ...
{ "input": [ "xxxxxx\nxxxxxx\n", "tinkoff\nzscoder\n", "ioi\nimo\n" ], "output": [ "xxxxxx\n", "fzfsirk\n", "ioi\n" ] }
315
8
Karen has just arrived at school, and she has a math test today! <image> The test is about basic addition and subtraction. Unfortunately, the teachers were too busy writing tasks for Codeforces rounds, and had no time to make an actual test. So, they just put one question in the test that is worth all the points. Th...
from sys import exit n = int(input()) a = [int(i) for i in input().split()] if n == 1: print(a[0]) exit(0) mod = 1000000007 f = [0] * (n + 1) f[0] = 1 for i in range(1, n + 1): f[i] = (f[i-1] * i) % mod def f_pow(a, k): if k == 0: return 1 if k % 2 == 1: return f_pow(a, k - 1) * a %...
{ "input": [ "4\n3 7 5 2\n", "5\n3 6 9 12 15\n" ], "output": [ "\n1000000006\n", "\n36\n" ] }
316
8
Leha plays a computer game, where is on each level is given a connected graph with n vertices and m edges. Graph can contain multiple edges, but can not contain self loops. Each vertex has an integer di, which can be equal to 0, 1 or - 1. To pass the level, he needs to find a Β«goodΒ» subset of edges of the graph or say...
# https://codeforces.com/problemset/problem/840/B # TLE import sys input=sys.stdin.readline n, m = map(int, input().split()) d = list(map(int, input().split())) g={} def push(g, u, v, i): if u not in g: g[u]=[] if v not in g: g[v]=[] g[u].append([v, i+1]) g[v].append([u, i+1]) ...
{ "input": [ "3 3\n0 -1 1\n1 2\n2 3\n1 3\n", "4 5\n0 0 0 -1\n1 2\n2 3\n3 4\n1 4\n2 4\n", "1 0\n1\n", "2 1\n1 1\n1 2\n" ], "output": [ "1\n2\n", "0\n", "-1\n", "1\n1\n" ] }
317
9
The All-Berland National Olympiad in Informatics has just ended! Now Vladimir wants to upload the contest from the Olympiad as a gym to a popular Codehorses website. Unfortunately, the archive with Olympiad's data is a mess. For example, the files with tests are named arbitrary without any logic. Vladimir wants to re...
import random def genTemp(): sl = "" firstTime = True while firstTime or sl in pre or sl in post: sl = "" firstTime = False for i in range(6): sl += chr(random.randint(ord("a"), ord("z"))) return sl n = int(input()) e = 0 pre = set() post = set() for i in range(n):...
{ "input": [ "5\n01 0\n2 1\n2extra 0\n3 1\n99 0\n", "2\n1 0\n2 1\n", "5\n1 0\n11 1\n111 0\n1111 1\n11111 0\n" ], "output": [ "4\nmove 3 1\nmove 01 3\nmove 2extra 4\nmove 99 5\n", "3\nmove 1 3\nmove 2 1\nmove 3 2\n", "5\nmove 1 3\nmove 11 1\nmove 111 4\nmove 1111 2\nmove 11111 5\n" ] }
318
8
Absent-minded Masha got set of n cubes for her birthday. At each of 6 faces of each cube, there is exactly one digit from 0 to 9. Masha became interested what is the largest natural x such she can make using her new cubes all integers from 1 to x. To make a number Masha can rotate her cubes and put them in a row. Aft...
n=int(input()) def find(x,d=[]): if x==0 and d!=[]: return True l=x%10 i=-1 a=False for lis in s: i+=1 if l in lis and i not in d: a=max(a,find(x//10,d+[i])) return a s=[list(map(int,input().split())) for x in range(n)] e=1 while find(e): e+=1 print(i...
{ "input": [ "3\n0 1 3 5 6 8\n1 2 4 5 7 8\n2 3 4 6 7 9\n", "3\n0 1 2 3 4 5\n6 7 8 9 0 1\n2 3 4 5 6 7\n" ], "output": [ "98\n", "87\n" ] }
319
8
An African crossword is a rectangular table n Γ— m in size. Each cell of the table contains exactly one letter. This table (it is also referred to as grid) contains some encrypted word that needs to be decoded. To solve the crossword you should cross out all repeated letters in rows and columns. In other words, a lette...
def column(matrix, i): return [row[i] for row in matrix] n, m = map(int, input().split()) mat = [] for _ in range(n): mat.append([char for char in input()]) ans = "" # print(mat) for i in range(n): for j in range(m): # print(mat[:][j], mat[:][j].count(mat[i][j])) if mat[i][:].count(mat[i][j])>1 or column(ma...
{ "input": [ "3 3\ncba\nbcd\ncbc\n", "5 5\nfcofd\nooedo\nafaoa\nrdcdf\neofsf\n" ], "output": [ "abcd\n", "codeforces\n" ] }
320
11
Mishka received a gift of multicolored pencils for his birthday! Unfortunately he lives in a monochrome world, where everything is of the same color and only saturation differs. This pack can be represented as a sequence a1, a2, ..., an of n integer numbers β€” saturation of the color of each pencil. Now Mishka wants to ...
def main(): import sys from bisect import bisect_left input = sys.stdin.readline N, K, D = map(int, input().split()) A = list(map(int, input().split())) A.sort() part = [0] * (N+2) part[0] = 1 part[1] = -1 for i, a in enumerate(A): part[i] += part[i-1] if part[i...
{ "input": [ "6 3 10\n7 2 7 7 4 2\n", "3 2 5\n10 16 22\n", "6 2 3\n4 5 3 13 4 10\n" ], "output": [ "YES\n", "NO\n", "YES\n" ] }
321
9
You are given n segments on a coordinate line; each endpoint of every segment has integer coordinates. Some segments can degenerate to points. Segments can intersect with each other, be nested in each other or even coincide. Your task is the following: for every k ∈ [1..n], calculate the number of points with integer ...
def ii(): return int(input()) def mi(): return map(int, input().split()) def li(): return list(mi()) from collections import Counter n = ii() a1 = [tuple(mi()) for i in range(n)] a = [] for l, r in a1: a.append((l, 0)) a.append((r, 1)) c = Counter(a) b = [(k[0], k[1], v) for k, v in c.items()] b.so...
{ "input": [ "3\n0 3\n1 3\n3 8\n", "3\n1 3\n2 4\n5 7\n" ], "output": [ "6 2 1\n", "5 2 0\n" ] }
322
10
Dima the hamster enjoys nibbling different things: cages, sticks, bad problemsetters and even trees! Recently he found a binary search tree and instinctively nibbled all of its edges, hence messing up the vertices. Dima knows that if Andrew, who has been thoroughly assembling the tree for a long time, comes home and s...
from math import gcd import random,time,sys input=sys.stdin.buffer.readline def main(): n=int(input()) a=list(map(int,input().split())) #a=[2*random.randint(1,10**9) for i in range(n)] start=time.time() a+=[0] GCD=[0 for i in range(n+1)] for i in range(n+1): for j in range(n+1): ...
{ "input": [ "9\n4 8 10 12 15 18 33 44 81\n", "6\n3 6 9 18 36 108\n", "2\n7 17\n" ], "output": [ "Yes\n", "Yes\n", "No\n" ] }
323
12
Ivan places knights on infinite chessboard. Initially there are n knights. If there is free cell which is under attack of at least 4 knights then he places new knight in this cell. Ivan repeats this until there are no such free cells. One can prove that this process is finite. One can also prove that position in the en...
gcd = lambda a, b: gcd(b, a % b) if b else a def main(): n = int(input()) if n == 1: print(0, 0) return x = 2 * n // 3 if 2 * n % 2: x += 1 s = 0 for i in range(x): print(i, 0) s += 1 for j in range(1, x, 2): print(j, 3) s += 1 w...
{ "input": [ "7\n", "4\n" ], "output": [ "0 0\n1 0\n1 3\n2 0\n3 0\n3 3\n4 0\n", "0 0\n1 0\n1 3\n2 0\n" ] }
324
8
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya recently learned to determine whether a string of lowercase Latin letters is lucky. For each i...
def main(): n = int(input()) s = ['a', 'b', 'c', 'd'] * n return ''.join(s)[:n] print(main())
{ "input": [ "3\n", "5\n" ], "output": [ "abc", "abcda" ] }
325
11
There are n students and m clubs in a college. The clubs are numbered from 1 to m. Each student has a potential p_i and is a member of the club with index c_i. Initially, each student is a member of exactly one club. A technical fest starts in the college, and it will run for the next d days. There is a coding competit...
n, m = map(int, input().split()) p = list(map(int, input().split())) c = list(map(int, input().split())) d = int(input()) k = [] for i in range(d): k.append(int(input())) vis = [False for i in range(m+1)] match = [-1 for i in range(m+1)] def dfs(u: int) -> bool: for v in e[u]: if not vis[v]: ...
{ "input": [ "5 5\n0 1 2 4 5\n1 2 3 4 5\n4\n2\n3\n5\n4\n", "5 3\n0 1 2 2 0\n1 2 2 3 2\n5\n3\n2\n4\n5\n1\n", "5 3\n0 1 2 2 1\n1 3 2 3 2\n5\n4\n2\n3\n5\n1\n" ], "output": [ "1\n1\n1\n1\n", "3\n1\n1\n1\n0\n", "3\n2\n2\n1\n0\n" ] }
326
11
You are given two arrays a and b, both of length n. All elements of both arrays are from 0 to n-1. You can reorder elements of the array b (if you want, you may leave the order of elements as it is). After that, let array c be the array of length n, the i-th element of this array is c_i = (a_i + b_i) \% n, where x \% ...
import collections def solve(n, a, b): c = collections.Counter(b) nex = list(range(1, n)) + [0] res = [] for x in a: v = (n - x) % n while c[v] == 0: if c[nex[v]] == 0: nex[v] = nex[nex[v]] v = nex[v] c[v] -= 1 res.append((x + v) %...
{ "input": [ "4\n0 1 2 1\n3 2 1 1\n", "7\n2 5 1 5 3 4 3\n2 4 3 5 6 5 1\n" ], "output": [ "1 0 0 2 ", "0 0 0 1 0 2 4 " ] }
327
8
In a very ancient country the following game was popular. Two people play the game. Initially first player writes a string s1, consisting of exactly nine digits and representing a number that does not exceed a. After that second player looks at s1 and writes a string s2, consisting of exactly nine digits and representi...
import sys from math import * def minp(): return sys.stdin.readline().strip() def mint(): return int(minp()) def mints(): return map(int, minp().split()) a,b,mod = mints() z = (10**9)%mod c = 0 for i in range(min(a+1,mod)): if c != 0 and mod-c > b: s = str(i) s = '0'*(9-len(s))+s print(1, s) exit(0) c ...
{ "input": [ "4 0 9\n", "1 10 7\n" ], "output": [ "1 000000001\n", "2\n" ] }
328
9
You are given a graph with 3 β‹… n vertices and m edges. You are to find a matching of n edges, or an independent set of n vertices. A set of edges is called a matching if no two edges share an endpoint. A set of vertices is called an independent set if no two vertices are connected with an edge. Input The first line...
from sys import stdin input = stdin.readline def solve_graph(): n,m = map(int, input().split()) included = [False] + ([True]*(3*n)) matching =[] for i in range(1,m+1): e1, e2 = map(int, input().split()) if included[e1] and included[e2]: matching.append(i) includ...
{ "input": [ "4\n1 2\n1 3\n1 2\n1 2\n1 3\n1 2\n2 5\n1 2\n3 1\n1 4\n5 1\n1 6\n2 15\n1 2\n1 3\n1 4\n1 5\n1 6\n2 3\n2 4\n2 5\n2 6\n3 4\n3 5\n3 6\n4 5\n4 6\n5 6\n" ], "output": [ "Matching\n1 \nMatching\n1 \nIndSet\n3 4 \nMatching\n1 10 \n" ] }
329
8
You are given a sequence a_1, a_2, ..., a_n consisting of n non-zero integers (i.e. a_i β‰  0). You have to calculate two following values: 1. the number of pairs of indices (l, r) (l ≀ r) such that a_l β‹… a_{l + 1} ... a_{r - 1} β‹… a_r is negative; 2. the number of pairs of indices (l, r) (l ≀ r) such that a_l β‹… a...
n = int(input()) def m(x): return -1 if int(x) < 0 else 1 l = list(map(m, input().split())) pos = 1 neg = 0 t = 1 for x in l: t *= x if t < 0: neg += 1 else: pos += 1 print(neg * pos, neg * (neg - 1) // 2 + (pos * (pos - 1) // 2))
{ "input": [ "10\n4 2 -4 3 1 2 -4 3 2 3\n", "5\n-1 -2 -3 -4 -5\n", "5\n5 -3 3 -1 1\n" ], "output": [ "28 27\n", "9 6\n", "8 7\n" ] }
330
10
The string t_1t_2 ... t_k is good if each letter of this string belongs to at least one palindrome of length greater than 1. A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not. Here are some examp...
def comp(a): if a=="A": return "B" else: return "A" n=int(input()) s=input() ans=(n*(n-1))//2 groups=[0] prev=s[0] for i in range(1,n): if s[i]!=prev: groups.append(i) prev=s[i] for i in range(0,len(groups)-2): ans -= (groups[i+2]-groups[i]-1) if len(groups)>1: ans -= (n-groups[-2]-1) print (ans)
{ "input": [ "5\nAABBB\n", "3\nAAA\n", "7\nAAABABB\n" ], "output": [ "6\n", "3\n", "15\n" ] }
331
11
There are n students at your university. The programming skill of the i-th student is a_i. As a coach, you want to divide them into teams to prepare them for the upcoming ICPC finals. Just imagine how good this university is if it has 2 β‹… 10^5 students ready for the finals! Each team should consist of at least three s...
import sys def minp(): return sys.stdin.readline().strip() def mint(): return int(minp()) def mints(): return map(int,minp().split()) def solve(): n = mint() a = [0]*n b = [0]*n j = 0 for i in mints(): a[j] = (i, j) j += 1 a.sort() dp = [(2000000005,0)]*(n+1) dp[3] = (a[2][0] - a[0][0], 3) if n > 3...
{ "input": [ "5\n1 1 3 4 2\n", "6\n1 5 12 13 2 15\n", "10\n1 2 5 129 185 581 1041 1909 1580 8150\n" ], "output": [ "3 1\n1 1 1 1 1 ", "7 2\n2 2 1 1 2 1\n", "7486 3\n3 3 3 2 2 2 2 1 1 1\n" ] }
332
11
Calculate the number of ways to place n rooks on n Γ— n chessboard so that both following conditions are met: * each empty cell is under attack; * exactly k pairs of rooks attack each other. An empty cell is under attack if there is at least one rook in the same row or at least one rook in the same column. Two...
n,k=map(int,input().split()) if k>=n:print(0) else: m=998244353 L=[1] for i in range(1,n+1): L.append((L[-1]*i)%m) def comb(n,k): return (L[n]*pow((L[n-k]*L[k]),m-2,m))%m c=0 for i in range(n-k): c+=((-1)**i*pow(n-k-i,n,m)*comb(n-k,n-k-i))%m c*=2 c%=m c*=comb(...
{ "input": [ "4 0\n", "3 2\n", "1337 42\n", "3 3\n" ], "output": [ "24\n", "6\n", "807905441\n", "0\n" ] }
333
9
Fishing Prince loves trees, and he especially loves trees with only one centroid. The tree is a connected graph without cycles. A vertex is a centroid of a tree only when you cut this vertex (remove it and remove all edges from this vertex), the size of the largest connected component of the remaining graph is the sma...
import sys def minp(): return sys.stdin.readline().strip() def mint(): return int(minp()) def mints(): return map(int, minp().split()) def solve(): n = mint() e = [[] for i in range(n+1)] for i in range(n-1): x, y = mints() e[x].append(y) e[y].append(x) q = [None]*(n+1) d = [None]*(n+1) q[0] = (1,-1...
{ "input": [ "2\n5\n1 2\n1 3\n2 4\n2 5\n6\n1 2\n1 3\n1 4\n2 5\n2 6\n" ], "output": [ "1 2\n1 2\n2 5\n1 5\n" ] }
334
10
You are given a deck of n cards numbered from 1 to n (not necessarily in this order in the deck). You have to sort the deck by repeating the following operation. * Choose 2 ≀ k ≀ n and split the deck in k nonempty contiguous parts D_1, D_2,..., D_k (D_1 contains the first |D_1| cards of the deck, D_2 contains the f...
n = int(input()) def sf(a, d): s = [0] for di in d: s.append(s[-1] + di) rv = [] for i in range(len(d) - 1, -1, -1): rv += a[s[i]:s[i+1]] return rv c = list(map(int, input().split())) ans = [] while True: for i in range(n): if c[i] != i+1: break else: ...
{ "input": [ "1\n1\n", "6\n6 5 4 3 2 1\n", "4\n3 1 2 4\n" ], "output": [ "0\n", "4\n3 1 1 4\n3 1 1 4\n3 1 1 4\n3 2 2 2\n", "2\n3 1 2 1\n2 1 3\n" ] }
335
10
On the competitive programming platform CodeCook, every person has a rating graph described by an array of integers a of length n. You are now updating the infrastructure, so you've created a program to compress these graphs. The program works as follows. Given an integer parameter k, the program takes the minimum of ...
from sys import stdin input=stdin.readline def rating(arr): arr=list(map(lambda s:s-1,lst)) cnt=[0]*len(arr) ans=[0]*len(arr) for i in arr: cnt[i]+=1 ans[0] = 0 if cnt.count(0) > 0 else 1 ans[-1] = int(cnt[0] > 0) l=0 r=len(arr)-1 for i in range(1,len(arr)): j=i-1 ...
{ "input": [ "5\n5\n1 5 3 4 2\n4\n1 3 2 1\n5\n1 3 3 3 2\n10\n1 2 3 4 5 6 7 8 9 10\n3\n3 3 2\n" ], "output": [ "\n10111\n0001\n00111\n1111111111\n000\n" ] }
336
8
Positive integer x is called divisor of positive integer y, if y is divisible by x without remainder. For example, 1 is a divisor of 7 and 3 is not divisor of 8. We gave you an integer d and asked you to find the smallest positive integer a, such that * a has at least 4 divisors; * difference between any two di...
def isprime(n): for i in range(2,int(n**0.5//1)+1): if(n%i==0): return 0 return 1 t=int(input()) for i in range(t): d=int(input()) a=d+1 while(not isprime(a)): a+=1 b=a+d while(not isprime(b)): b=b+1 print(a*b)
{ "input": [ "2\n1\n2\n" ], "output": [ "\n6\n15\n" ] }
337
10
<image> William is hosting a party for n of his trader friends. They started a discussion on various currencies they trade, but there's an issue: not all of his trader friends like every currency. They like some currencies, but not others. For each William's friend i it is known whether he likes currency j. There are...
import random import sys from sys import stdin def popcnt(x): ret = 0 while x > 0: ret += x % 2 x //= 2 return ret n,m,p = map(int,stdin.readline().split()) s = [stdin.readline()[:-1] for i in range(n)] ans = 0 anslis = ["0"] * m for loop in range(8): v = random.randint(0,n-1) ...
{ "input": [ "3 4 3\n1000\n0110\n1001\n", "5 5 4\n11001\n10101\n10010\n01110\n11011\n" ], "output": [ "\n1000\n", "\n10001\n" ] }
338
9
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks. Sergey totally forgot about ...
def f(a,bad): i=0 retain=0 while i<len(a): c={} while i<len(a)-1 and (a[i+1]==a[i]or a[i+1]==bad.get(a[i],None)): c[a[i]]=c.get(a[i],0)+1 i+=1 c[a[i]] = c.get(a[i], 0) + 1 retain+=max(c.items(),key=lambda s:s[1])[1] i+=1 return len(a)-retain a=list(input()) n=int(input()) bad={} for i in range(n)...
{ "input": [ "ababa\n1\nab\n", "codeforces\n2\ndo\ncs\n" ], "output": [ "2", "1\n" ] }
339
10
The Smart Beaver from ABBYY invented a new message encryption method and now wants to check its performance. Checking it manually is long and tiresome, so he decided to ask the ABBYY Cup contestants for help. A message is a sequence of n integers a1, a2, ..., an. Encryption uses a key which is a sequence of m integers...
def solve(n , m , c , a , b): for i in range(n - m + 1): for j in range(m): a[i + j] = (a[i+j]+b[j])%c a = map(str , a) return " ".join(a) n , m , c = map(int , input().split()) a = list(map(int , input().split())) b = list(map(int , input().split())) print(solve(n , m , c , a , b))
{ "input": [ "3 1 5\n1 2 3\n4\n", "4 3 2\n1 1 1 1\n1 1 1\n" ], "output": [ "0 1 2 \n", "0 1 1 0 \n" ] }
340
12
You've got a list of program warning logs. Each record of a log stream is a string in this format: "2012-MM-DD HH:MM:SS:MESSAGE" (without the quotes). String "MESSAGE" consists of spaces, uppercase and lowercase English letters and characters "!", ".", ",", "?". String "2012-MM-DD" determines a correct date in the ...
import atexit import io import sys _INPUT_LINES = sys.stdin.read().splitlines() input = iter(_INPUT_LINES).__next__ _OUTPUT_BUFFER = io.StringIO() sys.stdout = _OUTPUT_BUFFER @atexit.register def write(): sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) import bisect from datetime import datetime def main(): ...
{ "input": [ "60 3\n2012-03-16 16:15:25: Disk size is\n2012-03-16 16:15:25: Network failute\n2012-03-16 16:16:29: Cant write varlog\n2012-03-16 16:16:42: Unable to start process\n2012-03-16 16:16:43: Disk size is too small\n2012-03-16 16:16:53: Timeout detected\n", "2 2\n2012-03-16 23:59:59:Disk size is too s...
341
10
Emuskald is an avid horticulturist and owns the world's longest greenhouse β€” it is effectively infinite in length. Over the years Emuskald has cultivated n plants in his greenhouse, of m different plant species numbered from 1 to m. His greenhouse is very narrow and can be viewed as an infinite line, with each plant o...
def f(arr): arr=[None]+arr dp=[0]*(len(arr)) for i in range(1,len(arr)): j=int(arr[i]) for k in range(int(j),0,-1): dp[j]=max(dp[j],1+dp[k]) return len(arr)-max(dp)-1 a,b=map(int,input().strip().split()) lst=[] for i in range(a): x,y=map(float,input().strip().split()) lst.append(x) print(f(lst))
{ "input": [ "3 3\n1 5.0\n2 5.5\n3 6.0\n", "6 3\n1 14.284235\n2 17.921382\n1 20.328172\n3 20.842331\n1 25.790145\n1 27.204125\n", "3 2\n2 1\n1 2.0\n1 3.100\n" ], "output": [ "0\n", "2\n", "1\n" ] }
342
7
Shaass has decided to hunt some birds. There are n horizontal electricity wires aligned parallel to each other. Wires are numbered 1 to n from top to bottom. On each wire there are some oskols sitting next to each other. Oskol is the name of a delicious kind of birds in Shaass's territory. Supposed there are ai oskols ...
"""609C""" # import math def main(): n = int(input()) a = list(map(int,input().split())) m = int(input()) for i in range(m): x,y = map(int,input().split()) x = x-1 if x-1>=0: a[x-1] += y-1 if x+1<n: a[x+1] += a[x]-y a[x]=0 for i in range(len(a)): print(a[i]) main()
{ "input": [ "5\n10 10 10 10 10\n5\n2 5\n3 13\n2 12\n1 13\n4 6\n", "3\n2 4 1\n1\n2 2\n" ], "output": [ "0\n12\n5\n0\n16\n", "3\n0\n3\n" ] }
343
10
Vasya and Petya wrote down all integers from 1 to n to play the "powers" game (n can be quite large; however, Vasya and Petya are not confused by this fact). Players choose numbers in turn (Vasya chooses first). If some number x is chosen at the current turn, it is forbidden to choose x or all of its other positive in...
import math, collections mod = 10**9+7 def isPower(n): if (n <= 1): return True for x in range(2, (int)(math.sqrt(n)) + 1): p = x while (p <= n): p = p * x if (p == n): return True return False n = int(input()) arr = [0,1,2,1,4,3,2,1,5,6,2,1,8...
{ "input": [ "8\n", "1\n", "2\n" ], "output": [ "Petya\n", "Vasya\n", "Petya\n" ] }
344
7
Let's call a number k-good if it contains all digits not exceeding k (0, ..., k). You've got a number k and an array a containing n numbers. Find out how many k-good numbers are in a (count each number every time it occurs in array a). Input The first line contains integers n and k (1 ≀ n ≀ 100, 0 ≀ k ≀ 9). The i-th ...
def main(): n,k=map(int,input().split()) ans=0 kset=set(map(str,range(k+1))) for i in range(n): if kset<=set(input()): ans+=1 print(ans) if __name__=='__main__': main()
{ "input": [ "2 1\n1\n10\n", "10 6\n1234560\n1234560\n1234560\n1234560\n1234560\n1234560\n1234560\n1234560\n1234560\n1234560\n" ], "output": [ "1\n", "10\n" ] }
345
9
Salve, mi amice. Et tu quidem de lapis philosophorum. Barba non facit philosophum. Labor omnia vincit. Non potest creatio ex nihilo. Necesse est partibus. Rp: I Aqua Fortis I Aqua Regia II Amalgama VII Minium IV Vitriol Misce in vitro et Γ¦stus, et nil admirari. Festina lente, et nulla tenaci invia est via. Fac...
def main(): a = list(map(int, input().split())) assert(len(a) == 5) z = [1, 1, 2, 7, 4] ans = min(x // y for x, y in zip(a, z)) print(ans) main()
{ "input": [ "2 4 6 8 10\n" ], "output": [ "1\n" ] }
346
10
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, tha...
def main(): n, m = map(int, input().split()) n += 1 cluster, dest, ab = list(range(n)), [0] * n, [[] for _ in range(n)] def root(x): if x != cluster[x]: cluster[x] = x = root(cluster[x]) return x for _ in range(m): a, b = map(int, input().split()) ab[a]....
{ "input": [ "4 6\n1 2\n1 4\n2 3\n2 4\n3 2\n3 4\n", "4 5\n1 2\n1 3\n1 4\n2 3\n2 4\n" ], "output": [ "4", "3" ] }
347
11
There are many anime that are about "love triangles": Alice loves Bob, and Charlie loves Bob as well, but Alice hates Charlie. You are thinking about an anime which has n characters. The characters are labeled from 1 to n. Every pair of two characters can either mutually love each other or mutually hate each other (the...
class DSU(object): def __init__(self, n): self.father = list(range(n)) self.size = n def union(self, x, s): x = self.find(x) s = self.find(s) if x == s: return self.father[s] = x self.size -= 1 def find(self, x): xf = self.father[...
{ "input": [ "4 4\n1 2 1\n2 3 1\n3 4 0\n4 1 0\n", "3 0\n", "4 4\n1 2 1\n2 3 1\n3 4 0\n4 1 1\n" ], "output": [ "1", "4", "0" ] }
348
10
When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were n dishes. Kefa knows that he needs exactly m dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the i-th dish gives him ai units of satisfact...
import sys from array import array # noqa: F401 import typing as Tp # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') def output(*args): sys.stdout.buffer.write( ('\n'.join(map(str, args)) + '\n').encode('utf-8') ) def main(): n, m, k = map(int, input().split()...
{ "input": [ "2 2 1\n1 1\n2 1 1\n", "4 3 2\n1 2 3 4\n2 1 5\n3 4 2\n" ], "output": [ "3", "12" ] }
349
9
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network β€” for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one r...
def BFS(start): queue = [start] visited = [False] * n visited[start] = True dists = [0] * n while len(queue): current = queue.pop(0) for i in graph[current]: if not visited[i]: queue.append(i) visited[i] = True dists[i] = di...
{ "input": [ "5 5\n4 2\n3 5\n4 5\n5 1\n1 2\n", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4\n", "4 2\n1 3\n3 4\n" ], "output": [ "3\n", "-1\n", "2\n" ] }
350
7
Kolya Gerasimov loves kefir very much. He lives in year 1984 and knows all the details of buying this delicious drink. One day, as you probably know, he found himself in year 2084, and buying kefir there is much more complicated. Kolya is hungry, so he went to the nearest milk shop. In 2084 you may buy kefir in a plas...
def f(n, a, b, c): if a<=b-c: return n//a ans=0 while n>=b: t=max((n-b)//(b-c), 1) n-=(b-c)*t ans+=t return ans+n//a import sys print(f(*map(int, sys.stdin.read().split())))
{ "input": [ "10\n11\n9\n8\n", "10\n5\n6\n1\n" ], "output": [ "2\n", " 2\n" ] }
351
9
Bear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color ti. For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the bigges...
def main(): n = int(input()) a = [int(i) for i in input().strip().split()] res = [0] * n for st in range(n): cnt = [0] * n x = 0 y = 0 for ed in range(st, n): cnt[a[ed] - 1] += 1 if (cnt[a[ed] - 1] > x) or (cnt[a[ed] - 1] == x and a[ed] - 1 < y):...
{ "input": [ "3\n1 1 1\n", "4\n1 2 1 2\n" ], "output": [ "6 0 0\n", "7 3 0 0\n" ] }
352
8
Little Alyona is celebrating Happy Birthday! Her mother has an array of n flowers. Each flower has some mood, the mood of i-th flower is ai. The mood can be positive, zero or negative. Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose severa...
def cin(): return list(map(int,input().split())) n,m=cin() A=cin() s=0 for i in range(m): a,b=cin() B=sum(A[a-1:b]) s+=max(0,B) print(s)
{ "input": [ "4 3\n1 2 3 4\n1 3\n2 4\n1 1\n", "5 4\n1 -2 1 3 -4\n1 2\n4 5\n3 4\n1 4\n", "2 2\n-1 -2\n1 1\n1 2\n" ], "output": [ "16\n", "7\n", "0\n" ] }
353
7
Comrade Dujikov is busy choosing artists for Timofey's birthday and is recieving calls from Taymyr from Ilia-alpinist. Ilia-alpinist calls every n minutes, i.e. in minutes n, 2n, 3n and so on. Artists come to the comrade every m minutes, i.e. in minutes m, 2m, 3m and so on. The day is z minutes long, i.e. the day cons...
from math import gcd def I(): return map(int, input().split()) n, m, z = I() print(z//(n*m//gcd(n, m)))
{ "input": [ "1 1 10\n", "2 3 9\n", "1 2 5\n" ], "output": [ "10\n", "1\n", "2\n" ] }
354
7
Petya is a big fan of mathematics, especially its part related to fractions. Recently he learned that a fraction <image> is called proper iff its numerator is smaller than its denominator (a < b) and that the fraction is called irreducible if its numerator and its denominator are coprime (they do not have positive comm...
def gdc(a,b): if b ==0: return a return gdc(b,a%b) n = int(input()) a = n//2 b=n-a while gdc(a,b)!=1: a=a-1 b=b+1 print(a, b)
{ "input": [ "12\n", "4\n", "3\n" ], "output": [ "5 7\n", "1 3\n", "1 2\n" ] }
355
7
Pig is visiting a friend. Pig's house is located at point 0, and his friend's house is located at point m on an axis. Pig can use teleports to move along the axis. To use a teleport, Pig should come to a certain point (where the teleport is located) and choose where to move: for each teleport there is the rightmost ...
def fn(n): a=0 for i in range(int(n[0])): t=input().split(' ') if int(t[0])<=a : a=max(a,int(t[1])) if a>=int(n[1]): return 'YES' else: return 'NO' print(fn(input().split(' ')))
{ "input": [ "3 5\n0 2\n2 4\n3 5\n", "3 7\n0 4\n2 5\n6 7\n" ], "output": [ "YES\n", "NO\n" ] }
356
9
Arkady decides to observe a river for n consecutive days. The river's water level on each day is equal to some real value. Arkady goes to the riverside each day and makes a mark on the side of the channel at the height of the water level, but if it coincides with a mark made before, no new mark is created. The water d...
# python3 def readline(): return map(int, input().split()) def main(): n = int(input()) m = tuple(readline()) md = [None] * n prev = 0 for i in range(n): prev = md[i] = max(prev, m[i]) prev = 0 for i in range(n - 1, -1, -1): prev -= 1 prev = md[i] = max(prev, md[...
{ "input": [ "5\n0 1 1 2 2\n", "6\n0 1 0 3 0 2\n", "5\n0 1 2 1 2\n" ], "output": [ "0\n", "6\n", "1\n" ] }
357
11
Not to be confused with [chessboard](https://en.wikipedia.org/wiki/Chessboard). <image> Input The first line of input contains a single integer N (1 ≀ N ≀ 100) β€” the number of cheeses you have. The next N lines describe the cheeses you have. Each line contains two space-separated strings: the name of the cheese and...
def main(): n = int(input()) b, w = 0, 0 for x in range(n): s = input().split()[1] if s == 'soft': b += 1 else: w += 1 for x in range(1, 100): a = x ** 2 a1 = a // 2 a2 = a - a1 if max(b, w) <= a2 and min(b, w) <= a1: ...
{ "input": [ "6\nparmesan hard\nemmental hard\nedam hard\ncolby hard\ngruyere hard\nasiago hard\n", "9\nbrie soft\ncamembert soft\nfeta soft\ngoat soft\nmuenster soft\nasiago hard\ncheddar hard\ngouda hard\nswiss hard\n" ], "output": [ "4\n", "3\n" ] }
358
8
In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup...
def s(): n = int(input()) a = [int(input()) for _ in range(n)] mi = min(enumerate(a),key = lambda x:x[1]) ma = max(enumerate(a),key = lambda x:x[1]) p = sum(a) if p%n != 0: return 'Unrecoverable configuration.' if mi[1] == ma[1]: return 'Exemplary pages.' if a.count(mi[1]) > 1 or a.count(ma[1]) > 1: retur...
{ "input": [ "5\n250\n250\n250\n250\n250\n", "5\n270\n250\n250\n230\n250\n", "5\n270\n250\n249\n230\n250\n" ], "output": [ "Exemplary pages.\n", "20 ml. from cup #4 to cup #1.\n", "Unrecoverable configuration.\n" ] }
359
7
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners. The valid sizes of T-shirts are either "M" or from 0 to 3 "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not. Ther...
while True: try: def read(): n = int(input()) p = list() for i in range(n): p.append(input()) for i in range(n): n = input() if n in p: p.remove(n) print(len(p)) if __name__ =="__main__": read() except EOFError: break
{ "input": [ "2\nM\nXS\nXS\nM\n", "3\nXS\nXS\nM\nXL\nS\nXS\n", "2\nXXXL\nXXL\nXXL\nXXXS\n" ], "output": [ "0\n", "2\n", "1\n" ] }
360
8
During the research on properties of the greatest common divisor (GCD) of a set of numbers, Ildar, a famous mathematician, introduced a brand new concept of the weakened common divisor (WCD) of a list of pairs of integers. For a given list of pairs of integers (a_1, b_1), (a_2, b_2), ..., (a_n, b_n) their WCD is arbit...
n = int(input()) a,b = [0]*n,[0]*n g = 0 def gcd(a,b): return a if b == 0 else gcd(b,a%b) for i in range(n): (a[i],b[i]) = map(int,input().split()) g = gcd(g,a[i]*b[i]) for i in range(n): if gcd(g,a[i]) > 1: g = gcd(g,a[i]) else: g = gcd(g,b[i]) print(g if g > 1 else -1)
{ "input": [ "2\n10 16\n7 17\n", "3\n17 18\n15 24\n12 15\n", "5\n90 108\n45 105\n75 40\n165 175\n33 30\n" ], "output": [ "-1\n", "2\n", "3\n" ] }
361
10
Ivan unexpectedly saw a present from one of his previous birthdays. It is array of n numbers from 1 to 200. Array is old and some numbers are hard to read. Ivan remembers that for all elements at least one of its neighbours ls not less than it, more formally: a_{1} ≀ a_{2}, a_{n} ≀ a_{n-1} and a_{i} ≀ max(a_{i-1}, ...
from math import trunc MX = 201 MOD = 998244353 MODF = MOD * 1.0 quickmod = lambda x: x - MODF * trunc(x / MODF) def main(): n = int(input()) a = map(int, input().split()) dp0 = [1.0] * MX dp1 = [0.0] * MX for x in a: pomdp0 = [0.0] * MX pomdp1 = [0.0] * MX if x == -1: ...
{ "input": [ "3\n1 -1 2\n", "2\n-1 -1\n" ], "output": [ "1\n", "200\n" ] }
362
9
You are given a tree (a connected undirected graph without cycles) of n vertices. Each of the n - 1 edges of the tree is colored in either black or red. You are also given an integer k. Consider sequences of k vertices. Let's call a sequence [a_1, a_2, …, a_k] good if it satisfies the following criterion: * We will...
import collections as cc I=lambda:list(map(int,input().split())) n,k=I() mod=10**9+7 parent=[i for i in range(n+1)] def find(x): global count count+=1 while parent[x]!=x: x=parent[x] return x def union(x,y): a=find(x) b=find(y) if a!=b: parent[a]=parent[b]=min(a,b) count=0 tf=0 for i in range(n-1): a,b,c=I(...
{ "input": [ "4 4\n1 2 1\n2 3 1\n3 4 1\n", "4 6\n1 2 0\n1 3 0\n1 4 0\n", "3 5\n1 2 1\n2 3 0\n" ], "output": [ " 252\n", " 0\n", " ...
363
9
The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2). You are given a sequence a consisting of n integers. You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the...
def fun(array): ans='' count=0 l,r=0,n-1 last=-1 while l<=r: if min(array[l],array[r])<=last: break if array[l]<array[r]: last=array[l] ans+='L' l+=1 count+=1 elif array[l]>array[r]: last=array[r] ans+='R' r-=1 count+=1 else: break ans_1=ans last_1=last l_1=l while l_1<=...
{ "input": [ "7\n1 3 5 6 5 4 2\n", "5\n1 2 4 3 2\n", "4\n1 2 4 3\n", "3\n2 2 2\n" ], "output": [ "6\nLRLRRR", "4\nLRRR", "4\nLLRR\n", "1\nR" ] }
364
7
One common way of digitalizing sound is to record sound intensity at particular time moments. For each time moment intensity is recorded as a non-negative integer. Thus we can represent a sound file as an array of n non-negative integers. If there are exactly K distinct values in the array, then we need k = ⌈ log_{2} ...
def solve(): n,i = map(int, input().split()) ns = sorted([*map(int, input().split())]) k = 1<<(i*8//n) lis = [] for i in range(n-1): if ns[i]!=ns[i+1]: lis.append(i+1) lis.append(n) print(0 if len(lis) <= k else n-max(lis[i+k]-lis[i] for i in range(len(lis)-k))) solve()
{ "input": [ "6 1\n2 1 2 3 4 3\n", "6 1\n1 1 2 2 3 3\n", "6 2\n2 1 2 3 4 3\n" ], "output": [ "2\n", "2\n", "0\n" ] }
365
8
Ivan plays an old action game called Heretic. He's stuck on one of the final levels of this game, so he needs some help with killing the monsters. The main part of the level is a large corridor (so large and narrow that it can be represented as an infinite coordinate line). The corridor is divided into two parts; let'...
import sys I = sys.stdin.readline pr = sys.stdout.write srt=sorted lst=list st=set def main(): for _ in range(int(I())): n,r=map(int,I().split()) ar=srt(lst(st(map(int,I().split())))) pre=0 i=len(ar)-1;c=0 while i>=0: if ar[i]<=pre:break else:c+=1;pre+=r i-=1 pr(str(c)) pr('\n') main()
{ "input": [ "2\n3 2\n1 3 5\n4 1\n5 2 3 5\n" ], "output": [ "2\n2\n" ] }
366
9
There is a river of width n. The left bank of the river is cell 0 and the right bank is cell n + 1 (more formally, the river can be represented as a sequence of n + 2 cells numbered from 0 to n + 1). There are also m wooden platforms on a river, the i-th platform has length c_i (so the i-th platform takes c_i consecuti...
def f(n,m,d,a): b=[0]*m pos=0 for i in range(m): # print(b) b[i]=pos+d pos=pos+d+a[i]-1 # print(b) if b[-1]+a[-1]-1+d<n+1: print("NO") return [] pos=n+1 c=[0]*n for i in range(m-1,-1,-1): if b[i]+a[i]-1>=pos: b[i]=pos-a[i] pos=b[i] for j in range(b[i],b[i]+a[i]): c[j-1]=i+1 print("YES") ...
{ "input": [ "7 3 2\n1 2 1\n", "10 1 5\n2\n", "10 1 11\n1\n" ], "output": [ "YES\n0 1 0 2 2 0 3\n", "YES\n0 0 0 0 1 1 0 0 0 0\n", "YES\n0 0 0 0 0 0 0 0 0 1\n" ] }
367
9
Bob is about to take a hot bath. There are two taps to fill the bath: a hot water tap and a cold water tap. The cold water's temperature is t1, and the hot water's temperature is t2. The cold water tap can transmit any integer number of water units per second from 0 to x1, inclusive. Similarly, the hot water tap can ...
import math def gcd(a,b): if(b==0): return a return gcd(b,a%b) l=input().split() t1=int(l[0]) t2=int(l[1]) x1=int(l[2]) x2=int(l[3]) t0=int(l[4]) num1=t2-t0 num2=t0-t1 if(t1==t2): print(x1,x2) quit() if(num1==0): print(0,x2) quit() if(num2==0): print(x1,0) quit() z=num2/num1 maxa...
{ "input": [ "300 500 1000 1000 300\n", "10 70 100 100 25\n", "143 456 110 117 273\n" ], "output": [ "1000 0\n", "99 33\n", "76 54\n" ] }
368
8
One cold winter evening Alice and her older brother Bob was sitting at home near the fireplace and giving each other interesting problems to solve. When it was Alice's turn, she told the number n to Bob and said: β€”Shuffle the digits in this number in order to obtain the smallest possible number without leading zeroes....
def main(): s = input() if s != "0": l = sorted(c for c in s if c != '0') l[0] += '0' * s.count('0') s = ''.join(l) print(("OK", "WRONG_ANSWER")[s != input()]) if __name__ == '__main__': main()
{ "input": [ "3310\n1033\n", "4\n5\n" ], "output": [ "OK\n", "WRONG_ANSWER\n" ] }
369
10
Catherine 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 came up with. But when she came up with another one β€” xor of all pairwise sums of elements in the array, she realiz...
import sys from array import array # noqa: F401 from typing import List, Tuple, TypeVar, Generic, Sequence, Union # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') def main(): n = int(input()) a = sorted(map(int, input().split())) ans = 0 for d in range(25, -1, -1):...
{ "input": [ "3\n1 2 3\n", "2\n1 2\n" ], "output": [ "2\n", "3\n" ] }
370
9
You are given two integers a and b, and q queries. The i-th query consists of two numbers l_i and r_i, and the answer to it is the number of integers x such that l_i ≀ x ≀ r_i, and ((x mod a) mod b) β‰  ((x mod b) mod a). Calculate the answer for each query. Recall that y mod z is the remainder of the division of y by z...
import math a = 0 b = 0 p = 0 def get(x): k = x // p return (x-(k*max(a, b)+min(max(a, b), (x % p+1)))) for _ in range(int(input())): a, b, q = map(int, input().split()) p = math.gcd(a, b) p = a * b // p for k in range(q): l, r = map(int, input().split()) print(get(r) - get(...
{ "input": [ "2\n4 6 5\n1 1\n1 3\n1 5\n1 7\n1 9\n7 10 2\n7 8\n100 200\n" ], "output": [ "0\n0\n0\n2\n4\n0\n91\n" ] }
371
9
Given an array a of length n, find another array, b, of length n such that: * for each i (1 ≀ i ≀ n) MEX(\\{b_1, b_2, …, b_i\})=a_i. The MEX of a set of integers is the smallest non-negative integer that doesn't belong to this set. If such array doesn't exist, determine this. Input The first line contains an ...
from sys import stdin,stderr def rl(): return [int(w) for w in stdin.readline().split()] n, = rl() a = rl() a_set = set(a) free = 0 prev = 0 b = [] for cur in a: if cur != prev: b.append(prev) if free == prev: free += 1 prev = cur else: while free in a_set: ...
{ "input": [ "3\n1 2 3\n", "3\n1 1 3\n", "4\n0 0 0 2\n" ], "output": [ "0 1 2\n", "0 2 1\n", "1 3 4 0\n" ] }
372
10
Koa the Koala and her best friend want to play a game. The game starts with an array a of length n consisting of non-negative integers. Koa and her best friend move in turns and each have initially a score equal to 0. Koa starts. Let's describe a move in the game: * During his move, a player chooses any element of...
def solve(): n = int(input()) lst = list(map(int,input().split())) k = 1 while k < 10**9: k *= 2 num = 0 while k and num % 2 == 0: num = 0 for i in lst: if i % (k * 2) // k == 1: num += 1 k //= 2 if k == 0 and num % 2 == 0: ...
{ "input": [ "4\n5\n4 1 5 1 3\n4\n1 0 1 6\n1\n0\n2\n5 4\n", "3\n3\n1 2 2\n3\n2 2 3\n5\n0 0 0 2 2\n" ], "output": [ "WIN\nWIN\nDRAW\nWIN\n", "WIN\nLOSE\nDRAW\n" ] }
373
7
Given a set of integers (it can contain equal elements). You have to split it into two subsets A and B (both of them can contain equal elements or be empty). You have to maximize the value of mex(A)+mex(B). Here mex of a set denotes the smallest non-negative integer that doesn't exist in the set. For example: * m...
t = int(input()) def mex(setter): a = set(range(0, 101)) return min(a - setter) for i in range(t): n = int(input()) a = list(map(int,input().split())) A = set(a) B = set() for elem in a: if a.count(elem) > 1: B.add(elem) minimum = mex(A)+mex(B) print(minimum)
{ "input": [ "4\n6\n0 2 1 5 0 1\n3\n0 1 2\n4\n0 2 0 1\n6\n1 2 3 4 5 6\n" ], "output": [ "5\n3\n4\n0\n" ] }
374
8
You like playing chess tournaments online. In your last tournament you played n games. For the sake of this problem, each chess game is either won or lost (no draws). When you lose a game you get 0 points. When you win you get 1 or 2 points: if you have won also the previous game you get 2 points, otherwise you get 1 ...
def solve(): n,k=map(int,input().split()) #print(n,k) l=sorted(map(len,input().strip('L').split('W'))) z=len(l)+k while l and l[0]<=k: k-=l.pop(0) ans=2*min(n,z-1)-len(l) if ans<=0: ans=1 print(ans-1) t=int(input()) for _ in range(0,t): solve()
{ "input": [ "8\n5 2\nWLWLL\n6 5\nLLLWWL\n7 1\nLWLWLWL\n15 5\nWWWLLLWWWLLLWWW\n40 7\nLLWLWLWWWLWLLWLWWWLWLLWLLWLLLLWLLWWWLWWL\n1 0\nL\n1 1\nL\n6 1\nWLLWLW\n" ], "output": [ "7\n11\n6\n26\n46\n0\n1\n6\n" ] }
375
8
You have n distinct points (x_1, y_1),…,(x_n,y_n) on the plane and a non-negative integer parameter k. Each point is a microscopic steel ball and k is the attract power of a ball when it's charged. The attract power is the same for all balls. In one operation, you can select a ball i to charge it. Once charged, all ba...
def dist(a, b): return abs(a[0] - b[0]) + abs(a[1] - b[1]) def solve(n, k, p): for i in range(n): if all(dist(p[i], p[j]) <= k for j in range(n)): return 1 return -1 tests = int(input()) for test in range(tests): n, k = map(int, input().split()) p = [list(map(int, input().split())) for i in range(n)] print...
{ "input": [ "3\n3 2\n0 0\n3 3\n1 1\n3 3\n6 7\n8 8\n6 9\n4 1\n0 0\n0 1\n0 2\n0 3\n" ], "output": [ "\n-1\n1\n-1\n" ] }
376
8
Having stayed home alone, Petya decided to watch forbidden films on the Net in secret. "What ungentlemanly behavior!" β€” you can say that, of course, but don't be too harsh on the kid. In his country films about the Martians and other extraterrestrial civilizations are forbidden. It was very unfair to Petya as he adored...
def s(): a = [[ord(i)-48 if ord(i) < 60 else ord(i)-55 for i in i]for i in input().split(':')] r = [i for i in range(max(max(a[0]),max(a[1]))+1,61) if sum(list(i**l[0]*l[1] for l in enumerate(reversed(a[0]))))<24 and sum(list(i**l[0]*l[1] for l in enumerate(reversed(a[1]))))<60] if len(r) == 0: print(0) elif r[-1...
{ "input": [ "2A:13\n", "11:20\n", "000B:00001\n" ], "output": [ "0", "3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 ", "-1" ] }
377
8
<image> While trading on his favorite exchange trader William realized that he found a vulnerability. Using this vulnerability he could change the values of certain internal variables to his advantage. To play around he decided to change the values of all internal variables from a_1, a_2, …, a_n to -a_1, -a_2, …, -a_n...
def solve(n: int) -> None: arr = [2, 1, 2, 2, 1, 2] print(3 * n) for i in range(1, n + 1, 2): for j in arr: print(j, i, i + 1) t = int(input()) for _ in range(t): n = int(input()) input() solve(n)
{ "input": [ "2\n4\n1 1 1 1\n4\n4 3 1 2\n" ], "output": [ "\n8\n2 1 2\n2 1 2\n2 1 3\n2 1 3\n2 1 4\n2 1 4\n1 1 2\n1 1 2\n8\n2 1 4\n1 2 4\n1 2 4\n1 2 4\n1 3 4\n1 1 2\n1 1 2\n1 1 4\n" ] }
378
7
Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him. One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For e...
def fun(lst): s=l=lst[0] a=0 for i in lst[1:]: if i<s: s=i a+=1 if i>l: l=i a+=1 return a n=int(input()) lst=list(map(int,input().split())) print(fun(lst))
{ "input": [ "10\n4664 6496 5814 7010 5762 5736 6944 4850 3698 7242\n", "5\n100 50 200 150 200\n" ], "output": [ "4\n", "2\n" ] }
379
9
To celebrate the second ABBYY Cup tournament, the Smart Beaver decided to throw a party. The Beaver has a lot of acquaintances, some of them are friends with each other, and some of them dislike each other. To make party successful, the Smart Beaver wants to invite only those of his friends who are connected by friends...
from sys import setrecursionlimit setrecursionlimit(10 ** 9) def dfs(g, col, st): global used used[st] = col for w in g[st]: if used[w] is False: dfs(g, col, w) n = int(input()) k = int(input()) g = [] used = [False] * n for i in range(n): g.append([]) for i in range(k): x...
{ "input": [ "9\n8\n1 2\n1 3\n2 3\n4 5\n6 7\n7 8\n8 9\n9 6\n2\n1 6\n7 9\n" ], "output": [ "3" ] }
380
8
Vasya plays a computer game with ninjas. At this stage Vasya's ninja should get out of a deep canyon. The canyon consists of two vertical parallel walls, their height is n meters. Let's imagine that we split these walls into 1 meter-long areas and number them with positive integers from 1 to n from bottom to top. Some...
f = lambda: [q != '-' for q in input()] n, k = map(int, input().split()) t = [(0, 0, f(), f())] def g(d, s, a, b): if d > n - 1: print('YES') exit() if not (a[d] or s > d): a[d] = 1 t.append((d, s, a, b)) while t: d, s, a, b = t.pop() g(d + 1, s + 1, a, b) g(d - 1, s ...
{ "input": [ "7 3\n---X--X\n-X--XX-\n", "6 2\n--X-X-\nX--XX-\n" ], "output": [ "YES\n", "NO\n" ] }
381
9
The Little Elephant has got a problem β€” somebody has been touching his sorted by non-decreasing array a of length n and possibly swapped some elements of the array. The Little Elephant doesn't want to call the police until he understands if he could have accidentally changed the array himself. He thinks that he could ...
def arr_inp(n): if n == 1: return [int(x) for x in stdin.readline().split()] elif n == 2: return [float(x) for x in stdin.readline().split()] else: return [str(x) for x in stdin.readline().split()] from sys import stdin n, a = int(input()), arr_inp(1) a1, c, ix = sorted(a.copy()),...
{ "input": [ "3\n3 2 1\n", "4\n4 3 2 1\n", "2\n1 2\n" ], "output": [ "YES", "NO", "YES" ] }
382
8
Emuskald is addicted to Codeforces, and keeps refreshing the main page not to miss any changes in the "recent actions" list. He likes to read thread conversations where each thread consists of multiple messages. Recent actions shows a list of n different threads ordered by the time of the latest message in the thread....
def main(): n = int(input()) aa = list(map(int, input().split())) m = aa[-1] for i in range(n - 2, -2, -1): a = aa[i] if m < a: break m = a print(i + 1) if __name__ == '__main__': main()
{ "input": [ "5\n5 2 1 3 4\n", "4\n4 3 2 1\n", "3\n1 2 3\n" ], "output": [ "2\n", "3\n", "0\n" ] }
383
8
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear a...
from bisect import bisect_right def answer(n,A): ans=[A[0]] for i in range(1,n): if ans[-1]<A[i]: ans.append(A[i]) else: index=bisect_right(ans,A[i]) ans[index]=A[i] return len(ans) n=int(input()) arr=list(map(int,input().split())) print(ans...
{ "input": [ "3\n3 1 2\n" ], "output": [ "2\n" ] }
384
9
Fox Ciel is playing a card game with her friend Fox Jiro. There are n piles of cards on the table. And there is a positive integer on each card. The players take turns and Ciel takes the first turn. In Ciel's turn she takes a card from the top of any non-empty pile, and in Jiro's turn he takes a card from the bottom o...
import re def main(): n=eval(input()) a=[] s=[] s.append(0) s.append(0) while n: n-=1 temp=re.split(' ',input()) k=eval(temp[0]) for i in range(k>>1): s[0]+=eval(temp[i+1]) if k&1: a.append(eval(temp[(k+1)>>1])) for i in range((k+1)>>1,k): s[1]+=eval(temp[i+1]) a...
{ "input": [ "3\n3 1 3 2\n3 5 4 6\n2 8 7\n", "2\n1 100\n2 1 10\n", "3\n3 1000 1000 1000\n6 1000 1000 1000 1000 1000 1000\n5 1000 1000 1000 1000 1000\n", "1\n9 2 8 6 5 9 4 7 1 3\n" ], "output": [ "18 18\n", "101 10\n", "7000 7000\n", "30 15\n" ] }
385
7
Two teams meet in The Game World Championship. Some scientists consider this game to be the most intellectually challenging game in the world. You are given two strings describing the teams' actions in the final battle. Figure out who became the champion. Input The input contains two strings of equal length (between ...
def get(c): return "8[(".index(c) def win(d, e): return (get(d) + 1) % 3 == get(e) a = input() b = input() x = 0 y = 0 for i in range(0, len(a), 2): x += win(a[i], b[i]) y += win(b[i], a[i]) if x > y: print('TEAM 1 WINS') elif x < y: print('TEAM 2 WINS') else: print('TIE')
{ "input": [ "[]()[]8&lt;\n8&lt;[]()8&lt;\n", "8&lt;8&lt;()\n[]8&lt;[]\n" ], "output": [ "TEAM 2 WINS", "TEAM 1 WINS" ] }
386
8
Om Nom really likes candies and doesn't like spiders as they frequently steal candies. One day Om Nom fancied a walk in a park. Unfortunately, the park has some spiders and Om Nom doesn't want to see them at all. <image> The park can be represented as a rectangular n Γ— m field. The park has k spiders, each spider at ...
def ans(): n, m, k = map(int, input().split()) a = list([] for i in range(n)) s = [0]*m for i in range(n): a[i] = input() for i in range(1,n): for j in range(m): if i < m-j and a[i][j+i] == 'L': s[j]+=1 if i <= j and a[i][j-i] == 'R': ...
{ "input": [ "2 2 2\n..\nRL\n", "3 3 4\n...\nR.L\nR.U\n", "2 2 2\n..\nUU\n", "3 4 8\n....\nRRLL\nUUUU\n", "2 2 2\n..\nLR\n" ], "output": [ "1 1 ", "0 2 2 ", "0 0 ", "1 3 3 1 ", "0 0 " ] }
387
9
Recently Pashmak has been employed in a transportation company. The company has k buses and has a contract with a school which has n students. The school planned to take the students to d different places for d days (each day in one place). Each day the company provides all the buses for the trip. Pashmak has to arrang...
def f(t): i = -1 t[i] += 1 while t[i] > k: t[i] = 1 i -= 1 t[i] += 1 return list(map(str, t)) n, k, d = map(int, input().split()) if k ** d < n: print(-1) else: t = [1] * d t[-1] = 0 s = [f(t) for i in range(n)] print('\n'.join([' '.join(t) for t in zip(*s)]))
{ "input": [ "3 2 2\n", "3 2 1\n" ], "output": [ "1 2 1\n1 1 2\n", "-1\n" ] }
388
8
Valery is a PE teacher at a school in Berland. Soon the students are going to take a test in long jumps, and Valery has lost his favorite ruler! However, there is no reason for disappointment, as Valery has found another ruler, its length is l centimeters. The ruler already has n marks, with which he can make measure...
n, l, x, y = map(int, input().split()) s = set(map(int, input().split())) def f(d): return any(i + d in s for i in s) def g(): for i in s: if i + x + y in s: return i + x return 0 def h(): for i in s: if i + y - x in s: if i - x >= 0: return i - x if i + y <= l:...
{ "input": [ "3 250 185 230\n0 185 250\n", "2 300 185 230\n0 300\n", "4 250 185 230\n0 20 185 250\n" ], "output": [ "1\n230\n", "2\n185 230\n", "0\n" ] }
389
8
Mr. Kitayuta has just bought an undirected graph consisting of n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi. Mr. Kitayuta wants you to process the following q queries. In the i-th query, he gives you two integers β€” ui...
f = lambda: map(int, input().split()) n, m = f() p = [list(range(n + 1)) for x in range(m + 1)] def g(c, x): if x != p[c][x]: p[c][x] = g(c, p[c][x]) return p[c][x] for i in range(m): a, b, c = f() p[c][g(c, a)] = g(c, b) for j in range(int(input())): a, b = f() print(sum(g(i, a) == g(i, b) for ...
{ "input": [ "5 7\n1 5 1\n2 5 1\n3 5 1\n4 5 1\n1 2 2\n2 3 2\n3 4 2\n5\n1 5\n5 1\n2 5\n1 5\n1 4\n", "4 5\n1 2 1\n1 2 2\n2 3 1\n2 3 3\n2 4 3\n3\n1 2\n3 4\n1 4\n" ], "output": [ "1\n1\n1\n1\n2\n", "2\n1\n0\n" ] }
390
9
Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i...
mod = 10 ** 9 + 7 import math def f(n): return math.factorial(n) k = int(input()) c = [int(input()) for i in range(k)] s, cnt = 0, 1 for i in c: cnt *= f(s + i - 1) // f(i - 1) // f(s) cnt %= mod s += i print(cnt)
{ "input": [ "3\n2\n2\n1\n", "4\n1\n2\n3\n4\n" ], "output": [ "3\n", "1680\n" ] }
391
8
Kefa wants to celebrate his first big salary by going to restaurant. However, he needs company. Kefa has n friends, each friend will agree to go to the restaurant if Kefa asks. Each friend is characterized by the amount of money he has and the friendship factor in respect to Kefa. The parrot doesn't want any friend t...
def key_sort(x): return x[0] v = [] n, d = input().split() n = int(n) d = int(d) for i in range(n): x = input().split() v.append([int(x[0]), int(x[1])]) v.sort(key = key_sort) i = j = s = m = 0 while i < n and j < n: if v[j][0] - v[i][0] >= d: s -= v[i][1] i += 1 else: ...
{ "input": [ "5 100\n0 7\n11 32\n99 10\n46 8\n87 54\n", "4 5\n75 5\n0 100\n150 20\n75 1\n" ], "output": [ "111", "100" ] }
392
7
After seeing the "ALL YOUR BASE ARE BELONG TO US" meme for the first time, numbers X and Y realised that they have different bases, which complicated their relations. You're given a number X represented in base bx and a number Y represented in base by. Compare those two numbers. Input The first line of the input con...
I=lambda:map(int,input().split()[::-1]) def f(): b,_=I() r,x=0,1 for i in I(): r+=i*x x*=b return r a=f()-f() print("<"if a<0 else ">="[a==0])
{ "input": [ "7 16\n15 15 4 0 0 7 10\n7 9\n4 8 0 3 1 5 0\n", "3 3\n1 0 2\n2 5\n2 4\n", "6 2\n1 0 1 1 1 1\n2 10\n4 7\n" ], "output": [ ">", "<", "=" ] }
393
7
Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks. Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off. You know that there will be n interesting minutes t1, t2, ..., tn. Yo...
def f(l): for i in range(len(l)): if l[i]-l[i-1]>15: return l[i-1]+15 return 90 n=int(input()) l=list(map(int,input().split())) l.append(0) if 90 not in l: l.append(90) l.sort() print(f(l))
{ "input": [ "3\n7 20 88\n", "9\n15 20 30 40 50 60 70 80 90\n", "9\n16 20 30 40 50 60 70 80 90\n" ], "output": [ "35\n", "90\n", "15\n" ] }
394
8
A tree is an undirected connected graph without cycles. Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is cons...
from collections import defaultdict from sys import stdin,setrecursionlimit setrecursionlimit(10**6) import threading def f(a): n=len(a) a=list(map(lambda s:s-1,a)) root=None for i in range(len(a)): if a[i]==i: root=i vis=[0]*(n) traitors=[] for i in range(0,n): cycle=-1 cur=i move=set() while vis...
{ "input": [ "5\n3 2 2 5 3\n", "8\n2 3 5 4 1 6 6 7\n", "4\n2 3 3 4\n" ], "output": [ "0\n3 2 2 5 3 ", "2 \n2 3 5 4 4 4 6 7 \n", "1 \n2 3 3 3 \n" ] }
395
8
Anatoly lives in the university dorm as many other students do. As you know, cockroaches are also living there together with students. Cockroaches might be of two colors: black and red. There are n cockroaches living in Anatoly's room. Anatoly just made all his cockroaches to form a single line. As he is a perfectioni...
n, s = int(input()), input() def f(x): a, b = s[::2].count(x[0]), s[1::2].count(x[1]) return min(a, b) + abs(a - b) print(min(f('rb'), f('br')))
{ "input": [ "5\nrbbrr\n", "5\nbbbbb\n", "3\nrbr\n" ], "output": [ "1\n", "2\n", "0\n" ] }
396
7
A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times b, b + a, b + 2a, b + 3a, ... and Morty screams at times d, d + c, d + 2c, d + 3c, .... <image> The Monster will catch them if at any point they scream at the same tim...
def readInts(): return [int(x) for x in input().split()] a, b = readInts() c, d = readInts() l = set(a*i + b for i in range(100)) & set(c*i + d for i in range(100)) print(min(l) if l else -1)
{ "input": [ "20 2\n9 19\n", "2 1\n16 12\n" ], "output": [ "82\n", "-1\n" ] }
397
11
After several latest reforms many tourists are planning to visit Berland, and Berland people understood that it's an opportunity to earn money and changed their jobs to attract tourists. Petya, for example, left the IT corporation he had been working for and started to sell souvenirs at the market. This morning, as us...
def souvenier_calc(max_weight, weights, value): const = len(weights) ans = [-1061109567 for x in range(max_weight+1)] node = [(x, y) for x, y in zip(weights, value)] node = sorted(node, key=lambda x: x[1]/x[0], reverse=True) weights = [x[0] for x in node] value = [x[1] for x in node] sum = 0...
{ "input": [ "4 3\n3 10\n2 7\n2 8\n1 1\n", "2 2\n1 3\n2 2\n", "1 1\n2 1\n" ], "output": [ "10\n", "3\n", "0\n" ] }
398
7
<image> Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting. The game consists of multiple rounds. Its rules are very simple: in each round, a natural number k is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's s...
import sys input = sys.stdin.buffer.readline def gcd(a, b): if a > b: a, b = b, a if b % a==0: return a return gcd(b % a, a) def process(a, b): g = gcd(a, b) r = a//g s = b//g if g % r != 0: return 'No' g = g//r if g % s != 0: return 'No' G3 = ...
{ "input": [ "6\n2 4\n75 45\n8 8\n16 16\n247 994\n1000000000 1000000\n" ], "output": [ "Yes\nYes\nYes\nNo\nNo\nYes\n" ] }
399
8
This time the Berland Team Olympiad in Informatics is held in a remote city that can only be reached by one small bus. Bus has n passenger seats, seat i can be occupied only by a participant from the city ai. Today the bus has completed m trips, each time bringing n participants. The participants were then aligned in ...
def main(): _, k, m = [int(x) for x in input().split()] a = [] last = ("-1", 0) a.append(last) for ai in input().split(): if last[0] == ai: last = (ai, last[1]+1) a[-1] = last else: last = (ai, 1) a.append(last) if last[1] == k...
{ "input": [ "4 2 5\n1 2 3 1\n", "1 9 10\n1\n", "3 2 10\n1 2 1\n" ], "output": [ "12\n", "1\n", "0\n" ] }