index
int64
0
5.16k
difficulty
int64
7
12
question
stringlengths
126
7.12k
solution
stringlengths
30
18.6k
test_cases
dict
100
9
After his wife's tragic death, Eurydice, Orpheus descended to the realm of death to see her. Reaching its gates was uneasy, but passing through them proved to be even more challenging. Mostly because of Cerberus, the three-headed hound of Hades. Orpheus, a famous poet, and musician plans to calm Cerberus with his poe...
def main(s): a, b = 0, 0 rs = 0 for ch in s: if ch in [a, b]: rs += 1 ch = 0 a, b = b, ch return rs rs = [] for _ in range(int(input())): rs.append(main(input())) print(*rs, sep='\n')
{ "input": [ "7\nbabba\nabaac\ncodeforces\nzeroorez\nabcdcba\nbbbbbbb\na\n" ], "output": [ "\n1\n1\n0\n1\n1\n4\n0\n" ] }
101
10
A permutation — is a sequence of length n integers from 1 to n, in which all the numbers occur exactly once. For example, [1], [3, 5, 2, 1, 4], [1, 3, 2] — permutations, and [2, 3, 2], [4, 3, 1], [0] — no. Polycarp was recently gifted a permutation a[1 ... n] of length n. Polycarp likes trees more than permutations, s...
def tree(arr,cnt): if not arr: return mx=max(arr) d[mx]=cnt ind=arr.index(mx) tree(arr[:ind],cnt+1) tree(arr[ind+1:],cnt+1) for _ in range(int(input())): n=int(input()) a = list(map(int, input().split())) d=dict() tree(a,0) for i in a: print(d[i],end=" ") print()
{ "input": [ "3\n5\n3 5 2 1 4\n1\n1\n4\n4 3 1 2\n" ], "output": [ "\n1 0 2 3 1 \n0 \n0 1 3 2 \n" ] }
102
9
In some country live wizards. They love playing with numbers. The blackboard has two numbers written on it — a and b. The order of the numbers is not important. Let's consider a ≤ b for the sake of definiteness. The players can cast one of the two spells in turns: * Replace b with b - ak. Number k can be chosen by...
def solve(a, b): if a == 0: return False if solve(b % a, a): b //= a return not (b % (a + 1) & 1) return True n = int(input()) for _ in range(n): a, b = [int(x) for x in input().split()] if a > b: a, b = b, a if solve(a, b): print("First") else: ...
{ "input": [ "4\n10 21\n31 10\n0 1\n10 30\n" ], "output": [ "First\nSecond\nSecond\nFirst\n" ] }
103
8
Flatland is inhabited by pixels of three colors: red, green and blue. We know that if two pixels of different colors meet in a violent fight, only one of them survives the fight (that is, the total number of pixels decreases by one). Besides, if pixels of colors x and y (x ≠ y) meet in a violent fight, then the pixel t...
a = list(map(int,input().split())) def calc(a): return int((((a[1]-a[0])+(a[1]+a[0]))/2)) a.sort() if a[1] % 2 == 0 and a[0] % 2 == 0: print(calc(a)) elif a[1] % 2 == 0 or a[0] % 2 == 0: print(a[2]) else: print(calc(a))
{ "input": [ "1 1 1\n", "3 1 0\n" ], "output": [ " 1\n", " 3\n" ] }
104
7
Some days ago, I learned the concept of LCM (least common multiple). I've played with it for several times and I want to make a big number with it. But I also don't want to use many numbers, so I'll choose three positive integers (they don't have to be distinct) which are not greater than n. Can you help me to find th...
def main(): n = int(input()) print(n if n < 3 else ((n - 1) * (n * (n - 2) if n & 1 else (n - 3) * (n if n % 3 else n - 2)))) if __name__ == '__main__': main()
{ "input": [ "7\n", "9\n" ], "output": [ "210\n", "504\n" ] }
105
10
Berland Government decided to improve relations with neighboring countries. First of all, it was decided to build new roads so that from each city of Berland and neighboring countries it became possible to reach all the others. There are n cities in Berland and neighboring countries in total and exactly n - 1 two-way r...
def getPar(x): while (p[x] != x): x = p[x] return x def union(x,y): p1 = getPar(x) p2 = getPar(y) p[p2] = p1 n = int(input()) p = [i for i in range(n+1)] e = [] for _ in range(n-1): u,v = map(int,input().split()) p1 = getPar(u) p2 = getPar(v) if (p1 == p2): e.append([u,v]) else: union(u,v) s =...
{ "input": [ "7\n1 2\n2 3\n3 1\n4 5\n5 6\n6 7\n", "2\n1 2\n" ], "output": [ "1\n3 1 1 4 ", "0\n" ] }
106
9
Polycarpus is sure that his life fits the description: "first there is a white stripe, then a black one, then a white one again". So, Polycarpus is sure that this rule is going to fulfill during the next n days. Polycarpus knows that he is in for w good events and b not-so-good events. At least one event is going to ta...
import sys MOD = int(1e9) + 9 def inv(n): return pow(n, MOD - 2, MOD) def combo(n): rv = [0 for __ in range(n + 1)] rv[0] = 1 for k in range(n): rv[k + 1] = rv[k] * (n - k) % MOD * inv(k + 1) % MOD return rv with sys.stdin as fin, sys.stdout as fout: n, w, b = map(int, next(fin).spl...
{ "input": [ "3 2 1\n", "3 2 2\n", "4 2 2\n" ], "output": [ "2\n", "4\n", "4\n" ] }
107
9
Pavel loves grid mazes. A grid maze is an n × m rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side. Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any oth...
from collections import deque dirs = ((1, 0), (0, 1), (-1, 0), (0, -1)) def valid(r, c): return 0 <= r < n and 0 <= c < m and grid[r][c] == '.' def dfs(r, c, count, viewed): queue = deque() queue.append((r, c)) viewed[r][c] = True count -= 1 while len(queue) != 0 and count > 0: r, ...
{ "input": [ "3 4 2\n#..#\n..#.\n#...\n", "5 4 5\n#...\n#.#.\n.#..\n...#\n.#.#\n" ], "output": [ "#..#\n..#X\n#..X\n", "#...\n#.#.\nX#..\nXX.#\nX#X#\n" ] }
108
7
As usual, Sereja has array a, its elements are integers: a[1], a[2], ..., a[n]. Let's introduce notation: <image> A swap operation is the following sequence of actions: * choose two indexes i, j (i ≠ j); * perform assignments tmp = a[i], a[i] = a[j], a[j] = tmp. What maximum value of function m(a) can Serej...
R=lambda:map(int,input().split()) n,k=R() a=list(R()) def f(l,r): x=sorted(a[:l]+a[r+1:],reverse=True) y=sorted(a[l:r+1]) return sum(y+[max(0,x[i]-y[i])for i in range(min(k,len(x),len(y)))]) print(max(f(l,r)for l in range(n)for r in range(l,n)))
{ "input": [ "5 10\n-1 -1 -1 -1 -1\n", "10 2\n10 -1 2 2 2 2 2 2 -1 10\n" ], "output": [ "-1\n", "32\n" ] }
109
10
Jzzhu have n non-negative integers a1, a2, ..., an. We will call a sequence of indexes i1, i2, ..., ik (1 ≤ i1 < i2 < ... < ik ≤ n) a group of size k. Jzzhu wonders, how many groups exists such that ai1 & ai2 & ... & aik = 0 (1 ≤ k ≤ n)? Help him and print this number modulo 1000000007 (109 + 7). Operation x & y deno...
import sys input = lambda : sys.stdin.readline().rstrip() sys.setrecursionlimit(2*10**5+10) write = lambda x: sys.stdout.write(x+"\n") debug = lambda x: sys.stderr.write(x+"\n") writef = lambda x: print("{:.12f}".format(x)) # zeta mebius def zeta_super(val, n): # len(val)==2^n out = val[:] for i in rang...
{ "input": [ "3\n2 3 3\n", "4\n0 1 2 3\n", "6\n5 2 0 5 2 1\n" ], "output": [ "0\n", "10\n", "53\n" ] }
110
7
Malek has recently found a treasure map. While he was looking for a treasure he found a locked door. There was a string s written on the door consisting of characters '(', ')' and '#'. Below there was a manual on how to open the door. After spending a long time Malek managed to decode the manual and found out that the ...
def f(t): n = t.count('#') - 1 k = t.rfind('#') + 1 t = t.replace('#', ')') t = [2 * ord(i) - 81 for i in t] a = b = c = 0 for i in t[k: ]: b -= i c -= i if c < 0: c = 0 if c > 0: return -1 for i in t[: k]: a -= i if a < 0: return -1 if b + a...
{ "input": [ "(((#)((#)\n", "#\n", "()((#((#(#()\n", "(#)\n" ], "output": [ "1\n2\n", "-1\n", "1\n1\n3\n", "-1\n" ] }
111
11
After bracket sequences Arthur took up number theory. He has got a new favorite sequence of length n (a1, a2, ..., an), consisting of integers and integer k, not exceeding n. This sequence had the following property: if you write out the sums of all its segments consisting of k consecutive elements (a1 + a2 ... + ak, ...
INF = 10000000001 def fill(s): s.insert(0, -INF) s.append(INF) i = 0 for j in filter(lambda x: s[x] != '?', range(1, len(s))): d = i - j s[j] = int(s[j]) if s[i] > s[j]+d: raise a = max(min(d//2, s[j]+d), s[i]) for t in range(i+1, j): s[t] = a + t - i i = j return s[1:-1] n...
{ "input": [ "3 2\n? 1 2\n", "5 1\n-10 -9 ? -7 -6\n", "5 3\n4 6 7 2 9\n" ], "output": [ "0 1 2\n", "-10 -9 -8 -7 -6\n", "Incorrect sequence\n" ] }
112
8
You've got array A, consisting of n integers and a positive integer k. Array A is indexed by integers from 1 to n. You need to permute the array elements so that value <image> became minimal possible. In particular, it is allowed not to change order of elements at all. Input The first line contains two integers n,...
def solve(n, k, As): As.sort() m, r = divmod(n, k) dp = [0] * (r + 1) for i in range(1, k): im = i * m new_dp = [0] * (r + 1) new_dp[0] = dp[0] + As[im] - As[im - 1] for h in range(1, min(i, r) + 1): new_dp[h] = max(dp[h], dp[h - 1]) + As[im + h] - As[im + h -...
{ "input": [ "5 2\n3 -5 3 -5 3\n", "3 2\n1 2 4\n", "6 3\n4 3 4 3 2 5\n" ], "output": [ "0\n", "1\n", "3\n" ] }
113
9
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it...
def main(): n, a, b = map(int, input().split()) l, res = [], [] for _ in range(n): u, v = input().split() l.append((int(u) - a, int(v) - b)) x0, y0 = l[-1] for x1, y1 in l: res.append(x1 * x1 + y1 * y1) dx, dy = x1 - x0, y1 - y0 if (x0 * dx + y0 * dy) * (x1 * ...
{ "input": [ "3 0 0\n0 1\n-1 2\n1 2\n", "4 1 -1\n0 0\n1 2\n2 0\n1 1\n" ], "output": [ "12.566370614359176\n", "21.991148575128552\n" ] }
114
7
Recently, Pari and Arya did some research about NP-Hard problems and they found the minimum vertex cover problem very interesting. Suppose the graph G is given. Subset A of its vertices is called a vertex cover of this graph, if for each edge uv there is at least one endpoint of it in this set, i.e. <image> or <image>...
n,m=map(int,input().split()) flag=False f=[0]*100001 E=[[] for i in range(n+1)] ee=[tuple(map(int,input().split())) for _ in range(m)] for u,v in sorted(ee): E[u]+=[v]; E[v]+=[u] def bfs(nom,col): ch=[(nom,col)] while ch: v,c=ch.pop() if f[v]==0: f[v]=c for u in E[v]: if f[u]==0: ch+=...
{ "input": [ "4 2\n1 2\n2 3\n", "3 3\n1 2\n2 3\n1 3\n" ], "output": [ "3\n1 3 4 \n1\n2 ", "-1" ] }
115
8
Ilya is an experienced player in tic-tac-toe on the 4 × 4 field. He always starts and plays with Xs. He played a lot of games today with his friend Arseny. The friends became tired and didn't finish the last game. It was Ilya's turn in the game when they left it. Determine whether Ilya could have won the game by making...
def tri(ar): d={'.':0,'x':0,'o':0} for i,j in ar: d[a[i][j]]+=1 if d['.']==1 and d['x']==2: ans[0]='YES' #print(d) ans=['NO'] a=[input() for i in range(4)] for i in range(2): for j in range(2): tri([(i,j),(i+1,j+1),(i+2,j+2)]) for j in range(2,4): tri([(i...
{ "input": [ "o.x.\no...\n.x..\nooxx\n", "x.ox\nox..\nx.o.\noo.x\n", "xx..\n.oo.\nx...\noox.\n", "x..x\n..oo\no...\nx.xo\n" ], "output": [ "NO\n", "NO\n", "YES\n", "YES\n" ] }
116
7
Mister B once received a gift: it was a book about aliens, which he started read immediately. This book had c pages. At first day Mister B read v0 pages, but after that he started to speed up. Every day, starting from the second, he read a pages more than on the previous day (at first day he read v0 pages, at second —...
#!/usr/bin/python3 def read_ints(): return [int(i) for i in input().split()] c, v0, v1, a, l = read_ints() s = 0 d = 1 while s < c: s = min(s + v0, c) if s == c: break v0 = min(v0 + a, v1) s -= l d += 1 print(d)
{ "input": [ "5 5 10 5 4\n", "12 4 12 4 1\n", "15 1 100 0 0\n" ], "output": [ "1\n", "3\n", "15\n" ] }
117
8
Polycarp takes part in a math show. He is given n tasks, each consists of k subtasks, numbered 1 through k. It takes him tj minutes to solve the j-th subtask of any task. Thus, time required to solve a subtask depends only on its index, but not on the task itself. Polycarp can solve subtasks in any order. By solving s...
n,k,M = map(int,input().split()) T = sorted(map(int,input().split())) sT = sum(T) def it(p): # pタスク完成させるノリ score = p*(k+1) m = M - p*sT if m < 0: return 0 q = n-p for t in T: if m > q*t: m -= q*t score += q else: score += m//t break return score print(max(it(i) f...
{ "input": [ "5 5 10\n1 2 4 8 16\n", "3 4 11\n1 2 3 4\n" ], "output": [ "7\n", "6\n" ] }
118
7
Alex, Bob and Carl will soon participate in a team chess tournament. Since they are all in the same team, they have decided to practise really hard before the tournament. But it's a bit difficult for them because chess is a game for two players, not three. So they play with each other according to following rules: ...
def solve(): n = int(input()) spector = 3 for _ in range(n): p = int(input()) if p == spector: return 'NO' spector = 6 - p - spector return 'YES' print(solve())
{ "input": [ "2\n1\n2\n", "3\n1\n1\n2\n" ], "output": [ "NO\n", "YES\n" ] }
119
8
You have a Petri dish with bacteria and you are preparing to dive into the harsh micro-world. But, unfortunately, you don't have any microscope nearby, so you can't watch them. You know that you have n bacteria in the Petri dish and size of the i-th bacteria is a_i. Also you know intergalactic positive integer constan...
from bisect import bisect def main(): N, K = map(int, input().split()) A = list(map(int, input().split())) A.sort() ans = N for i in range(N): j = bisect(A, A[i] + K) if A[i] < A[j-1]: ans -= 1 print(ans) main()
{ "input": [ "6 5\n20 15 10 15 20 25\n", "7 1\n101 53 42 102 101 55 54\n", "7 1000000\n1 1 1 1 1 1 1\n" ], "output": [ "1\n", "3\n", "7\n" ] }
120
11
Vasya has a sequence a consisting of n integers a_1, a_2, ..., a_n. Vasya may pefrom the following operation: choose some number from the sequence and swap any pair of bits in its binary representation. For example, Vasya can transform number 6 (... 00000000110_2) into 3 (... 00000000011_2), 12 (... 000000001100_2), 10...
from array import array def popcount(x): res = 0; while(x > 0): res += (x & 1) x >>= 1 return res def main(): n = int(input()) a = array('i',[popcount(int(x)) for x in input().split(' ')]) ans,s0,s1 = 0,0,0 for i in range(n): if(a[i] & 1): s0,s1 = s1,s0 ...
{ "input": [ "4\n1 2 1 16\n", "3\n6 7 14\n" ], "output": [ "4\n", "2\n" ] }
121
10
You are playing a strange game with Li Chen. You have a tree with n nodes drawn on a piece of paper. All nodes are unlabeled and distinguishable. Each of you independently labeled the vertices from 1 to n. Neither of you know the other's labelling of the tree. You and Li Chen each chose a subtree (i.e., a connected su...
import sys def ask(u, t): if t == 0: print('A', u) else: print('B', u) sys.stdout.flush() return int(input()) def solve(): n = int(input()) e = [[] for _ in range(n + 1)] p = [0] * (n + 1) inA = [False] * (n + 1) for _ in range(n - 1): u, v = map(int, input...
{ "input": [ "1\n3\n1 2\n2 3\n1\n1\n1\n2\n2\n1\n", "2\n6\n1 2\n1 3\n1 4\n4 5\n4 6\n4\n1 3 4 5\n3\n3 5 2\n3\n6\n1 2\n1 3\n1 4\n4 5\n4 6\n3\n1 2 3\n3\n4 1 6\n5\n" ], "output": [ "B 2\nA 1\nC -1\n", "B 2\nC 3\nB 1\nA 1\nC -1\n" ] }
122
11
Hasan loves playing games and has recently discovered a game called TopScore. In this soccer-like game there are p players doing penalty shoot-outs. Winner is the one who scores the most. In case of ties, one of the top-scorers will be declared as the winner randomly with equal probability. They have just finished the...
base=998244353; def power(x, y): if(y==0): return 1 t=power(x, y//2) t=(t*t)%base if(y%2): t=(t*x)%base return t; def inverse(x): return power(x, base-2) f=[1] iv=[1] for i in range(1, 5555): f.append((f[i-1]*i)%base) iv.append(inverse(f[i])) def C(n, k): return (f[n]...
{ "input": [ "10 30 10\n", "2 6 3\n", "5 20 11\n" ], "output": [ "85932500\n", "124780545\n", "1\n" ] }
123
8
Polycarp has an array a consisting of n integers. He wants to play a game with this array. The game consists of several moves. On the first move he chooses any element and deletes it (after the first move the array contains n-1 elements). For each of the next moves he chooses any element with the only restriction: its...
def calc(a, b): return sum(a) + sum(b[-(len(a) + 1):]) _ = int(input()) numbers = list(map(int, input().split())) odds = sorted(x for x in numbers if x % 2 == 1) evens = sorted(x for x in numbers if x % 2 != 1) deleted = calc(odds, evens) if len(odds) < len(evens) else calc(evens, odds) print(sum(numbers) - del...
{ "input": [ "2\n1000000 1000000\n", "6\n5 1 2 4 6 3\n", "5\n1 5 7 8 2\n" ], "output": [ "1000000\n", "0\n", "0\n" ] }
124
7
You are given a huge decimal number consisting of n digits. It is guaranteed that this number has no leading zeros. Each digit of this number is either 0 or 1. You may perform several (possibly zero) operations with this number. During each operation you are allowed to change any digit of your number; you may change 0...
def f(l1,l2): n,x,y = l1 l2.reverse() l2[y] = [1,0][l2[y]] #1->0,0->1 return sum(l2[:x]) l1 = list(map(int,input().split())) l2 = list(map(int,list(input()))) print(f(l1,l2))
{ "input": [ "11 5 2\n11010100101\n", "11 5 1\n11010100101\n" ], "output": [ "1\n", "3\n" ] }
125
9
You have a string s — a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands: * 'W' — move one cell up; * 'S' — move one cell down; * 'A' — move one cell left; * 'D' — move one cell right. Let Grid(s) be the grid of minimum possibl...
def main(): h, v = hv = ([0], [0]) f = {'W': (v, -1), 'S': (v, 1), 'A': (h, -1), 'D': (h, 1)}.get for _ in range(int(input())): del h[1:], v[1:] for l, d in map(f, input()): l.append(l[-1] + d) x = y = 1 for l in hv: lh, a, n = (min(l), max(l)), 200001...
{ "input": [ "3\nDSAWWAW\nD\nWA\n" ], "output": [ "8\n2\n4\n" ] }
126
9
The football season has just ended in Berland. According to the rules of Berland football, each match is played between two teams. The result of each match is either a draw, or a victory of one of the playing teams. If a team wins the match, it gets w points, and the opposing team gets 0 points. If the game results in ...
def exgcd(a,b): if(b==0): return 1,0,a x,y,gg=exgcd(b,a%b) return y,x-a//b*y,gg n,p,w,d=map(int,input().split()) x,y,gg=exgcd(w,d) if(p%gg!=0): print(-1) else: x=x*p//gg y=y*p//gg tmp=(y//(w//gg)) y=y-tmp*(w//gg) x=x+tmp*(d//gg) if(x+y>n or x<0): print(-1) else: print("{} {} {}".format(x,y,n-x-y)) ...
{ "input": [ "30 60 3 1\n", "20 0 15 5\n", "10 51 5 4\n" ], "output": [ "20 0 10\n", "0 0 20\n", "-1\n" ] }
127
7
So the Beautiful Regional Contest (BeRC) has come to an end! n students took part in the contest. The final standings are already known: the participant in the i-th place solved p_i problems. Since the participants are primarily sorted by the number of solved problems, then p_1 ≥ p_2 ≥ ... ≥ p_n. Help the jury distrib...
from sys import stdin def rl(): return [int(w) for w in stdin.readline().split()] k, = rl() for _ in range(k): n, = rl() p = rl() g = 1 while g < n and p[g-1] == p[g]: g += 1 s = g + 1 while g + s < n and p[g+s-1] == p[g+s]: s += 1 a = n//2 while a > 0 and p[a...
{ "input": [ "5\n12\n5 4 4 3 2 2 1 1 1 1 1 1\n4\n4 3 2 1\n1\n1000000\n20\n20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1\n32\n64 64 63 58 58 58 58 58 37 37 37 37 34 34 28 28 28 28 28 28 24 24 19 17 17 17 17 16 16 16 16 11\n" ], "output": [ "1 2 3\n0 0 0\n0 0 0\n1 2 7\n2 6 6\n" ] }
128
9
Today, Osama gave Fadi an integer X, and Fadi was wondering about the minimum possible value of max(a, b) such that LCM(a, b) equals X. Both a and b should be positive integers. LCM(a, b) is the smallest positive integer that is divisible by both a and b. For example, LCM(6, 8) = 24, LCM(4, 12) = 12, LCM(2, 3) = 6. O...
from math import gcd def nok(a,b): return a*b//gcd(a,b) a=int(input()) i=1 while i**2<=a: if a%i==0 and nok(i,a//i)==a: b=i i+=1 print(b,a//b)
{ "input": [ "1\n", "4\n", "6\n", "2\n" ], "output": [ "1 1\n", "1 4\n", "2 3\n", "1 2\n" ] }
129
11
Gildong 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 he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wan...
n = int(input()) g = [[] for _ in range(n)] for i in range(n - 1): u, v = map(int, input().split()) g[u - 1].append(v - 1) g[v - 1].append(u - 1) logn = 19 st = [0] * n dep = [-1] * n par = [[0] * n for _ in range(logn + 1)] st[0], cur = 0, 1 dep[0] = 0 while cur > 0: x = st[cur - 1] cur = cur - ...
{ "input": [ "5\n1 2\n2 3\n3 4\n4 5\n5\n1 3 1 2 2\n1 4 1 3 2\n1 4 1 3 3\n4 2 3 3 9\n5 2 3 3 9\n" ], "output": [ "YES\nYES\nNO\nYES\nNO\n" ] }
130
12
You are given the array a consisting of n elements and the integer k ≤ n. You want to obtain at least k equal elements in the array a. In one move, you can make one of the following two operations: * Take one of the minimum elements of the array and increase its value by one (more formally, if the minimum value of ...
def main(): (n, m), d = map(int, input().split()), {} for i in map(int, input().split()): t = 0 while i: d.setdefault(i, [1000000000]).append(t) i >>= 1 t += 1 print(min(sum(sorted(v)[:m]) for v in d.values())) if __name__ == '__main__': main()
{ "input": [ "6 5\n1 2 2 4 2 3\n", "7 5\n3 3 2 1 1 1 3\n" ], "output": [ "4\n", "2\n" ] }
131
10
Lee tried so hard to make a good div.2 D problem to balance his recent contest, but it still doesn't feel good at all. Lee invented it so tediously slow that he managed to develop a phobia about div.2 D problem setting instead. And now he is hiding behind the bushes... Let's define a Rooted Dead Bush (RDB) of level n ...
def draw(n): MOD = 10 ** 9 + 7 INV = 47619048 ADD = [6, -30, -18] def fpow(x, n): r = 1 while n > 1: if n & 1: r = r * x % MOD x = x * x % MOD n >>= 1 return x * r % MOD return ((fpow(2, n+3)+14*(2*(n&1)...
{ "input": [ "7\n1\n2\n3\n4\n5\n100\n2000000\n" ], "output": [ "0\n0\n4\n4\n12\n990998587\n804665184\n" ] }
132
9
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). Consider a permutation p of length ...
def fact(x): ans = 1 for i in range(1, x+1): ans = (ans*i) % (10**9+7) return ans n = int(input()) print((fact(n)-2**(n-1)) % (10**9+7))
{ "input": [ "4\n", "583291\n" ], "output": [ "16\n", "135712853\n" ] }
133
12
Consider an infinite triangle made up of layers. Let's number the layers, starting from one, from the top of the triangle (from top to bottom). The k-th layer of the triangle contains k points, numbered from left to right. Each point of an infinite triangle is described by a pair of numbers (r, c) (1 ≤ c ≤ r), where r ...
def helper(a, b): if a == b: return 0 x0, y0 = a; x1, y1 = b if (x0+y0) % 2 == 0: x0 += 1 y0 += x1-x0 if y1 > y0: return x1-x0+1 elif y1 == y0: return 0 else: return (y0-y1+1) // 2 for i in range(int(input())):n = int(input());r = list(map(int,input().sp...
{ "input": [ "4\n3\n1 4 2\n1 3 1\n2\n2 4\n2 3\n2\n1 1000000000\n1 1000000000\n4\n3 10 5 8\n2 5 2 4\n" ], "output": [ "\n0\n1\n999999999\n2\n" ] }
134
8
One day Polycarpus stopped by a supermarket on his way home. It turns out that the supermarket is having a special offer for stools. The offer is as follows: if a customer's shopping cart contains at least one stool, the customer gets a 50% discount on the cheapest item in the cart (that is, it becomes two times cheape...
import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.wri...
{ "input": [ "3 2\n2 1\n3 2\n3 1\n", "4 3\n4 1\n1 2\n2 2\n3 2\n" ], "output": [ "5.5\n1 3 \n2 1 2 \n", "8.0\n1 1 \n1 2 \n2 3 4 \n" ] }
135
10
Everything got unclear to us in a far away constellation Tau Ceti. Specifically, the Taucetians choose names to their children in a very peculiar manner. Two young parents abac and bbad think what name to give to their first-born child. They decided that the name will be the permutation of letters of string s. To keep...
def findmin(lcopy, toexceed): toex = ord(toexceed) - 97 for each in lcopy[(toex+1):]: if each > 0: return True return False def arrange(lcopy, toexceed = None): if toexceed is None: ans = "" for i in range(26): ans += chr(i+97)*lcopy[i] return ans...
{ "input": [ "abc\ndefg\n", "czaaab\nabcdef\n", "aad\naac\n", "abad\nbob\n" ], "output": [ "-1\n", "abczaa\n", "aad\n", "daab\n" ] }
136
8
Little Petya likes arrays of integers a lot. Recently his mother has presented him one such array consisting of n elements. Petya is now wondering whether he can swap any two distinct integers in the array so that the array got unsorted. Please note that Petya can not swap equal integers even if they are in distinct po...
def solve(arr): if len(arr) <= 2 or len(set(arr)) == 1: return [-1] else: for i in range(len(arr)): for j in range(i+1, len(arr)): if arr[i] != arr[j]: arr[i], arr[j] = arr[j], arr[i] if arr != sorted(arr) and arr != list(revers...
{ "input": [ "3\n1 1 1\n", "1\n1\n", "2\n1 2\n", "4\n1 2 3 4\n" ], "output": [ "-1\n", "-1\n", "-1\n", "1 2\n" ] }
137
7
One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number ...
import math def I(): return(list(map(int,input().split()))) n=int(input()) a=I() sa=sum(a) ans=max(max(a),math.ceil(sa/(n-1))) print(ans)
{ "input": [ "3\n3 2 2\n", "4\n2 2 2 2\n" ], "output": [ "4\n", "3\n" ] }
138
8
Two little greedy bears have found two pieces of cheese in the forest of weight a and b grams, correspondingly. The bears are so greedy that they are ready to fight for the larger piece. That's where the fox comes in and starts the dialog: "Little bears, wait a little, I want to make your pieces equal" "Come off it fox...
import math a, b = map(int, input().split()) c = math.gcd(a, b) a //= c b //= c ans = 0 def d(x, t): global ans while(x > 1 and x % t == 0): x //= t ans += 1 return x for i in [2, 3, 5]: a = d(a, i) b = d(b, i) print([-1, ans][a == 1 and b == 1])
{ "input": [ "15 20\n", "14 8\n", "6 6\n" ], "output": [ "3\n", "-1\n", "0\n" ] }
139
9
Artem has an array of n positive integers. Artem decided to play with it. The game consists of n moves. Each move goes like this. Artem chooses some element of the array and removes it. For that, he gets min(a, b) points, where a and b are numbers that were adjacent with the removed number. If the number doesn't have a...
def maxScore(list): score=0 stack=[] stack.append(list[0]) for i in range(1,len(list)): while(len(stack)>1 and stack[-1]<=min(list[i],stack[-2])): score=score+min(list[i],stack[-2]) stack.pop() stack.append(list[i]) for i in range(1,len(stack)-1): sco...
{ "input": [ "5\n1 2 3 4 5\n", "5\n1 100 101 100 1\n", "5\n3 1 5 2 6\n" ], "output": [ "6", "102", "11" ] }
140
9
A monster is attacking the Cyberland! Master Yang, a braver, is going to beat the monster. Yang and the monster each have 3 attributes: hitpoints (HP), offensive power (ATK) and defensive power (DEF). During the battle, every second the monster's HP decrease by max(0, ATKY - DEFM), while Yang's HP decreases by max(0,...
from math import ceil hy, ay, dy = map(int, input().split()) hm, am, dm = map(int, input().split()) hp, ap, dp = map(int, input().split()) def time(ay, hm, dm): return float('inf') if ay <= dm else ceil(hm / (ay - dm)) def health_need(t, dy, am): return 0 if dy >= am else t * (am - dy) + 1 min_p = float(...
{ "input": [ "1 2 1\n1 100 1\n1 100 100\n", "100 100 100\n1 1 1\n1 1 1\n" ], "output": [ "99", "0" ] }
141
8
Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0. There are also n cards, each card has 2 attributes: length li and cost ci. If she pays ci dollars then she can apply i-th card. After app...
def main(): input() acc = {0: 0} for p, c in zip(list(map(int, input().split())), list(map(int, input().split()))): adds = [] for b, u in acc.items(): a = p while b: a, b = b, a % b adds.append((a, u + c)) for a,...
{ "input": [ "5\n10 20 30 40 50\n1 1 1 1 1\n", "8\n4264 4921 6321 6984 2316 8432 6120 1026\n4264 4921 6321 6984 2316 8432 6120 1026\n", "3\n100 99 9900\n1 1 1\n", "7\n15015 10010 6006 4290 2730 2310 1\n1 1 1 1 1 1 10\n" ], "output": [ "-1", "7237\n", "2\n", "6\n" ] }
142
10
Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings a and b of equal length are called equivalent in one of the two cases: 1. They are equal. 2. If we split string a into two halves of the same size a1 and a2, and string b into two halves of the same size b1 and b2...
def f(s): if(len(s) % 2 != 0): return s return sorted([f(s[:len(s)//2]), f(s[len(s)//2 :])]) if(f(input()) == f(input())): print("YES") else: print("NO")
{ "input": [ "aaba\nabaa\n", "aabb\nabab\n" ], "output": [ "YES\n", "NO\n" ] }
143
12
In the game Lizard Era: Beginning the protagonist will travel with three companions: Lynn, Meliana and Worrigan. Overall the game has n mandatory quests. To perform each of them, you need to take exactly two companions. The attitude of each of the companions to the hero is an integer. Initially, the attitude of each o...
#!/usr/bin/env python3 n = int(input()) a = [0] * n b = [0] * n c = [0] * n for i in range(n): a[i], b[i], c[i] = map(int, input().split()) middle = { } stack = [ ] result = (-1e10, ()) phase = 1 def search(pos, l, m, w): global result if (pos == n >> 1) if phase == 1 else (pos < n >> 1): if phas...
{ "input": [ "7\n0 8 9\n5 9 -2\n6 -8 -7\n9 4 5\n-4 -9 9\n-4 5 2\n-6 8 -7\n", "2\n1 0 0\n1 1 0\n", "3\n1 0 0\n0 1 0\n0 0 1\n" ], "output": [ "LM\nMW\nLM\nLW\nMW\nLM\nLW\n", "Impossible\n", "LM\nLM\nLW\n" ] }
144
8
Emily's birthday is next week and Jack has decided to buy a present for her. He knows she loves books so he goes to the local bookshop, where there are n books on sale from one of m genres. In the bookshop, Jack decides to buy two books of different genres. Based on the genre of books on sale in the shop, find the nu...
def intline(): return [int(i) for i in input().split()] n, m = intline() l = [0] * m for i in intline(): l[i-1] += 1 total = sum(l[i] * sum(l[i+1:]) for i in range(m)) print(total)
{ "input": [ "7 4\n4 2 3 1 2 4 3\n", "4 3\n2 1 3 1\n" ], "output": [ "18\n", "5\n" ] }
145
7
The HR manager was disappointed again. The last applicant failed the interview the same way as 24 previous ones. "Do I give such a hard task?" — the HR manager thought. "Just raise number 5 to the power of n and get last two digits of the number. Yes, of course, n can be rather big, and one cannot find the power using ...
def main(): print(25) main()
{ "input": [ "2\n" ], "output": [ "25\n" ] }
146
11
You are given a complete undirected graph. For each pair of vertices you are given the length of the edge that connects them. Find the shortest paths between each pair of vertices in the graph and return the length of the longest of them. Input The first line of the input contains a single integer N (3 ≤ N ≤ 10). Th...
from itertools import product def relax(D, t): k, i, j = t D[i][j] = min(D[i][j], D[i][k] + D[k][j]) N = int(input()) D = list(map(lambda i:list(map(int, input().split())), range(N))) list(map(lambda t: relax(D, t), product(range(N), range(N), range(N)))) print(max(map(max, D)))
{ "input": [ "3\n0 1 1\n1 0 4\n1 4 0\n", "4\n0 1 2 3\n1 0 4 5\n2 4 0 6\n3 5 6 0\n" ], "output": [ "2", "5" ] }
147
11
You are given a functional graph. It is a directed graph, in which from each vertex goes exactly one arc. The vertices are numerated from 0 to n - 1. Graph is given as the array f0, f1, ..., fn - 1, where fi — the number of vertex to which goes the only arc from the vertex i. Besides you are given array with weights o...
g = {} def push(u, v, w): g[u] = [v, w] n, pos = map(int, input().split()) V = list(map(int, input().split())) W = list(map(int, input().split())) for _ in range(n): push(_, V[_], W[_]) max_log = 35 next_n = [[-1] * n for _ in range(max_log)] next_m = [[float('inf')] * n for _ in range(max_log)] next_s...
{ "input": [ "5 3\n1 2 3 4 0\n4 1 2 14 3\n", "7 3\n1 2 3 4 3 2 6\n6 3 1 4 2 2 3\n", "4 4\n0 1 2 3\n0 1 2 3\n" ], "output": [ " 7 1\n ...
148
9
Nadeko's birthday is approaching! As she decorated the room for the party, a long garland of Dianthus-shaped paper pieces was placed on a prominent part of the wall. Brother Koyomi will like it! Still unsatisfied with the garland, Nadeko decided to polish it again. The garland has n pieces numbered from 1 to n from le...
import string import bisect import sys def main(): lines = sys.stdin.readlines() n = int(lines[0]) s = lines[1] vals = {} for c in string.ascii_lowercase: a = [i for i, ch in enumerate(s) if ch == c] m = len(a) b = [0] for length in range(1, m + 1): best = n for i in range(m - le...
{ "input": [ "15\nyamatonadeshiko\n10\n1 a\n2 a\n3 a\n4 a\n5 a\n1 b\n2 b\n3 b\n4 b\n5 b\n", "6\nkoyomi\n3\n1 o\n4 o\n4 m\n", "10\naaaaaaaaaa\n2\n10 b\n10 z\n" ], "output": [ "3\n4\n5\n7\n8\n1\n2\n3\n4\n5\n", "3\n6\n5\n", "10\n10\n" ] }
149
9
You already know that Valery's favorite sport is biathlon. Due to your help, he learned to shoot without missing, and his skills are unmatched at the shooting range. But now a smaller task is to be performed, he should learn to complete the path fastest. The track's map is represented by a rectangle n × m in size divi...
import sys from array import array # noqa: F401 from itertools import combinations from collections import deque def input(): return sys.stdin.buffer.readline().decode('utf-8') n, m, k = map(int, input().split()) chars = ( ['}' * (m + 2)] + ['}' + ''.join('{' if c == 'S' else '|' if c == 'T' else c for...
{ "input": [ "5 3 2\nSba\nccc\naac\nccc\nabT\n", "3 4 1\nSxyy\nyxxx\nyyyT\n", "1 3 3\nTyS\n", "1 4 1\nSxyT\n" ], "output": [ "bcccc\n", "xxxx\n", "y\n", "-1\n" ] }
150
10
A substring of some string is called the most frequent, if the number of its occurrences is not less than number of occurrences of any other substring. You are given a set of strings. A string (not necessarily from this set) is called good if all elements of the set are the most frequent substrings of this string. Res...
#https://codeforces.com/problemset/problem/886/D def is_all_used(used): for val in used.values(): if val != True: return False return True def is_circle(d, pre): used = {x:False for x in d} pre_none = [x for x in used if x not in pre] s_arr = [] for x in pre_...
{ "input": [ "3\nkek\npreceq\ncheburek\n", "4\nmail\nai\nlru\ncf\n" ], "output": [ "NO\n", "cfmailru\n" ] }
151
10
You are given a set of points on a straight line. Each point has a color assigned to it. For point a, its neighbors are the points which don't have any other points between them and a. Each point has at most two neighbors - one from the left and one from the right. You perform a sequence of operations on this set of p...
# https://codeforces.com/problemset/problem/909/D def process(a): assert len(a) >= 2 n = len(a) min_ = float('inf') for i, [cnt, c] in enumerate(a): if i == 0 or i == n-1: min_ = min(min_, cnt) else: min_ = min(min_, (cnt+1) //2) b = [] f...
{ "input": [ "aabb\n", "aabcaa\n" ], "output": [ "2\n", "1\n" ] }
152
7
Two friends are on the coordinate axis Ox in points with integer coordinates. One of them is in the point x1 = a, another one is in the point x2 = b. Each of the friends can move by one along the line in any direction unlimited number of times. When a friend moves, the tiredness of a friend changes according to the f...
a=int(input()) b=int(input()) c=(a+b)//2 def f(x): x=abs(x) return x*(x+1)//2 print(f(c-a)+f(b-c))
{ "input": [ "3\n4\n", "5\n10\n", "101\n99\n" ], "output": [ "1", "9", "2" ] }
153
7
You are given a chessboard of size 1 × n. It is guaranteed that n is even. The chessboard is painted like this: "BWBW...BW". Some cells of the board are occupied by the chess pieces. Each cell contains no more than one chess piece. It is known that the total number of pieces equals to <image>. In one step you can mov...
def calc(num): ans=0 for i in range(len(l)): ans+=(abs((l[i]-1)-(2*i+num))) return ans n=int(input()) l=list(map(int,input().split())) l.sort() print (min(calc(0),calc(1)))
{ "input": [ "10\n1 2 3 4 5\n", "6\n1 2 6\n" ], "output": [ "10\n", "2\n" ] }
154
10
Polycarp has n coins, the value of the i-th coin is a_i. It is guaranteed that all the values are integer powers of 2 (i.e. a_i = 2^d for some non-negative integer number d). Polycarp wants to know answers on q queries. The j-th query is described as integer number b_j. The answer to the query is the minimum number of...
import sys input = sys.stdin.readline out = sys.stdout def cbits(x): i=0 while x: x>>=1 i+=1 return i bits=[0]*31 n,q=map(int,input().split()) a=map(int,input().split()) for b in a: c=cbits(b)-1 bits[c]+=1 for i in range(q): ans=0 x=int(input()) num=cbits(x) for j in range(num,-1,-1): p=1<<j c=x//p ...
{ "input": [ "5 4\n2 4 8 2 4\n8\n5\n14\n10\n" ], "output": [ "1\n-1\n3\n2\n" ] }
155
11
You are given a square board, consisting of n rows and n columns. Each tile in it should be colored either white or black. Let's call some coloring beautiful if each pair of adjacent rows are either the same or different in every position. The same condition should be held for the columns as well. Let's call some col...
def norm(x): return (x % 998244353 + 998244353) % 998244353 n, k = map(int, input().split()) dp1 = [0] dp2 = [0] for i in range(n): l = [1] cur = 0 for j in range(n + 1): cur += l[j] if(j > i): cur -= l[j - i - 1] cur = norm(cur) l.append(cur) dp1.appen...
{ "input": [ "2 3\n", "1 1\n", "49 1808\n" ], "output": [ "6\n", "0\n", "359087121\n" ] }
156
11
Grigory has n magic stones, conveniently numbered from 1 to n. The charge of the i-th stone is equal to c_i. Sometimes Grigory gets bored and selects some inner stone (that is, some stone with index i, where 2 ≤ i ≤ n - 1), and after that synchronizes it with neighboring stones. After that, the chosen stone loses its ...
def mp(): return map(int, input().split()) n = int(input()) c = list(mp()) t = list(mp()) a = [abs(c[i] - c[i + 1]) for i in range(n - 1)] b = [abs(t[i] - t[i + 1]) for i in range(n - 1)] if sorted(a) == sorted(b) and c[0] == t[0]: print('Yes') else: print('No')
{ "input": [ "4\n7 2 4 12\n7 15 10 12\n", "3\n4 4 4\n1 2 3\n" ], "output": [ "Yes\n", "No\n" ] }
157
8
You have a string s of length n consisting of only characters > and <. You may do some operations with this string, for each operation you have to choose some character that still remains in the string. If you choose a character >, the character that comes right after it is deleted (if the character you chose was the l...
def cnt(s, i, j): if s[i]=='>' or s[j]=='<': return 0 else: return 1+cnt(s, i+1, j-1) T = int(input()) for i in range(T): N = int(input()) s = input() print(cnt(s, 0, N-1))
{ "input": [ "3\n2\n&lt;&gt;\n3\n&gt;&lt;&lt;\n1\n&gt;\n" ], "output": [ "0\n0\n0\n" ] }
158
11
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...
import sys input = sys.stdin.readline def main(): tes = int(input()) for testcase in [0]*tes: n,m = map(int,input().split()) new = [True]*(3*n) res = [] for i in range(1,m+1): u,v = map(int,input().split()) if new[u-1] and new[v-1]: if le...
{ "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\n" ] }
159
10
There were n types of swords in the theater basement which had been used during the plays. Moreover there were exactly x swords of each type. y people have broken into the theater basement and each of them has taken exactly z swords of some single type. Note that different people might have taken different types of swo...
def gcd(a:int,b:int) -> int: return a if b==0 else gcd(b,a%b) n=int(input()) a=list(map(int,input().split())) m=max(a) g=0 s=0 for x in a: s+=m-x g=gcd(g,m-x) print(s//g,g)
{ "input": [ "2\n2 9\n", "3\n3 12 6\n", "7\n2 1000000000 4 6 8 4 2\n", "6\n13 52 0 13 26 52\n" ], "output": [ "1 7\n", "5 3\n", "2999999987 2\n", "12 13\n" ] }
160
8
Your friend Jeff Zebos has been trying to run his new online company, but it's not going very well. He's not getting a lot of sales on his website which he decided to call Azamon. His big problem, you think, is that he's not ranking high enough on the search engines. If only he could rename his products to have better ...
def solve(s, c): q, p = list(s), sorted(s) for i in range(len(s)): if s[i] != p[i]: j = s.rindex(p[i]) q[i], q[j] = q[j], q[i] break q = ''.join(q) return q if q < c else '---' for T in range(int(input())): print(solve(*input().split()))
{ "input": [ "3\nAZAMON APPLE\nAZAMON AAAAAAAAAAALIBABA\nAPPLE BANANA\n" ], "output": [ "AAZMON\n---\nAEPLP\n" ] }
161
8
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array a of n non-negative integers. Dark created that array 1000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high...
def mi(): return map(int, input().split()) import math for _ in range(int(input())): n = int(input()) a = list(mi()) s = 0 ss=0 for i in a: if i!=-1: s+=i ss+=1 if ss==0: print (0,1) continue s,ss=0,0 cc = [] for i in range(n): if a[i]==-1: if i-1>=0 and a[i-1]!=-1: cc+=[a[i-1]] ss+=1...
{ "input": [ "7\n5\n-1 10 -1 12 -1\n5\n-1 40 35 -1 35\n6\n-1 -1 9 -1 3 -1\n2\n-1 -1\n2\n0 -1\n4\n1 -1 3 -1\n7\n1 -1 7 5 2 -1 5\n" ], "output": [ "1 11\n5 37\n3 6\n0 0\n0 0\n1 2\n3 4\n" ] }
162
8
Ehab has an array a of length n. He has just enough free time to make a new array consisting of n copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence? A sequence a is a subsequence of an array b if a can be obtained from b by deletion of several (pos...
def copy(): a = set(input().split()) return len(a) for i in range(int(input())): input() print(copy())
{ "input": [ "2\n3\n3 2 1\n6\n3 1 4 1 5 9\n" ], "output": [ "3\n5\n" ] }
163
7
Hilbert's Hotel is a very unusual hotel since the number of rooms is infinite! In fact, there is exactly one room for every integer, including zero and negative integers. Even stranger, the hotel is currently at full capacity, meaning there is exactly one guest in every room. The hotel's manager, David Hilbert himself,...
def sol(): x=int(input()) s=list(map(int,input().split())) st=set() for n in range(x): u=(s[n]+n)%x st.add(u) print('YES' if len(list(st))==x else 'NO') for n in range(int(input())): sol()
{ "input": [ "6\n1\n14\n2\n1 -1\n4\n5 5 5 1\n3\n3 2 1\n2\n0 1\n5\n-239 -2 -100 -3 -11\n" ], "output": [ "YES\nYES\nYES\nNO\nNO\nYES\n" ] }
164
7
Polycarp plays a well-known computer game (we won't mention its name). In this game, he can craft tools of two types — shovels and swords. To craft a shovel, Polycarp spends two sticks and one diamond; to craft a sword, Polycarp spends two diamonds and one stick. Each tool can be sold for exactly one emerald. How many...
def solve(): a,b=map(int,input().split()) print(min(a,b,(a+b)//3)) TC=int(input()) for _ in range(TC): solve()
{ "input": [ "4\n4 4\n1000000000 0\n7 15\n8 7\n" ], "output": [ "2\n0\n7\n5\n" ] }
165
7
You are given three sequences: a_1, a_2, …, a_n; b_1, b_2, …, b_n; c_1, c_2, …, c_n. For each i, a_i ≠ b_i, a_i ≠ c_i, b_i ≠ c_i. Find a sequence p_1, p_2, …, p_n, that satisfy the following conditions: * p_i ∈ \\{a_i, b_i, c_i\} * p_i ≠ p_{(i mod n) + 1}. In other words, for each element, you need to choose ...
def solve(a, b, c): first = a[0] print(first, end=" ") prev = first for i in range(1, len(a)): for x in [a[i], b[i], c[i]]: if x != prev and x != first: prev = x print(x, end=" ") break print() for _ in range(int(input())): n ...
{ "input": [ "5\n3\n1 1 1\n2 2 2\n3 3 3\n4\n1 2 1 2\n2 1 2 1\n3 4 3 4\n7\n1 3 3 1 1 1 1\n2 4 4 3 2 2 4\n4 2 2 2 4 4 2\n3\n1 2 1\n2 3 3\n3 1 2\n10\n1 1 1 2 2 2 3 3 3 1\n2 2 2 3 3 3 1 1 1 2\n3 3 3 1 1 1 2 2 2 3\n" ], "output": [ "1 2 3\n1 2 1 2\n1 3 4 1 2 1 4\n1 2 3\n1 2 1 2 3 2 3 1 3 2\n" ] }
166
10
To improve the boomerang throwing skills of the animals, Zookeeper has set up an n × n grid with some targets, where each row and each column has at most 2 targets each. The rows are numbered from 1 to n from top to bottom, and the columns are numbered from 1 to n from left to right. For each column, Zookeeper will t...
import sys input = sys.stdin.readline def NO(): print(-1) exit(0) N = int(input()) A = list(map(int, input().split())) T = [] ones = [] others = [] for i in range(N-1, -1, -1): if A[i] == 0: continue if A[i] == 1: T.append((i, i)) ones.append(i) elif A[i] == 2: if not ones: NO() one = ones.pop() T...
{ "input": [ "1\n0\n", "6\n2 0 3 0 1 1\n", "6\n3 2 2 2 1 1\n" ], "output": [ "0\n\n", "5\n6 6\n5 5\n4 3\n4 5\n6 1\n", "-1\n" ] }
167
10
Utkarsh is forced to play yet another one of Ashish's games. The game progresses turn by turn and as usual, Ashish moves first. Consider the 2D plane. There is a token which is initially at (0,0). In one move a player must increase either the x coordinate or the y coordinate of the token by exactly k. In doing so, the...
def solve(k,d): n=int(((d**2)/(2*k*k))**(1/2)) if (n*n*k*k+(n+1)*(n+1)*k*k)<=d**2: return "Ashish" else: return "Utkarsh" n=int(input()) for _ in range(n): d,k=map(int,input().split()) print(solve(k,d))
{ "input": [ "5\n2 1\n5 2\n10 3\n25 4\n15441 33\n" ], "output": [ "\nUtkarsh\nAshish\nUtkarsh\nUtkarsh\nAshish\n" ] }
168
10
Polycarp often uses his smartphone. He has already installed n applications on it. Application with number i takes up a_i units of memory. Polycarp wants to free at least m units of memory (by removing some applications). Of course, some applications are more important to Polycarp than others. He came up with the fol...
from bisect import bisect_left def solve(): n, m = map(int, input().split()) a = list(map(int, input().split())) i = 0 q = [None, [], []] for v in map(int, input().split()): q[v].append(a[i]) i += 1 aa = q[1] bb = q[2] aa.sort(reverse=True) bb.sort(reverse=True) cc = [0]*(len(bb)+1) for i in range(len(bb...
{ "input": [ "5\n5 7\n5 3 2 1 4\n2 1 1 2 1\n1 3\n2\n1\n5 10\n2 3 2 3 2\n1 2 1 2 1\n4 10\n5 1 3 4\n1 2 1 2\n4 5\n3 2 1 2\n2 1 2 1\n" ], "output": [ "\n2\n-1\n6\n4\n3\n" ] }
169
8
Vasya is a CEO of a big construction company. And as any other big boss he has a spacious, richly furnished office with two crystal chandeliers. To stay motivated Vasya needs the color of light at his office to change every day. That's why he ordered both chandeliers that can change its color cyclically. For example: r...
import sys, os if os.environ['USERNAME']=='kissz': inp=open('in5.txt','r').readline def debug(*args): print(*args,file=sys.stderr) else: inp=sys.stdin.readline def debug(*args): pass # SCRIPT STARTS HERE def extgcd(a,b): if b==0: x=1 y=0 return a, x, y ...
{ "input": [ "3 8 41\n1 3 2\n1 6 4 3 5 7 2 8\n", "1 2 31\n1\n1 2\n", "4 2 4\n4 2 3 1\n2 1\n" ], "output": [ "\n47\n", "\n62\n", "\n5\n" ] }
170
10
There are n armchairs, numbered from 1 to n from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than n/2. For some reason, you would like to tell people to move from their armchairs to some other ones. If the i-th ...
from sys import stdin input=stdin.readline def answer(): dp=[[1e9 for i in range(m + 1)] for j in range(n + 1)] for i in range(m + 1):dp[0][i]=0 for i in range(1,n + 1): for j in range(1,m + 1): dp[i][j]=dp[i][j-1] if(dp[i-1][j-1] == 1e9):co...
{ "input": [ "6\n1 1 1 0 0 0\n", "5\n0 0 0 0 0\n", "7\n1 0 0 1 0 0 1\n" ], "output": [ "\n9\n", "\n0\n", "\n3\n" ] }
171
7
Sherlock Holmes and Dr. Watson played some game on a checkered board n × n in size. During the game they put numbers on the board's squares by some tricky rules we don't know. However, the game is now over and each square of the board contains exactly one number. To understand who has won, they need to count the number...
def main(): l = [list(map(int, input().split())) for _ in range(int(input()))] h = list(map(sum, l)) print(sum(x > y for x in map(sum, zip(*l)) for y in h)) if __name__ == '__main__': main()
{ "input": [ "1\n1\n", "2\n1 2\n3 4\n", "4\n5 7 8 4\n9 5 3 2\n1 6 6 4\n9 5 7 3\n" ], "output": [ "0\n", "2\n", "6\n" ] }
172
7
The Smart Beaver from ABBYY began to develop a new educational game for children. The rules of the game are fairly simple and are described below. The playing field is a sequence of n non-negative integers ai numbered from 1 to n. The goal of the game is to make numbers a1, a2, ..., ak (i.e. some prefix of the sequenc...
n=int(input()) a=list(map(int, input().split(" "))) def check(n): while n>1: n/=2 if n==1: return True else: return False s=0 for j in range(n-1): s+=a[j] for i in range(n-1, -1, -1): if check(i-j): print(s) a[i]+=a[j] break
{ "input": [ "8\n1 2 3 4 5 6 7 8\n", "4\n1 0 1 2\n" ], "output": [ "1\n3\n6\n10\n16\n24\n40\n", "1\n1\n3\n" ] }
173
8
Bob came to a cash & carry store, put n items into his trolley, and went to the checkout counter to pay. Each item is described by its price ci and time ti in seconds that a checkout assistant spends on this item. While the checkout assistant is occupied with some item, Bob can steal some other items from his trolley. ...
def read(): return [int(v) for v in input().split()] def main(): n = read()[0] t, c = [], [] for i in range(n): line = read() t.append(line[0] + 1) c.append(line[1]) MAX = 10 ** 15 dp = [MAX] * (n + 1) dp[0] = 0 for i in range(n): for j in range(n, -1, ...
{ "input": [ "4\n2 10\n0 20\n1 5\n1 3\n", "3\n0 1\n0 10\n0 100\n" ], "output": [ "8", "111" ] }
174
9
You've got an array a, consisting of n integers. The array elements are indexed from 1 to n. Let's determine a two step operation like that: 1. First we build by the array a an array s of partial sums, consisting of n elements. Element number i (1 ≤ i ≤ n) of array s equals <image>. The operation x mod y means that ...
def ncr(n, r, p): # initialize numerator # and denominator num = den = 1 for i in range(r): num = (num * (n - i)) % p den = (den * (i + 1)) % p return (num * pow(den, p - 2, p)) % p p=10**9+7 n,k=map(int,input().split()) b=list(map(int,input().split())) if k==...
{ "input": [ "5 0\n3 14 15 92 6\n", "3 1\n1 2 3\n" ], "output": [ "3 14 15 92 6 ", "1 3 6 " ] }
175
7
One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house. Karlsson's gaze immediately fell on n wooden ...
def main(): n = int(input()) ll = rr = 0 for _ in range(n): l, r = map(int, (input().split())) ll += l rr += r print(sum(min(_, n - _) for _ in (ll, rr))) if __name__ == '__main__': main()
{ "input": [ "5\n0 1\n1 0\n0 1\n1 1\n0 1\n" ], "output": [ "3\n" ] }
176
8
Dima got into number sequences. Now he's got sequence a1, a2, ..., an, consisting of n positive integers. Also, Dima has got a function f(x), which can be defined with the following recurrence: * f(0) = 0; * f(2·x) = f(x); * f(2·x + 1) = f(x) + 1. Dima wonders, how many pairs of indexes (i, j) (1 ≤ i < j ≤...
def f(x): return str(bin(x)).count('1') n = int(input()) a = list(map(int, input().split())) ans = [f(x) for x in a] s = set(ans) counts = {x:ans.count(x) for x in s} ans = 0 for i in counts: ans += (counts[i]*(counts[i]-1))//2 print(ans)
{ "input": [ "3\n1 2 4\n", "3\n5 3 1\n" ], "output": [ "3", "1" ] }
177
8
There are n psychos standing in a line. Each psycho is assigned a unique integer from 1 to n. At each step every psycho who has an id greater than the psycho to his right (if exists) kills his right neighbor in the line. Note that a psycho might kill and get killed at the same step. You're given the initial arrangeme...
from sys import stdin,stdout def main(n, a): ans = 0 top = 0 t = [0 for i in range(n)] f = [0 for i in range(n)] for i in range(n - 1, -1, -1): tt = 0 while top > 0 and a[t[top - 1]] < a[i]: top -= 1 tt = max(tt + 1, f[t[top]]) f[i] = tt t...
{ "input": [ "6\n1 2 3 4 5 6\n", "10\n10 9 7 8 6 5 3 4 2 1\n" ], "output": [ "0\n", "2\n" ] }
178
8
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended u...
def main(): stack = [] for c in input(): if stack and c == stack[-1]: del stack[-1] else: stack.append(c) print(("Yes", "No")[bool(stack)]) if __name__ == '__main__': main()
{ "input": [ "-++-\n", "++\n", "+-\n", "-\n" ], "output": [ "YES\n", "YES\n", "NO\n", "NO\n" ] }
179
9
The blinds are known to consist of opaque horizontal stripes that can be rotated thus regulating the amount of light flowing in the room. There are n blind stripes with the width of 1 in the factory warehouse for blind production. The problem is that all of them are spare details from different orders, that is, they ma...
def get_answer(k): return sum([i // k for i in a]) n, l = map(int, input().split()) a = list(map(int, input().split())) ans = 0 for i in range(l, max(a) + 1): ans = max(ans, get_answer(i) * i) print(ans)
{ "input": [ "5 3\n5 5 7 3 1\n", "4 2\n1 2 3 4\n", "2 3\n1 2\n" ], "output": [ "15\n", "8\n", "0\n" ] }
180
8
A chessboard n × m in size is given. During the zero minute we repaint all the black squares to the 0 color. During the i-th minute we repaint to the i color the initially black squares that have exactly four corner-adjacent squares painted i - 1 (all such squares are repainted simultaneously). This process continues a...
def calculate_sides(n, m): if n == 1: return m // 2 if m % 2 == 0 else m // 2 + 1 if m == 1: return n // 2 if n % 2 == 0 else n // 2 + 1 left, right, top, bottom = 0, 0, 0, 0 top = m // 2 if m % 2 == 0 else m // 2 + 1 bottom = top if n % 2 != 0 else m // 2 n -= 2 m -= 2 ...
{ "input": [ "1 1\n1\n", "3 3\n2\n", "3 3\n1\n" ], "output": [ "1\n", "1\n", "4\n" ] }
181
7
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy. The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The...
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**10 mod = 998244353 dd = [(-1,0),(0,1),(1,0),(0,-1)] ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(): return list(map(int, sys.stdin.readline().sp...
{ "input": [ "4 4\n100 100 100 100\n1 2\n2 3\n2 4\n3 4\n", "4 3\n10 20 30 40\n1 4\n1 2\n2 3\n", "7 10\n40 10 20 10 20 80 40\n1 5\n4 7\n4 5\n5 2\n5 7\n6 4\n1 6\n1 3\n4 3\n1 4\n" ], "output": [ "400\n", "40\n", "160\n" ] }
182
8
You have two friends. You want to present each of them several positive integers. You want to present cnt1 numbers to the first friend and cnt2 numbers to the second friend. Moreover, you want all presented numbers to be distinct, that also means that no number should be presented to both friends. In addition, the fir...
a,b,x,y=map(int,input().split()); l=0 r=10000000000000; res=0; def judge(n,a,b,x,y): return (n - n // (x * y)) >= a + b and (n - n // x >= a) and (n - n // y >= b); while l<=r: m=(l+r)//2; if judge(m,a,b,x,y): r=m-1; res=m; else :l=m+1; print(res);
{ "input": [ "3 1 2 3\n", "1 3 2 3\n" ], "output": [ "5\n", "4\n" ] }
183
8
Amr loves Geometry. One day he came up with a very interesting problem. Amr has a circle of radius r and center in point (x, y). He wants the circle center to be in new position (x', y'). In one step Amr can put a pin to the border of the circle in a certain point, then rotate the circle around that pin by any angle ...
import math def main(): r,x1,y1,x2,y2=map(int,input().split()) d=(int)(((x2-x1)**2)+((y2-y1)**2))**0.5 print(math.ceil(d/(2*r))) main()
{ "input": [ "1 1 1 4 4\n", "2 0 0 0 4\n", "4 5 6 5 6\n" ], "output": [ "3\n", "1\n", "0\n" ] }
184
9
Andrewid the Android is a galaxy-famous detective. He is now investigating the case of vandalism at the exhibition of contemporary art. The main exhibit is a construction of n matryoshka dolls that can be nested one into another. The matryoshka dolls are numbered from 1 to n. A matryoshka with a smaller number can be ...
def main(): ts = input().split() n = int(ts[0]) k = int(ts[1]) ans = 0 b=None for _ in range(k): ts = [int(t) for t in input().split()] ts = ts[1:] i = 0 while i<len(ts) and ts[i]==i+1: i+=1 if i==0: ans += len(ts)-1 else: ...
{ "input": [ "3 2\n2 1 2\n1 3\n", "7 3\n3 1 3 7\n2 2 5\n2 4 6\n" ], "output": [ "1\n", "10\n" ] }
185
7
The GCD table G of size n × n for an array of positive integers a of length n is defined by formula <image> Let us remind you that the greatest common divisor (GCD) of two positive integers x and y is the greatest integer that is divisor of both x and y, it is denoted as <image>. For example, for array a = {4, 3, 6,...
def gcd(a,b): if b==0: return a return gcd(b,a%b) n=int(input()) from collections import Counter l=[int(i) for i in input().split()] g=Counter(l) ans=[] while g: m=max(g) g[m]-=1 for i in ans: g[gcd(m,i)]-=2 ans+=[m] g+=Counter() print(*ans)
{ "input": [ "4\n2 1 2 3 4 3 2 6 1 1 2 2 1 2 3 2\n", "1\n42\n", "2\n1 1 1 1\n" ], "output": [ "6 4 3 2 ", "42 ", "1 1 " ] }
186
7
Kevin Sun has just finished competing in Codeforces Round #334! The round was 120 minutes long and featured five problems with maximum point values of 500, 1000, 1500, 2000, and 2500, respectively. Despite the challenging tasks, Kevin was uncowed and bulldozed through all of them, distinguishing himself from the herd a...
def n(): return list(map(int, input().split())) m, w, h, r, p = n(), n(), n(), 0, [500,1000,1500,2000,2500] for i in range(5): r += max(0.3*p[i], (1-m[i]/250)*p[i] - 50*w[i]) r += h[0] * 100 - h[1] * 50 print(int(r))
{ "input": [ "20 40 60 80 100\n0 1 2 3 4\n1 0\n", "119 119 119 119 119\n0 0 0 0 0\n10 0\n" ], "output": [ "4900\n", "4930\n" ] }
187
10
Andrew and Jerry are playing a game with Harry as the scorekeeper. The game consists of three rounds. In each round, Andrew and Jerry draw randomly without replacement from a jar containing n balls, each labeled with a distinct positive integer. Without looking, they hand their balls to Harry, who awards the point to t...
def main(): n = int(input()) a = list(map(int, input().split())) max_element = max(a) + 1 #print(max_element) diff_freq = [0 for i in range(max_element)] for i in range(n): for j in range(i): diff_freq[abs(a[i] - a[j])] += 1 largest = [0 for i in range(max_element)] ...
{ "input": [ "3\n1 2 10\n", "2\n1 2\n" ], "output": [ "0.0740740741", "0.0000000000" ] }
188
8
Vasya's telephone contains n photos. Photo number 1 is currently opened on the phone. It is allowed to move left and right to the adjacent photo by swiping finger over the screen. If you swipe left from the first photo, you reach photo n. Similarly, by swiping right from the last photo you reach photo 1. It takes a sec...
def main(): n, a, b, t = map(int, input().split()) b += 1 l = [b if char == "w" else 1 for char in input()] t -= sum(l) - a * (n + 2) hi, n2 = n, n * 2 n21 = n2 + 1 lo = res = 0 l *= 2 while lo <= n and hi < n2: t -= l[hi] hi += 1 b = hi - n while lo <...
{ "input": [ "5 2 4 13\nhhwhh\n", "3 1 100 10\nwhw\n", "5 2 4 1000\nhhwhh\n", "4 2 3 10\nwwhw\n" ], "output": [ "4", "0", "5", "2" ] }
189
11
Vasya commutes by train every day. There are n train stations in the city, and at the i-th station it's possible to buy only tickets to stations from i + 1 to ai inclusive. No tickets are sold at the last station. Let ρi, j be the minimum number of tickets one needs to buy in order to get from stations i to station j....
import sys input = sys.stdin.readline def solve(): n = int(input()) a = list(map(int, input().split())) T = [(-1,-1)]*(2*n) for i in range(n-1): T[i+n] = (a[i], i) T[n+n-1] = (n, n-1) for i in range(n-1,-1,-1): T[i] = max(T[2*i], T[2*i+1]) dp = [0]*n res = 0 for i in range(n-2,-1,-1): l = i + n r = a...
{ "input": [ "4\n4 4 4\n", "5\n2 3 5 5\n" ], "output": [ "6\n", "17\n" ] }
190
10
Artsem has a friend Saunders from University of Chicago. Saunders presented him with the following problem. Let [n] denote the set {1, ..., n}. We will also write f: [x] → [y] when a function f is defined in integer points 1, ..., x, and all its values are integers from 1 to y. Now then, you are given a function f: [...
def main(): n = int(input()) ar = [] fi_values = map(int, input().strip().split()) groups = dict() for i, fi in enumerate(fi_values): if fi not in groups: groups[fi] = [] groups[fi].append(i+1) g = [0] * n h = [] for k, v in groups.items(): if k not in v: print(-1) return else: h.append(k)...
{ "input": [ "3\n1 2 3\n", "3\n2 2 2\n", "2\n2 1\n" ], "output": [ "3\n1 2 3 \n1 2 3 ", "1\n1 1 1 \n2 ", "-1" ] }
191
7
Anastasia loves going for a walk in Central Uzhlyandian Park. But she became uninterested in simple walking, so she began to collect Uzhlyandian pebbles. At first, she decided to collect all the pebbles she could find in the park. She has only two pockets. She can put at most k pebbles in each pocket at the same time....
import math n, k = map(int, input().split()) def f(s): f = int(s) return math.ceil(f / k) a = sum(map(f, input().split())) print(math.ceil(a / 2))
{ "input": [ "5 4\n3 1 8 9 7\n", "3 2\n2 3 4\n" ], "output": [ "5\n", "3\n" ] }
192
9
The year of 2012 is coming... According to an ancient choradrican legend in this very year, in 2012, Diablo and his brothers Mephisto and Baal will escape from hell, and innumerable hordes of demons will enslave the human world. But seven brave heroes have already gathered on the top of a mountain Arreat to protect us...
R=range S=str.split I=input L=S('Anka Chapay Cleo Troll Dracul Snowy Hexadecimal') h={} for i in R(7):h[L[i]]=i d=[[]for i in R(9)] for z in '0'*int(I()):a,_,b=S(I());d[h[a]]+=[h[b]] a,b,c=map(int,S(I())) o=[10**9,0] def C(q,w,e,n): if n==7: if not(q and w and e):return p=[a//len(q),b//len(w),c//(le...
{ "input": [ "3\nTroll likes Dracul\nDracul likes Anka\nSnowy likes Hexadecimal\n210 200 180\n", "2\nAnka likes Chapay\nChapay likes Anka\n10000 50 50\n" ], "output": [ "30 3\n", "1950 2\n" ] }
193
7
Two boys decided to compete in text typing on the site "Key races". During the competition, they have to type a text consisting of s characters. The first participant types one character in v1 milliseconds and has ping t1 milliseconds. The second participant types one character in v2 milliseconds and has ping t2 millis...
def read(): return [int(e) for e in input().split()] x=read() a=2*x[3]+x[0]*x[1] b=2*x[4]+x[0]*x[2] if a>b: print("Second") elif a==b: print("Friendship") else: print("First")
{ "input": [ "4 5 3 1 5\n", "5 1 2 1 2\n", "3 3 1 1 1\n" ], "output": [ "Friendship\n", "First\n", "Second\n" ] }
194
8
Programmer Vasya is studying a new programming language &K*. The &K* language resembles the languages of the C family in its syntax. However, it is more powerful, which is why the rules of the actual C-like languages are unapplicable to it. To fully understand the statement, please read the language's description below...
n=int(input()) def Ref(v): stars=0 ands=0 nam="" for item in v: if(item=='*'): stars+=1 elif(item=='&'): ands+=1 else: nam+=item if(nam not in T): return "errtype" x=T[nam] if(x=="errtype"): return str(x) x+=sta...
{ "input": [ "17\ntypedef void* b\ntypedef b* c\ntypeof b\ntypeof c\ntypedef &amp;b b\ntypeof b\ntypeof c\ntypedef &amp;&amp;b* c\ntypeof c\ntypedef &amp;b* c\ntypeof c\ntypedef &amp;void b\ntypeof b\ntypedef b******* c\ntypeof c\ntypedef &amp;&amp;b* c\ntypeof c\n", "5\ntypedef void* ptv\ntypeof ptv\ntypedef...
195
10
Let's denote a function <image> You are given an array a consisting of n integers. You have to calculate the sum of d(ai, aj) over all pairs (i, j) such that 1 ≤ i ≤ j ≤ n. Input The first line contains one integer n (1 ≤ n ≤ 200000) — the number of elements in a. The second line contains n integers a1, a2, ..., ...
n = int(input()) ar = list(map(int, input().split())) rev = ar[::-1] from collections import Counter def d(ar): me = Counter() s = 0 for i in range (n) : s+=(i*ar[i]) s-=(me[ar[i]] + me[ar[i]+1]*ar[i] + me[ar[i]-1]*ar[i]) me[ar[i]]+=1 return s print(d(ar) - d(rev))
{ "input": [ "4\n6 6 5 5\n", "5\n1 2 3 1 3\n", "4\n6 6 4 4\n" ], "output": [ "0", "4", "-8" ] }
196
12
You are running through a rectangular field. This field can be represented as a matrix with 3 rows and m columns. (i, j) denotes a cell belonging to i-th row and j-th column. You start in (2, 1) and have to end your path in (2, m). From the cell (i, j) you may advance to: * (i - 1, j + 1) — only if i > 1, * (i, ...
from operator import itemgetter import sys input = sys.stdin.buffer.readline def _mul(A, B, MOD): C = [[0] * len(B[0]) for i in range(len(A))] for i in range(len(A)): for k in range(len(B)): for j in range(len(B[0])): C[i][j] = (C[i][j] + A[i][k] * B[k][j]) % MOD return...
{ "input": [ "2 5\n1 3 4\n2 2 3\n" ], "output": [ "2\n" ] }
197
11
Hexadecimal likes drawing. She has drawn many graphs already, both directed and not. Recently she has started to work on a still-life «interesting graph and apples». An undirected graph is called interesting, if each of its vertices belongs to one cycle only — a funny ring — and does not belong to any other cycles. A f...
import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') def NO(): print('NO') exit() def YES(edges): edges.sort() print('YES') print(len(edges)) for e in edges: print(e[0] + 1, e[1] + 1) exit() n, m = map(int, input...
{ "input": [ "3 2\n1 2\n2 3\n" ], "output": [ "YES\n1\n1 3\n" ] }
198
7
Natasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the string — concatenation of letters, which correspond to the stages. There are n stages available. The rock...
n,k = map(int,input().split()) def tonny(i) : return (ord(i)-96) a= sorted(input()) a=list(map(tonny,a)) a=sorted(list(set(a))) ans=[a.pop(0)] k-=1 for j in a : if j-ans[-1] >1 and k>0 : k-=1 ans.append(j) if k==0 : break if k!=0 : print(-1) else: print(sum(ans))
{ "input": [ "7 4\nproblem\n", "2 2\nab\n", "5 3\nxyabd\n", "12 1\nabaabbaaabbb\n" ], "output": [ "34\n", "-1\n", "29\n", "1\n" ] }
199
8
Mikhail walks on a Cartesian plane. He starts at the point (0, 0), and in one move he can go to any of eight adjacent points. For example, if Mikhail is currently at the point (0, 0), he can go to any of the following points in one move: * (1, 0); * (1, 1); * (0, 1); * (-1, 1); * (-1, 0); * (-1, -1);...
def solve(x, y, k): mx = max(x, y) if mx > k: return -1 return k-(x-k)%2-(y-k)%2 assert solve(2, 2, 3) == 1 assert solve(4, 3, 7) == 6 assert solve(10,1, 9) == -1 q = int(input()) for i in range(q): print(solve(*map(int, input().split())))
{ "input": [ "3\n2 2 3\n4 3 7\n10 1 9\n" ], "output": [ "1\n6\n-1\n" ] }