index
int64
0
5.16k
difficulty
int64
7
12
question
stringlengths
126
7.12k
solution
stringlengths
30
18.6k
test_cases
dict
700
11
A connected undirected graph is called a vertex cactus, if each vertex of this graph belongs to at most one simple cycle. A simple cycle in a undirected graph is a sequence of distinct vertices v1, v2, ..., vt (t > 2), such that for any i (1 ≀ i < t) exists an edge between vertices vi and vi + 1, and also exists an ed...
from collections import defaultdict import os import sys from io import BytesIO, IOBase from types import GeneratorType from collections import defaultdict BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self...
{ "input": [ "10 11\n1 2\n2 3\n3 4\n1 4\n3 5\n5 6\n8 6\n8 7\n7 6\n7 9\n9 10\n6\n1 2\n3 5\n6 9\n9 2\n9 3\n9 10\n" ], "output": [ "2\n2\n2\n4\n4\n1\n" ] }
701
10
Vasya has found a piece of paper with an array written on it. The array consists of n integers a1, a2, ..., an. Vasya noticed that the following condition holds for the array ai ≀ ai + 1 ≀ 2Β·ai for any positive integer i (i < n). Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will ge...
def invert(s): t = '' for i in s: if(i =='+'): t += '-' else: t += '+' #print(s,t) return t n = int(input()) if(n==1): print('+') exit() a=list(map(int,input().split())) cur = a[-1] s = '+' for i in range(n-2,0,-1): if(cur > 0): cur -= a[i] ...
{ "input": [ "3\n3 3 5\n", "4\n1 2 3 5\n" ], "output": [ "++-\n", "+--+\n" ] }
702
10
A star map in Berland is a checked field n Γ— m squares. In each square there is or there is not a star. The favourite constellation of all Berland's astronomers is the constellation of the Cross. This constellation can be formed by any 5 stars so, that for some integer x (radius of the constellation) the following is t...
import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') n, m, k = map(int, input().split()) a = [tuple(map(lambda c: c == '*', input().rstrip())) for _ in range(n)] cnt = [0] * 400 for i in range(1, n - 1): for j in range(1, m - 1): if not a[...
{ "input": [ "5 6 1\n....*.\n...***\n....*.\n..*...\n.***..\n", "7 7 2\n...*...\n.......\n...*...\n*.***.*\n...*...\n.......\n...*...\n", "5 6 2\n....*.\n...***\n....*.\n..*...\n.***..\n" ], "output": [ "2 5\n1 5\n3 5\n2 4\n2 6\n", "4 4\n1 4\n7 4\n4 1\n4 7\n", "-1\n" ] }
703
8
Jeff has become friends with Furik. Now these two are going to play one quite amusing game. At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjace...
def count(a): n = len(a) cnt = 0 for i in range(n): for j in range(i+1, n): if a[i] > a[j]: cnt+=1 return cnt n = int(input()) p = list(map(int, input().split())) num = count(p) print(num*2 - num%2)
{ "input": [ "5\n3 5 2 4 1\n", "2\n1 2\n" ], "output": [ "13", "0" ] }
704
7
Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it? The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out...
def ic(s): ss=set('AHIMOTUVWXY') m=len(s)//2+1 for c in range(m): if s[c]!=s[-(c+1)] or s[c] not in ss: return 0 return 1 s='YES' if ic(input()) else 'NO' print(s)
{ "input": [ "AHA\n", "Z\n", "XO\n" ], "output": [ "YES\n", "NO\n", "NO\n" ] }
705
11
Peter wrote on the board a strictly increasing sequence of positive integers a1, a2, ..., an. Then Vasil replaced some digits in the numbers of this sequence by question marks. Thus, each question mark corresponds to exactly one lost digit. Restore the the original sequence knowing digits remaining on the board. Inpu...
def solve(s, t, i, l): if i == l: return False if s[i] == "?": if solve(s, t, i + 1, l): s[i] = t[i] return True elif t[i] == "9": return False s[i] = nxt[t[i]] for j in range(i, l): if s[j] == "?": s[j] = "0...
{ "input": [ "3\n?\n18\n1?\n", "2\n??\n?\n", "5\n12224\n12??5\n12226\n?0000\n?00000\n" ], "output": [ "YES\n1\n18\n19\n", "NO\n", "YES\n12224\n12225\n12226\n20000\n100000\n" ] }
706
11
When Darth Vader gets bored, he sits down on the sofa, closes his eyes and thinks of an infinite rooted tree where each node has exactly n sons, at that for each node, the distance between it an its i-th left child equals to di. The Sith Lord loves counting the number of nodes in the tree that are at a distance at most...
# fast io from sys import stdin _data = iter(stdin.read().split('\n')) input = lambda: next(_data) N = 101 MOD = 1000000007 def mul_vec_mat(v, a): c = [0] * N for i in range(N): c[i] = sum(a[j][i] * v[j] % MOD for j in range(N)) % MOD return c def mul_vec_sparse_mat(v, a): c = [0] * N for...
{ "input": [ "3 3\n1 2 3\n" ], "output": [ "8" ] }
707
8
Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything. During an audit, you were surprised to find out that the...
def main(): n = int(input()) a = list(map(int, input().split())) used = [True] * (n + 1) X = {i + 1 for i in range(n)} Y = {i for i in a if i <= n} A = X ^ Y for i in a: if i > n or not used[i]: print(A.pop(), end = ' ') else: used[i] = False ...
{ "input": [ "3\n1 3 2\n", "4\n2 2 3 3\n", "1\n2\n" ], "output": [ "1 3 2 \n", "2 1 3 4 \n", "1 \n" ] }
708
10
Each employee of the "Blake Techologies" company uses a special messaging app "Blake Messenger". All the stuff likes this app and uses it constantly. However, some important futures are missing. For example, many users want to be able to search through the message history. It was already announced that the new feature ...
def ziped(a): p = [] for i in a: x = int(i.split('-')[0]) y = i.split('-')[1] if len(p) > 0 and p[-1][1] == y: p[-1][0] += x else: p.append([x, y]) return p def solve(a, b , c): ans = 0 if len(b) == 1: for token in a: if c(token, b[0]): ans += token[0] - b[0][0] + 1 return ans if len(...
{ "input": [ "6 1\n3-a 6-b 7-a 4-c 8-e 2-a\n3-a\n", "5 5\n1-h 1-e 1-l 1-l 1-o\n1-w 1-o 1-r 1-l 1-d\n", "5 3\n3-a 2-b 4-c 3-a 2-c\n2-a 2-b 1-c\n" ], "output": [ "6\n", "0\n", "1\n" ] }
709
8
Consider 2n rows of the seats in a bus. n rows of the seats on the left and n rows of the seats on the right. Each row can be filled by two people. So the total capacity of the bus is 4n. Consider that m (m ≀ 4n) people occupy the seats in the bus. The passengers entering the bus are numbered from 1 to m (in the order...
def get_ints(): return list(map(int, input().split())) N,M = get_ints() for i in range(1,min(2*N, M)+1): if 2*N+i<=M: print(2*N+i, end=" ") print(i,end=" ")
{ "input": [ "2 7\n", "9 36\n" ], "output": [ "5 1 6 2 7 3 4\n", "19 1 20 2 21 3 22 4 23 5 24 6 25 7 26 8 27 9 28 10 29 11 30 12 31 13 32 14 33 15 34 16 35 17 36 18\n" ] }
710
8
Vasya and Petya take part in a Codeforces round. The round lasts for two hours and contains five problems. For this round the dynamic problem scoring is used. If you were lucky not to participate in any Codeforces round with dynamic problem scoring, here is what it means. The maximum point value of the problem depends...
def f(v, x, n): if v<0: return 0 elif x<<1>n: return int( 500*(1-v/250)) elif x<<2>n: return int(1000*(1-v/250)) elif x<<3>n: return int(1500*(1-v/250)) elif x<<4>n: return int(2000*(1-v/250)) elif x<<5>n: return int(2500*(1-v/250)) else: return int(3000*(1-v/250)) n=int(input()) a=[list(map(int, ...
{ "input": [ "4\n-1 20 40 77 119\n30 10 73 50 107\n21 29 -1 64 98\n117 65 -1 -1 -1\n", "5\n119 119 119 119 119\n0 0 0 0 -1\n20 65 12 73 77\n78 112 22 23 11\n1 78 60 111 62\n", "2\n5 15 40 70 115\n50 45 40 30 15\n", "3\n55 80 10 -1 -1\n15 -1 79 60 -1\n42 -1 13 -1 -1\n" ], "output": [ "-1\n", ...
711
7
Mike has a string s consisting of only lowercase English letters. He wants to change exactly one character from the string so that the resulting one is a palindrome. A palindrome is a string that reads the same backward as forward, for example strings "z", "aaa", "aba", "abccba" are palindromes, but strings "codeforc...
def fun(ss): if len(ss)<2: return 0 if ss[0]==ss[-1]: return fun(ss[1:-1]) else: return 1+fun(ss[1:-1]) ss=input() print(['NO','YES'][[fun(ss)<2,fun(ss)==1][len(ss)%2==0]])
{ "input": [ "abbcca\n", "abcda\n", "abccaa\n" ], "output": [ "NO\n", "YES\n", "YES\n" ] }
712
9
Yet another round on DecoForces is coming! Grandpa Maks wanted to participate in it but someone has stolen his precious sofa! And how can one perform well with such a major loss? Fortunately, the thief had left a note for Grandpa Maks. This note got Maks to the sofa storehouse. Still he had no idea which sofa belongs ...
import sys from collections import defaultdict as dd from collections import deque pl=1 from math import * import copy #sys.setrecursionlimit(10**6) if pl: input=sys.stdin.readline def li(): return [int(xxx) for xxx in input().split()] def fi(): return int(input()) def si(): return list(input().rstrip()) def mi(...
{ "input": [ "2\n3 2\n3 1 3 2\n1 2 2 2\n1 0 0 1\n", "2\n2 2\n2 1 1 1\n1 2 2 2\n1 0 0 0\n", "3\n10 10\n1 2 1 1\n5 5 6 5\n6 4 5 4\n2 1 2 0\n" ], "output": [ "1\n", "-1\n", "2\n" ] }
713
8
Polycarp loves lowercase letters and dislikes uppercase ones. Once he got a string s consisting only of lowercase and uppercase Latin letters. Let A be a set of positions in the string. Let's call it pretty if following conditions are met: * letters on positions from A in the string are all distinct and lowercase; ...
import re def polycarp(string): parts = re.split("[A-Z]", string) return max(len(list(set(part))) for part in parts) n = int(input()) mystring = input() print(polycarp(mystring))
{ "input": [ "11\naaaaBaabAbA\n", "3\nABC\n", "12\nzACaAbbaazzC\n" ], "output": [ "2\n", "0\n", "3\n" ] }
714
7
Vasya studies music. He has learned lots of interesting stuff. For example, he knows that there are 12 notes: C, C#, D, D#, E, F, F#, G, G#, A, B, H. He also knows that the notes are repeated cyclically: after H goes C again, and before C stands H. We will consider the C note in the row's beginning and the C note aft...
def check(A,B,C): x = a.index(A) y = a.index(B) z = a.index(C) if((y-x)%12 == 4 and (z-y)%12 == 3): print("major") exit(0) elif((y-x)%12 == 3 and (z-y)%12 == 4): print("minor") exit(0) a = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'B', 'H'] A,B,C = input().split() check(A,B,C) check(A,C,B) ch...
{ "input": [ "A B H\n", "C E G\n", "C# B F\n" ], "output": [ "strange\n", "major\n", "minor\n" ] }
715
10
While Grisha was celebrating New Year with Ded Moroz, Misha gifted Sasha a small rectangular pond of size n Γ— m, divided into cells of size 1 Γ— 1, inhabited by tiny evil fishes (no more than one fish per cell, otherwise they'll strife!). The gift bundle also includes a square scoop of size r Γ— r, designed for fishing....
from heapq import * n, m, r, k = map(int, input().split()) u, v = n // 2, m // 2 h = [] g = lambda z, l: min(z + 1, l - z, l - r + 1, r) def f(x, y): if 0 <= x < n and 0 <= y < m: s = g(x, n) * g(y, m) heappush(h, (-s, x, y)) f(u, v) t = 0 for i in range(k): s, x, y = heappop(h) t -= s i...
{ "input": [ "12 17 9 40\n", "3 3 2 3\n" ], "output": [ "32.8333333333", "2.0000000000" ] }
716
10
In order to put away old things and welcome a fresh new year, a thorough cleaning of the house is a must. Little Tommy finds an old polynomial and cleaned it up by taking it modulo another. But now he regrets doing this... Given two integers p and k, find a polynomial f(x) with non-negative integer coefficients stric...
def solve(n, k): if n == 0: return [] x = n%k return [x] + solve(-(n-x)//k, k) n, k = map(int, input().split()) a = solve(n, k) print(len(a)) print(*a)
{ "input": [ "46 2\n", "2018 214\n" ], "output": [ "7\n 0 1 0 ...
717
9
You are given k sequences of integers. The length of the i-th sequence equals to n_i. You have to choose exactly two sequences i and j (i β‰  j) such that you can remove exactly one element in each of them in such a way that the sum of the changed sequence i (its length will be equal to n_i - 1) equals to the sum of the...
def sum_without_one(arr): s = sum(arr) return [s-x for x in arr] res = {} for i in range(int(input())): input() for j, x in enumerate(sum_without_one(list(map(int, input().split())))): if x in res and i+1 != res[x][0]: print('YES') print(i+1,j+1) print(*res[...
{ "input": [ "2\n5\n2 3 1 3 2\n6\n1 1 2 2 2 1\n", "4\n6\n2 2 2 2 2 2\n5\n2 2 2 2 2\n3\n2 2 2\n5\n2 2 2 2 2\n", "3\n1\n5\n5\n1 1 1 1 1\n2\n2 3\n" ], "output": [ "YES\n1 4\n2 1\n", "YES\n2 5\n4 1\n", "NO\n" ] }
718
11
Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide. Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the ...
from collections import * from math import * def ch(mx): if(mx > n): return 0 m = l[0]//(1<<(mx-1)) for i in range(mx): m = min(m,l[i]//(1<<(mx-i-1))) return m*((1<<mx)-1) n = int(input()) mx = ceil(log(n,2)) a = list(map(int,input().split())) c = Counter(a) l = list(c.values()) l.sort(reverse = True) n = len...
{ "input": [ "10\n6 6 6 3 6 1000000000 3 3 6 6\n", "3\n1337 1337 1337\n", "18\n2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10\n" ], "output": [ "9", "3", "14" ] }
719
11
Pavel has several sticks with lengths equal to powers of two. He has a_0 sticks of length 2^0 = 1, a_1 sticks of length 2^1 = 2, ..., a_{n-1} sticks of length 2^{n-1}. Pavel wants to make the maximum possible number of triangles using these sticks. The triangles should have strictly positive area, each stick can be ...
def li(): return list(map(int, input().split(" "))) input() ans = lo = 0 for i in li(): k = min(lo, i//2) i -= 2*k lo -= k ans += k ans += i//3 lo += (i%3) print(ans)
{ "input": [ "5\n1 2 2 2 2\n", "3\n1 1 1\n", "3\n3 3 3\n" ], "output": [ "3", "0", "3" ] }
720
8
Bob has a string s consisting of lowercase English letters. He defines s' to be the string after removing all "a" characters from s (keeping all other characters in the same order). He then generates a new string t by concatenating s and s'. In other words, t=s+s' (look at notes for an example). You are given a string...
def solution(t): no_a = t.replace('a', '') s_ = no_a[:len(no_a) // 2] if s_ + s_ == no_a and t.endswith(s_): return t[:-len(s_) or None] else: return ':(' print(solution(input()))
{ "input": [ "ababacacbbcc\n", "aacaababc\n", "baba\n", "aaaaa\n" ], "output": [ "ababacac", ":(", ":(", "aaaaa" ] }
721
8
This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You m...
# -*- coding: utf-8 -*- """ Created on Mon Apr 15 18:26:08 2019 @author: Hamadeh """ class LLNode: def __init__(self, data): self.data = data self.next = None self.prev = None # Class to create a Doubly Linked List class LL: # Constructor for empty Doubly Linked List de...
{ "input": [ "16\n64\n345\n672" ], "output": [ "? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 8...
722
11
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n Γ— m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells. Polycarp draws snakes with lowercase Latin letters. ...
import sys input = iter(sys.stdin.read().splitlines()).__next__ from collections import defaultdict as di def solve(): n,m = map(int,input().split()) B = [input() for _ in range(n)] pos = di(list) for i in range(n): b = B[i] for j in range(m): pos[b[j]].append((i,j)) i...
{ "input": [ "3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..\n", "2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc\n", "1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..\n" ], "output": [ "YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO\n", "YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2...
723
9
The main characters have been omitted to be short. You are given a directed unweighted graph without loops with n vertexes and a path in it (that path is not necessary simple) given by a sequence p_1, p_2, …, p_m of m vertexes; for each 1 ≀ i < m there is an arc from p_i to p_{i+1}. Define the sequence v_1, v_2, …, v...
def floyd(n, dist): for k in range(n): for i in range(n): for j in range(n): dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]) n = int(input()) graph = [[0] * n for _ in range(n)] for i in range(n): s = input() for j in range(n): graph[i][j] = int(s[j]) if s...
{ "input": [ "3\n011\n101\n110\n7\n1 2 3 1 3 2 1\n", "4\n0110\n0001\n0001\n1000\n3\n1 2 4\n", "4\n0110\n0010\n1001\n1000\n20\n1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4\n", "4\n0110\n0010\n0001\n1000\n4\n1 2 3 4\n" ], "output": [ "7\n1 2 3 1 3 2 1 \n", "2\n1 4 \n", "11\n1 2 4 2 4 2 4 2 4 ...
724
7
You are playing a variation of game 2048. Initially you have a multiset s of n integers. Every integer in this multiset is a power of two. You may perform any number (possibly, zero) operations with this multiset. During each operation you choose two equal integers from s, remove them from s and insert the number eq...
def solve(): n = int(input()) a = [x for x in map(int, input().split()) if x <= 2048] if sum(a) >= 2048: print('YES') else: print('NO') t = int(input()) for _ in range(t): solve()
{ "input": [ "6\n4\n1024 512 64 512\n1\n2048\n3\n64 512 2\n2\n4096 4\n7\n2048 2 2048 2048 2048 2048 2048\n2\n2048 4096\n" ], "output": [ "YES\nYES\nNO\nNO\nYES\nYES\n" ] }
725
8
Bob is playing with 6-sided dice. A net of such standard cube is shown below. <image> He has an unlimited supply of these dice and wants to build a tower by stacking multiple dice on top of each other, while choosing the orientation of each dice. Then he counts the number of visible pips on the faces of the dice. Fo...
input() def f(s): s = int(s) return ['NO', 'YES'][s >= 14 and s % 14 in range(1, 7)] print(*map(f, input().split()))
{ "input": [ "4\n29 34 19 38\n" ], "output": [ "YES\nYES\nYES\nNO\n" ] }
726
10
Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i β€” the number of vertices j in the subtree of vertex i, such that a_j < a_i. <image>Illustration for the second example, the first...
from sys import setrecursionlimit setrecursionlimit(1000000) n = int(input()) graph = [[] for _ in range(n + 1)] ci = [0] def solve(x): rlt = [] for v in graph[x]: rlt.extend(solve(v)) if len(rlt) < ci[x]: raise ValueError rlt.insert(ci[x], x) return rlt for i in range(1, n ...
{ "input": [ "3\n2 0\n0 2\n2 0\n", "5\n0 1\n1 3\n2 1\n3 0\n2 0\n" ], "output": [ "YES\n1 3 2 \n", "YES\n2 5 3 1 4 \n" ] }
727
10
Bessie is out grazing on the farm, which consists of n fields connected by m bidirectional roads. She is currently at field 1, and will return to her home at field n at the end of the day. The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has k special fields and he h...
from collections import deque import sys def bfs(s): q = deque() d = [-1] * n q.append(s) d[s] = 0 while len(q) > 0: u = q.popleft() for v in adj[u]: if d[v] == -1: d[v] = d[u] + 1 q.append(v) return d n, m, k = map(int, input().split()) a = list(map(lambda x : x - 1, map(int, input().split()))) ...
{ "input": [ "5 4 2\n2 4\n1 2\n2 3\n3 4\n4 5\n", "5 5 3\n1 3 5\n1 2\n2 3\n3 4\n3 5\n2 4\n" ], "output": [ "3\n", "3\n" ] }
728
10
Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS: You are given two integers d, m, find the number of arrays a, satisfying the following constraints: * The length of a is n, n β‰₯ 1 * 1 ≀ a_1 < a_2 < ... < a_n ≀ d * Define an array b of length n as foll...
def msb(x): return len(bin(x)) - 2 def solve(): d, mod = map(int, input().split()) way = 1 for i in range(msb(d) - 1): way += way * (1 << i) way += way * (d + 1 - (1 << (msb(d) - 1))) print((way - 1) % mod) for _ in range(int(input())): solve()
{ "input": [ "10\n1 1000000000\n2 999999999\n3 99999998\n4 9999997\n5 999996\n6 99995\n7 9994\n8 993\n9 92\n10 1\n" ], "output": [ "1\n3\n5\n11\n17\n23\n29\n59\n89\n0\n" ] }
729
10
Slime has a sequence of positive integers a_1, a_2, …, a_n. In one operation Orac can choose an arbitrary subsegment [l … r] of this sequence and replace all values a_l, a_{l + 1}, …, a_r to the value of median of \\{a_l, a_{l + 1}, …, a_r\}. In this problem, for the integer multiset s, the median of s is equal to th...
import sys input=sys.stdin.readline def main(): n,k=map(int,input().split()) A=list(map(int,input().split())) if min(A) == max(A) == k: print('yes') return if k not in A: print('no') return A = [x >= k for x in A] + [0, 0] print('yes' if max(sum(A[i:i+3]) for i i...
{ "input": [ "5\n5 3\n1 5 2 6 1\n1 6\n6\n3 2\n1 2 3\n4 3\n3 1 2 3\n10 3\n1 2 3 4 5 6 7 8 9 10\n" ], "output": [ "no\nyes\nyes\nno\nyes\n" ] }
730
9
Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling. Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat t...
from collections import Counter def solve(arr): n = len(arr) mp = Counter(arr) fmax = max(mp.values()) m = sum(1 for f in mp.values() if f==fmax) h = (n-m*fmax) // (fmax-1) return h + m - 1 for _ in range(int(input())): input() arr = list(map(int,input().split())) print(solve(arr))...
{ "input": [ "4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4\n" ], "output": [ "3\n2\n0\n4\n" ] }
731
8
You are given an array a, consisting of n integers. Each position i (1 ≀ i ≀ n) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearra...
def mp():return map(int,input().split()) def it():return int(input()) for _ in range(it()): n=it() l=list(mp()) k=list(mp()) v=[] for i in range(n): if not k[i]: v.append(l[i]) v.sort() ans=0 for i in range(n): if k[i]<1: l[i]=v.pop() print(*l)
{ "input": [ "5\n3\n1 3 2\n0 0 0\n4\n2 -3 4 -1\n1 1 1 1\n7\n-8 4 -2 -6 4 7 1\n1 0 0 0 1 1 0\n5\n0 1 -4 6 3\n0 0 0 1 1\n6\n-1 7 10 4 -8 -1\n1 0 0 0 0 1\n" ], "output": [ "3 2 1 \n2 -3 4 -1 \n-8 4 1 -2 4 7 -6 \n1 0 -4 6 3 \n-1 10 7 4 -8 -1 \n" ] }
732
7
For a given array a consisting of n integers and a given integer m find if it is possible to reorder elements of the array a in such a way that βˆ‘_{i=1}^{n}{βˆ‘_{j=i}^{n}{(a_j)/(j)}} equals m? It is forbidden to delete elements as well as insert new elements. Please note that no rounding occurs during division, for exampl...
def solv(): x, y = map(int, input().split()) s = sum(list(map(int, input().split()))) print('YES' if s == y else 'NO') for n in range(int(input())): solv()
{ "input": [ "2\n3 8\n2 5 1\n4 4\n0 1 2 3\n" ], "output": [ "YES\nNO\n" ] }
733
12
You are given an array of integers b_1, b_2, …, b_n. An array a_1, a_2, …, a_n of integers is hybrid if for each i (1 ≀ i ≀ n) at least one of these conditions is true: * b_i = a_i, or * b_i = βˆ‘_{j=1}^{i} a_j. Find the number of hybrid arrays a_1, a_2, …, a_n. As the result can be very large, you should pri...
import sys, os #from collections import defaultdict if os.environ['USERNAME']=='kissz': inp=open('in.txt','r').readline def debug(*args): print(*args,file=sys.stderr) else: inp=sys.stdin.readline def debug(*args): pass # SCRIPT STARTS HERE for _ in range(int(inp())): n=int(inp...
{ "input": [ "4\n3\n1 -1 1\n4\n1 2 3 4\n10\n2 -1 1 -2 2 3 -5 0 2 -1\n4\n0 0 0 1\n" ], "output": [ "\n3\n8\n223\n1\n" ] }
734
8
I, Fischl, Prinzessin der Verurteilung, descend upon this land by the call of fate an β€” Oh, you are also a traveler from another world? Very well, I grant you permission to travel with me. It is no surprise Fischl speaks with a strange choice of words. However, this time, not even Oz, her raven friend, can interpret h...
def increase(l) : i = 0 while i < len(l) and l[i] == 'z' : l[i] = 'a' i+=1 if i == len(l) : l.append('a') else : l[i] = chr(ord(l[i])+1) def solve(s) : l = ['a'] while 1 : c = ''.join(l[::-1]) if c not in s : print(c) return increase(l) t = int(input()) for i in range(t) : n = int(inpu...
{ "input": [ "3\n28\nqaabzwsxedcrfvtgbyhnujmiklop\n13\ncleanairactbd\n10\naannttoonn\n" ], "output": [ "\nac\nf\nb\n" ] }
735
7
One day Polycarpus got hold of two non-empty strings s and t, consisting of lowercase Latin letters. Polycarpus is quite good with strings, so he immediately wondered, how many different pairs of "x y" are there, such that x is a substring of string s, y is a subsequence of string t, and the content of x and y is the s...
def f(a,b): dp=[[0]*(len(b)+1) for i in range(len(a)+1)] for i in range(len(a)): for j in range(len(b)): dp[i+1][j+1]=(dp[i+1][j]+(a[i]==b[j])*(dp[i][j]+1))%(10**9+7) ans=0 for i in range(0,len(a)): ans=(ans+dp[i+1][-1])%(10**9+7) return ans a=input() b=input() print(f(a,b))
{ "input": [ "codeforces\nforceofcode\n", "aa\naa\n" ], "output": [ "60\n", "5\n" ] }
736
8
The Zoo in the Grid Kingdom is represented by an infinite grid. The Zoo has n observation binoculars located at the OX axis. For each i between 1 and n, inclusive, there exists a single binocular located at the point with coordinates (i, 0). There are m flamingos in the Zoo, located at points with positive coordinates....
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...
{ "input": [ "5 5\n2 1\n4 1\n3 2\n4 3\n4 4\n" ], "output": [ "11\n" ] }
737
9
You are given a table consisting of n rows and m columns. Each cell of the table contains a number, 0 or 1. In one move we can choose some row of the table and cyclically shift its values either one cell to the left, or one cell to the right. To cyclically shift a table row one cell to the right means to move the valu...
def solve(rows): all_dists = [0 for _ in range(len(rows[0]))] for r in rows: dists = [len(r) for _ in r] if '1' not in r: return -1 start = r.index('1') for i in range(len(r)): right = (i+start)%len(r) # going right left = (start+2*len(r)-i)%le...
{ "input": [ "3 6\n101010\n000100\n100000\n", "2 3\n111\n000\n" ], "output": [ "3", "-1" ] }
738
8
Mr. Bender has a digital table of size n Γ— n, each cell can be switched on or off. He wants the field to have at least c switched on squares. When this condition is fulfilled, Mr Bender will be happy. We'll consider the table rows numbered from top to bottom from 1 to n, and the columns β€” numbered from left to right f...
x, y, n, c = 0, 0, 0, 0 def suma_impares(m): return m * m def suma_n(m): return m * (m - 1) // 2 def cnt(t): u, d, l, r = x + t, x - t, y - t, y + t suma = t ** 2 + (t + 1) ** 2 if u > n: suma -= suma_impares(u - n) if d < 1: suma -= suma_impares(1 - d) if l < 1: suma -= suma_impares(1 - l) if r > n: suma -= su...
{ "input": [ "9 3 8 10\n", "6 4 3 1\n" ], "output": [ "2\n", "0\n" ] }
739
8
The tournament Β«Sleepyhead-2010Β» in the rapid falling asleep has just finished in Berland. n best participants from the country have participated in it. The tournament consists of games, each of them is a match between two participants. nΒ·(n - 1) / 2 games were played during the tournament, and each participant had a m...
def s(): n = int(input()) a = [0]*(n+1) b = [0]*(n+1) r = [] for _ in range(n*(n-1)//2-1): c = list(map(int,input().split())) a[c[0]] += 1 b[c[1]] += 1 for i in range(1,n+1): if a[i] + b[i] == n-2: r.append(i) r.sort(key = lambda x:-a[x]) print(*r) s()
{ "input": [ "4\n4 2\n4 1\n2 3\n2 1\n3 1\n" ], "output": [ "4 3\n" ] }
740
7
Eugeny has array a = a1, a2, ..., an, consisting of n integers. Each integer ai equals to -1, or to 1. Also, he has m queries: * Query number i is given as a pair of integers li, ri (1 ≀ li ≀ ri ≀ n). * The response to the query will be integer 1, if the elements of array a can be rearranged so as the sum ali + a...
def main(): n, m = map(int, input().split()) a = input().count('-') if a > n - a: a = n - a res = [] for _ in range(m): l, r = map(int, input().split()) r -= l res.append(('0', '1')[r & 1 and a * 2 >= r + 1]) print('\n'.join(res)) if __name__ == '__main__': ...
{ "input": [ "5 5\n-1 1 1 1 -1\n1 1\n2 3\n3 5\n2 5\n1 5\n", "2 3\n1 -1\n1 1\n1 2\n2 2\n" ], "output": [ "0\n1\n0\n1\n0\n", "0\n1\n0\n" ] }
741
11
On a number line there are n balls. At time moment 0 for each ball the following data is known: its coordinate xi, speed vi (possibly, negative) and weight mi. The radius of the balls can be ignored. The balls collide elastically, i.e. if two balls weighing m1 and m2 and with speeds v1 and v2 collide, their new speeds...
import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') n, t = map(int, input().split()) t = float(t) balls = sorted(list(map(float, input().split())) + [i] for i in range(n)) eps = 1e-9 def calc(i, j): ok, ng = 0.0, t + 1.0 for _ in range(50): ...
{ "input": [ "2 9\n3 4 5\n0 7 8\n", "3 10\n1 2 3\n4 -5 6\n7 -8 9\n" ], "output": [ "68.538461538\n44.538461538\n", "-93.666666667\n-74.666666667\n-15.666666667\n" ] }
742
7
Dima and Inna are doing so great! At the moment, Inna is sitting on the magic lawn playing with a pink pony. Dima wanted to play too. He brought an n Γ— m chessboard, a very tasty candy and two numbers a and b. Dima put the chessboard in front of Inna and placed the candy in position (i, j) on the board. The boy said h...
import sys input=sys.stdin.readline n,m,i,j,a,b=map(int,input().split()) MIN=10**18 def calc(u,v): global MIN if (u-i)%a==0 and (v-j)%b==0: x=abs(u-i)//a y=abs(v-j)//b if x%2==y%2 and 1+a<=n and 1+b<=m: MIN=min(MIN,max(x,y)) if x==y==0: MIN=0 calc(1,1) cal...
{ "input": [ "5 5 2 3 1 1\n", "5 7 1 3 2 2\n" ], "output": [ "Poor Inna and pony!\n", "2\n" ] }
743
8
DZY loves chemistry, and he enjoys mixing chemicals. DZY has n chemicals, and m pairs of them will react. He wants to pour these chemicals into a test tube, and he needs to pour them in one by one, in any order. Let's consider the danger of a test tube. Danger of an empty test tube is 1. And every time when DZY pour...
def gf(x): if fa[x] != x: fa[x] = gf(fa[x]) return fa[x] n, m = map(int, input().split()) fa = list(range(n + 1)) for _ in range(m): x, y = map(int, input().split()) fa[gf(x)] = gf(y) ans = 2 ** n for i in range(1, n + 1): if gf(i) == i: ans //= 2 print(ans)
{ "input": [ "3 2\n1 2\n2 3\n", "2 1\n1 2\n", "1 0\n" ], "output": [ "4\n", "2\n", "1\n" ] }
744
9
The new ITone 6 has been released recently and George got really keen to buy it. Unfortunately, he didn't have enough money, so George was going to work as a programmer. Now he faced the following problem at the work. Given a sequence of n integers p1, p2, ..., pn. You are to choose k pairs of integers: [l1, r1], [l2...
from sys import stdin input = stdin.readline def put(): return map(int, input().split()) n,m,k = put() l = list(put()) p = [] summ = 0 for i in range(m): summ+= l[i] p.append(summ) for i in range(m, n): summ+= l[i]-l[i-m] p.append(summ) r = p.copy() c = len(p) q = [0]*c for j in range(k): for i in...
{ "input": [ "5 2 1\n1 2 3 4 5\n", "7 1 3\n2 10 7 18 5 33 0\n" ], "output": [ "9", "61" ] }
745
10
Vasya is a school PE teacher. Unlike other PE teachers, Vasya doesn't like it when the students stand in line according to their height. Instead, he demands that the children stand in the following order: a1, a2, ..., an, where ai is the height of the i-th student in the line and n is the number of students in the line...
import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) ans = [] for i in range(n): j = b.index(a[i], i) while i < j: ans.append(f'{j} {j+1}') ...
{ "input": [ "2\n1 100500\n1 100500\n", "4\n1 2 3 2\n3 2 1 2\n" ], "output": [ "0\n", "3\n2 3\n1 2\n2 3\n" ] }
746
12
King of Berland Berl IV has recently died. Hail Berl V! As a sign of the highest achievements of the deceased king the new king decided to build a mausoleum with Berl IV's body on the main square of the capital. The mausoleum will be constructed from 2n blocks, each of them has the shape of a cuboid. Each block has th...
def check(l, r, a, b): if a < 0 or b >= 2 * N: return 0 def val(p): if p in [a, b]: return '0' if l <= p and p < r: return '1' return '-1' for i in range(K): x, y = val(A[i]), val(C[i]) if A[i] in [a, b] or C[i] in [a, b]: if not eval(x + B[i] + y)...
{ "input": [ "3 0\n", "4 1\n3 = 6\n", "3 1\n2 &gt; 3\n" ], "output": [ "9\n", "3\n", " 9\n" ] }
747
9
Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't). q events are abou...
import sys, collections def inp(): return map(int, input().split()) n, q = inp() Q = collections.deque() A = n * [0] B = A[:] L = [] s = n = 0 for _ in range(q): typeq, x = inp() if typeq == 1: x -= 1 Q.append(x) B[x] += 1 A[x] += 1 s += 1 elif typeq == 2: ...
{ "input": [ "4 6\n1 2\n1 4\n1 2\n3 3\n1 3\n1 3\n", "3 4\n1 3\n1 1\n1 2\n2 3\n" ], "output": [ "1\n2\n3\n0\n1\n2\n", "1\n2\n3\n2\n" ] }
748
7
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1. Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divi...
def bachgold(n): print(n//2) a = [2] * (n//2) if n%2: a[-1] += 1 print(*a) n = int(input()) bachgold(n)
{ "input": [ "6\n", "5\n" ], "output": [ "3\n2 2 2 \n", "2\n2 3\n" ] }
749
8
After returning from the army Makes received a gift β€” an array a consisting of n positive integer numbers. He hadn't been solving problems for a long time, so he became interested to answer a particular question: how many triples of indices (i, j, k) (i < j < k), such that aiΒ·ajΒ·ak is minimum possible, are there in the...
def C(n,r): if r>n//2: r=n-r ans=1 for i in range(1,r+1): ans*=(n-r+i) ans//=i return ans n=input() a=list(map(int,input().split())) a.sort() b=set(a[0:3]) m={} for i in b: m[i]=0 for i in a[0:3]: m[i]+=1 ans=1 for i in m: ans*=C(a.count(i),m[i]) print(ans)
{ "input": [ "5\n1 3 2 3 4\n", "6\n1 3 3 1 3 2\n", "4\n1 1 1 1\n" ], "output": [ "2\n", "1\n", "4\n" ] }
750
8
Gleb ordered pizza home. When the courier delivered the pizza, he was very upset, because several pieces of sausage lay on the crust, and he does not really like the crust. The pizza is a circle of radius r and center at the origin. Pizza consists of the main part β€” circle of radius r - d with center at the origin, an...
R=lambda:list(map(int,input().split())) r,d=R() def ok(): x,y,z=R() return 1 if (r-d+z)**2<=x*x+y*y<=(r-z)**2 else 0 print(sum(ok() for i in range(int(input()))))
{ "input": [ "10 8\n4\n0 0 9\n0 0 10\n1 0 1\n1 0 2\n", "8 4\n7\n7 8 1\n-7 3 2\n0 2 1\n0 -2 2\n-3 -3 1\n0 6 2\n5 3 1\n" ], "output": [ "0\n", "2\n" ] }
751
8
Vadim is really keen on travelling. Recently he heard about kayaking activity near his town and became very excited about it, so he joined a party of kayakers. Now the party is ready to start its journey, but firstly they have to choose kayaks. There are 2Β·n people in the group (including Vadim), and they have exactly...
n = int(input()) ws = sorted(list(map(int, input().split(' ')))) res = 10 ** 10 def f(vs): return sum(abs(a - b) for a, b in zip(vs[0::2], vs[1::2])) for i in range(len(ws)): for j in range(i + 1, len(ws)): test = ws[:i] + ws[i+1:j] + ws[j+1:] res = min(res, f(test)) print(res)
{ "input": [ "4\n1 3 4 6 3 4 100 200\n", "2\n1 2 3 4\n" ], "output": [ "5\n", "1\n" ] }
752
12
There are n points marked on the plane. The points are situated in such a way that they form a regular polygon (marked points are its vertices, and they are numbered in counter-clockwise order). You can draw n - 1 segments, each connecting any two marked points, in such a way that all points have to be connected with e...
import sys from array import array n = int(input()) edge = [list(map(int, input().split())) for _ in range(n)] mod = 10**9 + 7 dp_f = [array('i', [-1])*n for _ in range(n)] dp_g = [array('i', [-1])*n for _ in range(n)] for i in range(n): dp_f[i][i] = dp_g[i][i] = 1 for i in range(n-1): dp_f[i][i+1] = dp_g[i...
{ "input": [ "3\n0 0 1\n0 0 1\n1 1 0\n", "4\n0 1 1 1\n1 0 1 1\n1 1 0 1\n1 1 1 0\n", "3\n0 0 0\n0 0 1\n0 1 0\n" ], "output": [ "1\n", "12\n", "0\n" ] }
753
10
A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i, j) such that i > j and ai < aj. For example, a permutation [4, 1, 3, 2] contains 4 inversions: (2, 1), (3, 1), (4, 1), (4, 3). You are given a per...
def solve(): n=int(input()) a=list(map(int,input().split())) cl=['odd','even'] m=int(input()) ans=True b=[] ap=b.append for i in range(n): for j in range(i): if a[j]>a[i]: ans=not ans for i in range(m): left,right=map(int,input().split()) ...
{ "input": [ "4\n1 2 4 3\n4\n1 1\n1 4\n1 4\n2 3\n", "3\n1 2 3\n2\n1 2\n2 3\n" ], "output": [ "odd\nodd\nodd\neven\n", "odd\neven\n" ] }
754
8
In order to put away old things and welcome a fresh new year, a thorough cleaning of the house is a must. Little Tommy finds an old polynomial and cleaned it up by taking it modulo another. But now he regrets doing this... Given two integers p and k, find a polynomial f(x) with non-negative integer coefficients stric...
def solve(n, k): if n == 0: return [] x = n%k return [x] + solve(-(n-x)//k, k) n, k = map(int, input().split()) a = solve(n, k) print(len(a)) print(*a)
{ "input": [ "46 2\n", "2018 214\n" ], "output": [ "7\n0 1 0 0 1 1 1 \n", "3\n92 205 1 \n" ] }
755
8
Year 2118. Androids are in mass production for decades now, and they do all the work for humans. But androids have to go to school to be able to solve creative tasks. Just like humans before. It turns out that high school struggles are not gone. If someone is not like others, he is bullied. Vasya-8800 is an economy-cl...
import math x,y=map(int, input().split()) def f(x): if x: return math.log(x)/x if f(x)<f(y): print('<') elif f(y)<f(x): print('>') elif x==y:print('=') else: print('=')
{ "input": [ "5 8\n", "6 6\n", "10 3\n" ], "output": [ ">\n", "=\n", "<\n" ] }
756
8
This is an interactive problem. Imur Ishakov decided to organize a club for people who love to play the famous game Β«The hatΒ». The club was visited by n students, where n is even. Imur arranged them all in a circle and held a draw to break the students in pairs, but something went wrong. The participants are numbered ...
import sys def ask(x): print('? %d'%x) sys.stdout.flush() x=int(input()) return x n=int(input()) t=n//2 if t&1: print('! -1') sys.stdout.flush() sys.exit() l=1 r=n while l<r: mid=(l+r)>>1 if ask(mid)>=ask((mid+t-1)%n+1): r=mid else: l=mid+1 print('! %d'%l) sys.s...
{ "input": [ "6\n<span class=\"tex-span\"></span>\n1\n<span class=\"tex-span\"></span>\n2\n<span class=\"tex-span\"></span>\n3 \n<span class=\"tex-span\"></span>\n2\n<span class=\"tex-span\"></span>\n1\n<span class=\"tex-span\"></span>\n0", "8\n<span class=\"tex-span\"></span>\n2\n<span class=\"tex-span\"></s...
757
7
There are n benches in the Berland Central park. It is known that a_i people are currently sitting on the i-th bench. Another m people are coming to the park and each of them is going to have a seat on some bench out of n available. Let k be the maximum number of people sitting on one bench after additional m people c...
def inp(): return list(map(int,input().split())) n,=inp() m,=inp() a = [int(input()) for i in range(n)] s=sum(a) mx=max(a) mi= max([mx, int((s+m+n-1)/n)]) mx= mx + m print(mi,mx)
{ "input": [ "4\n6\n1\n1\n1\n1\n", "1\n10\n5\n", "3\n6\n1\n6\n5\n", "3\n7\n1\n6\n5\n" ], "output": [ "3 7\n", "15 15\n", "6 12\n", "7 13\n" ] }
758
10
Lunar New Year is approaching, and Bob decides to take a wander in a nearby park. The park can be represented as a connected graph with n nodes and m bidirectional edges. Initially Bob is at the node 1 and he records 1 on his notebook. He can wander from one node to another through those bidirectional edges. Whenever ...
import bisect def dfs(i,vis,g): print(i,end=" ") vis[i]=1 for j in g[i]: if vis[j]==0: dfs(j,vis,g) n,m=map(int,input().split()) g=[[] for i in range(n+1)] for i in range(m): u,v=map(int,input().split()) bisect.insort(g[u],v) bisect.insort(g[v],u) bfs=[1] l=1 vis=[0]*(n+1) vis[1]=1 while l!=0: i=bfs.pop(0...
{ "input": [ "3 2\n1 2\n1 3\n", "10 10\n1 4\n6 8\n2 5\n3 7\n9 4\n5 6\n3 4\n8 10\n8 9\n1 10\n", "5 5\n1 4\n3 4\n5 4\n3 2\n1 5\n" ], "output": [ "1 2 3 ", "1 4 3 7 9 8 6 5 2 10 ", "1 4 3 2 5 " ] }
759
11
You are a coach at your local university. There are n students under your supervision, the programming skill of the i-th student is a_i. You have to form k teams for yet another new programming competition. As you know, the more students are involved in competition the more probable the victory of your university is! ...
from sys import stdin input=stdin.readline from collections import defaultdict def f(a,n,k): cnt=[0]*(n) a=sorted(a) for i in range(n): while i+cnt[i]<n and a[i+cnt[i]]-a[i]<=5: cnt[i]+=1 dp=[[0]*(k+1) for i in range(n+1)] for i in range(n): for j in range(k+1): dp[i+1][j]=max(dp[i+1][j],dp[i][j]) if...
{ "input": [ "4 4\n1 10 100 1000\n", "6 1\n36 4 1 25 9 16\n", "5 2\n1 2 15 15 15\n" ], "output": [ "4\n", "2\n", "5\n" ] }
760
8
You are given a sequence a_1, a_2, ..., a_n consisting of n integers. You can choose any non-negative integer D (i.e. D β‰₯ 0), and for each a_i you can: * add D (only once), i. e. perform a_i := a_i + D, or * subtract D (only once), i. e. perform a_i := a_i - D, or * leave the value of a_i unchanged. It is...
input() s = set(map(int, input().split())) def no(): print(-1) exit(0) n = len(s) if n > 3: no() elif n == 1: print(0) else: a = sorted([x for x in s]) if n == 2: m = a[1] - a[0] if m % 2 == 0: print(m // 2) else: print(m) elif a[0] + a[2] != a[1] + a[1]: no() else: print(a[1] - a[0])
{ "input": [ "2\n2 8\n", "4\n1 3 3 7\n", "5\n2 2 5 2 5\n", "6\n1 4 4 7 4 1\n" ], "output": [ "3\n", "-1\n", "3\n", "3\n" ] }
761
12
Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only T seconds after coming. Fortunately, Adilbek can spend time witho...
mod = 10 ** 9 + 7 MAX = 2 * 10 ** 5+2 r = [1] * MAX factorial = [1] * MAX rfactorial = [1] * MAX rp = [1] * MAX for i in range(2, MAX): factorial[i] = i * factorial[i - 1] % mod r[i] = mod - (mod // i) * r[mod%i] % mod rfactorial[i] = rfactorial[i-1] * r[i] % mod for i in range(1, MAX): rp...
{ "input": [ "3 5\n2 2 2\n", "3 5\n2 1 2\n" ], "output": [ "750000007\n", "125000003\n" ] }
762
8
The only difference between easy and hard versions are constraints on n and k. You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most k most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals 0...
from collections import deque def solve(k, ids): mes = deque(maxlen=k) for i in ids: if i not in mes: mes.appendleft(i) return len(mes), mes n, k = map(int, input().split()) ids = input().split() m, ids = solve(k, ids) print(m) print(' '.join(ids))
{ "input": [ "10 4\n2 3 3 1 1 2 1 2 3 3\n", "7 2\n1 2 3 2 1 3 2\n" ], "output": [ "3\n1 3 2\n", "2\n2 1\n" ] }
763
11
There are four stones on an infinite line in integer coordinates a_1, a_2, a_3, a_4. The goal is to have the stones in coordinates b_1, b_2, b_3, b_4. The order of the stones does not matter, that is, a stone from any position a_i can end up in at any position b_j, provided there is a required number of stones in each ...
def gcd(a, b): while a and b: a %= b if a: b %= a return a + b def gcd2(A): r = A[1] - A[0] for i in (2, 3): r = gcd(r, A[i] - A[0]) return r def Mir(x, c): return c * 2 - x def Solve(A): A[0].sort() A[1].sort() gcds = [gcd2(A[0]), gcd2(A[1])] I0, I1 = 0, 1...
{ "input": [ "0 1 2 3\n3 5 6 8\n", "0 0 0 1\n0 1 0 1\n", "0 0 0 0\n1 1 1 1\n" ], "output": [ "\n3\n1 3\n2 5\n0 3\n", "-1\n", "-1\n" ] }
764
11
This is a hard version of the problem. The actual problems are different, but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different. You are given a string s consisting of n lowercase Latin letters. You have to color all its characters the minimum numb...
def main(): n = int(input()) s = input() lst = ['a']*n ans=[] m=0 for i in range(n): for j in range(n): if lst[j]<=s[i]: lst[j] = s[i] ans.append(j+1) m = max(m, j+1) break print (m) print (*ans) main()
{ "input": [ "8\naaabbcbb\n", "5\nabcde\n", "7\nabcdedc\n", "9\nabacbecfd\n" ], "output": [ "2\n1 1 1 1 1 1 2 2 \n", "1\n1 1 1 1 1 \n", "3\n1 1 1 1 1 2 3 \n", "2\n1 1 2 1 2 1 2 1 2 \n" ] }
765
9
You have an array a of length n. For every positive integer x you are going to perform the following operation during the x-th second: * Select some distinct indices i_{1}, i_{2}, …, i_{k} which are between 1 and n inclusive, and add 2^{x-1} to each corresponding position of a. Formally, a_{i_{j}} := a_{i_{j}} + 2^{...
t=int(input()) def f(x): i=0 for _ in range(t): n=int(input()) a=(list(map(int,input().split()))) k=0 for i in range(1,n): if a[i-1]>a[i]: d= a[i-1] - a[i] a[i] = a[i-1] k=max(k, len(bin(d))-2) print(k)
{ "input": [ "3\n4\n1 7 6 5\n5\n1 2 3 4 5\n2\n0 -4\n" ], "output": [ "2\n0\n3\n" ] }
766
7
This is the easy version of the problem. The difference between the versions is the constraint on n and the required number of operations. You can make hacks only if all versions of the problem are solved. There are two binary strings a and b of length n (a binary string is a string consisting of symbols 0 and 1). In ...
def solve(): # put code here n = int(input()) a=input() b=input() ans=[] for i in range(n): if a[i]!=b[i]: ans.extend([i+1, 1, i+1]) print(len(ans), ' '.join(str(v) for v in ans)) t = int(input()) for _ in range(t): solve()
{ "input": [ "5\n2\n01\n10\n5\n01011\n11100\n2\n01\n01\n10\n0110011011\n1000110100\n1\n0\n1\n" ], "output": [ "3 1 2 1\n3 1 5 2\n0\n7 1 10 8 7 1 2 1\n1 1\n" ] }
767
7
We have a point A with coordinate x = n on OX-axis. We'd like to find an integer point B (also on OX-axis), such that the absolute difference between the distance from O to B and the distance from A to B is equal to k. <image> The description of the first test case. Since sometimes it's impossible to find such point ...
def func(n,k): print(0+(n%2!=k%2))if n>=k else print(abs(n-k)) t=int(input()) for i in range(t): n,k=map(int,input().split()) func(n,k)
{ "input": [ "6\n4 0\n5 8\n0 1000000\n0 0\n1 0\n1000000 1000000\n" ], "output": [ "0\n3\n1000000\n0\n1\n0\n" ] }
768
10
You are given an array a of length 2n. Consider a partition of array a into two subsequences p and q of length n each (each element of array a should be in exactly one subsequence: either in p or in q). Let's sort p in non-decreasing order, and q in non-increasing order, we can denote the sorted versions by x and y, r...
def res(n): nu=s=1 for i in range(n): nu=(nu*(2*n-i))%m s=(s*(i+1))%m return((nu*pow(s,m-2,m))%m) m=998244353 n=int(input()) fg=sorted(list(map(int,input().split()))) f=abs((sum(fg[:n])-sum(fg[n:]))) print((f*res(n))%m) #print(f)
{ "input": [ "5\n13 8 35 94 9284 34 54 69 123 846\n", "2\n2 1 2 1\n", "3\n2 2 2 2 2 2\n", "1\n1 4\n" ], "output": [ "2588544", "12", "0", "6" ] }
769
10
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya loves long lucky numbers very much. He is interested in the minimum lucky number d that meet...
a1,a2,a3,a4=map(int,input().split()) L=[] def Solve(a1,a2,a3,a4): if(a3-a4<-1 or a3-a4>1 or a1<a3 or a1<a4 or a2<a3 or a2<a4): return -1 elif(a3-a4==0): Ans="47"*a3 Ans+="4" if(a1-a3==0 and a2-a4==0): return -1 elif(a1-a3==0): return "74"*a3+"7"*...
{ "input": [ "2 2 1 1\n", "4 7 3 1\n" ], "output": [ "4774\n", "-1\n" ] }
770
9
Polycarp is an organizer of a Berland ICPC regional event. There are n universities in Berland numbered from 1 to n. Polycarp knows all competitive programmers in the region. There are n students: the i-th student is enrolled at a university u_i and has a programming skill s_i. Polycarp has to decide on the rules now....
from collections import defaultdict def mkprefix(a): b = [] sm = 0 for i in range(len(a)): sm+= a[i] b.append(sm) return b R = lambda : list(map(int,input().split())) for _ in range(int(input())): n = int(input()) u = R() s = R() d = defaultdict(lambda : list()) for i in range(n): d[u[i]].append(s[i]) ...
{ "input": [ "4\n7\n1 2 1 2 1 2 1\n6 8 3 1 5 1 5\n10\n1 1 1 2 2 2 2 3 3 3\n3435 3014 2241 2233 2893 2102 2286 2175 1961 2567\n6\n3 3 3 3 3 3\n5 9 6 7 9 7\n1\n1\n3083\n" ], "output": [ "\n29 28 26 19 0 0 0 \n24907 20705 22805 9514 0 0 0 0 0 0 \n43 43 43 32 38 43 \n3083 \n" ] }
771
9
AquaMoon has n friends. They stand in a row from left to right, and the i-th friend from the left wears a T-shirt with a number a_i written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right. AquaMoon can make some operations on friends. On each operation, AquaM...
import sys input = sys.stdin.readline def main(): n=int(input()) a=list(map(int,input().split())) if sorted(a)[::2]==sorted(a[::2]): print("YES") else: print("NO") for _ in range(int(input())): main()
{ "input": [ "3\n4\n4 3 2 5\n4\n3 3 2 2\n5\n1 2 3 5 4\n" ], "output": [ "YES\nYES\nNO\n" ] }
772
11
John Doe has a list of all Fibonacci numbers modulo 1013. This list is infinite, it starts with numbers 0 and 1. Each number in the list, apart from the first two, is a sum of previous two modulo 1013. That is, John's list is made from the Fibonacci numbers' list by replacing each number there by the remainder when div...
n,m,l,f,L=10000,15000,int(10**13),int(input()),[] def F(i): if i==0: return (0,1) x,y=F(i>>1) x,y=((2*x*y-x*x)%n,(y*y+x*x)%n) if i&1: x,y=(y%n,(x+y)%n) return (x,y) for i in range(m): if F(i)[0]==f%n: L.append(i) while n<l: n*=10; T=[] for i in L: for j in range(10): if F(i+j*m)[0]==f%n: ...
{ "input": [ "13\n", "377\n" ], "output": [ "7\n", "14\n" ] }
773
9
You are given a square matrix consisting of n rows and n columns. We assume that 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. Some cells (n - 1 cells in total) of the the matrix are filled with ones, the remaining cells are filled with zeros. We can a...
def find_all(s, c): index = s.index(c) while True: yield index try: index = s.index(c, index + 1) except ValueError: break n = int(input()) row, col, actions = [], [], [] available = list(range(1, n + 1)) for _ in range(n - 1): (r, c) = map(int, input().spli...
{ "input": [ "3\n3 1\n1 3\n", "2\n1 2\n", "3\n2 1\n3 2\n" ], "output": [ "3\n2 2 3\n1 1 3\n1 1 2\n", "2\n2 1 2\n1 1 2\n", "0\n" ] }
774
9
There are n students living in the campus. Every morning all students wake up at the same time and go to wash. There are m rooms with wash basins. The i-th of these rooms contains ai wash basins. Every student independently select one the rooms with equal probability and goes to it. After all students selected their ro...
from sys import stdin input = stdin.buffer.readline def c(n, k): if k > n: return 0 a = b = 1 for i in range(n - k + 1, n + 1): a *= i for i in range(1, k + 1): b *= i return a // b n, m = map(int, input().split()) *a, = map(int, input().split()) dp = [[[0 for k in range(n + 1)] for j in range(m + 1)] for...
{ "input": [ "2 2\n1 1\n", "2 3\n1 1 1\n", "7 5\n1 1 2 3 1\n", "1 1\n2\n" ], "output": [ "1.500000000000000\n", "1.333333333333333\n", "2.502169600000002\n", "1.000000000000000\n" ] }
775
9
During the last Sereja's Codesecrof round the server crashed many times, so the round was decided to be made unrated for some participants. Let's assume that n people took part in the contest. Let's assume that the participant who got the first place has rating a1, the second place participant has rating a2, ..., the...
from sys import stdin,stdout nmbr = lambda: int(stdin.readline()) lst = lambda: list(map(int,stdin.readline().split())) def fn(a): print('a',a) n=len(a) pos1=[0] for i in range(1,n): pos1+=[pos1[-1]+a[i]*i] print('pos1',pos1) neg=[] for i in range(n): neg+=[i*(n-i-1)*a[i]] ...
{ "input": [ "5 0\n5 3 4 1 2\n", "10 -10\n5 5 1 7 5 1 2 4 9 2\n" ], "output": [ "2\n3\n4\n", "2\n4\n5\n7\n8\n9\n" ] }
776
8
One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning: a1, a2, ..., an β†’ an, a1, a2, ..., an - 1. Help Twi...
def min_moves(n,l): m,k=0,0 for i in range(n-1): if l[i+1]<l[i]: return (-1,n-i-1)[sorted(l)==l[i+1:]+l[:i+1]] break else: return 0 n=int(input()) l=list(map(int,input().split())) print(min_moves(n,l))
{ "input": [ "3\n1 3 2\n", "2\n1 2\n", "2\n2 1\n" ], "output": [ "-1\n", "0\n", "1\n" ] }
777
7
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem. Pete and Bi...
def a(n): return "YES" if n%2==0 and n!=2 else "NO" print(a(int(input())))
{ "input": [ "8\n" ], "output": [ "YES\n" ] }
778
7
You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order). Input The only line of input contains a string s of length between 1 and 105 consisting of uppercase Latin letters. Output Print "YES" (without the quot...
def f(inp, ab, ba): i = inp.find(ab) return i != -1 and inp.find(ba, i + 2) != -1 inp = input() if (f(inp, "AB", "BA") or f(inp, "BA", "AB")): print ("YES") else: print ("NO")
{ "input": [ "ABA\n", "AXBYBXA\n", "BACFAB\n" ], "output": [ "NO\n", "NO\n", "YES\n" ] }
779
8
You are given a sequence of numbers a1, a2, ..., an, and a number m. Check if it is possible to choose a non-empty subsequence aij such that the sum of numbers in this subsequence is divisible by m. Input The first line contains two numbers, n and m (1 ≀ n ≀ 106, 2 ≀ m ≀ 103) β€” the size of the original sequence and ...
def solve(): n, m = map(int, input().split()) a = list(map(int, input().split())) if n >= m: return "YES" s = set() for i in a: w = set() for j in s: w.add((i+j)%m) s.update(w) s.add(i%m) if 0 in s: return "YES" return "NO" ...
{ "input": [ "4 6\n3 1 1 3\n", "1 6\n5\n", "6 6\n5 5 5 5 5 5\n", "3 5\n1 2 3\n" ], "output": [ "YES\n", "NO\n", "YES\n", "YES\n" ] }
780
7
Little Petya has recently started attending a programming club. Naturally he is facing the problem of choosing a programming language. After long considerations he realized that Java is the best choice. The main argument in favor of choosing Java was that it has a very large integer data type, called BigInteger. But h...
def limit(n,l,z): if abs(n) <= abs(l) or n == l-1: print(z) exit() else: pass a = int(input()) limit(a,-127,'byte') limit(a,-32767,'short') limit(a,-2147483647,'int') limit(a,-9223372036854775807,'long') print('BigInteger')
{ "input": [ "123456789101112131415161718192021222324\n", "127\n", "130\n" ], "output": [ "BigInteger\n", "byte\n", "short\n" ] }
781
12
Heidi has finally found the mythical Tree of Life – a legendary combinatorial structure which is said to contain a prophecy crucially needed to defeat the undead armies. On the surface, the Tree of Life is just a regular undirected tree well-known from computer science. This means that it is a collection of n points (...
def main(): n = int(input()) l = [0] * (n + 1) for _ in range(n - 1): a, b = map(int, input().split()) l[a] += 1 l[b] += 1 res = 0 for x in l: res += x * (x - 1) print(res // 2) if __name__ == '__main__': main()
{ "input": [ "4\n1 2\n1 3\n1 4\n", "5\n1 2\n2 3\n3 4\n3 5\n" ], "output": [ "3\n", "4\n" ] }
782
11
Ostap already settled down in Rio de Janiero suburb and started to grow a tree in his garden. Recall that a tree is a connected undirected acyclic graph. Ostap's tree now has n vertices. He wants to paint some vertices of the tree black such that from any vertex u there is at least one black vertex v at distance no m...
def main(): n, k = map(int, input().split()) cnt = [[[0] * 21 for _ in (0, 1)] for _ in range(n + 1)] edges, mod = [[] for _ in range(n + 1)], 1000000007 for _ in range(n - 1): u, v = map(int, input().split()) edges[u].append(v) edges[v].append(u) def dfs(u, f): cnt[...
{ "input": [ "7 2\n1 2\n2 3\n1 4\n4 5\n1 6\n6 7\n", "4 1\n1 2\n2 3\n3 4\n", "2 0\n1 2\n", "2 1\n1 2\n" ], "output": [ "91\n", "9\n", "1\n", "3\n" ] }
783
10
Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters. Each club's full name consist of two wo...
from sys import stdin n = int(stdin.readline().strip()) T,A = [],[] N,M = {},{} for _ in range(n): t,h = stdin.readline().split() n1,n2 = t[:3],t[:2]+h[0] N[n1] = N.get(n1,0)+1 T.append((n1,n2)) A.append(n1) def solve(): for i in range(n): n1,n2 = T[i] if n1 not in M and N[n1]=...
{ "input": [ "3\nABC DEF\nABC EFG\nABD OOO\n", "2\nDINAMO BYTECITY\nFOOTBALL MOSCOW\n", "3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP\n", "2\nDINAMO BYTECITY\nDINAMO BITECITY\n" ], "output": [ "YES\nABD\nABE\nABO\n", "YES\nDIN\nFOO\n", "YES\nPLM\nPLS\nGOG\n", "NO\n" ...
784
7
A few years ago Sajjad left his school and register to another one due to security reasons. Now he wishes to find Amir, one of his schoolmates and good friends. There are n schools numerated from 1 to n. One can travel between each pair of them, to do so, he needs to buy a ticket. The ticker between schools i and j co...
def find(n): return (n + 1) // 2 - 1 print(find(int(input())))
{ "input": [ "10\n", "2\n" ], "output": [ "4\n", "0\n" ] }
785
10
Merge sort is a well-known sorting algorithm. The main function that sorts the elements of array a with indices from [l, r) can be implemented as follows: 1. If the segment [l, r) is already sorted in non-descending order (that is, for any i such that l ≀ i < r - 1 a[i] ≀ a[i + 1]), then end the function call; 2....
n,k=map(int,input().split()) if not k&1:exit(print(-1)) k-=1 a=[int(i+1) for i in range(n)] def f(l,r): global k if k<2or r-l<2:return k-=2 m=(l+r)//2 a[m],a[m-1]=a[m-1],a[m] f(l,m) f(m,r) f(0,n) if k:exit(print(-1)) for i in a: print(int(i),end=' ')
{ "input": [ "3 3\n", "5 6\n", "4 1\n" ], "output": [ "3 1 2 \n", "-1\n", "1 2 3 4 \n" ] }
786
9
Petya has n integers: 1, 2, 3, ..., n. He wants to split these integers in two non-empty groups in such a way that the absolute difference of sums of integers in each group is as small as possible. Help Petya to split the integers. Each of n integers should be exactly in one group. Input The first line contains a s...
def case_not_4(n): res = n*(n+1)//4 a = [] s = res i = n while (s != 0): if (s >= i): s -= i a.append(i) i -= 1 if (res*4 == n*(n+1)): print(0) else: print(1) print(len(a), end=' ') for i in a: print(i, end=' ') n = int(input()) case_not_4(n)
{ "input": [ "2\n", "4\n" ], "output": [ "1\n1 1", "0\n2 4 1\n" ] }
787
8
Alice and Bob begin their day with a quick game. They first choose a starting number X0 β‰₯ 3 and try to reach one million by the process described below. Alice goes first and then they take alternating turns. In the i-th turn, the player whose turn it is selects a prime number smaller than the current number, and anno...
from math import sqrt import sys # from io import StringIO # # sys.stdin = StringIO(open(__file__.replace('.py', '.in')).read()) def largest_prime_factor(n): for i in range(2, int(sqrt(n) + 1)): if n % i == 0: return largest_prime_factor(n // i) return n x2 = int(input()) p2 = largest_p...
{ "input": [ "8192\n", "20\n", "14\n" ], "output": [ "8191\n", "15\n", "6\n" ] }
788
8
You might have heard about the next game in Lara Croft series coming out this year. You also might have watched its trailer. Though you definitely missed the main idea about its plot, so let me lift the veil of secrecy. Lara is going to explore yet another dangerous dungeon. Game designers decided to use good old 2D e...
def inpmap(): return list(map(int, input().split())) n, m, k = inpmap() if k < n: print(k + 1, 1) else: k -= n a, b = divmod(k, (m - 1)) print(n - a, m - b if a % 2 else b + 2)
{ "input": [ "4 3 0\n", "4 3 7\n", "4 3 11\n" ], "output": [ "1 1\n", "3 2\n", "1 2\n" ] }
789
9
Recently Vasya found a golden ticket β€” a sequence which consists of n digits a_1a_2... a_n. Vasya considers a ticket to be lucky if it can be divided into two or more non-intersecting segments with equal sums. For example, ticket 350178 is lucky since it can be divided into three segments 350, 17 and 8: 3+5+0=1+7=8. No...
def check(i): s = 0 for x in b: s += x if s == i: s = 0 if s == 0: return True return False a = int(input()) b = [int(i) for i in list(input())] for i in range(max(1, sum(b))): if check(i): print("YES") break else: print("NO")
{ "input": [ "4\n1248\n", "5\n73452\n" ], "output": [ "NO\n", "YES\n" ] }
790
7
Vasya has got three integers n, m and k. He'd like to find three integer points (x_1, y_1), (x_2, y_2), (x_3, y_3), such that 0 ≀ x_1, x_2, x_3 ≀ n, 0 ≀ y_1, y_2, y_3 ≀ m and the area of the triangle formed by these points is equal to nm/k. Help Vasya! Find such points (if it's possible). If there are multiple solutio...
def gcd(a, b): while b: a, b = b, a % b return a n, m, k = map(int, input().split()) if n*m*2 % k: print("NO") else: print("YES") g1 = gcd(n, k) n //= g1 k //= g1 g2 = gcd(m, k) m //= g2 k //= g2 if k == 1: if g1 == 1: m *= 2 else: n *= 2 print('0 0') print('0', m) print(n, '0')
{ "input": [ "4 4 7\n", "4 3 3\n" ], "output": [ "NO\n", "YES\n0 0\n4 0\n0 2\n" ] }
791
8
Palo Alto is an unusual city because it is an endless coordinate line. It is also known for the office of Lyft Level 5. Lyft has become so popular so that it is now used by all m taxi drivers in the city, who every day transport the rest of the city residents β€” n riders. Each resident (including taxi drivers) of Palo...
n,m=map(int,input().split()) a=list(map(int,input().split())) b=list(map(int,input().split())) def next(k,a): i=k+1 while a[i]!=1: i+=1 return i ans=[0]*(m+1) k=-1 k=next(k,b) ans[1]=k for i in range(2,m+1): kk=next(k,b) for j in range(k+1,kk): if a[j]-a[k]<=a[kk]-a[j]: ans[i-...
{ "input": [ "1 4\n2 4 6 10 15\n1 1 1 1 0\n", "3 2\n2 3 4 5 6\n1 0 0 0 1\n", "3 1\n1 2 3 10\n0 0 1 0\n" ], "output": [ "0 0 0 1\n", "2 1\n", "3\n" ] }
792
9
You are given an angle ang. The Jury asks You to find such regular n-gon (regular polygon with n vertices) that it has three vertices a, b and c (they can be non-consecutive) with \angle{abc} = ang or report that there is no such n-gon. <image> If there are several answers, print the minimal one. It is guarantied t...
import math def C(): T = int(input()) for i in range(T): angle = int(input()) d = math.gcd(180,angle) if(angle + d >= 180): print(2*180// d) continue print(180//d) C()
{ "input": [ "4\n54\n50\n2\n178\n" ], "output": [ "10\n18\n90\n180\n" ] }
793
10
Reziba has many magic gems. Each magic gem can be split into M normal gems. The amount of space each magic (and normal) gem takes is 1 unit. A normal gem cannot be split. Reziba wants to choose a set of magic gems and split some of them, so the total space occupied by the resulting set of gems is N units. If a magic g...
import sys MOD = 10**9+7 # Polymod def polymod(P,Q): assert(Q[-1]==1) n = len(Q) while len(P)>=n: p = P[-1] for i in range(n): P[-i-1] -= p*Q[-i-1] assert(P[-1]==0) P.pop() return P def polyprod(P,Q): n = len(P) m = len(Q) W = [0]*(n+m-1) fo...
{ "input": [ "3 2\n", "4 2\n" ], "output": [ "3\n", "5\n" ] }
794
12
Recently Vasya learned that, given two points with different x coordinates, you can draw through them exactly one parabola with equation of type y = x^2 + bx + c, where b and c are reals. Let's call such a parabola an U-shaped one. Vasya drew several distinct points with integer coordinates on a plane and then drew an...
import sys def cross(o, a, b): return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]) N = int(input()) A = [None]*N for i in range(N): x, y = map(int, sys.stdin.readline().split()) A[i] = (x, y-x*x) A.sort() upper = [] for p in reversed(A): while len(upper) >= 2 and cross(upper[-2], upper...
{ "input": [ "3\n-1 0\n0 2\n1 0\n", "5\n1 0\n1 -1\n0 -1\n-1 0\n-1 -1\n" ], "output": [ "2\n", "1\n" ] }
795
11
Kuro has just learned about permutations and he is really excited to create a new permutation type. He has chosen n distinct positive integers and put all of them in a set S. Now he defines a magical permutation to be: * A permutation of integers from 0 to 2^x - 1, where x is a non-negative integer. * The [bitwis...
def size(k): return int(math.log2(k)) def v2(k): if k%2==1: return 0 else: return 1+v2(k//2) n=int(input()) s=list(map(int,input().split())) import math s.sort() used=[] use=0 found={0:1} good=0 for guy in s: big=size(guy) if guy not in found: used.append(guy) use+=1 ...
{ "input": [ "1\n1\n", "1\n20\n", "2\n2 4\n", "3\n1 2 3\n", "2\n2 3\n", "4\n1 2 3 4\n" ], "output": [ "1\n0 1 ", "0 \n0", "0 \n0", "2\n0 1 3 2 ", "2\n0 2 1 3 ", "3\n0 1 3 2 6 7 5 4 " ] }
796
8
Heidi and Doctor Who hopped out of the TARDIS and found themselves at EPFL in 2018. They were surrounded by stormtroopers and Darth Vader was approaching. Miraculously, they managed to escape to a nearby rebel base but the Doctor was very confused. Heidi reminded him that last year's HC2 theme was Star Wars. Now he und...
s, b = map(int, input().split()) a = list(map(int, input().split())) z = [[-1, 0]] + sorted(list(map(int, input().split())) for _ in range(b)) for i in range(1, b+1): z[i][1] += z[i-1][1] v = [p[0] for p in z] def binary_search(v, x): l, r = 0, len(v)-1 while l <= r: m = l+r >> 1 if v[m] > ...
{ "input": [ "5 4\n1 3 5 2 4\n0 1\n4 2\n2 8\n9 4\n" ], "output": [ "1 9 11 9 11 " ] }
797
7
You are given two binary strings x and y, which are binary representations of some two integers (let's denote these integers as f(x) and f(y)). You can choose any integer k β‰₯ 0, calculate the expression s_k = f(x) + f(y) β‹… 2^k and write the binary representation of s_k in reverse order (let's denote it as rev_k). For e...
def solve(): x = input() y = input().rjust(len(x), '0') j = y.rfind('1') i = x.rfind('1', 0, j + 1) print(j - i) for _ in range(int(input())): solve()
{ "input": [ "4\n1010\n11\n10001\n110\n1\n1\n1010101010101\n11110000\n" ], "output": [ "1\n3\n0\n0\n" ] }
798
7
Tomorrow is a difficult day for Polycarp: he has to attend a lectures and b practical classes at the university! Since Polycarp is a diligent student, he is going to attend all of them. While preparing for the university, Polycarp wonders whether he can take enough writing implements to write all of the lectures and d...
def ceil(x, y): return x // y + bool(x % y) for _ in range(int(input())): a, b, c, d, k = map(int, input().split()) u, v = ceil(a, c), ceil(b, d) if u + v > k: print('-1') else: print(u, v)
{ "input": [ "3\n7 5 4 5 8\n7 5 4 5 2\n20 53 45 26 4\n" ], "output": [ "2 1\n-1\n1 3\n" ] }
799
11
The development of a text editor is a hard problem. You need to implement an extra module for brackets coloring in text. Your editor consists of a line with infinite length and cursor, which points to the current character. Please note that it points to only one of the characters (and not between a pair of characters)...
import traceback def push(stack, delta): if stack: _, d, mn, mx = stack[-1] else: d, mn, mx = 0, 0, 0 stack.append((delta, d + delta, min(d + delta, mn), max(d + delta, mx))) def main(): n = int(input()) ss = input() left = [(0, 0,0,0)] right = [(0, 0,0,0)] * n res = []...
{ "input": [ "11\n(R)R(R)Ra)c\n", "11\n(RaRbR)L)L(\n" ], "output": [ "-1 -1 1 1 -1 -1 1 1 1 -1 1 ", "-1 -1 -1 -1 -1 -1 1 1 -1 -1 2 " ] }