index
int64
0
5.16k
difficulty
int64
7
12
question
stringlengths
126
7.12k
solution
stringlengths
30
18.6k
test_cases
dict
400
10
You are given a connected undirected graph with n vertices and m edges. The vertices are enumerated from 1 to n. You are given n integers c1, c2, ..., cn, each of them is between - n and n, inclusive. It is also guaranteed that the parity of cv equals the parity of degree of vertex v. The degree of a vertex is the n...
def divisors(M): d=[] i=1 while M>=i**2: if M%i==0: d.append(i) if i**2!=M: d.append(M//i) i=i+1 return d def popcount(x): x = x - ((x >> 1) & 0x55555555) x = (x & 0x33333333) + ((x >> 2) & 0x33333333) x = (x + (x >> 4)) & 0x0f0f0f0f ...
{ "input": [ "6 6\n3 5 5 5 1 5\n1 4\n3 2\n4 3\n4 5\n3 5\n5 6\n", "4 4\n4 4 2 4\n1 2\n2 3\n3 4\n4 1\n", "3 3\n2 2 2\n1 2\n2 3\n1 3\n", "4 3\n-1 0 2 1\n1 2\n2 3\n3 4\n" ], "output": [ "YES\n 3\n ...
401
7
There is a rectangular grid of n rows of m initially-white cells each. Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and...
import sys def p(s): print(s) sys.exit(0) n,m = list(map(int, input().split())) t = [input() for _ in range(n)] sts = [] for i in range(n): founds = set() for j in range(m): if t[i][j] == '#': founds.add(j) sts.append(founds) for i in range(n): for j in range(i+1, n): if len(sts[i]&sts[j]) != 0 and s...
{ "input": [ "5 9\n........#\n#........\n..##.#...\n.......#.\n....#.#.#\n", "5 5\n..#..\n..#..\n#####\n..#..\n..#..\n", "5 8\n.#.#..#.\n.....#..\n.#.#..#.\n#.#....#\n.....#..\n" ], "output": [ "No\n", "No\n", "Yes\n" ] }
402
9
Everybody knows of [spaghetti sort](https://en.wikipedia.org/wiki/Spaghetti_sort). You decided to implement an analog sorting algorithm yourself, but as you survey your pantry you realize you're out of spaghetti! The only type of pasta you have is ravioli, but you are not going to let this stop you... You come up with...
def mp(): return map(int, input().split()) n = int(input()) a = list(mp()) r = [abs(a[i] - a[i + 1]) for i in range(n - 1)] if n != 1 and max(r) >= 2: print('NO') else: print('YES')
{ "input": [ "3\n3 1 2\n", "3\n1 2 3\n" ], "output": [ "NO", "YES" ] }
403
12
There are n players sitting at the card table. Each player has a favorite number. The favorite number of the j-th player is f_j. There are k β‹… n cards on the table. Each card contains a single integer: the i-th card contains number c_i. Also, you are given a sequence h_1, h_2, ..., h_k. Its meaning will be explained b...
import math from collections import defaultdict def main(): n, k = map(int, input().split()) cards = list(map(int, input().split())) fav = list(map(int, input().split())) h = [0] + list(map(int, input().split())) cards_cnt = defaultdict(int) for val in cards: cards_cnt[val] += 1 ...
{ "input": [ "4 3\n1 3 2 8 5 5 8 2 2 8 5 2\n1 2 2 5\n2 6 7\n", "3 3\n9 9 9 9 9 9 9 9 9\n1 2 3\n1 2 3\n" ], "output": [ "21\n", "0\n" ] }
404
11
You are given three integers n, d and k. Your task is to construct an undirected tree on n vertices with diameter d and degree of each vertex at most k, or say that it is impossible. An undirected tree is a connected undirected graph with n - 1 edges. Diameter of a tree is the maximum length of a simple path (a path...
n,d,k=map(int,input().split()) if n==1: print("NO") exit() if k==1: if n==2 and d==1: print("YES") print(1,2) else: print("NO") exit() if n<d+1: print("NO") exit() co=1 ans=[] for i in range(1,d+1): ans.append((i,i+1)) co+=1 def dfs(r,dist,co): if 2<=r<=d: t=k-2 else: t=k-1 i...
{ "input": [ "8 5 3\n", "6 3 3\n", "10 4 3\n", "6 2 3\n" ], "output": [ "YES\n1 2\n2 3\n3 4\n4 5\n5 6\n2 7\n3 8\n", "YES\n1 2\n2 3\n3 4\n2 5\n3 6\n", "YES\n1 2\n2 3\n3 4\n4 5\n2 6\n3 7\n7 8\n7 9\n4 10\n", "NO\n" ] }
405
10
Enough is enough. Too many times it happened that Vasya forgot to dispose of garbage and his apartment stank afterwards. Now he wants to create a garbage disposal plan and stick to it. For each of next n days Vasya knows a_i β€” number of units of garbage he will produce on the i-th day. Each unit of garbage must be dis...
def read(): return list(map(int, input().split())) def solve(n, k, A): ans, prev = 0, 0 for a in A: total = prev + a if prev and total < k: ans += 1 total = 0 elif total >= k: ans += total // k total %= k prev = total ...
{ "input": [ "3 2\n1 0 1\n", "4 4\n2 8 4 1\n", "3 2\n3 2 1\n", "5 1\n1000000000 1000000000 1000000000 1000000000 1000000000\n" ], "output": [ "2\n", "4\n", "3\n", "5000000000\n" ] }
406
9
You have a playlist consisting of n songs. The i-th song is characterized by two numbers t_i and b_i β€” its length and beauty respectively. The pleasure of listening to set of songs is equal to the total length of the songs in the set multiplied by the minimum beauty among them. For example, the pleasure of listening to...
from sys import stdin import heapq input=stdin.readline def f(a,k): h=[] ans=-222222222 a=sorted(a,key=lambda s:s[1],reverse=True) s=0 for ad,p in a: heapq.heappush(h,ad) s+=ad if len(h)>k: s-=heapq.heappop(h) ans=max(ans,s*p) return ans n,m=map(int,input().strip().split()) blanck=[] for i in range(n):...
{ "input": [ "5 3\n12 31\n112 4\n100 100\n13 55\n55 50\n", "4 3\n4 7\n15 1\n3 6\n6 8\n" ], "output": [ "10000", "78" ] }
407
7
Vasya has a pile, that consists of some number of stones. n times he either took one stone from the pile or added one stone to the pile. The pile was non-empty before each operation of taking one stone from the pile. You are given n operations which Vasya has made. Find the minimal possible number of stones that can b...
def main(): n = int(input()) ans = 0 for i in input(): if i == '-': ans = max(0, ans-1) else: ans += 1 return ans if __name__ == '__main__': print(main())
{ "input": [ "2\n-+\n", "3\n---\n", "5\n++-++\n", "4\n++++\n" ], "output": [ "1\n", "0\n", "3\n", "4\n" ] }
408
7
Soon after the Chunga-Changa island was discovered, it started to acquire some forms of civilization and even market economy. A new currency arose, colloquially called "chizhik". One has to pay in chizhiks to buy a coconut now. Sasha and Masha are about to buy some coconuts which are sold at price z chizhiks per cocon...
def main(): x, y, z = map(int, input().split()) print((x + y) // z, max(min(x % z - (x + y) % z, y % z - (x + y) % z), 0)) main()
{ "input": [ "6 8 2\n", "5 4 3\n" ], "output": [ "7 0\n", "3 1\n" ] }
409
11
The only difference between the easy and the hard versions is the maximum value of k. You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one β€” from 1 to 2...
word = '' arr = [0] for i in range(1,22000): word = word + str(i) arr.append(arr[-1] + len(word)) def sol(k): d = 0 for i in range(1,22000): if arr[i] > k: d = i - 1 break k = k - arr[d] if k == 0: return str(d)[-1] else: return word[...
{ "input": [ "4\n2132\n506\n999999999\n1000000000\n", "5\n1\n3\n20\n38\n56\n" ], "output": [ "8\n2\n9\n8\n", "1\n2\n5\n2\n0\n" ] }
410
7
Lengths are measures in Baden in inches and feet. To a length from centimeters it is enough to know that an inch equals three centimeters in Baden and one foot contains 12 inches. You are given a length equal to n centimeters. Your task is to convert it to feet and inches so that the number of feet was maximum. The re...
def dliny(number): return ((number + 1) // 3) // 12, ((number + 1) // 3) % 12 print(*dliny(int(input())))
{ "input": [ "42\n", "5\n" ], "output": [ "1 2\n", "0 2\n" ] }
411
9
We start with a string s consisting only of the digits 1, 2, or 3. The length of s is denoted by |s|. For each i from 1 to |s|, the i-th character of s is denoted by s_i. There is one cursor. The cursor's location β„“ is denoted by an integer in \{0, …, |s|\}, with the following meaning: * If β„“ = 0, then the cursor...
def solve(l,s): n = len(s) for i in range(l): n += (n-i-1)*(int(s[i])-1) n %= 7 + 10**9 if len(s) < l: s += s[i+1:]*(int(s[i])-1) return n for _ in range(int(input())): l = int(input()) s = input() print(solve(l,s))
{ "input": [ "4\n5\n231\n7\n2323\n6\n333\n24\n133321333\n" ], "output": [ "25\n1438\n1101\n686531475\n" ] }
412
9
Ayoub thinks that he is a very smart person, so he created a function f(s), where s is a binary string (a string which contains only symbols "0" and "1"). The function f(s) is equal to the number of substrings in the string s that contains at least one symbol, that is equal to "1". More formally, f(s) is equal to the ...
import sys input = sys.stdin.readline t=int(input()) def calc(x): return x*(x+1)//2 for test in range(t): n,m=map(int,input().split()) ANS=calc(n) k=n-m q,mod=divmod(k,m+1) ANS-=calc(q+1)*mod+calc(q)*(m+1-mod) print(ANS)
{ "input": [ "5\n3 1\n3 2\n3 3\n4 0\n5 2\n" ], "output": [ "4\n5\n6\n0\n12\n" ] }
413
9
You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold: * Every label is an integer between 0 and n-2 inclusive. * All the written labels are distinct. * The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as ...
def main(): n = int(input()) lst = [0] * (n+1) s = [] for i in range(n-1): a, b = map(int, input().split()) s.append((a,b)) lst[a]+=1 lst[b] +=1 sol = [] left = 0 right = n-2 for a, b in s: if lst[a] == 1 or lst[b] == 1: print(left)...
{ "input": [ "6\n1 2\n1 3\n2 4\n2 5\n5 6\n", "3\n1 2\n1 3\n" ], "output": [ "0\n3\n1\n2\n4\n", "0\n1\n" ] }
414
8
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care. There is an nΓ— m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowe...
import sys import math def readStr(): return sys.stdin.readline().rstrip() def readInts(): return list(map(int, readStr().split(' '))) def main(n, m, a): x = 0 empty = False for i in range(n): boundary = 0 dx = True for j in range(m): if a[i][j] == '#': ...
{ "input": [ "3 3\n.#.\n###\n##.\n", "4 5\n....#\n####.\n.###.\n.#...\n", "4 2\n##\n.#\n.#\n##\n", "3 5\n.....\n.....\n.....\n", "2 1\n.\n#\n" ], "output": [ "1\n", "2\n", "-1\n", "0\n", "-1\n" ] }
415
8
You are given an array consisting of n integers a_1, a_2, ..., a_n. Initially a_x = 1, all other elements are equal to 0. You have to perform m operations. During the i-th operation, you choose two indices c and d such that l_i ≀ c, d ≀ r_i, and swap a_c and a_d. Calculate the number of indices k such that it is poss...
def f(): return list(map(int,input().split())) for _ in range(int(input())): n,k,m=f() p=q=k for _ in range(m): a,b=f() if a<=p<=b or a<=q<=b: p=min(p,a) q=max(q,b) print(q-p+1)
{ "input": [ "3\n6 4 3\n1 6\n2 3\n5 5\n4 1 2\n2 4\n1 2\n3 3 2\n2 3\n1 2\n" ], "output": [ "6\n2\n3\n" ] }
416
8
You are given a non-decreasing array of non-negative integers a_1, a_2, …, a_n. Also you are given a positive integer k. You want to find m non-decreasing arrays of non-negative integers b_1, b_2, …, b_m, such that: * The size of b_i is equal to n for all 1 ≀ i ≀ m. * For all 1 ≀ j ≀ n, a_j = b_{1, j} + b_{2, j}...
from math import ceil def main(n, k, a): a = set(a) n = len(a) if n > k == 1: return -1 if n <= k: return 1 return 1 + ceil((n-k)/(k-1)) for i in range(int(input())): n, k = map(int, input().split()) a = list(map(int, input().split())) print(main(n, k, a))
{ "input": [ "6\n4 1\n0 0 0 1\n3 1\n3 3 3\n11 3\n0 1 2 2 3 3 3 4 4 4 4\n5 3\n1 2 3 4 5\n9 4\n2 2 3 5 7 11 13 13 17\n10 7\n0 1 1 2 3 3 4 5 5 6\n" ], "output": [ "-1\n1\n2\n2\n2\n1\n" ] }
417
11
There are some rabbits in Singapore Zoo. To feed them, Zookeeper bought n carrots with lengths a_1, a_2, a_3, …, a_n. However, rabbits are very fertile and multiply very quickly. Zookeeper now has k rabbits and does not have enough carrots to feed all of them. To solve this problem, Zookeeper decided to cut the carrots...
import heapq n, k = map(int, input().split()) A = list(map(int, input().split())) def cal(x, m): k, r = divmod(x, m) return r * (k + 1) ** 2 + (m - r) * k ** 2 hp = [(cal(a, 2) - cal(a, 1), a, 2) for a in A] heapq.heapify(hp) ans = sum(a ** 2 for a in A) for _ in range(k - n): d, x, m = heapq.heappop(hp) ...
{ "input": [ "1 4\n19\n", "3 6\n5 3 1\n" ], "output": [ "91\n", "15\n" ] }
418
12
Jeel and Ashish play a game on an n Γ— m matrix. The rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right. They play turn by turn. Ashish goes first. Initially, each cell of the matrix contains a non-negative integer. Each turn, a player must perform all of the following ac...
def solve_case(): n, m = [int(x) for x in input().split()];a = [[int(x) for x in input().split()] for x in range(n)];xr = [0] * (n + m) for i in range(n): for j in range(m):xr[i + j] ^= a[i][j] return sum(xr) > 0 for _ in range(int(input())):print(['Jeel', 'Ashish'][solve_case()])
{ "input": [ "4\n1 1\n0\n1 3\n0 0 5\n2 2\n0 1\n1 0\n3 3\n1 2 3\n4 5 6\n7 8 9\n" ], "output": [ "\nJeel\nAshish\nJeel\nAshish\n" ] }
419
11
Masha works in an advertising agency. In order to promote the new brand, she wants to conclude contracts with some bloggers. In total, Masha has connections of n different bloggers. Blogger numbered i has a_i followers. Since Masha has a limited budget, she can only sign a contract with k different bloggers. Of course...
import math def nCr(n,r): f = math.factorial return f(n) // (f(r)*f(n-r)) for iii in range(int(input())): n,k=map(int,input().split()) arr=list(map(int,input().split())) arr.sort(reverse=True) xx=arr.count(arr[k-1]) c=0 for item in arr[:k]: if(item==arr[k-1]): c+=1 ...
{ "input": [ "3\n4 3\n1 3 1 2\n4 2\n1 1 1 1\n2 1\n1 2\n" ], "output": [ "\n2\n6\n1\n" ] }
420
11
Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands. Monocarp's empire has n cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monum...
p=998244353 def f(x,y): r=1 x=x%p if x==0: return 0 while y>0: if y%2==1: r=(r*x)%p y=y>>1 x=(x*x)%p return r n,m=map(int,input().split()) l=[] for _ in range(n): l.append(list(map(int,input().split()))) a=1 for i in range(1,n+1): a=(a*i)%p q=0 for...
{ "input": [ "3 5\n1 4 4 3 4\n1 4 1 4 2\n1 4 4 4 3\n" ], "output": [ "\n166374062\n" ] }
421
8
One day, as Sherlock Holmes was tracking down one very important criminal, he found a wonderful painting on the wall. This wall could be represented as a plane. The painting had several concentric circles that divided the wall into several parts. Some parts were painted red and all the other were painted blue. Besides,...
def mi(): return map(int, input().split()) n = int(input()) a = list(mi()) a.sort(reverse=True) ans = 0 s = -1 from math import pi for r in a: s*=-1 ans+=pi*r*r*s print (ans)
{ "input": [ "1\n1\n", "3\n1 4 2\n" ], "output": [ "3.141592653589793\n", "40.840704496667314\n" ] }
422
7
The Smart Beaver from ABBYY began to develop a new educational game for children. The rules of the game are fairly simple and are described below. The playing field is a sequence of n non-negative integers ai numbered from 1 to n. The goal of the game is to make numbers a1, a2, ..., ak (i.e. some prefix of the sequenc...
n=int(input()) a=list(map(int, input().split(" "))) def check(n): while n>1: n/=2 if n==1: return True else: return False s=0 for j in range(n-1): s+=a[j] for i in range(n-1, -1, -1): if check(i-j): print(s) a[i]+=a[j] break
{ "input": [ "8\n1 2 3 4 5 6 7 8\n", "4\n1 0 1 2\n" ], "output": [ "1\n3\n6\n10\n16\n24\n40\n", "1\n1\n3\n" ] }
423
9
Once Bob saw a string. It contained so many different letters, that the letters were marked by numbers, but at the same time each letter could be met in the string at most 10 times. Bob didn't like that string, because it contained repeats: a repeat of length x is such a substring of length 2x, that its first half coin...
def pow(x, exp, mod): res = 1 while exp: if exp & 1: res = (res * x) % mod x = (x * x) % mod exp >>= 1 return res MOD = 2 ** 121 - 1 M = int(1e9) + 1 n = int(input()) vals = list(map(int, input().split())) groups = dict() for i in range(n): groups.setdefault(vals...
{ "input": [ "6\n1 2 3 1 2 3\n", "7\n4 5 6 5 6 7 7\n" ], "output": [ "3\n1 2 3 ", "1\n7 " ] }
424
8
Chilly Willy loves playing with numbers. He only knows prime numbers that are digits yet. These numbers are 2, 3, 5 and 7. But Willy grew rather bored of such numbers, so he came up with a few games that were connected with them. Chilly Willy wants to find the minimum number of length n, such that it is simultaneously...
def cat(n): if n < 3: return -1 return 210 * (10 ** (n - 1) // 210 + 1) print(cat(int(input())))
{ "input": [ "5\n", "1\n" ], "output": [ "10080\n", "-1\n" ] }
425
9
Dima's got a staircase that consists of n stairs. The first stair is at height a1, the second one is at a2, the last one is at an (1 ≀ a1 ≀ a2 ≀ ... ≀ an). Dima decided to play with the staircase, so he is throwing rectangular boxes at the staircase from above. The i-th box has width wi and height hi. Dima throws eac...
def main(): n, res = int(input()), [] l = list(map(int, input().split())) for _ in range(int(input())): w, h = map(int, input().split()) m = max(l[0], l[w - 1]) res.append(m) l[0] = m + h print('\n'.join(map(str, res))) if __name__ == '__main__': main()
{ "input": [ "1\n1\n5\n1 2\n1 10\n1 10\n1 10\n1 10\n", "3\n1 2 3\n2\n1 1\n3 1\n", "5\n1 2 3 6 6\n4\n1 1\n3 1\n1 1\n4 3\n" ], "output": [ "1\n3\n13\n23\n33\n", "1\n3\n", "1\n3\n4\n6\n" ] }
426
9
Kalila and Dimna are two jackals living in a huge jungle. One day they decided to join a logging factory in order to make money. The manager of logging factory wants them to go to the jungle and cut n trees with heights a1, a2, ..., an. They bought a chain saw from a shop. Each time they use the chain saw on the tree...
read = lambda: map(int, input().split()) n = int(input()) a = list(read()) b = list(read()) dp = [0] * n st = [0] def f1(): i0, i1 = st[0], st[1] b1 = dp[i1] - dp[i0] k1 = b[i0] - b[i1] return b1 <= a[i] * k1 def f2(): i1, i2 = st[-1], st[-2] k1, k2 = b[i1] - b[i], b[i2] - b[i1] b1, b2 = dp[...
{ "input": [ "5\n1 2 3 4 5\n5 4 3 2 0\n", "6\n1 2 3 10 20 30\n6 5 4 3 2 0\n" ], "output": [ "25\n", "138\n" ] }
427
9
Mad scientist Mike does not use slow hard disks. His modification of a hard drive has not one, but n different heads that can read data in parallel. When viewed from the side, Mike's hard drive is an endless array of tracks. The tracks of the array are numbered from left to right with integers, starting with 1. In the...
import sys def input(): return sys.stdin.buffer.readline()[:-1] for T in range(1): n, m = map(int, input().split()) p = list(map(int, input().split())) q = list(map(int, input().split())) ok, ng = 10**11, -1 while ok-ng > 1: x = (ok+ng)//2 flg = True j = 0 for i in range(n): l = max(p[i] - q[j], 0)...
{ "input": [ "3 4\n2 5 6\n1 3 6 8\n", "3 3\n1 2 3\n1 2 3\n", "1 2\n165\n142 200\n" ], "output": [ "2\n", "0\n", "81\n" ] }
428
11
Dima loves Inna very much. He decided to write a song for her. Dima has a magic guitar with n strings and m frets. Dima makes the guitar produce sounds like that: to play a note, he needs to hold one of the strings on one of the frets and then pull the string. When Dima pulls the i-th string holding it on the j-th fret...
def solution() : # ζœ€ε€§ηš„θ·η¦»ζ₯θ‡ͺδΊŽθ§’θ½ι™„θΏ‘ηš„η‚Ή n,m,k,s = map(int, input().split()) dis = lambda a,b : abs(a[0] - b[0]) + abs(a[1] - b[1]) corner = [(0,0), (0,m-1), (n-1,0), (n-1,m-1)] vertex = [[(n,m), (n,-1), (-1,m), (-1,-1)] for _ in range(k+1)] for i in range(n) : for j,note in enumerate(map(int, input().split())) : ve...
{ "input": [ "4 6 5 7\n3 1 2 2 3 1\n3 2 2 2 5 5\n4 2 2 2 5 3\n3 2 2 1 4 3\n2 3 1 4 1 5 1\n", "4 4 9 5\n4 7 9 5\n1 2 1 7\n8 3 4 9\n5 7 7 2\n7 1 9 2 5\n" ], "output": [ "8\n", "4\n" ] }
429
9
Last year the world's largest square was built in Berland. It is known that the square can be represented as an infinite plane with an introduced Cartesian system of coordinates. On that square two sets of concentric circles were painted. Let's call the set of concentric circles with radii 1, 2, ..., K and the center i...
def readGen(trans): while 1: for x in input().split(): yield(trans(x)) readint=readGen(int) [N,x,M,y]=(next(readint) for i in range(4)) d=abs(y-x) def interval(a,b): return range(a,b+1) def case1(N,M,d): # d>=N ans=0 for r in interval(1, min(M,d-N)): ans+=1 if (M<=d-N): return ans for r in interval(...
{ "input": [ "3 3 4 7\n", "1 0 1 2\n", "1 0 1 1\n" ], "output": [ " 17\n", " 3\n", " 4\n" ] }
430
8
Of course our child likes walking in a zoo. The zoo has n areas, that are numbered from 1 to n. The i-th area contains ai animals in it. Also there are m roads in the zoo, and each road connects two distinct areas. Naturally the zoo is connected, so you can reach any area of the zoo from any other area using the roads....
R = lambda:map(int, input().split()) n, m = R() a = list(R()) p, f, sz =[], [], [] e = [[] for i in range(n)] vis = [0] * n ans = 0 def find(u): if f[u] != u: f[u] = find(f[u]) return f[u] for i in range(n): p.append([a[i], i]) f.append(i) sz.append(1) p.sort() p.reverse() for i in range(m)...
{ "input": [ "7 8\n40 20 10 30 20 50 40\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n1 4\n5 7\n", "3 3\n10 20 30\n1 2\n2 3\n3 1\n", "4 3\n10 20 30 40\n1 3\n2 3\n4 3\n" ], "output": [ "18.5714285714\n", "13.3333333333\n", "16.6666666667\n" ] }
431
9
Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1, p2, ..., pn. Your task is to find such permutation p of length n, that the group of numbers |p1 - p2|, |p2 - p3|, ..., |pn - 1 - pn| has exactly k d...
def getLine(): return list(map(int,input().split())) n,k = getLine() l = [0]*n for i in range(n): if i%2 == 0:l[i] = i//2+1 else : l[i] = n - l[i-1]+1 ans=l for i in range(k,n): if k%2 == 0:l[i] = l[i-1]-1 else : l[i] = l[i-1]+1 for i in ans: print(i,end=" ")
{ "input": [ "5 2\n", "3 1\n", "3 2\n" ], "output": [ "1 3 2 4 5 ", "1 2 3 \n", "1 3 2 " ] }
432
9
Amr bought a new video game "Guess Your Way Out!". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height h. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node. Let's index all the leaf nodes from the left to ...
def main(): h, n = (map(int, input().split())) c, m = 0, 2 ** h r = 0 while m > 1: if c == 0: if n > (m//2): r += m - 1 n -= m//2 c = 1 - c else: if n > m//2: n -= m//2 else: r += m - 1 c = 1 - c c = 1 - c r += 1 m //= 2 print(r) if __name__ == '__main__': main() ...
{ "input": [ "1 2\n", "10 1024\n", "3 6\n", "2 3\n" ], "output": [ "2\n", "2046\n", "10\n", "5\n" ] }
433
10
Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water. The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: ...
#!/usr/bin/env python # 556D_fug.py - Codeforces.com 556D Fug quiz # # Copyright (C) 2015 Sergey # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2...
{ "input": [ "4 4\n1 4\n7 8\n9 10\n12 14\n4 5 3 8\n", "2 2\n11 14\n17 18\n2 9\n", "2 1\n1 1\n1000000000000000000 1000000000000000000\n999999999999999999\n" ], "output": [ "Yes\n2 3 1 ", "No", "Yes\n1 " ] }
434
8
You are given an array of positive integers a1, a2, ..., an Γ— T of length n Γ— T. We know that for any i > n it is true that ai = ai - n. Find the length of the longest non-decreasing sequence of the given array. Input The first line contains two space-separated integers: n, T (1 ≀ n ≀ 100, 1 ≀ T ≀ 107). The second li...
mul=lambda A,B,r:[[max([A[i][k]+B[k][j] for k in r if A[i][k] and B[k][j]],default=0) for j in r] for i in r] def binpower(A,n,e): r = range(n) B = A #A^0 is invalid, thus start from A^1 e -= 1 while True: if e &1: B = mul(B,A,r) e =e>>1 if e==0: return B A =mul(A,A,r...
{ "input": [ "4 3\n3 1 4 2\n" ], "output": [ "5\n" ] }
435
8
Kevin Sun wants to move his precious collection of n cowbells from Naperthrill to Exeter, where there is actually grass instead of corn. Before moving, he must pack his cowbells into k boxes of a fixed size. In order to keep his collection safe during transportation, he won't place more than two cowbells into a single ...
def main(): n, k = map(int, input().split()) l = list(map(int, input().split())) for i, x in zip(range((n - k) * 2 - 1, n - k - 1, -1), l): l[i] += x print(max(l)) if __name__ == '__main__': main()
{ "input": [ "4 3\n2 3 5 9\n", "2 1\n2 5\n", "3 2\n3 5 7\n" ], "output": [ "9\n", "7\n", "8\n" ] }
436
11
Define the simple skewness of a collection of numbers to be the collection's mean minus its median. You are given a list of n (not necessarily distinct) integers. Find the non-empty subset (with repetition) with the maximum simple skewness. The mean of a collection is the average of its elements. The median of a colle...
from itertools import accumulate from fractions import Fraction n = int(input()) A = [int(x) for x in input().split()] A.sort() B = list(accumulate([0] + A)) def condition(i, z): return (2*z - 1)*(A[i-z] + A[-z]) > 2*(B[i+1] - B[i-z+1] + B[-1] - B[-z]) def average(i, z): return Fraction((B[i+1] - B[i-z] + B[-1...
{ "input": [ "2\n1 2\n", "4\n1 1 2 2\n", "4\n1 2 3 12\n" ], "output": [ "1\n 1 \n", "3\n 1 1 ...
437
7
Nicholas has an array a that contains n distinct integers from 1 to n. In other words, Nicholas has a permutation of size n. Nicholas want the minimum element (integer 1) and the maximum element (integer n) to be as far as possible from each other. He wants to perform exactly one swap in order to maximize the distance...
def answer(): a =int(input()) b = input().split() b = [int(x) for x in b] up=max(b) down=min(b) print(max(len(b)-b.index(up)-1,len(b)-b.index(down)-1,b.index(up),b.index(down))) answer()
{ "input": [ "6\n6 5 4 3 2 1\n", "7\n1 6 5 3 4 7 2\n", "5\n4 5 1 3 2\n" ], "output": [ "5\n", "6\n", "3\n" ] }
438
7
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy...
def vectorsum(a,b): return [a[i]+b[i] for i in range(3)] n = int(input()) V = [0,0,0] for i in range(n): V = vectorsum(V,[int(x) for x in input().split()]) print(['NO','YES'][V==[0,0,0]])
{ "input": [ "3\n3 -1 7\n-5 2 -4\n2 -1 -3\n", "3\n4 1 7\n-2 4 -1\n1 -5 -3\n" ], "output": [ "YES\n", "NO\n" ] }
439
7
There exists an island called Arpa’s land, some beautiful girls live there, as ugly ones do. Mehrdad wants to become minister of Arpa’s land. Arpa has prepared an exam. Exam has only one question, given n, print the last digit of 1378n. <image> Mehrdad has become quite confused and wants you to help him. Please hel...
def main(): print(pow(8, int(input()), 10)) main()
{ "input": [ "2\n", "1\n" ], "output": [ "4\n", "8\n" ] }
440
11
Vanya wants to minimize a tree. He can perform the following operation multiple times: choose a vertex v, and two disjoint (except for v) paths of equal length a0 = v, a1, ..., ak, and b0 = v, b1, ..., bk. Additionally, vertices a1, ..., ak, b1, ..., bk must not have any neighbours in the tree other than adjacent verti...
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time sys.setrecursionlimit(10**7) inf = 10**20 mod = 10**9 + 7 def LI(): return list(map(int, input().split())) def II(): return int(input()) def LS(): return input().split() def S(): return input() def main(): n = II() d = ...
{ "input": [ "6\n1 2\n2 3\n2 4\n4 5\n1 6\n", "7\n1 2\n1 3\n3 4\n1 5\n5 6\n6 7\n" ], "output": [ "3\n", "-1\n" ] }
441
8
Masha really loves algebra. On the last lesson, her strict teacher Dvastan gave she new exercise. You are given geometric progression b defined by two integers b1 and q. Remind that a geometric progression is a sequence of integers b1, b2, b3, ..., where for each i > 1 the respective term satisfies the condition bi = ...
#!/usr/bin/env python3 from math import * def ri(): return map(int, input().split()) b, q, l, m = ri() a = list(ri()) ans = 0 if abs(b) <= l: if not b in a: ans+=1 else: print(0) exit() i = 0 while True: i += 1 b = b*q if b in a: pass elif abs(b) <= l: ans+=...
{ "input": [ "123 1 2143435 4\n123 11 -5453 141245\n", "3 2 30 4\n6 14 25 48\n", "123 1 2143435 4\n54343 -13 6 124\n" ], "output": [ "0\n", "3\n", "inf\n" ] }
442
10
For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all. Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who ...
def li(): return list(map(int, input().split(" "))) for _ in range(int(input())): a, b=li() if b != 0 and a != 0: s = (max(0, a-4*b) + a)/2 s*=min((a/4), b) ans = 1/2 + s/(2*a*b) print("{:.8f}".format(ans)) elif b == 0: print(1) else: print(0.5)
{ "input": [ "2\n4 2\n1 2\n" ], "output": [ "0.6250000000\n0.5312500000\n" ] }
443
8
Some natural number was written on the board. Its sum of digits was not less than k. But you were distracted a bit, and someone changed this number to n, replacing some digits with others. It's known that the length of the number didn't change. You have to find the minimum number of digits in which these two numbers c...
def r(): return list(map(int, input().split())) k = int(input()) s = sorted(map(int, input())) ck, i = sum(s), 0 while ck < k: ck += 9 - s[i] i += 1 print(i)
{ "input": [ "3\n11\n", "3\n99\n" ], "output": [ "1\n", "0\n" ] }
444
9
Two best friends Serozha and Gena play a game. Initially there is one pile consisting of n stones on the table. During one move one pile should be taken and divided into an arbitrary number of piles consisting of a1 > a2 > ... > ak > 0 stones. The piles should meet the condition a1 - a2 = a2 - a3 = ... = ak - 1 - ak =...
import math from collections import Counter n = int(input()) g = [0 for i in range(n + 1)] prefix_xor = g.copy() def in_range(d, k): if (2 * k - d * d + d) % (2 * d) != 0: return -1 x = (2 * k - d * d + d) / (2 * d) return int(x) if x > 0 else -1 def mex(arr): counter = Counter() for i ...
{ "input": [ "6\n", "100\n", "3\n" ], "output": [ "-1\n", "8\n", "2\n" ] }
445
11
We had a string s consisting of n lowercase Latin letters. We made k copies of this string, thus obtaining k identical strings s1, s2, ..., sk. After that, in each of these strings we swapped exactly two characters (the characters we swapped could be identical, but they had different indices in the string). You are gi...
import collections def swapCharacters(strings, k, n): """ Time: O(n^2 * k) Space: O(1) """ if k == 1: s0 = list(strings[0]) s0[0], s0[1] = s0[1], s0[0] return ''.join(s0) # Initial check for validity freq = collections.Counter(strings[0]) canSame = (max(freq.values()) >= 2) # could swap two of the same...
{ "input": [ "5 4\nabcd\ndcba\nacbd\ndbca\nzzzz\n", "3 4\nabac\ncaab\nacba\n", "3 4\nkbbu\nkbub\nubkb\n" ], "output": [ "-1\n", "acab\n", "kbub\n" ] }
446
7
You received a notebook which is called Death Note. This notebook has infinite number of pages. A rule is written on the last page (huh) of this notebook. It says: "You have to write names in this notebook during n consecutive days. During the i-th day you have to write exactly a_i names.". You got scared (of course yo...
def main(): n, m = map(int, input().split()) a_string = input() a = map(int, a_string.split()) t = [] used = 0 for ai in a: used += ai t.append(used // m) used %= m print(*t) main()
{ "input": [ "1 100\n99\n", "4 20\n10 9 19 2\n", "3 5\n3 7 9\n" ], "output": [ "0\n", "0 0 1 1\n", "0 2 1\n" ] }
447
7
The average miner Vaganych took refresher courses. As soon as a miner completes the courses, he should take exams. The hardest one is a computer test called "Testing Pants for Sadness". The test consists of n questions; the questions are to be answered strictly in the order in which they are given, from question 1 to ...
n=int(input()) arr=[int(x) for x in input().split()] ans=0 def func(i): return (i+1)*(arr[i]-1)+1 for i in range(n): ans+=func(i) print(ans)
{ "input": [ "2\n2 2\n", "2\n1 1\n", "1\n10\n" ], "output": [ "5", "2", "10" ] }
448
8
JATC's math teacher always gives the class some interesting math problems so that they don't get bored. Today the problem is as follows. Given an integer n, you can perform the following operations zero or more times: * mul x: multiplies n by x (where x is an arbitrary positive integer). * sqrt: replaces n with √...
def smol(n): prod = 1 orig = n d = 2 while d*d <= orig and n>1: if n%d == 0: prod *= d while n % d == 0: n //=d d += 1 if n > 1: prod *= n return prod num = int(input()) small = smol(num) ans = 0 while small%num > 0: small *= sm...
{ "input": [ "20\n", "5184\n" ], "output": [ "10 2\n", "6 4\n" ] }
449
7
The Fair Nut lives in n story house. a_i people live on the i-th floor of the house. Every person uses elevator twice a day: to get from the floor where he/she lives to the ground (first) floor and to get from the first floor to the floor where he/she lives, when he/she comes back home in the evening. It was decided ...
def solve(): _ = map(int, input()) m = list(map(int, input().split())) answer = 0 for i in range(len(m)): answer += i*4*m[i] return answer print(solve())
{ "input": [ "2\n1 1\n", "3\n0 2 1\n" ], "output": [ "4\n", "16\n" ] }
450
9
Cowboy Vlad has a birthday today! There are n children who came to the celebration. In order to greet Vlad, the children decided to form a circle around him. Among the children who came, there are both tall and low, so if they stand in a circle arbitrarily, it may turn out, that there is a tall and low child standing n...
def main(): n = int(input()) height = list(map(int, input().split())) height.sort() odd = height[::2] even = height[1::2] even.reverse() print(' '.join(map(str, odd + even))) main()
{ "input": [ "3\n30 10 20\n", "5\n2 1 1 3 2\n" ], "output": [ "10 30 20 ", "1 2 3 2 1 " ] }
451
11
The Kingdom of Kremland is a tree (a connected undirected graph without cycles) consisting of n vertices. Each vertex i has its own value a_i. All vertices are connected in series by edges. Formally, for every 1 ≀ i < n there is an edge between the vertices of i and i+1. Denote the function f(l, r), which takes two in...
N = int(input()) A = [int(a) for a in input().split()] def calc(a0, b0): a, b = min(a0, b0), max(a0, b0) return b-1 + (a-1) * (b-a-1) + N-a + (b-a-1) * (N-b) def calc0(a): return N+(a-1)*(N-a) s = calc0(A[0]) + calc0(A[-1]) for i in range(N-1): s += calc(A[i], A[i+1]) print(s//2)
{ "input": [ "3\n2 1 3\n", "10\n1 5 2 5 5 3 10 6 5 1\n", "4\n2 1 1 3\n" ], "output": [ "7\n", "104\n", "11\n" ] }
452
10
Nauuo is a girl who loves drawing circles. One day she has drawn a circle and wanted to draw a tree on it. The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n. Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points o...
import sys def topological_sort_tree(E, p): Q = [p] L = [] visited = set([p]) while Q: p = Q.pop() L.append(p) for vf in E[p]: if vf not in visited: visited.add(vf) Q.append(vf) return L def getpar(Edge, p): N = len(Edge) ...
{ "input": [ "4\n1 2\n1 3\n1 4\n", "4\n1 2\n1 3\n2 4\n" ], "output": [ "24\n", "16\n" ] }
453
7
Tokitsukaze is one of the characters in the game "Kantai Collection". In this game, every character has a common attribute β€” health points, shortened to HP. In general, different values of HP are grouped into 4 categories: * Category A if HP is in the form of (4 n + 1), that is, when divided by 4, the remainder is ...
def f(x): return 'DACB'[x % 4] n = int(input()) x = min(range(n, n + 3), key=f) print(x - n, f(x))
{ "input": [ "33\n", "98\n" ], "output": [ "0 A\n", "1 B\n" ] }
454
10
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya has a number consisting of n digits without leading zeroes. He represented it as an array of d...
def solve(n, k, digits): if k == 0: return ''.join(digits) for i in range(n): r_i = i + 1 if digits[i] == "4" and i < (n - 1) and digits[i + 1] == "7": if r_i % 2 == 1: digits[i + 1] = "4" else: digits[i] = "7" k = k - 1 if k == 0: break if digits[i] == "7" and i - 1 >= 0 and digits[i -...
{ "input": [ "4 2\n4478\n", "7 4\n4727447\n" ], "output": [ "4478\n", "4427477\n" ] }
455
9
You are given a huge integer a consisting of n digits (n is between 1 and 3 β‹… 10^5, inclusive). It may contain leading zeros. You can swap two digits on adjacent (neighboring) positions if the swapping digits are of different parity (that is, they have different remainders when divided by 2). For example, if a = 032...
from collections import deque def move(t): od = deque() ev = deque() for x in t: if int(x)%2: od.append(x) else: ev.append(x) ans = list() while od and ev: if od[0] < ev[0]: ans.append(od.popleft()) else: ans.append(ev.popleft()) ans += od ans += ev return "".joi...
{ "input": [ "3\n0709\n1337\n246432\n" ], "output": [ "0079\n1337\n234642\n" ] }
456
7
A new delivery of clothing has arrived today to the clothing store. This delivery consists of a ties, b scarves, c vests and d jackets. The store does not sell single clothing items β€” instead, it sells suits of two types: * a suit of the first type consists of one tie and one jacket; * a suit of the second type ...
def suit(n): ret = (C[4] * n) + min(C[1], C[2], C[3]-n)*C[5] return ret C = [] for i in range(6): C.append(int(input())) ans = 0 for i in range(min(C[0], C[3])+1): ans = max(ans, suit(i)) print(ans)
{ "input": [ "4\n5\n6\n3\n1\n2\n", "17\n14\n5\n21\n15\n17\n", "12\n11\n13\n20\n4\n6\n" ], "output": [ "6\n", "325\n", "102\n" ] }
457
8
There is a robot in a warehouse and n packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0, 0). The i-th package is at the point (x_i, y_i). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point ...
def get(): n = int(input()) c = [(0, 0)] for i in range(n): c.append(tuple(map(int, input().split()))) c.sort() way = '' for i in range(n): if c[i + 1][0] - c[i][0] < 0 or c[i + 1][1] - c[i][1] < 0: return 'NO' else:way+=(c[i + 1][0] - c[i][0])*'R'+(c[i + 1][1] - c[i][1])...
{ "input": [ "3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3\n" ], "output": [ "YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU\n" ] }
458
8
After a long party Petya decided to return home, but he turned out to be at the opposite end of the town from his home. There are n crossroads in the line in the town, and there is either the bus or the tram station at each crossroad. The crossroads are represented as a string s of length n, where s_i = A, if there is...
def solve(s, a, b, p): index = len(s) totalSum = 0 while totalSum <= p and index > 0: index -= 1 if index == len(s) - 1 or s[index - 1] != s[index]: totalSum += a if s[index - 1] == "A" else b return index + 1 for case in range(int(input())): a,b,p = map(int, input().sp...
{ "input": [ "5\n2 2 1\nBB\n1 1 1\nAB\n3 2 8\nAABBBBAABB\n5 3 4\nBBBBB\n2 1 1\nABABAB\n" ], "output": [ "2\n1\n3\n1\n6\n" ] }
459
11
This is the easy version of the problem. The only difference between easy and hard versions is the constraint of m. You can make hacks only if both versions are solved. Chiori loves dolls and now she is going to decorate her bedroom! <image> As a doll collector, Chiori has got n dolls. The i-th doll has a non-negati...
MOD = 998244353 BOUND = 19 n, m = map(int, input().split()) l = list(map(int,input().split())) basis = [] for p in range(m-1,-1,-1): p2 = pow(2,p) nex = -1 for i in range(n): if l[i] >= p2: nex = l[i] break if nex != -1: basis.append(nex) for i in rang...
{ "input": [ "6 7\n11 45 14 9 19 81\n", "4 4\n3 5 8 14\n" ], "output": [ "1 2 11 20 15 10 5 0 \n", "2 2 6 6 0 \n" ] }
460
8
You might have remembered Theatre square from the [problem 1A](https://codeforces.com/problemset/problem/1/A). Now it's finally getting repaved. The square still has a rectangular shape of n Γ— m meters. However, the picture is about to get more complicated now. Let a_{i,j} be the j-th square in the i-th row of the pav...
import sys def I(): return sys.stdin.readline().rstrip() for tc in range(1, 1+int(I())): R, C, x, y = map(int, I().split()) y = min(y, 2 * x) ans = 0 for row in range(R): for s in I().split('*'): ans += len(s) // 2 * y ans += len(s) % 2 * x print(ans)
{ "input": [ "4\n1 1 10 1\n.\n1 2 10 1\n..\n2 1 10 1\n.\n.\n3 3 3 7\n..*\n*..\n.*.\n" ], "output": [ "10\n1\n20\n18\n" ] }
461
10
There are many freight trains departing from Kirnes planet every day. One day on that planet consists of h hours, and each hour consists of m minutes, where m is an even number. Currently, there are n freight trains, and they depart every day at the same time: i-th train departs at h_i hours and m_i minutes. The gover...
import sys import re def minp(): return sys.stdin.readline().strip() def mint(): return int(minp()) def mints(): return map(int, minp().split()) def solve(): n, h, m, k = mints() m //= 2 a = [0]*n e = [None]*(2*n+2) c = 0 for i in range(n): hh, mm = mints() x = mm % m a[i] = mm e[2*i] = ((x+k)%m, -...
{ "input": [ "2 24 60 16\n16 0\n17 15\n", "2 24 60 15\n16 0\n17 15\n" ], "output": [ "1 0\n2 ", "0 0\n" ] }
462
8
Having bought his own apartment, Boris decided to paper the walls in every room. Boris's flat has n rooms, each of which has the form of a rectangular parallelepiped. For every room we known its length, width and height of the walls in meters (different rooms can have different dimensions, including height). Boris cho...
n = int(input()) rooms = [] for _ in range(n): rooms.append(list(map(int, input().split()))) m = int(input()) wallpapers = [] for _ in range(m): wallpapers.append(list(map(int, input().split()))) def room_cost(room, wallpapers): min_cost = 10**18 parimeter = 2 * (room[0] + room[1]) if room[2] == ...
{ "input": [ "1\n5 5 3\n3\n10 1 100\n15 2 320\n3 19 500\n" ], "output": [ "640\n" ] }
463
12
A famous gang of pirates, Sea Dogs, has come back to their hideout from one of their extravagant plunders. They want to split their treasure fairly amongst themselves, that is why You, their trusted financial advisor, devised a game to help them: All of them take a sit at their round table, some of them with the golde...
import os import sys from io import BytesIO, IOBase # region fastio 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...
{ "input": [ "4 2\n1 2\n2 2\n", "3 2\n1 1\n2 2\n", "6 2\n2 3\n4 1\n" ], "output": [ "1", "-1", "1" ] }
464
7
You are given two integers n and k. You are asked to choose maximum number of distinct integers from 1 to n so that there is no subset of chosen numbers with sum equal to k. A subset of a set is a set that can be obtained from initial one by removing some (possibly all or none) elements of it. Input The first line c...
def solve1(): n, k = map(int,input().split()) a = [] for i in range(k+1,n+1): a.append(i) t = (k+1)//2 for i in range(t,k): a.append(i) print(len(a)) print(*a) for testis in range(int(input())): solve1()
{ "input": [ "3\n3 2\n5 3\n1 1\n" ], "output": [ "\n2\n3 1 \n3\n4 5 2 \n0\n\n" ] }
465
7
Input The input contains two integers a1, a2 (0 ≀ ai ≀ 109), separated by a single space. Output Output a single integer. Examples Input 3 14 Output 44 Input 27 12 Output 48 Input 100 200 Output 102
#!/usr/bin/python3 def readln(): return tuple(map(int, input().split())) a, b = readln() print(a + int(''.join(reversed(list(str(b))))))
{ "input": [ "27 12\n", "3 14\n", "100 200\n" ], "output": [ "48\n", "44\n", "102\n" ] }
466
10
Berland starts to seize the initiative on the war with Flatland. To drive the enemy from their native land, the berlanders need to know exactly how many more flatland soldiers are left in the enemy's reserve. Fortunately, the scouts captured an enemy in the morning, who had a secret encrypted message with the informati...
def answer(): ans,count,j=0,0,0 d=dict() for i in range(n): while(j==0 or d[a[j-1]] < k): if(j==n): j+=1 break try:d[a[j]]+=1 except:d[a[j]]=1 count += 1 m=n-count+1 j+=1 if(...
{ "input": [ "5 3\n1 2 1 1 3\n", "4 2\n1 2 1 2\n", "3 1\n1 1 1\n" ], "output": [ " 2\n", " 3\n", " 6\n" ...
467
8
Vasya has found a piece of paper with a coordinate system written on it. There are n distinct squares drawn in this coordinate system. Let's number the squares with integers from 1 to n. It turned out that points with coordinates (0, 0) and (ai, ai) are the opposite corners of the i-th square. Vasya wants to find such...
#!/usr/bin/python def next_split(): return input().split() n, k = map(int, next_split()) data = list(map(int, next_split())) if k > n: print(-1) exit(0) data.sort(reverse = True) print(data[k - 1], 0)
{ "input": [ "3 1\n2 4 1\n", "4 3\n5 1 3 4\n", "4 50\n5 1 10 2\n" ], "output": [ "4 4\n", "3 3\n", "-1\n" ] }
468
8
Vova, the Ultimate Thule new shaman, wants to build a pipeline. As there are exactly n houses in Ultimate Thule, Vova wants the city to have exactly n pipes, each such pipe should be connected to the water supply. A pipe can be connected to the water supply if there's water flowing out of it. Initially Vova has only on...
N, K = map(int, input().split()) def in_bounds(k): return N <= K*(K+1)//2 - (K-k)*(K-k+1)//2 - k + 1 l = 0 r = K while l <= r: c = (l + r) // 2 if in_bounds(c): r = c - 1 else: l = c + 1 if in_bounds(K): print(l) else: print(-1)
{ "input": [ "4 3\n", "8 4\n", "5 5\n" ], "output": [ "2\n", "-1\n", "1\n" ] }
469
8
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is <image> for SmallR while <image> for Zanoes. The one who shoots in the target first should be the winner. Output the probability th...
##B def main(): a,b,c,d=map(int,input().split()) PA=a/b PB=c/d qA=1-PA qB=1-PB print((PA/(1-qA*qB))) main()
{ "input": [ "1 2 1 2\n" ], "output": [ "0.666666667\n" ] }
470
9
Now it's time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. They've been best friends ever since primary school and hopefully, that can somehow help them in teamwork. For each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing ...
def main(): n, m = map(int, input().split()) c = [0] * (n + 1) for i in range(1, m + 1): c[i % (n + 1)] += 1 if (len(c) > 2 and min(c[1:-1]) == 0) or max(c) > 2: print(-1) else: print('0'.join('1' * x for x in c)) if __name__ == '__main__': main()
{ "input": [ "4 8\n", "1 5\n", "1 2\n", "4 10\n" ], "output": [ "110110110110\n", "-1\n", "110\n", "11011011011011\n" ] }
471
10
Iahub and Sorin are the best competitive programmers in their town. However, they can't both qualify to an important contest. The selection will be made with the help of a single problem. Blatnatalag, a friend of Iahub, managed to get hold of the problem before the contest. Because he wants to make sure Iahub will be t...
import os import math cumsum = [int(x) for x in os.read(0, os.fstat(0).st_size).split()] n = cumsum[0] cumsum[0] = 0 for i in range(n): cumsum[i+1] += cumsum[i] def work(besta, i, sqrtbesta, lowerbound, upperbound, cumsumi): for j in range(i+1, min(n, i - 1 + sqrtbesta) + 1): if lowerbound < cumsum[j]...
{ "input": [ "4\n1 0 0 -1\n", "2\n1 -1\n" ], "output": [ "1\n", "2\n" ] }
472
8
Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array a consisting of n distinct integers. Unfortunately, the size of a is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question correctly:...
def reverse(a): return a[::-1] n=int(input()) a=[int(i) for i in input().split()] b=sorted(a) if a==b: print("yes") print(1,1) exit(0) for i in range(n): if a[i] != b[i]: x=a.index(b[i]) y=i break if b == a[:y]+reverse(a[y:x+1])+a[x+1:]: print("yes") print(y+1,x+1) el...
{ "input": [ "2\n1 2\n", "4\n2 1 3 4\n", "4\n3 1 2 4\n", "3\n3 2 1\n" ], "output": [ "yes\n1 1\n", "yes\n1 2\n", "no\n", "yes\n1 3\n" ] }
473
7
Our good friend Mole is trying to code a big message. He is typing on an unusual keyboard with characters arranged in following way: qwertyuiop asdfghjkl; zxcvbnm,./ Unfortunately Mole is blind, so sometimes it is problem for him to put his hands accurately. He accidentally move...
def main(): v = -1 if input() == 'R' else 1 table = 'qwertyuiopasdfghjkl;zxcvbnm,./' s = input() t = ''.join([table[table.find(x) + v] for x in s]) print ( t ) main()
{ "input": [ "R\ns;;upimrrfod;pbr\n" ], "output": [ "allyouneedislove\n" ] }
474
7
Vasya became interested in bioinformatics. He's going to write an article about similar cyclic DNA sequences, so he invented a new method for determining the similarity of cyclic sequences. Let's assume that strings s and t have the same length n, then the function h(s, t) is defined as the number of positions in whic...
def fast_pow(x, y): if y == 0: return 1 p = fast_pow(x, y // 2) p = p * p % 1000000007 if y % 2: p = p * x % 1000000007 return p n = int(input()) s = input() cnts = [s.count(ch) for ch in ['A', 'G', 'T', 'C']] k = cnts.count(max(cnts)) if k == 1: print(1) else: print(fast_p...
{ "input": [ "2\nAG\n", "3\nTTT\n", "1\nC\n" ], "output": [ "4\n", "1\n", "1\n" ] }
475
9
Wilbur is playing with a set of n points on the coordinate plane. All points have non-negative integer coordinates. Moreover, if some point (x, y) belongs to the set, then all points (x', y'), such that 0 ≀ x' ≀ x and 0 ≀ y' ≀ y also belong to this set. Now Wilbur wants to number the points in the set he has, that is ...
read = lambda: map(int, input().split()) n = int(input()) Max = {} for i in range(n): x, y = read() s = y - x if s not in Max or y > Max[s]: Max[s] = y cur = {i: max(i, 0) for i in Max} ans = [] def no(): print('NO') exit() for i in read(): if i not in cur: no() y = cur[i] f2 ...
{ "input": [ "5\n2 0\n0 0\n1 0\n1 1\n0 1\n0 -1 -2 1 0\n", "3\n1 0\n0 0\n2 0\n0 1 2\n" ], "output": [ "YES\n0 0\n1 0\n2 0\n0 1\n1 1\n", "NO\n" ] }
476
11
Bob has a favorite number k and ai of length n. Now he asks you to answer m queries. Each query is given by a pair li and ri and asks you to count the number of pairs of integers i and j, such that l ≀ i ≀ j ≀ r and the xor of the numbers ai, ai + 1, ..., aj is equal to k. Input The first line of the input contains i...
# [https://codeforces.com/contest/617/submission/15550846 <- https://codeforces.com/blog/entry/22971 <- https://codeforces.com/problemset/problem/617/E <- https://algoprog.ru/material/pc617pE] BLOCK_SIZE = 316 #sqrt(1e5) class Query: def __init__(self, left, right, number): self.left = left ...
{ "input": [ "6 2 3\n1 2 1 1 0 3\n1 6\n3 5\n", "5 3 1\n1 1 1 1 1\n1 5\n2 4\n1 3\n" ], "output": [ "7\n0\n", "9\n4\n4\n" ] }
477
8
Berland scientists face a very important task - given the parts of short DNA fragments, restore the dinosaur DNA! The genome of a berland dinosaur has noting in common with the genome that we've used to: it can have 26 distinct nucleotide types, a nucleotide of each type can occur at most once. If we assign distinct En...
def main(): ab, tails, res = {}, set(), [] for _ in range(int(input())): a, *s = input() for b in s: ab[a] = a = b tails.add(b) ab.setdefault(a, '') for a in ab.keys(): if a not in tails: while a: res.append(a) ...
{ "input": [ "3\nbcd\nab\ncdef\n", "4\nx\ny\nz\nw\n" ], "output": [ "abcdef\n", "wxyz\n" ] }
478
8
Memory is performing a walk on the two-dimensional plane, starting at the origin. He is given a string s with his directions for motion: * An 'L' indicates he should move one unit left. * An 'R' indicates he should move one unit right. * A 'U' indicates he should move one unit up. * A 'D' indicates he shoul...
def compute(): s = input() if len(s)%2 == 1:return -1 d = {'R':0,'L':0,'U':0,'D':0} for x in s:d[x] += 1 return (abs(d['L']-d['R']) + abs(d['U']-d['D']))//2 print(compute())
{ "input": [ "UDUR\n", "RUUR\n", "RRU\n" ], "output": [ "1\n", "2\n", "-1\n" ] }
479
7
One day, the Grasshopper was jumping on the lawn and found a piece of paper with a string. Grasshopper became interested what is the minimum jump ability he should have in order to be able to reach the far end of the string, jumping only on vowels of the English alphabet. Jump ability is the maximum possible length of ...
v=['A','E','I','O','U','Y'] def fun(c,ss): if not(ss): return c if ss[0] in v: return max(c,fun(1,ss[1:])) return fun(c+1,ss[1:]) ss=input() print(fun(1,ss))
{ "input": [ "ABABBBACFEYUKOTT\n", "AAA\n" ], "output": [ "4\n", "1\n" ] }
480
8
Bash has set out on a journey to become the greatest Pokemon master. To get his first Pokemon, he went to Professor Zulu's Lab. Since Bash is Professor Zulu's favourite student, Zulu allows him to take as many Pokemon from his lab as he pleases. But Zulu warns him that a group of k > 1 Pokemon with strengths {s1, s2, ...
import math factor = [0] * (100001) def factors(x): i = 0 for i in range(2, int(math.sqrt(x)) + 1): if x % i == 0: factor[i] += 1 if x // i != i: factor[x // i] += 1 if x != 1 and i < x: factor[x] += 1 n = int(input()) s = list(map(int, input().split()...
{ "input": [ "5\n2 3 4 6 7\n", "3\n2 3 4\n" ], "output": [ "3\n", "2\n" ] }
481
10
Peter decided to lay a parquet in the room of size n Γ— m, the parquet consists of tiles of size 1 Γ— 2. When the workers laid the parquet, it became clear that the tiles pattern looks not like Peter likes, and workers will have to re-lay it. The workers decided that removing entire parquet and then laying it again is v...
#!/usr/bin/env python3 board = [] n, m = 0, 0 def rotate(x, y): if board[x][y] == 'L': board[x][y] = board[x][y+1] = 'U' board[x+1][y] = board[x+1][y+1] = 'D' else: board[x][y] = board[x+1][y] = 'L' board[x][y+1] = board[x+1][y+1] = 'R' def fix(x, y, moves): if board[x+1][...
{ "input": [ "4 3\nULR\nDLR\nLRU\nLRD\nULR\nDUU\nUDD\nDLR", "2 3\nULR\nDLR\nLRU\nLRD\n" ], "output": [ "5\n1 2\n3 1\n3 2\n1 2\n2 2\n", "2\n1 2\n1 1\n" ] }
482
9
Makes solves problems on Decoforces and lots of other different online judges. Each problem is denoted by its difficulty β€” a positive integer number. Difficulties are measured the same across all the judges (the problem with difficulty d on Decoforces is as hard as the problem with difficulty d on any other judge). M...
def main(): n, k = map(int, input().split()) a = list(map(int, input().split())) a.sort() b = k p = 0 ans = 0 while p < n: while 2 * b < a[p]: b = 2 * b ans += 1 b = max(b, a[p]) p += 1 print(ans) main()
{ "input": [ "4 20\n10 3 6 3\n", "3 3\n2 1 9\n" ], "output": [ "0", "1" ] }
483
7
From beginning till end, this message has been waiting to be conveyed. For a given unordered multiset of n lowercase English letters ("multi" means that a letter may appear more than once), we treat all letters as strings of length 1, and repeat the following operation n - 1 times: * Remove any two elements s and t...
def solve(k, c): if k == 0: return c n = 1 while f(n + 1) <= k: n += 1 return c * n + solve(k - f(n), chr(ord(c) + 1)) k = int(input()) f = lambda n: n * (n - 1) // 2 print(solve(k, 'a'))
{ "input": [ "12\n", "3\n" ], "output": [ "aaaaabbcc\n", "aaa\n" ] }
484
8
Arkady wants to water his only flower. Unfortunately, he has a very poor watering system that was designed for n flowers and so it looks like a pipe with n holes. Arkady can only use the water that flows from the first hole. Arkady can block some of the holes, and then pour A liters of water into the pipe. After that,...
def f(l1,l2): n,a,b = l1 s = sum(l2) l = l2[1:] l.sort(reverse=True) i = 0 while b*s>l2[0]*a: s -= l[i] i += 1 return i l1 = list(map(int,input().split())) l2 = list(map(int,input().split())) print(f(l1,l2))
{ "input": [ "4 10 3\n2 2 2 2\n", "5 10 10\n1000 1 1 1 1\n", "4 80 20\n3 2 1 4\n" ], "output": [ "1\n", "4\n", "0\n" ] }
485
8
Two participants are each given a pair of distinct numbers from 1 to 9 such that there's exactly one number that is present in both pairs. They want to figure out the number that matches by using a communication channel you have access to without revealing it to you. Both participants communicated to each other a set ...
def rp(): cs = list(map(int, input().split(' '))) cs = list(zip(cs[0::2], cs[1::2])) return cs def dist(p1, p2): return len(set(p1).union(set(p2))) - 2 input() ps = [rp(), rp()] theyCan = True myPos = set() for ps1, ps2 in [ps, ps[::-1]]: for p1 in ps1: pos = set() for p2 in ps...
{ "input": [ "2 3\n1 2 4 5\n1 2 1 3 2 3\n", "2 2\n1 2 3 4\n1 5 3 4\n", "2 2\n1 2 3 4\n1 5 6 4\n" ], "output": [ "-1", "1", "0" ] }
486
7
You are given a string s consisting of n lowercase Latin letters. n is even. For each position i (1 ≀ i ≀ n) in string s you are required to change the letter on this position either to the previous letter in alphabetic order or to the next one (letters 'a' and 'z' have only one of these options). Letter in every posi...
def solve(n, s): return 'YES' if all([(ord(s[i]) - ord(s[n - 1 - i])) in (-2, 0, 2) for i in range(n)]) else 'NO' for t in range(int(input())): print(solve(int(input()), input()))
{ "input": [ "5\n6\nabccba\n2\ncf\n4\nadfa\n8\nabaazaba\n2\nml\n" ], "output": [ "YES\nNO\nYES\nNO\nNO\n" ] }
487
9
There are n people sitting in a circle, numbered from 1 to n in the order in which they are seated. That is, for all i from 1 to n-1, the people with id i and i+1 are adjacent. People with id n and 1 are adjacent as well. The person with id 1 initially has a ball. He picks a positive integer k at most n, and passes th...
n=int(input()) def fun(a,b): return (a*(2+b*(a-1)))//2 i=1 ans=set() while i*i<=n: if n%i==0: ans.add(fun(n//i,i)) ans.add(fun(i,n//i)) i+=1 print(*sorted(ans))
{ "input": [ "6\n", "16\n" ], "output": [ "1 5 9 21\n", "1 10 28 64 136\n" ] }
488
7
You are given an integer n (n β‰₯ 0) represented with k digits in base (radix) b. So, $$$n = a_1 β‹… b^{k-1} + a_2 β‹… b^{k-2} + … a_{k-1} β‹… b + a_k.$$$ For example, if b=17, k=3 and a=[11, 15, 7] then n=11β‹…17^2+15β‹…17+7=3179+255+7=3441. Determine whether n is even or odd. Input The first line contains two integers b and...
def mp(): return map(int, input().split()) b, k = mp() a = list(mp()) t = a[-1] for i in range(k - 1): t += (a[i] * b) % 2 if t % 2 == 0: print('even') else: print('odd')
{ "input": [ "13 3\n3 2 7\n", "99 5\n32 92 85 74 4\n", "2 2\n1 0\n", "10 9\n1 2 3 4 5 6 7 8 9\n" ], "output": [ "even\n", "odd\n", "even\n", "odd\n" ] }
489
8
Let s be some string consisting of symbols "0" or "1". Let's call a string t a substring of string s, if there exists such number 1 ≀ l ≀ |s| - |t| + 1 that t = s_l s_{l+1} … s_{l + |t| - 1}. Let's call a substring t of string s unique, if there exist only one such l. For example, let s = "1010111". A string t = "010...
from math import * from fractions import * def li(): return list(map(int, input().split(" "))) n,k = li() if k == 1: print("1" + "0"*(n-1)) else: a = (n-k)//2 p = "1" + "0"*a ans = p * (n//(a+1)) + p[:(n%(a+1))] print(ans)
{ "input": [ "4 4\n", "7 3\n", "5 3\n" ], "output": [ "1111\n", "0010010\n", "01010\n" ] }
490
7
While playing with geometric figures Alex has accidentally invented a concept of a n-th order rhombus in a cell grid. A 1-st order rhombus is just a square 1 Γ— 1 (i.e just a cell). A n-th order rhombus for all n β‰₯ 2 one obtains from a n-1-th order rhombus adding all cells which have a common side with it to it (look ...
def f(n):return n if n == 1 else f(n-1)+(n-1)*4 print(f(int(input())))
{ "input": [ "3\n", "1\n", "2\n" ], "output": [ "13\n", "1\n", "5\n" ] }
491
7
For years, the Day of city N was held in the most rainy day of summer. New mayor decided to break this tradition and select a not-so-rainy day for the celebration. The mayor knows the weather forecast for the n days of summer. On the i-th day, a_i millimeters of rain will fall. All values a_i are distinct. The mayor k...
n, x, y = *map(int,input().split()), a = *map(int,input().split()), def check(i): return all(map(lambda x: x > a[i], a[max(0, i-x):i] + a[i+1:i+y+1])) for i in range(n): if check(i): print(i+1) break
{ "input": [ "5 5 5\n100000 10000 1000 100 10\n", "10 2 2\n10 9 6 7 8 3 2 1 4 5\n", "10 2 3\n10 9 6 7 8 3 2 1 4 5\n" ], "output": [ "5\n", "3\n", "8\n" ] }
492
12
In addition to complaints about lighting, a lot of complaints about insufficient radio signal covering has been received by Bertown city hall recently. n complaints were sent to the mayor, all of which are suspiciosly similar to each other: in the i-th complaint, one of the radio fans has mentioned that the signals of ...
# ------------------- fast io -------------------- import os import sys input = lambda: sys.stdin.readline().rstrip("\r\n") # ------------------- fast io -------------------- def find_SCC(graph): SCC, S, P = [], [], [] depth = [0] * len(graph) stack = list(range(len(graph))) while stack: ...
{ "input": [ "2 4 4 2\n1 3\n2 3\n1 4\n1 2\n3 4\n1 4\n1 2\n3 4\n", "2 4 4 2\n1 3\n2 4\n1 2\n1 2\n3 4\n3 4\n1 2\n3 4\n" ], "output": [ "2 3\n1 3 ", "-1" ] }
493
7
Recently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area. To prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of n r...
mod = 1000000007 n,m = map(int, input().split()) def fib(n): a,b = 1,1 for i in range(n): a,b = b,(a+b)%mod return a res = (2*(fib(n) + fib(m) - 1)) % mod print(res)
{ "input": [ "2 3\n" ], "output": [ "8\n" ] }
494
9
Let's call an array t dominated by value v in the next situation. At first, array t should have at least 2 elements. Now, let's calculate number of occurrences of each number num in t and define it as occ(num). Then t is dominated (by v) if (and only if) occ(v) > occ(v') for any other number v'. For example, arrays [1...
def dominated(n,l): p={} m=n+1 for i in range(n): if l[i] in p.keys(): m=min(m,i-p[l[i]]+1) p[l[i]]=i return m if m!=n+1 else -1 for _ in range(int(input())): n=int(input()) l=list(map(int,input().split())) print(dominated(n,l))
{ "input": [ "4\n1\n1\n6\n1 2 3 4 5 1\n9\n4 1 2 4 5 4 3 2 1\n4\n3 3 3 3\n" ], "output": [ "-1\n6\n3\n2\n" ] }
495
9
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative. She would like to r...
def main(): n = int(input().strip()) A = [int(s) for s in input().strip().split()] for i in range(31, -1, -1): if sum((a >> i) & 1 for a in A) == 1: break for j, a in enumerate(A): if (a >> i) & 1: break result = [A[j]] + A[:j] + A[j + 1:] print(" ".join(...
{ "input": [ "1\n13\n", "4\n4 0 11 6\n" ], "output": [ "13\n", "11 4 0 6 \n" ] }
496
10
The next lecture in a high school requires two topics to be discussed. The i-th topic is interesting by a_i units for the teacher and by b_i units for the students. The pair of topics i and j (i < j) is called good if a_i + a_j > b_i + b_j (i.e. it is more interesting for the teacher). Your task is to find the number...
import bisect def f(n): return (n*(n+1))//2 n=int(input()) a=list(map(int,input().split())) b=list(map(int,input().split())) c=[a[i]-b[i] for i in range(n)] c.sort() ans=0 for i in range(n): x=1-c[i] j=bisect.bisect_left(c,x,i+1,n) ans+=n-j print(ans)
{ "input": [ "4\n1 3 2 4\n1 3 2 4\n", "5\n4 8 2 6 2\n4 5 4 1 3\n" ], "output": [ "0\n", "7\n" ] }
497
9
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [...
def solve(): n=int(input()) lis=list(map(int,input().split())) j=0 ans=0 for i,v in enumerate(lis[1:],1): if v*lis[j]<0: ans+=max(lis[j:i]) j=i ans+=max(lis[j:]) print(ans) t=int(input()) for i in range(t): solve()
{ "input": [ "4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000\n" ], "output": [ "2\n-1\n6\n-2999999997\n" ] }
498
10
Vivek has encountered a problem. He has a maze that can be represented as an n Γ— m grid. Each of the grid cells may represent the following: * Empty β€” '.' * Wall β€” '#' * Good person β€” 'G' * Bad person β€” 'B' The only escape from the maze is at cell (n, m). A person can move to a cell only if it shares a...
from math import * def r1(t): return t(input()) def r2(t): return [t(i) for i in input().split()] def r3(t): return [t(i) for i in input()] g=[] def dfs(i,j,n,m): if g[i][j]=='#': return 0 ans=0 if g[i][j]=='G': ans+=1 if g[i][j]=='B': return -100000 g[i][j]='#' if (i>0): ans+=dfs(i-1,j,n,m) if...
{ "input": [ "6\n1 1\n.\n1 2\nG.\n2 2\n#B\nG.\n2 3\nG.#\nB#.\n3 3\n#B.\n#..\nGG.\n2 2\n#B\nB.\n" ], "output": [ "Yes\nYes\nNo\nNo\nYes\nYes\n" ] }
499
10
You are given a string s[1 ... n] consisting of lowercase Latin letters. It is guaranteed that n = 2^k for some integer k β‰₯ 0. The string s[1 ... n] is called c-good if at least one of the following three conditions is satisfied: * The length of s is 1, and it consists of the character c (i.e. s_1=c); * The lengt...
def f(s,c):n=len(s)//2;m=n or 1;return s>''and min(m-s.count(chr(c),i,i+m)+f(s[n-i:][:n],c+1)for i in{0,n}) for s in[*open(0)][2::2]:print(f(s[:-1],97))
{ "input": [ "6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac\n" ], "output": [ "0\n7\n4\n5\n1\n1\n" ] }