index
int64
0
5.16k
difficulty
int64
7
12
question
stringlengths
126
7.12k
solution
stringlengths
30
18.6k
test_cases
dict
900
8
Vasya lives in a strange world. The year has n months and the i-th month has ai days. Vasya got a New Year present — the clock that shows not only the time, but also the date. The clock's face can display any number from 1 to d. It is guaranteed that ai ≤ d for all i from 1 to n. The clock does not keep information ab...
def ii(): return int(input()) def mi(): return map(int, input().split()) def li(): return list(mi()) d = ii() n = ii() a = li() su= 0 for i in range(n-1): su+=(abs(a[i]-d)) print(su)
{ "input": [ "31\n12\n31 28 31 30 31 30 31 31 30 31 30 31\n", "5\n3\n3 4 3\n", "4\n2\n2 2\n" ], "output": [ "7", "3", "2" ] }
901
10
The Little Elephant loves to play with color cards. He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks...
def main(): n = int(input()) d = {} for i in range(n): a, b = [int(i) for i in input().split()] if a == b: if a not in d: d[a] = [0, 0] d[a][0] += 1 else: if a not in d: d[a] = [0, 0] d[a][0...
{ "input": [ "3\n4 7\n4 7\n7 4\n", "5\n4 7\n7 4\n2 11\n9 7\n1 1\n" ], "output": [ "0\n", "2\n" ] }
902
9
Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of se...
def _print(v, n): for i in range(1, n + 1): if v != i: print(i," ",v) n, m, v = map(int,input().split()) l = (n - 1) * (n - 2) div = 2 + 1 if m < n - 1 or m > l//2+1: print(-1) exit() k = n - 1 if n == v: n -= 1 _print(v, n) x, y = 1, 1 while k != m: if x == n - 1: ...
{ "input": [ "5 6 3\n", "6 100 1\n" ], "output": [ "3 1\n3 2\n3 4\n3 5\n2 4\n2 5\n", "-1\n" ] }
903
8
Little Vitaly loves different algorithms. Today he has invented a new algorithm just for you. Vitaly's algorithm works with string s, consisting of characters "x" and "y", and uses two following operations at runtime: 1. Find two consecutive characters in the string, such that the first of them equals "y", and the s...
def main(): stack = [] for c in input(): if stack and stack[-1] != c: del stack[-1] else: stack.append(c) print(''.join(reversed(stack))) if __name__ == '__main__': main()
{ "input": [ "x\n", "yxyxy\n", "xxxxxy\n" ], "output": [ "x", "y", "xxxx" ] }
904
8
When Valera has got some free time, he goes to the library to read some books. Today he's got t free minutes to read. That's why Valera took n books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to n. Valera needs ai minutes to read the ...
def bs(a,t): d=0 c=0 for i in range(len(a)): d+=a[i] if d>t: d-=a[c] c+=1 return len(a)-c n,t=map(int,input().split()) a=[int(i) for i in input().split()] print(bs(a,t))
{ "input": [ "4 5\n3 1 2 1\n", "3 3\n2 2 3\n" ], "output": [ "3\n", "1\n" ] }
905
7
Yaroslav has an array, consisting of (2·n - 1) integers. In a single operation Yaroslav can change the sign of exactly n elements in the array. In other words, in one operation Yaroslav can select exactly n array elements, and multiply each of them by -1. Yaroslav is now wondering: what maximum sum of array elements c...
def main(): n = int(input()) l = list(map(int, input().split())) res = sum(map(abs, l)) if not n & 1 and sum(x < 0 for x in l) & 1: res -= abs(min(l, key=abs)) * 2 print(res) if __name__ == '__main__': main()
{ "input": [ "2\n-1 -100 -1\n", "2\n50 50 50\n" ], "output": [ "100\n", "150\n" ] }
906
10
After too much playing on paper, Iahub has switched to computer games. The game he plays is called "Block Towers". It is played in a rectangular grid with n rows and m columns (it contains n × m cells). The goal of the game is to build your own city. Some cells in the grid are big holes, where Iahub can't build any bui...
#Connected component import sys from collections import deque sys.setrecursionlimit(501 * 501) n,m = [int(i) for i in input().split()] a=[[0 for i in range(m)] for i in range(n)] d=[(0,1),(0,-1),(1,0),(-1,0)] q=deque() def main(): global a ans=[] first=[] q=deque() for i in range(n): l...
{ "input": [ "1 3\n...\n", "2 3\n..#\n.#.\n" ], "output": [ "7\nB 1 1\nB 1 2\nB 1 3\nD 1 3\nR 1 3\nD 1 2\nR 1 2\n", "8\nB 1 1\nB 2 1\nD 2 1\nR 2 1\nB 1 2\nD 1 2\nR 1 2\nB 2 3\n" ] }
907
7
Cucumber boy is fan of Kyubeat, a famous music game. Kyubeat has 16 panels for playing arranged in 4 × 4 table. When a panel lights up, he has to press that panel. Each panel has a timing to press (the preffered time when a player should press it), and Cucumber boy is able to press at most k panels in a time with his...
k=int(input()) b={} for i in range(4): s=input() for i in s: if i in b:b[i]+=1 else:b[i]=1 def fn(b): for i in b: if i!='.' and b[i]>2*k:return 'NO' return 'YES' print(fn(b))
{ "input": [ "5\n..1.\n1111\n..1.\n..1.\n", "1\n.135\n1247\n3468\n5789\n", "1\n....\n12.1\n.2..\n.2..\n" ], "output": [ "YES\n", "YES\n", "NO\n" ] }
908
9
During the break, we decided to relax and play dominoes. Our box with Domino was empty, so we decided to borrow the teacher's dominoes. The teacher responded instantly at our request. He put nm dominoes on the table as an n × 2m rectangle so that each of the n rows contained m dominoes arranged horizontally. Each half...
def find_matrix_col_sum(mat): max_sum = -1 for cols in range(len(mat[0])): s = 0 for i in range(2): for rows in range(len(mat)): s+=int(mat[rows][cols][i]) if s > max_sum: max_sum = s return max_sum n,m=input().split() n,m=int(n), int...
{ "input": [ "4 1\n11\n10\n01\n00\n", "2 3\n01 11 00\n00 01 11\n" ], "output": [ "11 \n10 \n01 \n00 \n", "11 11 10 \n00 00 01 \n" ] }
909
9
You've got array a[1], a[2], ..., a[n], consisting of n integers. Count the number of ways to split all the elements of the array into three contiguous parts so that the sum of elements in each part is the same. More formally, you need to find the number of such pairs of indices i, j (2 ≤ i ≤ j ≤ n - 1), that <image>...
def main(): n = int(input()) l = list(map(int,input().split())) s=0 for x in l: s+=x if s%3!=0: print(0) else: s//=3 su=0 k=0 ans=0 l.pop() for x in l: su+=x if su==2*s: ans+=k if su==s: k+=1 print(ans) if __name__ == '__main__': main()
{ "input": [ "2\n4 1\n", "4\n0 1 -1 0\n", "5\n1 2 3 0 3\n" ], "output": [ "0\n", "1\n", "2\n" ] }
910
7
Uncle Fyodor, Matroskin the Cat and Sharic the Dog live their simple but happy lives in Prostokvashino. Sometimes they receive parcels from Uncle Fyodor’s parents and sometimes from anonymous benefactors, in which case it is hard to determine to which one of them the package has been sent. A photographic rifle is obvio...
f = input() m = input() s = input() def win(x, y): return (x == 'rock' and y == 'scissors') or (x == 'scissors' and y == 'paper') or (x == 'paper' and y == 'rock') if win(f, m) and win(f, s): print("F") elif win(m, f) and win(m, s): print("M") elif win(s, f) and win(s, m): print("S") else: print("?")
{ "input": [ "scissors\nrock\nrock\n", "scissors\npaper\nrock\n", "rock\nrock\nrock\n", "paper\nrock\nrock\n" ], "output": [ "?\n", "?\n", "?\n", "F\n" ] }
911
7
All cities of Lineland are located on the Ox coordinate axis. Thus, each city is associated with its position xi — a coordinate on the Ox axis. No two cities are located at a single point. Lineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another city (bec...
def call(i,a): print(min(abs(a[i]-a[i-1]),abs(a[i]-a[i+1])),max(abs(a[i]-a[0]),abs(a[i]-a[n-1]))) n=int(input()) a=list(map(int,input().split())) print(abs(a[0]-a[1]),abs(a[0]-a[n-1])) for i in range(1,n-1): call(i,a) print(abs(a[n-2]-a[n-1]),abs(a[n-1]-a[0]))
{ "input": [ "2\n-1 1\n", "4\n-5 -2 2 7\n" ], "output": [ "2 2\n2 2\n", "3 12\n3 9\n4 7\n5 12\n" ] }
912
9
Recently, Duff has been practicing weight lifting. As a hard practice, Malek gave her a task. He gave her a sequence of weights. Weight of i-th of them is 2wi pounds. In each step, Duff can lift some of the remaining weights and throw them away. She does this until there's no more weight left. Malek asked her to minimi...
def inc(a,w): n=len(a) i=w while(i<n and a[i]==1): a[i]=0 i+=1 if(i<n): a[i]=1 else: a.append(1) n=int(input()) x=input().split(' ') w=[int(y) for y in x] a=[0]*1000024 for t in w: inc(a,t) print(sum(a))
{ "input": [ "5\n1 1 2 3 3\n", "4\n0 1 2 3\n" ], "output": [ "2\n", "4\n" ] }
913
11
Once upon a time in the thicket of the mushroom forest lived mushroom gnomes. They were famous among their neighbors for their magic mushrooms. Their magic nature made it possible that between every two neighboring mushrooms every minute grew another mushroom with the weight equal to the sum of weights of two neighbori...
#!/usr/bin/pypy3 from sys import stdin, stdout input, print = stdin.readline, stdout.write p = 0 def readints(): return list(map(int, input().split())) def writeln(x): print(str(x) + '\n') def mod(x): return (x % p + p) % p def matmul(a, b): n = len(a) c = [[0 for x in range(n)] for y in range(n...
{ "input": [ "2 1 0 657276545\n1 2\n", "4 5 0 10000\n1 2 3 4\n", "2 1 1 888450282\n1 2\n" ], "output": [ "6", "1825", "14" ] }
914
8
Very soon Berland will hold a School Team Programming Olympiad. From each of the m Berland regions a team of two people is invited to participate in the olympiad. The qualifying contest to form teams was held and it was attended by n Berland students. There were at least two schoolboys participating from each of the m ...
def cmp(x): return x[1] n,m=map(int,input().split()) q=[[] for i in range(m)] for i in range(n): name,r,b=input().split() q[int(r)-1].append([name,int(b)]) for i in q: i=sorted(i,key=cmp) if len(i)==2: print(i[-1][0],i[-2][0]) elif i[-1][1]==i[-2][1]==i[-3][1] or i[-2][1]==i[-3][1]: print('?') e...
{ "input": [ "5 2\nIvanov 1 763\nAndreev 2 800\nPetrov 1 595\nSidorov 1 790\nSemenov 2 503\n", "5 2\nIvanov 1 800\nAndreev 2 763\nPetrov 1 800\nSidorov 1 800\nSemenov 2 503\n" ], "output": [ "Sidorov Ivanov\nAndreev Semenov\n", "?\nAndreev Semenov\n" ] }
915
10
Sasha lives in a big happy family. At the Man's Day all the men of the family gather to celebrate it following their own traditions. There are n men in Sasha's family, so let's number them with integers from 1 to n. Each man has at most one father but may have arbitrary number of sons. Man number A is considered to b...
n, m = map(int, input().split()) adj = [[] for _ in range(n)] cp = [-1] * n for i in range(m): p, c = map(int, input().split()) adj[p - 1].append(c - 1) cp[c - 1] = p - 1 pres = [i - 1 for i in map(int, input().split())] level = [0] * n from collections import deque def bfs(v): q = deque([v]) whi...
{ "input": [ "3 2\n1 2\n2 3\n1 2 1\n", "4 2\n1 2\n3 4\n1 2 3 3\n" ], "output": [ "-1\n", "3\n2\n1\n3\n" ] }
916
7
Vasily has a number a, which he wants to turn into a number b. For this purpose, he can do two types of operations: * multiply the current number by 2 (that is, replace the number x by 2·x); * append the digit 1 to the right of current number (that is, replace the number x by 10·x + 1). You need to help Vasil...
def reach(a, b, path=[]): if a > b: return if a == b: path.append(a) print("YES") print(len(path)) print(*path) exit(0) reach(a*2,b,path+[a]) reach(a*10+1,b,path+[a]) a,b=map(int,input().split()) reach(a,b,[]) print("NO")
{ "input": [ "4 42\n", "2 162\n", "100 40021\n" ], "output": [ "NO\n", "YES\n5\n2 4 8 81 162 \n", "YES\n5\n100 200 2001 4002 40021 \n" ] }
917
8
Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be. ...
def solve(s, t): n=len(s) M={} for i in range(n): if M.get(s[i], t[i])!=t[i] or M.get(t[i], s[i])!=s[i]: return -1 M[ s[i] ]=t[i] M[ t[i] ]=s[i] return M M=solve(input(), input()) if M==-1: print(-1) else: M=list((c, M[c]) for c in M if c<M[c]) print(len(M)) for x in M: print(*x)
{ "input": [ "helloworld\nehoolwlroz\n", "hastalavistababy\nhastalavistababy\n", "merrychristmas\nchristmasmerry\n" ], "output": [ "3\nh e\nl o\nd z\n", "0\n", "-1\n" ] }
918
7
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures). There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves. Let A-B denote that membe...
from collections import Counter as cntr from math import inf def cin(): return map(int, input().split(' ')) def dfs(graph, src, n): q = [src] h = 0 global visited edges = 0 while q: idx = q.pop() h += 1 for v in graph[idx]: edges += 1 if visited[v] == False: visited[v] = True q.append(v) ret...
{ "input": [ "10 4\n4 3\n5 10\n8 9\n1 2\n", "4 4\n3 1\n2 3\n3 4\n1 2\n", "3 2\n1 2\n2 3\n", "4 3\n1 3\n3 4\n1 4\n" ], "output": [ "YES\n", "NO\n", "NO\n", "YES\n" ] }
919
7
Zane the wizard had never loved anyone before, until he fell in love with a girl, whose name remains unknown to us. <image> The girl lives in house m of a village. There are n houses in that village, lining in a straight line from left to right: house 1, house 2, ..., house n. The village is also well-structured: hou...
n, m, k = [int(x) for x in input().split()] ls = [int(x) for x in input().split()] dp = [] def dist(f, t): return abs((t-f)*10) for i in range(0,n): if ls[i] != 0 and ls[i] <= k: dp.append(dist(m-1,i)) else: dp.append(1000) print(min(dp))
{ "input": [ "10 5 100\n1 0 1 0 0 0 0 0 1 1\n", "5 1 20\n0 27 32 21 19\n", "7 3 50\n62 0 0 0 99 33 22\n" ], "output": [ "20", "40", "30" ] }
920
8
To stay woke and attentive during classes, Karen needs some coffee! <image> Karen, a coffee aficionado, wants to know the optimal temperature for brewing the perfect cup of coffee. Indeed, she has spent some time reading several recipe books, including the universally acclaimed "The Art of the Covfefe". She knows n ...
import io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline def pref_sum(s): t = 0 for i in range(200002): t += s[i] s[i] = t n, k, q = map(int, input().split()) s = [0]*(200002) for _ in range(n): l, r = map(int, input().split()) s[l] += 1 s[r+1] -= 1 pref_sum(s) for i in range(200002): s[...
{ "input": [ "3 2 4\n91 94\n92 97\n97 99\n92 94\n93 97\n95 96\n90 100\n", "2 1 1\n1 1\n200000 200000\n90 100\n" ], "output": [ "3\n3\n0\n4\n", "0\n" ] }
921
8
Leha somehow found an array consisting of n integers. Looking at it, he came up with a task. Two players play the game on the array. Players move one by one. The first player can choose for his move a subsegment of non-zero length with an odd sum of numbers and remove it from the array, after that the remaining parts a...
def f(l): return 'First' if sum([i%2>0 for i in l])>0 else 'Second' _ = input() l = list(map(int,input().split())) print(f(l))
{ "input": [ "4\n1 3 2 3\n", "2\n2 2\n" ], "output": [ "First\n", "Second\n" ] }
922
9
Mahmoud and Ehab are on the third stage of their adventures now. As you know, Dr. Evil likes sets. This time he won't show them any set from his large collection, but will ask them to create a new set to replenish his beautiful collection of sets. Dr. Evil has his favorite evil integer x. He asks Mahmoud and Ehab to f...
def list_input(): return list(map(int,input().split())) def map_input(): return map(int,input().split()) def map_string(): return input().split() from random import randint n,x = map_input() if n == 2 and x == 0: print("NO") else: while True: s = set([]) a = [] cnt = 0 for i in range(n-1...
{ "input": [ "3 6\n", "5 5\n" ], "output": [ "YES\n0 131072 131078\n", "YES\n1 2 0 131072 131078\n" ] }
923
7
You are given an array a. Some element of this array ai is a local minimum iff it is strictly less than both of its neighbours (that is, ai < ai - 1 and ai < ai + 1). Also the element can be called local maximum iff it is strictly greater than its neighbours (that is, ai > ai - 1 and ai > ai + 1). Since a1 and an have ...
def le(v,n): t=0 for c in range(1,n-1): if v[c-1]<v[c]>v[c+1] or v[c-1]>v[c]<v[c+1]: t+=1 return t n=int(input()) v=[int(c) for c in input().split()] print(le(v,n))
{ "input": [ "3\n1 2 3\n", "4\n1 5 2 5\n" ], "output": [ "0\n", "2\n" ] }
924
8
Petya has equal wooden bars of length n. He wants to make a frame for two equal doors. Each frame has two vertical (left and right) sides of length a and one top side of length b. A solid (i.e. continuous without breaks) piece of bar is needed for each side. Determine a minimal number of wooden bars which are needed t...
def check(n,a,b,vertical,upper,bar,bars): if vertical==0 and upper==0: bars[bar-1]=True return for i in range(vertical+1): for j in range(upper+1): if i+j>0 and i*a+j*b<=n: check(n,a,b,vertical-i,upper-j,bar+1,bars) n=int(input()) a=int(input()) b=int(input()) bars=[False]*6 check(n,a,b,4,2,0,bars) for...
{ "input": [ "6\n4\n2\n", "5\n3\n4\n", "8\n1\n2\n", "20\n5\n6\n" ], "output": [ "4", "6", "1", "2" ] }
925
11
Ehab is interested in the bitwise-xor operation and the special graphs. Mahmoud gave him a problem that combines both. He has a complete graph consisting of n vertices numbered from 0 to n - 1. For all 0 ≤ u < v < n, vertex u and vertex v are connected with an undirected edge that has weight <image> (where <image> is t...
a = int(input()) def ans(n, p=1): return ans( (n+1) // 2, p*2 ) + (n//2)*p if n > 1 else 0 print (ans(a))
{ "input": [ "4\n" ], "output": [ "4\n" ] }
926
9
You are given a set of size m with integer elements between 0 and 2^{n}-1 inclusive. Let's build an undirected graph on these integers in the following way: connect two integers x and y with an edge if and only if x \& y = 0. Here \& is the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). C...
n, m = map(int, input().split()) a = set(map(int, input().split())) y = 2 ** n mk = [0] * (2 * y) cur = 0 for x in a: if mk[x]: continue mk[x] = 1 st = [x] def push(v): if not mk[v]: mk[v] = 1; st.append(v) while st: u = st.pop() if u < y: push(y + u) els...
{ "input": [ "2 3\n1 2 3\n", "5 5\n5 19 10 20 12\n" ], "output": [ "2\n", "2\n" ] }
927
12
There is a rectangular grid of size n × m. Each cell has a number written on it; the number on the cell (i, j) is a_{i, j}. Your task is to calculate the number of paths from the upper-left cell (1, 1) to the bottom-right cell (n, m) meeting the following constraints: * You can move to the right or to the bottom onl...
n, m, k = map(int, input().split()) l = [list(map(int, input().split())) for _ in range(n)] re = 0 half = (m + n - 2) // 2 d = [dict() for _ in range(22)] def forward(i, j, value): if i >= n or j >= m: return value ^= l[i][j] if i + j == half: if value in d[i]: d[i][value] += 1...
{ "input": [ "3 4 1000000000000000000\n1 3 3 3\n0 3 3 2\n3 0 1 1\n", "3 3 11\n2 1 5\n7 10 0\n12 6 4\n", "3 4 2\n1 3 3 3\n0 3 3 2\n3 0 1 1\n" ], "output": [ "0\n", "3\n", "5\n" ] }
928
11
Vasya owns three big integers — a, l, r. Let's define a partition of x such a sequence of strings s_1, s_2, ..., s_k that s_1 + s_2 + ... + s_k = x, where + is a concatanation of strings. s_i is the i-th element of the partition. For example, number 12345 has the following partitions: ["1", "2", "3", "4", "5"], ["123",...
def kmp(pat,text,t): s=pat+"?"+text; #z[i] es el tamaño del prefijo mas largo de, formado por una subcadena s[i:...] z=[0 for i in range(len(s))] L=0;R=0;n=len(s); for i in range(1,len(s)): if i>R: L=R=i while R<n and s[R-L]==s[R]: R+=1 z[i...
{ "input": [ "135\n1\n15\n", "10000\n0\n9\n" ], "output": [ "2", "1" ] }
929
12
You are given an undirected unweighted tree consisting of n vertices. An undirected tree is a connected undirected graph with n - 1 edges. Your task is to choose two pairs of vertices of this tree (all the chosen vertices should be distinct) (x_1, y_1) and (x_2, y_2) in such a way that neither x_1 nor y_1 belong to t...
import sys n = int(sys.stdin.readline()) edges = [[] for _ in range(n)] for _ in range(n - 1): i, j = tuple(int(k) for k in sys.stdin.readline().split()) i -= 1 j -= 1 edges[i].append(j) edges[j].append(i) # Prunes the graph starting from the vertices with # only 1 edge until we reach a vertex wit...
{ "input": [ "9\n9 3\n3 5\n1 2\n4 3\n4 7\n1 7\n4 6\n3 8\n", "10\n6 8\n10 3\n3 7\n5 8\n1 7\n7 2\n2 9\n2 8\n1 4\n", "11\n1 2\n2 3\n3 4\n1 5\n1 6\n6 7\n5 8\n5 9\n4 10\n4 11\n", "7\n1 4\n1 5\n1 6\n2 3\n2 4\n4 7\n" ], "output": [ "8 2\n5 6\n", "10 6\n4 5\n", "11 9\n10 8\n", "3 6\n7 5\n"...
930
12
You are given an undirected graph consisting of n vertices. A number is written on each vertex; the number on vertex i is a_i. Initially there are no edges in the graph. You may add some edges to this graph, but you have to pay for them. The cost of adding an edge between vertices x and y is a_x + a_y coins. There are...
import sys input = sys.stdin.readline n,m=map(int,input().split()) A=list(map(int,input().split())) SP=[list(map(int,input().split())) for i in range(m)] MIN=min(A) x=A.index(MIN) EDGE_x=[[x+1,i+1,A[x]+A[i]] for i in range(n) if x!=i] EDGE=EDGE_x+SP EDGE.sort(key=lambda x:x[2]) #UnionFind Group=[i for i in range...
{ "input": [ "5 4\n1 2 3 4 5\n1 2 8\n1 3 10\n1 4 7\n1 5 15\n", "3 2\n1 3 3\n2 3 5\n2 1 1\n", "4 0\n1 3 3 7\n" ], "output": [ "18\n", "5\n", "16\n" ] }
931
7
You are given array a_1, a_2, ..., a_n. Find the subsegment a_l, a_{l+1}, ..., a_r (1 ≤ l ≤ r ≤ n) with maximum arithmetic mean (1)/(r - l + 1)∑_{i=l}^{r}{a_i} (in floating-point numbers, i.e. without any rounding). If there are many such subsegments find the longest one. Input The first line contains single integer...
def inpl(): return list(map(int, input().split())) N = int(input()) A = inpl() + [-1] x = max(A) ctr = 0 ans = 0 for a in A: if a == x: ctr += 1 else: ans = max(ans, ctr) ctr = 0 print(ans)
{ "input": [ "5\n6 1 6 6 0\n" ], "output": [ "2\n" ] }
932
9
You are given a rooted tree with vertices numerated from 1 to n. A tree is a connected graph without cycles. A rooted tree has a special vertex named root. Ancestors of the vertex i are all vertices on the path from the root to the vertex i, except the vertex i itself. The parent of the vertex i is the nearest to the ...
import sys def input(): return sys.stdin.buffer.readline().strip() n=int(input()) notremove = [0]*(n+1) for i in range(1,n+1): p,c = map(int,input().split()) if(c==0): notremove[i] = 1 if(p>0): notremove[p] = 1 check=0 for i in range(1,n+1): if(notremove[i]==0): ch...
{ "input": [ "5\n3 1\n1 1\n-1 0\n2 1\n3 0\n", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0\n", "5\n-1 0\n1 1\n1 1\n2 0\n3 0\n" ], "output": [ "1 2 4\n", "5\n", "-1\n" ] }
933
9
This problem is same as the next one, but has smaller constraints. It was a Sunday morning when the three friends Selena, Shiro and Katie decided to have a trip to the nearby power station (do not try this at home). After arriving at the power station, the cats got impressed with a large power transmission system cons...
def gcd(x,y): while y: x,y=y,x%y return x def frac(a,b): x=gcd(a,b) return (a//x,b//x) n=int(input()) coords=[] for i in range(n): coords.append(tuple(map(int,input().split()))) slopes={} for i in range(n): for j in range(i+1,n): x1,y1=coords[i][0],coords[i][1] x2,y2=coor...
{ "input": [ "4\n0 0\n1 1\n0 3\n1 2\n", "4\n0 0\n0 2\n0 4\n2 0\n", "3\n-1 -1\n1 0\n3 1\n" ], "output": [ "14\n", "6\n", "0\n" ] }
934
7
Melody Pond was stolen from her parents as a newborn baby by Madame Kovarian, to become a weapon of the Silence in their crusade against the Doctor. Madame Kovarian changed Melody's name to River Song, giving her a new identity that allowed her to kill the Eleventh Doctor. Heidi figured out that Madame Kovarian uses a...
def f(n): return ['NO'] if (n%2==0 or n<5) else [1,((n-3)//2)] n = int(input()) print(*f(n))
{ "input": [ "19\n", "16\n" ], "output": [ "1 8\n", "NO\n" ] }
935
10
You are on the island which can be represented as a n × m table. The rows are numbered from 1 to n and the columns are numbered from 1 to m. There are k treasures on the island, the i-th of them is located at the position (r_i, c_i). Initially you stand at the lower left corner of the island, at the position (1, 1). I...
from bisect import bisect_left n, m, k, q = map(int, input().split()) x = sorted(list(map(int, input().split())) for _ in range(k)) y = sorted(map(int, input().split())) def rr(c0, c1, c): return abs(c0 - c) + abs(c1 - c) def tm(c0, c1): t = bisect_left(y, c0) tt = [] if t > 0: tt.append(r...
{ "input": [ "3 6 3 2\n1 6\n2 2\n3 4\n1 6\n", "3 3 3 2\n1 1\n2 1\n3 1\n2 3\n", "3 5 3 2\n1 2\n2 3\n3 1\n1 5\n" ], "output": [ "15\n", "6\n", "8\n" ] }
936
9
Alice became interested in periods of integer numbers. We say positive X integer number is periodic with length L if there exists positive integer number P with L digits such that X can be written as PPPP…P. For example: X = 123123123 is periodic number with length L = 3 and L = 9 X = 42424242 is periodic number with...
l = int(input()) xs = input() def run(): if len(xs)%l != 0: d = len(xs)//l+1 ans = ('1'+'0'*(l-1))*d return ans d = len(xs) // l prf = xs[:l] tl = prf*d if tl > xs: return tl if prf == '9'*l: return ('1'+'0'*(l-1))*(d+1) return str(...
{ "input": [ "3\n12345\n", "3\n123456\n" ], "output": [ "100100", "124124" ] }
937
9
Ujan has been lazy lately, but now has decided to bring his yard to good shape. First, he decided to paint the path from his house to the gate. The path consists of n consecutive tiles, numbered from 1 to n. Ujan will paint each tile in some color. He will consider the path aesthetic if for any two different tiles wit...
def mdc( a, b ): if ( b == 0 ): return a return mdc(b, a % b) n = int(input()) a = n for i in range(2, int(n ** .5) + 1): if ( n % i == 0 ): a = mdc(a, i) a = mdc(a, n // i) print(a)
{ "input": [ "5\n", "4\n" ], "output": [ "5\n", "2\n" ] }
938
8
A PIN code is a string that consists of exactly 4 digits. Examples of possible PIN codes: 7013, 0000 and 0990. Please note that the PIN code can begin with any digit, even with 0. Polycarp has n (2 ≤ n ≤ 10) bank cards, the PIN code of the i-th card is p_i. Polycarp has recently read a recommendation that it is bette...
def solve(): n = int(input()) num = [] for i in range(n): ss = input() num.append(ss) cnt = 0 for i in range(n): if (num[i] in num[i+1:]): cnt += 1 j = 0 while (num[i] in num[:i] + num[i+1:]): num[i] = num[i][:3] + str(j) ...
{ "input": [ "3\n2\n1234\n0600\n2\n1337\n1337\n4\n3139\n3139\n3139\n3139\n" ], "output": [ "0\n1234\n0600\n1\n1337\n0337\n3\n3139\n0139\n1139\n2139\n" ] }
939
7
You are given two positive integers a and b. In one move you can increase a by 1 (replace a with a+1). Your task is to find the minimum number of moves you need to do in order to make a divisible by b. It is possible, that you have to make 0 moves, as a is already divisible by b. You have to answer t independent test c...
def turn(a,b): if a%b==0: return 0 else: c=a%b return b-c for _ in range(int(input())): a,b=map(int,input().split()) print(turn(a,b))
{ "input": [ "5\n10 4\n13 9\n100 13\n123 456\n92 46\n" ], "output": [ "2\n5\n4\n333\n0\n" ] }
940
7
Phoenix has n coins with weights 2^1, 2^2, ..., 2^n. He knows that n is even. He wants to split the coins into two piles such that each pile has exactly n/2 coins and the difference of weights between the two piles is minimized. Formally, let a denote the sum of weights in the first pile, and b denote the sum of weigh...
def do(n): print(int(2*(2**(n/2)-1))) t = int(input()) for _ in range(t): do(int(input()))
{ "input": [ "2\n2\n4\n" ], "output": [ "2\n6\n" ] }
941
7
Naruto has sneaked into the Orochimaru's lair and is now looking for Sasuke. There are T rooms there. Every room has a door into it, each door can be described by the number n of seals on it and their integer energies a_1, a_2, ..., a_n. All energies a_i are nonzero and do not exceed 100 by absolute value. Also, n is e...
def inplst(): return list(map(int,input().split())) for _ in range(int(input())): n=int(input()) l=inplst() for i in range(1,n,2): print(-l[i],l[i-1],end=' ') print()
{ "input": [ "2\n2\n1 100\n4\n1 2 3 6\n" ], "output": [ "-100 1\n-2 1 -6 3\n" ] }
942
7
Let's define a function f(x) (x is a positive integer) as follows: write all digits of the decimal representation of x backwards, then get rid of the leading zeroes. For example, f(321) = 123, f(120) = 21, f(1000000) = 1, f(111) = 111. Let's define another function g(x) = (x)/(f(f(x))) (x is a positive integer as well...
def read(): return [int(x) for x in input().split()] if __name__ == '__main__': ca, = read() for _ in range(ca): print(len(input()))
{ "input": [ "5\n4\n37\n998244353\n1000000007\n12345678901337426966631415\n" ], "output": [ "\n1\n2\n9\n10\n26\n" ] }
943
8
The only difference between the two versions is that this version asks the minimal possible answer. Homer likes arrays a lot. Today he is painting an array a_1, a_2, ..., a_n with two kinds of colors, white and black. A painting assignment for a_1, a_2, ..., a_n is described by an array b_1, b_2, ..., b_n that b_i ind...
#!/usr/bin/env python3 import collections def solveTestCase(): n = int(input()) A = [int(i) for i in input().split()] s1 = [0] s2 = [0] d = dict() v = n B = [] for i in A[::-1]: nxt = n+1 if i in d: nxt = d[i] B.append((i, nxt)) d[i] = v v -= 1 B = B[::-1] next1 = n+2 next2 = n+2 for (v, ...
{ "input": [ "7\n1 2 1 2 1 2 1\n", "6\n1 2 3 1 2 2\n" ], "output": [ "\n2\n", "\n4\n" ] }
944
7
Polycarp found a rectangular table consisting of n rows and m columns. He noticed that each cell of the table has its number, obtained by the following algorithm "by columns": * cells are numbered starting from one; * cells are numbered from left to right by columns, and inside each column from top to bottom; ...
def solve(): n,m,x = map(int,input().split()) x-=1 col = int(x/n) row = int(x%n) print(row*m+col+1) n = int(input()) for i in range(n): solve()
{ "input": [ "5\n1 1 1\n2 2 3\n3 5 11\n100 100 7312\n1000000 1000000 1000000000000\n" ], "output": [ "\n1\n2\n9\n1174\n1000000000000\n" ] }
945
8
A sequence (b_1, b_2, …, b_k) is called strange, if the absolute difference between any pair of its elements is greater than or equal to the maximum element in the sequence. Formally speaking, it's strange if for every pair (i, j) with 1 ≤ i<j ≤ k, we have |a_i-a_j|≥ MAX, where MAX is the largest element of the sequenc...
def solve(values): values.sort() x = 1 while x < len(values) and values[x] <= 0: x += 1 if x == len(values): return x else: for y in range(1, x + 1): if abs(values[y] - values[y - 1]) < values[x]: return x return x + 1 if __name__ == '__m...
{ "input": [ "6\n4\n-1 -2 0 0\n7\n-3 4 -2 0 -4 6 1\n5\n0 5 -3 2 -5\n3\n2 3 1\n4\n-3 0 2 0\n6\n-3 -2 -1 1 1 1\n" ], "output": [ "\n4\n5\n4\n1\n3\n4\n" ] }
946
8
Each of you probably has your personal experience of riding public transportation and buying tickets. After a person buys a ticket (which traditionally has an even number of digits), he usually checks whether the ticket is lucky. Let us remind you that a ticket is lucky if the sum of digits in its first half matches th...
n=int(input()) s=input() def solve(): s1=sorted(s[:n]) s2=sorted(s[n:]) if s2[0]<s1[0]: s1,s2=s2,s1 for x in range(n): if s1[x]>=s2[x]: return "NO" return "YES" print(solve())
{ "input": [ "2\n3754\n", "2\n0135\n", "2\n2421\n" ], "output": [ "NO\n", "YES\n", "YES\n" ] }
947
8
Little Petya likes permutations a lot. Recently his mom has presented him permutation q1, q2, ..., qn of length n. A permutation a of length n is a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ n), all integers there are distinct. There is only one thing Petya likes more than permutations: playing with little Masha...
def Solve(x,L): if(x==k[0]): return L==S if((x,tuple(L)) in Mem): return False if(L==S): return False E=[] for i in range(len(L)): E.append(L[Q[i]-1]) if(Solve(x+1,E)): return True E=[0]*len(L) for i in range(len(L)): E[Q[i]-1]=L[i] ...
{ "input": [ "4 1\n4 3 1 2\n3 4 2 1\n", "4 1\n4 3 1 2\n2 1 4 3\n", "4 3\n4 3 1 2\n3 4 2 1\n", "4 1\n2 3 4 1\n1 2 3 4\n", "4 2\n4 3 1 2\n2 1 4 3\n" ], "output": [ "YES\n", "NO\n", "YES\n", "NO\n", "YES\n" ] }
948
9
The little girl loves the problems on array queries very much. One day she came across a rather well-known problem: you've got an array of n elements (the elements of the array are indexed starting from 1); also, there are q queries, each one is defined by a pair of integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n). You need to f...
from sys import stdin stdin.readline def mp(): return list(map(int, stdin.readline().strip().split())) def it():return int(stdin.readline().strip()) n,q=mp() d=[0]*n l=sorted(mp(),reverse=True) for _ in range(q): v=mp() d[v[0]-1]+=1 if v[1]!=n: d[v[1]]-=1 for i in range(1,n): d[i]+=d[i-1] d.sort(reverse=True) ...
{ "input": [ "5 3\n5 2 4 1 3\n1 5\n2 3\n2 3\n", "3 3\n5 3 2\n1 2\n2 3\n1 3\n" ], "output": [ "33\n", "25\n" ] }
949
9
Fox Ciel has a robot on a 2D plane. Initially it is located in (0, 0). Fox Ciel code a command to it. The command was represented by string s. Each character of s is one move operation. There are four move operations at all: * 'U': go up, (x, y) → (x, y+1); * 'D': go down, (x, y) → (x, y-1); * 'L': go left...
def inc(c, x, y): if c == 'R': x += 1 if c == 'L': x -= 1 if c == 'U': y += 1 if c == 'D': y -= 1 return x, y a, b = map(int, input().split()) s = input() x, y = 0, 0 for i in range(len(s)): x, y = inc(s[i], x, y) nx, ny = 0, 0 for i in range(len(s) + 1): ...
{ "input": [ "0 0\nD\n", "-1 1000000000\nLRRLU\n", "2 2\nRU\n", "1 2\nRU\n" ], "output": [ "Yes\n", "Yes\n", "Yes\n", "No\n" ] }
950
7
You want to arrange n integers a1, a2, ..., an in some order in a row. Let's define the value of an arrangement as the sum of differences between all pairs of adjacent integers. More formally, let's denote some arrangement as a sequence of integers x1, x2, ..., xn, where sequence x is a permutation of sequence a. The ...
def main(): input() a = sorted(input().split(), key=int) print(a[-1], ' '.join(a[1:-1]), a[0]) if __name__ == '__main__': main()
{ "input": [ "5\n100 -100 50 0 -50\n" ], "output": [ "100 -50 0 50 -100\n" ] }
951
8
Lately, a national version of a bingo game has become very popular in Berland. There are n players playing the game, each player has a card with numbers. The numbers on each card are distinct, but distinct cards can have equal numbers. The card of the i-th player contains mi numbers. During the game the host takes num...
def s(): n = int(input()) a = [set(list(map(int,input().split()))[1:])for _ in range(n)] res = 0 print(*['YES'if sum(i.issubset(j)for i in a) == 1 else 'NO' for j in a],sep = '\n') s()
{ "input": [ "2\n1 1\n1 1\n", "3\n1 1\n3 2 4 1\n2 10 11\n" ], "output": [ "NO\nNO\n", "YES\nNO\nYES\n" ] }
952
9
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y). Valera wants to place...
def print_tube(a): print(len(a),end = " ") print(" ".join(map(lambda x: " ".join(str(i) for i in x), a))) n, m, k = map(int, input().split()) res = [(x+1,y+1) for x in range(n) for y in range(m)[::(1 if (x%2 == 0) else -1)]] for i in range(k-1): print_tube(res[2*i:2*i+2]) print_tube(res[2*k-2:])
{ "input": [ "3 3 3\n", "2 3 1\n" ], "output": [ "2 1 1 1 2\n2 1 3 2 3\n5 2 2 2 1 3 1 3 2 3 3\n", "6 1 1 1 2 1 3 2 3 2 2 2 1\n" ] }
953
10
Gargari got bored to play with the bishops and now, after solving the problem about them, he is trying to do math homework. In a math book he have found k permutations. Each of them consists of numbers 1, 2, ..., n in some order. Now he should find the length of the longest common subsequence of these permutations. Can...
def main(): n, k = tuple(map(int, input().split())) a = [set(range(n)) for _ in range(n)] for i in range(k): p = set() for j in map(int, input().split()): a[j-1] -= p p.add(j-1) sa = sorted(range(n), key=lambda i: len(a[i])) maxx = [0] * n res = 0 ...
{ "input": [ "4 3\n1 4 2 3\n4 1 2 3\n1 2 4 3\n" ], "output": [ "3" ] }
954
9
Consider a sequence [a1, a2, ... , an]. Define its prefix product sequence <image>. Now given n, find a permutation of [1, 2, ..., n], such that its prefix product sequence is a permutation of [0, 1, ..., n - 1]. Input The only input line contains an integer n (1 ≤ n ≤ 105). Output In the first output line, print ...
def comp(x): for i in range(2, x): if x % i == 0: return True return False N = int(input()) if N == 4: print('YES', '1', '3', '2', '4', sep = '\n') elif comp(N): print('NO') else: print('YES', '1', sep = '\n') if N > 1: for i in range(2, N): print((i - 1...
{ "input": [ "6\n", "7\n" ], "output": [ "NO\n", "YES\n1\n2\n5\n6\n3\n4\n7\n" ] }
955
8
Fox Ciel is playing a mobile puzzle game called "Two Dots". The basic levels are played on a board of size n × m cells, like this: <image> Each cell contains a dot that has some color. We will use different uppercase Latin characters to express different colors. The key of this game is to find a cycle that contain d...
def dfs(x,y,x1,y1): v.add((x,y)) for dx,dy in [(-1,0),(0,1),(1,0),(0,-1)]: if x+dx>=0 and x+dx<n and y+dy>=0 and y+dy<m and (x+dx,y+dy)!=(x1,y1) and a[x+dx][y+dy]==a[x][y]: if (x+dx,y+dy) in v or dfs(x+dx,y+dy,x,y): return True return False import sys sys.setrecursionlimit(10000) n,m=map(int,input(...
{ "input": [ "2 13\nABCDEFGHIJKLM\nNOPQRSTUVWXYZ\n", "7 6\nAAAAAB\nABBBAB\nABAAAB\nABABBB\nABAAAB\nABBBAB\nAAAAAB\n", "3 4\nAAAA\nABCA\nAAAA\n", "3 4\nAAAA\nABCA\nAADA\n", "4 4\nYYYR\nBYBY\nBBBY\nBBBY\n" ], "output": [ "No\n", "Yes\n", "Yes\n", "No\n", "Yes\n" ] }
956
9
Karafs is some kind of vegetable in shape of an 1 × h rectangle. Tavaspolis people love Karafs and they use Karafs in almost any kind of food. Tavas, himself, is crazy about Karafs. <image> Each Karafs has a positive integer height. Tavas has an infinite 1-based sequence of Karafses. The height of the i-th Karafs is ...
import sys input = sys.stdin.readline a, b, n, l, t, m = -1, -1, -1, -1, -1, -1 def is_valid(mid): biggest = a + (mid - 1) * b; if t < biggest: return False sum = ((mid - l + 1) * (a + (l - 1) * b + biggest)) // 2 return t >= biggest and m * t >= sum def binary_search(b, e): while b <= e...
{ "input": [ "1 5 2\n1 5 10\n2 7 4\n", "2 1 4\n1 5 3\n3 3 10\n7 10 2\n6 4 8\n" ], "output": [ "1\n2\n", "4\n-1\n8\n-1\n" ] }
957
7
Alena has successfully passed the entrance exams to the university and is now looking forward to start studying. One two-hour lesson at the Russian university is traditionally called a pair, it lasts for two academic hours (an academic hour is equal to 45 minutes). The University works in such a way that every day it...
def main(): input() s = input() s = s[s.find("1"): s.rfind("1") + 1:2] s1 = s.replace("10", "1") print(len(s) - s1.count("0") - s1.count("10")) if __name__ == '__main__': main()
{ "input": [ "5\n0 1 0 1 1\n", "7\n1 0 1 0 0 1 0\n", "1\n0\n" ], "output": [ "4\n", "4\n", "0\n" ] }
958
8
Genos needs your help. He was asked to solve the following programming problem by Saitama: The length of some string s is denoted |s|. The Hamming distance between two strings s and t of equal length is defined as <image>, where si is the i-th character of s and ti is the i-th character of t. For example, the Hamming ...
def solve(a, b): m = len(a) n = len(b) p_b = [0] for x in b[:]: p_b.append(p_b[-1] + int(x)) s = 0 for i in range(m): if a[i] == '0': s += p_b[n - m + 1 + i] - p_b[i] else: s += (n - m + 1) - (p_b[n - m + 1 + i] - p_b[i]) return s a = input()...
{ "input": [ "01\n00111\n", "0011\n0110\n" ], "output": [ "3\n", "2\n" ] }
959
7
Statistics claims that students sleep no more than three hours a day. But even in the world of their dreams, while they are snoring peacefully, the sense of impending doom is still upon them. A poor student is dreaming that he is sitting the mathematical analysis exam. And he is examined by the most formidable profess...
f=lambda:map(int,input().split()) dl,dr=f() ml,mr=f() def chk(d,m): return d-2<m and m<2*d+3 if chk(dl,mr) or chk(dr,ml): print("YES") else: print("NO")
{ "input": [ "4 5\n3 3\n", "5 1\n10 5\n", "1 2\n11 6\n" ], "output": [ "YES\n", "YES\n", "NO\n" ] }
960
7
You are given names of two days of the week. Please, determine whether it is possible that during some non-leap year the first day of some month was equal to the first day of the week you are given, while the first day of the next month was equal to the second day of the week you are given. Both months should belong t...
def main(): d = {"monday": 6, "tuesday": 5, "wednesday": 4, "thursday": 3, "friday": 2, "saturday": 1, "sunday": 0} dif = (d[input()] - d[input()]) % 7 print(("NO", "YES")[any(a % 7 == dif for a in (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31))]) if __name__ == '__main__': main()
{ "input": [ "monday\ntuesday\n", "saturday\ntuesday\n", "sunday\nsunday\n" ], "output": [ "NO\n", "YES\n", "YES\n" ] }
961
7
Nikolay has a lemons, b apples and c pears. He decided to cook a compote. According to the recipe the fruits should be in the ratio 1: 2: 4. It means that for each lemon in the compote should be exactly 2 apples and exactly 4 pears. You can't crumble up, break up or cut these fruits into pieces. These fruits — lemons, ...
def r(): return int(input()) a = r() b = r() c = r() print(min(a, b // 2, c // 4) * 7)
{ "input": [ "2\n5\n7\n", "4\n7\n13\n", "2\n3\n2\n" ], "output": [ "7", "21", "0" ] }
962
7
There is the faculty of Computer Science in Berland. In the social net "TheContact!" for each course of this faculty there is the special group whose name equals the year of university entrance of corresponding course of students at the university. Each of students joins the group of his course and joins all groups f...
import sys def main(): _, *l = map(int, sys.stdin.read().strip().split()) return sum(l)//len(l) print(main())
{ "input": [ "1\n2050\n", "3\n2014 2016 2015\n" ], "output": [ "2050\n", "2015\n" ] }
963
7
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg...
def f(l,m,n): c=0 k=min(l) for i in l: d=i-k if d%m!=0: return -1 c+=d//m return c n,m=map(int,input().split()) l=list(map(int,input().split())) print(f(l,m,n))
{ "input": [ "2 2\n10 9\n", "3 3\n12 9 15\n", "4 1\n1 1000000000 1000000000 1000000000\n" ], "output": [ "-1\n", "3\n", "2999999997\n" ] }
964
10
Alice is a beginner composer and now she is ready to create another masterpiece. And not even the single one but two at the same time! Alice has a sheet with n notes written on it. She wants to take two such non-empty non-intersecting subsequences that both of them form a melody and sum of their lengths is maximal. ...
import sys def solve(): n = int(sys.stdin.readline()) a = [0] + [int(i) for i in sys.stdin.readline().split()] dp = [[0]*(n + 1) for i in range(n + 1)] ans = 0 maxnum = [0] * (10**5 + 2) maxmod = [0] * 7 for y in range(n + 1): maxmod = [0] * 7 for ai in a: ma...
{ "input": [ "6\n62 22 60 61 48 49\n", "4\n1 2 4 5\n" ], "output": [ "5\n", "4\n" ] }
965
9
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them....
from sys import stdin def main(): n = int(input()) g, r = [[] for _ in range(n + 1)], 0. for s in stdin.read().splitlines(): u, v = map(int, s.split()) g[u].append(v) g[v].append(u) stack = [(1, 1, -1)] while stack: u, denom, depth = stack.pop() depth += 1 ...
{ "input": [ "5\n1 2\n1 3\n3 4\n2 5\n", "4\n1 2\n1 3\n2 4\n" ], "output": [ "2.000000\n", "1.500000\n" ] }
966
7
In Arcady's garden there grows a peculiar apple-tree that fruits one time per year. Its peculiarity can be explained in following way: there are n inflorescences, numbered from 1 to n. Inflorescence number 1 is situated near base of tree and any other inflorescence with number i (i > 1) is situated at the top of branch...
# python3 def main(): n = int(input()) parent = tuple(int(x) - 1 for x in input().split()) depth = [0] for v in range(n - 1): depth.append(depth[parent[v]] + 1) parity = [0] * n for d in depth: parity[d] ^= 1 print(sum(parity)) main()
{ "input": [ "18\n1 1 1 4 4 3 2 2 2 10 8 9 9 9 10 10 4\n", "3\n1 1\n", "5\n1 2 2 2\n" ], "output": [ "4\n", "1\n", "3\n" ] }
967
7
Two players play a game. Initially there are n integers a_1, a_2, …, a_n written on the board. Each turn a player selects one number and erases it from the board. This continues until there is only one number left on the board, i. e. n - 1 turns are made. The first player makes the first move, then players alternate t...
def do(): N=int(input()) ch=sorted(map(int,input().split())) print(ch[(N-1)//2]) do()
{ "input": [ "3\n2 2 2\n", "3\n2 1 3\n" ], "output": [ "2\n", "2\n" ] }
968
8
Everybody seems to think that the Martians are green, but it turns out they are metallic pink and fat. Ajs has two bags of distinct nonnegative integers. The bags are disjoint, and the union of the sets of numbers in the bags is \{0,1,…,M-1\}, for some positive integer M. Ajs draws a number from the first bag and a num...
import sys input = sys.stdin.readline def main(): n, m = map(int, input().split()) a = list(map(int, input().split())) + [0]*500000 ans_S = 0 a[n] = a[0] + m s = [0]*600600 for i in range(n): s[i] = a[i + 1] - a[i] s[n] = -1 for i in range(n): s[2*n - i] = s[i] for i...
{ "input": [ "4 1000000000\n5 25 125 625\n", "2 4\n1 3\n", "2 5\n3 4\n" ], "output": [ "0\n", "2\n0 2 \n", "1\n2 \n" ] }
969
8
Ivan has number b. He is sorting through the numbers a from 1 to 10^{18}, and for every a writes ([a, b])/(a) on blackboard. Here [a, b] stands for least common multiple of a and b. Ivan is very lazy, that's why this task bored him soon. But he is interested in how many different numbers he would write on the boa...
def fun(): n=int(input()) s=set() limit= int(n**0.5)+1 for i in range(1,limit): if(n%i==0): s.add(i) s.add(n//i) print(len(s)) fun()
{ "input": [ "1\n", "2\n" ], "output": [ "1\n", "2\n" ] }
970
7
You are given a string s=s_1s_2... s_n of length n, which only contains digits 1, 2, ..., 9. A substring s[l ... r] of s is a string s_l s_{l + 1} s_{l + 2} … s_r. A substring s[l ... r] of s is called even if the number represented by it is even. Find the number of even substrings of s. Note, that even if some subs...
def f(): n=int(input()) s=input() rez=0 for i in range(n): if int(s[i])%2==0: rez+=i+1 print(rez) f()
{ "input": [ "4\n1234\n", "4\n2244\n" ], "output": [ "6\n", "10\n" ] }
971
8
You are given a long decimal number a consisting of n digits from 1 to 9. You also have a function f that maps every digit from 1 to 9 to some (possibly the same) digit from 1 to 9. You can perform the following operation no more than once: choose a non-empty contiguous subsegment of digits in a, and replace each digi...
import sys input=sys.stdin.readline def main(): n=int(input()) l=list(map(int,list(input().strip()))) f=[0]+list(map(int,input().split())) i=0 while i<n and l[i] >= f[l[i]] : i+=1 while i<n and f[l[i]] >= l[i] : l[i]=f[l[i]] i+=1 print(''.join(map(str,l))) main()
{ "input": [ "2\n33\n1 1 1 1 1 1 1 1 1\n", "4\n1337\n1 2 5 4 6 6 3 1 9\n", "5\n11111\n9 8 7 6 5 4 3 2 1\n" ], "output": [ "33", "1557", "99999" ] }
972
11
There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has n different matryoshkas. Any matryoshka is a figure of volume out_i with an empty space inside of volume in_i (of course, out_i > in_i). You don't have much free spac...
from sys import stdin, stdout mod = 10**9+7 n = int(input()) dolls = [] for i in range(n): o, i = map(int, stdin.readline().split()) dolls.append((o, i)) dolls.sort() dolls = [(i, o) for (o, i) in dolls] #print(dolls) def bin_search(i): lo = -1 hi = n-1 while lo+1 < hi: mid = (lo+hi-1)/...
{ "input": [ "7\n4 1\n4 2\n4 2\n2 1\n5 4\n6 4\n3 2\n" ], "output": [ "6" ] }
973
7
You have a coins of value n and b coins of value 1. You always pay in exact change, so you want to know if there exist such x and y that if you take x (0 ≤ x ≤ a) coins of value n and y (0 ≤ y ≤ b) coins of value 1, then the total value of taken coins will be S. You have to answer q independent test cases. Input The...
def solve(a, b, n, S): return ['NO', 'YES'][min((S // n), a)*n + b >= S] for q in range(int(input())): a, b, n, S = map(int, input().split()) print(solve(a, b, n, S))
{ "input": [ "4\n1 2 3 4\n1 2 3 6\n5 2 6 27\n3 3 5 18\n" ], "output": [ "YES\nNO\nNO\nYES\n" ] }
974
7
Mr. Scrooge, a very busy man, decided to count the time he wastes on all sorts of useless stuff to evaluate the lost profit. He has already counted the time he wastes sleeping and eating. And now Mr. Scrooge wants to count the time he has wasted signing papers. Mr. Scrooge's signature can be represented as a polyline ...
n,k = map(int,input().split()) l=0 s=[] for a in range(n): s.append([int(j) for j in input().split()]) def f(x,y): a=(x[0]-y[0])**2 b=(x[1]-y[1])**2 return (a+b)**.5 for j in range(n-1): l+=f(s[j],s[j+1]) x=(l/50)*k print('%.6f'%x)
{ "input": [ "2 1\n0 0\n10 0\n", "6 10\n5 0\n4 0\n6 0\n3 0\n7 0\n2 0\n", "5 10\n3 1\n-5 6\n-2 -1\n3 2\n10 0\n" ], "output": [ "0.200000000\n", "3.000000000\n", "6.032163204\n" ] }
975
8
You are given an array a of length n and array b of length m both consisting of only integers 0 and 1. Consider a matrix c of size n × m formed by following rule: c_{i, j} = a_i ⋅ b_j (i.e. a_i multiplied by b_j). It's easy to see that c consists of only zeroes and ones too. How many subrectangles of size (area) k con...
def getInput(): return [sum([int(ele) for ele in rang]) for rang in input().replace(' ', '').split('0')] n, m, k = list(map(int, input().split())) recs = [(i+1, int(k / (i + 1))) for i in range(int(k ** 0.5)) if k % (i + 1) == 0] recs += [(p[1], p[0]) for p in recs if p[1] != p[0]] a = getInput() b = getInput() ...
{ "input": [ "3 5 4\n1 1 1\n1 1 1 1 1\n", "3 3 2\n1 0 1\n1 1 1\n" ], "output": [ "14\n", "4\n" ] }
976
7
You are given two integers x and y. You can perform two types of operations: 1. Pay a dollars and increase or decrease any of these integers by 1. For example, if x = 0 and y = 7 there are four possible outcomes after this operation: * x = 0, y = 6; * x = 0, y = 8; * x = -1, y = 7; * x = 1, y = ...
def R(): return map(int, input().split()) t, = R() for _ in range(t): x, y = sorted(R()) a, b = R() print(min(2*a, b)*x + a*(y-x))
{ "input": [ "2\n1 3\n391 555\n0 0\n9 4\n" ], "output": [ "1337\n0\n" ] }
977
7
Ehab loves number theory, but for some reason he hates the number x. Given an array a, find the length of its longest subarray such that the sum of its elements isn't divisible by x, or determine that such subarray doesn't exist. An array a is a subarray of an array b if a can be obtained from b by deletion of several...
def main(): for _ in range(int(input())): input() print(len(set(input().split()))) main()
{ "input": [ "3\n3 3\n1 2 3\n3 4\n1 2 3\n2 2\n0 6\n" ], "output": [ "2\n3\n-1\n" ] }
978
8
The only difference between easy and hard versions is on constraints. In this version constraints are higher. You can make hacks only if all versions of the problem are solved. Koa the Koala is at the beach! The beach consists (from left to right) of a shore, n+1 meters of sea and an island at n+1 meters from the sho...
import math import sys def solve(): n, k, l = map(int, input().split()) a = list(map(int, input().split())) lt = -1 for i in range(n): lt += 1 if(a[i] > l): print("No") return if(l - a[i] >= k): lt = -1 continue l1 = 2 * k - (l - a[i]) r1 = 2 * k + (l - a[i]) if(lt == 0): lt = l1 cont...
{ "input": [ "7\n2 1 1\n1 0\n5 2 3\n1 2 3 2 2\n4 3 4\n0 2 4 3\n2 3 5\n3 0\n7 2 3\n3 0 2 1 3 0 1\n7 1 4\n4 4 3 0 2 4 2\n5 2 3\n1 2 3 2 2\n" ], "output": [ "Yes\nNo\nYes\nYes\nYes\nNo\nNo\n" ] }
979
10
Alice and Bob are playing a fun game of tree tag. The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges. Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first mov...
from collections import deque def dist(G, n, s): D = [None] * n;Q = deque();Q.append(s);D[s] = 0 while Q: f = Q.popleft() for t in G[f]: if D[t] is None:D[t] = D[f] + 1;Q.append(t) return D for ti in range(int(input())): n, a, b, da, db = map(int, input().split());a -= 1;b -=...
{ "input": [ "4\n4 3 2 1 2\n1 2\n1 3\n1 4\n6 6 1 2 5\n1 2\n6 5\n2 3\n3 4\n4 5\n9 3 9 2 5\n1 2\n1 6\n1 9\n1 3\n9 5\n7 9\n4 8\n4 3\n11 8 11 3 3\n1 2\n11 9\n4 9\n6 5\n2 10\n3 2\n5 9\n8 3\n7 4\n7 10\n" ], "output": [ "Alice\nBob\nAlice\nAlice\n" ] }
980
12
You are given a string s consisting of lowercase Latin letters "a", "b" and "c" and question marks "?". Let the number of question marks in the string s be k. Let's replace each question mark with one of the letters "a", "b" and "c". Here we can obtain all 3^{k} possible strings consisting only of letters "a", "b" and...
def main(): n = eval(input()) s=input() mod = 1000000007 a=0 b=0 ab=0 sz=1 ans=0 for c in s: if(c=='a'): a=a+sz a=a%mod elif(c=='b'): ab=ab+a ab=ab%mod elif(c=='c'): ans=ans+ab ans=ans%mod else : ans=(ans*3+ab)%mod ab=(ab*3+a)%mod a=(a*3+sz)%mod sz=(sz*3)%mod print(ans) ...
{ "input": [ "9\ncccbbbaaa\n", "7\n???????\n", "5\na???c\n", "6\nac?b?c\n" ], "output": [ "0\n", "2835\n", "46\n", "24\n" ] }
981
11
You are given a weighted undirected connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph. Let's define the weight of the path consisting of k edges with indices e_1, e_2, ..., e_k as ∑_{i=1}^{k}{w_{e_i}} - max_{i=1}^{k}{w_{e_i}} + min_...
import io import os # import __pypy__ def dijkstra(*args): # return dijkstraHeap(*args) # return dijkstraHeapComparatorWrong(*args) return dijkstraHeapComparator(*args) # return dijkstraSegTree(*args) # return dijkstraSortedList(*args) def dijkstraHeap(source, N, getAdj): # Heap of (dist, n...
{ "input": [ "7 10\n7 5 5\n2 3 3\n4 7 1\n5 3 6\n2 7 6\n6 2 6\n3 7 6\n4 2 1\n3 1 4\n1 7 4\n", "5 4\n5 3 4\n2 1 1\n3 2 2\n2 4 2\n", "6 8\n3 1 1\n3 6 2\n5 4 2\n4 2 2\n6 1 1\n5 2 1\n3 2 3\n1 5 4\n" ], "output": [ "\n3 4 2 7 7 3 \n", "\n1 2 2 4 \n", "\n2 1 4 3 1 \n" ] }
982
11
You like numbers, don't you? Nastia has a lot of numbers and she wants to share them with you! Isn't it amazing? Let a_i be how many numbers i (1 ≤ i ≤ k) you have. An n × n matrix is called beautiful if it contains all the numbers you have, and for each 2 × 2 submatrix of the original matrix is satisfied: 1. The...
def cheak(x): return x**2-(x//2)**2>=m and x*(x//2+(1 if x%2!=0 else 0))>=mx for test in range(int(input())): m,k=(int(i) for i in input().split()) a=[int(i) for i in input().split()] mx=max(a) z=0;y=m*4 while z!=y: x=(z+y)//2 if cheak(x): y=x else: ...
{ "input": [ "2\n3 4\n2 0 0 1\n15 4\n2 4 8 1\n" ], "output": [ "\n2\n4 1\n0 1\n5\n3 0 0 2 2\n3 2 3 3 0\n0 1 0 4 0\n3 0 0 0 0\n2 1 3 3 3" ] }
983
11
You are given a string s of length n. Each character is either one of the first k lowercase Latin letters or a question mark. You are asked to replace every question mark with one of the first k lowercase Latin letters in such a way that the following value is maximized. Let f_i be the maximum length substring of str...
N, K = list(map(int, input().split())) S = input().strip() S = [-1 if _ == '?' else ord(_) - ord('a') for _ in S] def check(x): p = [[N for i in range(N+1)] for k in range(K)] for k in range(K): keep = 0 for i in range(N-1, -1, -1): keep += 1 if S[i] != -1 and S[i] != k...
{ "input": [ "2 3\n??\n", "10 2\na??ab????b\n", "9 4\n?????????\n", "4 4\ncabd\n", "15 3\n??b?babbc??b?aa\n" ], "output": [ "0\n", "4\n", "2\n", "1\n", "3\n" ] }
984
8
The Smart Beaver from ABBYY decided to have a day off. But doing nothing the whole day turned out to be too boring, and he decided to play a game with pebbles. Initially, the Beaver has n pebbles. He arranges them in a equal rows, each row has b pebbles (a > 1). Note that the Beaver must use all the pebbles he has, i. ...
def sieve(x): i=2 while(i*i<=x): if(x%i==0): return x//i i+=1 else: return 1 n=int(input()) c=n ans=c while(c!=1): c= sieve(c) ans+=c print(ans)
{ "input": [ "10\n", "8\n" ], "output": [ "16\n", "15\n" ] }
985
7
The Little Elephant enjoys recursive functions. This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: ...
def f(l): return [n]+list(range(1,n)) n = int(input()) print(*f(n))
{ "input": [ "1\n", "2\n" ], "output": [ "1\n", "2 1\n" ] }
986
8
Vasya is an active Internet user. One day he came across an Internet resource he liked, so he wrote its address in the notebook. We know that the address of the written resource has format: <protocol>://<domain>.ru[/<context>] where: * <protocol> can equal either "http" (without the quotes) or "ftp" (without the q...
def s(): a = input() r = 'http://' if a[0] == 'h' else 'ftp://' if a[0] == 'h': a = a[4:] else: a = a[3:] c = a[0] a = a[1:].replace('ru','.ru/',1) print(r,c,a[:-1] if a[-1] == '/'else a,sep='') s()
{ "input": [ "httpsunrux\n", "ftphttprururu\n" ], "output": [ "http://sun.ru/x\n", "ftp://http.ru/ruru\n" ] }
987
11
You are given the following concurrent program. There are N processes and the i-th process has the following pseudocode: repeat ni times yi := y y := yi + 1 end repeat Here y is a shared variable. Everything else is local for the process. All actions on a given row are a...
import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') n, w = map(int, input().split()) a = [0] + list(map(int, input().split())) total = sum(a) def ng(): print('No') exit() def ok(a): print('Yes') print(*a) exit() if w < 1 or t...
{ "input": [ "1 10\n11\n", "2 3\n4 4\n", "3 6\n1 2 3\n" ], "output": [ "No\n", "Yes\n1 2 2 2 2 2 2 1 2 1 1 1 1 2 1 1\n", "Yes\n1 1 2 2 2 2 3 3 3 3 3 3\n" ] }
988
11
Iahub is so happy about inventing bubble sort graphs that he's staying all day long at the office and writing permutations. Iahubina is angry that she is no more important for Iahub. When Iahub goes away, Iahubina comes to his office and sabotage his research work. The girl finds an important permutation for the resea...
MOD = 10**9+7 n = int(input()) notUsed = set(range(1, n+1)) chairs = set() for i, a in enumerate(map(int, input().split()), 1): if a == -1: chairs.add(i) else: notUsed -= {a} fixed = len(chairs & notUsed) m = len(notUsed) U = m fact = [0]*(U+1) fact[0] = 1 for i in range(1, U+1): fact[i] =...
{ "input": [ "5\n-1 -1 4 3 -1\n" ], "output": [ "2\n" ] }
989
7
Fox Ciel has n boxes in her room. They have the same size and weight, but they might have different strength. The i-th box can hold at most xi boxes on its top (we'll call xi the strength of the box). Since all the boxes have the same size, Ciel cannot put more than one box directly on the top of some box. For exampl...
def go(): n = int(input()) a = [int(i) for i in input().split(' ')] a.sort() o = 1 for i in range(n): if(a[i] < i // o): o += 1 return o print(go())
{ "input": [ "9\n0 1 0 2 0 1 1 2 10\n", "5\n0 1 2 3 4\n", "3\n0 0 10\n", "4\n0 0 0 0\n" ], "output": [ "3\n", "1\n", "2\n", "4\n" ] }
990
10
One day, little Vasya found himself in a maze consisting of (n + 1) rooms, numbered from 1 to (n + 1). Initially, Vasya is at the first room and to get out of the maze, he needs to get to the (n + 1)-th one. The maze is organized as follows. Each room of the maze has two one-way portals. Let's consider room number i (...
n = int(input()) A = [int(i) for i in input().split()] dp = [[10**10 for i in range(n+1)] for k in range(n+1)] import sys sys.setrecursionlimit(10**7) for i in range(n+1): dp[i][i] = 1 MOD = 10**9 + 7 def f(i, x): if dp[i][x] != 10**10: return dp[i][x] dp[i][x] = (1 + (f(A[i]-1, i))%MOD + (f(i...
{ "input": [ "2\n1 2\n", "5\n1 1 1 1 1\n", "4\n1 1 2 3\n" ], "output": [ "4\n", "62\n", "20\n" ] }
991
7
Pashmak has fallen in love with an attractive girl called Parmida since one year ago... Today, Pashmak set up a meeting with his partner in a romantic garden. Unfortunately, Pashmak has forgotten where the garden is. But he remembers that the garden looks like a square with sides parallel to the coordinate axes. He al...
x1, y1, x2, y2 = map(int,input().split()) def garden(x1,y,x2,y2): a = abs(x1-x2) b = abs(y1-y2) if x1 == x2: print(x1+b,y1,x2+b,y2) elif y1 == y2: print(x1,y1+a,x2,y2+a) elif a!=b: print(-1) else: print(x1,y2,x2,y1) garden(x1,y1,x2,y2)
{ "input": [ "0 0 1 2\n", "0 0 0 1\n", "0 0 1 1\n" ], "output": [ "-1\n", "1 0 1 1\n", "0 1 1 0\n" ] }
992
11
Bertown is under siege! The attackers have blocked all the ways out and their cannon is bombarding the city. Fortunately, Berland intelligence managed to intercept the enemies' shooting plan. Let's introduce the Cartesian system of coordinates, the origin of which coincides with the cannon's position, the Ox axis is di...
import sys from array import array # noqa: F401 from math import pi, sin, cos from bisect import bisect_left def input(): return sys.stdin.buffer.readline().decode('utf-8') n, v = map(int, input().split()) v = float(v) alpha = [float(input()) for _ in range(n)] m = int(input()) wall = sorted(tuple(map(float, i...
{ "input": [ "2 10\n0.7853\n0.3\n2\n4.0 2.4\n6.0 1.9\n", "2 10\n0.7853\n0.3\n3\n5.0 5.0\n4.0 2.4\n6.0 1.9\n" ], "output": [ "10.204081436 0.000000000\n4.000000000 0.378324889\n", "5.000000000 2.549499369\n4.000000000 0.378324889\n" ] }
993
7
Kyoya Ootori is selling photobooks of the Ouran High School Host Club. He has 26 photos, labeled "a" to "z", and he has compiled them into a photo booklet with some photos in some order (possibly with some photos being duplicated). A photo booklet can be described as a string of lowercase letters, consisting of the pho...
def photograph(s): print((len(s)+1)*26-len(s)) s=input('') photograph(s)
{ "input": [ "hi\n", "a\n" ], "output": [ "76\n", "51\n" ] }
994
8
You are given an alphabet consisting of n letters, your task is to make a string of the maximum possible length so that the following conditions are satisfied: * the i-th letter occurs in the string no more than ai times; * the number of occurrences of each letter in the string must be distinct for all the lette...
def f(): input() a = list(map(int,input().split(' '))) a.sort() t = 10**9+1 r = 0 for i in reversed(a): t = i if i < t else t - 1 if t == 0: break r += t print(r) f()
{ "input": [ "3\n2 5 5\n", "3\n1 1 2\n" ], "output": [ "11\n", "3\n" ] }
995
10
We all know the impressive story of Robin Hood. Robin Hood uses his archery skills and his wits to steal the money from rich, and return it to the poor. There are n citizens in Kekoland, each person has ci coins. Each day, Robin Hood will take exactly 1 coin from the richest person in the city and he will give it to t...
import sys sys.stderr = sys.stdout def hood(n, k, C): C.sort() m, r = divmod(sum(C), n) m1 = (m + 1) if r else m c_lo = C[0] k_lo = k for i, c in enumerate(C): if c_lo == m: break c_m = min(c, m) dc = c_m - c_lo dk = i * dc if k_lo >= dk: ...
{ "input": [ "4 1\n1 1 4 2\n", "3 1\n2 2 2\n" ], "output": [ "2\n", "0\n" ] }
996
8
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other. Help Timofey to color his rectangles in 4 different...
def f(): n = int(input()) a = [1,2,3,4] print("YES") for i in range(n): x = input().split() x = [int(j)%2 for j in x] print(a[x[2]*2+x[3]]) f()
{ "input": [ "8\n0 0 5 3\n2 -1 5 0\n-3 -4 2 -1\n-1 -1 2 0\n-3 0 0 5\n5 2 10 3\n7 -3 10 2\n4 -2 7 -1\n" ], "output": [ "YES\n1\n2\n3\n4\n3\n3\n4\n1\n" ] }
997
9
Polycarp invited all his friends to the tea party to celebrate the holiday. He has n cups, one for each of his n friends, with volumes a1, a2, ..., an. His teapot stores w milliliters of tea (w ≤ a1 + a2 + ... + an). Polycarp wants to pour tea in cups in such a way that: * Every cup will contain tea for at least hal...
def main(): n, w = map(int, input().split()) aa = list(map(int, input().split())) x, y = sum(aa), sum(a & 1 for a in aa) if x < w or x + y > w * 2: print(-1) return res = [r + 1 if r * 2 < a else r for r, a in ((a * w // x, a) for a in aa)] for i in sorted(range(n), key=aa.__geti...
{ "input": [ "2 10\n8 7\n", "3 10\n9 8 10\n", "4 4\n1 1 1 1\n" ], "output": [ "6 4 ", "-1\n", "1 1 1 1 " ] }
998
10
Misha and Grisha are funny boys, so they like to use new underground. The underground has n stations connected with n - 1 routes so that each route connects two stations, and it is possible to reach every station from any other. The boys decided to have fun and came up with a plan. Namely, in some day in the morning M...
# by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO, IOBase def euler_path(n,path): height = [0]*n+[10**10] euler,st,visi,he = [],[0],[1]+[0]*(n-1),0 first = [-1]*n while len(st): x = st[-1] euler.append(x) if first[x] == -1: ...
{ "input": [ "3 2\n1 1\n1 2 3\n2 3 3\n", "4 1\n1 2 3\n1 2 3\n" ], "output": [ "2\n3\n", "2\n" ] }
999
8
Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process. There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for...
# ---------------------------iye ha aam zindegi--------------------------------------------- import math import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- impor...
{ "input": [ "2 4 5\n1 2 0 5000\n2 1 0 4500\n2 1 0 3000\n8 0 1 6000\n", "2 6 5\n1 1 0 5000\n3 2 0 5500\n2 2 0 6000\n15 0 2 9000\n9 0 1 7000\n8 0 2 6500\n" ], "output": [ "-1", " 24500\n" ] }