problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
You are given two strings s and t. In a single move, you can choose any of two strings and delete the first (that is, the leftmost) character. After a move, the length of the string decreases by 1. You can't choose a string if it is empty. For example: * by applying a move to the string "where", the result is the s...
3
s = input() t = input() n = len(s) m = len(t) i = n-1 j = m-1 count = 0 while(i>=0 and j>=0 and s[i]==t[j]): count+=1 i-=1 j-=1 print(m+n-count*2)
[The Duck song](https://www.youtube.com/watch?v=MtN1YnoL46Q) For simplicity, we'll assume that there are only three types of grapes: green grapes, purple grapes and black grapes. Andrew, Dmitry and Michal are all grapes' lovers, however their preferences of grapes are different. To make all of them happy, the followi...
3
l1=list(map(int,input().split())) l2=list(map(int,input().split())) x=l1[0];z=l1[1];y=l1[2] a1=l2[0];b1=l2[1];c1=l2[2] g=a1-x;p=b1;yes=0;b=c1 if g>=0: if c1<y: y=y-c1 if g+p>=y+z: yes=1 else: if g+p>=z: yes=1 if yes==1: print("YES") else: print("NO")
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base. Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of 2. Thanos wants to destroy the...
3
def rec(l, r, a, A, B): if len(a) == 0: return A cur = len(a) * B * (r-l+1) if l == r: return cur b = [] c = [] mid = (l+r)//2 for i in a: if i <= mid: b.append(i) else: c.append(i-mid-1) return min(rec(l, mid, b, A, B)+rec(l, mid, ...
Input The input consists of a single string of uppercase letters A-Z. The length of the string is between 1 and 10 characters, inclusive. Output Output "YES" or "NO". Examples Input GENIUS Output YES Input DOCTOR Output NO Input IRENE Output YES Input MARY Output NO Input SMARTP...
3
s = input() import string l = string.ascii_letters[26:] flag = 0 for i in range(len(s)-2): if (l.index(s[i])+l.index(s[i+1]))%26 != l.index(s[i+2]): flag = 1 print("NO") break if flag==0: print("YES")
You are given a sequence a_1, a_2, ..., a_n consisting of n integers. You may perform the following operation on this sequence: choose any element and either increase or decrease it by one. Calculate the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perfor...
3
n,k=map(int,input().strip().split()) a =list(map(int,input().strip().split())) from collections import deque, Counter temp = Counter(a) a = deque(sorted(map(lambda x: [x,temp[x]], temp))) # print(a) while( (k>=a[0][1] or k>=a[-1][1] ) and len(a)>1): # forward cf,f,smf = a[0][1], a[0][0], a[1][0] cr,r,smr = ...
You are playing a variation of game 2048. Initially you have a multiset s of n integers. Every integer in this multiset is a power of two. You may perform any number (possibly, zero) operations with this multiset. During each operation you choose two equal integers from s, remove them from s and insert the number eq...
3
T = int(input()) for i in range(T): n = int(input()) l = list(map(int,input().split())) if 2048 in l: print("YES") else: t = 0 if 1 in l: k = l.count(1) else: k = 0 for i in range(1,11): if 2**i in l: k = l.count(2**i) + k//2 elif t >=0: k = k//2 if k <= 1: t = 0 t = t + k ...
Some country is populated by wizards. They want to organize a demonstration. There are n people living in the city, x of them are the wizards who will surely go to the demonstration. Other city people (n - x people) do not support the wizards and aren't going to go to the demonstration. We know that the city administr...
1
a=raw_input() a=a.split() n=int(a[0]) x=int(a[1]) y=int(a[2]) b=(y*n)/100.0 b=b-x if(b<=0): print "0" else: c=int(b) if((c-b)!=0): c=c+1 print c
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
n=int(input()) for i in range(1,n+1): if n%i==0: s=str(i) pd=True for c in s: if c!='4' and c!='7': pd=False break if pd==True: break if pd==True: print('YES') else: print('NO')
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
def solve(n,a): bool_a = [False]*n p = [] for i in range(len(a)): if bool_a[a[i]-1] == False: bool_a[a[i]-1] = True p.append(a[i]) return p t = int(input()) for i in range(t): n = int(input()) a= list(map(int, input().split())) p = solve(n,a) print(*p)
Vadim loves decorating the Christmas tree, so he got a beautiful garland as a present. It consists of n light bulbs in a single row. Each bulb has a number from 1 to n (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland....
3
def f(mass, a): mass.sort() prov = True for i in range(len(mass)): if a >= mass[i]: a -= mass[i] else: prov = False break if prov: return [0, a] return [2 * (len(mass) - i), a] n = int(input()) mass = [int(i) for i in input().split()] c...
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
n=int(input()) print(["NO","YES"][any(n%i==0 for i in[4,7,47,744,477,777])])
Polycarp is preparing the first programming contest for robots. There are n problems in it, and a lot of robots are going to participate in it. Each robot solving the problem i gets p_i points, and the score of each robot in the competition is calculated as the sum of p_i over all problems i solved by it. For each prob...
3
import math def dtb(n): return bin(n).replace("0b","") def btd(n): return int(n,2) n=int(input()) r=list(map(int,input().split()))[:n] b=list(map(int,input().split()))[:n] count1,count2=0,0 flag=0 for i in range (n): if r[i]==1 and b[i]==0: count1+=1 if r[i]==0 and b[i]==1: count2+=1...
Snark and Philip are preparing the problemset for the upcoming pre-qualification round for semi-quarter-finals. They have a bank of n problems, and they want to select any non-empty subset of it as a problemset. k experienced teams are participating in the contest. Some of these teams already know some of the problems...
3
n,k = list(map(int, input().split())) sq_k = 2**k rec = [0]*sq_k for _ in range(n): ind = int(''.join(input().split()), 2) rec[ind] += 1 ans = 'YES' if rec[0] > 0: print(ans) exit() for i in range(sq_k): for j in range(sq_k): if rec[i] > 0 and rec[j] > 0: if i&j == 0: ...
"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()) arr = list(map(int, input().split())) s = 0 for i in range(n): if arr[i] >= arr[k - 1] and arr[i] > 0: s += 1 print(s)
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
a,b=map(int,input().split()) for i in range(1,100): if str(a*i)[-1]==str(b): print(i) break elif str(a*i)[-1]=='0': print(i) break
You are given a string s consisting of exactly n characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings. Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string ...
3
from sys import stdin def update(a,idx1,idx2): a[idx1]+=1 a[idx2]-=1 return a def check(a): if '0' not in a: a['0']=0 if '1' not in a: a['1']=0 if '2' not in a: a['2']=0 return a n=int(stdin.readline()) s=stdin.readline() arr={} z,o,t=0,0,0 for i in range(n): if...
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that. For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two ...
3
from math import sqrt n=int(input()) def isnotprime(n): for i in range(2,int(sqrt(n))+1): if n%i==0: return False return True a=4 b=n-4 while isnotprime(b) and b>1: a+=2 b-=2 print(a,b)
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
N = input() N = int(N) if((N>=4) and (N % 2 == 0)): print("YES") else: print("NO")
Alexander is a well-known programmer. Today he decided to finally go out and play football, but with the first hit he left a dent on the new Rolls-Royce of the wealthy businessman Big Vova. Vladimir has recently opened a store on the popular online marketplace "Zmey-Gorynych", and offers Alex a job: if he shows his pro...
3
import math for test in range(int(input())): pocet = int(input()) vstup = list(map(int, input().split(" "))) maximum = max(vstup) output = str(maximum) b = [] b.append(str(maximum)) vstup.remove(max(vstup)) maxgcd = int(b[0]) #print(vstup) while len(vstup)>0: divisors = [] for i in vstup: divisors.appe...
Let's define the following recurrence: $$$a_{n+1} = a_{n} + minDigit(a_{n}) ⋅ maxDigit(a_{n}).$$$ Here minDigit(x) and maxDigit(x) are the minimal and maximal digits in the decimal representation of x without leading zeroes. For examples refer to notes. Your task is calculate a_{K} for given a_{1} and K. Input The ...
3
def minmax(a): l=[] while a>0: l.append(a%10) a=a//10 return min(l)*max(l) for _ in range(int(input())): a,k=map(int,input().split()) for i in range(k-1): x=minmax(a) if x==0: break else: a+=x print(a)
Ashish has an array a of consisting of 2n positive integers. He wants to compress a into an array b of size n-1. To do this, he first discards exactly 2 (any two) elements from a. He then performs the following operation until there are no elements left in a: * Remove any two elements from a and append their sum to...
3
import math t=int(input()) for w in range(t): n=int(input()) l=[int(i) for i in input().split()] l1=[] l2=[] k=2*n for i in range(k): if(l[i]%2==0): l1.append(i) else: l2.append(i) c=0 for i in range(0,len(l1)-1,2): if(c==n-1): ...
Quickly after finishing the tutorial of the online game ATChat, you have decided to visit a particular place with N-1 players who happen to be there. These N players, including you, are numbered 1 through N, and the friendliness of Player i is A_i. The N players will arrive at the place one by one in some order. To ma...
3
N=int(input()) A=list(map(int,input().split())) A.sort() ans=0 for i in range(N-1): ans+=A[N-1-(i+1)//2] print(ans)
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like [walls](https://www.youtube.com/watch?v=YR5ApYxkU-U), he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid. Roger Waters has a square grid of size n× n and he wants to traverse his grid f...
3
import sys LI=lambda:list(map(int, sys.stdin.readline().strip('\n').split())) MI=lambda:map(int, sys.stdin.readline().strip('\n').split()) SI=lambda:sys.stdin.readline().strip('\n') II=lambda:int(sys.stdin.readline().strip('\n')) for _ in range(II()): n=II() g=[] for i in range(n): g.append(list(SI())) if g[0][1...
Compute A \times B, truncate its fractional part, and print the result as an integer. Constraints * 0 \leq A \leq 10^{15} * 0 \leq B < 10 * A is an integer. * B is a number with two digits after the decimal point. Input Input is given from Standard Input in the following format: A B Output Print the answer as ...
3
import decimal a,b=map(decimal.Decimal,input().split()) print(int(a*b))
Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be n problems, sorted by difficulty, i.e. problem 1 is the easiest and problem n is the hardest. Limak knows it will take him 5·i minutes to solve the i-th...
3
import sys,math n, k = map(int, sys.stdin.readline().split()) total = (240 - k)//5 a = (int(math.sqrt(8*total + 1)) - 1)//2 print(min(n,a))
Polycarpus has n friends in Tarasov city. Polycarpus knows phone numbers of all his friends: they are strings s1, s2, ..., sn. All these strings consist only of digits and have the same length. Once Polycarpus needed to figure out Tarasov city phone code. He assumed that the phone code of the city is the longest comm...
3
import sys import math import itertools import functools import collections import operator import fileinput import copy ORDA = 97 # a def ii(): return int(input()) def mi(): return map(int, input().split()) def li(): return [int(i) for i in input().split()] def lcm(a, b): return abs(a * b) // math.gcd(a, b) ...
Ilya is a very clever lion, he lives in an unusual city ZooVille. In this city all the animals have their rights and obligations. Moreover, they even have their own bank accounts. The state of a bank account is an integer. The state of a bank account can be a negative number. This means that the owner of the account ow...
3
n = int(input()) if (n >= 0): print(n) else: s = "" + str(-n) k = (len(s)) ld = -(int(s[0:k-1])) ld1 = -(int(s[0:k-2] + s[k-1])) if(ld > ld1): print(ld) else: print(ld1)
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
def capitalise(s): if s[:1].lower(): print(s[:1].upper()+s[1:]) capitalise(input())
When Serezha was three years old, he was given a set of cards with letters for his birthday. They were arranged into words in the way which formed the boy's mother favorite number in binary notation. Serezha started playing with them immediately and shuffled them because he wasn't yet able to read. His father decided t...
3
n=int(input()) s=input() c=0 c1=0 for i in range(0,n): if(s[i]=='n'): c1+=1 elif(s[i]=='z'): c+=1 for i in range(c1): print('1',end=" ") for i in range(c): print('0',end=" ")
Snuke got an integer sequence of length N from his mother, as a birthday present. The i-th (1 ≦ i ≦ N) element of the sequence is a_i. The elements are pairwise distinct. He is sorting this sequence in increasing order. With supernatural power, he can perform the following two operations on the sequence in any order: ...
3
n = int(input()) A = [int(input()) for _ in range(n)] d = {element: i for i, element in enumerate(sorted(set(A)))} ans = 0 for i in range(n): if i % 2 != d[A[i]] % 2: ans += 1 print(ans // 2)
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
n = int(input()) while n > 0: n -= 1 word = input() if len(word) > 10: word = word[0] + (len(word)-2).__str__() + word[len(word)-1] print(word)
There is a sequence of length N: A_1, A_2, ..., A_N. Initially, this sequence is a permutation of 1, 2, ..., N. On this sequence, Snuke can perform the following operation: * Choose K consecutive elements in the sequence. Then, replace the value of each chosen element with the minimum value among the chosen elements....
3
n,k=map(int,input().split());print(((n-2)//(k-1))+1)
The student council has a shared document file. Every day, some members of the student council write the sequence TMT (short for Towa Maji Tenshi) in it. However, one day, the members somehow entered the sequence into the document at the same time, creating a jumbled mess. Therefore, it is Suguru Doujima's task to fig...
3
for _ in range(int(input())): n = int(input()) s = input() t = 0 m = 0 for c in s: if c == "M": m += 1 if m > t: print("NO") break else: t += 1 else: if t == 2 * m: m = 0 t = 0 ...
The new "Die Hard" movie has just been released! There are n people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 ruble bill. A "Die Hard" ticket costs 25 rubles. Can the booking clerk sell a ticket to each person and give the change if he initially has no money and sells the...
3
n = int(input()) A = [int(x) for x in input().split()] def canSolve(): quarters = halves = 0 for a in A: if a == 25: quarters += 1 elif a == 50: if quarters >= 1: quarters -= 1 halves += 1 else: return False else: if halves >= 1 and quarters >= 1: ...
Our good friend Mole is trying to code a big message. He is typing on an unusual keyboard with characters arranged in following way: qwertyuiop asdfghjkl; zxcvbnm,./ Unfortunately Mole is blind, so sometimes it is problem for him to put his hands accurately. He accidentally move...
3
f = "qwertyuiop" s = "asdfghjkl;" l = 'zxcvbnm,./' letter = input() t = input() if letter == "R": for i in t: if i in f: j = f.index(i) if j==0: pass else: print(f[j-1],end='') elif i in s: j = s.index(i) if j == 0: pass else: print(s[j-1],end='') else: j = l.index(i) if j...
A permutation p of size n is the sequence p1, p2, ..., pn, consisting of n distinct integers, each of them is from 1 to n (1 ≤ pi ≤ n). A lucky permutation is such permutation p, that any integer i (1 ≤ i ≤ n) meets this condition ppi = n - i + 1. You have integer n. Find some lucky permutation p of size n. Input T...
3
n=int(input()) if(n%4>1): print(-1) else: ans=[0]*(n+1) i,j,a,b=1,n,1,n while(i<j and a<=n and b>=1): ans[i],ans[j]=a+1,b-1 ans[i+1],ans[j-1]=b,a i+=2 j-=2 a+=2 b-=2 if(i==j): ans[i]=a for i in range(1,n+1): print(ans[i],end=' ') ...
Snuke has decided to play a game using cards. He has a deck consisting of N cards. On the i-th card from the top, an integer A_i is written. He will perform the operation described below zero or more times, so that the values written on the remaining cards will be pairwise distinct. Find the maximum possible number of...
3
N = int(input()) A = list(map(int,input().rstrip().split(" "))) A.sort() ans = N for i in range(N-1): if A[i] == A[i+1]: ans -= 1 if ans % 2 == 0: ans -= 1 print(ans)
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
from sys import stdin def minimum(data) -> int: m, actual = 0, 0 for d in data: actual += d[1] - d[0] m = actual if actual > m else m return m def main(): n = stdin.readline().strip() while len(n) != 0: data = [] for c in range(int(n)): a, b = [int(n) fo...
During the lesson small girl Alyona works with one famous spreadsheet computer program and learns how to edit tables. Now she has a table filled with integers. The table consists of n rows and m columns. By ai, j we will denote the integer located at the i-th row and the j-th column. We say that the table is sorted in...
3
from sys import stdin, stdout def main(): n, m = map(int, stdin.readline().split()) k = [] for i in range(n): k.append(list(map(int, stdin.readline().split()))) ans = [] BASE = [1 for i in range(m)] ans.append(list(BASE)) for i in range(1, n): ans.append(list(BASE)) ...
Bob is playing with 6-sided dice. A net of such standard cube is shown below. <image> He has an unlimited supply of these dice and wants to build a tower by stacking multiple dice on top of each other, while choosing the orientation of each dice. Then he counts the number of visible pips on the faces of the dice. Fo...
3
input() for e in map(int, input().split()): q, r = divmod(e, 14) if q >= 1 and r >= 1 and r <= 6: print("YES") continue print("NO")
Ilya is a very clever lion, he lives in an unusual city ZooVille. In this city all the animals have their rights and obligations. Moreover, they even have their own bank accounts. The state of a bank account is an integer. The state of a bank account can be a negative number. This means that the owner of the account ow...
1
n = int(raw_input()) if n > 0: print n else: a = str(n) print max(int(a[:-2] + a[-1]), int(a[:-1]))
"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(" ")) w=list(map(int,input().split(" "))) count=0 for i in w[0:k]: if i>0: count+=1 for j in w[k:len(w)]: if j>0 and j>=w[k-1]: count+=1 print(count)
Mishka wants to buy some food in the nearby shop. Initially, he has s burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1 ≤ x ≤ s, buy food that costs exactly x burles and obtain ⌊x/10⌋ burles as a cashback (in other words, Mishka ...
3
a=int(input()) for k in range(a): b= int(input()) if b % 9 != 0: print(b+(b// 9)) else: print(b+(b// 9) -1)
Robot Doc is located in the hall, with n computers stand in a line, numbered from left to right from 1 to n. Each computer contains exactly one piece of information, each of which Doc wants to get eventually. The computers are equipped with a security system, so to crack the i-th of them, the robot needs to collect at ...
3
n = int(input()) a = [int(x) for x in input().split()] collected = 0 ans = -1 dr = 1 st = -1 while collected < n: st += dr ans += 1 while st >=0 and st < n: if a[st] != -1 and a[st] <= collected: collected += 1 a[st] = -1 st += dr dr *= -1 print(ans)
You have a list of numbers from 1 to n written from left to right on the blackboard. You perform an algorithm consisting of several steps (steps are 1-indexed). On the i-th step you wipe the i-th number (considering only remaining numbers). You wipe the whole number (not one digit). <image> When there are less than ...
3
import sys sys.setrecursionlimit(10**9) t=int(input()) for _ in range(t): n, x = map(int, input().split()) # 2, 4, 6, ... print(2 * x)
There are N integers, A_1, A_2, ..., A_N, written on the blackboard. You will choose one of them and replace it with an integer of your choice between 1 and 10^9 (inclusive), possibly the same as the integer originally written. Find the maximum possible greatest common divisor of the N integers on the blackboard afte...
3
from fractions import gcd n = int(input()) as_ = list(map(int, input().split())) gcd_all = as_.pop() set_ = {as_[0]} for a in as_: set_ = set(gcd(s, a) for s in set_) set_.add(gcd_all) gcd_all = gcd(gcd_all, a) print(max(set_))
Quick sort is based on the Divide-and-conquer approach. In QuickSort(A, p, r), first, a procedure Partition(A, p, r) divides an array A[p..r] into two subarrays A[p..q-1] and A[q+1..r] such that each element of A[p..q-1] is less than or equal to A[q], which is, inturn, less than or equal to each element of A[q+1..r]. I...
3
def partition(p, r): x = A[r] i = p - 1 for j in range(p, r): if A[j] <= x: i += 1 A[i], A[j] = A[j], A[i] A[i + 1], A[r] = A[r], A[i + 1] return i + 1 n = int(input()) A = [int(i) for i in input().split()] q = partition(0, n - 1) A[q] = "[%d]"%A[q] print(*A)
George woke up and saw the current time s on the digital clock. Besides, George knows that he has slept for time t. Help George! Write a program that will, given time s and t, determine the time p when George went to bed. Note that George could have gone to bed yesterday relatively to the current time (see the second...
3
hour, mnt = map(int,input().split(":")) durH, durM = map(int,input().split(":")) resM = mnt - durM sn = ((resM//(abs(resM)+.1))-abs(resM//(abs(resM)+.1)))/-2 resM += sn*60 resH = hour - durH - sn resH += ((resH//(abs(resH)+.1))-abs(resH//(abs(resH)+.1)))*-12 print(f"{str(int(resH)).zfill(2)}:{str(int(resM)).zfil...
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution....
3
# -*- coding: utf-8 -*- n = int(input()) ans = 0 for i in range(n): a, b, c = map(int, input().split()) sum = a + b + c if sum >= 2: ans += 1 print(ans)
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the oppo...
3
n=int(input()) count=1 t=input() for i in range(0,n-1): t1=input() if t!=t1: count=count+1 t=t1 if count!=0: print(count)
There is a function f(x), which is initially a constant function f(x) = 0. We will ask you to process Q queries in order. There are two kinds of queries, update queries and evaluation queries, as follows: * An update query `1 a b`: Given two integers a and b, let g(x) = f(x) + |x - a| + b and replace f(x) with g(x). ...
3
import heapq q = int(input()) inf = 10000000000 left = [inf] right = [inf] minval = 0 for _ in range(q): query = list(map(int, input().split())) if query[0] == 1: _, a, b = query if a < -left[0]: v = -heapq.heappop(left) heapq.heappush(right, v) heapq.heappus...
Nikolay got a string s of even length n, which consists only of lowercase Latin letters 'a' and 'b'. Its positions are numbered from 1 to n. He wants to modify his string so that every its prefix of even length has an equal amount of letters 'a' and 'b'. To achieve that, Nikolay can perform the following operation arb...
3
n = int(input()) s = str(input()) changes = 0 final_str = list(s) n = n - n % 2 for i in range(0,n,2): if s[i] == s[i+1]: if s[i] == 'a': final_str[i] = 'b' #s[i] = 'b' else: final_str[i] = 'a' #s[i] = 'a' changes += 1 print(changes) print("".join(final_str))
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
#http://codeforces.com/problemset/problem/112/A str1 = input().upper() str2 = input().upper() if str1 < str2: print(-1) elif str1 > str2: print(1) else: print(0)
"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 = list(map(int,input().split())) m = list(map(int,input().split())) k = n[1] score = m[k-1] counter = 0 for i in m: if i > 0 and i >= score: counter += 1 print(counter)
Natasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the string — concatenation of letters, which correspond to the stages. There are n stages available. The rock...
3
def getWeight(a): return(ord(a) - ord('a')+1) n,k = input().strip().split(" ") n = int(n) k = int(k) if (k <= 0): print("0") exit(0) if (n <= 0): print("-1") exit(0) if (k > 14): print("-1") exit(0) s = set() st = input().strip() for x in st: s.add(x) count = 0 skip = False ret = 0 pre...
So, the New Year holidays are over. Santa Claus and his colleagues can take a rest and have guests at last. When two "New Year and Christmas Men" meet, thear assistants cut out of cardboard the letters from the guest's name and the host's name in honor of this event. Then the hung the letters above the main entrance. O...
3
a=input() c=input() b=input() a+=c p='' v='' if len(a)!=len(b): print('NO') else: c=[0]*26 d=[0]*26 for i in a: nom=ord(i)-65 c[nom]+=1 for i in range(26): p+=chr(i+65)*c[i] for i in b: nom=ord(i)-65 d[nom]+=1 for i in range(26): v+=chr(i+65)*d...
Problem N idols, numbered from 1 to n in order, are lined up in a row. Idle i can transmit information to idle i-1 and idle i + 1 in a unit time. However, idol 1 can transmit information only to idol 2, and idol n can transmit information only to idol n-1. At time 0, m idols with numbers a1, a2, ..., am have secret i...
3
n, m = map(int, input().split()) li = list(map(int, input().split())) print(max(li[0]-1, n-li[-1], *[(li[i]-li[i-1])//2 for i in range(1,m)]))
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr...
3
import sys import collections import math import functools import itertools import bisect import operator import heapq import random true=True false=False null=None tcid=0 def ceil(a,b): ans=a//b if a%b!=0: ans+=1 return ans def perr(*args,**kwargs): print(*args,file=sys.stderr,**kwargs) def line(): ln=sys.stdin.re...
You have n gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The i-th gift consists of a_i candies and b_i oranges. During one move, you can choose some gift 1 ≤ i ≤ n and do one of the following operations: * eat exactly...
1
def solve(a,b): mina = min(a) minb = min(b) nyoh = 0 for i in range(len(a)): jara = a[i]-mina jarb = b[i]-minb nyoh += max(jara,jarb) return nyoh for _ in range(input()): n = raw_input() candy = map(int,raw_input().split()) orange = map(int,raw_input().split()) ...
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....
1
s=raw_input();print s[0:1].capitalize()+s[1:]
Duff is in love with lovely numbers! A positive integer x is called lovely if and only if there is no such positive integer a > 1 such that a2 is a divisor of x. <image> Malek has a number store! In his store, he has only divisors of positive integer n (and he has all of them). As a birthday present, Malek wants to g...
3
import math n = int(input()) realn = n divisors = [ -1 ] if n % 2 == 0: divisors.append(2) while n % 2 == 0: n /= 2 x = 3 while x <= math.sqrt(n): a, b = divmod(n, x) if b == 0: n /= x divisors.append(x) while n % x == 0: n /= x x += 2 if n > 1: divisors.append(int(n)) if len(diviso...
"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] = [int(x) for x in input().split(' ')] scores = [int(x) for x in input().split(' ')] number = 0 for x in scores: if x >= scores[k - 1] and x > 0: number += 1 print(number)
There is a grid with N rows and N columns of squares. Let (i, j) be the square at the i-th row from the top and the j-th column from the left. Each of the central (N-2) \times (N-2) squares in the grid has a black stone on it. Each of the 2N - 1 squares on the bottom side and the right side has a white stone on it. Q...
3
N, Q = map(int, input().split()) N -= 2 # 枠を取り除いたサイズに直す #ここから33行目まで準備。Binary indexed tree(BIT)というデータ構造を使う。 BIT = [[0 for i in range(N+1)] for _ in range(2)] #BITを2つ用意 # BITでできること。 # 1, 要素の更新をO(logn)で行う # 2, 累積和をO(logn)で求める。 #  ※ 両方ともそれなりに早くできるのがメリット。 # 普通の配列だと、1と2がそれぞれO(1),O(n)かかる。 # 一方、累積和で記録した配列だと、1と2がO(...
There is an infinite board of square tiles. Initially all tiles are white. Vova has a red marker and a blue marker. Red marker can color a tiles. Blue marker can color b tiles. If some tile isn't white then you can't use marker of any color on it. Each marker must be drained completely, so at the end there should be e...
3
import math import time D = False def b_search(lst, num, row, col, ab): H = len(lst) - 1 L = 0 while L <= H: M = (L + H)//2 if D: print(lst[M], row, ab/lst[M], col) if D: print("cond:", lst[M] <= row, num/lst[M] <= col) if lst[M] <= row and num/lst[M] <= col: ...
Skier rides on a snowy field. Its movements can be described by a string of characters 'S', 'N', 'W', 'E' (which correspond to 1 meter movement in the south, north, west or east direction respectively). It is known that if he moves along a previously unvisited segment of a path (i.e. this segment of the path is visite...
3
t = int(input()) for __ in range(t): dirs = input() x, y = 0, 0 visited_path = set() time = 0 for movement in dirs: if movement == 'N': new_x, new_y = x, y+1 if movement == 'S': new_x, new_y = x, y-1 if movement == 'W': new_x, new_y = x-1, ...
There are n banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if n > 1. No bank is a neighbour of itself. Vasya has an account in each bank. Its balance may be negative, meaning V...
3
import sys import math input = sys.stdin.readline n = int(input()) a = [0] + [int(_) for _ in input().split()] dp = [0] * (n + 1) last = dict() total, ans, last[0] = 0, 0, 0 for i in range(1, n + 1): total += a[i] if last.get(total, -1) == -1: dp[i] = 0 else: dp[i] = 1 + dp[last[total]] ...
Nothing has changed since the last round. Dima and Inna still love each other and want to be together. They've made a deal with Seryozha and now they need to make a deal with the dorm guards... There are four guardposts in Dima's dorm. Each post contains two guards (in Russia they are usually elderly women). You can b...
1
rubles = input() flag = False for i in range(4): choc1,juice1,choc2,juice2 = map(int,raw_input().split(' ')) gaurd1 = min(choc1,juice1) gaurd2 = min(choc2,juice2) if (gaurd1 + gaurd2 < rubles): print i+1, gaurd1 , rubles-gaurd1 flag = True break elif gaurd1 + gaurd2 == rubl...
Vasya has got two number: a and b. However, Vasya finds number a too short. So he decided to repeat the operation of lengthening number a n times. One operation of lengthening a number means adding exactly one digit to the number (in the decimal notation) to the right provided that the resulting number is divisible by...
3
a,b,n=map(int,input().split()) s=str(a) x=0 for j in range(10): if int(s+str(j))%b==0: s=s+str(j) x=1 break if x==0: print("-1") else: print(s+"0"*(n-1))
An adult game master and N children are playing a game on an ice rink. The game consists of K rounds. In the i-th round, the game master announces: * Form groups consisting of A_i children each! Then the children who are still in the game form as many groups of A_i children as possible. One child may belong to at m...
3
def main(): k, *a = map(int, open(0).read().split()) m = M = 2 for x in a[::-1]: M -= M % x if m > M: print(-1) exit() m += -m % x M += x - 1 print(m, M) if __name__=="__main__": main()
Let LCM(x, y) be the minimum positive integer that is divisible by both x and y. For example, LCM(13, 37) = 481, LCM(9, 6) = 18. You are given two integers l and r. Find two integers x and y such that l ≤ x < y ≤ r and l ≤ LCM(x, y) ≤ r. Input The first line contains one integer t (1 ≤ t ≤ 10000) — the number of tes...
3
t = int(input()) for i in range(t): l, r = map(int, input().split()) if r // l >= 2: if r % 2 == 0: print(r // 2, r) else: print((r-1) // 2, r-1) else: print(-1, -1)
A positive (strictly greater than zero) integer is called round if it is of the form d00...0. In other words, a positive integer is round if all its digits except the leftmost (most significant) are equal to zero. In particular, all numbers from 1 to 9 (inclusive) are round. For example, the following numbers are roun...
3
for i in range(int(input())): l = [] cnt = 0 a = input() b = len(a) for j in range(len(a)): b = b - 1 if a[j] != '0': r = a[j] + '0' * b l.append(r) cnt = cnt + 1 print(cnt) for k in l: print(str(k) , end = ' ')
There are K items placed on a grid of squares with R rows and C columns. Let (i, j) denote the square at the i-th row (1 \leq i \leq R) and the j-th column (1 \leq j \leq C). The i-th item is at (r_i, c_i) and has the value v_i. Takahashi will begin at (1, 1), the start, and get to (R, C), the goal. When he is at (i, ...
3
import sys,queue,math,copy,itertools,bisect,collections,heapq def main(): LI = lambda : [int(x) for x in sys.stdin.readline().split()] R,C,K = LI() m = [[0] * (C+1) for _ in range(R+1)] dp = [[0] * 4 for _ in range(C+1)] for _ in range(K): r,c,v = LI() m[r][c] = v for i in ra...
There is a trampoline park with n trampolines in a line. The i-th of which has strength S_i. Pekora can jump on trampolines in multiple passes. She starts the pass by jumping on any trampoline of her choice. If at the moment Pekora jumps on trampoline i, the trampoline will launch her to position i + S_i, and S_i wi...
3
from sys import * for _ in range(int(stdin.readline())): n=int(stdin.readline()) l=[int(x) for x in stdin.readline().split()] ind=0 ans=0 sp=[0]*n while(ind<n and l[ind]==1): ind+=1 if ind==n: print(0) continue while(ind<n): if l[ind]==1: if s...
Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food: * on Mondays, Thursdays and Sundays he eats fish food; * on Tuesdays and Saturdays he eats rabbit stew; * on other days of week he eats chicken stake. Polycarp plans to go on a trip and already pa...
3
if __name__ == '__main__': schedule = "abcacba" abc = list(map(int,input().split())) a = abc[0] b = abc[1] c = abc[2] multiple = a // 3 if multiple > b // 2: multiple = b // 2 if multiple > c // 2: multiple = c // 2 aOver = a - multiple * 3 if aOver > 3: aOver = 3 bOver = b - multiple * 2 if bOver > ...
Robot Doc is located in the hall, with n computers stand in a line, numbered from left to right from 1 to n. Each computer contains exactly one piece of information, each of which Doc wants to get eventually. The computers are equipped with a security system, so to crack the i-th of them, the robot needs to collect at ...
1
n=int(raw_input()) ar=map(int,raw_input().split()) vis=[0]*n ctr=0 cur=0 pos=0 dir=1 while sum(vis)!=n: if dir==1: while(pos!=n): if(cur>=ar[pos] and vis[pos]==0): cur+=1 vis[pos]=1 pos+=1 pos=n-1 dir=-1 ctr+=1 else: while(pos!=-1): if(cur>=ar[pos] and vis[pos]==0): cur+=1 vis[pos]=...
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the...
3
i=input; a,b=map(int,i().split()) print(sum((y>b)+1 for y in list(map(int,i().split()))))
You are given four digits N_1, N_2, N_3 and N_4. Determine if these can be arranged into the sequence of digits "1974". Constraints * 0 \leq N_1, N_2, N_3, N_4 \leq 9 * N_1, N_2, N_3 and N_4 are integers. Input Input is given from Standard Input in the following format: N_1 N_2 N_3 N_4 Output If N_1, N_2, N_3 ...
1
import sys from collections import deque import copy import math def get_read_func(fileobject): if fileobject == None : return raw_input else: return fileobject.readline def main(): if len(sys.argv) > 1: f = open(sys.argv[1]) else: f = None read_func = get_read_func(...
Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on i...
3
import heapq n,k = [int(i) for i in input().split()] deck = input() cartas = {} for card in deck: if(card not in cartas): cartas[card] = 1 else: cartas[card]+=1 pq = [] for key in cartas: heapq.heappush(pq,-cartas[key]) coins = 0 element = -heapq.heappop(pq) qtdElement = element mult = 0 ...
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d...
3
n = list(str(input())) if n.count('4') + n.count('7') == 4 or n.count('4') + n.count('7') == 7: print('YES') else: print('NO')
Alice and Bob are controlling a robot. They each have one switch that controls the robot. Alice started holding down her button A second after the start-up of the robot, and released her button B second after the start-up. Bob started holding down his button C second after the start-up, and released his button D second...
3
a,b,c,d=map(int,input().split()) print(max(min(d,b)-max(c,a),0))
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like. Now let's imagine a typical morning in your family. You haven't w...
3
n =input("") sn =input("") min_cn = 0 accum = 0 sn_list = [int(k) for k in sn.split(' ')] sn_list.sort(reverse=True) sn_list_dup = sn_list.copy() for x in range(len(sn_list)): if(accum > sum(sn_list_dup)): break accum += sn_list_dup.pop(0) min_cn += 1 print(min_cn)
You went to the store, selling n types of chocolates. There are a_i chocolates of type i in stock. You have unlimited amount of cash (so you are not restricted by any prices) and want to buy as many chocolates as possible. However if you buy x_i chocolates of type i (clearly, 0 ≤ x_i ≤ a_i), then for all 1 ≤ j < i at ...
3
import sys input = sys.stdin.readline I = lambda : list(map(int,input().split())) n,=I() l=I() an=l[-1];mi=l[-1] for i in range(n-2,-1,-1): if l[i]>=mi: an+=max(0,mi-1) mi=max(0,mi-1) else: an+=l[i] mi=l[i] print(an)
— Hey folks, how do you like this problem? — That'll do it. BThero is a powerful magician. He has got n piles of candies, the i-th pile initially contains a_i candies. BThero can cast a copy-paste spell as follows: 1. He chooses two piles (i, j) such that 1 ≤ i, j ≤ n and i ≠ j. 2. All candies from pile i are...
3
#idly for _ in range(int(input())): n, k=[int(x)for x in input().split()] a=[int(x)for x in input().split()] ss=0 a.sort() for i in range(1,n): ss+=(k-a[i])//a[0] print(ss)
A new e-mail service "Berlandesk" is going to be opened in Berland in the near future. The site administration wants to launch their project as soon as possible, that's why they ask you to help. You're suggested to implement the prototype of site registration system. The system should work on the following principle. ...
3
passwords = set({}) lines = int(input()) prev_pass = {} for _ in range(lines): password = input() og_password = password if password in passwords: prev_pass[password] += 1 password += str(prev_pass[password]) else: prev_pass[password] = 0 passwords.add(password) if pass...
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
""" 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?...
Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of length k have the same sum. A subarray of an array is any sequence of consecutive elements. Phoenix currently has an array a of length n. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautifu...
3
from collections import Counter for _ in range(int(input())): n, k = [int(x) for x in input().split()] arr = [int(x) for x in input().split()] if k < len(Counter(arr)): print(-1) continue ans = [] posl = list(Counter(arr).keys()) if len(posl) < k: posl += [1] * (k - le...
You have N bamboos. The lengths (in centimeters) of these are l_1, l_2, ..., l_N, respectively. Your objective is to use some of these bamboos (possibly all) to obtain three bamboos of length A, B, C. For that, you can use the following three kinds of magics any number: * Extension Magic: Consumes 1 MP (magic point)....
3
from itertools import product n,*B=map(int,input().split()) A=[int(input()) for i in range(n)] s=10**9 for P in product([0,1,2,3],repeat=n): if {0,1,2}<=set(P): m=[0,0,0] for x,y in zip(P,A): if x!=3: m[x]+=y t=sum(abs(m-y) for m,y in zip(m,B)) l=sum(1 for j in P if j!=3)-3 s=min(s,t...
Kuroni has n daughters. As gifts for them, he bought n necklaces and n bracelets: * the i-th necklace has a brightness a_i, where all the a_i are pairwise distinct (i.e. all a_i are different), * the i-th bracelet has a brightness b_i, where all the b_i are pairwise distinct (i.e. all b_i are different). Kuro...
3
for i in range(int(input())): n = int(input()) for j in range(2): print(*sorted(list(map(int, input().split()))))
We have a secret array. You don't know this array and you have to restore it. However, you know some facts about this array: * The array consists of n distinct positive (greater than 0) integers. * The array contains two elements x and y (these elements are known for you) such that x < y. * If you sort the arr...
3
import sys import math import collections import bisect import itertools import decimal import copy # import numpy as np # sys.setrecursionlimit(10 ** 6) INF = 10 ** 20 # MOD = 10 ** 9 + 7 # MOD = 998244353 ni = lambda: int(sys.stdin.readline().rstrip()) ns = lambda: map(int, sys.stdin.readline().rstrip().split()) n...
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
I=lambda:list(map(int,input().split())) for tc in range(int(input())): n=int(input()) print(n)
Alice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of n stations, enumerated from 1 through n. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit afte...
3
# TAIWAN NUMBER ONE!!!!!!!!!!!!!!!!!!! # TAIWAN NUMBER ONE!!!!!!!!!!!!!!!!!!! # TAIWAN NUMBER ONE!!!!!!!!!!!!!!!!!!! from sys import stdin, stdout import math #N = int(input()) #N,M,K = [int(x) for x in stdin.readline().split()] N,M = [int(x) for x in stdin.readline().split()] def dist(a,b,N): if b>=a: ...
You are given an integer m as a product of integers a1, a2, ... an <image>. Your task is to find the number of distinct decompositions of number m into the product of n ordered positive integers. Decomposition into n products, given in the input, must also be considered in the answer. As the answer can be very large, ...
3
f=[1]*15001 fi=[1]*15001 a=1 b=1 m=10**9+7 from collections import defaultdict for i in range(1,15001): a*=i b*=pow(i,m-2,m) a%=m b%=m f[i]=a fi[i]=b d=defaultdict(int) def factorize(n): count = 0; while ((n % 2 > 0) == False): # equivalent to n = n / 2; ...
Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears. These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite — cookies. Ichihime decides to attend the contest. Now sh...
3
def solve(tests): for a, b, c, d in tests: print(a, c, c) t = int(input()) tests = [] for _ in range(t): tests.append(list(map(int, input().split()))) solve(tests)
There are N men and N women, both numbered 1, 2, \ldots, N. For each i, j (1 \leq i, j \leq N), the compatibility of Man i and Woman j is given as an integer a_{i, j}. If a_{i, j} = 1, Man i and Woman j are compatible; if a_{i, j} = 0, they are not. Taro is trying to make N pairs, each consisting of a man and a woman...
3
#!/usr/bin/env pypy3 def I(): return int(input()) def MI(): return map(int, input().split()) def LI(): return list(map(int, input().split())) def main(): mod=10**9+7 N=I() a=[[] for _ in range(N)] for i in range(N): a[i]=LI() #dp[S]は状態Sから何通りあるか?男性は1から順に,女性マッチング情報がS M=pow(2,N) ...
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the...
3
T = list(map(int, input().split())) a = list(map(int, input().split())) w = 0 for i in a: if i <= T[1]: w = w + 1 else: w = w + 2 print(w)
There are two rival donut shops. The first shop sells donuts at retail: each donut costs a dollars. The second shop sells donuts only in bulk: box of b donuts costs c dollars. So if you want to buy x donuts from this shop, then you have to buy the smallest number of boxes such that the total number of donuts in them ...
3
t=int(input()) for i in range(t): a,b,c=map(int,input().split()) if(a>c): print('-1',b) elif(a<c and (c/b)>=a): print(1,'-1') elif(a<c and (c/b)<a): print(1,b) else: print('-1',b)
A sequence (b_1, b_2, …, b_k) is called strange, if the absolute difference between any pair of its elements is greater than or equal to the maximum element in the sequence. Formally speaking, it's strange if for every pair (i, j) with 1 ≤ i<j ≤ k, we have |a_i-a_j|≥ MAX, where MAX is the largest element of the sequenc...
3
cases = int(input()) for _ in range(cases): n = int(input()) mylist = [int(i) for i in input().split(' ')] mylist.sort() ans = 0 if(mylist[0] > 0): print(1) continue min_diff = 1000000000 for i in range(0,n): if(mylist[i] < 0): ...
Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. For example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. When a team plays as ...
3
n=int(input()) ans=0 lis=[] while(n): l=list(map(int,input().split())) lis.append(l) n-=1 cnt=0 for i in range(len(lis)): for j in range(len(lis)): if(i!=j and lis[i][0]==lis[j][1]): cnt+=1 print(cnt)
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...
1
nums = raw_input().split("+") nums.sort() print "+".join(nums)
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
n = int(input()) f = (n+1)//2 if(n%2==1): f=-f print(f)