problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
Ilya lives in a beautiful city of Chordalsk. There are n houses on the street Ilya lives, they are numerated from 1 to n from left to right; the distance between every two neighboring houses is equal to 1 unit. The neighboring houses are 1 and 2, 2 and 3, ..., n-1 and n. The houses n and 1 are not neighboring. The ho...
3
n = int(input()) c = [int(i)for i in input().split()] max1 = 0 max2 = 0 for i in range(n): if not(c[i]==c[0]): max1 = i for i in range(n-1, -1, -1): if not(c[i]==c[n-1]): max2 = n - i-1 print(max(max1, max2))
Recently Vasya decided to improve his pistol shooting skills. Today his coach offered him the following exercise. He placed n cans in a row on a table. Cans are numbered from left to right from 1 to n. Vasya has to knock down each can exactly once to finish the exercise. He is allowed to choose the order in which he wi...
3
n=int(input()) a=list(map(int,input().split())) b=sorted(a) c=[0]*n b.reverse() x=0 sum=0 count=0 for i in b: sum=sum+(i*x)+1 x=x+1 print(sum) for i in b: if count==0: count=a.count(i) for j in range(0,n): if a[j]==i: c=1+j print(c,end=' ') cou...
You are given an array a consisting of n integers. In one move, you can choose two indices 1 ≤ i, j ≤ n such that i ≠ j and set a_i := a_j. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. yo...
3
t=int(input()) for i in range(t): o=0 e=0 n=int(input()) x=list(map(int,input().split())) for k in range(0,n): if(x[k]%2==0): e=e+1 else: o=o+1 if(o==n and x[0]%2!=0): if(o%2==0): print("NO") else: print...
There is a special offer in Vasya's favourite supermarket: if the customer buys a chocolate bars, he or she may take b additional bars for free. This special offer can be used any number of times. Vasya currently has s roubles, and he wants to get as many chocolate bars for free. Each chocolate bar costs c roubles. He...
3
t = int(input()) for each_t in range(t): s, a, b, c = input().split() s, a, b, c = int(s), int(a), int(b), int(c) number_of_chocolates = s // c result = (number_of_chocolates // a) * b + number_of_chocolates print(result)
The Little Girl loves problems on games very much. Here's one of them. Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules: * The players move in turns; In one move the player can remove an arbitrary letter from string s. * If the pl...
1
entrada = raw_input() alfabeto = [0]*26 for i in range(len(entrada)): alfabeto[ord(entrada[i]) - ord('a')] += 1 contador = 0 for j in range(26): if alfabeto[j] % 2 == 1: contador += 1 if contador == 0 or contador % 2 == 1: print 'First' else: print 'Second'
Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone. In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules o...
3
a = [0] + list(map(int, input().split())) s = input() sol = 0 for i in range(0, len(s)): sol += a[int(ord(s[i]) - ord('0'))] print(sol)
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
if __name__ == "__main__": n = int(input()) r = 1 s = input() for i in range(n - 1): new = input() if new[0] == s[1]: r += 1 s = new print(r)
We just discovered a new data structure in our research group: a suffix three! It's very useful for natural language processing. Given three languages and three suffixes, a suffix three can determine which language a sentence is written in. It's super simple, 100% accurate, and doesn't involve advanced machine learni...
3
t = int(input()) output = [] for _ in range(t): x = input() if x[-2:] == 'po': output.append('FILIPINO') elif x[-4:] == 'desu' or x[-4:] == 'masu': output.append("JAPANESE") elif x[-5:] == 'mnida': output.append('KOREAN') for x in output: print(x)
There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0, y0). In one shot it can can ...
3
""" B. Han Solo and Lazer Gun """ import sys class Point: def __init__(self, x, y): self.x = float(x) self.y = float(y) n, gun_x, gun_y = map(int, sys.stdin.readline().split(" ")) gun_x = float(gun_x) gun_y = float(gun_y) points = [] for x in range(n): points.append(Point(*map(int, sys.stdin.r...
Tokitsukaze is one of the characters in the game "Kantai Collection". In this game, every character has a common attribute — health points, shortened to HP. In general, different values of HP are grouped into 4 categories: * Category A if HP is in the form of (4 n + 1), that is, when divided by 4, the remainder is ...
3
x = int(input()) if x % 4 == 1: print(0, 'A') exit() if x % 4 == 3: print(2, 'A') exit() if x % 4 == 0: print(1,'A') exit() if x % 4 == 2: print(1, 'B')
As technologies develop, manufacturers are making the process of unlocking a phone as user-friendly as possible. To unlock its new phone, Arkady's pet dog Mu-mu has to bark the password once. The phone represents a password as a string of two lowercase English letters. Mu-mu's enemy Kashtanka wants to unlock Mu-mu's p...
3
password = input() n = int(input()) words = [] ans = False for i in range(n): word = input() words.append(word) if word == password: ans = True if ans: print("YES") else: for a in words: first = a[1] for b in words: second = b[0] if first + second == password: ans = True break if ans:...
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...
3
n = int(input()) x = [] y = [] z = [] for l in range(n): for a,b in zip([x,y,z], list(map(int, input().split(" ")))): a.append(b) net = sum([abs(sum(q)) for q in [x,y,z]]) print("YES" if net == 0 else "NO")
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
n = int(input()) x = input() counter = 0 for i in range(n-1): if x[i] == x[i + 1]: counter += 1 print(counter)
Petr wants to make a calendar for current month. For this purpose he draws a table in which columns correspond to weeks (a week is seven consequent days from Monday to Sunday), rows correspond to weekdays, and cells contain dates. For example, a calendar for January 2017 should look like on the picture: <image> Petr ...
3
import math m, d = list(map(int, input().split())) mon = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] print(math.ceil((mon[m - 1] - (7 - d + 1)) / 7) + 1)
Berland shop sells n kinds of juices. Each juice has its price c_i. Each juice includes some set of vitamins in it. There are three types of vitamins: vitamin "A", vitamin "B" and vitamin "C". Each juice can contain one, two or all three types of vitamins in it. Petya knows that he needs all three types of vitamins to...
3
# your code goes here A = [] B = [] C = [] AB = [] BC = [] AC = [] ABC = [] n = int(input()) for __ in range(n): j, c = input().split() j = int(j) c = ''.join(sorted(list(c))) if c == 'A': A.append(j) elif c == 'B': B.append(j) elif c == 'C': C.append(j) elif c == 'AB': AB.append(j) elif c == 'BC': ...
Leha somehow found an array consisting of n integers. Looking at it, he came up with a task. Two players play the game on the array. Players move one by one. The first player can choose for his move a subsegment of non-zero length with an odd sum of numbers and remove it from the array, after that the remaining parts a...
3
n,flag=int(input()),0 a=[int(i) for i in input().split()] for i in a: if(i%2!=0): flag=1 break if(flag==1): print('First') else: print('Second')
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr...
3
a = str(input()) b = str(input()) if a.lower() == b.lower(): print(0) elif a.lower() < b.lower(): print(-1) else: print(1)
"IT can do almost everything using codes", a Arjun(a CS Student) says to his mathematics' teacher. Mathematics teacher gives a very simple problem to solve using codes but Arjun got stuck. The problem was find out all those pairs of two numbers whose multiplication is divisible by their sum, i.e. You are given a numb...
1
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' #print 'Hello World!' t=input() while t>0: t-=1 n=input() c=0 for i in range(1,n+1): for j in range(i+1,n+1): if (i*j)%(i+j)==0: c+=1 #print i,j print c
Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it. Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and...
3
n = int(input()) l = input().split() g = [0]*100000 for i in l: g[int(i)-1] += 1 ''' p = [] a = [] for i in range(100000): b = g[i] if b!=0: a.append((i+1)*b) else: if a != []: p.append(a) a = [] def f(v): if v==[]: return 0 elif len(v)==1: ...
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them. A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the t...
3
import sys, math readline = sys.stdin.readline s = readline().split()[0] def z_Func(s): n = len(s) l,r = 0,0 z = [0 for _ in range(n)] for i in range(1,n): if i <= r: z[i] = min(r - i + 1,z[i - l]) while i + z[i] < n and s[z[i]] == s[i + z[i]]: z[i] += 1 i...
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it: * deletes all the vowels, * inserts a character "." before each consonant, * repl...
3
vowels = "aeiouy" st = input() st = st.lower() for i in vowels: st = st.replace(i,"") res = "" for i in st: res += "." + i print(res)
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
numberofvectors = int(raw_input()) vectors = [] sum1=0 sum2=0 sum3=0 for x in range(numberofvectors): vectors.extend([[int(x) for x in raw_input().split()]]) for x in range(numberofvectors): sum1 = sum1 + vectors[x][0] sum2 = sum2 + vectors[x][1] sum3 = sum3 + vectors[x][2] if sum1==0 and sum2==0 and...
Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers a, b, c on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting e...
3
a = int(input()) b = int(input()) c = int(input()) S1 = a+b+c S2 = a+b*c S3 = a*b+c S4 = a*b*c S5 = (a+b)*c S6 = a*(b+c) P = max(S1, S2, S3, S4, S5, S6) print(P)
Berland scientists face a very important task - given the parts of short DNA fragments, restore the dinosaur DNA! The genome of a berland dinosaur has noting in common with the genome that we've used to: it can have 26 distinct nucleotide types, a nucleotide of each type can occur at most once. If we assign distinct En...
1
n = input() a = [raw_input() for _ in xrange(n)] for i in xrange(n): if a[i] == '': continue for j in xrange(n): if i == j or a[j] == '': continue if a[i][0] in a[j]: t = a[j].index(a[i][0]) if len(a[i]) > len(a[j]) - t: a[j] = a[j][:t...
Gleb ordered pizza home. When the courier delivered the pizza, he was very upset, because several pieces of sausage lay on the crust, and he does not really like the crust. The pizza is a circle of radius r and center at the origin. Pizza consists of the main part — circle of radius r - d with center at the origin, an...
3
R, d = map(int, input().split()) n = int(input()) ans = 0 for _ in range(n): x, y, r = map(int, input().split()) dist_d = ((x*x)+(y*y))**0.5 if dist_d >= R-d+r and dist_d+r <= R: ans += 1 print(ans)
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation. The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe...
3
s=input() a=[] for i in s: if(i=='+'): continue else: a.append(i) a.sort() for i in range(1,len(s),2): a.insert(i,'+') t="" t=t.join(a) print(t)
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr...
3
f_string = input().lower() s_string = input().lower() if f_string < s_string: print(-1) elif f_string == s_string: print(0) else: print(1)
For an integer n not less than 0, let us define f(n) as follows: * f(n) = 1 (if n < 2) * f(n) = n f(n-2) (if n \geq 2) Given is an integer N. Find the number of trailing zeros in the decimal notation of f(N). Constraints * 0 \leq N \leq 10^{18} Input Input is given from Standard Input in the following format: ...
3
n = int(input()) ans = 0 x = 10 if n % 2 == 0: while x <= n: ans += n // x x *= 5 print(ans)
Flatland has recently introduced a new type of an eye check for the driver's licence. The check goes like that: there is a plane with mannequins standing on it. You should tell the value of the minimum angle with the vertex at the origin of coordinates and with all mannequins standing inside or on the boarder of this a...
1
import math N = int(raw_input()) points = [map(int, raw_input().split()) for n in range(N)] angles = sorted(map(lambda x: math.degrees(math.atan2(x[0], x[1])), points)) pairs = [(angles[i], angles[(i+1) % N]) for i in range(N)] diffs = map(lambda x: (720 + x[1] - x[0]) % 360, pairs) print (360 - max(diffs)) % 360
Your friend has n cards. You know that each card has a lowercase English letter on one side and a digit on the other. Currently, your friend has laid out the cards on a table so only one side of each card is visible. You would like to know if the following statement is true for cards that your friend owns: "If a car...
3
a=input() b=['a','e','i','o','u','1','3','5','7','9'] ans=0 for i in a: if i in b: ans+=1 print(ans)
Polycarp wants to train before another programming competition. During the first day of his training he should solve exactly 1 problem, during the second day — exactly 2 problems, during the third day — exactly 3 problems, and so on. During the k-th day he should solve k problems. Polycarp has a list of n contests, th...
3
#codeforces1165B_live gi = lambda : list(map(int,input().strip().split())) n, = gi() l = gi() l.sort() ans = 0 day = 1 for e in l: if e >= day: ans += 1 day += 1 print(ans)
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1. Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divi...
3
n = int(input()) print(n // 2) if(n % 2 == 0): for i in range(n // 2) : print(str(2),end=" ") else: for i in range((n // 2) - 1) : print(str(2),end=" ") print(str(3),end="")
We've got no test cases. A big olympiad is coming up. But the problemsetters' number one priority should be adding another problem to the round. The diameter of a multiset of points on the line is the largest distance between two points from this set. For example, the diameter of the multiset {1, 3, 2, 1} is 2. Diame...
3
n,d=map(int,input().split()) s=list(map(int,input().split())) s.sort() sol=-1 for i in range(n): for j in range(i,n): if(s[j]-s[i]<=d): if(j-i)>sol: sol=j-i print(n-sol-1)
Iroha is very particular about numbers. There are K digits that she dislikes: D_1, D_2, ..., D_K. She is shopping, and now paying at the cashier. Her total is N yen (the currency of Japan), thus she has to hand at least N yen to the cashier (and possibly receive the change). However, as mentioned before, she is very ...
3
n,k=map(int,input().split()) D=list(map(int,input().split())) for i in range(n,88889): for j in str(i): if int(j) in D: break else: print(i) exit()
This is the easy version of the problem. The difference between the versions is that in the easy version all prices a_i are different. You can make hacks if and only if you solved both versions of the problem. Today is Sage's birthday, and she will go shopping to buy ice spheres. All n ice spheres are placed in a row ...
3
#872#sily n=int(input()) a=[int(x)for x in input().split()] a.sort() print((n+1)//2-1) for i in range(n): if(i%2==0): print(a[n//2+i//2],end=" ") else: print(a[i//2],end=" ")
A permutation of length n is a sequence of integers from 1 to n of length n containing each number exactly once. For example, [1], [4, 3, 5, 1, 2], [3, 2, 1] are permutations, and [1, 1], [0, 1], [2, 2, 1, 4] are not. There was a permutation p[1 ... n]. It was merged with itself. In other words, let's take two instanc...
3
for _ in range(int(input())): n=int(input()) l=list(map(int,input().split())) val=l[0] j=1 d={val:True} for i in range(1,2*n): if d.get(l[i],None) is None: l[j]=l[i] j+=1 d[l[i]]=True print(' '.join(map(str,l[:n])))
<image> Input The input contains two integers a1, a2 (0 ≤ ai ≤ 32), separated by a single space. Output Output a single integer. Examples Input 1 1 Output 0 Input 3 7 Output 0 Input 13 10 Output 1
3
x,y=input().split() x=int(x) y=int(y[::-1]) print(x+y)
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given n numbers finds one that is di...
3
from sys import stdin def main(): n = int(stdin.readline().strip()) l, c = [0, 0], [0, 0] for i, x in enumerate(map(int, stdin.readline().strip().split())): x &= 1 l[x] = i c[x] += 1 return l[c[0] > c[1]] + 1 print(main())
Consider the infinite sequence of integers: 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5.... The sequence is built in the following way: at first the number 1 is written out, then the numbers from 1 to 2, then the numbers from 1 to 3, then the numbers from 1 to 4 and so on. Note that the sequence contains numbers, not d...
3
import sys import bisect from bisect import bisect_left as lb input_=lambda: sys.stdin.readline().strip("\r\n") from math import log from math import gcd from math import atan2,acos from random import randint sa=lambda :input_() sb=lambda:int(input_()) sc=lambda:input_().split() sd=lambda:list(map(int,input_().split())...
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s. You have to answer t independent test cases. Input The first line of the input co...
3
for _ in range(int(input())): n,s=[int(x) for x in input().split()] a=[int(x) for x in str(n)] if sum(a)<=s: print(0) else: acum=0 j=0 encontrado=-1 for i in range(len(a)-1,-1,-1): if sum(a[0:i+1])+1<=s: encontrado=i bre...
Lee was cleaning his house for the party when he found a messy string under the carpets. Now he'd like to make it clean accurately and in a stylish way... The string s he found is a binary string of length n (i. e. string consists only of 0-s and 1-s). In one move he can choose two consecutive characters s_i and s_{i...
3
#!/usr/bin/env python3 import io import os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline def get_str(): return input().decode().strip() def rint(): return map(int, input().split()) def oint(): return int(input()) t = oint() for _ in range(t): n = oint() s = get_str() ans = ''...
In the year 2168, AtCoder Inc., which is much larger than now, is starting a limited express train service called AtCoder Express. In the plan developed by the president Takahashi, the trains will run as follows: * A train will run for (t_1 + t_2 + t_3 + ... + t_N) seconds. * In the first t_1 seconds, a train must ru...
3
import sys sys.setrecursionlimit(10000000) MOD = 10 ** 9 + 7 INF = 10 ** 15 N = int(input()) T = list(map(int,input().split())) V = list(map(int,input().split())) def calc_area(v1,v2,t,lim): if v1 > v2: v1,v2 = v2,v1 if v2 == lim: if lim - v1 < t: return t*lim - (lim - v1)*(lim - v...
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
n, k = input().split() n, k = int(n), int(k) ID = [int(i) for i in input().split()] from collections import deque from itertools import islice d = deque([], maxlen=k) for i in ID: if i in islice(d, 0, k): pass else: d.appendleft(i) print(len(d)) for i in islice(d, 0, k): print(i, end=' ')
The goal of the matrix-chain multiplication problem is to find the most efficient way to multiply given $n$ matrices $M_1, M_2, M_3,...,M_n$. Write a program which reads dimensions of $M_i$, and finds the minimum number of scalar multiplications to compute the maxrix-chain multiplication $M_1M_2...M_n$. Constraints ...
3
# -*- coding: utf-8 -*- n = int(input()) p = [] m = dict() for _ in range(n): r, c = map(int, input().split()) p.append(r) if _ == n-1: p.append(c) for i in range(n+1): m[(i,i)] = 0 for l in range(2, n + 1): for i in range(1, n - l + 2): j = i + l - 1 m[(i, j)] = float('in...
It's a walking tour day in SIS.Winter, so t groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another. Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P": * "A" corresponds to an angry...
3
for t in range(int(input())): k = int(input()) s = input().strip() try: i = s.index('A') except: print(0) continue s = s[i:] l = 0 count = 0 for c in s: if c == 'A': count = 0 continue else: count += 1 ...
Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are n drinks in his fridge, the volume fraction of orange juice in the i-th drink equals pi percent. One day Vasya decided to make himself an orange cocktail. He took equal proportions of ea...
3
n = int(input()) p = sum(list(map(int, input().split()))) print(p/n)
You're given an array a_1, …, a_n of n non-negative integers. Let's call it sharpened if and only if there exists an integer 1 ≤ k ≤ n such that a_1 < a_2 < … < a_k and a_k > a_{k+1} > … > a_n. In particular, any strictly increasing or strictly decreasing array is sharpened. For example: * The arrays [4], [0, 1], [...
3
for _ in range(int(input())): n = int(input()) arr = list(map(int, input().split())) pref_poss = n suf_poss = 0 for i in range(n): if arr[i] >= i: pref_poss = i else: break for i in range(n - 1, -1, -1): if arr[i] >= n - 1 - i: suf_poss...
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc....
3
def rev(word): if len(word)==1: return word if len(word)==2: return word[-1]+word[0] return word[-1]+rev(word[1:len(word)-1])+word[0] word1=input() word2=input() if rev(word1)==word2: print("YES") else: print("NO")
Hands that shed innocent blood! There are n guilty people in a line, the i-th of them holds a claw with length Li. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the i-th person kills the j-th person if and only if j < i and j ≥ i - Li. You are g...
3
n = int(input()) l= list(map(int,input().split())) count = 0 mi =n-1 -l[n-1] for i in range(n-1): if n-i-2 >= mi: count+=1 mi = min(mi, n-i -2 -l[n-i -2]) #print(l) print(n -count)
There are N squares arranged in a row from left to right. The height of the i-th square from the left is H_i. You will land on a square of your choice, then repeat moving to the adjacent square on the right as long as the height of the next square is not greater than that of the current square. Find the maximum numb...
3
n=int(input()) a=list(map(int,input().split())) i=0 p=q=0 for i in range(n-1): if a[i]>=a[i+1]: p+=1 else: q=max(p,q) p=0 q=max(p,q) print(q)
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...
3
amt_coords = int(input()) x_pressure = 0 y_pressure = 0 z_pressure = 0 for i in range(amt_coords): x, y, z = [int(x) for x in input().split(" ")] x_pressure += x y_pressure += y z_pressure += z if x_pressure == 0 and y_pressure == 0 and z_pressure == 0: print("YES") else: print("NO")
You are given an array a of length n. You are also given a set of distinct positions p_1, p_2, ..., p_m, where 1 ≤ p_i < n. The position p_i means that you can swap elements a[p_i] and a[p_i + 1]. You can apply this operation any number of times for each of the given positions. Your task is to determine if it is poss...
3
t = int(input()) while t != 0: n_m = [int(i) for i in input().split()] a = [int(i) for i in input().split()] p = [int(i) for i in input().split()] for i in range(n_m[0]): for i in range(n_m[1]): if a[p[i] - 1] > a[p[i]]: a[p[i] - 1], a[p[i]] = a[p[i]], a[p[i] - 1] ...
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≤ i ≤ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is it...
3
n = int(input()) lst = list(map(int, input().strip().split()))[:n] max_len = 0 length = 1 for i in range(1, len(lst)): if lst[i] >= lst[i - 1]: length = length + 1 else: if max_len < length: max_len = length length = 1 if max_len < length: max_len = length if max_len =...
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
n=str(input()) k=0 if len(n)<7: print("NO") else: for i in range(len(n)): m=n[i:i+7] if m.count('1')==7 or m.count('0')==7: k=k+1 break if k==1: print("YES") else: print("NO")
You are given a permutation p=[p_1, p_2, …, p_n] of integers from 1 to n. Let's call the number m (1 ≤ m ≤ n) beautiful, if there exists two indices l, r (1 ≤ l ≤ r ≤ n), such that the numbers [p_l, p_{l+1}, …, p_r] is a permutation of numbers 1, 2, …, m. For example, let p = [4, 5, 1, 3, 2, 6]. In this case, the numb...
3
from __future__ import division, print_function from io import BytesIO, IOBase import os,sys,math,heapq,copy from collections import defaultdict,deque from bisect import bisect_left,bisect_right from functools import cmp_to_key from itertools import permutations,combinations,combinations_with_replacement # <fastio> if ...
There is a hotel with the following accommodation fee: * X yen (the currency of Japan) per night, for the first K nights * Y yen per night, for the (K+1)-th and subsequent nights Tak is staying at this hotel for N consecutive nights. Find his total accommodation fee. Constraints * 1 \leq N, K \leq 10000 * 1 \leq ...
3
n=int(input()) k=int(input()) x=int(input()) y=int(input()) print( x*min(n,k)+y*max(0,n-k) )
N contestants participated in a competition. The total of N-1 matches were played in a knockout tournament. For some reasons, the tournament may not be "fair" for all the contestants. That is, the number of the matches that must be played in order to win the championship may be different for each contestant. The struct...
3
''' 自宅用PCでの解答 ''' import math #import numpy as np import itertools import queue import bisect from collections import deque,defaultdict import heapq as hpq from sys import stdin,setrecursionlimit #from scipy.sparse.csgraph import dijkstra #from scipy.sparse import csr_matrix ipt = stdin.readline setrecursionlimit(10**7...
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 ...
1
#!/usr/bin/env python import sys, math line = sys.stdin.readline().strip() n = int(line) line = sys.stdin.readline().strip() capacity = 0 max_capacity = 0 while line != "": parts = line.split(" ") a = int(parts[0]) b = int(parts[1]) capacity -= a capacity += b if capacity >...
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
t = int(input()) for i in range(t): n = int(input()) l = sorted([int(i) for i in input().split()]) last = abs(l[0]-l[1]) for i in range(n-1): a = abs(l[i] - l[i+1]) if last >= a: last = a print(last)
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
from sys import exit n = int(input()) strings = [input() for _ in range(n)] strings = sorted(strings, key=len) for i in range(len(strings) - 1): if strings[i] not in strings[i + 1]: print('NO') exit() print('YES') for string in strings: print(string)
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem. Pete and Bi...
3
#!/usr/bin/env python # -*- coding: utf-8 -*- n=int(input()) if n!=2 and n % 2==0: print('YES') else: print('NO')
Lenny is playing a game on a 3 × 3 grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be swit...
3
a = list() for _ in range(3): x, y, z = map(int, input().split()) a.append(x) a.append(y) a.append(z) for i in range(9): if i%3==0 and i!=0: print("") if i==0: print("1" if (a[i]+a[i+1]+a[i+3])%2==0 else "0", end = '') if i==1: print("1" if (a[i]+a[i+1]+a[i+3]+a[i-1])%2==0 else "0", end = '') if i==2: p...
One day Vitaly was going home late at night and wondering: how many people aren't sleeping at that moment? To estimate, Vitaly decided to look which windows are lit in the house he was passing by at that moment. Vitaly sees a building of n floors and 2·m windows on each floor. On each floor there are m flats numbered ...
3
listm=list(map(int,input().split())) n,m=(listm[0],listm[1]) count=0 for i in range(n): l=list(map(int,input().split())) for i in range(0,2*m,2): if i%2==0: k=l[i:i+2] if k[0]==1 or k[1]==1 : count+=1 print(count)
Takahashi is organizing a party. At the party, each guest will receive one or more snack pieces. Takahashi predicts that the number of guests at this party will be A or B. Find the minimum number of pieces that can be evenly distributed to the guests in both of the cases predicted. We assume that a piece cannot be ...
3
import fractions a,b=map(int,input().split()) i=fractions.gcd(a,b) print(int(a*b/i))
Vector Willman and Array Bolt are the two most famous athletes of Byteforces. They are going to compete in a race with a distance of L meters today. <image> Willman and Bolt have exactly the same speed, so when they compete the result is always a tie. That is a problem for the organizers because they want a winner. ...
1
#jkm #Moovon's Solution t,w,b=map(int,raw_input().split()) #inputs #gcd formula def gcd(a,b): if b==0: return a else: return gcd(b,a%b) lc=gcd(w,b) temp=(w*b)/lc temp2=min(w,b) amla=(t/temp)*temp2 monk=amla+min(temp2-1,(t%temp)) divi=gcd(monk,t) #reducing to irreducible fraction print "%d/%d" %(...
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
numlines = int(input().strip()) words = [] maxChars = 10 for i in range(numlines): words.append(input()) for word in words: wlength = len(word) if wlength > maxChars: print(''.join([word[0],str(wlength-2),word[wlength-1]])) else: print(word)
Let's say string s has period k if s_i = s_{i + k} for all i from 1 to |s| - k (|s| means length of string s) and k is the minimum positive integer with this property. Some examples of a period: for s="0101" the period is k=2, for s="0000" the period is k=1, for s="010" the period is k=2, for s="0011" the period is k=...
3
t=int(input()) for i in range(t): newstring="" x=set() k=input() b=len(k) for j in k: x.add(j) for i in x: newstring=newstring+i print(newstring*b)
A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs. Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages ...
3
def main(): read = lambda: list(map(int, input().split())) n = read()[0] l = read() ans = 0 lv = 0 t = 0 was = [-1] * 300000 for v in l: #print(was[v], v) t += 1 if was[v] != -1: was[t] = was[v] was[v] = -1 else: ans += ...
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 can_do_one_more(p, f, ns, nw, s, w): #print(ns, nw) for fw in range(nw + 1): if fw * w > f: continue fs = (f - fw * w) // s ps = ns - fs pw = nw - fw if ps < 0 or pw < 0 or fs < 0 or fw < 0: continue if ps * s + pw * w <= p and fs * s +...
There are N participants in the CODE FESTIVAL 2016 Qualification contests. The participants are either students in Japan, students from overseas, or neither of these. Only Japanese students or overseas students can pass the Qualification contests. The students pass when they satisfy the conditions listed below, from t...
3
p = 0 f = 0 n, a, b = map(int, input().split()) for i in input(): if i == "a" and p < a+b: p += 1 print("Yes") elif i == "b" and p < a+b and f < b: p += 1 f += 1 print("Yes") else: print("No")
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 math import factorial if __name__ == '__main__': n = (int)(input()) print(factorial(n))
You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the integers from 1 through N. You would like to sort this sequence in ascending order by repeating the following operation: * Choose an element in the sequence and move it to the beginning or the end of the sequence. Find the minimum number of op...
3
N = int(input()) P = [int(input()) for _ in range(N)] V = [-1] * (N+1) for i in range(N): V[P[i]] = i+1 # print(V) c = 0 ans = 0 for i in range(1, N+1): if V[i-1] > V[i]: c = 1 else: c += 1 ans = max(c, ans) print(N-ans)
It is September 9 in Japan now. You are given a two-digit integer N. Answer the question: Is 9 contained in the decimal notation of N? Constraints * 10≤N≤99 Input Input is given from Standard Input in the following format: N Output If 9 is contained in the decimal notation of N, print `Yes`; if not, print `No...
3
n = input() print('Yes' if ('9' in n) else 'No')
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
from sys import stdin, stdout import math,sys from itertools import permutations, combinations from collections import defaultdict,deque,OrderedDict import bisect as bi import heapq ''' #------------------PYPY FAst I/o--------------------------------# def I():return (int(stdin.readline())) def In():return(map(int,s...
You helped Dima to have a great weekend, but it's time to work. Naturally, Dima, as all other men who have girlfriends, does everything wrong. Inna and Dima are now in one room. Inna tells Dima off for everything he does in her presence. After Inna tells him off for something, she goes to another room, walks there in ...
1
#!/usr/bin/env python from sys import stdin as cin def main(): n,k = map(int, next(cin).split()) a = map(int, next(cin).split()) a = [ a[i*k:(i+1)*k] for i in range(n//k) ] a = map(sum, zip(*a)) return 1 + min(enumerate(a), key=lambda x: x[1])[0] print main()
Polycarp is a great fan of television. He wrote down all the TV programs he is interested in for today. His list contains n shows, i-th of them starts at moment li and ends at moment ri. Polycarp owns two TVs. He can watch two different shows simultaneously with two TVs but he can only watch one show at any given mom...
1
from sys import stdin from collections import defaultdict mem = defaultdict(int) for _ in range(int(input())): l, r = map(int, stdin.readline().split()) mem[l] += 1 mem[r + 1] -= 1 lst = 0 for i in sorted(mem.keys()): mem[i] += lst lst = mem[i] print('YES' if max(mem.values()) < 3 else 'NO')
There is a house with n flats situated on the main street of Berlatov. Vova is watching this house every night. The house can be represented as an array of n integer numbers a_1, a_2, ..., a_n, where a_i = 1 if in the i-th flat the light is on and a_i = 0 otherwise. Vova thinks that people in the i-th flats are distur...
3
n = int(input()) A = list(map(int, input().split())) ans = 0 check = [] for a in A: check.append(a) if check == [1, 0, 1, 0, 1]: ans += 1 check = [1] elif check == [1, 0, 1, 0, 0]: ans += 1 check = [] elif check == [1, 0, 1, 1]: ans += 1 check = [1] ...
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
tc = int(input()) while(tc > 0): a = input() print(a) tc-=1
The Cartesian coordinate system is set in the sky. There you can see n stars, the i-th has coordinates (xi, yi), a maximum brightness c, equal for all stars, and an initial brightness si (0 ≤ si ≤ c). Over time the stars twinkle. At moment 0 the i-th star has brightness si. Let at moment t some star has brightness x. ...
3
import sys input=sys.stdin.buffer.readline n,q,bright=map(int,input().split()) dp=[[[0 for j in range(11)] for i in range(100+3)] for k in range(100+3)] for i in range(n): a,b,c=map(int,input().split()) dp[a][b][c]+=1 for i in range(1,101): for j in range(1,101): for k in range(11): dp...
You have n students under your control and you have to compose exactly two teams consisting of some subset of your students. Each student had his own skill, the i-th student skill is denoted by an integer a_i (different students can have the same skills). So, about the teams. Firstly, these two teams should have the s...
3
from collections import Counter t = int(input()) for _ in range(t): n = int(input()) a = list(dict(Counter(map(int, input().split()))).values()) a.sort(reverse = True) mx = a[0] ln = len(a) if mx > ln: print(ln) elif mx == ln: print(ln-1) else: #mx < ln print(m...
Write a program which computes the digit number of sum of two integers a and b. Constraints * 0 ≤ a, b ≤ 1,000,000 * The number of datasets ≤ 200 Input There are several test cases. Each test case consists of two non-negative integers a and b which are separeted by a space in a line. The input terminates with EOF. ...
3
for line in open(0).readlines(): a, b = map(int, line.split()) c = a+b ans = +(c == 0) while c: ans += 1 c //= 10 print(ans)
n hobbits are planning to spend the night at Frodo's house. Frodo has n beds standing in a row and m pillows (n ≤ m). Each hobbit needs a bed and at least one pillow to sleep, however, everyone wants as many pillows as possible. Of course, it's not always possible to share pillows equally, but any hobbit gets hurt if h...
3
n, m, k = map(int, input().split()) min_delta = min(k - 1, n - k) max_delta = max(k - 1, n - k) top = ((k - 1) * k + (n - k) * (n - k + 1)) // 2 + (max_delta - min_delta) * min_delta + max_delta + 1 def get_level(n, k, level): return 1 + min(level, k - 1) + min(level, n - k) if top <= m: print(max_delta + 1 + (m ...
Zibi is a competitive programming coach. There are n competitors who want to be prepared well. The training contests are quite unusual – there are two people in a team, two problems, and each competitor will code exactly one of them. Of course, people in one team will code different problems. Rules of scoring also are...
1
""" What I cannot create, I do not understand. https://github.com/Cheran-Senthil/PyRival Copyright (c) 2018 Cheran Senthilkumar """ from __future__ import division, print_function import cmath import itertools import math import operator as op import sys from atexit import register from bisect import bisect_left, bis...
There are n rectangles in a row. You can either turn each rectangle by 90 degrees or leave it as it is. If you turn a rectangle, its width will be height, and its height will be width. Notice that you can turn any number of rectangles, you also can turn all or none of them. You can not change the order of the rectangle...
3
n = int(input()) from sys import stdin from sys import exit t = 1000000009 for i in range(n): a,b = map(int,stdin.readline().split()) e,r = min(a,b),max(a,b) if r<=t: t = r else: if e<=t: t = e else: print('NO') exit() print('YES')
Programmer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the expose procedure. Unfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agreed...
1
a=raw_input().split() l=int(a[0]) r=int(a[1]) k=int(a[2]) x=1 while x<l: x=x*k f=0 while x<=r: print x, x=x*k f=1 if f==0: print"-1"
You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum: <image> Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p). Input The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn...
1
n, m = map(int, raw_input().split()) bin = [] m -= 1 for j in xrange(n-1): bin.append(m%2) m /= 2 perm = [1] cur = 0 for j in xrange(2,n+1): if bin[n-j]: perm.insert(cur, j) else: perm.insert(cur+1, j) cur += 1 print ' '.join(map(str, perm))
You are given two integers n and m. You have to construct the array a of length n consisting of non-negative integers (i.e. integers greater than or equal to zero) such that the sum of elements of this array is exactly m and the value ∑_{i=1}^{n-1} |a_i - a_{i+1}| is the maximum possible. Recall that |x| is the absolut...
3
import sys, os.path if(os.path.exists('input.txt')): sys.stdin = open('input.txt',"r") sys.stdout = open('output.txt',"w") sys.setrecursionlimit(10 ** 5) def II(): return int(sys.stdin.readline()) def MI(): return map(int, sys.stdin.readline().split()) def LI(): return list(map(int, sys.stdin.readline().spli...
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≤ i ≤ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is it...
3
num = input() team = input().split() moving = 1 max = 1 for i in range(1,len(team)): if int(team[i-1]) <= int(team[i]): moving += 1 if moving >= max: max = moving else: moving = 1 print(max)
Iahub isn't well prepared on geometry problems, but he heard that this year there will be a lot of geometry problems on the IOI selection camp. Scared, Iahub locked himself in the basement and started thinking of new problems of this kind. One of them is the following. Iahub wants to draw n distinct points and m segme...
1
n, m = map(int, raw_input().split()) xs = enumerate(map(int, raw_input().split())) xs = enumerate(sorted(xs, key=lambda (x, y): y)) xs = sorted(xs, key=lambda (z, (x, y)): x) for (z, (x, y)) in xs: print z % 2,
Polycarp is practicing his problem solving skill. He has a list of n problems with difficulties a_1, a_2, ..., a_n, respectively. His plan is to practice for exactly k days. Each day he has to solve at least one problem from his list. Polycarp solves the problems in the order they are given in his list, he cannot skip ...
3
m,n=map(int,input().split()) l=list(map(int,input().split())) cn=list(enumerate(l,0)) cn.sort(key=lambda x:-x[1]) print(sum([cn[i][1] for i in range(n)])) day=[-1]+sorted([cn[i][0] for i in range(n)])+[m] for i in range(1,n): print(day[i]-day[i-1],end=' ') print(m-1-day[n-1])
Recently Anton found a box with digits in his room. There are k2 digits 2, k3 digits 3, k5 digits 5 and k6 digits 6. Anton's favorite integers are 32 and 256. He decided to compose this integers from digits he has. He wants to make the sum of these integers as large as possible. Help him solve this task! Each digit c...
3
k2, k3, k5, k6 = map(int, input().split()) no_256 = min(k2, k5, k6) no_32 = max(0, min(k2-no_256, k3)) print(256*no_256 + 32 * no_32)
Let s be some string consisting of symbols "0" or "1". Let's call a string t a substring of string s, if there exists such number 1 ≤ l ≤ |s| - |t| + 1 that t = s_l s_{l+1} … s_{l + |t| - 1}. Let's call a substring t of string s unique, if there exist only one such l. For example, let s = "1010111". A string t = "010...
3
n, k = map(int, input().split()) # while making the string, k = (n - 2 * length + 2) length = (n - k + 2) // 2 # length of a cycle string = "0" * (length - 1) + "1" # make the cycle answer = string * (n // length + 1) # make the string with length >= n print(answer[ : n])
Luke Skywalker gave Chewbacca an integer number x. Chewbacca isn't good at numbers but he loves inverting digits in them. Inverting digit t means replacing it with digit 9 - t. Help Chewbacca to transform the initial number x to the minimum possible positive number by inverting some (possibly, zero) digits. The decim...
3
x =list((input())) x = [int(i) for i in x] for i in x: if i>4 and len(x)!=1: x[x.index(i)] = 9 - x[x.index(i)] if x[0] == 0: x[0] = 9 x = [str(i) for i in x] print(''.join(x))
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 tc in range(T): n = int(input()) ans = n // 2 if not n % 2: ans -= 1 print(ans)
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
a = input() s = [] t = 0 for i in range(len(a)): s.append(ord(a[i])) for j in range(len(a)-1): if abs(s[j]-s[j+1]) <= 13: t = t + abs(s[j]-s[j+1]) else: t = t + 26 - abs(s[j]-s[j+1]) if abs(ord('a')-s[0]) <= 13: t = t + abs(ord('a')-s[0]) else: t = t + 26 - abs(ord('a')-s[0]) print(...
Takahashi, who lives on the number line, is now at coordinate X. He will make exactly K moves of distance D in the positive or negative direction. More specifically, in one move, he can go from coordinate x to x + D or x - D. He wants to make K moves so that the absolute value of the coordinate of the destination wil...
3
x,k,d = map(int,input().split()) x = abs(x) if k*d <= x: print(x - k*d) exit() n = x//d x = x - (d * n) k -= n k %= 2 x -= d*k x = abs(x) print(x)
Your friend has n cards. You know that each card has a lowercase English letter on one side and a digit on the other. Currently, your friend has laid out the cards on a table so only one side of each card is visible. You would like to know if the following statement is true for cards that your friend owns: "If a car...
1
s = raw_input() v = 'aeiou' c = 0 for i in s: if i in v: c +=1 if i in '0123456789': if int(i) % 2 == 1: c+=1 print(c)
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
def solve(n): start = 3 base = 2 while n%start: base = base*2 start+=base return int(n/start) testCases = int(input()) while testCases: n = int(input()) print(solve(n)) testCases -= 1
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr...
3
def main(): str1=input().lower() str2=input().lower() if(str1==str2): print("0") for i in range(len(str1)): if(ord(str1[i])<ord(str2[i])): print("-1") break elif(ord(str1[i])>ord(str2[i])): print("1") break if __nam...
You have two variables a and b. Consider the following sequence of actions performed with these variables: 1. If a = 0 or b = 0, end the process. Otherwise, go to step 2; 2. If a ≥ 2·b, then set the value of a to a - 2·b, and repeat step 1. Otherwise, go to step 3; 3. If b ≥ 2·a, then set the value of b to b - 2...
3
def great(a,b): if a>=b*2: k=a//(2*b) a=a-k*2*b func(a,b) else: if b>=a*2: s=0 k=b//(2*a) b=b-k*2*a func(a,b) else: print(a,b) def func(a,b): if a==0 or b==0 : print(a,b) else: great(a,b)...