problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
The HR manager was disappointed again. The last applicant failed the interview the same way as 24 previous ones. "Do I give such a hard task?" β€” the HR manager thought. "Just raise number 5 to the power of n and get last two digits of the number. Yes, of course, n can be rather big, and one cannot find the power using ...
1
import sys f = sys.stdin print 25
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it [here](http://tiny.cc/636xmz). The picture showing the correct sudoku solution: <image> Blocks are bordered with bold black color. Your task is to change at most 9 elements of this field (i.e. choose s...
3
for _ in range(int(input())): a = [] for i in range(9): a.append(list(map(str, input()))) for i in range(3): for r in range(3): if a[i * 3 + r][r * 3 + i] == '1': a[i * 3 + r][r * 3 + i] = '9' else: a[i * 3 + r][r * 3 + i] = '1' for...
Let's say string s has period k if s_i = s_{i + k} for all i from 1 to |s| - k (|s| means length of string s) and k is the minimum positive integer with this property. Some examples of a period: for s="0101" the period is k=2, for s="0000" the period is k=1, for s="010" the period is k=2, for s="0011" the period is k=...
3
tc = int(input()) for _ in range(tc): s = list(input()) if s.count('1') in (len(s), 0): print(''.join(s)) else: i = 1 while i < len(s): if s[i] == s[i - 1]: s.insert(i, '0' if s[i] == '1' else '1') i += 1 print(''.join(s))
The time is 2020. There is data that saves the qualifying results of PC Koshien 2020. This data stores the reference number and the number of correct answers assigned to each team. Here, the ranking is determined by the number of correct answers, and the ranking is given in descending order of the number of correct ans...
3
t = [0] * 101 while 1: p, s = map(int, input().split(',')) if p == s == 0: break t[p] = s rank = list(set(t)) rank.sort(reverse=True) while 1: try: n = int(input()) print(rank.index(t[n])+1) except: break
Each day in Berland consists of n hours. Polycarp likes time management. That's why he has a fixed schedule for each day β€” it is a sequence a_1, a_2, ..., a_n (each a_i is either 0 or 1), where a_i=0 if Polycarp works during the i-th hour of the day and a_i=1 if Polycarp rests during the i-th hour of the day. Days go ...
3
n = int(input()) first = -1 last = -1 longest = 0 cur = 0 for i, inp in enumerate(input().split()): inp = int(inp) if inp == 1: cur += 1 longest = max(cur, longest) elif inp == 0: cur = 0 if first == -1: first = i cur += first longest = max(longest, cur) print(lo...
We call two numbers x and y similar if they have the same parity (the same remainder when divided by 2), or if |x-y|=1. For example, in each of the pairs (2, 6), (4, 3), (11, 7), the numbers are similar to each other, and in the pairs (1, 4), (3, 12), they are not. You are given an array a of n (n is even) positive in...
3
for _ in range(int(input())): n=int(input()) a=list(map(int,input().split())) a.sort() o,e=0,0 for z in a: if z&1: o+=1 else: e+=1 diff=0 for i in range(1,n): if a[i]-a[i-1]==1: diff+=1 f=1 if (o&1) and diff==0: f=0 if f: print("YES") else: print("NO")
Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: 1. The product of all numbers in the first set is less than zero ( < 0). 2. The product of all numbers in the second set is greater than zero ( > 0). 3. The product of a...
3
n=int(input()) a=list(map(int,input().split())) n1=[] n2=[] n3=["0"] a.remove(0) n4=[] for i in a: m=True if len(n1)<1 and i<0: n1.append(str(i)) m=False elif m==True and i<0: n2.append(str(i)) elif i>0: n4.append(str(i)) if len(n2)==0: for i in n4: n2.append(...
A permutation of length n is a sequence of integers from 1 to n of length n containing each number exactly once. For example, [1], [4, 3, 5, 1, 2], [3, 2, 1] are permutations, and [1, 1], [0, 1], [2, 2, 1, 4] are not. There was a permutation p[1 ... n]. It was merged with itself. In other words, let's take two instanc...
3
t = int(input()) for i in range(t): n = int(input()) lst1 = list(map(int,input().split())) dict1 = {} ans = [] for i in range(len(lst1)): if lst1[i] in dict1: i+=1 else: ans.append(lst1[i]) dict1[lst1[i]] = 1 for i in range(len(ans)): ...
Dawid has four bags of candies. The i-th of them contains a_i candies. Also, Dawid has two friends. He wants to give each bag to one of his two friends. Is it possible to distribute the bags in such a way that each friend receives the same amount of candies in total? Note, that you can't keep bags for yourself or thro...
3
a, b, c, d = sorted(list(map(int, input().split()))) if a+d == b+c or a+b+c == d: print("YES") else: print('NO')
Takahashi has a maze, which is a grid of H \times W squares with H horizontal rows and W vertical columns. The square at the i-th row from the top and the j-th column is a "wall" square if S_{ij} is `#`, and a "road" square if S_{ij} is `.`. From a road square, you can move to a horizontally or vertically adjacent ro...
3
h,w=map(int,input().split()) g=[input() for _ in range(h)] from collections import * def bfs(x,y): d=[[-1]*w for _ in range(h)] d[x][y]=0 q=deque([(x,y)]) while q: tx,ty=q.popleft() for dx,dy in [(1,0),(0,1),(-1,0),(0,-1)]: nx,ny=tx+dx,ty+dy if 0<=nx<h and 0<=ny<w and g[nx][ny]=='.' and d[nx...
After battling Shikamaru, Tayuya decided that her flute is too predictable, and replaced it with a guitar. The guitar has 6 strings and an infinite number of frets numbered from 1. Fretting the fret number j on the i-th string produces the note a_{i} + j. Tayuya wants to play a melody of n notes. Each note can be play...
3
la = input().split() la = list(map(int,la)) t=input() lb = input().split() lb = list(map(int,lb)) lenb=len(lb) l=[(lb[j]-i,j) for i in la for j in range(lenb)] l.sort() last=0 first=0 l0=[0]*lenb l1=[i for i in range(lenb)] dic=dict(zip(l1,l0)) dic[l[first][1]]+=1 length=1 lenl=len(l) while (length<lenb): last+=1 ...
You are given an array a_1, a_2, ... , a_n. Array is good if for each pair of indexes i < j the condition j - a_j β‰  i - a_i holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option). For example, if a = [1, 1, ...
3
R=lambda:map(int, input().split()) for _ in range(int(input())): n = int(input()) arr = sorted(R(), reverse=True) print(*arr)
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm: * if the last digit of the number is non-zero, she decreases the number by one; * if the last digit of the number is ze...
3
a, b = input().split() a, b = int(a), int(b) while b > 0: b -= 1 ld = a % 10 if ld == 0: a = a/10 else: a -= 1 print(int(a))
A family consisting of father bear, mother bear and son bear owns three cars. Father bear can climb into the largest car and he likes it. Also, mother bear can climb into the middle car and she likes it. Moreover, son bear can climb into the smallest car and he likes it. It's known that the largest car is strictly larg...
3
a=list(map(int,input().split())) if a[3]>2*a[2] or 2*a[3]<a[2] or a[3]>=a[1]: print("-1") else: print(2*a[0],2*a[1],min(2*a[2],2*a[3]))
You are given a positive integer x. Find any such 2 positive integers a and b such that GCD(a,b)+LCM(a,b)=x. As a reminder, GCD(a,b) is the greatest integer that divides both a and b. Similarly, LCM(a,b) is the smallest integer such that both a and b divide it. It's guaranteed that the solution always exists. If ther...
3
if __name__ == '__main__': problems = int(input()) for problem in range(problems): n = int(input()) print("1 "+str(n-1))
A penguin Rocher has n sticks. He has exactly one stick with length i for all 1 ≀ i ≀ n. He can connect some sticks. If he connects two sticks that have lengths a and b, he gets one stick with length a + b. Two sticks, that were used in the operation disappear from his set and the new connected stick appears in his se...
3
for z in range(int(input())): n = int(input()) n-=1 ans = (n//2)+1 print(ans)
There are two popular keyboard layouts in Berland, they differ only in letters positions. All the other keys are the same. In Berland they use alphabet with 26 letters which coincides with English alphabet. You are given two strings consisting of 26 distinct letters each: all keys of the first and the second layouts i...
3
S = str(input()) chars = [] chars2 = [] chars3 = [] chars4 = [] chars5 =[] chars7 = [] chars6 = [] chars8 = [] count2 = "" for i in S: chars.append(i) S2 = str(input()) S3 = str(input()) for i in S2: chars2.append(i) for i in S3: chars3.append(i) for i in range(0, len(chars3)): if chars.count(chars3[i]....
You are given one integer number n. Find three distinct integers a, b, c such that 2 ≀ a, b, c and a β‹… b β‹… c = n or say that it is impossible to do it. If there are several answers, you can print any. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 100)...
3
''' بِسْمِ Ψ§Ω„Ω„ΩŽΩ‘Ω‡Ω Ψ§Ω„Ψ±ΩŽΩ‘Ψ­Ω’Ω…ΩŽΩ°Ω†Ω Ψ§Ω„Ψ±ΩŽΩ‘Ψ­ΩΩŠΩ…Ω ''' #codeforces gi = lambda : list(map(int,input().split())) t, = gi() for k in range(t): n, = gi() div = 1 sq = int(n ** .5) for j in range(2, sq + 1): if n % j == 0: div = j break x = n // div sq = int(x ** .5) div2 = 1 for j in range(2, sq + 1): if x % j =...
Among other things, Bob is keen on photography. Especially he likes to take pictures of sportsmen. That was the reason why he placed himself in position x0 of a long straight racetrack and got ready to take pictures. But the problem was that not all the runners passed him. The total amount of sportsmen, training at tha...
1
I=lambda:map(int,raw_input().split()) n, x0 = I() xm = 0 xM = 1000 for _ in range(n): x, X = I() x, X = min(x, X), max(x, X) xm = max(x, xm) xM = min(X, xM) if xM < xm: print(-1) elif xm <= x0 <= xM: print(0) elif x0 < xm: print(xm-x0) else: print(x0-xM)
Mountaineers Mr. Takahashi and Mr. Aoki recently trekked across a certain famous mountain range. The mountain range consists of N mountains, extending from west to east in a straight line as Mt. 1, Mt. 2, ..., Mt. N. Mr. Takahashi traversed the range from the west and Mr. Aoki from the east. The height of Mt. i is h_i...
3
n=int(input()) t=list(map(int,input().split())) a=list(map(int,input().split())) mod=pow(10,9)+7 ans=[[0,0] for _ in range(n)] pre=0 for i in range(n): if t[i]>pre: ans[i]=[t[i],1] else: ans[i]=[t[i],0] pre=t[i] #print(ans) pre=0 for i in range(n-1,-1,-1): if a[i]>pre: if ans[i][1]==0 and ans[i][0]<...
Pasha has a wooden stick of some positive integer length n. He wants to perform exactly three cuts to get four parts of the stick. Each part must have some positive integer length and the sum of these lengths will obviously be n. Pasha likes rectangles but hates squares, so he wonders, how many ways are there to spli...
1
if __name__ == '__main__': n = input() print [n / 2 / 2 - (n % 4 == 0), 0][n % 2]
On the way to Rio de Janeiro Ostap kills time playing with a grasshopper he took with him in a special box. Ostap builds a line of length n such that some cells of this line are empty and some contain obstacles. Then, he places his grasshopper to one of the empty cells and a small insect in another empty cell. The gras...
1
import sys import math line = raw_input() split_line = line.split() n = int(split_line[0]) k = int(split_line[1]) path = raw_input() start = -1 end = -1 for i in range(len(path)): char = path[i] if(char == 'G'): start = i elif(char == 'T'): end = i if(abs(start - end) % k != 0): pri...
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
3
number_of_line=int(input()) word_list=[] for i in range(0,number_of_line): word_list.append(input()) for j in range(0,len(word_list)): if (len(word_list[j])<=10): print(word_list[j]) else: print(word_list[j][:1]+f"{(len(word_list[j])-2)}"+word_list[j][-1:])
The penultimate task involved the calculation of the typical Fibonacci sequence up to the nth term. Input – single integer n Output – Fibonacci sequence up to the nth term, all terms on a new line SAMPLE INPUT 5 SAMPLE OUTPUT 1 1 2 3 5
1
n=input() n+=1 x=5**.5 for i in range(1,n): print int(((.5+x/2)**i-(.5-x/2)**i)/x)
Spongebob is already tired trying to reason his weird actions and calculations, so he simply asked you to find all pairs of n and m, such that there are exactly x distinct squares in the table consisting of n rows and m columns. For example, in a 3 Γ— 5 table there are 15 squares with side one, 8 squares with side two a...
1
x = int(raw_input()) n = 1 ans = [] n_ans = 0 for n in xrange(1,1450000): nume = x + n*(n**2-1)/6 deno = n*(n+1)/2 if n*deno > nume: break if nume % deno == 0: ans.append((n,nume/deno)) n_ans += 1 ub = 1 if ans[n_ans-1][0] == ans[n_ans-1][1] else 0 print n_ans*2 - ub for i in xrange(n_ans): print ans[i][0],ans...
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1. Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divi...
3
n=int(input()) c=0 if(n%2==1): n-=3 l=[2]*(n//2) l.append(3) print(len(l)) print(*l) else: l=[2]*(n//2) print(len(l)) print(*l)
Two little greedy bears have found two pieces of cheese in the forest of weight a and b grams, correspondingly. The bears are so greedy that they are ready to fight for the larger piece. That's where the fox comes in and starts the dialog: "Little bears, wait a little, I want to make your pieces equal" "Come off it fox...
1
a, b = map(int, raw_input().split()) a1, a2, a3 = 0, 0, 0 b1, b2, b3 = 0, 0, 0 while a & 1 == 0: a /= 2 a1 += 1 while a % 3 == 0: a /= 3 a2 += 1 while a % 5 == 0: a /= 5 a3 += 1 while b & 1 == 0: b /= 2 b1 += 1 while b % 3 == 0: b /= 3 b2 += 1 while b % 5 == 0: b /= 5 b3 ...
You've got two rectangular tables with sizes na Γ— ma and nb Γ— mb cells. The tables consist of zeroes and ones. We will consider the rows and columns of both tables indexed starting from 1. Then we will define the element of the first table, located at the intersection of the i-th row and the j-th column, as ai, j; we w...
3
n1,m1=map(int,input().split()) arr1=[] for i in range(n1): arr1.append(list(map(int,list(input())))) n2,m2=map(int,input().split()) arr2=[] for i in range(n2): arr2.append(list(map(int,list(input())))) def foo(x,y): ans=0 for i in range(n1): for j in range(m1): if i+x<n2 and i+x>...
You are given a string s, consisting of n lowercase Latin letters. A substring of string s is a continuous segment of letters from s. For example, "defor" is a substring of "codeforces" and "fors" is not. The length of the substring is the number of letters in it. Let's call some string of length n diverse if and o...
3
n = int(input()) a = input() b = [] flag = 0 c = len(set(a)) for i in range(n-1): if a[i]!=a[i+1]: flag = 1 b.append(a[i]) b.append(a[i+1]) break if flag == 1: print("YES") print(b[0],b[1],sep = "") else: print("NO")
Roy wants to change his profile picture on Facebook. Now Facebook has some restriction over the dimension of picture that we can upload. Minimum dimension of the picture can be L x L, where L is the length of the side of square. Now Roy has N photos of various dimensions. Dimension of a photo is denoted as W x H wh...
1
l = int(raw_input()) n = int(raw_input()) for i in range(n): w,h = map(int, raw_input().split()) if(w < l or h < l): print "UPLOAD ANOTHER" elif (w == h): print "ACCEPTED" else: print "CROP IT"
You are given an array a1, a2, ..., an consisting of n integers, and an integer k. You have to split the array into exactly k non-empty subsegments. You'll then compute the minimum integer on each subsegment, and take the maximum integer over the k obtained minimums. What is the maximum possible integer you can get? D...
3
i, j = map(int, input().split()) a=[int(n) for n in input().split()] if j == 1: minn = min(a) elif j == 2: minn = max(a[0], a[-1]) else: minn = max(a) print(minn)
Tom loves vowels, and he likes long words with many vowels. His favorite words are vowelly words. We say a word of length k is vowelly if there are positive integers n and m such that nβ‹… m = k and when the word is written by using n rows and m columns (the first row is filled first, then the second and so on, with each...
3
n=int(input().strip()) import math q=0 for k in range(5,n+1): if(n%k==0 and (n//k)>=5): a=k b=n//k q=1 pp=['a','e','i','o','u'] if(q==0): print(-1) else: start=0 ss="" for t in range(a): for tt in range(b): ss=ss+pp[(t+tt)%5] print(ss)
Ujan decided to make a new wooden roof for the house. He has n rectangular planks numbered from 1 to n. The i-th plank has size a_i Γ— 1 (that is, the width is 1 and the height is a_i). Now, Ujan wants to make a square roof. He will first choose some of the planks and place them side by side in some order. Then he will...
3
k = int(input()) for i in range(k): n = int(input()) ls = sorted([int(x) for x in input().split()], reverse=True) count = 0 best = 0 for l in ls: if l < best: break count += 1 best = min(l, count) if l == best: break print(best)
Takahashi has a string S consisting of lowercase English letters. Starting with this string, he will produce a new one in the procedure given as follows. The procedure consists of Q operations. In Operation i (1 \leq i \leq Q), an integer T_i is provided, which means the following: * If T_i = 1: reverse the string S...
3
import collections import sys S=collections.deque(input()) Q=int(input()) r=0 for _ in range(Q): fs=next(sys.stdin).split() T=int(fs[0]) if T==1: r^=1 else: F,C=int(fs[1])-1,fs[2] if F==r: S.appendleft(C) else: S.append(C) ans=''.join(reversed(S...
Allen has a LOT of money. He has n dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are 1, 5, 10, 20, 100. What is the minimum number of bills Allen could receive after withdrawing his entire balance? Input The first...
3
n=int(input()) sum1=0 if n>=100: t=int(n/100) sum1=sum1+t n=n%100 if n>=20: t=int(n/20) sum1=sum1+t n=n%20 if n>=10: t=int(n/10) sum1=sum1+t n=n%10 if n>=5: t=int(n/5) sum1=sum1+t n=n%5 print(sum1+n)
For god's sake, you're boxes with legs! It is literally your only purpose! Walking onto buttons! How can you not do the one thing you were designed for? Oh, that's funny, is it? Oh it's funny? Because we've been at this for twelve hours and you haven't solved it either, so I don't know why you're laughing. You've got ...
3
for _ in range(int(input())): n=int(input()) arr=list(map(int,input().split())) can=False for i in range(1,n): if arr[i]>=arr[i-1]: can=True break if can: print("YES") else: print("NO")
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d...
3
n=input() count=0 for ele in n: if ele=='4' or ele=='7': count+=1 flag=False string_count = str(count) for ele in string_count: if ele=='4' or ele == '7': flag=True else: flag=False if flag: print('YES') else: print('NO')
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it: * deletes all the vowels, * inserts a character "." before each consonant, * repl...
3
import re s = input() s = s.lower() string = re.sub("a|e|i|o|u|y", "", s) for i in string: print(".",end = "") print(i,end = "")
On a random day, Neko found n treasure chests and m keys. The i-th chest has an integer a_i written on it and the j-th key has an integer b_j on it. Neko knows those chests contain the powerful mysterious green Grapes, thus Neko wants to open as many treasure chests as possible. The j-th key can be used to unlock the ...
3
a,b=map(int,input().split()) c=list(map(int,input().split())) d=list(map(int,input().split())) k=0 k1=0 for i in c: if i%2==0: k+=1 else: k1+=1 l=0 l1=0 for j in d: if j%2==0: l+=1 else: l1+=1 print(min(k,l1)+min(k1,l))
To make a paper airplane, one has to use a rectangular piece of paper. From a sheet of standard size you can make s airplanes. A group of k people decided to make n airplanes each. They are going to buy several packs of paper, each of them containing p sheets, and then distribute the sheets between the people. Each pe...
3
from math import ceil k , n , s , p = map(int,input().split()) sn = ceil(n / s) print( ceil(sn * k / p ) )
Dr. Evil kidnapped Mahmoud and Ehab in the evil land because of their performance in the Evil Olympiad in Informatics (EOI). He decided to give them some problems to let them go. Dr. Evil is interested in sets, He has a set of n integers. Dr. Evil calls a set of integers evil if the MEX of it is exactly x. the MEX of ...
3
m,n = map(int,input().strip().split(' ')) a = list(map(int,input().strip().split(' '))) b = sorted(a) num1 = 0 num2 = 0 if n in b : for i in range(n): if i not in b : num1+=1 print(str(num1+1)) else: for i in range(n): if i not in b : num1+=1 print(str(num1)) ...
DLS and JLS are bored with a Math lesson. In order to entertain themselves, DLS took a sheet of paper and drew n distinct lines, given by equations y = x + p_i for some distinct p_1, p_2, …, p_n. Then JLS drew on the same paper sheet m distinct lines given by equations y = -x + q_i for some distinct q_1, q_2, …, q_m. ...
1
range = xrange input = raw_input t = int(input()) for _ in range(t): n = int(input()) l1 = [int(x) for x in input().split()] m = int(input()) l2 = [int(x) for x in input().split()] p0,p1,q0,q1 = 0,0,0,0 for i in l1: if i % 2 == 0: p0+=1 else: p1+=1 for i in l2: if i % 2 == 0:q0+=1 else:q1+=1 print...
Let's define the following recurrence: $$$a_{n+1} = a_{n} + minDigit(a_{n}) β‹… maxDigit(a_{n}).$$$ Here minDigit(x) and maxDigit(x) are the minimal and maximal digits in the decimal representation of x without leading zeroes. For examples refer to notes. Your task is calculate a_{K} for given a_{1} and K. Input The ...
3
t=int(input()) for i in range(t): n,k = map(int, input().split()) ans=n for i in range(1,k): if('0' in str(ans)): break else: ans+=int(max(str(ans)))*int(min(str(ans))) print(ans)
The number "zero" is called "love" (or "l'oeuf" to be precise, literally means "egg" in French), for example when denoting the zero score in a game of tennis. Aki is fond of numbers, especially those with trailing zeros. For example, the number 9200 has two trailing zeros. Aki thinks the more trailing zero digits a n...
1
N,B = map(int,raw_input().split()) arr = [] for i in range(2,int(pow(B,0.5))+1): cnt = 0 while B%i==0: B /= i cnt += 1 if cnt: arr.append([i,cnt]) if B!=1: arr.append([B,1]) ans = pow(10,18) for i in arr: c = i[0] cnt = 0 while c <= N: cnt += N/c c *= ...
Dima and his friends have been playing hide and seek at Dima's place all night. As a result, Dima's place got messy. In the morning they decided that they need to clean the place. To decide who exactly would clean the apartment, the friends want to play a counting-out game. First, all the guys stand in a circle, and t...
1
n=input() s=map(int,raw_input().split()) summ=sum(s) count=0 for i in range(1,6): if (i+summ)%(n+1)!=1: count=count+1 print count
Joisino has a formula consisting of N terms: A_1 op_1 A_2 ... op_{N-1} A_N. Here, A_i is an integer, and op_i is an binary operator either `+` or `-`. Because Joisino loves large numbers, she wants to maximize the evaluated value of the formula by inserting an arbitrary number of pairs of parentheses (possibly zero) in...
3
#!/usr/bin/env python3 def solve(n): s = input() sum_a = 0 sum_n = 0 sum_np = 0 min_sum_np = 10 ** 15 j = s.find('-') if j < 0: return sum(list(map(int, s.split(' + ')))) sum_a = sum(list(map(int, s[:j - 1].split(' + ')))) j += 2 s += ' ' len_s = len(s) sign ...
Snuke has decided to construct a string that starts with `A` and ends with `Z`, by taking out a substring of a string s (that is, a consecutive part of s). Find the greatest length of the string Snuke can construct. Here, the test set guarantees that there always exists a substring of s that starts with `A` and ends w...
3
s=input() l=s.find("A") r=s[::-1].find("Z") print(len(s)-l-r)
New Year is coming and you are excited to know how many minutes remain before the New Year. You know that currently the clock shows h hours and m minutes, where 0 ≀ hh < 24 and 0 ≀ mm < 60. We use 24-hour time format! Your task is to find the number of minutes before the New Year. You know that New Year comes when the...
3
for i in range(int(input())): a, b = map(int, input().split()) m = (24 - a)*60 m -= b print(m)
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory. George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living...
1
n=int(raw_input()) count =0 for i in range(n): c=map(int, raw_input().split()) if c[1]-c[0]>1: count +=1 print count
Translator's note: in Russia's most widespread grading system, there are four grades: 5, 4, 3, 2, the higher the better, roughly corresponding to A, B, C and F respectively in American grading system. The term is coming to an end and students start thinking about their grades. Today, a professor told his students that...
1
import atexit,io,sys buffer=io.BytesIO() sys.stdout=buffer @atexit.register def write(): sys.__stdout__.write(buffer.getvalue()) def main(): s_min = 4.5 * int(raw_input()) cal = [int(x) for x in raw_input().split()] s_obt = sum(cal) cal.sort() nt=0 while s_min>s_obt: s_obt += 5-cal[nt] ...
Write a program which finds a pattern $p$ in a ring shaped text $s$. <image> Constraints * $1 \leq $ length of $p \leq $ length of $s \leq 100$ * $s$ and $p$ consists of lower-case letters Input In the first line, the text $s$ is given. In the second line, the pattern $p$ is given. Output If $p$ is in $s$, prin...
3
s = input() p = input() s = s*2 if p in s: print('Yes') else: print('No')
Takahashi will take part in an eating contest. Teams of N members will compete in this contest, and Takahashi's team consists of N players numbered 1 through N from youngest to oldest. The consumption coefficient of Member i is A_i. In the contest, N foods numbered 1 through N will be presented, and the difficulty of ...
3
n,k=map(int,input().split()) a=list(map(int,input().split())) f=list(map(int,input().split())) a.sort() f.sort() f.reverse() li = [0]*n for i in range(n): li[i] = a[i]*f[i] l=-1 r=10**18+5 while(l+1<r): m=(l+r)//2 cnt=0 for i in range(n): ov = li[i]-m if ov>0: cnt+= (ov+f[i]-1)//f[i] if cnt<=k: r=m els...
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits. Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has on...
3
l=int(input()) l=l+1 while 0<1: m=str(l) if(any(m.count(i)>1 for i in m)): l=l+1 else: print(l) break
Aiz Onsen has a bathhouse and a pool. To use the bathhouse, you need to buy a bathing ticket, and to use the pool, you need to buy a pool ticket. Prices for these tickets may vary from day to day. In addition, Aiz Onsen has the following rules. * Tickets are valid only once on the day of purchase. * If you buy 5 or mo...
3
while True: try: n=int(input()) except: break; for i in range(n): (x,y,b,p)=map(int,input().split()) s=b*x+p*y t=(max(b,5)*x+max(p,2)*y)*4//5 print(min(s,t))
A progress bar is an element of graphical interface that displays the progress of a process for this very moment before it is completed. Let's take a look at the following form of such a bar. A bar is represented as n squares, located in line. To add clarity, let's number them with positive integers from 1 to n from t...
3
from sys import stdin import math def read(): return stdin.readline().strip() a=[] n,k,t=map(int,read().split()) box=(n*t)/100 floorBox=math.floor(box) extraBox=(box-floorBox)*k for _ in range(floorBox): a.append(k) if(floorBox!=n): a.append(math.floor(extraBox)) for _ in range(n-floorBox-1): a.append...
Imagine a city with n horizontal streets crossing m vertical streets, forming an (n - 1) Γ— (m - 1) grid. In order to increase the traffic flow, mayor of the city has decided to make each street one way. This means in each horizontal street, the traffic moves only from west to east or only from east to west. Also, traff...
3
import sys # with open(sys.stdin) as f: f = sys.stdin line1 = f.readline().strip('\n').split() numh, numv = line1[0], line1[1] hor = f.readline().strip('\n') vert = f.readline().strip('\n') if (hor[0], vert[0]) == ('<', '^') or (hor[-1], vert[0]) == ('<', 'v') or (hor[0], vert[-1]) == ('>', '^') or (hor[-1], vert...
You are given a string s. You have to reverse it β€” that is, the first letter should become equal to the last letter before the reversal, the second letter should become equal to the second-to-last letter before the reversal β€” and so on. For example, if your goal is to reverse the string "abddea", you should get the str...
3
# =============================================================================================== # importing some useful libraries. from __future__ import division, print_function from fractions import Fraction import sys import os from io import BytesIO, IOBase from itertools import * import bisect from heapq import ...
"Night gathers, and now my watch begins. It shall not end until my death. I shall take no wife, hold no lands, father no children. I shall wear no crowns and win no glory. I shall live and die at my post. I am the sword in the darkness. I am the watcher on the walls. I am the shield that guards the realms of men. I ple...
3
from sys import stdin n = int(stdin.readline()) a = list(map(int,stdin.readline().split())) mns = a.count(min(a)) mxs = a.count(max(a)) res = n - mns - mxs if res<0 : res = 0 print(res)
Polycarp likes arithmetic progressions. A sequence [a_1, a_2, ..., a_n] is called an arithmetic progression if for each i (1 ≀ i < n) the value a_{i+1} - a_i is the same. For example, the sequences [42], [5, 5, 5], [2, 11, 20, 29] and [3, 2, 1, 0] are arithmetic progressions, but [1, 0, 1], [1, 3, 9] and [2, 3, 1] are ...
3
n = int(input()) b = list(map(int, input().split())) if n==1: print(0) exit() globalArr = [] for k in (1,0,-1): for l in (1,0,-1): a1,a2 = b[0]+k,b[1]+l cnt = 0 flag = True for j in range(n): ai = a1+(j)*(a2-a1) if abs(ai-b[j]) <= 1: ...
Among Johnny's numerous hobbies, there are two seemingly harmless ones: applying bitwise operations and sneaking into his dad's office. As it is usually the case with small children, Johnny is unaware that combining these two activities can get him in a lot of trouble. There is a set S containing very important number...
3
import sys import math as mt input=sys.stdin.buffer.readline t=int(input()) #t=1 for __ in range(t): #a,b=map(int,input().split()) n=int(input()) l=list(map(int,input().split())) xori=0 d={} for i in l: d[i]=1 ans=-1 #print(d) for i in range(1,1024): d1={} ...
DZY loves chessboard, and he enjoys playing with it. He has a chessboard of n rows and m columns. Some cells of the chessboard are bad, others are good. For every good cell, DZY wants to put a chessman on it. Each chessman is either white or black. After putting all chessmen, DZY wants that no two chessmen with the sa...
3
n,m = map(int,input().split()) for i in range(n): s=input() res = [i for i in s] for j in range(m): if res[j]=='.': if (i+j)%2==0: res[j]='B' else: res[j]='W' print(''.join(res))
You are given a string S of length N consisting of `(` and `)`. Your task is to insert some number of `(` and `)` into S to obtain a correct bracket sequence. Here, a correct bracket sequence is defined as follows: * `()` is a correct bracket sequence. * If X is a correct bracket sequence, the concatenation of `(`, X ...
3
input() s = input() d = 0 x = 0 for c in s: if c == "(": d += 1 else: d -= 1 x = min(d, x) print("(" * -x + s + ")" * (d - x))
Snuke has a blackboard and a set S consisting of N integers. The i-th element in S is S_i. He wrote an integer X on the blackboard, then performed the following operation N times: * Choose one element from S and remove it. * Let x be the number written on the blackboard now, and y be the integer removed from S. Repla...
3
import math import sys sys.setrecursionlimit(100000000) # ε‹•ηš„θ¨ˆη”»ζ³•γ¨memoεŒ–γ§θ§£γγ€‚ N, X = map(int, input().split()) S = list(map(int, input().split())) S.sort(reverse=True) def memoize(f): # γƒ‘γƒ’εŒ–ι–’ζ•° table = [{} for _ in range(N+1)] def func(i, key): if key not in table[i]: table[i][key] = f(i, key...
Innokentiy decides to change the password in the social net "Contact!", but he is too lazy to invent a new password by himself. That is why he needs your help. Innokentiy decides that new password should satisfy the following conditions: * the length of the password must be equal to n, * the password should con...
3
n, k = list(map(int, input().split())) s = "" for i in range(k): s += chr(ord('a') + i) m = n // k res = s * m res += s[:n % k] print(res)
Welcome to Codeforces Stock Exchange! We're pretty limited now as we currently allow trading on one stock, Codeforces Ltd. We hope you'll still be able to make profit from the market! In the morning, there are n opportunities to buy shares. The i-th of them allows to buy as many shares as you want, each at the price o...
3
import sys, os f = lambda:list(map(int,input().split())) if 'local' in os.environ : sys.stdin = open('./input.txt', 'r') def solve(): n, m, r = f() s = f() b = f() s = sorted(s) b = sorted(b, reverse = True) buy = r//s[0] print(max(r - buy * s[0] + buy * b[0], r)) solve()
Limak is a grizzly bear who desires power and adoration. He wants to win in upcoming elections and rule over the Bearland. There are n candidates, including Limak. We know how many citizens are going to vote for each candidate. Now i-th candidate would get ai votes. Limak is candidate number 1. To win in elections, he...
1
n = int(raw_input()) a = map(int,raw_input().split(' ')) b = a[0] a = a[1:] if b > max(a): print 0 else: c = max(a) bribe = 0 while c>=b: amt = 1 bribe += amt a[a.index(c)] -= amt b += amt c = max(a) print bribe
We have a grid with H rows and W columns, where all the squares are initially white. You will perform some number of painting operations on the grid. In one operation, you can do one of the following two actions: * Choose one row, then paint all the squares in that row black. * Choose one column, then paint all the s...
3
h=int(input()) w=int(input()) n=int(input()) l = max(h,w) print(-(-n//l))
You are given a string S consisting of `a`,`b` and `c`. Find the number of strings that can be possibly obtained by repeatedly performing the following operation zero or more times, modulo 998244353: * Choose an integer i such that 1\leq i\leq |S|-1 and the i-th and (i+1)-th characters in S are different. Replace each...
3
s = input() n = len(s) flg = 0 for i in range(1,n): if s[i-1] != s[i]: flg += 1 if flg == 0: print(1) exit() par = (s.count("a")+s.count("b")*2+2)%3 dp = [[0 for i in range(9)] for j in range(n)] mod = 998244353 dp[0][0] = 1 dp[0][4] = 1 dp[0][8] = 1 for i in range(1,n): dp[i][0] = dp[i-1][5]+dp[i-1][8] d...
You are given a picture consisting of n rows and m columns. Rows are numbered from 1 to n from the top to the bottom, columns are numbered from 1 to m from the left to the right. Each cell is painted either black or white. You think that this picture is not interesting enough. You consider a picture to be interesting...
1
import pprint q = int(raw_input()) for _ in xrange(q): n, m = map(int, raw_input().split()) a = [] rows = [0] * n cols = [0] * m for r in xrange(n): a.append(raw_input()) rows[r] = a[-1].count("*") for c in xrange(m): for r in xrange(n): if a[r][c] == "*": ...
Lunar New Year is approaching, and Bob decides to take a wander in a nearby park. The park can be represented as a connected graph with n nodes and m bidirectional edges. Initially Bob is at the node 1 and he records 1 on his notebook. He can wander from one node to another through those bidirectional edges. Whenever ...
3
from sys import stdin, stdout import collections , heapq , bisect , math input = stdin.readline def rint() : return int(input()) def rstr() : return input().strip() def rlstr() : return list(input().strip().split()) def rlint() : return list(map(int , input().split())) def main(): n , m = rlint() ...
Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone. In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules o...
1
arr = map(int,raw_input().split()) s=raw_input() su=0 for i in s: su += arr[int(i)-1] print su
The School β„–0 of the capital of Berland has n children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value ti: * ti = 1, if the i-th child is good at programming, *...
3
a = int(input()) b = [int(i) for i in input().split()] first = list() second = list() third = list() for i in range(a): if b[i] == 1: first.append(i+1) elif b[i] == 2: second.append(i+1) elif b[i] == 3: third.append(i+1) if len(first) > 0 and len(second) > 0 and len(third) > 0: p...
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 ...
3
'''input 5 3 1 3 2 3 3 4 0 5 2 ''' import sys read = lambda: list(map(int,sys.stdin.readline().strip().split())) # try: sigma = lambda x:x*(x+1)//2 for _ in range(int(input())): n,m = read() k = n-m total = sigma(n) # if m==0 or m==n: # print(total) # continue if k>m: e,f =...
You are given an array d_1, d_2, ..., d_n consisting of n integer numbers. Your task is to split this array into three parts (some of which may be empty) in such a way that each element of the array belongs to exactly one of the three parts, and each of the parts forms a consecutive contiguous subsegment (possibly, em...
3
n = int(input()) s = list(map(int, input().split())) m = 0 x = 0 y = n-1 a = s[x] b = s[y] sx = a sy = b while y-x > 0: if sx == sy: m = sx x += 1 y -= 1 a = s[x] b = s[y] sx += a sy += b elif sx < sy: x += 1 a = s[x] sx += a el...
You are both a shop keeper and a shop assistant at a small nearby shop. You have n goods, the i-th good costs a_i coins. You got tired of remembering the price of each product when customers ask for it, thus you decided to simplify your life. More precisely you decided to set the same price for all n goods you have. ...
3
q = int(input()) for i in range(q): n = int(input()) a = list(map(int,input().split())) print(int(sum(a) // n) if int(sum(a) // n) * n >= sum(a) else int(sum(a) / n) + 1)
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them. Input The first line contains integ...
3
input() x=input() count=0 for i in range(0,len(x)-1): if x[i]=='R' and x[i+1]=='R': count+=1 elif x[i]=='G' and x[i+1]=='G': count+=1 elif x[i]=='B' and x[i+1]=='B': count+=1 print(count)
It is known that the area of a regular dodecagon inscribed in a circle of radius a is 3a^2. Given an integer r, find the area of a regular dodecagon inscribed in a circle of radius r. Constraints * 1 \leq r \leq 100 * r is an integer. Input Input is given from Standard Input in the following format: r Output ...
3
n = int(input()) print((n**2)*3)
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi. To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem...
3
n,m = [x for x in map(int, input().strip().split(" "))] # 3 5 req = list(map(int,input().strip().split(" "))) # 1 2 3 prep = list(map(int,input().strip().split(" "))) # 1 3 5 6 7 # 3 5 # 1 2 3 # 1 1 1 1 1 count = 0 j = 0 for i in range(0, n): while (j < m): if (req[i] == prep[j] or prep[j] > req[i]): ...
Sereja has an array a, consisting of n integers a1, a2, ..., an. The boy cannot sit and do nothing, he decided to study an array. Sereja took a piece of paper and wrote out m integers l1, l2, ..., lm (1 ≀ li ≀ n). For each number li he wants to know how many distinct numbers are staying on the positions li, li + 1, ......
3
n, m = map(int, input().split()) l = list(map(int, input().split())) s = set() l2 = [0] * len(l) l.reverse() for i, e in enumerate(l): if not e in s: l2[i] = 1 s.add(e) for i in range(1, len(l2)): l2[i] += l2[i - 1] l2.reverse() for i in range(m): a = int(input()) print(l2[a - 1]) ...
A coordinate line has n segments, the i-th segment starts at the position li and ends at the position ri. We will denote such a segment as [li, ri]. You have suggested that one of the defined segments covers all others. In other words, there is such segment in the given set, which contains all other ones. Now you want...
1
n=int(raw_input()) l=[] min,max=1100000000,-1 for i in range(n): l.append(map(int,raw_input().split())) if l[i][0]<min: min=l[i][0] if l[i][1]>max: max=l[i][1] key=[min,max] if key in l: print l.index(key)+1 else : print '-1'
Little Joty has got a task to do. She has a line of n tiles indexed from 1 to n. She has to paint them in a strange pattern. An unpainted tile should be painted Red if it's index is divisible by a and an unpainted tile should be painted Blue if it's index is divisible by b. So the tile with the number divisible by a a...
1
def mdc(a,b): resto = a % b if (resto == 0): return b else: return mdc(b, resto) N,a,b,p,q = map(int, raw_input().split(' ')) divisao_a = N/a divisao_b = N/b divisao_aEb = N/((a*b)/mdc(a,b)) print (divisao_a*p) + (divisao_b*q) - (divisao_aEb*min(p,q))
The only difference between easy and hard versions are constraints on n and k. You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most k most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals 0...
3
#social network import math; import array arr1=array.array('l',[]); arr2=array.array('l',[]); arr3=array.array('l',[]); arr1=[int(j) for j in input().split()] n=arr1[0] k=arr1[1] arr2=[int(j) for j in input().split()] for i in range (0,n,1): a=arr2[i] if a in arr3:continue; else: arr...
There are N balls in a two-dimensional plane. The i-th ball is at coordinates (x_i, y_i). We will collect all of these balls, by choosing two integers p and q such that p \neq 0 or q \neq 0 and then repeating the following operation: * Choose a ball remaining in the plane and collect it. Let (a, b) be the coordinates...
1
rr = raw_input rrm = lambda: map(int, rr().split()) class DSU: def __init__(self, N): self.par = list(range(N + 1)) self.rnk = [0] * (N + 1) self.sz = [1] * (N + 1) def find(self, x): if self.par[x] != x: self.par[x] = self.find(self.par[x]) return self.par[...
Dreamoon wants to climb up a stair of n steps. He can climb 1 or 2 steps at each move. Dreamoon wants the number of moves to be a multiple of an integer m. What is the minimal number of moves making him climb to the top of the stairs that satisfies his condition? Input The single line contains two space separated i...
3
n,m = map(int, input().split()) for i in range(n//2+n%2,n+1): if i%m == 0: print(i) break else: print(-1)
Theatre Square in the capital city of Berland has a rectangular shape with the size n Γ— m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a Γ— a. What is the least number of flagstones needed to pave the Square? It'...
3
height, weigth, block = map(int, input().split()) if height%block==0: height_block = height//block else: height_block = height//block+1 if weigth % block == 0: weigth_block = weigth // block else: weigth_block = weigth // block+1 print(height_block * weigth_block)
A well-known art union called "Kalevich is Alive!" manufactures objects d'art (pictures). The union consists of n painters who decided to organize their work as follows. Each painter uses only the color that was assigned to him. The colors are distinct for all painters. Let's assume that the first painter uses color 1...
3
#!/usr/bin/python import re import inspect from sys import argv, exit def rstr(): return input() def rint(): return int(input()) def rints(splitchar=' '): return [int(i) for i in input().split(splitchar)] def rstrs(splitchar=' '): return [i for i in input().split(splitchar)] def varnames(obj, names...
Masha has three sticks of length a, b and c centimeters respectively. In one minute Masha can pick one arbitrary stick and increase its length by one centimeter. She is not allowed to break sticks. What is the minimum number of minutes she needs to spend increasing the stick's length in order to be able to assemble a ...
3
a,b,c=sorted(map(int,input().split())) m=0 while(a+b<=c): m+=1 b+=1 print(m)
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr...
3
s1=list(input().upper()) s2=list(input().upper()) for i in range(len(s1)): if ord(s1[i])>ord(s2[i]): print(1) exit() elif ord(s1[i])<ord(s2[i]): print(-1) exit() print(0)
You are given a tree consisting of n vertices. A number is written on each vertex; the number on vertex i is equal to a_i. Let's denote the function g(x, y) as the greatest common divisor of the numbers written on the vertices belonging to the simple path from vertex x to vertex y (including these two vertices). For ...
3
from sys import stdin, stdout from math import * from heapq import * from collections import * dv=list(range(200002)) for i in range(2,200002): if ((i*i)>=200002): break if (dv[i]==i): j=i while ((i*j)<200002): dv[i*j]=i j=j+1 def loPr(x): global dv if (...
Alice is the leader of the State Refactoring Party, and she is about to become the prime minister. The elections have just taken place. There are n parties, numbered from 1 to n. The i-th party has received a_i seats in the parliament. Alice's party has number 1. In order to become the prime minister, she needs to b...
3
n = int(input()) l = list(map(int,input().split())) a = l[0] dup = [] suma = a for i in range(1,n): if l[i] <= a // 2: dup.append(i) suma += l[i] if suma * 2 <= sum(l): print(0) else: print(len(dup)+1) print(1, end = " ") for i in dup: print(i + 1, end = " ")
A map of some object is a rectangular field consisting of n rows and n columns. Each cell is initially occupied by the sea but you can cover some some cells of the map with sand so that exactly k islands appear on the map. We will call a set of sand cells to be island if it is possible to get from each of them to each ...
3
def main(): n, k = map(int, input().split()) grid = [['S' for _ in range(n)] for _ in range(n)] lands = 0 for i in range(n): for j in range(n): if (i + j) % 2 == 0 and lands < k: grid[i][j] = 'L' lands += 1 if lands != k: print('NO') e...
You are given a string s consisting of n lowercase Latin letters. You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation. String s = s_1 s_2 ... s_n is lexicograp...
3
length = int(input()) s = input() del_num = length-1 for i in range(length-1): if s[i] > s[i+1]: del_num = i break new_s = "" for i in range(length): if i != del_num: new_s = new_s + s[i] print(new_s)
Theatre Square in the capital city of Berland has a rectangular shape with the size n Γ— m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a Γ— a. What is the least number of flagstones needed to pave the Square? It'...
3
n,m,a = list(map(int,input().split(' '))) print((n//a+(1 if n%a!=0 else 0))*(m//a+(1 if m%a!=0 else 0)))
There are N people, conveniently numbered 1 through N. They were standing in a row yesterday, but now they are unsure of the order in which they were standing. However, each person remembered the following fact: the absolute difference of the number of the people who were standing to the left of that person, and the nu...
3
n=int(input()) a=sorted(list(map(int,input().split()))) if n%2==1: if a[0]==0 and all(a[i]==2*((i+1)//2) for i in range(1,n)):print(2**(n//2)%(10**9+7)) else: print(0) else: if all(a[i]==2*(i//2)+1 for i in range(n)):print(2**(n//2)%(10**9+7)) else: print(0)
Recently, Tokitsukaze found an interesting game. Tokitsukaze had n items at the beginning of this game. However, she thought there were too many items, so now she wants to discard m (1 ≀ m ≀ n) special items of them. These n items are marked with indices from 1 to n. In the beginning, the item with index i is placed o...
3
####################################################################################################################### # Author: BlackFyre # Language: PyPy 3.7 ####################################################################################################################### from sys import stdin, stdou...
Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot. He wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fence corners at a single angle a. Will the robot be able to build the fence Emuskald...
3
n=int(input()) while n>0: x=int(input()) t=360%(180-x) if t==0: print("YES") else:print("NO") n-=1
Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad. Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element eq...
3
import math n, k = [int(x) for x in input().split()] A = [0]*50 for i in range(50): A[i] = 2**i if k in A: print(round(math.log(k, 2)) +1) else: if k%2 == 1: print("1") else: i = 1 while k%A[i] == 0: i+=1 print(i)
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he rem...
3
n,k = [int(i) for i in input().split()] if n==1 and k==0: print(1) elif n==1 and k>0: print(-1) elif k<n//2 : print(-1) elif n>=2: if n%2==0: m = n-2 summ = 0 st = 10**8 while(m>0): print(st,end=' ') st+=1 print(st,end=' ') ...
Walter White is on a tour to sell meth. There are N cities. Each city has a id between 1 and N (both inclusive). You are given cost matrix. In cost matrix, the j\;th element in the i\;th row denotes the cost of travelling between cities with id i and j. cost[i][j]=cost[j][i] and cost[i][i]=0 Given the path taken b...
1
n = int(raw_input()) d = {} l = [] lcity = [] dic = {} ans = 0 for i in range(n): c = raw_input() l.append(c) d[c] = i for i in range(n): co = list(map(int,raw_input().split(" "))) dic[l[i]] = co p = int(raw_input()) for i in range(p): city = raw_input() lcity.append(city) for i in range(p): ind1 = d[lcity[i]] ...
You and your friend are playing the game Mortal Kombat XI. You are trying to pass a challenge tower. There are n bosses in this tower, numbered from 1 to n. The type of the i-th boss is a_i. If the i-th boss is easy then its type is a_i = 0, otherwise this boss is hard and its type is a_i = 1. During one session, eith...
3
import os, sys from io import IOBase, BytesIO py2 = round(0.5) if py2: from future_builtins import ascii, filter, hex, map, oct, zip range = xrange BUFSIZE = 8192 class FastIO(BytesIO): newlines = 0 def __init__(self, file): self._file = file self._fd = file.fileno() self.writa...