problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
You've got a 5 × 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix: 1....
3
for i in range (0,5): for j, a in enumerate(map(int, input().split())): if a==1: print (abs(i-2)+abs(j-2))
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
s = input(); p = input(); print("YES" if s==p[::-1] else "NO")
n children are standing in a circle and playing the counting-out game. Children are numbered clockwise from 1 to n. In the beginning, the first child is considered the leader. The game is played in k steps. In the i-th step the leader counts out ai people in clockwise order, starting from the next person. The last one ...
3
n, k = map(int,input().split()) ai = list(map(int,input().split())) ai2 = list(range(1,n+1)) num = 0 for i in range(k): num = num + ai[i] num %= n print(ai2[num],end=" ") n -= 1 ai2.remove(ai2[num])
Petya has an array a consisting of n integers. He wants to remove duplicate (equal) elements. Petya wants to leave only the rightmost entry (occurrence) for each element of the array. The relative order of the remaining unique elements should not be changed. Input The first line contains a single integer n (1 ≤ n ≤ ...
3
n=int(input()) l=list(map(int,input().split())) l=l[::-1] d=[] c=0 for i in l: if(i not in d): d.append(i) c=c+1 print(c) print(*d[::-1])
You are given an array of n elements, you must make it a co-prime array in as few moves as possible. In each move you can insert any positive integral number you want not greater than 109 in any place in the array. An array is co-prime if any two adjacent numbers of it are co-prime. In the number theory, two integer...
3
n=int(input()) lst = list(map(int, input().strip().split(' '))) c=0 l=[lst[0]] for i in range(1,n): if (l[-1]==lst[i] or l[-1]%lst[i]==0 or lst[i]%l[-1]==0) and (l[-1]!=1 and lst[i]!=1): l.append(1) l.append(lst[i]) c+=1 elif l[-1]==1 or lst[i]==1: l.append(lst[i]) else: ...
After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum nu...
3
n = int(input()) lis = list(map(int, input().split())) car1 = 0 ; car2 = 0; car3 = 0; car4 = 0 for i in lis: if i == 1 : car1 += 1 if i == 2 : car2 += 1 if i == 3 : car3 += 1 if i == 4 : car4 += 1 sagheraho = car4 sagheraho += car3 car1 = max(0, car1 - car3) sagheraho += car2 // 2 car2 %= 2 sagheraho += car...
We call two numbers x and y similar if they have the same parity (the same remainder when divided by 2), or if |x-y|=1. For example, in each of the pairs (2, 6), (4, 3), (11, 7), the numbers are similar to each other, and in the pairs (1, 4), (3, 12), they are not. You are given an array a of n (n is even) positive in...
3
def main(): for _ in range(int(input())): n=int(input()) lst=list(map(int,input().split())) lst=sorted(lst) cnt=[0,0,0] cnt[lst[0]%2]+=1 for i in range(len(lst)-1): cnt[lst[i+1]%2]+=1 if(lst[i+1]-lst[i]==1): cnt[2]+=1 if...
Let's define a function f(x) (x is a positive integer) as follows: write all digits of the decimal representation of x backwards, then get rid of the leading zeroes. For example, f(321) = 123, f(120) = 21, f(1000000) = 1, f(111) = 111. Let's define another function g(x) = (x)/(f(f(x))) (x is a positive integer as well...
3
t = int(input()) for _ in range(t): n = [int(i) for i in input().strip()] print(len(n))
During the break the schoolchildren, boys and girls, formed a queue of n people in the canteen. Initially the children stood in the order they entered the canteen. However, after a while the boys started feeling awkward for standing in front of the girls in the queue and they started letting the girls move forward each...
3
n,t = [int(x) for x in input().split()] str = input() for i in range(t): str = str.replace('BG','GB') print(str)
Mr. Takahashi has a string s consisting of lowercase English letters. He repeats the following operation on s exactly K times. * Choose an arbitrary letter on s and change that letter to the next alphabet. Note that the next letter of `z` is `a`. For example, if you perform an operation for the second letter on `aa...
3
s = input().strip() k = int(input()) ans = '' for _s in s[:-1]: if _s == 'a': ans += 'a' elif 26 - ord(_s) + ord('a') <= k: ans += 'a' k -= 26 - ord(_s) + ord('a') else: ans += _s ans += chr(ord('a') + (ord(s[-1]) - ord('a') + k) % 26) print(ans)
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
n = int(input()) total = 0 for i in range(n): line = input() line = line.split() if int(line[0]) + int(line[1]) + int(line[2]) >= 2: total = total + 1 else: total = total print(int(total))
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...
1
s=str(raw_input()) s=s.lower() z="" vowels='aeouiy' for char in s: if char in vowels: s=s.replace(char,"") for i in s: z+="."+i print z
Polycarp loves ciphers. He has invented his own cipher called repeating. Repeating cipher is used for strings. To encrypt the string s=s_{1}s_{2} ... s_{m} (1 ≤ m ≤ 10), Polycarp uses the following algorithm: * he writes down s_1 ones, * he writes down s_2 twice, * he writes down s_3 three times, * ... ...
3
e = input() e = list(e) res = ['0' for i in range(len(e))] i = 0 n = len(e) - 1 if len(e) % 2 != 0: r = 1 else: r = -1 y = len(e) - 1 while i != n + 1: if r == -1: res[y] = e[n] n -= 1 else: res[y] = e[i] i += 1 r *= -1 y -= 1 print(*res, sep = '')
Nikolay has a lemons, b apples and c pears. He decided to cook a compote. According to the recipe the fruits should be in the ratio 1: 2: 4. It means that for each lemon in the compote should be exactly 2 apples and exactly 4 pears. You can't crumble up, break up or cut these fruits into pieces. These fruits — lemons, ...
3
a=eval(input()) b=eval(input()) c=eval(input()) k=0 while(a>0 and b>0 and c>0): if(a>=1 and b>=2 and c>=4): k+=1 a-=1 b-=2 c-=4 print(k*7)
Fafa owns a company that works on huge projects. There are n employees in Fafa's company. Whenever the company has a new project to start working on, Fafa has to divide the tasks of this project among all the employees. Fafa finds doing this every time is very tiring for him. So, he decided to choose the best l employ...
3
n = int(input()) ans = 0 for l in range(1, n // 2 + 1): k = n - l if k % l == 0: ans += 1 print(ans)
When preparing a tournament, Codeforces coordinators try treir best to make the first problem as easy as possible. This time the coordinator had chosen some problem and asked n people about their opinions. Each person answered whether this problem is easy or hard. If at least one of these n people has answered that th...
3
a = input() b = input() if b.find('1') == -1: print('EASY') else: print('HARD')
Amugae has a hotel consisting of 10 rooms. The rooms are numbered from 0 to 9 from left to right. The hotel has two entrances — one from the left end, and another from the right end. When a customer arrives to the hotel through the left entrance, they are assigned to an empty room closest to the left entrance. Similar...
3
n = int(input()) s = input() l = [0] * 10 for i in s: if i == 'L': for j in range(10): if l[j] == 0: l[j] = 1 break elif i == 'R': for j in range(9, -1, -1): if l[j] == 0: l[j] = 1 break else: l[i...
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
import math,itertools,fractions,heapq,collections,bisect,sys,queue,copy sys.setrecursionlimit(10**7) inf=10**20 mod=10**9+7 dd=[(-1,0),(0,1),(1,0),(0,-1)] ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(): return [int(x) for x in sys.stdin.readline().split()] # def LF(): return [float(x) for x in s...
Reminder: the [median](https://en.wikipedia.org/wiki/Median) of the array [a_1, a_2, ..., a_{2k+1}] of odd number of elements is defined as follows: let [b_1, b_2, ..., b_{2k+1}] be the elements of the array in the sorted order. Then median of this array is equal to b_{k+1}. There are 2n students, the i-th student has...
3
t = int(input()) for i in range(t): n = int(input()) l = list(map(int, input().split())) tmp = sorted(l) print(tmp[n] - tmp[n-1])
You are given a permutation of length n. Recall that the permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2, 3, 1, 5, 4] is a permutation, but [1, 2, 2] is not a permutation (2 appears twice in the array) and [1, 3, 4] is also not a permutation (n=3 but there is 4 ...
3
q = int(input()) for _ in range(q): n = int(input()) P = list(map(int, input().split())) used = set() for i in reversed(range(1, n)): if P[i-1] > P[i]: P[i], P[i-1] = P[i-1], P[i] used.add((i-1, i)) for i in range(n-1): if P[i] > P[i+1] and (i, i+1) not in use...
Polycarp has interviewed Oleg and has written the interview down without punctuation marks and spaces to save time. Thus, the interview is now a string s consisting of n lowercase English letters. There is a filler word ogo in Oleg's speech. All words that can be obtained from ogo by adding go several times to the end...
3
n = int(input()) s = input() a, b = True, True if 'ogo' not in s: print(s) else: while b == True: a = True k = s.index('ogo') s = s[0:k] + '***' + s[k+3:] i = k + 3 while i < len(s) and a == True: if s[i:i+2] == 'go': s = s[0:i] + s[i+2:] ...
You are given an array a consisting of n integers. You have to find the length of the smallest (shortest) prefix of elements you need to erase from a to make it a good array. Recall that the prefix of the array a=[a_1, a_2, ..., a_n] is a subarray consisting several first elements: the prefix of the array a of length k...
3
for tc in range(int(input())): n = int(input()) lis = [int(i) for i in input().split()] minVal = 0 p = 0 q = n-1 ans = 0 init = 0 while p <= q: if lis[p] < lis[q] and lis[p] >= minVal: minVal = lis[p] p+=1 elif lis[p] >= lis[q] and lis[q] >= minVal...
Amugae has a hotel consisting of 10 rooms. The rooms are numbered from 0 to 9 from left to right. The hotel has two entrances — one from the left end, and another from the right end. When a customer arrives to the hotel through the left entrance, they are assigned to an empty room closest to the left entrance. Similar...
3
hotel=[0,0,0,0,0,0,0,0,0,0] n=int(input()) g=input() for i in g: if i=='L': for k in range(10): if not hotel[k]: hotel[k]=1 break elif i=='R': hotel.reverse() for k in range(10): if not hotel[k]: hotel[k]=1 ...
In Republic of Atcoder, there are N prefectures, and a total of M cities that belong to those prefectures. City i is established in year Y_i and belongs to Prefecture P_i. You can assume that there are no multiple cities that are established in the same year. It is decided to allocate a 12-digit ID number to each ci...
1
n, m = map(int, raw_input().split()) array = [] for i in xrange(m): p, y = map(int, raw_input().split()) array.append((y, p, i)) array.sort() hash_map = dict() for i in xrange(m): y, p, id = array[i] if p in hash_map: hash_map[p].append((y,id)) else: hash_map[p] = [] hash_map[p].append((y,id)) res = [] for...
You are given the array a consisting of n elements and the integer k ≤ n. You want to obtain at least k equal elements in the array a. In one move, you can make one of the following two operations: * Take one of the minimum elements of the array and increase its value by one (more formally, if the minimum value of ...
3
l=input().split() n=int(l[0]) k=int(l[1]) hashi=dict() l=input().split() li=[int(i) for i in l] z=0 for i in li: z=i count=0 while(z>0): if(z not in hashi): hashi[z]=[count] else: hashi[z].append(count) z=z//2 count+=1 if(0 not in hashi): h...
Valera runs a 24/7 fast food cafe. He magically learned that next day n people will visit his cafe. For each person we know the arrival time: the i-th person comes exactly at hi hours mi minutes. The cafe spends less than a minute to serve each client, but if a client comes in and sees that there is no free cash, than ...
3
n=int(input()) maxi=[] a,b=input().split() counter=1 for i in range(1,n): x,y=input().split() if x==a and y==b: counter+=1 else: maxi.append(counter) counter=1 a=x b=y if i==n-1: maxi.append(counter) if n==1: maxi.append(1) print(max(maxi))
Vasya wants to turn on Christmas lights consisting of m bulbs. Initially, all bulbs are turned off. There are n buttons, each of them is connected to some set of bulbs. Vasya can press any of these buttons. When the button is pressed, it turns on all the bulbs it's connected to. Can Vasya light up all the bulbs? If Va...
3
a=input().split() n=int(a[0]) m=int(a[1]) l=[list(map(int,input().split())) for i in range(n)] l2=[] for i in range(n): l2+=l[i][1:] if len(set(l2))==m: print("YES") else: print("NO")
There is a famous olympiad, which has more than a hundred participants. The Olympiad consists of two stages: the elimination stage, and the final stage. At least a hundred participants will advance to the final stage. The elimination stage in turn consists of two contests. A result of the elimination stage is the tota...
3
t = int(input()) for _ in range(t): a,b,c,d = map(int,input().split()) x = a+b y = c+d if x >= y: print(x) else: print(y)
There are n piranhas with sizes a_1, a_2, …, a_n in the aquarium. Piranhas are numbered from left to right in order they live in the aquarium. Scientists of the Berland State University want to find if there is dominant piranha in the aquarium. The piranha is called dominant if it can eat all the other piranhas in the...
3
t = int(input()) for j in range(t): k = int(input()) a = list(map(int, input().split())) m = a[0]; r = 0 for i in range(1, k): if a[i] >= m and (a[i-1] < a[i] or (i < k-1 and a[i+1] < a[i])): m = a[i]; r = i if r > 0 or a[1] < a[0]: print(r+1) else: print(-1)
Guy-Manuel and Thomas have an array a of n integers [a_1, a_2, ..., a_n]. In one step they can add 1 to any element of the array. Formally, in one step they can choose any integer index i (1 ≤ i ≤ n) and do a_i := a_i + 1. If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and T...
3
t = int(input()) while t > 0: t -= 1 n = int(input()) totalSum = 0 zeroCount = 0 for item in input().split(): item = int(item) totalSum += item if item == 0: zeroCount += 1 totalSum += 1 print(zeroCount + (1 if totalSum == 0 else 0))
ZS the Coder is coding on a crazy computer. If you don't type in a word for a c consecutive seconds, everything you typed disappear! More formally, if you typed a word at second a and then the next word at second b, then if b - a ≤ c, just the new word is appended to other words on the screen. If b - a > c, then ever...
1
n,c=raw_input().split(" ") n=int(n) c=int(c) m=map(int,raw_input().split(" ")) count=1 for i in range(n-1): if m[i+1]-m[i]>c: count=1 else: count+=1 print count
Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1, p2, ..., pn. You have a sequence of integers a1, a2, ..., an. In on...
1
n = input() t = 0 for i, c in enumerate(sorted(map(int, raw_input().split()))): t += abs(c - i - 1) print t
The World Programming Olympics Medal is a metal disk, consisting of two parts: the first part is a ring with outer radius of r1 cm, inner radius of r2 cm, (0 < r2 < r1) made of metal with density p1 g/cm3. The second part is an inner disk with radius r2 cm, it is made of metal with density p2 g/cm3. The disk is nested ...
1
def get_nums(): a = map(int, raw_input().split()[1:]) a.sort() return a rs = get_nums() p1s = get_nums() p2s = get_nums() A, B = map(int, raw_input().split()) r1 = rs[-1] + 0. p2 = p2s[0] + 0. p1 = p1s[-1] + 0. # print r1, p1, p2 r2 = ((B * p1 * r1**2)/(A * p2 + B * p1))**0.5 print '%.8f'%r2
You've got a rectangular table with length a and width b and the infinite number of plates of radius r. Two players play the following game: they take turns to put the plates on the table so that the plates don't lie on each other (but they can touch each other), and so that any point on any plate is located within the...
3
a,b,r=map(int, input().split(" ")) if 2*r <= a and 2*r <=b: print("First") else: print("Second")
Max wants to buy a new skateboard. He has calculated the amount of money that is needed to buy a new skateboard. He left a calculator on the floor and went to ask some money from his parents. Meanwhile his little brother Yusuf came and started to press the keys randomly. Unfortunately Max has forgotten the number which...
3
from sys import stdin,stdout from math import gcd,sqrt,factorial,pi,inf from collections import deque,defaultdict input=stdin.readline R=lambda:map(int,input().split()) I=lambda:int(input()) S=lambda:input().rstrip('\n') L=lambda:list(R()) P=lambda x:stdout.write(str(x)+'\n') lcm=lambda x,y:(x*y)//gcd(x,y) hg=lambda x,...
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()) for x in range(n): w=input() l=len(w) if l>10: l=str(l-2) w=w[0]+l+w[-1] print(w)
Bob is an avid fan of the video game "League of Leesins", and today he celebrates as the League of Leesins World Championship comes to an end! The tournament consisted of n (n ≥ 5) teams around the world. Before the tournament starts, Bob has made a prediction of the rankings of each team, from 1-st to n-th. After th...
3
import sys, math, collections import sys,io,os;input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline N=int(input()) A=[] for i in range(N-2): A.append(list(map(int,input().split()))) DC=collections.defaultdict(int) DI=collections.defaultdict(list) for i in A: for j in i: DC[j]+=1 DI[j]...
A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay i·k dollars for the i-th banana). He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas? Input The first lin...
1
k1,n1,w1=raw_input().split() k=int(k1) n=int(n1) w=int(w1) t=k sum=0 for i in range(1,w+1): t=k*i sum=sum+t if n>=sum: print 0 else: ans=sum-n print ans
Mishka started participating in a programming contest. There are n problems in the contest. Mishka's problem-solving skill is equal to k. Mishka arranges all problems from the contest into a list. Because of his weird principles, Mishka only solves problems from one of the ends of the list. Every time, he chooses whic...
3
a,k=[int(i) for i in input().split()] c=[int(i) for i in input().split()] i=0 while i<a and c[i]<=k: i+=1 j=1 while a-j>i and c[-j]<=k: j+=1 print(i+j-1)
String can be called correct if it consists of characters "0" and "1" and there are no redundant leading zeroes. Here are some examples: "0", "10", "1001". You are given a correct string s. You can perform two different operations on this string: 1. swap any pair of adjacent characters (for example, "101" <image>...
3
n = int(input()) s = input() cnt = s.count('0') if cnt == n: print(0) else: print('1' + '0' * cnt)
Phoenix has a string s consisting of lowercase Latin letters. He wants to distribute all the letters of his string into k non-empty strings a_1, a_2, ..., a_k such that every letter of s goes to exactly one of the strings a_i. The strings a_i do not need to be substrings of s. Phoenix can distribute letters of s and re...
3
from math import ceil t=int(input()) for test in range(t): n,k=map(int,input().split()) s=sorted(input()) if s[0]==s[-1]: print(''.join(s[:ceil(n/k)])) elif s[0]==s[k-1]: c=0 for i in range(k,n): if s[i]!=s[0]: break c+=1 if s[k]==s...
Andrey needs one more problem to conduct a programming contest. He has n friends who are always willing to help. He can ask some of them to come up with a contest problem. Andrey knows one value for each of his fiends — the probability that this friend will come up with a problem if Andrey asks him. Help Andrey choose...
1
input() a,b,c=1,0,0 for p in sorted(map(float,raw_input().split()))[::-1]: b=b*(1-p)+a*p a*=1-p c=max(c,b) print c
Polycarp is going to participate in the contest. It starts at h_1:m_1 and ends at h_2:m_2. It is guaranteed that the contest lasts an even number of minutes (i.e. m_1 \% 2 = m_2 \% 2, where x \% y is x modulo y). It is also guaranteed that the entire contest is held during a single day. And finally it is guaranteed tha...
3
start = list(input()) end = list(input()) h1 = int(''.join(start[:2])) m1 = int(''.join(start[-2:])) h2 = int(''.join(end[:2])) m2 = int(''.join(end[-2:])) extra = 0 min = (60 - m1) + (h2 - h1 - 1) * 60 + m2 mid_m = (h1 * 60 + m1 + min // 2) % 60 mid_h = (h1 * 60 + m1 + min // 2) // 60 print('{:02d}:{:02d}'.format(...
You've got a string a_1, a_2, ..., a_n, consisting of zeros and ones. Let's call a sequence of consecutive elements a_i, a_{i + 1}, …, a_j (1≤ i≤ j≤ n) a substring of string a. You can apply the following operations any number of times: * Choose some substring of string a (for example, you can choose entire strin...
3
n, x, y=map(int, input().split()) a='1'+input() c=0 for i in range(1, n+1): if a[i]=='0' and a[i-1]=='1': c+=1 print(min(c*y, max(0, y+(c-1)*x)))
Anton is playing a very interesting computer game, but now he is stuck at one of the levels. To pass to the next level he has to prepare n potions. Anton has a special kettle, that can prepare one potions in x seconds. Also, he knows spells of two types that can faster the process of preparing potions. 1. Spells of...
1
__author__ = 'ActiveChooN Dusted' def binSearch(x): l = 0 r = k while l<r: m = (l + r+1) // 2 if d[m]<=x: l = m else: r = m-1 return c[l] (n,p,k) = map(int,raw_input().split()) (x,s) = map(int,raw_input().split()) a = [x] + map(int,raw_input().split()) b...
Very soon there will be a parade of victory over alien invaders in Berland. Unfortunately, all soldiers died in the war and now the army consists of entirely new recruits, many of whom do not even know from which leg they should begin to march. The civilian population also poorly understands from which leg recruits beg...
3
def parade(): no_columns = int(input()) march_band = [] l_value = 0 r_value = 0 for i in range(no_columns): march_band.append([int(x) for x in input().strip().split(' ')]) l_value += march_band[i][0] r_value += march_band[i][1] max_beauty = abs(l_value - r_value) result = 0 for i in range(no_columns...
Vasya has n pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every m-th day (at days with numbers m, 2m, 3m, ...) mom buys a pair of socks to Vasya. She does it late in the eve...
3
n, m = map(int, input().split()) days = 0 a = 0 while n != 0: days += 1 n -= 1 a += 1 if a == m: n += 1 a -= a elif n == 0: print(days)
Drazil is playing a math game with Varda. Let's define <image> for positive integer x as a product of factorials of its digits. For example, <image>. First, they choose a decimal number a consisting of n digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then th...
1
from sys import stdin, stdout import math n = int(stdin.readline()) s = stdin.readline()[:-1] a2 = 0 a3 = 0 a5 = 0 a7 = 0 for d in s: for x in range(2,int(d)+1): if x==2: a2+=1 if x==3: a3+=1 if x==4: a2+=2 if x==5: a5+=1 if ...
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d...
3
n=input() a=[] count=0 for i in n: a.append(i) if i=='7' or i=='4': count+=1 if count == 4 or count == 7: print('YES') else: print('NO')
There are N squares in a row. The leftmost square contains the integer A, and the rightmost contains the integer B. The other squares are empty. Aohashi would like to fill the empty squares with integers so that the following condition is satisfied: * For any two adjacent squares, the (absolute) difference of the two...
3
N, A, B, C, D = list(map(int, input().split())) M = N - 1 n = abs(A - B) m = abs(C - D) def prin(tf): if tf: print("YES") else: print("NO") exit() if n > D * M: prin(False) GC = n GD = n if M % 2 == 1: M -= 1 GC = abs(n - C) GD = abs(n - D) t = GC // (2 * C) k = M // 2 - t a = t * 2 * C b = t *...
You are given three integers x, y and n. Your task is to find the maximum integer k such that 0 ≤ k ≤ n that k mod x = y, where mod is modulo operation. Many programming languages use percent operator % to implement it. In other words, with given x, y and n you need to find the maximum possible integer from 0 to n tha...
3
t = int(input()) for i in range(t): x, y, n = list(map(int, input().strip().split())) ans = n//x*x+y if n//x*x+y<=n else (n-x)//x*x+y print(ans)
The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2). You are given a sequence a consisting of n integers. All these integers are distinct, each value from 1 to n appears in the sequence exactly once. You are making a sequen...
3
from collections import deque n=int(input()) A=deque(map(int,input().split())) ans='' last=0 i=0 while i<n and max(A[0],A[-1])>last: if A[0]==A[-1] and A[0]>last: left,right=A[0],A[-1] size=len(A) ansLeft='L' for i in range(1,size): if A[i]>left: ansLeft+=...
You are given an integer n. In one move, you can either multiply n by two or divide n by 6 (if it is divisible by 6 without the remainder). Your task is to find the minimum number of moves needed to obtain 1 from n or determine if it's impossible to do that. You have to answer t independent test cases. Input The fi...
3
from collections import Counter, defaultdict BS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" def to_base(s, b): res = "" while s: res+=BS[s%b] s//= b return res[::-1] or "0" alpha = "abcdefghijklmnopqrstuvwxyz" from math import floor, ceil,pi primes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53...
You are given three positive (i.e. strictly greater than zero) integers x, y and z. Your task is to find positive integers a, b and c such that x = max(a, b), y = max(a, c) and z = max(b, c), or determine that it is impossible to find such a, b and c. You have to answer t independent test cases. Print required a, b a...
3
def possibleTriple(x, y, z): tem = " ".join(str(i) for i in [x, x, y]) return 'NO' if z > y else "\n".join(str(i) for i in ['YES', tem]) if __name__ == "__main__": t = int(input()) for _ in range(t): x, y, z = sorted(map(int, input().split())) print(possibleTriple(x, y, z))
Today the kindergarten has a new group of n kids who need to be seated at the dinner table. The chairs at the table are numbered from 1 to 4n. Two kids can't sit on the same chair. It is known that two kids who sit on chairs with numbers a and b (a ≠ b) will indulge if: 1. gcd(a, b) = 1 or, 2. a divides b or b d...
3
for _ in range(int(input())): n = int(input()) x = 4*n for i in range(n): print(x,end =" ") x-=2 print()
You are given a garland consisting of n lamps. States of the lamps are represented by the string s of length n. The i-th character of the string s_i equals '0' if the i-th lamp is turned off or '1' if the i-th lamp is turned on. You are also given a positive integer k. In one move, you can choose one lamp and change i...
3
import sys input = sys.stdin.readline t=int(input()) for tests in range(t): n,k=map(int,input().split()) S=input().strip() DIV=[[] for i in range(k)] SUM1=0 for i in range(n): if S[i]=="0": DIV[i%k].append(0) else: DIV[i%k].append(1) SUM1+=1 ...
Alica and Bob are playing a game. Initially they have a binary string s consisting of only characters 0 and 1. Alice and Bob make alternating moves: Alice makes the first move, Bob makes the second move, Alice makes the third one, and so on. During each move, the current player must choose two different adjacent char...
3
from sys import stdin,stdout for _ in range(int(stdin.readline().strip())): s=stdin.readline().strip() stdout.write(("NET","DA")[min(s.count('0'),s.count('1')) % 2]+"\n")
Ryouko is an extremely forgetful girl, she could even forget something that has just happened. So in order to remember, she takes a notebook with her, called Ryouko's Memory Note. She writes what she sees and what she hears on the notebook, and the notebook became her memory. Though Ryouko is forgetful, she is also bo...
1
R = lambda: map(int, raw_input().split()) (n, m), a = R(), R() v = [[] for i in range(n + 1)] ans = 0 for i in range(1, m): if a[i] != a[i - 1]: v[a[i - 1]].append(a[i]) v[a[i]].append(a[i - 1]) ans += abs(a[i] - a[i - 1]) max_change = 0 for i in range(1, n + 1): l = len(v[i]) v[i].sort() suma = sumb = 0 fo...
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 ...
1
m, d = map(int, raw_input().split()) if m in [1, 3, 5, 7, 8, 10, 12]: print 6 if d > 5 else 5 elif m == 2: print 4 if d == 1 else 5 else: print 6 if d == 7 else 5
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array a of n non-negative integers. Dark created that array 1000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high...
3
def solution(): from sys import stdin, stdout _input, _print, _range, _int, _zip, _set, _len = stdin.readline, stdout.write, range, int, zip, set, len _min, _max, _str, _abs = min, max, str, abs n = _int(_input()) for _ in _range(n): l = _int(_input()) arr = [_int(i) for i in _input(...
In the online judge system, a judge file may include multiple datasets to check whether the submitted program outputs a correct answer for each test case. This task is to practice solving a problem with multiple datasets. Write a program which reads an integer x and print it as is. Note that multiple datasets are give...
3
import sys a=1 for b in sys.stdin: b=b.strip() if b=='0':break print(f'Case {a}: {b}') a+=1
The last contest held on Johnny's favorite competitive programming platform has been received rather positively. However, Johnny's rating has dropped again! He thinks that the presented tasks are lovely, but don't show the truth about competitors' skills. The boy is now looking at the ratings of consecutive participan...
3
exec(int(input())*"n=int(input())\nprint(2*n-bin(n)[2:].count('1'))\n")
This winter is so cold in Nvodsk! A group of n friends decided to buy k bottles of a soft drink called "Take-It-Light" to warm up a bit. Each bottle has l milliliters of the drink. Also they bought c limes and cut each of them into d slices. After that they found p grams of salt. To make a toast, each friend needs nl ...
3
n,k,l,c,d,p,a,b=map(int,input().split()) print(min(k*l//a,c*d,p//b)//n)
You are given an array of n integers a_1, a_2, ..., a_n, and a set b of k distinct integers from 1 to n. In one operation, you may choose two integers i and x (1 ≤ i ≤ n, x can be any integer) and assign a_i := x. This operation can be done only if i does not belong to the set b. Calculate the minimum number of opera...
3
import bisect INF = 0x3f3f3f3f3f3f3f3f n, k = map(int, input().split()) a = [-INF] + [ ai - i for i, ai in enumerate(map(int, input().split())) ] + [INF] b = [0] + (list(map(int, input().split())) if k else list()) + [n+1] ans = 0 for j in range(k+1): l = b[j] r = b[j+1] if a[r] < a[l]: print("-1")...
There are n positive integers a_1, a_2, ..., a_n. For the one move you can choose any even value c and divide by two all elements that equal c. For example, if a=[6,8,12,6,3,12] and you choose c=6, and a is transformed into a=[3,8,12,3,3,12] after the move. You need to find the minimal number of moves for transformin...
3
from collections import Counter t = int(input()) for _ in range(0,t): n = int(input()) lst = [int(i) for i in input().split()] ans = 0 c = Counter(lst) ss = sorted(c)[::-1] for i in ss: if i%2 == 0 and c[i] != 0: while i%2 == 0: ans += 1 i //= ...
After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer. At the start of the day they have x ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. Each person in the q...
1
#!/usr/bin/env python from __future__ import print_function import sys DEBUG = '-d' in sys.argv def debug(*args, **kwargs): if DEBUG: print(*args, file=sys.stderr, **kwargs) return None n, x = map(int, raw_input().split()) distress = 0 for _ in xrange(n): op, m = raw_input().split() m = ...
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
t =int(input()) s="" for a in range(t): s=input() if len(s) >10 : i= len(s)-2 print(f"{s[0]}{i}{s[len(s)-1]}" ) else: print(s)
Karafs is some kind of vegetable in shape of an 1 × h rectangle. Tavaspolis people love Karafs and they use Karafs in almost any kind of food. Tavas, himself, is crazy about Karafs. <image> Each Karafs has a positive integer height. Tavas has an infinite 1-based sequence of Karafses. The height of the i-th Karafs is ...
3
from math import sqrt inp = input() l = list(map(int, inp.split(' '))) A = l[0] B = l[1] n = l[2] for i in range(n): inp = input() temp = list(map(int, inp.split(' '))) l = temp[0] t = temp[1] m = temp[2] imp = 0 a = B/2 b = (A - 1/2 * B) c = -A * (l - 1) + 3*B*l/2 - B*l*l/2 - B ...
Ayush and Ashish play a game on an unrooted tree consisting of n nodes numbered 1 to n. Players make the following move in turns: * Select any leaf node in the tree and remove it together with any edge which has this node as one of its endpoints. A leaf node is a node with degree less than or equal to 1. A tree...
3
from collections import defaultdict import heapq n = int(input()) # int(input()) # list(map(int, input().split())) def solve(n, x, edges): # Ayush moves first # Ashish afterwards if edges[x] <= 1: return "Ayush" if n & 1 == 1: return "Ashish" else: return "Ayush" for _ in range(n): n, x = list(map(int,...
You are given an array of n integers a_1,a_2,...,a_n. You have to create an array of n integers b_1,b_2,...,b_n such that: * The array b is a rearrangement of the array a, that is, it contains the same values and each value appears the same number of times in the two arrays. In other words, the multisets \\{a_1,a_...
3
t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) if (sum(a) == 0): print("NO") else: print("YES") pos = 0 neg = 0 for i in range(n): if (a[i] > 0): pos += a[i] else: ne...
During the break the schoolchildren, boys and girls, formed a queue of n people in the canteen. Initially the children stood in the order they entered the canteen. However, after a while the boys started feeling awkward for standing in front of the girls in the queue and they started letting the girls move forward each...
3
import sys from copy import copy n, t = map(int, input().split()) s = list(input()) for t_ in range(t): a = copy(s) for i in range(n-1): if s[i] == 'B' and s[i+1] == 'G': a[i] = 'G' a[i+1] = 'B' s = a print("".join(s))
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). For a positive integer n, we call a...
3
t=int(input()) for test in range(t): n=int(input()) s=set(range(n+1)) s.pop() print(*s) s=list(s) f=True '''for a in range(1,n+1): x=a for b in range(a+1,n+1): x=x|b if x<b-a+1: print("NOT GOOD") f=False break...
There are N flowers arranged in a row. For each i (1 \leq i \leq N), the height and the beauty of the i-th flower from the left is h_i and a_i, respectively. Here, h_1, h_2, \ldots, h_N are all distinct. Taro is pulling out some flowers so that the following condition is met: * The heights of the remaining flowers ar...
3
class SegmentTree: def __init__(self, size, default, op = max): self.size = 2**size.bit_length() self.dat = [default]*(self.size*2) self.op = op def update(self, i, x): i += self.size self.dat[i] = x while i > 0: i >>= 1 self.dat[i] = self.op(self.dat[i*2], self.dat[i*2+1]) d...
I decided to plant vegetables in the vegetable garden. There were n seeds, so I sown n seeds one by one a day over n days. All seeds sprout and grow quickly. I can't wait for the harvest time. One day, when I was watering the seedlings as usual, I noticed something strange. There should be n vegetable seedlings, but o...
1
while 1: n = input() if n == 0: break a = map(int,raw_input().split()) da = [a[i+1] - a[i] for i in range(n)] d = sorted(list(set(da)), key = lambda x:da.count(x))[-1] for i in range(n): if i == 0 and a[i] + d != a[i+1]: if a[i+1] + d != a[i+2]: print a[i+1] else: print a[i] break elif a[i] +...
We will call a string obtained by arranging the characters contained in a string a in some order, an anagram of a. For example, `greenbin` is an anagram of `beginner`. As seen here, when the same character occurs multiple times, that character must be used that number of times. Given are N strings s_1, s_2, \ldots, s...
3
import collections n=int(input()) L=["".join(sorted(input()))for _ in range(n)] C=collections.Counter(L) a=0 for i in set(L): n=C[i] a+=n*(n-1)//2 print(a)
Given three integers x, m and n. Evaluate (1 + x + x^ 2 + .. + x^ m) (mod n) Input First line of the input contains a single integer T representing number of test cases that follow. For next T lines, each line contains three space separated integers x, m and n. Output Output exactly T lines each containing the...
1
t=int(input()) for i in range(t): x,m,n=map(int,raw_input().split()) if x==1: ans=(m+1)%n else: n=n*(x-1) ans=pow(x,m+1,n)-1 ans=(ans+n)%n ans=ans/(x-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
''' import math def BearAndBigBrother(): a, b = map(int, input().split(' ')) year = 0 while 1: if a > b: break else: a *= 3 b *= 2 year += 1 print(year) return None ''' def Tram(): n = int(input()) p = [0] for i in range(1...
Little X and Little Z are good friends. They always chat online. But both of them have schedules. Little Z has fixed schedule. He always online at any moment of time between a1 and b1, between a2 and b2, ..., between ap and bp (all borders inclusive). But the schedule of Little X is quite strange, it depends on the ti...
3
import sys from functools import lru_cache, cmp_to_key from heapq import merge, heapify, heappop, heappush # from math import * from collections import defaultdict as dd, deque, Counter as C from itertools import combinations as comb, permutations as perm from bisect import bisect_left as bl, bisect_right as br, bisect...
Let n be a positive integer. Let a, b, c be nonnegative integers such that a + b + c = n. Alice and Bob are gonna play rock-paper-scissors n times. Alice knows the sequences of hands that Bob will play. However, Alice has to play rock a times, paper b times, and scissors c times. Alice wins if she beats Bob in at lea...
3
import math t=int(input()) for _ in range(t): n=int(input()) a,b,c=map(int,input().split()) s=input() r=0 l=[0]*n for i in range(n): if s[i]=='R': b-=1 if b>=0: r+=1 l[i]='P' elif s[i]=='P': c-=1 if c...
Sherlock Holmes and Dr. Watson played some game on a checkered board n × n in size. During the game they put numbers on the board's squares by some tricky rules we don't know. However, the game is now over and each square of the board contains exactly one number. To understand who has won, they need to count the number...
1
n=input() table=[] def sumco(x): res=0 for i in range(n): res+=table[i][x] return res def sumci(x): return sum(table[x]) def how(x,y): return sumco(x)>sumci(y) for x in range(n): table+=[map(int,raw_input().split())] res=0 for x in range(n): for y in range(n...
AtCoDeer the deer found two positive integers, a and b. Determine whether the product of a and b is even or odd. Constraints * 1 ≤ a,b ≤ 10000 * a and b are integers. Input Input is given from Standard Input in the following format: a b Output If the product is odd, print `Odd`; if it is even, print `Even`. E...
3
a, b = (int(i) for i in input().split()) print("Odd" if (a*b)&1 else "Even")
A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay i·k dollars for the i-th banana). He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas? Input The first lin...
3
c,d,b=map(int,input().split()) print (max(0,b*(b+1)*c//2-d))
Ayush and Ashish play a game on an unrooted tree consisting of n nodes numbered 1 to n. Players make the following move in turns: * Select any leaf node in the tree and remove it together with any edge which has this node as one of its endpoints. A leaf node is a node with degree less than or equal to 1. A tree...
3
def main(): for i in range(int(input())): solve() def solve(): n, x = map(int, input().split()) a = [] c = 0 for i in range(n-1): u, v= map(int, input().split()) if u == x or v == x: c+=1 if c == 1 or n == 1: print("Ayush") return if (n) ...
Masha works in an advertising agency. In order to promote the new brand, she wants to conclude contracts with some bloggers. In total, Masha has connections of n different bloggers. Blogger numbered i has a_i followers. Since Masha has a limited budget, she can only sign a contract with k different bloggers. Of course...
3
import bisect from itertools import accumulate import os import sys import math from decimal import * from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in fi...
Vasily the Programmer loves romance, so this year he decided to illuminate his room with candles. Vasily has a candles.When Vasily lights up a new candle, it first burns for an hour and then it goes out. Vasily is smart, so he can make b went out candles into a new candle. As a result, this new candle can be used like...
3
n,m= map(int, input().split()) cnt=0 cnt+=n while(int(n/m)!=0): cnt+=int(n/m) #print(cnt) n=int(n/m)+(n%m) print(cnt)
Polycarp is very careful. He even types numeric sequences carefully, unlike his classmates. If he sees a sequence without a space after the comma, with two spaces in a row, or when something else does not look neat, he rushes to correct it. For example, number sequence written like "1,2 ,3,..., 10" will be corrected to...
3
from sys import stdin,stdout from math import gcd, ceil, sqrt ii1 = lambda: int(stdin.readline().strip()) is1 = lambda: stdin.readline().strip() iia = lambda: list(map(int, stdin.readline().strip().split())) isa = lambda: stdin.readline().strip().split() mod = 1000000007 s = is1() res = "" for j,i in enumerate(s): ...
An SNS has N users - User 1, User 2, \cdots, User N. Between these N users, there are some relationships - M friendships and K blockships. For each i = 1, 2, \cdots, M, there is a bidirectional friendship between User A_i and User B_i. For each i = 1, 2, \cdots, K, there is a bidirectional blockship between User C_i...
3
import sys import math import copy import queue input = sys.stdin.readline n,m,k = map(int,input().split()) f = [[] for _ in range(n+1)] b = [[] for _ in range(n+1)] for _ in range(m): x,y = map(int,input().split()) f[x].append(y) f[y].append(x) for _ in range(k): x,y = map(int, input().split()) b[x...
A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay i·k dollars for the i-th banana). He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas? Input The first lin...
3
k, n, w = [int(x) for x in input().split()] print(max((w + 1) * w * k // 2 - n, 0))
Boboniu likes playing chess with his employees. As we know, no employee can beat the boss in the chess game, so Boboniu has never lost in any round. You are a new applicant for his company. Boboniu will test you with the following chess question: Consider a n× m grid (rows are numbered from 1 to n, and columns are nu...
3
import math from decimal import * import random n,m,y, x = map(int, input().split()) grid = [[0 for i in range(m)]for i in range(n)] ans = [[str(y),str(x)]] grid[y-1][x-1]=1 posx, posy = x-1, y-1 for i in range(y-1): posy-=1 if(grid[posy][posx]==0): grid[posy][posx] = 1 ans.append([str(posy+1),...
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
w=input() w=int(w) if w!=2 and w//2==w/2: print('YES') else: print('NO')
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi). They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan consider...
1
from collections import defaultdict, Counter n = int(raw_input()) xd = defaultdict(int) yd = defaultdict(int) watchmen = [] for i in range(n): x, y = map(int, raw_input().split()) xd[x] += 1 yd[y] += 1 watchmen.append((x, y)) ans = 0 c = Counter(watchmen) for v in c.itervalues(): ans -= v*(v-1)/2 f...
One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are n lines in that description each of which described one goal. Eve...
3
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**10 mod = 10**9+7 dd = [(-1,0),(0,1),(1,0),(0,-1)] ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(): return [int(x) for x in sys.stdin....
It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not en...
3
n = int(input()) k = input().split() s = 0 x = '1' for i in range(n): if k[i] == '0': print('0') break elif k[i].count('0') + k[i].count('1') != len(k[i]) or k[i].count('1') >1: x = k[i] else: s+=k[i].count('0') else: print(x+'0'*s) ...
There are n robots driving along an OX axis. There are also two walls: one is at coordinate 0 and one is at coordinate m. The i-th robot starts at an integer coordinate x_i~(0 < x_i < m) and moves either left (towards the 0) or right with the speed of 1 unit per second. No two robots start at the same coordinate. Whe...
3
import sys import math #input = sys.stdin.readline imp = 'IMPOSSIBLE' t = int(input()) for test in range(t): n, m = list(map(int, input().split(" "))) xx = list(map(int, input().split(" "))) sorx = sorted(enumerate(xx), key=lambda z: z[1]) porx = [i[0] for i in sorx] invpor = [i[0] for i in sorte...
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm: * if the last digit of the number is non-zero, she decreases the number by one; * if the last digit of the number is ze...
3
n,k=map(int,input().split()) for _ in range(k): if n%10: n-=1 else: n=n//10 print(n)
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves. We know that several boy&girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair m...
1
# coding: utf-8 men = int(raw_input()) mskills = map(int, raw_input().split()) girls = int(raw_input()) gskills = map(int, raw_input().split()) ans = 0 mskills.sort() gskills.sort() for i in xrange(men): for j in xrange(girls): if gskills[j] > 0 and mskills[i] > 0: if 0 <= gskills[j] - mskills[i] <= 1 or 0 <...
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
if __name__ == "__main__": n,h=map(int,input().split(' ')) arr=list(map(int, input().split())) sm=0 for a in arr: if a<=h: sm+=1 elif a>h: sm+=2 print(sm)
You are given an array a of size n, and q queries to it. There are queries of two types: * 1 li ri — perform a cyclic shift of the segment [li, ri] to the right. That is, for every x such that li ≤ x < ri new value of ax + 1 becomes equal to old value of ax, and new value of ali becomes equal to old value of ari; ...
3
import sys f = lambda: list(map(int, sys.stdin.readline().split())) q = f()[1] a = f() d = [f() for i in range(q)][::-1] for k in f(): for t, l, r in d: if l <= k <= r: k = l + r - k if t == 2 else r if k == l else k - 1 print(a[k - 1])
Vasya and Petya are playing a simple game. Vasya thought of number x between 1 and n, and Petya tries to guess the number. Petya can ask questions like: "Is the unknown number divisible by number y?". The game is played by the following rules: first Petya asks all the questions that interest him (also, he can ask no ...
3
def eratosthenes(): # n - �����, �� �������� ����� ����� ������� ����� sieve = list(range(n + 1)) sieve[1] = 0 # ��� ���� ������ �������� ������ ����� ��������� ������� for i in sieve: if i > 1: for j in range(i + i, len(sieve), i): sieve[j] = 0 return sieve n...
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
w = int(input()) #Weight of the Watermelon if 1 <= w <= 100: if w % 2 == 0: if w <= 2: print("NO") else: print("YES") else: print("NO") else: print("NO")