problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
There is an infinitely long street that runs west to east, which we consider as a number line. There are N roadworks scheduled on this street. The i-th roadwork blocks the point at coordinate X_i from time S_i - 0.5 to time T_i - 0.5. Q people are standing at coordinate 0. The i-th person will start the coordinate 0 ...
3
def main(): import bisect import sys input = sys.stdin.readline n,q = map(int,input().split()) l = [list(map(int,input().split())) for i in range(n)] l = sorted(l,key = lambda x: x[2]) d = [int(input()) for i in range(q)] ans = [-1]*q skip = [-1]*q for s,t,x in l: le...
Today Patrick waits for a visit from his friend Spongebob. To prepare for the visit, Patrick needs to buy some goodies in two stores located near his house. There is a d1 meter long road between his house and the first shop and a d2 meter long road between his house and the second shop. Also, there is a road of length ...
3
#-------------Program------------- #----KuzlyaevNikita-Codeforces---- # d1,d2,d3=map(int,input().split()) d1,d2=min(d1,d2),max(d1,d2) k=d1 a=d3+d2 b=d3+d3+d1 c=d1+d2+min(d2,d3+d1) k+=min(a,b,c) print(k)
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it. Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all custo...
3
from sys import stdin input = stdin.readline def getAns(n,m): c = sorted([list(map(int,input().split())) for i in range(n)]) l,h,t = m,m,0 for i in range(n): if c[i][0] - t + h < c[i][1] or l - (c[i][0] - t) > c[i][2]: return "NO" l,h,t = max(c[i][1], l - (c[i][0] - t)), min(c[i][2], h + (c...
Panic is rising in the committee for doggo standardization β€” the puppies of the new brood have been born multi-colored! In total there are 26 possible colors of puppies in the nature and they are denoted by letters from 'a' to 'z' inclusive. The committee rules strictly prohibit even the smallest diversity between dog...
3
def func(s): for i in range(26): x=chr(97+i) if(s.count(x)>=2): return 1 return 0 n=int(input()) s=input() if(func(s) or len(s)==1): print("Yes") else: print("No")
A number is ternary if it contains only digits 0, 1 and 2. For example, the following numbers are ternary: 1022, 11, 21, 2002. You are given a long ternary number x. The first (leftmost) digit of x is guaranteed to be 2, the other digits of x can be 0, 1 or 2. Let's define the ternary XOR operation βŠ™ of two ternary n...
3
def main(): t = int(input()) for _ in range(t): n = int(input()) x = input() v, u = "1", "1" for i in range(1, n): k = int(x[i]) if k == 1: v += "0" u += "1" v += x[i+1:] u += "0" * (n-i-1) ...
Lately, a national version of a bingo game has become very popular in Berland. There are n players playing the game, each player has a card with numbers. The numbers on each card are distinct, but distinct cards can have equal numbers. The card of the i-th player contains mi numbers. During the game the host takes num...
3
#!/usr/bin/python3 def readln(): return tuple(map(int, input().split())) n, = readln() lst = [set(readln()[1:]) for _ in range(n)] for a in lst: print("YES" if len([1 for b in lst if len(a.union(b)) == len(a)]) == 1 else "NO")
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...
1
x,y=map(int,raw_input().split()) z=x*y c=0 while(z>1): z=z-2 c=c+1 print(c)
You are given k sequences of integers. The length of the i-th sequence equals to n_i. You have to choose exactly two sequences i and j (i β‰  j) such that you can remove exactly one element in each of them in such a way that the sum of the changed sequence i (its length will be equal to n_i - 1) equals to the sum of the...
3
k=int(input()) l=[] for i in range(k): n=int(input()) xs=[int(x) for x in input().split()] l.append(xs) p=[sum(l[i]) for i in range(k)] d={} flag=0 i=0 j=0 while(i<k): j=0 while(j<len(l[i])): if(p[i]-l[i][j] not in d): d[p[i]-l[i][j]]=[i+1,j+1] else: if(d[p[i]...
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find ...
3
def lucky(n): while n!=0: if n%10 !=4 and n%10 != 7: return False n = n//10 return True n = int(input()) if lucky(n): print("YES") elif n%47==0: print("YES") elif n%4==0 or n%7==0: print("YES") else: print("NO")
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that 1. 1 ≀ i, j ≀ N 2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th. Input The single input line contains S, consisting of lowercase Latin letters and digits. It is ...
1
text = raw_input() d = dict() for c in text: d[c] = d.get(c, 0) + 1 print sum(value*value for value in d.values())
You are given four integers A, B, C, and D. Find the number of integers between A and B (inclusive) that can be evenly divided by neither C nor D. Constraints * 1\leq A\leq B\leq 10^{18} * 1\leq C,D\leq 10^9 * All values in input are integers. Input Input is given from Standard Input in the following format: A B ...
1
#!/usr/bin/env python from collections import deque import itertools as ite import sys import math sys.setrecursionlimit(1000000) INF = 10 ** 18 MOD = 10 ** 9 + 7 A, B, C, D = map(int, raw_input().split()) def GCD(a, b): dummy1 = max(a, b) dummy2 = min(a, b) while True: dummy = dummy1 % dummy2 dummy1 = dummy...
++++++++[>+>++>+++>++++>+++++>++++++>+++++++>++++++++>+++++++++>++++++++++>+ ++++++++++>++++++++++++>+++++++++++++>++++++++++++++>+++++++++++++++>+++++++ +++++++++<<<<<<<<<<<<<<<<-]>>>>>>>>>>.<<<<<<<<<<>>>>>>>>>>>>>>++.--<<<<<<<<< <<<<<>>>>>>>>>>>>>+.-<<<<<<<<<<<<<>>>>>>>>>>>>>>--.++<<<<<<<<<<<<<...
3
A=int(input("")) A=oct(A) A=str(A) a=A.count("1") print(a)
Polycarp urgently needs a shovel! He comes to the shop and chooses an appropriate one. The shovel that Policarp chooses is sold for k burles. Assume that there is an unlimited number of such shovels in the shop. In his pocket Polycarp has an unlimited number of "10-burle coins" and exactly one coin of r burles (1 ≀ r ...
3
k,r=list(map(int,input().split())) cntr=0 while True: cntr+=1 h=k*cntr if h%10==0 or (h-r)%10==0: break print(cntr)
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
from math import pow h, l = input().split() h = float(h) l = float(l) y = pow(l, 2)/(2*h)-(h/2) print(y) print()
The only difference between the easy and the hard versions is constraints. A subsequence is a string that can be derived from another string by deleting some or no symbols without changing the order of the remaining symbols. Characters to be deleted are not required to go successively, there can be any gaps between th...
3
import sys input=sys.stdin.readline xx='abcdefghijklmnopqrstuvwxyz' yy={} for i in range(26): yy[xx[i]]=i n,kk=map(int,input().split()) st=list(input())[:-1] count_ar=[0]*n se=[-1]*26 count=0 for i in range(n-1,-1,-1): se[yy[st[i]]]=i count_ar[i]=se.copy() count_ar.append([]) main=[1] freq_ind=[0]*n nex=...
Let us call a pair of integer numbers m-perfect, if at least one number in the pair is greater than or equal to m. Thus, the pairs (3, 3) and (0, 2) are 2-perfect while the pair (-1, 1) is not. Two integers x, y are written on the blackboard. It is allowed to erase one of them and replace it with the sum of the number...
3
x, y, m = [int(x) for x in input().split()] a = max(x, y) b = min(x, y) num = 0 if a >= m: print('0') else: if a + b <= b: print(-1) else: if b < 0: num += int(-b / a) b += a * int(-b / a) while a < m: num += 1 a, b = [max(a + b, a),min...
For a given array a consisting of n integers and a given integer m find if it is possible to reorder elements of the array a in such a way that βˆ‘_{i=1}^{n}{βˆ‘_{j=i}^{n}{(a_j)/(j)}} equals m? It is forbidden to delete elements as well as insert new elements. Please note that no rounding occurs during division, for exampl...
3
import sys input = sys.stdin.readline for _ in range(int(input())): n,m = map(int,input().split()) a = list(map(int,input().split())) if m==sum(a): print("YES") else: print("NO")
Nauuo is a girl who loves writing comments. One day, she posted a comment on Codeforces, wondering whether she would get upvotes or downvotes. It's known that there were x persons who would upvote, y persons who would downvote, and there were also another z persons who would vote, but you don't know whether they woul...
3
x, y, z = [int(x) for x in input().split()] if x > y + z: print('+') elif y > x + z: print('-') elif x == y and z == 0: print('0') else: print('?')
Sometimes it is not easy to come to an agreement in a bargain. Right now Sasha and Vova can't come to an agreement: Sasha names a price as high as possible, then Vova wants to remove as many digits from the price as possible. In more details, Sasha names some integer price n, Vova removes a non-empty substring of (cons...
3
Mod = (10 ** 9) + 7 T = str(input()) n = len(T) substring = [0 for i in range(n)] pow10 = [0 for j in range(n)] pow10[0] = 1 for i in range(1, n): pow10[i] = (pow10[i - 1] * 10) % Mod for i in range(n - 1): substring[n - i - 2] = (substring[n - i - 1] + (pow10[i]) * (i + 1)) % Mod count = 0 for i in range...
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated. The language is that peculiar as it has exactly one variable, called x. Also, there are two operations: * Operation ++ increases the value of variable x by 1. * Operation -- decreases the value of variable x by 1....
3
n=int(input()) nr=0 for i in range(n): s=input() if '+' in s: nr=nr+1; else: nr=nr-1 print(nr)
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
import math line = input() n, m = line.split() n = int(n) m = int (m) #algorithm begins result= math.floor((n*m)/2) print(result)
Fox Ciel is developing an artificial intelligence (AI) for a game. This game is described as a game tree T with n vertices. Each node in the game has an evaluation value which shows how good a situation is. This value is the same as maximum value of child nodes’ values multiplied by -1. Values on leaf nodes are evaluat...
3
from collections import deque import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): N = int(readline()) *P, = map(int, readline().split()) G = [] prt = [0]*N for i in range(N): k, *t = map(int, readline().split()) G.append([e-1 for e in t]) for e in t...
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...
3
n=int(input()) x = 0 for i in range(n): t,k = list(map(int,input().split())) if t>=k or ((k-t)==1): x+=1 print(n-x)
Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths a, b, and c. Now he needs to find out some possible integer length d of the fourth straight fence segment so that he can build the fence using these four...
3
t=int(input()) for _ in range(t): a,b,c=map(int,input().split()) m=max(a,b,c) s=a+b+c print(int(2*m-s+1>0)*(2*m-s+1)+(1-int(2*m-s+1>0))*(a+b+c-1))
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
def go(): n = int(input()) a = [int(i) for i in input().split(' ')] i = -1 j = n s1 = 0 s2 = 0 output = 0 while i < j: if s1 > s2: j -= 1 s2 += a[j] elif s2 > s1: i += 1 s1 += a[i] else: output = s1 ...
Alica and Bob are playing a game. Initially they have a binary string s consisting of only characters 0 and 1. Alice and Bob make alternating moves: Alice makes the first move, Bob makes the second move, Alice makes the third one, and so on. During each move, the current player must choose two different adjacent char...
3
n = int(input()) for _ in range(n): s = str(input()) c1 = s.count("0") c2 = len(s)-c1 c = min(c1,c2) if c&1: print("DA") else: print("NET")
Due to the coronavirus pandemic, city authorities obligated citizens to keep a social distance. The mayor of the city Semyon wants to light up Gluharniki park so that people could see each other even at night to keep the social distance. The park is a rectangular table with n rows and m columns, where the cells of the...
3
import math import sys from sys import stdin input=sys.stdin.readline for _ in range(int(input())): n,m=[int(j) for j in input().split()] s = n*(m//2) + (m%2)*(math.ceil(n/2)) print(s)
Vova had a pretty weird sleeping schedule. There are h hours in a day. Vova will sleep exactly n times. The i-th time he will sleep exactly after a_i hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is 0). Each time Vova sleeps exactly one day (in...
3
import sys import math input=sys.stdin.readline #t=int(input()) t=1 for _ in range(t): n,h,l,r=map(int,input().split()) a=list(map(int,input().split())) a.insert(0,0) dp=[[0 for j in range(n+1)] for i in range(n+1)] pref=[0]*(n+2) for i in range(1,n+1): pref[i]=pref[i-1]+a[i] if...
You are given a sequence a consisting of n integers. You may partition this sequence into two sequences b and c in such a way that every element belongs exactly to one of these sequences. Let B be the sum of elements belonging to b, and C be the sum of elements belonging to c (if some of these sequences is empty, the...
3
def answer(): n = int(input()) a = [int(x) for x in input().split()] b = [x for x in a if x<0] c = [x for x in a if x>0] print(abs(sum(b))+sum(c)) answer()
Prateek wants to give a party to his N friends on his birthday, where each friend is numbered from 1 to N. His friends are asking for a gift to come to the party, instead of giving him one. The cost of the gifts are given in the array Value where i^th friend asks for a gift which has a cost Costi. But, Prateek has o...
1
T = int(raw_input()) while T>0: T -= 1 N, X = map(int, raw_input().split(" ")) nums = [] while N>0: nums.append( int(raw_input())) N -= 1 _sum = 0 start = 0 ptr = 0 yes = False length = len(nums) while start < length: if _sum == X: yes = True break elif _sum < X and ptr<length: _sum += nums[...
You're given two arrays a[1 ... n] and b[1 ... n], both of the same length n. In order to perform a push operation, you have to choose three integers l, r, k satisfying 1 ≀ l ≀ r ≀ n and k > 0. Then, you will add k to elements a_l, a_{l+1}, …, a_r. For example, if a = [3, 7, 1, 4, 1, 2] and you choose (l = 3, r = 5, ...
3
def compare(a,b): n=len(a) for i in range(n): if a[i]==b[i]: continue else: k=b[i]-a[i] for j in range(i,n): if b[j]-a[j]!=k: for k in range(j,n): if a[k]==b[k]: return "YES" else: return "NO" def com(a,b): i=0 n=len(a) c=[] for _ in range(n): c.append(b[_]-a[_]) ...
There is a river of width n. The left bank of the river is cell 0 and the right bank is cell n + 1 (more formally, the river can be represented as a sequence of n + 2 cells numbered from 0 to n + 1). There are also m wooden platforms on a river, the i-th platform has length c_i (so the i-th platform takes c_i consecuti...
3
from sys import stdin, stdout if __name__ == '__main__': A = stdin.readline().strip().split() n = int(A[0]) # the width of the river m = int(A[1]) # the number of platforms d = int(A[2]) # the maximum distance of your jump c = list(map(int, stdin.readline().strip().split())) gap = n - s...
Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer. Reliable sources have informed the financier Anton of some information about the exchange rate of...
3
n=input() ans=-1 l=len(n) last=n[l-1] m=-1 for x in range(l-1): if int(n[x])%2==0: m=x if int(n[x])<int(n[-1]): break if(m==-1): print(-1) else: print(n[0:m]+last+n[m+1:-1]+n[m])
Let's play Amidakuji. In the following example, there are five vertical lines and four horizontal lines. The horizontal lines can intersect (jump across) the vertical lines. <image> In the starting points (top of the figure), numbers are assigned to vertical lines in ascending order from left to right. At the first...
3
w = eval(input()) n = eval(input()) numlist = [item for item in range(1, w + 1)] for t in range(n): i, j = [eval(item) - 1 for item in input().split(',')] numlist[i], numlist[j] = numlist[j], numlist[i] for item in numlist: print(item)
All cities of Lineland are located on the Ox coordinate axis. Thus, each city is associated with its position xi β€” a coordinate on the Ox axis. No two cities are located at a single point. Lineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another city (bec...
3
no_cities = int(input()) string = input() l1 = string.split(' ') l2 = [] count = 0 for ele in l1: ele = int(ele) l2.append(ele) l4 = l2[:] l4.sort(reverse = True) for ele in l2: left = l2[0] right = l4[0] dist1 = ele - left dist2 = right - ele if (dist1 == 0): mincost = l2[1] - ele ...
There are n beacons located at distinct positions on a number line. The i-th beacon has position ai and power level bi. When the i-th beacon is activated, it destroys all beacons to its left (direction of decreasing coordinates) within distance bi inclusive. The beacon itself is not destroyed however. Saitama will acti...
1
import sys num = int(raw_input()) lst = 1000001 * [0] for item in xrange(0, num): loc, power = map(int, raw_input().split()) lst[loc] = power lst2 = 1000001 * [0] for item in xrange(0, 1000001): if(lst[item] == 0): if(item == 0): lst2[item] = 0 else: lst2[item] = lst2[item - 1] else: if(item - 1 -...
Ayush is a cashier at the shopping center. Recently his department has started a ''click and collect" service which allows users to shop online. The store contains k items. n customers have already used the above service. Each user paid for m items. Let aij denote the j-th item in the i-th person's order. Due to the...
3
[n, k, m] = [int(x) for x in input().split()] u=[] result = 0 for i in range (1): t = [int(x) for x in input().split()] for i in range (1,n+1): x = [int(x) for x in input().split()] for j in range (k): u.append(x[j]) for l in range (n*k): a = u[l] b = t.index(a)+1 result = result + b ...
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'...
1
import math a,b,c = map(float, raw_input().split(' ')) print int(math.ceil(a/c)*math.ceil(b/c))
<image> William is a huge fan of planning ahead. That is why he starts his morning routine by creating a nested list of upcoming errands. A valid nested list is any list which can be created from a list with one item "1" by applying some operations. Each operation inserts a new item into the list, on a new line, just...
3
a=int(input()) from collections import * import heapq for i in range(a): ans=[] n=int(input()) for i in range(n): s=int(input()) ans.append(s) stack=[] for i in range(len(ans)): if(i==0): stack.append(ans[i]) print(ans[i]) continue;...
There are n points on the plane, (x_1,y_1), (x_2,y_2), …, (x_n,y_n). You need to place an isosceles triangle with two sides on the coordinate axis to cover all points (a point is covered if it lies inside the triangle or on the side of the triangle). Calculate the minimum length of the shorter side of the triangle. I...
3
n = int(input()) s = [] c,r=0,0 for i in range(n): a,b = map(int,input().split()) c = max(a+b,c) print(c)
One day Alex was creating a contest about his friends, but accidentally deleted it. Fortunately, all the problems were saved, but now he needs to find them among other problems. But there are too many problems, to do it manually. Alex asks you to write a program, which will determine if a problem is from this contest ...
1
a=raw_input() p=["Danil", "Olya", "Slava", "Ann", "Nikita"] s=0 for i in p: s+=a.count(i) if s==1:print "YES" else : print "NO"
Vlad likes to eat in cafes very much. During his life, he has visited cafes n times. Unfortunately, Vlad started to feel that his last visits are not any different from each other. To fix that Vlad had a small research. First of all, Vlad assigned individual indices to all cafes. Then, he wrote down indices of cafes h...
3
n = int(input()) lst = list(map(int, input().split())) # lst.reverse() s = set(lst) i = n-1 while len(s) > 1: if lst[i] in s: s.remove(lst[i]) i -= 1 print(s.pop())
You are given the array a consisting of n positive (greater than zero) integers. In one move, you can choose two indices i and j (i β‰  j) such that the absolute difference between a_i and a_j is no more than one (|a_i - a_j| ≀ 1) and remove the smallest of these two elements. If two elements are equal, you can remove a...
3
I=input exec(int(I())*"n=int(I());o=sum(int(x)%2for x in I().split());print('NYOE S'[0<o<n+n%2::2]);")
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
a=int(input()) s=input() count=0 for i in range(0,a-1): if s[a-i-1]==s[a-i-2]: s=s[:a-i-1]+s[a-i:] count+=1 print(count)
Walking along a riverside, Mino silently takes a note of something. "Time," Mino thinks aloud. "What?" "Time and tide wait for no man," explains Mino. "My name, taken from the river, always reminds me of this." "And what are you recording?" "You see it, tide. Everything has its own period, and I think I've figured...
3
n,m = map(int,input().split()) s=input() h=s k=s[:m] s=s[m:] count=1 result="" while s.find(k)>=0 and len(s)>m: s=s[m:] count+=1 check=False for i in range(min(len(k),len(s))): if k[i]!=s[i]: check=True if s[i]==".": mid=k[i] dk="s" else: dk="k" ...
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word s. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if...
3
s=input() a='hello' j=0 for i in range(len(s)): if s[i]==a[j]: j+=1 if j==5: break if j==5: print("YES") else: print("NO")
Chef loves research! Now he is looking for subarray of maximal length with non-zero product. Chef has an array A with N elements: A1, A2, ..., AN. Subarray Aij of array A is elements from index i to index j: Ai, Ai+1, ..., Aj. Product of subarray Aij is product of all its elements (from ith to jth). Input First li...
1
n=int(raw_input()) a=map(int,raw_input().split()) ans=0 count=0 for i in xrange(n): if a[i]!=0: count+=1 if count>ans: ans=count if a[i]==0: count=0 print ans
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 = int(input()) #n, m = map(int, input().split()) #d = list(map(int, input().split())) n, m = map(int, input().split()) a = list(map(int, input().split())) b = list(map(int, input().split())) p = 0 for i in range(m): if a[p] <= b[i]: p += 1 if p >= n: break print(n - p)
We have two distinct integers A and B. Print the integer K such that |A - K| = |B - K|. If such an integer does not exist, print `IMPOSSIBLE` instead. Constraints * All values in input are integers. * 0 \leq A,\ B \leq 10^9 * A and B are distinct. Input Input is given from Standard Input in the following format: ...
3
a,b = map(int, input().split()) print(int(a+((b-a)/2)) if (b-a)%2 == 0 else "IMPOSSIBLE")
A sequence a0, a1, ..., at - 1 is called increasing if ai - 1 < ai for each i: 0 < i < t. You are given a sequence b0, b1, ..., bn - 1 and a positive integer d. In each move you may choose one element of the given sequence and add d to it. What is the least number of moves required to make the given sequence increasin...
1
def f(a): if a>0: return a else: return 0 temp = raw_input().split() n, d = int(temp[0]), int(temp[1]) tab = raw_input().split() for i in range(len(tab)): tab[i] = int(tab[i]) res = 0 for i in range(1,len(tab)): res += f((tab[i-1]-tab[i])/d+1) tab[i] += f(((tab[i-1]-tab[i])/d+1)...
Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not. Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindro...
3
# -*- coding: utf-8 -*- """ Created on Wed Mar 18 14:49:22 2020 @author: Alok """ def palin(num): f_no=num+num[::-1] print(f_no) num=input() palin(num)
Let's consider a table consisting of n rows and n columns. The cell located at the intersection of i-th row and j-th column contains number i Γ— j. The rows and columns are numbered starting from 1. You are given a positive integer x. Your task is to count the number of cells in a table that contain number x. Input T...
3
n, x = (int(x) for x in input().split()) print([x % i == 0 and x // i <= n for i in range(1, n + 1)].count(True))
You are playing one RPG from the 2010s. You are planning to raise your smithing skill, so you need as many resources as possible. So how to get resources? By stealing, of course. You decided to rob a town's blacksmith and you take a follower with you. You can carry at most p units and your follower β€” at most f units. ...
3
def maxItem(p, f, cnts, cntw, s, w): if s > w: return maxItem(p, f, cntw, cnts, w, s) if p < f: return maxItem(f, p, cntw, cnts, w, s) ans = 0 for s1 in range(min(cnts, p // s) + 1): w1 = min(cntw, (p - s1 * s) // w) s2 = min(cnts - s1, f // s) w2 = min(cntw - w1,...
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
import math if __name__ == '__main__': n,m,a = input().split(" ") n = int(n) m = int(m) a = int(a) i = int(math.ceil(n/a)) j = int(math.ceil(m/a)) print(i*j)
To satisfy his love of matching socks, Phoenix has brought his n socks (n is even) to the sock store. Each of his socks has a color c_i and is either a left sock or right sock. Phoenix can pay one dollar to the sock store to either: * recolor a sock to any color c' (1 ≀ c' ≀ n) * turn a left sock into a right ...
3
g = int(input()) while g>0: g -= 1 n,L,R = map(int, input().split()) a = list(map(int, input().split())) l = {} r = {} for i in range(n): if i<L: if a[i] not in l: l[a[i]] = 0 l[a[i]] += 1 else: if a[i] not in r: ...
Two polar bears Menshykov and Uslada from the St.Petersburg zoo and elephant Horace from the Kiev zoo got six sticks to play with and assess the animals' creativity. Menshykov, Uslada and Horace decided to make either an elephant or a bear from those sticks. They can make an animal from sticks in the following way: ...
1
m = map(int,raw_input().split()) d = {} for i in m: d[i] = d.get(i,0) + 1 if sum(d[i] >= 4 for i in d.keys()) == 0: print 'Alien' else: l = [i for i in d.keys() if d[i] != 4] if max(l) == min(l): print 'Elephant' else: print 'Bear'
Little Vasya went to the supermarket to get some groceries. He walked about the supermarket for a long time and got a basket full of products. Now he needs to choose the cashier to pay for the products. There are n cashiers at the exit from the supermarket. At the moment the queue for the i-th cashier already has ki p...
3
def calculator(men, buying): result = 0 result += sum(buying) * 5 result += men * 15 return result def main(): pay_desks = int(input()) queue = list(map(int, input().split())) temporal = 0 amount = calculator(queue[0], list(map(int, input().split()))) for i in range(1, pay_desks): ...
It is winter now, and Max decided it's about time he watered the garden. The garden can be represented as n consecutive garden beds, numbered from 1 to n. k beds contain water taps (i-th tap is located in the bed xi), which, if turned on, start delivering water to neighbouring beds. If the tap on the bed xi is turned ...
3
t=int(input()) for mmm in range(t): n,m=map(int,input().split()) time=0 wa=[i-1 for i in map(int,input().split())] a=[0 for i in range(n)] for i in wa: a[i]=1 while a.count(1)!=len(a): time+=1 j=0 b=a.copy() while j<n: if b[j]==1 and j!=0 and j!=n-1: ...
Kolya is very absent-minded. Today his math teacher asked him to solve a simple problem with the equation a + 1 = b with positive integers a and b, but Kolya forgot the numbers a and b. He does, however, remember that the first (leftmost) digit of a was d_a, and the first (leftmost) digit of b was d_b. Can you reconst...
3
def gp(d1, d2): if d1 == d2: return d1 * 10, d2 * 10 + 1 elif d2 - d1 == 1: return d1 * 10 + 9, d2 * 10 elif d2 == 1 and d1 == 9: return 9, 10 return [-1] print(*gp(*[int(i) for i in input().split()]))
Girl Lena likes it when everything is in order, and looks for order everywhere. Once she was getting ready for the University and noticed that the room was in a mess β€” all the objects from her handbag were thrown about the room. Of course, she wanted to put them back into her handbag. The problem is that the girl canno...
1
x0, y0 = map(int, raw_input().split()) n = input() def cdist(x, y): return x * x + y * y d0 = [0] * n d1 = [[0] * n for i in xrange(n)] d2 = [] for i in xrange(n): x, y = map(int, raw_input().split()) d0[i] = cdist(x - x0, y - y0) for j in xrange(i): d1[i][j] = cdist(x - d2[j][0], y - d2...
You are given an array A, consisting of n positive integers a_1, a_2, ..., a_n, and an array B, consisting of m positive integers b_1, b_2, ..., b_m. Choose some element a of A and some element b of B such that a+b doesn't belong to A and doesn't belong to B. For example, if A = [2, 1, 7] and B = [1, 3, 4], we can ...
3
int(input()) a=max(map(int,input().split())) int(input()) b=max(map(int,input().split())) print(a,b)
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
def lp(s): n = len(s) l, r = 0, n - 1 while True: i, j = 0, r while i < j and s[i] == s[j]: i, j = i + 1, j - 1 if i >= j: return s[:r+1] r -= 1 i, j = l, n - 1 while i < j and s[i] == s[j]: i, j = i + 1, j - 1 if i >= j: retu...
Student Valera is an undergraduate student at the University. His end of term exams are approaching and he is to pass exactly n exams. Valera is a smart guy, so he will be able to pass any exam he takes on his first try. Besides, he can take several exams on one day, and in any order. According to the schedule, a stud...
3
n=int(input()) l=[] for i in range (n) : ch=input() l1=ch.split() l.append((int(l1[0]),int(l1[1]))) l.sort() m=l[0][1] i=1 b=False while i<(len(l)): if l[i][1]>= m : m=l[i][1] i=i+1 elif l[i][0]>= m : m=l[i][0] i=i+1 else : i=len(l) b=True if...
Adilbek was assigned to a special project. For Adilbek it means that he has n days to run a special program and provide its results. But there is a problem: the program needs to run for d days to calculate the results. Fortunately, Adilbek can optimize the program. If he spends x (x is a non-negative integer) days opt...
3
t=int(input()) for i in range(t): n,d=map(int,input().split()) if(((n+1)**2-4*d)>=0): print("YES") else: print("NO")
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated. The language is that peculiar as it has exactly one variable, called x. Also, there are two operations: * Operation ++ increases the value of variable x by 1. * Operation -- decreases the value of variable x by 1....
3
n = int(input()) x = 0 for i in range(n): a = input() # a = a.capitalize() # print(a) if a == "++X" or a == "X++": # print("xinc") x = x + 1 elif a == "--X" or a == "X--": # print("xdec") x = x - 1 else: x = 0 print(x)
There are N observatories in AtCoder Hill, called Obs. 1, Obs. 2, ..., Obs. N. The elevation of Obs. i is H_i. There are also M roads, each connecting two different observatories. Road j connects Obs. A_j and Obs. B_j. Obs. i is said to be good when its elevation is higher than those of all observatories that can be r...
3
N,M = map(int,input().split()) H = list(map(int,input().split())) P = [1]*N for _ in range(M): A,B = map(int,input().split()) Ah = H[A-1] Bh = H[B-1] if Ah >= Bh: P[B-1] = 0 if Bh >= Ah: P[A-1] = 0 print(sum(P))
You have r red, g green and b blue balloons. To decorate a single table for the banquet you need exactly three balloons. Three balloons attached to some table shouldn't have the same color. What maximum number t of tables can be decorated if we know number of balloons of each color? Your task is to write a program tha...
3
l = [int(x) for x in input().split()] l.sort() s = sum(l) a = int(s/3) s-=l[2] if(s<a): print(s) else: print(a)
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
n = int(input()) T = 0 max_ = 0 for i in range(n): a, b = map(int, input().split()) T = T - a + b if T > max_: max_ = T print(max_)
Our monk, while taking a stroll in the park, stumped upon a polynomial ( A X^2 + B X +C ) lying on the ground. The polynomial was dying! Being considerate, our monk tried to talk and revive the polynomial. The polynomial said: I have served my purpose, and shall not live anymore. Please fulfill my dying wish. Find m...
1
from math import log, ceil, sqrt E = lambda a,b,c,x: a*x**2 + b*x + c y = lambda a,b,c: b**2 - 4*a*c X = lambda a,b,c, det: ((-b - det)/float(2*a), (-b + det)/float(2*a)) def poly_solver(a,b,c,K): if K < min(a,b,c): # print "%s < min(%s,%s,%s)"%(K, a,b,c) return 0 N = 0 det = y(a,b,c) ...
You are given two positive integers a and b. In one move you can increase a by 1 (replace a with a+1). Your task is to find the minimum number of moves you need to do in order to make a divisible by b. It is possible, that you have to make 0 moves, as a is already divisible by b. You have to answer t independent test c...
3
a = int(input()) for _ in range(a): a, b = map(int, input().split()) if a % b == 0: print('0') else: floor = a // b b = (floor + 1) * b print(b-a)
There are n athletes in front of you. Athletes are numbered from 1 to n from left to right. You know the strength of each athlete β€” the athlete number i has the strength s_i. You want to split all athletes into two teams. Each team must have at least one athlete, and each athlete must be exactly in one team. You want...
3
for _ in range(int(input())): n=int(input()) s=sorted(map(int,input().split())) a=9e9 for i in range(1,n):a=min(a,s[i]-s[i-1]) print(a)
There are N integers, A_1, A_2, ..., A_N, arranged in a row in this order. You can perform the following operation on this integer sequence any number of times: Operation: Choose an integer i satisfying 1 \leq i \leq N-1. Multiply both A_i and A_{i+1} by -1. Let B_1, B_2, ..., B_N be the integer sequence after your ...
3
N = int(input()) A = list(map(int, input().split())) B = [abs(a) for a in A] M = len([a for a in A if a < 0]) if M % 2 == 0: print(sum(B)) else: print(sum(B) - 2 * min(B))
There is a square-shaped grid with N vertical rows and N horizontal columns. We will denote the square at the i-th row from the top and the j-th column from the left as (i,\ j). Initially, each square is either white or black. The initial color of the grid is given to you as characters a_{ij}, arranged in a square sha...
3
n = int(input()) a = [input() for _ in range(n)] ans1 = float('inf') for i in range(n): for j in range(n): if a[j][i] == '#': break else: continue break else: print(-1) exit(0) for i in range(n): cnt = 1 for j in range(n): if a[j][i] == '#': cn...
You are given three integers A, B and C. Determine whether C is not less than A and not greater than B. Constraints * -100≀A,B,C≀100 * A, B and C are all integers. Input Input is given from Standard Input in the following format: A B C Output If the condition is satisfied, print `Yes`; otherwise, print `No`. ...
3
a, b, c = map(int,input().split()) ans = "No" if(a <= c <= b): ans = "Yes" print(ans)
Gerald got a very curious hexagon for his birthday. The boy found out that all the angles of the hexagon are equal to <image>. Then he measured the length of its sides, and found that each of them is equal to an integer number of centimeters. There the properties of the hexagon ended and Gerald decided to draw on it. ...
1
s = raw_input().split() for i in range(len(s)): s[i] = int(s[i]) ans = (s[0] + s[3]) * (s[1] + s[2]) + s[4] * s[5] + s[2] * s[1] print ans
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
print(["NO","YES"][any(map(input().count,["H","Q","9"]))])
A car moves from point A to point B at speed v meters per second. The action takes place on the X-axis. At the distance d meters from A there are traffic lights. Starting from time 0, for the first g seconds the green light is on, then for the following r seconds the red light is on, then again the green light is on fo...
1
x,d,v,g,r=map(float,raw_input().split()) t1=d/v eps=1e-10 if (t1%(g+r))>g-eps: print "%.10f" % ((g+r)*(t1//(g+r)+1)+(x-d)/v) else: print "%.10f" % (x/v)
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
stone_list = [] t = int(input()) stones = input() for character in stones: stone_list.append(character) active = True deletes = 0 i = 0 while active and i < len(stone_list) - 1: if stone_list[i] == stone_list[i+1]: deletes += 1 del stone_list[i] else: i += 1 print (deletes)
Polycarp plays a well-known computer game (we won't mention its name). In this game, he can craft tools of two types β€” shovels and swords. To craft a shovel, Polycarp spends two sticks and one diamond; to craft a sword, Polycarp spends two diamonds and one stick. Each tool can be sold for exactly one emerald. How many...
3
for _ in range(int(input())): a, b = map(int, input().split()) print(min([a,b,(a+b)//3]))
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." β€” an excerpt from contest rules. A total of n participants took part in the contest (n β‰₯ k), and you already know their scores. Calculate how many ...
3
n,k = map(int,input().split()) score = list(map(int,input().split())) promote=k if score[k-1]==0: while promote>0: if score[promote-1]==0: promote-=1 else: break else: while promote<n: if score[promote]==score[k-1]: promote+=1 else: ...
Bob is a competitive programmer. He wants to become red, and for that he needs a strict training regime. He went to the annual meeting of grandmasters and asked n of them how much effort they needed to reach red. "Oh, I just spent x_i hours solving problems", said the i-th of them. Bob wants to train his math skills...
3
n = int(input()) for i in range(n): y = input() zero = 0 even = 0 sm = 0 zero = y.count('0') for j in y: sm += int(j) if(int(j)%2==0 and j!='0'): even = 1 ans = 0 if(sm == 0): ans = 1 elif(zero>0): if(zero==1): if(even==1...
There is a rectangular room, covered with square tiles. Each tile is colored either red or black. A man is standing on a black tile. From a tile, he can move to one of four adjacent tiles. But he can't move on red tiles, he can move only on black tiles. Write a program to count the number of black tiles which he can r...
3
def main(): while 1: w, h = map(int, input().split()) if w == 0: break fld = [[] for i in range(h)] for i in range(h): readline = input() for j in range(w): item = readline[j] fld[i].append(item) if item == '@': ...
There are five people playing a game called "Generosity". Each person gives some non-zero number of coins b as an initial bet. After all players make their bets of b coins, the following operation is repeated for several times: a coin is passed from one player to some other player. Your task is to write a program that...
3
""" https://codeforces.com/problemset/problem/478/A """ c = [int(x) for x in input().split(" ")] if sum(c)%5 == 0 and sum(c) != 0: print(sum(c)//5) else: print("-1")
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th...
3
palavra = input() maiusculo = 0 minusculo = 0 for i in palavra: if i.isupper(): maiusculo += 1 else: minusculo += 1 if maiusculo > minusculo: print(palavra.upper()) else: print(palavra.lower())
Vasya claims that he had a paper square. He cut it into two rectangular parts using one vertical or horizontal cut. Then Vasya informed you the dimensions of these two rectangular parts. You need to check whether Vasya originally had a square. In other words, check if it is possible to make a square using two given rec...
3
t = int(input()) for i in range(t): a = list(map(int, input().split())) b = list(map(int, input().split())) n = min(a) + min(b) m = max(a) l = max(b) if n==m==l: print("YES") else: print("NO")
You have a coins of value n and b coins of value 1. You always pay in exact change, so you want to know if there exist such x and y that if you take x (0 ≀ x ≀ a) coins of value n and y (0 ≀ y ≀ b) coins of value 1, then the total value of taken coins will be S. You have to answer q independent test cases. Input The...
3
t=int(input()) for i in range(t): q=input().split() a=int(q[0]) b=int(q[1]) n=int(q[2]) s=int(q[3]) div=s//n rem=s%n if a>=div: if (n*div+b)>=s and b>=rem: print('YES') else: print('NO') else: if (n*a+b)>=s and b>=rem: print...
Given an array A1, A2, ..., AN, count the number of subarrays of array A which are non-decreasing. A subarray A[i, j], where 1 ≀ i ≀ j ≀ N is a sequence of integers Ai, Ai+1, ..., Aj. A subarray A[i, j] is non-decreasing if Ai ≀ Ai+1 ≀ Ai+2 ≀ ... ≀ Aj. You have to count the total number of such subarrays. Input The fi...
1
test = input() for t in range(test): n = input() c = 1 k = 1 arr = map(int, raw_input().split()) for i in xrange(n-1): if(arr[i+1]>=arr[i]): k += 1 else: k = 1 c += k print c
Fox Ciel starts to learn programming. The first task is drawing a fox! However, that turns out to be too hard for a beginner, so she decides to draw a snake instead. A snake is a pattern on a n by m table. Denote c-th cell of r-th row as (r, c). The tail of the snake is located at (1, 1), then it's body extends to (1,...
3
n,m=map(int,input().split(' ')) for i in range(0,n): if(i%2): if(i%4==1): for i in range(0,m-1): print(".",end=('')) print("#") else: print("#",end=('')) for i in range(0,m-1): print(".",end=('')) print() ...
The city park of IT City contains n east to west paths and n north to south paths. Each east to west path crosses each north to south path, so there are n2 intersections. The city funded purchase of five benches. To make it seems that there are many benches it was decided to place them on as many paths as possible. Ob...
1
x=long(input()) ans=x*(x-1)*(x-2)*(x-3)*(x-4) ans=ans*ans//120 print ans
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network. Bu...
3
print("CHAT WITH HER!" if len(set(list(input())))%2==0 else "IGNORE HIM!")
For a positive integer n let's define a function f: f(n) = - 1 + 2 - 3 + .. + ( - 1)nn Your task is to calculate f(n) for a given integer n. Input The single line contains the positive integer n (1 ≀ n ≀ 1015). Output Print f(n) in a single line. Examples Input 4 Output 2 Input 5 Output -3 Note f(4)...
3
def read_int(): return int(input()) def solve(): n = read_int() return n // 2 if n & 1 == 0 else (n - 1) // 2 - n if __name__ == "__main__": print(solve())
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
from collections import deque def solution(arr, n) -> None: d = deque(maxlen=n) for v in arr: if v not in d: d.appendleft(v) print("{}\n{}".format(len(d), " ".join(str(i) for i in d))) def main(): p, q = map(int, input().split()) arr = map(int, input().split()) solution(...
We have a point A with coordinate x = n on OX-axis. We'd like to find an integer point B (also on OX-axis), such that the absolute difference between the distance from O to B and the distance from A to B is equal to k. <image> The description of the first test case. Since sometimes it's impossible to find such point ...
3
from sys import stdin input = lambda : stdin.readline().strip() for _ in range(int(input())): n,k = map(int,input().split()) ans = 0 if(k>=n): ans = k-n elif(n+k)%2!=0: ans = 1 else: ans = 0 print(ans)
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word. Note, that during capitalization all the letters except the first one remains unchanged. Input A single line contains a non-empty word. This word consists of lowercase and uppercase English letters....
3
import sys import math import re import io def main(): s = input() print(s[0].upper() + s[1:]) if __name__ == "__main__": main()
Consider a conveyor belt represented using a grid consisting of n rows and m columns. The cell in the i-th row from the top and the j-th column from the left is labelled (i,j). Every cell, except (n,m), has a direction R (Right) or D (Down) assigned to it. If the cell (i,j) is assigned direction R, any luggage kept o...
3
for i in range(int(input())): n,m = map(int,input().split()) arr = [] for i in range(n): arr.append(list(input())) col = [x[-1] for x in arr] row = arr[-1] ans = 0 for x in col: if x != "D": ans += 1 for x in row: if x != "R": ans += 1 ...
Kana was just an ordinary high school girl before a talent scout discovered her. Then, she became an idol. But different from the stereotype, she is also a gameholic. One day Kana gets interested in a new adventure game called Dragon Quest. In this game, her quest is to beat a dragon. <image> The dragon has a hit p...
3
from math import floor t=int(input()) for _ in range(t): h,n,m=map(int,input().split()) for i in range(n): if(h>20): h=floor(h/2)+10 else: break for i in range(m): h-=10 if(h<=0): print("yes") else: print("no") ...
We have a board with a 2 \times N grid. Snuke covered the board with N dominoes without overlaps. Here, a domino can cover a 1 \times 2 or 2 \times 1 square. Then, Snuke decided to paint these dominoes using three colors: red, cyan and green. Two dominoes that are adjacent by side should be painted by different colors...
3
#dekimasen-deshita- n = int(input()) s = [input(), input()] mod = 10**9+7 i = 0 ans = 3 pre = 0 while i < n: if s[0][i] == s[1][i]: typ = 1 i += 1 else: typ = 2 i += 2 if pre == 0 and typ == 2: ans *= 2 elif pre == 1: ans = (ans*2)%mod elif pre == 2 a...
The statement of this problem is the same as the statement of problem C1. 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 t = int(input()) for _ in range(t): n = int(input()) print(1/(2*math.sin(math.radians(90/(2*n)))))
Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k. In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10k. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result ...
3
import math, sys def main(): s = input().split() k = int(s[1]) n = s[0] l = len(n) ans=0 for i in range(l): if (i-ans == k): print(ans) sys.exit(0) if n[l-i-1]!='0': ans+=1 if (l-ans>0): print(l-1) if __name__=="__main__": main()
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves. We know that several boy&girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair m...
3
count = 0 n = input() h = input() h = h.split(" ") h2 = list() for i in h: h2.append(int(i)) h2.sort() m = input() w = input() w = w.split(" ") w2 = list() for i in w: w2.append(int(i)) w2.sort() while (len(w2) > 0 and len(h2) > 0): if w2[-1] > h2[-1] + 1: w2.pop() continue elif h2[-1] >...