problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the...
3
n, h = input().split() n, h = int(n), int(h) a = list(map(int, input().split())) width = 0 for i in range(n): if a[i] > h: width += 2 else: width += 1 print(width)
Is it rated? Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it. Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before ...
3
from sys import stdin,stdout input = stdin.readline def write(n,sep="\n"): stdout.write(str(n)) stdout.write(sep) def gil(): return list(map(int, input().split())) n = int(input()) m = 1e7 r = 0 for _ in range(n): a,b = gil() if a != b: r = 1 break elif a > m : r = 2 m = min(m,a) if r == 0: print("maybe...
You are given a number n (divisible by 3) and an array a[1 ... n]. In one move, you can increase any of the array elements by one. Formally, you choose the index i (1 ≤ i ≤ n) and replace a_i with a_i + 1. You can choose the same index i multiple times for different moves. Let's denote by c_0, c_1 and c_2 the number o...
3
import math t=int(input()) for _ in range(t): n=int(input()) l=list(map(int,input().split())) for i in range(n): l[i]=l[i]%3 a=l.count(0) b=l.count(1) c=l.count(2) ans=0 n//=3 if(a>n): ans+=a-n b+=a-n a=n if(a<n): ans+=n-a c-=n-a ...
You are given a rectangular board of M × N squares. Also you are given an unlimited number of standard domino pieces of 2 × 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions: 1. Each domino completely covers two squa...
3
# 50A x, y = input().split() x = int(x) y = int(y) print(int((x*y)/2))
Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first n. He writes down the followin...
3
nk = input().split(" ") n = int(nk[0]) k = int(nk[1]) if n % 2 == 0: if k <=n/2: number = 2*k-1 else: number = 2*k-n else: if k <=(n+1)/2: number = 2*k-1 else: number = 2*k-n-1 print(number)
You're given an array a of length 2n. Is it possible to reorder it in such way so that the sum of the first n elements isn't equal to the sum of the last n elements? Input The first line contains an integer n (1 ≤ n ≤ 1000), where 2n is the number of elements in the array a. The second line contains 2n space-separat...
3
n = int(input()) A = list(map(int, input().split())) A = sorted(A) s1 = 0 for i in range (n): s1 = s1 + A[i] - A[n + i] if s1 != 0: print(*A) else: print(-1)
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). For a positive integer n, we call a...
3
t = int(input());ar = []; for i in range(t) : n = int(input()) a = [i for i in range(1,n+1)] ar.append(a) for i in ar : s = ' '.join(str(j) for j in i) print(s)
The Little Elephant enjoys recursive functions. This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: ...
3
n = int(input()) print(n, *range(1, n), sep=' ')
You have integer n. Calculate how many ways are there to fully cover belt-like area of 4n-2 triangles with diamond shapes. Diamond shape consists of two triangles. You can move, rotate or flip the shape, but you cannot scale it. 2 coverings are different if some 2 triangles are covered by the same diamond shape in ...
3
def solve(): n = int(input()) print(n) for i in range(int(input())): solve()
Monk loves cakes! He visits the Binary Bakery to buy some of his favorite cheesecakes. The owner of the bakery, Bob, is a clever man. He does not want Monk to finish all his cheesecakes. Hence, he plays a game. The Monk is given N numbers and has to select K of these numbers. For each number that Monk chooses, he wil...
1
test=input() to=0 list1=list() list2=list() while to<test: list1.append(raw_input()) list2.append(raw_input()) to=to+1 j=0 while j<len(list1): a,b=map(int,list1[j].split()) x1=map(int,list2[j].split()) p=list() c=0 for i in range(len(x1)): x=x1[i] while x!=0: if(x%2)==1: c=c+1 x=x/2 p.append(c) ...
To make it difficult to withdraw money, a certain bank allows its customers to withdraw only one of the following amounts in one operation: * 1 yen (the currency of Japan) * 6 yen, 6^2(=36) yen, 6^3(=216) yen, ... * 9 yen, 9^2(=81) yen, 9^3(=729) yen, ... At least how many operations are required to withdraw exa...
3
n=int(input()) def k(a,b): ans=0 while (a!=0): ans+=a%b a//=b return ans res=10**10 for i in range(n+1): res=min(res,k(i,9)+k(n-i,6)) print(res)
Find the maximum possible sum of the digits (in base 10) of a positive integer not greater than N. Constraints * 1\leq N \leq 10^{16} * N is an integer. Input Input is given from Standard Input in the following format: N Output Print the maximum possible sum of the digits (in base 10) of a positive integer not...
3
N=input() if(N[1:len(N)].count("9")!=len(N)-1): print(int(N[0])-1+9*(len(N)-1)) else: print(int(N[0])+9*(len(N)-1))
Greatest common divisor GCD(a, b) of two positive integers a and b is equal to the biggest integer d such that both integers a and b are divisible by d. There are many efficient algorithms to find greatest common divisor GCD(a, b), for example, Euclid algorithm. Formally, find the biggest integer d, such that all int...
3
s = input() a,b = s.split() a = int(a) b = int(b) if a==b: print(a) else: print("1")
Encryption System A programmer developed a new encryption system. However, his system has an issue that two or more distinct strings are `encrypted' to the same string. We have a string encrypted by his system. To decode the original string, we want to enumerate all the candidates of the string before the encryption....
3
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**10 mod = 10**9+7 dd = [(-1,0),(0,1),(1,0),(0,-1)] ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(): return [int(x) for x in sys.stdin....
Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it ...
3
arr = [] count = 0 for i in range(int(input())): a, b = map(int, input().split()) count -= a count += b arr.append(count) print(max(arr))
You are given three strings A, B and C. Check whether they form a word chain. More formally, determine whether both of the following are true: * The last character in A and the initial character in B are the same. * The last character in B and the initial character in C are the same. If both are true, print `YES`....
3
a, b, c = input().split() if a[-1:]==b[0] and b[-1:]==c[0]: print("YES") else: print("NO")
A competitive eater, Alice is scheduling some practices for an eating contest on a magical calendar. The calendar is unusual because a week contains not necessarily 7 days! In detail, she can choose any integer k which satisfies 1 ≤ k ≤ r, and set k days as the number of days in a week. Alice is going to paint some n...
3
for i in range(int(input())): n,r=map(int,input().split()) t=min(n-1,r) count=(t*(t+1))//2 if n<=r: count+=1 print(count)
Write a program which reads an integer n and prints the factorial of n. You can assume that n ≤ 20. Input An integer n (1 ≤ n ≤ 20) in a line. Output Print the factorial of n in a line. Example Input 5 Output 120
3
from functools import reduce from operator import mul n = int(input()) print(reduce(mul, range(1, n + 1), 1))
Kuroni has n daughters. As gifts for them, he bought n necklaces and n bracelets: * the i-th necklace has a brightness a_i, where all the a_i are pairwise distinct (i.e. all a_i are different), * the i-th bracelet has a brightness b_i, where all the b_i are pairwise distinct (i.e. all b_i are different). Kuro...
3
import sys import math import bisect def main(): for _ in range(int(input())): n = int(input()) A = list(map(int, input().split())) B = list(map(int, input().split())) A.sort() B.sort() print(' '.join(list(str(a) for a in A))) print(' '.join(list(str(b) for b...
You are given a integer n (n > 0). Find any integer s which satisfies these conditions, or report that there are no such numbers: In the decimal representation of s: * s > 0, * s consists of n digits, * no digit in s equals 0, * s is not divisible by any of it's digits. Input The input consists of mult...
3
def badug(n): if(n==1): return -1 else: s='23'+'3'*(n-2) return int(s) t=int(input()) for i in range(0,t): n=int(input()) print(badug(n))
Happy new year! The year 2020 is also known as Year Gyeongja (경자년, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years. There are two sequences of n strings s_1, s_2, s_3, …, s_{n} and m strings t_1, t_2, t_3, …, t_{m}. ...
3
def HCF(n,m): a = min(n,m) b = max(n,m) while True: t = n%m if t == 0: break n = m m = t return m n,m = map(int,input().split()) l1 = input().split() l2 = input().split() LCM = (n*m)//(HCF(n,m)) d = {} for i in range(1,LCM+1): d[i] = l1[(i-1)%n]+l2[(i-1)%m] t = int(input()) for i in range(t): y = int(...
You are looking at the floor plan of the Summer Informatics School's new building. You were tasked with SIS logistics, so you really care about travel time between different locations: it is important to know how long it would take to get from the lecture room to the canteen, or from the gym to the server room. The bu...
3
n,h,a,b,k=map(int,input().split()) for i in range(k): c=0 l=list(map(int,input().split())) if l[1]>=b: x=b elif l[1]<=a: x=a else: x=0 if l[0]==l[2]: print((abs(l[3]-l[1]))) elif l[0]!=l[2] and l[1]>a and l[1]<b : print(abs(l[2]-l[0])+abs(l[3]-l[1])) ...
You are given a sequence with N integers: A = \\{ A_1, A_2, \cdots, A_N \\}. For each of these N integers, we will choose a color and paint the integer with that color. Here the following condition must be satisfied: * If A_i and A_j (i < j) are painted with the same color, A_i < A_j. Find the minimum number of col...
3
import sys from bisect import bisect n = int(input()) aaa = list(map(int, sys.stdin.readlines())) dp = [1] for a in aaa: a *= -1 i = bisect(dp, a) if i < len(dp): dp[i] = a else: dp.append(a) print(len(dp))
Petya has an array a consisting of n integers. He wants to remove duplicate (equal) elements. Petya wants to leave only the rightmost entry (occurrence) for each element of the array. The relative order of the remaining unique elements should not be changed. Input The first line contains a single integer n (1 ≤ n ≤ ...
3
import operator n = int(input()) array = [int(x) for x in input().split(' ')] d = {} for i in range(n): d[array[i]] = i sorted_d = sorted(d.items(), key=operator.itemgetter(1)) print(len(sorted_d)) print(" ".join(str(x[0]) for x in sorted_d))
In this problem, we only consider strings consisting of lowercase English letters. Strings s and t are said to be isomorphic when the following conditions are satisfied: * |s| = |t| holds. * For every pair i, j, one of the following holds: * s_i = s_j and t_i = t_j. * s_i \neq s_j and t_i \neq t_j. For example, `a...
3
n = int(input()) a = ord('a') def dfs(s, m): # print("dfs", s, chr(m)) if len(s) == n: print(s) else: for i in range(m + 1 - a): dfs(s + chr(a + i), m + 1 if i == m - a else m) dfs("", a)
Alicia has an array, a_1, a_2, …, a_n, of non-negative integers. For each 1 ≤ i ≤ n, she has found a non-negative integer x_i = max(0, a_1, …, a_{i-1}). Note that for i=1, x_i = 0. For example, if Alicia had the array a = \{0, 1, 2, 0, 3\}, then x = \{0, 0, 1, 2, 2\}. Then, she calculated an array, b_1, b_2, …, b_n: ...
3
n = int(input()) b = input().split() b = list(map(lambda x: int(x), b)) a = [] maxTilNow = 0 for i in b: j = i + maxTilNow a.append(j) maxTilNow = j if j > maxTilNow else maxTilNow print(*a)
[The Duck song](https://www.youtube.com/watch?v=MtN1YnoL46Q) For simplicity, we'll assume that there are only three types of grapes: green grapes, purple grapes and black grapes. Andrew, Dmitry and Michal are all grapes' lovers, however their preferences of grapes are different. To make all of them happy, the followi...
3
# -*- coding: utf-8 -*- def rli(): return list(map(int, input().split())) def main(): x, y, z = rli() a, b, c = rli() if x > a or x + y > a + b or x + y + z > a + b + c: print('NO') else: print('YES') if __name__ == '__main__': main()
You are given an integer n (n > 1). Your task is to find a sequence of integers a_1, a_2, …, a_k such that: * each a_i is strictly greater than 1; * a_1 ⋅ a_2 ⋅ … ⋅ a_k = n (i. e. the product of this sequence is n); * a_{i + 1} is divisible by a_i for each i from 1 to k-1; * k is the maximum possible (i. e...
3
import math def _sieve(N): primes = [True]*(N+1) primes[0] = False primes[1] = False sqrtN = round(math.sqrt(N)) for i in range(2, sqrtN+1): if primes[i]: for j in range(i*i, N+1, i): primes[j] = False return primes def _getPrime(N): primes = _sieve(N)...
In Berland it is the holiday of equality. In honor of the holiday the king decided to equalize the welfare of all citizens in Berland by the expense of the state treasury. Totally in Berland there are n citizens, the welfare of each of them is estimated as the integer in ai burles (burle is the currency in Berland). ...
3
a=int(input()) b=list(map(int,input().split(" "))) c=max(b) s=0 for i in b: s=s+(c-i) print(s)
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line. Unfortunately, from time to ti...
3
# taking and modifiying input and basic hashing # use ord() and chr() in python st = input() count=0 has = [0 for i in range(26)] i=1 while True: if st[i]=='}': break else: #print(has) if(has[ord(st[i])-ord('a')]==0): count+=1 has[ord(st[i])-ord('a')]=1 i...
Draw a chessboard which has a height of H cm and a width of W cm. For example, the following figure shows a chessboard which has a height of 6 cm and a width of 10 cm. .#.#.#.#. .#.#.#.#.# .#.#.#.#. .#.#.#.#.# .#.#.#.#. .#.#.#.#.# Note that the top left corner should be drawn by '#'. Constraints * 1 ≤ H ≤ 300 * 1...
3
while True: line = list(map(int,input().split())) if line==[0,0]: break for i in range(line[0]): for j in range(line[1]): print('#' if (i+j)%2==0 else '.',end='\n' if j==line[1]-1 else '') print()
We have a grid with A horizontal rows and B vertical columns, with the squares painted white. On this grid, we will repeatedly apply the following operation: * Assume that the grid currently has a horizontal rows and b vertical columns. Choose "vertical" or "horizontal". * If we choose "vertical", insert one row at th...
3
a, b, c, d = map(int, input().split()) mod = 998244353 dp = [[-1 for i in range(d+1)] for j in range(c+1)] for i in range(a+1): for j in range(b+1): dp[i][j] = 1 def doubling(n, m, modulo=0): y = 1 base = n tmp = m while tmp: if tmp % 2 == 1: y *= base if mo...
Harry Potter has n mixtures in front of him, arranged in a row.Each mixture has one of 100 different colors (colors have numbers from 0 to 99). He wants to mix all these mixtures together. At each step, he is going to take two mixtures that stand next to each other and mix them together, and put the resulting mixture ...
1
''' MIXTURE problem ''' import fileinput import sys def min_smoke(colors): n = len(colors) mixed_colors = [[None for c in colors] for c in colors] min_costs = [[sys.maxint for c in colors] for c in colors] for i in xrange(0, n): mixed_colors[i][i] = colors[i] min_costs[i][i] = 0 for L in xrange(2, n+1): ...
You took a peek on Thanos wearing Infinity Gauntlet. In the Gauntlet there is a place for six Infinity Gems: * the Power Gem of purple color, * the Time Gem of green color, * the Space Gem of blue color, * the Soul Gem of orange color, * the Reality Gem of red color, * the Mind Gem of yellow color. ...
3
n = int(input()) d = {'purple': 'Power', 'green': 'Time', 'blue': 'Space', 'orange': 'Soul', 'red': 'Reality', 'yellow': 'Mind'} for i in range(n): x = input() del d[x] print(len(d)) for k in d: print(d[k])
We have a permutation p = {p_1,\ p_2,\ ...,\ p_n} of {1,\ 2,\ ...,\ n}. Print the number of elements p_i (1 < i < n) that satisfy the following condition: * p_i is the second smallest number among the three numbers p_{i - 1}, p_i, and p_{i + 1}. Constraints * All values in input are integers. * 3 \leq n \leq 20 * p...
3
input() p=[int(x) for x in input().split()] q=[x-y for x,y in zip(p[1:],p[:])] r=[1 for x,y in zip(q[1:],q[:]) if x*y>0] print(len(r))
Alice and Bob play a game. They have a binary string s (a string such that each character in it is either 0 or 1). Alice moves first, then Bob, then Alice again, and so on. During their move, the player can choose any number (not less than one) of consecutive equal characters in s and delete them. For example, if the...
3
t = int(input()) for asd in range(t): s = str(input()) a=[] if(s[0]=='1'): count=1 else: count=0 for i in range(0,len(s)-1): if(s[i+1]=='1' and s[i]=='0'): count=1 elif(s[i+1]=='1' and s[i]=='1'): count+=1 elif(s[i+1]=='0' and s[i]=='1'): a.append(count) count=0 a.append(count) # print(a)...
This is the easy version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task. You are given a string s, consisting of lowercase English letters. Find the longest string, t, which satisfies the fol...
3
import sys def kmp(s): s=s+'$'+s[::-1] temp=[0 for i in range(len(s))] j=0 for i in range(1,len(s)): while j!=0 and s[i]!=s[j]: j=temp[j-1] if s[i]==s[j]: j+=1 temp[i]=j return s[:temp[-1]] #input = sys.stdin.readline for _ in range(int(input())): ...
A PIN code is a string that consists of exactly 4 digits. Examples of possible PIN codes: 7013, 0000 and 0990. Please note that the PIN code can begin with any digit, even with 0. Polycarp has n (2 ≤ n ≤ 10) bank cards, the PIN code of the i-th card is p_i. Polycarp has recently read a recommendation that it is bette...
3
import math def change(p, n): digit = n // 10 add = n % 10 newdigit = str((int(p[digit]) + add) % 10) if digit == 0: return newdigit + p[1:] elif digit == 1: return p[0] + newdigit + p[2:] elif digit == 2: return p[:1] + newdigit + p[3] elif digit == 3: retur...
There are n students in a school class, the rating of the i-th student on Codehorses is a_i. You have to form a team consisting of k students (1 ≤ k ≤ n) such that the ratings of all team members are distinct. If it is impossible to form a suitable team, print "NO" (without quotes). Otherwise print "YES", and then pri...
1
N = map(int, raw_input().split(" ")) x = N[1] D = map(int, raw_input().split(" ")) X = [] Z = [] for i in D: if len(X) == x: break if i not in X: X.append(i) Z.append(D.index(i)+1) if len(X) == x: print "YES" print " ".join(map(str,Z)) else: print "NO"
There are N one-off jobs available. If you take the i-th job and complete it, you will earn the reward of B_i after A_i days from the day you do it. You can take and complete at most one of these jobs in a day. However, you cannot retake a job that you have already done. Find the maximum total reward that you can ea...
3
n, m = map(int,input().split()) pay = [[] for i in range(m+1)] for i in range(n): a, b = map(int,input().split()) if a <= m: pay[a].append(b) import heapq as hq ans = 0 stack = [] for i in range(m+1): for j in pay[i]: hq.heappush(stack, -j) ans -= hq.heappop(stack) if stack else 0 pr...
Xenia lives in a city that has n houses built along the main ringroad. The ringroad houses are numbered 1 through n in the clockwise order. The ringroad traffic is one way and also is clockwise. Xenia has recently moved into the ringroad house number 1. As a result, she's got m things to do. In order to complete the i...
3
def calc(a,pos,n): if a[pos+1] >= a[pos]: g = a[pos+1]-a[pos] else: g=n + (a[pos+1]-a[pos]) return g num = str(input()) num = [int(j) for j in num.split()] n = num[0] m = num[1] a = str(input()) a= [int(j) for j in a.split()] a.insert(0,1) l = len(a) count = 0 for i in range(l-1): ...
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition. Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character...
3
s = input() ans = 0 for i in range(len(s)-1): k = [] k.append(ord(s[i])) k.append(ord(s[i+1])) k.sort() a = abs(k[0] - k[1]) b = abs(ord('a')-k[0]) + abs(ord('z')-k[1]) +1 tt=min(a,b) #print(s[i],s[i+1],tt) ans+=tt kk = min(abs(ord(s[0]) - ord('a')), abs(ord(s[0]) - ord('z'))+1 ) pr...
Alice has a birthday today, so she invited home her best friend Bob. Now Bob needs to find a way to commute to the Alice's home. In the city in which Alice and Bob live, the first metro line is being built. This metro line contains n stations numbered from 1 to n. Bob lives near the station with number 1, while Alice ...
3
n, s = list(map(int, input().split(' '))) up = list(map(int, input().split(' '))) down = list(map(int, input().split(' '))) if up[0] == 0: print("NO") elif up[s-1] == 1: print("YES") elif down[s-1] == 0: print('NO') else: cunt = 0 for i in range(s+1, n+1): if up[i-1] == 1 and up[i-1]...
Vadim loves decorating the Christmas tree, so he got a beautiful garland as a present. It consists of n light bulbs in a single row. Each bulb has a number from 1 to n (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland....
3
from functools import lru_cache n = int(input()) arr = list(map(int,input().split())) odds = evens = 0 for a in arr: if a!=0: odds += a%2 evens += a%2==0 @lru_cache(None) def parity(i, e, o, last=None): if i==n: return 0 elif arr[i]==0 and last==None: even = parity(i+1,e-1,o,0) ...
Does \sqrt{a} + \sqrt{b} < \sqrt{c} hold? Constraints * 1 \leq a, b, c \leq 10^9 * All values in input are integers. Input Input is given from Standard Input in the following format: a \ b \ c Output If \sqrt{a} + \sqrt{b} < \sqrt{c}, print `Yes`; otherwise, print `No`. Examples Input 2 3 9 Output No I...
1
def solve(): a, b, c = [int(_) for _ in raw_input().split()] if a + b >= c: print 'No' elif 4 * a * b < (c - a - b)**2: print 'Yes' else: print 'No' if __name__ == '__main__': solve()
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()) b=list(map(int,input().split())) a=set() unq=[0]*n for i in range(n-1,-1,-1): a.add(b[i]) unq[i]=len(a) l=[] for i in range(m): l.append(int(input())) j=0 for i in range(m): print(unq[l[i]-1])
The only difference between easy and hard versions is constraints. The BerTV channel every day broadcasts one episode of one of the k TV shows. You know the schedule for the next n days: a sequence of integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ k), where a_i is the show, the episode of which will be shown in i-th day. The...
3
for _ in range(int(input())): n, k, d = map(int, input().split()) a = list(map(int, input().split())) s = {} for q in range(d): s[a[q]] = s.get(a[q], 0)+1 ans = len(s) for q in range(d, n): if s[a[q-d]] == 1: del s[a[q-d]] else: s[a[q-d]] -= 1 ...
You are given n strings. Each string consists of lowercase English letters. Rearrange (reorder) the given strings in such a way that for every string, all strings that are placed before it are its substrings. String a is a substring of string b if it is possible to choose several consecutive letters in b in such a way...
3
def SubStrings(n, s): s.sort(key=len) i = n - 1 #print(s) while i > 0: if s[i - 1] not in s[i]: #print(i) # print(s[i - 1] + " " + s[i]) ...
You are given the strings a and b, consisting of lowercase Latin letters. You can do any number of the following operations in any order: * if |a| > 0 (the length of the string a is greater than zero), delete the first character of the string a, that is, replace a with a_2 a_3 … a_n; * if |a| > 0, delete the las...
3
def lcs(str_1, str_2, n, m): dp = [[0 for i in range(m+1)] for i in range(n+1)] result = 0 for i in range(1, n+1): for j in range(1, m+1): if str_1[i-1] == str_2[j-1]: dp[i][j] = dp[i-1][j-1] +1 result = max(result, dp[i][j]) else: ...
Petya organized a strange birthday party. He invited n friends and assigned an integer k_i to the i-th of them. Now Petya would like to give a present to each of them. In the nearby shop there are m unique presents available, the j-th present costs c_j dollars (1 ≤ c_1 ≤ c_2 ≤ … ≤ c_m). It's not allowed to buy a single...
1
import sys if sys.subversion[0] == "PyPy": import io, atexit sys.stdout = io.BytesIO() atexit.register(lambda: sys.__stdout__.write(sys.stdout.getvalue())) sys.stdin = io.BytesIO(sys.stdin.read()) input = lambda: sys.stdin.readline().rstrip() RS = raw_input RI = lambda x=int: map(x,RS().split(...
Alice has a string s. She really likes the letter "a". She calls a string good if strictly more than half of the characters in that string are "a"s. For example "aaabb", "axaa" are good strings, and "baca", "awwwa", "" (empty string) are not. Alice can erase some characters from her string s. She would like to know wh...
3
s = input() n_a = 0 for c in s: if c == 'a': n_a += 1 print(min(2 * n_a - 1, len(s)))
The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, n is always even, and in C2, n is always odd. You are given a regular polygon with 2 ⋅ n vertices (it's convex and has equal sides and equal angles) and all its sides have length 1. Let's name it as 2n...
3
import math # print(math.tan(math.pi/3)) def main(): n=int(input()) p=math.pi tht=p/n ans=1/(math.tan(tht/2)) print(ans) if __name__=="__main__": t=int(input()) for i in range(t): main()
Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are n players (including Limak himself) and right now all of them have bids on the table. i-th of them has bid with size ai dollars. Each player can double his bid any number of times and triple his bid any number of ...
3
def change(n): while n and not n % 2: n /= 2 while n and not n % 3: n /= 3 return n n = int(input()) a = [int(i) for i in input().split()] a = [change(i) for i in a] print("Yes" if len(set(a)) == 1 else "No")
There are N cards placed face down in a row. On each card, an integer 1 or 2 is written. Let A_i be the integer written on the i-th card. Your objective is to guess A_1, A_2, ..., A_N correctly. You know the following facts: * For each i = 1, 2, ..., M, the value A_{X_i} + A_{Y_i} + Z_i is an even number. You ar...
3
N,M=map(int, input().split()) E=[[] for _ in range(N)] for _ in range(M): x,y,z=map(lambda i:int(i)-1, input().split()) E[x].append(y) E[y].append(x) #情報のつながりがあるカードでグルーピングする #グループIDのリスト(0は未割り当て) G=[0]*(N+1) def dfs(root,g): stack=[root] G[root]=g while stack: node=stack.pop() f...
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
from math import ceil n, m, a = map(int, input().split()) x=ceil(n/a)*ceil(m/a) print(x)
While sailing on a boat, Inessa noticed a beautiful water lily flower above the lake's surface. She came closer and it turned out that the lily was exactly H centimeters above the water surface. Inessa grabbed the flower and sailed the distance of L centimeters. Exactly at this point the flower touched the water surfac...
3
x,y = input().split() a = int(x) b = int(y) t = (b*b-a*a)/(2*a) print(t)
Write a program which reads an integer and prints sum of its digits. Input The input consists of multiple datasets. For each dataset, an integer x is given in a line. The number of digits in x does not exceed 1000. The input ends with a line including single zero. Your program should not process for this terminal ...
1
import sys for line in sys.stdin: if int(line) == 0: break s = 0 for c in line.strip('\n'): s += '0123456789'.index(c) print s
Let's call a string a phone number if it has length 11 and fits the pattern "8xxxxxxxxxx", where each "x" is replaced by a digit. For example, "80123456789" and "80000000000" are phone numbers, while "8012345678" and "79000000000" are not. You have n cards with digits, and you want to use them to make as many phone n...
3
n=int(input()) s=list(str(input())) e,m=0,0 if '8' not in s or n<11: print(0) else: e=s.count('8') m=n//11 print(min(e,m))
Draw a chessboard which has a height of H cm and a width of W cm. For example, the following figure shows a chessboard which has a height of 6 cm and a width of 10 cm. .#.#.#.#. .#.#.#.#.# .#.#.#.#. .#.#.#.#.# .#.#.#.#. .#.#.#.#.# Note that the top left corner should be drawn by '#'. Constraints * 1 ≤ H ≤ 300 * 1...
3
while True: h, w = map (int,input().split(" ")) if h == w == 0 : break for y in range(h): print(''.join('#.'[(x+y) %2] for x in range(w))) print("")
As a tradition, every year before IOI all the members of Natalia Fan Club are invited to Malek Dance Club to have a fun night together. Malek Dance Club has 2n members and coincidentally Natalia Fan Club also has 2n members. Each member of MDC is assigned a unique id i from 0 to 2n - 1. The same holds for each member o...
1
x = raw_input() M = 10**9 + 7 k = 1 c = 0 for t in reversed(x): if t == '0': c = c * 2 else: c = c * 2 + k c %= M k *= 4 print c
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
for i in range(0, int(input())): s = input() if len(s) > 10: print(s[0] + str(len(s) - 2) + s[len(s) - 1]) else: print(s)
Top-model Izabella participates in the competition. She wants to impress judges and show her mathematical skills. Her problem is following: for given string, consisting of only 0 and 1, tell if it's possible to remove some digits in such a way, that remaining number is a representation of some positive integer, divisi...
1
s = raw_input() num = 0 flag = False for i in s: if i == '1': flag = True if i == '0' and flag: num += 1 if num >= 6: print 'yes' else: print 'no'
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
n = input() a = n.find("A") z = n.rfind("Z") print(z-a+1)
Arnab is a robber and he has managed to rob N different strings from Akash. Now he decides to sell these strings in the market to make some profit. But, of all the strings he has, he wants to find the size of the largest anagram group so that he can easily sell that one first and make maximum profit initially. Help him...
1
#! /usr/bin/python def hashing(): total_strings=int(raw_input()) assert(total_strings>=1 and total_strings<= 10**5) max_size_annagram=0 dict_hash=dict() for cases in xrange(total_strings): string_input=''.join(sorted(raw_input())) if(dict_hash.has_key(string_input)): dict_h...
There is an image with a height of H pixels and a width of W pixels. Each of the pixels is represented by either `.` or `*`. The character representing the pixel at the i-th row from the top and the j-th column from the left, is denoted by C_{i,j}. Extend this image vertically so that its height is doubled. That is, p...
3
a,b=map(int,input().split()) for i in range(a): s=input() print(s);print(s)
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...
1
from itertools import * num = input() x = y = z = 0 for i in xrange(num): a,b,c = raw_input().split() x = x + int(a) y = y + int(b) z = z + int(c) if x == 0 and y == 0 and z == 0: print "YES" else: print "NO"
There are an integer sequence A_1,...,A_N consisting of N terms, and N buttons. When the i-th (1 ≦ i ≦ N) button is pressed, the values of the i terms from the first through the i-th are all incremented by 1. There is also another integer sequence B_1,...,B_N. Takahashi will push the buttons some number of times so th...
3
N = int(input()) lst = [list(map(int,input().split())) for i in range(N)] lst.reverse() ans = 0 for A,B in lst: if (A+ans)%B != 0: ans += B-(A+ans)%B print(ans)
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not. You are given string s consisting of lowercase Latin letters. At once you can choose any position in th...
3
s = input() a = [0]*26 for i in s: a[ord(i) - 97] += 1 for i in range(26): if a[i] % 2: f = -1 for j in range(i + 1 , 26): if a[j] % 2: f = j if f == -1: break a[f] -= 1 a[i] += 1 fuc = -1 for i in range(26): if a[i]%2: ...
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official language...
3
#dsu from sys import stdin, stdout cin = stdin.readline cout = stdout.write ''' def bfs(x): visited[x] = 1 qu = [x] while len(qu) > 0: for a in v[qu[0]]: if visited[a]: continue visited[a] = 1 qu.append(a) qu.pop(0) ''' def find(x): #print('find ', x) if parent[x] != x: parent[x] = find(pare...
You are given string S and T consisting of lowercase English letters. Determine if S equals T after rotation. That is, determine if S equals T after the following operation is performed some number of times: Operation: Let S = S_1 S_2 ... S_{|S|}. Change S to S_{|S|} S_1 S_2 ... S_{|S|-1}. Here, |X| denotes the len...
3
S = input() T = input() SS = S + S if T in SS : print("Yes") else : print("No")
Shaass has decided to hunt some birds. There are n horizontal electricity wires aligned parallel to each other. Wires are numbered 1 to n from top to bottom. On each wire there are some oskols sitting next to each other. Oskol is the name of a delicious kind of birds in Shaass's territory. Supposed there are ai oskols ...
3
n = int(input()) wires = [0]#Adiciona um 0 e um n+1 elemento para não se preucupar com os extremos for j in (input().split()): wires.append(int(j)) wires.append(0) m = int(input()) for i in range(m): x,y = map(int,input().split()) E = y - 1 D = wires[x] - y wires[x] = 0 wires[x-1] += E ...
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array. According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the requ...
3
n=int(input()) a=list(map(int,input().split())) d={} for i in range(len(a)): d[a[i]]=i+1 m=int(input()) b=list(map(int,input().split())) v,p=0,0 for i in b: v+=d[i] p+=n-d[i]+1 print(v,p)
There are n students standing in a circle in some order. The index of the i-th student is p_i. It is guaranteed that all indices of students are distinct integers from 1 to n (i. e. they form a permutation). Students want to start a round dance. A clockwise round dance can be started if the student 2 comes right after...
3
from sys import stdin def ii(): return int(stdin.readline()) def mi(): return map(int, stdin.readline().split()) def li(): return list(mi()) for _ in range(ii()): n=ii() a=li() p=i=0 while i<n: if abs(a[i]-a[i-1])>1: p+=1 i+=1 print('YES' if p<2 else 'NO')
You are given two positive integers n and k. Print the k-th positive integer that is not divisible by n. For example, if n=3, and k=7, then all numbers that are not divisible by 3 are: 1, 2, 4, 5, 7, 8, 10, 11, 13 .... The 7-th number among them is 10. Input The first line contains an integer t (1 ≤ t ≤ 1000) — the ...
3
from math import * for u in range(int(input())): n,k=map(int,input().split()) print(k-1+ceil(k/(n-1)))
[Thanos sort](https://codegolf.stackexchange.com/questions/182221/implement-the-thanos-sorting-algorithm) is a supervillain sorting algorithm, which works as follows: if the array is not sorted, snap your fingers* to remove the first or the second half of the items, and repeat the process. Given an input array, what i...
3
n=int(input()) a=list(map(int,input().split())) def recursiveFunction(a,x=[]): if a==sorted(a): x.append(len(a)) else: z=len(a)//2 recursiveFunction(a[:z],x) recursiveFunction(a[z:],x) return max(x) print(recursiveFunction(a))
Kirill plays a new computer game. He came to the potion store where he can buy any potion. Each potion is characterized by two integers — amount of experience and cost. The efficiency of a potion is the ratio of the amount of experience to the cost. Efficiency may be a non-integer number. For each two integer numbers ...
3
import math import sys import collections def In(): return map(int, sys.stdin.readline().split()) input = sys.stdin.readline def krillgame(): l, r, x, y, k = In() for i in range(x,y+1): if l<= k*i <= r: print('YES') break else: print('NO') krillgame()
There are H rows and W columns of white square cells. You will choose h of the rows and w of the columns, and paint all of the cells contained in those rows or columns. How many white cells will remain? It can be proved that this count does not depend on what rows and columns are chosen. Constraints * All values i...
1
a, b = map(int, raw_input().split()) c, d = map(int, raw_input().split()) x = a - c y = b - d print x * y
Takahashi likes the sound when he buys a drink from a vending machine. That sound can be heard by spending A yen (the currency of Japan) each time. Takahashi has B yen. He will hear the sound as many times as he can with that money, but at most C times, as he would be satisfied at that time. How many times will he h...
3
A,B,C = map(int,input().split()) print(C if B/A>=C else B//A)
One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are n lines in that description each of which described one goal. Eve...
1
goals = int(input()) team1 = 0 team2 = 0 team1_name = "nope" team2_name = "nope" for x in range (0,goals): if(x==0): team1_name=raw_input() team1+=1 else: temp = raw_input() if(temp == team1_name): team1+=1 else: team2+=1 team2_name = temp if (team...
Melody Pond was stolen from her parents as a newborn baby by Madame Kovarian, to become a weapon of the Silence in their crusade against the Doctor. Madame Kovarian changed Melody's name to River Song, giving her a new identity that allowed her to kill the Eleventh Doctor. Heidi figured out that Madame Kovarian uses a...
3
import sys from collections import Counter import itertools from math import floor, ceil def input(): return sys.stdin.readline().strip() def dinput(): return int(input()) def tinput(): return input().split() def rinput(): return map(int, tinput()) def rt(x1, x2, y3): print(0.5*(x2+x1)) ...
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
def main(): for i in range( int(input())): n = int(input()) arr = list(map(int,input().split())) flag = 0 for i in range(1,len(arr)): if arr[i-1]<=arr[i]: flag = 1 break if flag == 0: print('NO') else: ...
A new e-mail service "Berlandesk" is going to be opened in Berland in the near future. The site administration wants to launch their project as soon as possible, that's why they ask you to help. You're suggested to implement the prototype of site registration system. The system should work on the following principle. ...
1
n=input() dic={} for i in xrange(n): s=raw_input() t=dic.setdefault(s,0) dic[s]+=1 if t==0: print 'OK' else: print s+str(t)
I decided to create a program that displays a "round and round pattern". The "round and round pattern" is as follows. * If the length of one side is n, it is displayed as a character string with n rows and n columns. * A spiral pattern that rotates clockwise with the lower left corner as the base point. * The part wit...
3
vector = ((0, -1), (1, 0), (0, 1), (-1, 0)) def make_guruguru(d): lst = [["#"] * (d + 4)] for _ in range(d + 2): lst.append(["#"] + [" "] * (d + 2) + ["#"]) lst.append(["#"] * (d + 4)) x, y = 2, d + 1 lst[y][x] = "#" direct = 0 vx, vy = vector[0] cnt = 1 while True: while lst[y + vy * 2][x + ...
HQ9+ is a joke programming language which has only four one-character instructions: * "H" prints "Hello, World!", * "Q" prints the source code of the program itself, * "9" prints the lyrics of "99 Bottles of Beer" song, * "+" increments the value stored in the internal accumulator. Instructions "H" and "Q"...
3
a=list(input()) st=0 for i in a: if(i=='H' or i=='Q' or i=='9'): st=1 print("YES") break; if(st==0): print("NO")
One evening Rainbow Dash and Fluttershy have come up with a game. Since the ponies are friends, they have decided not to compete in the game but to pursue a common goal. The game starts on a square flat grid, which initially has the outline borders built up. Rainbow Dash and Fluttershy have flat square blocks with si...
3
test_cases = int(input()) for e in range(test_cases): n = int(input()) ans = (n//2) + 1 print(ans)
Jack is a great mathematician. He loves to solve series. Now Stuart gave a series to Jack and said you have to solve the problem by making a computer program. But Jack doesn't know, how to code. The series is: 1 + (a1).(x)^1 + (a2).(x)^2 + (a3).(x)^3 +........+(an).(x)^n And the problem is find the sum of the a1 + ...
1
t=input() while t>0: t-=1 n=input() print pow(2,n)-1
There are two sisters Alice and Betty. You have n candies. You want to distribute these n candies between two sisters in such a way that: * Alice will get a (a > 0) candies; * Betty will get b (b > 0) candies; * each sister will get some integer number of candies; * Alice will get a greater amount of candie...
3
t= int(input()) for q in range(t): n= int(input()) if n & 1: #odd print(n//2) else: print(n//2 -1)
Little Tanya decided to present her dad a postcard on his Birthday. She has already created a message — string s of length n, consisting of uppercase and lowercase English letters. Tanya can't write yet, so she found a newspaper and decided to cut out the letters and glue them into the postcard to achieve string s. The...
3
s1 = input() s2 = input() ms1 = [0]*26 ms2 = [0]*26 ms3 = [0]*26 ms4 = [0]*26 m = 0 n = 0 for i in range (len(s1)): if ord(s1[i]) in range(ord('A'),ord('Z')+1): ms1[ord(s1[i])-ord('A')] += 1 else: ms2[ord(s1[i])-ord('a')] += 1 for i in range (len(s2)): if ord(s2[i]) in range(ord('A'),ord('Z'...
You have array of n numbers a_{1}, a_{2}, …, a_{n}. Rearrange these numbers to satisfy |a_{1} - a_{2}| ≤ |a_{2} - a_{3}| ≤ … ≤ |a_{n-1} - a_{n}|, where |x| denotes absolute value of x. It's always possible to find such rearrangement. Note that all numbers in a are not necessarily different. In other words, some numb...
3
import os import heapq import sys import math import operator from collections import defaultdict from io import BytesIO, IOBase # def gcd(a,b): # if b==0: # return a # else: # return gcd(b,a%b) def main(): # mod=10**9+7 for _ in range(int(input())): n=int(input()) arr=[...
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them. Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain nu...
3
str=input() sub="WUB" s=str.replace(sub,' ') print(s)
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya loves long lucky numbers very much. He is interested in the minimum lucky number d that meet...
1
a1, a2, a3, a4 = map(int, raw_input().strip().split()) def bad(): print -1 exit() if abs(a3 - a4) > 1: bad() if a3 < a4: if (a1 < a3 + 1):bad() if (a2 < a4):bad() print "7" + "4" * (a1 - a3 - 1) + "47" * a3 + "7" * (a2 - a4) + "4"; elif a3 == a4: if a1 < a3:bad() if a1 == a3: i...
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the oppo...
3
n = int(input()) group = 1 a = input() for i in range(n-1): b = input() if b[0] == a[1]: group += 1 a = b print(group)
In this problem you will write a simple generator of Brainfuck (<https://en.wikipedia.org/wiki/Brainfuck>) calculators. You are given an arithmetic expression consisting of integers from 0 to 255 and addition/subtraction signs between them. Output a Brainfuck program which, when executed, will print the result of eval...
3
from cmath import log10 s=input() a=eval(s) if a<0: print('+++++++++++++++++++++++++++++++++++++++++++++.>') a*=-1 q=a+((a%10)==0)+(a==0) l=(str(log10(q)).split('.')) l=l[0] l=int(l[1:])+1 for i in range(l): q=a//(10**(l-i-1)) a=a%(10**(l-i-1)) b = '++++++++++++++++++++++++++++++++++++++++++++++++'...
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If...
3
# auth: starkizard # just checking if 1111111 present in input or 0000000 present in input. n=input() if "1111111" in n or "0000000" in n: print("YES") else: print("NO")
Vasya has found a strange device. On the front panel of a device there are: a red button, a blue button and a display showing some positive integer. After clicking the red button, device multiplies the displayed number by two. After clicking the blue button, device subtracts one from the number on the display. If at so...
3
n, m = map(int, input().split()) ans = 0 while m > n: if m & 1: m += 1 else: m >>= 1; ans += 1 print(n - m + ans)
You've come to your favorite store Infinitesco to buy some ice tea. The store sells ice tea in bottles of different volumes at different costs. Specifically, a 0.25-liter bottle costs Q yen, a 0.5-liter bottle costs H yen, a 1-liter bottle costs S yen, and a 2-liter bottle costs D yen. The store has an infinite supply...
3
Q, H, S, D = map(int, input().split()) N = int(input()) a = min(Q+Q, H) b = min(a+a, S) c = min(b+b, D) print(N//2*c+b*(N%2))
Recently Vova found n candy wrappers. He remembers that he bought x candies during the first day, 2x candies during the second day, 4x candies during the third day, ..., 2^{k-1} x candies during the k-th day. But there is an issue: Vova remembers neither x nor k but he is sure that x and k are positive integers and k >...
3
t = int(input()) for _ in range(t): n = int(input()) k = 4 while n % (k - 1) != 0: k = k << 1 print(n // (k - 1))
Last year Bob earned by selling memory sticks. During each of n days of his work one of the two following events took place: * A customer came to Bob and asked to sell him a 2x MB memory stick. If Bob had such a stick, he sold it and got 2x berllars. * Bob won some programming competition and got a 2x MB memory ...
3
n=int(input()) dp=[0]*2010 viv=0 for i in range(n): st=input().split() c=int(st[1]) if st[0]=='win': dp[c]=viv+2**c else: viv=max(dp[c],viv) print(viv)
Vasiliy spent his vacation in a sanatorium, came back and found that he completely forgot details of his vacation! Every day there was a breakfast, a dinner and a supper in a dining room of the sanatorium (of course, in this order). The only thing that Vasiliy has now is a card from the dining room contaning notes ho...
3
a , b , c = map(int,input().split(' ')) if (a + b + c) == 1: print('0') exit() elif a==b and b==c: print('0') exit() d = max(a,b,c) res=0 if a < d: res = res + (d - a - 1) if b<d: res= res + (d - b - 1) if c<d: res = res + (d-c-1) print ( res )
There are three friend living on the straight line Ox in Lineland. The first friend lives at the point x1, the second friend lives at the point x2, and the third friend lives at the point x3. They plan to celebrate the New Year together, so they need to meet at one point. What is the minimum total distance they have to...
3
a = list(map(int, input().split())) b = a[:] b.sort() z = b[2] - b[1] m = b[1] - b[0] n = m + z print(n)