problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
The only difference between easy and hard versions is the size of the input. You are given a string s consisting of n characters, each character is 'R', 'G' or 'B'. You are also given an integer k. Your task is to change the minimum number of characters in the initial string s so that after the changes there will be ...
1
# print(*yo) t = int(raw_input()) for _ in range(t): mini = 10**18 n,k = map(int,raw_input().split()) s = raw_input() count1 = 0 count2 = 0 count3 = 0 count = 0 x = 0 i = 0 while i<n: if count!=k: if (x)%3 == 0: if s[i] == 'R': count2+=...
Little boy Valera studies an algorithm of sorting an integer array. After studying the theory, he went on to the practical tasks. As a result, he wrote a program that sorts an array of n integers a1, a2, ..., an in the non-decreasing order. The pseudocode of the program, written by Valera, is given below. The input of ...
1
n=int(raw_input()) if n==1 or n==2: print -1 else: for i in xrange(n): print n-i, print
For the given integer n (n > 2) let's write down all the strings of length n which contain n-2 letters 'a' and two letters 'b' in lexicographical (alphabetical) order. Recall that the string s of length n is lexicographically less than string t of length n, if there exists such i (1 ≤ i ≤ n), that s_i < t_i, and for a...
3
t=int(input()) for _ in range(t): n,k=map(int,input().split()) c=0 z=1 while(z<k): c+=1 z+=c if k!=z: z=z-c c=c-1 q=k-z ans="a"*q ans+="b" ans+="a"*(c-q) ans+="b" ans+="a"*(n-2-(c)) print(ans[::-1])
Lee was cleaning his house for the party when he found a messy string under the carpets. Now he'd like to make it clean accurately and in a stylish way... The string s he found is a binary string of length n (i. e. string consists only of 0-s and 1-s). In one move he can choose two consecutive characters s_i and s_{i...
3
t = int(input()); for i in range(0, t): n = int(input()) s = input() position = s.rfind('10'); while position != -1: length = len(s) if position + 2 < length: if s[position + 2] == str(0): s = s[0:position+1] + s[position+2:length]; ...
This is yet another problem on regular bracket sequences. A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequenc...
1
# coding=utf-8 """ D. Скобочная последовательность ограничение по времени на тест:1 second ограничение по памяти на тест:64 megabytes ввод:standard input вывод:standard output Перед вами еще одна задача на правильные скобочные последовательности. Напомним, что скобочная последовательность называется правильной, если ...
Takahashi has decided to hold fastest-finger-fast quiz games. Kizahashi, who is in charge of making the scoreboard, is struggling to write the program that manages the players' scores in a game, which proceeds as follows. A game is played by N players, numbered 1 to N. At the beginning of a game, each player has K poi...
3
N, K, Q = map(int, input().split()) V = [0] * N for _ in range(Q): a = int(input()) V[a-1] += 1 for v in V: print('Yes' if Q-v<K else 'No')
There are n students who have taken part in an olympiad. Now it's time to award the students. Some of them will receive diplomas, some wiil get certificates, and others won't receive anything. Students with diplomas and certificates are called winners. But there are some rules of counting the number of diplomas and ce...
1
n, k = map(int, raw_input().split()) x = (n / 2) / (k + 1) print x, k * x, n - (k + 1) * x
Given are three integers N, K, and S. Find a sequence A_1, A_2, ..., A_N of N integers between 1 and 10^9 (inclusive) that satisfies the condition below. We can prove that, under the conditions in Constraints, such a sequence always exists. * There are exactly K pairs (l, r) of integers such that 1 \leq l \leq r \leq...
3
N, K, S = map(int,input().split()) if S != 10**9: A = [S]*K + [S+1]*(N-K) else: A = [S]*K + [1]*(N-K) print(*A)
IT City company developing computer games invented a new way to reward its employees. After a new game release users start buying it actively, and the company tracks the number of sales with precision to each transaction. Every time when the next number of sales is divisible by all numbers from 2 to 10 every developer ...
3
def main(): n = int(input()) ans = n // (2 * 2 * 2 * 3 * 3 * 5 * 7) print(ans) if __name__ == '__main__': main()
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s. You have to answer t independent test cases. Input The first line of the input co...
3
t = int(input()) for i in range(t): ch = input() L = [int(k) for k in ch.split()] a = L[0] b = L[1] if (a % b == 0): print(0) else: print(b - (a % b))
Along a road running in an east-west direction, there are A shrines and B temples. The i-th shrine from the west is located at a distance of s_i meters from the west end of the road, and the i-th temple from the west is located at a distance of t_i meters from the west end of the road. Answer the following Q queries: ...
3
import bisect a,b,q=map(int,input().split(' ')) INF=10**19 s=[-INF]+[int(input()) for i in range(a)]+[INF] t=[-INF]+[int(input()) for i in range(b)]+[INF] s.sort() t.sort() for i in range(q): x=int(input()) b,d=bisect.bisect(s,x),bisect.bisect(t,x) mi=INF for j in [s[b-1],s[b]]: for k in [t[d-1]...
Imp likes his plush toy a lot. <image> Recently, he found a machine that can clone plush toys. Imp knows that if he applies the machine to an original toy, he additionally gets one more original toy and one copy, and if he applies the machine to a copied toy, he gets two additional copies. Initially, Imp has only on...
1
x, y = map(int, raw_input().split()) oc = y - 1 cc = x - oc if y == 1 and x > 0: print "No" elif y == 0: print "No" elif cc >= 0: print "No" if cc % 2 else "Yes" else: print "No"
Takahashi's house has only one socket. Takahashi wants to extend it with some number of power strips, each with A sockets, into B or more empty sockets. One power strip with A sockets can extend one empty socket into A empty sockets. Find the minimum number of power strips required. Constraints * All values in inp...
3
a,b=map(int,input().split()) print((b-a-1)//(a-1)+2)
You are given a rectangular board of M × N squares. Also you are given an unlimited number of standard domino pieces of 2 × 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions: 1. Each domino completely covers two squa...
3
num=input().split(' ') print(int(int(num[0])*int(num[1])/2))
We have a string s consisting of lowercase English letters. Snuke can perform the following operation repeatedly: * Insert a letter `x` to any position in s of his choice, including the beginning and end of s. Snuke's objective is to turn s into a palindrome. Determine whether the objective is achievable. If it is ...
3
s = input() l, r = 0, len(s) - 1 ans = 0 while l < r: if s[l] != s[r]: if s[l] == 'x': ans += 1 r += 1 elif s[r] == 'x': ans += 1 l -= 1 else: print(-1) exit(0) l += 1 r -= 1 print(ans)
Tomorrow is a difficult day for Polycarp: he has to attend a lectures and b practical classes at the university! Since Polycarp is a diligent student, he is going to attend all of them. While preparing for the university, Polycarp wonders whether he can take enough writing implements to write all of the lectures and d...
3
import math for case in range(int(input())): a,b,c,d,k = map(int,input().split()) c=math.ceil(a/c) d=math.ceil(b/d) if c+d>k: print(-1) else: print(c,d)
You are given a sequence a consisting of n integers a_1, a_2, ..., a_n, and an integer x. Your task is to make the sequence a sorted (it is considered sorted if the condition a_1 ≤ a_2 ≤ a_3 ≤ ... ≤ a_n holds). To make the sequence sorted, you may perform the following operation any number of times you want (possibly ...
3
import math t = int(input()) for _ in range(t): n,x =map(int,input().split()) l= list(map(int,input().split())) cnt=0 a=l[::-1] a.sort() i=-1 for j in range(n-1,-1,-1): if a[j]==l[j]: continue else: i=j break if i==-1: print(0)...
There are N balls in a two-dimensional plane. The i-th ball is at coordinates (x_i, y_i). We will collect all of these balls, by choosing two integers p and q such that p \neq 0 or q \neq 0 and then repeating the following operation: * Choose a ball remaining in the plane and collect it. Let (a, b) be the coordinates...
3
n=int(input()) s=[list(map(int, input().split())) for i in range(n)] x=[] if n==1: print(1) exit(0) for i in range(n): for j in range(n): if i==j: continue t=(s[i][0]-s[j][0],s[i][1]-s[j][1]) x.append(t) ans = [x.count(x[i]) for i in range(len(x))] print(n-max(...
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
s=input() s1=input() s2=s.lower() s3=s1.lower() if s2<s3: print(-1) elif s2>s3: print(1) else: print(0)
Masha lives in a multi-storey building, where floors are numbered with positive integers. Two floors are called adjacent if their numbers differ by one. Masha decided to visit Egor. Masha lives on the floor x, Egor on the floor y (not on the same floor with Masha). The house has a staircase and an elevator. If Masha u...
3
x, y, z, t1, t2, t3 = map(int, input().split()) dp = abs(x - y) * t1; dl = abs(x - z) * t2 + abs(x - y) * t2 + 3 * t3; if dp < dl: print("NO") else: print("YES")
There is a very secret base in Potatoland where potato mash is made according to a special recipe. The neighbours from Porridgia decided to seize this recipe and to sell it to Pilauland. For this mission they have been preparing special agent Pearlo for many years. When, finally, Pearlo learned all secrets of espionage...
3
a=input() b=input() c=input() t=a+b+c t1=t[::-1] if(t1==t): print("YES") else: print("NO")
Given is a string S representing the day of the week today. S is `SUN`, `MON`, `TUE`, `WED`, `THU`, `FRI`, or `SAT`, for Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, and Saturday, respectively. After how many days is the next Sunday (tomorrow or later)? Constraints * S is `SUN`, `MON`, `TUE`, `WED`, `THU`,...
1
days = ["SUN","MON","TUE","WED","THU","FRI","SAT"] s = raw_input() print 7 - days.index(s)
Walking along a riverside, Mino silently takes a note of something. "Time," Mino thinks aloud. "What?" "Time and tide wait for no man," explains Mino. "My name, taken from the river, always reminds me of this." "And what are you recording?" "You see it, tide. Everything has its own period, and I think I've figured...
1
n, p = map(int, raw_input().split()) a = [int(x) if x != '.' else -1 for x in raw_input()] good = False found = 0 for i in xrange(p): for j in xrange(i, n, p): if a[j] != -1: found = a[j] for j in xrange(i, n, p): if a[j] == -1: found ^= 1 a[j] = found if...
Let quasi-palindromic number be such number that adding some leading zeros (possible none) to it produces a palindromic string. String t is called a palindrome, if it reads the same from left to right and from right to left. For example, numbers 131 and 2010200 are quasi-palindromic, they can be transformed to strin...
3
x=input() m=list(x) for i in range (len(m)): if m[len(m)-1] == '0' : del m [len(m)-1] p= False for i in range (len(m)) : if m[i]!=m[len(m)-i-1] : p=True if p == False : print("YES") else: print("NO")
You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'. You ...
1
# # n=raw_input() def numb(x): try: int(x) if x[0]=='0' and len(x)>1: return False except ValueError: return False # print numb('awsf') # # print int('asad') import re l=raw_input().replace(';',',').split(',') a=[] b=[] for i in l: # print i if numb(i)!=False:...
Vasya has found a strange device. On the front panel of a device there are: a red button, a blue button and a display showing some positive integer. After clicking the red button, device multiplies the displayed number by two. After clicking the blue button, device subtracts one from the number on the display. If at so...
3
n,m = map(int,input().split()) c = 0 while n != m: c+=1 m+=1 if m<n or m&1 else-m//2 print(c)
Ari the monster always wakes up very early with the first ray of the sun and the first thing she does is feeding her squirrel. Ari draws a regular convex polygon on the floor and numbers it's vertices 1, 2, ..., n in clockwise order. Then starting from the vertex 1 she draws a ray in the direction of each other vertex...
1
n = input() print((n - 2) ** 2)
Haiku is a genre of Japanese traditional poetry. A haiku poem consists of 17 syllables split into three phrases, containing 5, 7 and 5 syllables correspondingly (the first phrase should contain exactly 5 syllables, the second phrase should contain exactly 7 syllables, and the third phrase should contain exactly 5 syll...
3
l=['a','e','i','o','u'] for i in range(0,3): c=0 a=''.join(input().split()) for j in a: if j in l: c+=1 if i==0 and c==5: continue elif i==1 and c==7: continue elif i==2 and c==5: print('YES') else: print('NO') break
This is the hard version of the problem. The difference between the versions is the constraint on n and the required number of operations. You can make hacks only if all versions of the problem are solved. There are two binary strings a and b of length n (a binary string is a string consisting of symbols 0 and 1). In ...
3
from sys import stdin, stdout def main(): t = int(stdin.readline()) for case in range(t): n = int(stdin.readline()) a = stdin.readline() b = stdin.readline() k = 0 seq = [] flips = 0 checks = n ax, ay, d = 0, n-1, 1 by = n - 1 ...
Dreamoon likes coloring cells very much. There is a row of n cells. Initially, all cells are empty (don't contain any color). Cells are numbered from 1 to n. You are given an integer m and m integers l_1, l_2, …, l_m (1 ≤ l_i ≤ n) Dreamoon will perform m operations. In i-th operation, Dreamoon will choose a number ...
3
def res(): print(-1) exit() n,m = map(int,input().split()) l = list(map(int,input().split())) idx = [] if sum(l)<n:res() else: for i in range(m): if i+l[i]>n:res() for i in range(m-1,-1,-1): if n>min(i,m-1-i): curr = min(n-i,l[i]) idx.append(n-curr+1) ...
Due to the coronavirus pandemic, city authorities obligated citizens to keep a social distance. The mayor of the city Semyon wants to light up Gluharniki park so that people could see each other even at night to keep the social distance. The park is a rectangular table with n rows and m columns, where the cells of the...
3
for _ in range(int(input())): a,b=map(int,input().split()) x=a*b if x%2==0: print(x//2) else: print(((x-1)//2)+1)
You are given a positive integer x. Find any such 2 positive integers a and b such that GCD(a,b)+LCM(a,b)=x. As a reminder, GCD(a,b) is the greatest integer that divides both a and b. Similarly, LCM(a,b) is the smallest integer such that both a and b divide it. It's guaranteed that the solution always exists. If ther...
3
''' def gcd(x,y): if y > x: t = x x = y y = t z = x % y while ( z != 0 ): x = y y = z z = x % y return y def lcm(x,y): return int(x*y/gcd(x,y)) ''' n = int(input()) for i in range(n): a = int(input()) ''' x = 1 y = 1 f = 1 for ...
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob. Right now, Limak and Bob weigh a and b respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight. Limak eats a lot and his weight is tripled after every year, while Bob's weight...
3
'''input 1 1 ''' a, b = map(int, input().split()) k = 0 while a <= b: a *= 3 b *= 2 k += 1 print(k)
Snuke is standing on a two-dimensional plane. In one operation, he can move by 1 in the positive x-direction, or move by 1 in the positive y-direction. Let us define a function f(r, c) as follows: * f(r,c) := (The number of paths from the point (0, 0) to the point (r, c) that Snuke can trace by repeating the operati...
3
def main(): M=10**9+7 r1,c1,r2,c2=map(int,input().split()) n=r2+c2+2 fac=[0]*(n+1) fac[0]=1 for i in range(1,n+1):fac[i]=fac[i-1]*i%M f=lambda r,c:fac[r+c+2]*pow(fac[c+1],M-2,M)*pow(fac[r+1],M-2,M)-c-r-2 print((f(r2,c2)-f(r2,c1-1)-f(r1-1,c2)+f(r1-1,c1-1))%M) main()
The only difference between easy and hard versions is the size of the input. You are given a string s consisting of n characters, each character is 'R', 'G' or 'B'. You are also given an integer k. Your task is to change the minimum number of characters in the initial string s so that after the changes there will be ...
3
from sys import stdin, stdout def check_diff(s, rgb): n = len(s) arr = [] for i in range(n): if s[i] == rgb[i]: arr.append(0) else: arr.append(1) return arr q = int(stdin.readline().rstrip()) for _ in range(q): n, k = map(int, stdin.readline().rstrip().split()) s = stdin.readline().rst...
Takahashi is standing on a two-dimensional plane, facing north. Find the minimum positive integer K such that Takahashi will be at the starting position again after he does the following action K times: * Go one meter in the direction he is facing. Then, turn X degrees counter-clockwise. Constraints * 1 \leq X \leq ...
3
import math x = int(input()) d = math.gcd(360, x) print(360//d)
Kolya loves putting gnomes at the circle table and giving them coins, and Tanya loves studying triplets of gnomes, sitting in the vertexes of an equilateral triangle. More formally, there are 3n gnomes sitting in a circle. Each gnome can have from 1 to 3 coins. Let's number the places in the order they occur in the ci...
3
n = int(input()) a = 1 b = 1 mod = 1e9+7 for i in range(3*n): a = (a*3) % mod for i in range(n): b = (b*7) % mod print(int((a-b + mod) % mod))
Let's write all the positive integer numbers one after another from 1 without any delimiters (i.e. as a single string). It will be the infinite sequence starting with 123456789101112131415161718192021222324252627282930313233343536... Your task is to print the k-th digit of this sequence. Input The first and only lin...
3
e='' for i in range(1,10000): e=e+str(i) n=int(input()) print(e[n-1])
Polycarp lives on the coordinate axis Ox and travels from the point x=a to x=b. It moves uniformly rectilinearly at a speed of one unit of distance per minute. On the axis Ox at the point x=c the base station of the mobile operator is placed. It is known that the radius of its coverage is r. Thus, if Polycarp is at a ...
3
for _ in [0]*int(input()): a, b, c, r = map(int, input().split()) if a > b:a, b = b, a print(b-a-(max(min(c+r, b)-max(c-r, a), 0)))
Aiz Onsen has a bathhouse and a pool. To use the bathhouse, you need to buy a bathing ticket, and to use the pool, you need to buy a pool ticket. Prices for these tickets may vary from day to day. In addition, Aiz Onsen has the following rules. * Tickets are valid only once on the day of purchase. * If you buy 5 or mo...
3
N = int(input()) for _ in range(N): A = [] x, y, b, p = map(int, input().split()) s = x*b+y*p #全部バラ A.append(int(s)) wari = 0.8*(5*x+2*y) for i in range(1, 4): s = wari*i if b-(5*i)>0: s += 0.8*(b-(5*i))*x if p-(2*i)>0: s += 0.8*(p-(2*i))*y A.append(int(s)) print(min(A))
Snuke has N integers: 1,2,\ldots,N. He will choose K of them and give those to Takahashi. How many ways are there to choose K consecutive integers? Constraints * All values in input are integers. * 1 \leq K \leq N \leq 50 Input Input is given from Standard Input in the following format: N K Output Print the a...
3
a,b=map(int,input().split(" ")) print(max(0,a-b+1))
One day a highly important task was commissioned to Vasya — writing a program in a night. The program consists of n lines of code. Vasya is already exhausted, so he works like that: first he writes v lines of code, drinks a cup of tea, then he writes as much as <image> lines, drinks another cup of tea, then he writes <...
3
import sys from collections import OrderedDict def possible(n, k, v): s = v curr = v while curr != 0: # Invariant: At this point curr has already # been added. curr = curr // k s += curr if s >= n: return True return False def main(n, k): min_v ...
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits. Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has on...
3
i = int(input()) i = i+1 while i > 0: n = str(i) x = list(n) y = list(set(n)) if sorted(x) == sorted(y): print(i) break i += 1
Karl likes Codeforces and subsequences. He wants to find a string of lowercase English letters that contains at least k subsequences codeforces. Out of all possible strings, Karl wants to find a shortest one. Formally, a codeforces subsequence of a string s is a subset of ten characters of s that read codeforces from ...
3
a = int(input()) for i in range(41): if (a > i**10 ) & (a<= (i+1)**10): n1 = i+1 #print(n1) for j in range(11): if (n1**(j))*(((n1-1)**(10-j))*(n1!=1)+1*(n1==1)) >= a: n2 = j #print(n2) break break a = ['c', 'o', 'd', ...
You are given an array a[0 … n-1] of length n which consists of non-negative integers. Note that array indices start from zero. An array is called good if the parity of each index matches the parity of the element at that index. More formally, an array is good if for all i (0 ≤ i ≤ n - 1) the equality i mod 2 = a[i] m...
3
t = int(input()) for i in range(t): n = int(input()) ch = input() L = [int(j) for j in ch.split()] comp = 0 for k in range(n-1): if ((L[k] % 2) != (k % 2)): x = k+1 d = comp ...
Polycarp plays a well-known computer game (we won't mention its name). In this game, he can craft tools of two types — shovels and swords. To craft a shovel, Polycarp spends two sticks and one diamond; to craft a sword, Polycarp spends two diamonds and one stick. Each tool can be sold for exactly one emerald. How many...
3
import math t = int(input()) for j in range(t): temp = input() a, b = temp.split(' ') a = int(a) b = int(b) if a==0 or b == 0 : print(0) elif a>=2*b or b>=2*a: print(min(a,b)) else: print(int((a+b)/3))
Luke Skywalker got locked up in a rubbish shredder between two presses. R2D2 is already working on his rescue, but Luke needs to stay alive as long as possible. For simplicity we will assume that everything happens on a straight line, the presses are initially at coordinates 0 and L, and they move towards each other wi...
3
a, b, c, d = map(int, input().split()) print("%.10f" % max(0, (b- a) / (c + d)))
There are n students numerated from 1 to n. The level of the i-th student is a_i. You need to split the students into stable groups. A group of students is called stable, if in the sorted array of their levels no two neighboring elements differ by more than x. For example, if x = 4, then the group with levels [1, 10, ...
3
import os import sys 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 file.mode or "r" not in file.mode self.write = self.buffer.write if self.wri...
You are given an angle ang. The Jury asks You to find such regular n-gon (regular polygon with n vertices) that it has three vertices a, b and c (they can be non-consecutive) with \angle{abc} = ang or report that there is no such n-gon. <image> If there are several answers, print the minimal one. It is guarantied t...
3
import math as mt import sys,string,bisect input=sys.stdin.readline from collections import deque,defaultdict L=lambda : list(map(int,input().split())) Ls=lambda : list(input().split()) M=lambda : map(int,input().split()) I=lambda :int(input()) def dist(x,y,c,d): return (x-c)**2+(y-d)**2 def circle(x1, y1, x2,y2, ...
Given are an integer X and an integer sequence of length N: p_1, \ldots, p_N. Among the integers not contained in the sequence p_1, \ldots, p_N (not necessarily positive), find the integer nearest to X, that is, find the integer whose absolute difference with X is the minimum. If there are multiple such integers, repo...
3
X, N = map(int, input().split()) if N: P = set(map(int, input().split())) else: P = set() c = [] for i in range(102): if i not in P: c.append((abs(i - X), i)) print(min(c)[1])
A card pyramid of height 1 is constructed by resting two cards against each other. For h>1, a card pyramid of height h is constructed by placing a card pyramid of height h-1 onto a base. A base consists of h pyramids of height 1, and h-1 cards on top. For example, card pyramids of heights 1, 2, and 3 look as follows: ...
3
from __future__ import division, print_function import sys if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip import os, sys, bisect, copy from collections import defaultdict, Counter, deque #from functools import lru_cache #use @...
You know that Japan is the country with almost the largest 'electronic devices per person' ratio. So you might be quite surprised to find out that the primary school in Japan teaches to count using a Soroban — an abacus developed in Japan. This phenomenon has its reasons, of course, but we are not going to speak about ...
3
n=int(input()) for i in range(len(str(n))-1,-1,-1): x=int(str(n)[i]) if x==0: print('O-|-OOOO') if x==1: print('O-|O-OOO') if x==2: print('O-|OO-OO') if x==3: print('O-|OOO-O') if x==4: print('O-|OOOO-') ...
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
t=int(input()) while(t): t-=1 n,k = [int(i) for i in input().split()] a = [int(i) for i in input().split()] aset = set(a) if len(aset)>k: print(-1) else: ans = [] count = [0]*(n+1) for i in aset: count[i]=1 alst = list(aset) if len(alst...
There is a robot in a warehouse and n packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0, 0). The i-th package is at the point (x_i, y_i). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point ...
3
for t in range(int(input())): packages = sorted(tuple(map(int, input().split())) for i in range(int(input()))) path = '' x, y = 0, 0 ability = True for p in packages: path += 'R' * (p[0] - x) x = p[0] if p[1] - y < 0: ability = False break path...
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point x(x > 0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order ...
3
num=int(input()) print((int(num/5)) if(num%5==0) else (int(num/5+1)))
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line. Unfortunately, from time to ti...
3
arr = input().split(", ") n = len(arr) if n == 1: if len(arr[0])== 2: print(0) else: print(1) else: s = set( [arr[0][1]] + arr[1:n-1] + [arr[n-1][0]] ) print(len(s))
problem Five students, Taro, Jiro, Saburo, Shiro, and Hanako, participated in the JOI High School class. In this class, a final exam was conducted. All five people took the final exam. For students with a final exam score of 40 or higher, the final exam score was used as is. All students with a final exam score of le...
3
scores = [] for _ in range(5): score = int(input()) if score < 40: scores.append(40) else: scores.append(score) print(sum(scores)//5)
Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is n. There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains 2 apartments, every other floor contains x apartments each. Apartments are numbered starting from one, from...
3
import math num = int(input()) for i in range(num): n, x = tuple(map(int, input().split())) if n <= 2: print(1) else: print(math.ceil((n - 2) / x) + 1)
New Year is coming and you are excited to know how many minutes remain before the New Year. You know that currently the clock shows h hours and m minutes, where 0 ≤ hh < 24 and 0 ≤ mm < 60. We use 24-hour time format! Your task is to find the number of minutes before the New Year. You know that New Year comes when the...
3
num = int(input()) arr = [] for i in range(num): arr.append(input()) arr = [[int(i) for i in c.split(" ")] for c in arr] for i in range(num): print(1440 - 60 * arr[i][0] - arr[i][1])
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them. Input The first line contains integ...
3
n = int(input()) s = input() ctr = 0 s = list(s) for i in range(len(s)-1): if(s[i]==s[i+1]): ctr += 1 print(ctr)
Polycarp has invited n friends to celebrate the New Year. During the celebration, he decided to take a group photo of all his friends. Each friend can stand or lie on the side. Each friend is characterized by two values h_i (their height) and w_i (their width). On the photo the i-th friend will occupy a rectangle h_i ...
3
import sys def correctPlacement(n, fren): fren.sort() # print(fren) ans = ['-1']*n # print(fren) # print(ans) j = 0 k = -1 for i in range(n): while fren[j][0] != fren[i][0]: if k == -1 or fren[j][1] < fren[k][1]: k = j j += 1 if k != -1 and fren[k][1] < fren[i][1]: ans[fren[i][2]-1] = str(fre...
The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups. Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime. If there is no police offi...
3
n = int(input()) a = list(map(int, input().split())) sum = 0 set = 0 for i in a: if i==-1 and sum==0: set += 1 elif i>0 : sum +=i elif i == -1 and sum > 0: sum -=1 print(set)
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 _ in range(n): inp = input() if len(inp) <= 10: print(inp) continue print(f'{inp[0]}{len(inp) - 2}{inp[-1]}')
We just discovered a new data structure in our research group: a suffix three! It's very useful for natural language processing. Given three languages and three suffixes, a suffix three can determine which language a sentence is written in. It's super simple, 100% accurate, and doesn't involve advanced machine learni...
3
n = int(input()) for i in range(n): q = input() if q[-2:]=="po": print("FILIPINO") elif q[-4:] == "desu" or q[-4:] == "masu": print("JAPANESE") else: print("KOREAN")
Write a program which solve a simultaneous equation: ax + by = c dx + ey = f The program should print x and y for given a, b, c, d, e and f (-1,000 ≤ a, b, c, d, e, f ≤ 1,000). You can suppose that given equation has a unique solution. Input The input consists of several data sets, 1 line for each data set. In a ...
3
from decimal import Decimal, ROUND_HALF_UP while True: try: a, b, c, d, e, f = map(float, input().split()) x = (c * e - b * f) / (a * e - b * d) + 0.0 y = (c * d - a * f) / (b * d - a * e) + 0.0 print(Decimal(str(x)).quantize(Decimal('0.001'), rounding=ROUND_HALF_UP), Decimal(str(y))...
You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") a and b. Then you try to turn a into b using two types of operations: * Write parity(a...
1
c=lambda:raw_input().count('1')+1 print['YES','NO'][c()|1<c()]
Some dwarves that are finishing the StUDY (State University for Dwarven Youngsters) Bachelor courses, have been told "no genome, no degree". That means that all dwarves should write a thesis on genome. Dwarven genome is far from simple. It is represented by a string that consists of lowercase Latin letters. Dwarf Mish...
3
s1=input();s2=input();l=[];m=min(len(s2),len(s1)) for i in range(m): if s1[i]!=s2[i]:l.append(i) if len(l)>1: b=s1[:l[0]]+s1[l[1]:l[1]+1]+s1[l[0]+1:l[1]]+s1[l[0]:l[0]+1]+s1[l[1]+1:] else:b='' if b==s2:print('YES') else:print('NO')
For a given sequence A = {a0, a1, ... , an-1}, find the length of the longest increasing subsequnece (LIS) in A. An increasing subsequence of A is defined by a subsequence {ai0, ai1, ... , aik} where 0 ≤ i0 < i1 < ... < ik < n and ai0 < ai1 < ... < aik. Constraints * 1 ≤ n ≤ 100000 * 0 ≤ ai ≤ 109 Input n a0 a1 : ...
3
from bisect import bisect_left n = int(input()) a = [int(input()) for i in range(n)] dp = [0 for i in range(n)] dp[0] = a[0] length = 1 for i in range(1, n): if dp[length-1] < a[i]: dp[length] = a[i] length += 1 else: dp[bisect_left(dp[:length],a[i])] = a[i] print(length)
You are planning to build housing on a street. There are n spots available on the street on which you can build a house. The spots are labeled from 1 to n from left to right. In each spot, you can build a house with an integer height between 0 and h. In each spot, if a house has height a, you will gain a^2 dollars fro...
3
n,h,m = map(int, input().split()) ls = [h]*n profit = 0 for i in range(m): l, r, x = map(int,input().split()) currentSpot = l while currentSpot < r+1: if ls[currentSpot-1] > x: ls[currentSpot-1] = x currentSpot += 1 for i in ls: profit += i**2 print(profit)
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth. Now Diamond has given Bort a string consisting of only uppercase English letters of length n. There is a great number of "QAQ" in the string (Diamond is so cute!). <image> illustration by 猫屋 https://twitter.com/nekoy...
3
s=input() n=len(s) cont=0 for i in range(n): for j in range(i+1,n): for k in range(j+1,n): if s[i]=="Q" and s[j]=="A" and s[k]=="Q": cont+=1 print(cont)
You are given a string s. Each character is either 0 or 1. You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met. You may eras...
3
n = int(input()) for i in range(n): s = input() k = len(s) a = 0 b = k-1 if "1" in s: while a < k and s[a] == "0": a += 1 while b >= 0 and s[b] == "0": b -= 1 print(b-a+1-s[a:b+1].count("1")) else: print(0)
Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number n. How many times can Gerald put a spell on it until the number becomes one-di...
3
n = input() def convert(n): n = list(n) n = [int(d) for d in n] return str(sum(n)) count = 0 while len(n)>1: n = convert(n) count += 1 print(count)
Once Bob needed to find the second order statistics of a sequence of integer numbers. Lets choose each number from the sequence exactly once and sort them. The value on the second position is the second order statistics of the given sequence. In other words it is the smallest element strictly greater than the minimum. ...
3
liczba = int(input()) lista=list() wejscie = input() count = 0 wez = wejscie.split() we = map(int,wez) we2 = sorted(we) min = we2[0] for i in range(1,len(we2)): if we2[i] > we2[0]: print (we2[i]) break else: count +=1 if count == len(we2) - 1: print ("NO")
Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first n. He writes down the followin...
3
a=input().split() n=int(a[0]) k=int(a[1]) x=0 if n%2==0: x=n/2 else: x=n//2+1 y=1 z=0 if k<=x: y=1+(k-1)*2 print(int(y)) elif k>x: z=(k-x)*2 print(int(z))
You have a given integer n. Find the number of ways to fill all 3 × n tiles with the shape described in the picture below. Upon filling, no empty spaces are allowed. Shapes cannot overlap. <image> This picture describes when n = 4. The left one is the shape and the right one is 3 × n tiles. Input The only line cont...
3
# -*- coding: utf-8 -*- """ Created on Tue Jun 11 18:14:57 2019 @author: Hamadeh """ class cinn: def __init__(self): self.x=[] def cin(self,t=int): if(len(self.x)==0): a=input() self.x=a.split() self.x.reverse() return self.get(t) def get(self,t)...
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
from sys import stdin x=stdin.readline() x=int(x) if x%2==0 and x!=2: print('YES') else: print('NO')
There are n districts in the town, the i-th district belongs to the a_i-th bandit gang. Initially, no districts are connected to each other. You are the mayor of the city and want to build n-1 two-way roads to connect all districts (two districts can be connected directly or through other connected districts). If two...
3
import sys import math def II(): return int(sys.stdin.readline()) def LI(): return list(map(int, sys.stdin.readline().split())) def MI(): return map(int, sys.stdin.readline().split()) def SI(): return sys.stdin.readline().strip() t = II() for q in range(t): n = II() a = LI() if len(set(a)) == 1: print("N...
Nauuo is a girl who loves writing comments. One day, she posted a comment on Codeforces, wondering whether she would get upvotes or downvotes. It's known that there were x persons who would upvote, y persons who would downvote, and there were also another z persons who would vote, but you don't know whether they woul...
3
x, y, z = map(int, input().split()) if abs(x - y) < z or abs(x - y) == z and z > 0: print("?") elif abs(x - y) == z and z == 0: print("0") else: if x < y: print("-") elif x == y: print("0") else: print("+")
You are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph. Your task is to choose at most ⌊n/2⌋ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at l...
3
import math from collections import defaultdict as dd def printTree(s): q = [s] visited[s] = 1 while(q): cur = q.pop(-1) for i in graph[cur]: if visited[i] == 0: visited[i] = 1 print(cur, i) q.append(i) n, m = [int(i) for i in in...
Consider writing each of the integers from 1 to N \times M in a grid with N rows and M columns, without duplicates. Takahashi thinks it is not fun enough, and he will write the numbers under the following conditions: * The largest among the values in the i-th row (1 \leq i \leq N) is A_i. * The largest among the value...
3
import sys read = sys.stdin.read readline = sys.stdin.readline N, M = map(int, readline().split()) A = list(map(int, readline().split())) + [0] B = list(map(int, readline().split())) + [0] mod = 10 ** 9 + 7 A.sort() B.sort() row = 0 # ある数字を書き込むことが可能な行の数 col = 0 available = 0 s = N * M answer = 1 for i in range(N * M...
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s. You have to answer t independent test cases. Input The first line of the input co...
3
import math cases = int(input()) for i in range(cases): data = list(map(int, input().split(' '))) if data[0] % data[1] != 0: print(data[1]*math.ceil(data[0]/data[1])-data[0]) else: print(0)
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second. One day in 230 AD Shapur was trying to find out if any one can possibly do...
1
def ufm(): n = raw_input() a = list(n) m = raw_input() b = list(m) c = str() for i in range(len(a)): if a[i] == b[i]: c += '0' else: c += '1' print(c) ufm()
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
weight = input() weight = int(weight) if weight % 2 == 0 and weight > 2: print("Yes") else: print("No")
Write a program to simulate rolling a dice, which can be constructed by the following net. <image> <image> As shown in the figures, each face is identified by a different label from 1 to 6. Write a program which reads integers assigned to each face identified by the label and a sequence of commands to roll the d...
3
u, s, e, w, n, d = list(map(int, input().split())) insts = input() for inst in insts: if inst == 'N': u, s, n, d = s, d, u, n elif inst == 'E': u, e, w, d = w, u, d, e elif inst == 'S': u, s, n, d = n, u, d, s elif inst == 'W': u, e, w, d = e, d, u, w print(u)
Panda had recently learnt about Bit manipulation and logic gates,now he is very excited about it.One day he came across a very interesting question: Given two numbers,xor them and then in resulting number find the number of set bits.If number of set bits are even then print "YES" otherwise "NO".As he is unable to solve...
1
t = int(input ()) while t>0: a ,b = map(int,raw_input().split()) c = a^b d =bin(c) sub=str(d) if ((sub[2:].count('1')) %2 == 0): print "YES" else: print "NO" t=t-1
Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yy...
1
t = [] for x in raw_input(): if t and x == t[-1]: t.pop() else: t.append(x) print ''.join(t)
Vasya has got many devices that work on electricity. He's got n supply-line filters to plug the devices, the i-th supply-line filter has ai sockets. Overall Vasya has got m devices and k electrical sockets in his flat, he can plug the devices or supply-line filters directly. Of course, he can plug the supply-line filt...
3
read = lambda:map(int, input().split()) n,m,k = read() a = sorted(read()) s = sum(a) if m<=k: print(0) elif k+s-n<m: print(-1) else: t = k result = 0 for i in range(n-1, -1, -1): t += a[i] - 1 result += 1 #print('i='+str(i)+' t='+str(t)+' result='+str(result)) if t>=m...
Takahashi will take part in an eating contest. Teams of N members will compete in this contest, and Takahashi's team consists of N players numbered 1 through N from youngest to oldest. The consumption coefficient of Member i is A_i. In the contest, N foods numbered 1 through N will be presented, and the difficulty of ...
3
def main(): n,k,*a=map(int,open(0).read().split()) a,f=sorted(a[:n])[::-1],sorted(a[n:]) ok=10**12 ng=-1 while abs(ok-ng)>1: mid=(ok+ng)//2 l=k for b,g in zip(a,f): if b*g>mid: l-=b-mid//g if l<0:ng=mid else:ok=mid print(ok) mai...
For an array a of integers let's denote its maximal element as max(a), and minimal as min(a). We will call an array a of k integers interesting if max(a) - min(a) ≥ k. For example, array [1, 3, 4, 3] isn't interesting as max(a) - min(a) = 4 - 1 = 3 < 4 while array [7, 3, 0, 4, 3] is as max(a) - min(a) = 7 - 0 = 7 ≥ 5. ...
3
for i in range(int(input())): n = int(input()) *a, = map(int, input().split()) for i in range(1, n): if abs(a[i] - a[i - 1]) > 1: print('YES') print(i, i + 1) break else: print('NO')
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
string = raw_input() print string[0].upper() + string[1: ]
Karl likes Codeforces and subsequences. He wants to find a string of lowercase English letters that contains at least k subsequences codeforces. Out of all possible strings, Karl wants to find a shortest one. Formally, a codeforces subsequence of a string s is a subset of ten characters of s that read codeforces from ...
3
import math ttt = int(input()) k = ttt ** .1 a = [math.floor(k)] * 10 for i in range(10): if (math.ceil(k) ** i) * (math.floor(k) ** (10 - i)) >= ttt: break a[i] += 1 print("c" *(a[9]) + "o" * (a[8]) + "d" * (a[2]) + "e" * (a[3]) + "f"*(a[4]) + "o" * (a[5]) + "r"*(a[6]) + "c"* (a[7]) + "e" * (a[1]) + "...
You are asked to watch your nephew who likes to play with toy blocks in a strange way. He has n boxes and the i-th box has a_i blocks. His game consists of two steps: 1. he chooses an arbitrary box i; 2. he tries to move all blocks from the i-th box to other boxes. If he can make the same number of blocks in ...
1
'''input 3 3 3 2 2 4 2 2 3 2 3 0 3 0 ''' RI = lambda: [int(_x) for _x in raw_input().split()] for _ in range(input()): n = input() A=RI() a1 = max(A) s = sum(A) if a1*(n-1) >= s: print a1*(n-1) - s else: print (-s)%(n-1)
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=map(int,input().split()) queue=list(input().strip()) cpqueue=queue.copy() for j in range(t): for i in range(1,n): if queue[i-1]=='B' and queue[i]=='G': cpqueue[i-1],cpqueue[i]=cpqueue[i],cpqueue[i-1] queue=cpqueue.copy() print(''.join(cpqueue))
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...
3
cases=int(input()) for i in range(cases): lenth=int(input()) orange=list(map(int,input().split())) candy=list(map(int,input().split())) total=0 random=0 first=min(orange) second=min(candy) for j in range(lenth): orange[j]-=first for j in range(0,lenth): candy[j]-=seco...
"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 = input().split() scores = input().split() limit = int(scores[int(k)-1]) count = 0 for i in range(int(n)): if (int(scores[i]) > 0): if (int(scores[i]) >= limit): count = count+1 print(count)
A ball will bounce along a number line, making N + 1 bounces. It will make the first bounce at coordinate D_1 = 0, and the i-th bounce (2 \leq i \leq N+1) at coordinate D_i = D_{i-1} + L_{i-1}. How many times will the ball make a bounce where the coordinate is at most X? Constraints * 1 \leq N \leq 100 * 1 \leq L_i ...
3
n,x=map(int,input().split()) l=list(map(int,input().split())) s=0 cnt=1 for i in l: if s+i<=x: s+=i cnt+=1 else:break print(cnt)
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy...
3
x=int(input()) g=[] h=[] j=[] for i in range(x): y=[int(a) for a in input().split()] b=y[0] c=y[1] d=y[2] g.append(b) h.append(c) j.append(d) if sum(g)==0 and sum(h)==0 and sum(j)==0: print("YES") else: print("NO")
Polycarp has an array a consisting of n integers. He wants to play a game with this array. The game consists of several moves. On the first move he chooses any element and deletes it (after the first move the array contains n-1 elements). For each of the next moves he chooses any element with the only restriction: its...
3
from math import * def sumx(z,t): count = 0 for i in range(t): count = count + z[i] return count n = int(input()) a = list(map(int,input().split())) b =[] c =[] for i in a: if i % 2 == 0: b.append(i) else: c.append(i) d = sorted(b) e = sorted(c) f = abs(len(d)-len(e)) if f ==...
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
a = int(input()) c = 0 list = [] for i in range(a): x,y = input().split(" ") x = int(x) y = int(y) c = c - x + y list.append(c) print(max(list))
You are given a rectangular board of M × N squares. Also you are given an unlimited number of standard domino pieces of 2 × 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions: 1. Each domino completely covers two squa...
3
#DominoPiling.py M,N=[int(x) for x in input().split()] print(int(M*N/2))