problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it:
* deletes all the vowels,
* inserts a character "." before each consonant,
* repl... | 3 | b = input().rstrip()
b = b.lower()
a = list(b)
c = []
for i in range(len(a)):
if a[i] == 'a' or a[i] == 'o' or a[i] == 'y' or a[i] == 'e' or a[i] == 'u' or a[i] == 'i' :
continue
else:
c.append('.')
c.append(a[i])
ans = ''
ans = ans.join(c)
print(ans) |
Santa has n candies and he wants to gift them to k kids. He wants to divide as many candies as possible between all k kids. Santa can't divide one candy into parts but he is allowed to not use some candies at all.
Suppose the kid who recieves the minimum number of candies has a candies and the kid who recieves the max... | 3 | t=int(input())
for i in range(t):
n,k=map(int,input().split())
tot=n-n%k;
tot=tot+min(k/2,n%k)
print(int(tot))
|
Even if the world is full of counterfeits, I still regard it as wonderful.
Pile up herbs and incense, and arise again from the flames and ashes of its predecessor — as is known to many, the phoenix does it like this.
The phoenix has a rather long lifespan, and reincarnates itself once every a! years. Here a! denotes ... | 3 | a, b = map(int, input().split())
a += 1
n = 1
while a < b + 1:
n *= a % 10
n %= 10
a += 1
if n == 0:
break
print(n)
|
We have a sequence of length N consisting of non-negative integers. Consider performing the following operation on this sequence until the largest element in this sequence becomes N-1 or smaller. (The operation is the same as the one in Problem D.)
* Determine the largest element in the sequence (if there is more than... | 3 | N = int(input())
A = [int(x) for x in input().split()]
ans = 0
while True:
max_A = max(A)
if max_A < N:
break
S = sum(a // N for a in A)
ans += S
for i in range(N):
A[i] = A[i] - (A[i] // N) * N + (S - (A[i] // N))
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 | n=int(input())
a=0
s=0
for i in range(n):
b=list(map(int,input().split()))
s=s-b[0]+b[1]
if(s>a):
a=s
print(a)
|
You are given a huge integer a consisting of n digits (n is between 1 and 3 ⋅ 10^5, inclusive). It may contain leading zeros.
You can swap two digits on adjacent (neighboring) positions if the swapping digits are of different parity (that is, they have different remainders when divided by 2).
For example, if a = 032... | 3 | for t in range(int(input())):
s = input()
n = len(s)
l = [int(j) for j in list(s)]
o = []
e = []
for i in range(n):
if l[i]%2==0:
e.append(l[i])
else:
o.append(l[i])
i = 0
j = 0
ans = [0 for i in range(n)]
while(i<len(o) and j<len(e)):
if e[j]>o[i]:
ans[i+j] = o[i]
i += 1
else:
ans[i+j]... |
The only difference between easy and hard versions are constraints on n and k.
You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most k most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals 0... | 3 | import queue
n ,s = map(int,input().split())
arr = list(map(int,input().split()))
m = []
st = set()
L = queue.Queue(maxsize=s)
for i in range(n):
if L.full()!= True and arr[i] not in st:
st.add(arr[i])
L.put(arr[i])
elif L.full()== True and arr[i] not in st:
x = L.get()
st.remove... |
There is a train going from Station A to Station B that costs X yen (the currency of Japan).
Also, there is a bus going from Station B to Station C that costs Y yen.
Joisino got a special ticket. With this ticket, she can take the bus for half the fare if she travels from Station A to Station B by train and then trav... | 3 | a,b = map(int,input().split())
print(a + int(b / 2)) |
There are N boxes arranged in a circle. The i-th box contains A_i stones.
Determine whether it is possible to remove all the stones from the boxes by repeatedly performing the following operation:
* Select one box. Let the box be the i-th box. Then, for each j from 1 through N, remove exactly j stones from the (i+j)-... | 3 | import sys
def debug(x, table):
for name, val in table.items():
if x is val:
print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr)
return None
def solve():
N = int(input())
A = [int(i) for i in input().split()]
K, r = divmod(sum(A), N * (N+1) // 2)
if r != 0:
... |
Kefa wants to celebrate his first big salary by going to restaurant. However, he needs company.
Kefa has n friends, each friend will agree to go to the restaurant if Kefa asks. Each friend is characterized by the amount of money he has and the friendship factor in respect to Kefa. The parrot doesn't want any friend t... | 3 | class MaximumFriendshipWithinMoneyRangeProblem:
def __init__(self):
self.numFriends, self.moneyRange, self.friends = self.getInput()
self.solution = self.computeMaximumFriendshipWithinMoneyRange()
def getInput(self):
numFriends, moneyDistance = map(int, input().split())
friends... |
A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not.
Ahcl wants to construct a beautiful string. He has a string s, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each c... | 3 | t=int(input())
while (t>0):
t=t-1
s=input()
if ('aa' in s or 'bb' in s or 'cc' in s):
print("-1")
else:
s=list(s)
s.append(0)
s.insert(0,0)
a=['a','b','c']
for i in range(len(s)):
if (s[i]=='?'):
for j in a:
... |
Vova is playing a computer game. There are in total n turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is k.
During each turn Vova can choose what to do:
* If the current charge of his laptop battery is strictly gre... | 3 | # print("Hello World!")
for _ in range(int(input())):
k,n,a,b=map(int,input().split())
ans=(k-1-b*n)/(a-b)
if ans<0:
print(-1)
else:
print(min(int(ans),n)) |
You are given an array a_1, a_2, ... , a_n, which is sorted in non-decreasing order (a_i ≤ a_{i + 1}).
Find three indices i, j, k such that 1 ≤ i < j < k ≤ n and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to a_i, a_j and a_k (for example it is possible to... | 3 | for i in range(int(input())):
n=int(input())
arr=list(map(int,input().split()))
flag=0
for i in range(len(arr)-1):
for j in range(i+1,len(arr)-1):
if arr[i]+arr[j]<=arr[len(arr)-1]:
flag=1
print(i+1,j+1,len(arr))
m=len(arr)
... |
Input
The only line of the input contains a 7-digit hexadecimal number. The first "digit" of the number is letter A, the rest of the "digits" are decimal digits 0-9.
Output
Output a single integer.
Examples
Input
A278832
Output
0
Input
A089956
Output
0
Input
A089957
Output
1
Input
A1440... | 3 | import bisect, collections
def solution():
n = input().strip()
if int(n[-1]) % 2 == 0:
print("0")
else:
print("1")
def main():
# T = int(input().strip())
for _ in range(1):
solution()
if __name__ == "__main__":
main() |
Vasya has found a piece of paper with a coordinate system written on it. There are n distinct squares drawn in this coordinate system. Let's number the squares with integers from 1 to n. It turned out that points with coordinates (0, 0) and (ai, ai) are the opposite corners of the i-th square.
Vasya wants to find such... | 3 | [n, k] = [int(i) for i in input().split()]
a = sorted([int(i) for i in input().split()])[::-1]
if k-1>=0 and k<=n:
print(a[k-1], 0)
else:
print(-1)
|
Leo has developed a new programming language C+=. In C+=, integer variables can only be changed with a "+=" operation that adds the right-hand side value to the left-hand side variable. For example, performing "a += b" when a = 2, b = 3 changes the value of a to 5 (the value of b does not change).
In a prototype progr... | 3 | t = int(input())
for i in range(t):
a,b,n = map(int,input().split(' '))
count = 0
a1 = max(a,b)
b1 = min(a,b)
while(a1 <= n):
b1 = a1+b1
a1,b1 = b1,a1
count+=1
print(count)
|
You are given a string s of length n, which consists only of the first k letters of the Latin alphabet. All letters in string s are uppercase.
A subsequence of string s is a string that can be derived from s by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD... | 3 | n,k=[int(x) for x in input().split()]
s=input()
value=[0]*k
for i in range(0,n):
x= (ord(s[i])-65)
value[x]+=1
m=min(value)
print(m*k)
|
A class of students wrote a multiple-choice test.
There are n students in the class. The test had m questions, each of them had 5 possible answers (A, B, C, D or E). There is exactly one correct answer for each question. The correct answer for question i worth a_i points. Incorrect answers are graded with zero points.... | 3 | from sys import stdin,stdout
for _ in range(1):#int(stdin.readline())):
# n=int(stdin.readline())
n,q=list(map(int,stdin.readline().split()))
s = [input() for _ in range(n)];ans=0
a=list(map(int,stdin.readline().split()))
for j in range(q):
ch={};mx=0
for i in range(n):
c... |
On his free time, Chouti likes doing some housework. He has got one new task, paint some bricks in the yard.
There are n bricks lined in a row on the ground. Chouti has got m paint buckets of different colors at hand, so he painted each brick in one of those m colors.
Having finished painting all bricks, Chouti was s... | 3 | # ========= /\ /| |====/|
# | / \ | | / |
# | /____\ | | / |
# | / \ | | / |
# ========= / \ ===== |/====|
# code
def main():
from math import factorial as fac
n,m,k = map(int , input().split())
ans = fac(n... |
An adult game master and N children are playing a game on an ice rink. The game consists of K rounds. In the i-th round, the game master announces:
* Form groups consisting of A_i children each!
Then the children who are still in the game form as many groups of A_i children as possible. One child may belong to at m... | 3 | from math import floor,ceil
K = int(input())
A = [int(x) for x in input().split()]
A.reverse()
jmax, jmin = 2,2
for i in range(0,K):
mmax,mmin = jmax,jmin
if mmin % A[i] != 0:
if (mmin + (A[i] - (mmin % A[i]))) > mmax:
print(-1)
exit()
jmin = ceil(jmin / A[i]) * A[i]
jm... |
A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not.
You are given a string s of length n, consisting of digits.
In one operation you can delete any character from strin... | 3 | # import math
# import sys
T = int(input().strip())
mod = 1000000007
for t in range(T):
n = int(input().strip())
#a = [int(x) for x in input().strip().split(" ")]
s = input().strip()
ans = False
for i in range(n):
if s[i]=='8':
if (n-i)>=11:
ans = True
break
if ans:
print("YES")
else:
print("NO"... |
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made lik... | 3 | a = int(input())
for i in range (a):
b = input()
c = len(b)
if c > 10:
print(b[0] + str(c - 2) + b[-1])
else:
print(b) |
n participants of the competition were split into m teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends.
Your task is to write a program that will find the minimum and the maximum number of pairs of friends that could ha... | 3 | num_de_participantes, num_de_times = map(int, input().split())
part_por_time = (num_de_participantes // num_de_times) - 1
aux1 = ((part_por_time * (part_por_time + 1)) // 2)
aux2 = (((part_por_time + 2) * (part_por_time + 1)) // 2)
resto_part_por_time = num_de_participantes % num_de_times
times_menos_resto = num_de_ti... |
You have array of n numbers a_{1}, a_{2}, …, a_{n}.
Rearrange these numbers to satisfy |a_{1} - a_{2}| ≤ |a_{2} - a_{3}| ≤ … ≤ |a_{n-1} - a_{n}|, where |x| denotes absolute value of x. It's always possible to find such rearrangement.
Note that all numbers in a are not necessarily different. In other words, some numb... | 3 | for ii in range(int(input())):
n = int(input())
l = [int(i) for i in input().split()]
x = n //2
ans = []
a = sorted(l)
for i in range(x+1):
if i == 0 : ans.append(a[x])
if i != 0 and i != x :
ans.append(a[x-i])
ans.append(a[x+i])
if i == x :
... |
Let us define the beauty of a sequence (a_1,... ,a_n) as the number of pairs of two adjacent elements in it whose absolute differences are d. For example, when d=1, the beauty of the sequence (3, 2, 3, 10, 9) is 3.
There are a total of n^m sequences of length m where each element is an integer between 1 and n (inclusi... | 3 | n,m,d = map(int, input().split())
s = (2-(d==0))*(m-1)*(n-d)
t = n**2
print(s/t) |
Captain Bill the Hummingbird and his crew recieved an interesting challenge offer. Some stranger gave them a map, potion of teleportation and said that only this potion might help them to reach the treasure.
Bottle with potion has two values x and y written on it. These values define four moves which can be performed... | 3 | x1,y1,x2,y2 = [int(i) for i in input().split()]
xx,yy=[int(i) for i in input().split()]
if abs(x1 - x2) % xx != 0 or abs(y1 - y2) % yy != 0:
print('NO')
else:
if (abs(x1 - x2) / xx) % 2 == abs(y1 - y2) / yy % 2:
print('YES')
else:
print('NO') |
A telephone number is a sequence of exactly 11 digits such that its first digit is 8.
Vasya and Petya are playing a game. Initially they have a string s of length n (n is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it fro... | 3 | n=int(input())
s=input()
p=(n-11)//2
count=0
for i in range(2*p+1):
if(s[i]=='8'):
count+=1
if count>p:
print("YES")
else:
print("NO")
|
Colonel has n badges. He wants to give one badge to every of his n soldiers. Each badge has a coolness factor, which shows how much it's owner reached. Coolness factor can be increased by one for the cost of one coin.
For every pair of soldiers one of them should get a badge with strictly higher factor than the secon... | 1 | n = int(raw_input())
a = map(int,raw_input().split(" "))
distinct = [0 for i in range(2*n+1)]
a.sort()
cost = 0
for ai in a:
while distinct[ai] == 1:
ai += 1
cost += 1
distinct[ai] = 1
print cost |
There are N mountains in a circle, called Mountain 1, Mountain 2, ..., Mountain N in clockwise order. N is an odd number.
Between these mountains, there are N dams, called Dam 1, Dam 2, ..., Dam N. Dam i (1 \leq i \leq N) is located between Mountain i and i+1 (Mountain N+1 is Mountain 1).
When Mountain i (1 \leq i \l... | 3 | N = int(input())
A = tuple(map(int, input().split()))
rain = [None]*N
rain[0] = sum(A) - 2*(sum(A[1:N-1:2]))
for i in range(1, N):
rain[i] = 2*A[i-1] - rain[i-1]
print(*rain) |
You have been given a String S. You need to find and print whether this string is a palindrome or not. If yes, print "YES" (without quotes), else print "NO" (without quotes).
Input Format
The first and only line of input contains the String S. The String shall consist of lowercase English alphabets only.
Output Form... | 1 | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
name = str(raw_input(''))
if name == name[::-1]:
print "YES\n"
else:
print "NO\n" |
One way to create a task is to learn from life. You can choose some experience in real life, formalize it and then you will get a new task.
Let's think about a scene in real life: there are lots of people waiting in front of the elevator, each person wants to go to a certain floor. We can formalize it in the following... | 1 | n,k = map(int,raw_input().split())
f = sorted(map(int,raw_input().split()))[::-1]
ans = 0
while f:
ans += (max(f[:k])-1)*2
f[:k] = []
print ans |
Bessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play!
More specifically, he wants to get from (0,0) to (x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance betw... | 3 | """
Author : thekushalghosh
Team : CodeDiggers
"""
import sys,math
input = sys.stdin.readline
############ ---- USER DEFINED INPUT FUNCTIONS ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(s[:len(s) - 1])
def i... |
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.
The language is that peculiar as it has exactly one variable, called x. Also, there are two operations:
* Operation ++ increases the value of variable x by 1.
* Operation -- decreases the value of variable x by 1.... | 1 | res=0;
for i in range(input()):
s=raw_input()
if(s.find('+')<>-1):
res += 1
elif(s.find('-')<>-1):
res -= 1
print res |
You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order).
Input
The only line of input contains a string s of length between 1 and 105 consisting of uppercase Latin letters.
Output
Print "YES" (without the quot... | 3 | s=str(input())
a=s.find('AB')
b=s.rfind('BA')
if(abs(a-b)>1 and min(a,b)>=0):
print('YES')
exit()
a=s.rfind('AB')
b=s.find('BA')
if(abs(a-b)>1 and min(a,b)>=0):
print('YES')
exit()
print('NO') |
We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer t Т-prime, if t has exactly three distinct positive divisors.
You are given an array of n positive integers. For each of them determine whether it is Т-prime or not.
Input
The f... | 3 | def get_prime(upper):
upper += 1
p = [0] * upper
primes = [2]
for i in range(3, upper, 2):
if p[i]:
continue
primes.append(i)
for j in range(i * 2, upper, i):
p[j] = 1
return primes
def main():
t = set([p * p for p in get_prime(int(1E6))])
_ = input()
nums = list(map(int, input().split()))
print... |
You are both a shop keeper and a shop assistant at a small nearby shop. You have n goods, the i-th good costs a_i coins.
You got tired of remembering the price of each product when customers ask for it, thus you decided to simplify your life. More precisely you decided to set the same price for all n goods you have.
... | 3 | import math
q = int(input())
for i in range(q):
n = int(input())
print(math.ceil((sum(map(int,input().split())))/n))
|
You are given a matrix a consisting of positive integers. It has n rows and m columns.
Construct a matrix b consisting of positive integers. It should have the same size as a, and the following conditions should be met:
* 1 ≤ b_{i,j} ≤ 10^6;
* b_{i,j} is a multiple of a_{i,j};
* the absolute value of the dif... | 3 | """
#If FastIO not needed, use this and don't forget to strip
#import sys, math
#input = sys.stdin.readline
"""
import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
import time
from types import GeneratorType
BUFSIZE = 8192
class FastIO(IOBase):
newl... |
There are n walruses sitting in a circle. All of them are numbered in the clockwise order: the walrus number 2 sits to the left of the walrus number 1, the walrus number 3 sits to the left of the walrus number 2, ..., the walrus number 1 sits to the left of the walrus number n.
The presenter has m chips. The presenter... | 3 | n,m=map(int,input().split())
i=1
while i<=m:
m-=i
i+=1
if i==n and m>=n:
i=1
if m>=n:
m-=n
if m==0:
break
if n==1:
m=0
print(m) |
A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not.
The next prime number after x is the smallest prime number greater than x. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that ... | 3 | n,m = map(int, input().split())
p = 0
for i in range(n+1, m+1):
f = 0
for j in range(i//2, 1, -1):
if i % j == 0:
f = 1
break
if f == 0:
p = i
break
if p == m:
print("YES")
else:
print("NO")
|
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is ... | 3 | s = list(input().strip())
piv = s.index('^')
torque = 0
for i in range(len(s)):
if s[i].isdigit():
torque += int(s[i]) * (piv - i)
if torque > 0:
print("left")
elif torque < 0:
print("right")
else:
print("balance") |
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 | for tc in range(int(input())):
n = int(input())
l1=list(map(int,input().split()))
l2=list(map(int,input().split()))
k = min(l1)
p = min(l2)
moves = 0
for i in range(n):
l1[i]-=k
l2[i]-=p
moves+=max(l1[i],l2[i])
print(moves) |
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())
s=0
for i in range(n):
a,b,c=map(int,input().split(" "))
sum1 = a+b+c
if sum1 >=2:
s+=1
print(s)
|
A coordinate line has n segments, the i-th segment starts at the position li and ends at the position ri. We will denote such a segment as [li, ri].
You have suggested that one of the defined segments covers all others. In other words, there is such segment in the given set, which contains all other ones. Now you want... | 3 | # get n
n = int(input())
lis_segment = []
# create a list named lis_segment which contain a list which is the splited elements of each line input
for i in range(n):
lis_segment.append(list(map(int, input().split())))
# find the min of all element on the left, zero index
l = min(x[0] for x in lis_segment)
# find ... |
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.
Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, seco... | 3 | N = int(input())
word_0 = 'I hate'
word_1 = 'I love'
l = []
for i in range(N):
if i % 2 == 0:
l.append(word_0)
else:
l.append(word_1)
sentence = ' that '.join(l) + ' it'
print(sentence)
|
You are given positive integers X and Y. If there exists a positive integer not greater than 10^{18} that is a multiple of X but not a multiple of Y, choose one such integer and print it. If it does not exist, print -1.
Constraints
* 1 ≤ X,Y ≤ 10^9
* X and Y are integers.
Input
Input is given from Standard Input in... | 3 | a, b = map(int, input().split())
if a%b==0:
print('-1')
else:
print(a) |
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... | 3 | n=int(input())
li=[int(x) for x in input().split()]
li.sort()
check=[i for i in range(1,n+1)]
add=[0]
sub=[0]
for i in range(n):
vl=check[i]-li[i]
if vl>0:
add.append(vl)
elif vl<0:
sub.append(abs(vl))
print(sum(add)+sum(sub)) |
Input
The input contains a single integer a (0 ≤ a ≤ 35).
Output
Output a single integer.
Examples
Input
3
Output
8
Input
10
Output
1024 | 1 | a = int(raw_input())
b = [
"Washington",
"Adams",
"Jefferson",
"Madison",
"Monroe",
"Adams",
"Jackson",
"Van Buren",
"Harrison",
"Tyler",
"Polk",
"Taylor",
"Fillmore",
"Pierce",
"Buchanan",
"Lincoln",
"Johnson",
"Grant",
"Hayes",
"Garfield"... |
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 ... | 3 | import sys
s = input()
a = []
b = []
num = ""
for i in range(len(s)):
if s[i] == ',' or s[i] == ';':
if num.isnumeric() and (len(num) == 1 or num[0] != '0'):
a.append(num);
else:
b.append(num);
num =""
else:
num += s[i];
if num.isnumeric() and (len(num) ==... |
We're giving away nice huge bags containing number tiles! A bag we want to present to you contains n tiles. Each of them has a single number written on it — either 1 or 2.
However, there is one condition you must fulfill in order to receive the prize. You will need to put all the tiles from the bag in a sequence, in a... | 3 | n = int(input())
a = list(map(int, input().split()))
o, t = a.count(1), a.count(2)
if t > 0:
print(2, end=' ')
t -= 1
for i in range(o - (1 - o % 2)): print(1, end=' ')
for i in range(t): print(2, end=' ')
for i in range(min(o, 1 - o % 2)): print(1, end=' ')
print() |
You are given string S and T consisting of lowercase English letters.
Determine if S equals T after rotation.
That is, determine if S equals T after the following operation is performed some number of times:
Operation: Let S = S_1 S_2 ... S_{|S|}. Change S to S_{|S|} S_1 S_2 ... S_{|S|-1}.
Here, |X| denotes the len... | 3 | s1 = input()
print("Yes" if input() in tuple(s1[i:] + s1[:i] for i in range(len(s1))) else "No")
|
Screen resolution of Polycarp's monitor is a × b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x, y) (0 ≤ x < a, 0 ≤ y < b). You can consider columns of pixels to be numbered from 0 to a-1, and rows — from 0 to b-1.
Polycarp wants to open a rectangular window of maximal size, which ... | 3 | result = []
def main():
n = int(input())
for i in range(0, n):
m = list(map(int, input().split()))
r1 = (m[0] - m[2] - 1) * m[1]
r2 = (m[1] - m[3] - 1) * m[0]
r3 = (m[2] - 1 + 1) * m[1]
r4 = (m[3] - 1 + 1) * m[0]
result.append(max(r1, r2, r3, r4))
for i in result:
print(i)
main() |
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())
sum = 0
for i in range(0, n):
x = input()
x = x.split(' ')
if int(x[0]) + int(x[1]) + int(x[2]) >= 2:
sum += 1
print(sum)
|
Top-model Izabella participates in the competition. She wants to impress judges and show her mathematical skills.
Her problem is following: for given string, consisting of only 0 and 1, tell if it's possible to remove some digits in such a way, that remaining number is a representation of some positive integer, divisi... | 3 | q=input()
if '1' in q:
a=q.index('1')
q=q[a:]
if q.count('0')>=6:
print('yes')
else:
print('no')
else:
print('no')
|
Masha has three sticks of length a, b and c centimeters respectively. In one minute Masha can pick one arbitrary stick and increase its length by one centimeter. She is not allowed to break sticks.
What is the minimum number of minutes she needs to spend increasing the stick's length in order to be able to assemble a ... | 3 | a = list(map(int, input().split()))
x = a.pop(a.index(max(a)))
if x < a[0] + a[1]:
print(0)
else:
print(x-a[0]-a[1]+1)
|
Polycarp has recently created a new level in this cool new game Berlio Maker 85 and uploaded it online. Now players from all over the world can try his level.
All levels in this game have two stats to them: the number of plays and the number of clears. So when a player attempts the level, the number of plays increases... | 3 | t = int(input())
for i in range(t):
n = int(input())
lst1 = []
lst2 = []
for j in range(n):
a,b = input().split()
a = int(a)
b = int(b)
lst1.append(a)
lst2.append(b)
count = 0
if lst2[0] > lst1[0]:
print("NO")
else:
count +=1
fo... |
Lunar New Year is approaching, and you bought a matrix with lots of "crosses".
This matrix M of size n × n contains only 'X' and '.' (without quotes). The element in the i-th row and the j-th column (i, j) is defined as M(i, j), where 1 ≤ i, j ≤ n. We define a cross appearing in the i-th row and the j-th column (1 < i... | 3 | n = int(input())
s = []
for i in range(n):
s.append(input())
print( sum( s[i][j] == s[i+2][j] == s[i+1][j+1] == s[i][j+2] == s[i+2][j+2] == 'X' for i in range(n-2) for j in range(n-2))) |
Fox Ciel is playing a mobile puzzle game called "Two Dots". The basic levels are played on a board of size n × m cells, like this:
<image>
Each cell contains a dot that has some color. We will use different uppercase Latin characters to express different colors.
The key of this game is to find a cycle that contain d... | 3 | #A
'''
n, m = map(int, input().split())
row = ['#' * m if i % 2 == 0 else '.' * (m - 1) + '#' if i % 4 == 1
else '#' + '.' * (m - 1) for i in range(n)]
print('\n'.join(row))
'''
#B
import sys
sys.setrecursionlimit(5000)
n, m = map(int, input().split())
dx = [-1, 0, 0, 1]
dy = [0, -1, 1, 0]
L = list(input() for i... |
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 | t=int(input())
while(t>0):
n=int(input())
l1=list(map(int,input().strip().split()))
l2=list(map(int,input().strip().split()))
a1=0
a2=0
z=0
f=0
maxi=0
count=0
a1=min(l1)
a2=min(l2)
for i in range(0,n):
z=l1[i]-a1
y=l2[i]-a2
if(z<y):
cou... |
Natasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the string — concatenation of letters, which correspond to the stages.
There are n stages available. The rock... | 1 | n,k = map(int,raw_input().split())
st = raw_input().strip()
d = [0]*26
for i in st:
d[ord(i)-ord('a')] += 1
ans = ''
i = 0
while i < 26:
if d[i] > 0:
ans += chr(i+97)
i += 2
else:
i += 1
if len(ans) < k:
print "-1"
else:
aa = 0
for i in range(k):
aa += (ord(ans[i])-ord('a')+1)
print aa |
You are given a string S consisting of lowercase English letters. Determine whether all the characters in S are different.
Constraints
* 2 ≤ |S| ≤ 26, where |S| denotes the length of S.
* S consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
S
Output
If all ... | 3 | S = list(input())
print('yes' if len(list(set(S))) == len(S) else 'no') |
One day Vasya was sitting on a not so interesting Maths lesson and making an origami from a rectangular a mm × b mm sheet of paper (a > b). Usually the first step in making an origami is making a square piece of paper from the rectangular sheet by folding the sheet along the bisector of the right angle, and cutting t... | 3 | a, b = map(int, input().split())
k = 0
while a != b and a != 0 and b != 0:
k += a // b
t = a
a = b
b = t % b
if a == b and a != 0:
k += 1
print(k) |
It seems that Borya is seriously sick. He is going visit n doctors to find out the exact diagnosis. Each of the doctors needs the information about all previous visits, so Borya has to visit them in the prescribed order (i.e. Borya should first visit doctor 1, then doctor 2, then doctor 3 and so on). Borya will get the... | 3 | v = 1
for i in range(int(input())):
si, di = map(int, input().split())
while v < si or (v - si) % di:
v += 1
v += 1
print(v - 1) |
Highway 201 is the most busy street in Rockport. Traffic cars cause a lot of hindrances to races, especially when there are a lot of them. The track which passes through this highway can be divided into n sub-tracks. You are given an array a where a_i represents the number of traffic cars in the i-th sub-track. You def... | 1 | """
// Author : snape_here - Susanta Mukherjee
"""
from __future__ import division, print_function
import os,sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
def ii(): return int(inp... |
Tomorrow Peter has a Biology exam. He does not like this subject much, but d days ago he learnt that he would have to take this exam. Peter's strict parents made him prepare for the exam immediately, for this purpose he has to study not less than minTimei and not more than maxTimei hours per each i-th day. Moreover, th... | 3 | d, sumTime = list(map(int,input().split()))
mint = list()
maxt = list()
allmin = 0
allmax = 0
rasp = list()
for i in range(d):
a = list(map(int, input().split()))
mint.append(a[0])
maxt.append(a[1])
allmin += a[0]
allmax += a[1]
rasp.append(a[0])
if(allmin <= sumTime and sumTime <= allmax):
... |
There is a white sheet of paper lying on a rectangle table. The sheet is a rectangle with its sides parallel to the sides of the table. If you will take a look from above and assume that the bottom left corner of the table has coordinates (0, 0), and coordinate axes are left and bottom sides of the table, then the bott... | 3 | # -*- coding: utf-8 -*-
import sys
from itertools import accumulate
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] fo... |
There is a directed graph G with N vertices and M edges. The vertices are numbered 1, 2, \ldots, N, and for each i (1 \leq i \leq M), the i-th directed edge goes from Vertex x_i to y_i. G does not contain directed cycles.
Find the length of the longest directed path in G. Here, the length of a directed path is the num... | 3 | import sys
input = sys.stdin.readline
sys.setrecursionlimit(200000)
n, m = map(int, input().split())
graph = [[] for _ in range(n)]
for i in range(m):
x, y = map(int, input().split())
graph[x - 1].append(y - 1)
dp = [-1] * n
def count(a):
if dp[a] != -1:
return dp[a]
else:
dp[a] = 0
... |
Aaryan went to school like any usual day, The teacher asked his crush the following question.
Given an array of numbers, First she had to compute the XOR of all the subsequences that can be formed.
Suppose each subsequence had their following XOR value that came out after computing -> {P[0], P[1], P[2], and so on upto... | 1 | def main():
tot=int(raw_input())
seq=map(int,raw_input().split(" "))
ii=0
ans=0
while(ii<tot):
ans|=seq[ii]
ii+=1
print ans
main() |
In a factory, there are N robots placed on a number line. Robot i is placed at coordinate X_i and can extend its arms of length L_i in both directions, positive and negative.
We want to remove zero or more robots so that the movable ranges of arms of no two remaining robots intersect. Here, for each i (1 \leq i \leq N... | 3 | import heapq
n = int(input())
st = []
for i in range(n):
x,l = map(int,input().split())
heapq.heappush(st,[x+l,x-l])
ans = 0
last = -float('inf')
while len(st) > 0:
e, s = heapq.heappop(st)
if last <= s:
ans += 1
last = e
print(ans)
|
You are given an array a consisting of n integers a_1, a_2, ... , a_n.
In one operation you can choose two elements of the array and replace them with the element equal to their sum (it does not matter where you insert the new element). For example, from the array [2, 1, 4] you can obtain the following arrays: [3, 4],... | 3 | test_cases = int(input())
while test_cases > 0:
num = input()
data = list(map(int,input().split()))
divisible = [0,0,0]
for element in data:
divisible[element%3] += 1
toPrint = divisible[0]
if divisible[1] >= divisible[2]:
toPrint += divisible[2]
divisible[1] -= divisibl... |
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 | a, b = input().split(' ')
a = int(a)
b = int(b)
n = 0
while a <= b:
a *= 3
b *= 2
n += 1
print(n)
|
Emily's birthday is next week and Jack has decided to buy a present for her. He knows she loves books so he goes to the local bookshop, where there are n books on sale from one of m genres.
In the bookshop, Jack decides to buy two books of different genres.
Based on the genre of books on sale in the shop, find the nu... | 1 | n, m = map(int, raw_input().split())
books = map(int, raw_input().split())
d = {}
for book in books:
if book not in d:
d[book] = 0
d[book] += 1
s = 0
vals= d.values()
n = len(vals)
for i in range(0,n-1):
for j in range(i+1, n):
s += vals[i]*vals[j]
print s |
Eighth-grader Vova is on duty today in the class. After classes, he went into the office to wash the board, and found on it the number n. He asked what is this number and the teacher of mathematics Inna Petrovna answered Vova that n is the answer to the arithmetic task for first-graders. In the textbook, a certain posi... | 3 | def f(n):
x=0
for i in map(int,str(n)):x+=i
return x
n=input()
l=len(n)
n=int(n)
res=[0,[]]
for i in range(n,max(n-9*l,-1),-1):
if i+f(i)==n:res[0]+=1;res[1]+=[i]
print(res[0])
if res[0]:print(*res[1][::-1]) |
Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.
Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindro... | 3 | s=input()
s+=s[-1::-1]
print(s)
|
We have N non-negative integers: A_1, A_2, ..., A_N.
Consider painting at least one and at most N-1 integers among them in red, and painting the rest in blue.
Let the beauty of the painting be the \mbox{XOR} of the integers painted in red, plus the \mbox{XOR} of the integers painted in blue.
Find the maximum possibl... | 3 | n=int(input())
l=list(map(int,input().split()))
e=[]
sx=0
for i in l:
sx^=i
for i in l:
i&=(~sx)
for j in e:
i=min(i,i^j)
if i:
e.append(i)
t=0
for i in e:
t=max(t,t^i)
print((t^sx)+t) |
Ashishgup and FastestFinger play a game.
They start with a number n and play in turns. In each turn, a player can make any one of the following moves:
* Divide n by any of its odd divisors greater than 1.
* Subtract 1 from n if n is greater than 1.
Divisors of a number include the number itself.
The player... | 3 | def isprime(n):
i = 2
while i*i<=n:
if n%i == 0:
return 0
i+=1
return 1
t = int(input())
while t>0:
t-=1
n = int(input())
s1 = 'Ashishgup'
s2 = 'FastestFinger'
if n == 1:
print(s2)
elif n == 2:
print(s1)
elif n>2 and n%2 == 1:
p... |
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 | ans = 0
for t in range(int(input())):
if sum( i==1 for i in list(map(int,input().split())))>=2:
ans += 1
print(ans) |
Alice and Bob play a game. The game consists of several sets, and each set consists of several rounds. Each round is won either by Alice or by Bob, and the set ends when one of the players has won x rounds in a row. For example, if Bob won five rounds in a row and x = 2, then two sets ends.
You know that Alice and Bob... | 3 |
from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush,heappop
import math
from collections import *
from functools import reduce,cmp_to_key,lru_cache
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
# import sys
# input = sys.stdin.readline
M =... |
You are given an integer N. Among the divisors of N! (= 1 \times 2 \times ... \times N), how many Shichi-Go numbers (literally "Seven-Five numbers") are there?
Here, a Shichi-Go number is a positive integer that has exactly 75 divisors.
Constraints
* 1 \leq N \leq 100
* N is an integer.
Input
Input is given from S... | 3 | n = int(input())
def nprf(m):
pf = {}
for i in range(2, m + 1):
for j in range(2, i + 1):
while i % j == 0:
pf[j] = pf.get(j, 0) + 1
i //= j
return pf
def c(P, m):
count = 0
for i in P:
if P[i] >= m - 1:
count += 1
return ... |
We have a string S consisting of lowercase English letters.
If the length of S is at most K, print S without change.
If the length of S exceeds K, extract the first K characters in S, append `...` to the end of them, and print the result.
Constraints
* K is an integer between 1 and 100 (inclusive).
* S is a string ... | 3 | k=int(input());s=input();print(s[:k]+'.'*3*(len(s)>k))
|
For a finite set of integers X, let f(X)=\max X - \min X.
Given are N integers A_1,...,A_N.
We will choose K of them and let S be the set of the integers chosen. If we distinguish elements with different indices even when their values are the same, there are {}_N C_K ways to make this choice. Find the sum of f(S) ove... | 3 | MOD=10**9+7
N,K=[int(s) for s in input().split()]
ls=[int(s) for s in input().split()]
ls.sort()
MAX = N+1
fac = [1, 1]
finv = [1, 1]
inv = [0, 1]
for i in range(2, MAX):
fac.append(fac[i - 1] * i % MOD)
inv.append(MOD - inv[MOD % i] * (MOD // i) % MOD)
finv.append(finv[i - 1] * inv[i] % MOD)
def COM(n, k):
... |
General Payne has a battalion of n soldiers. The soldiers' beauty contest is coming up, it will last for k days. Payne decided that his battalion will participate in the pageant. Now he has choose the participants.
All soldiers in the battalion have different beauty that is represented by a positive integer. The value... | 1 | n,k = map(int, raw_input().split())
a = map(int, raw_input().split())
a.sort(); a.reverse()
possible = {0:[]}
# print possible
for x in a:
for v in possible.keys():
if v+x not in possible:
possible[v+x] = possible[v] + [x]
if len(possible) > k:
break;
del possible[0]
cnt = 0
for v in possible:
ans = possib... |
Polycarp and his friends want to visit a new restaurant. The restaurant has n tables arranged along a straight line. People are already sitting at some tables. The tables are numbered from 1 to n in the order from left to right. The state of the restaurant is described by a string of length n which contains characters ... | 3 | tests = int(input())
for i in range(tests):
numbers = input().split()
n = int(numbers[0])
k = int(numbers[1])
line = input()
left = k
seats = 0
for x in range(n):
if line[x] == '1':
left = 0
else:
if left < k:
left += 1
els... |
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 sys
input=sys.stdin.buffer.readline
inin=lambda: int(input())
inar=lambda: list(map(int,input().split()))
inst=lambda: input().decode().rstrip('\n\r')
INF=float('inf')
#from collections import deque as que, defaultdict as vector, Counter
#from bisect import bisect as bsearch
#from heapq import heapify, heappush ... |
Leonid is developing new programming language. The key feature of his language is fast multiplication and raising to a power operations. He is asking you to help with the following task.
You have an expression S and positive integer M. S has the following structure: A1*A2*...*An where "*" is multiplication operation. ... | 1 | def modpow(b,e,m):
res=1;
while(e>0):
if(e%2==1):
res=(res%m*b%m)%m
e=e>>1
b=(b%m*b%m)%m
return res
t=int(raw_input())
while(t>0):
str=raw_input()
l=str.split()
m=int(l[0])
lst=l[1].split("*")
ans=1
for i in range(0,len(lst),3):
ans=(ans%m*modpow(int(lst[i]),int(lst[i+2]),m)%m)%m
print a... |
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 | first = input()
second = input()
for i in range(len(first)):
if first[i] != second[-1-i]:
print('NO')
break
elif i == len(first)-1:
print('YES') |
"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 | i=lambda:map(int,input().split())
n,k=i();l=list(i())
print(sum(v>=max(1,l[k-1])for v in l)) |
Little girl Margarita is a big fan of competitive programming. She especially loves problems about arrays and queries on them.
Recently, she was presented with an array a of the size of 10^9 elements that is filled as follows:
* a_1 = -1
* a_2 = 2
* a_3 = -3
* a_4 = 4
* a_5 = -5
* And so on ...
... | 3 | I = lambda: int(input())
IL = lambda: list(map(int, input().split()))
def f(x):
return x//2 - (x%2)*x
n = I()
for i in range(n):
l, r = IL()
print(f(r) - f(l-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()
i = 0
c = 0
while i < len(s)-1:
if s[i] == s[i+1]:
c += 1
i += 1
print(c)
|
You are given integer n. You have to arrange numbers from 1 to 2n, using each of them exactly once, on the circle, so that the following condition would be satisfied:
For every n consecutive numbers on the circle write their sum on the blackboard. Then any two of written on the blackboard 2n numbers differ not more th... | 3 | #------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import*
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
BUF... |
Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited n his friends there.
If t... | 3 | #34 presents
n=int(input())
l=input().split()
output=[]
for i in range(n):
output.append(str(l.index(str(i+1))+1))
print(' '.join(output))
|
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given n numbers finds one that is di... | 3 | if __name__=="__main__":
n=int(input())
a=[int(x) for x in input().split()]
d=0
for i in a:
if(i&1):
c=i
d+=1
else:
e=i... |
The R1 company has recently bought a high rise building in the centre of Moscow for its main office. It's time to decorate the new office, and the first thing to do is to write the company's slogan above the main entrance to the building.
The slogan of the company consists of n characters, so the decorators hung a lar... | 3 | n , k = map(int, input().split())
s = str(input())
ans = []
r=1
if k!=len(s) and k!=1:
if k==n/2:
r=0
start = min((len(s)-k) ,k )
if start == len(s)-k and r==1:
ans = ['RIGHT']*start
else:
ans = ['LEFT'] * (start-1)
if len(s)==1:
t = 'PRINT '+str(s)
print(t)
elif 'RIGHT' ... |
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.
The language is that peculiar as it has exactly one variable, called x. Also, there are two operations:
* Operation ++ increases the value of variable x by 1.
* Operation -- decreases the value of variable x by 1.... | 3 | n=int(input())
x=0
for i in range(n):
exp=input()
if exp=='X++' or exp=='++X':
x+=1
else:
x-=1
print(x)
|
You are given n strings s_1, s_2, …, s_n consisting of lowercase Latin letters.
In one operation you can remove a character from a string s_i and insert it to an arbitrary position in a string s_j (j may be equal to i). You may perform this operation any number of times. Is it possible to make all n strings equal?
In... | 3 | from collections import Counter
t=int(input())
for i in range(t):
n=int(input())
ans=dict()
for k in range(n):
s1=input()
ans=Counter(ans)+Counter(s1)
f=0
for j in ans.keys():
if ans[j]%n!=0:
f=1
break
if f==0:
print("YES")
else:
print("NO") |
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 | a,b = raw_input().count('1'), raw_input().count('1')
if a%2!=0:
a += 1
print 'YES' if a >= b else 'NO'
|
You are given a rectangular board of M × N squares. Also you are given an unlimited number of standard domino pieces of 2 × 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squa... | 3 | if __name__ == "__main__":
a,b = [int(x) for x in input().split(" ")]
print((a * b) // 2) |
Rudolf is on his way to the castle. Before getting into the castle, the security staff asked him a question:
Given two binary numbers a and b of length n. How many different ways of swapping two digits in a (only in a, not b) so that bitwise OR of these two numbers will be changed? In other words, let c be the bitwise... | 1 | r1=lambda:input()
r2=lambda:map(int,raw_input().split())
r3=lambda:list(map(int,raw_input().split()))
n=input()
a=str(raw_input())
b=str(raw_input())
v1=0
v2=0
v3=0
v4=0
c=0
ans=[]
for i in range(0,n):
if b[i]=="0":
c=c+1
ans.append(i)
if a[i]=="1":
v1=v1+1
else:
v2=v2+1
else:
if a[i... |
Recently Luba learned about a special kind of numbers that she calls beautiful numbers. The number is called beautiful iff its binary representation consists of k + 1 consecutive ones, and then k consecutive zeroes.
Some examples of beautiful numbers:
* 12 (110);
* 1102 (610);
* 11110002 (12010);
* 111110... | 3 | a=0
a=int(input())
arr=[]
for k in range(0, 100):
arr.append(int((2**k-1)*(2**(k-1))))
for k in range(99, -1, -1):
if(a%arr[k]==0):
print(arr[k])
break |
Limak is a little polar bear. In the snow he found a scroll with the ancient prophecy. Limak doesn't know any ancient languages and thus is unable to understand the prophecy. But he knows digits!
One fragment of the prophecy is a sequence of n digits. The first digit isn't zero. Limak thinks that it's a list of some s... | 1 | n = int(raw_input())
s = raw_input()
s += '1' #
bg = 10**9+7
#print ind, l
num = [ [0 for i in range(n+2)] for j in range(n+2) ]
cnum = [ [0 for i in range(n+2)] for j in range(n+2) ]
adad = [ [0 for i in range(n+2)] for j in range(n+2) ]
mogh = [ [0 for i in range(n+2)] for j in range(n+2) ]
num[0][n] = 1
#for i ... |
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.
Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character... | 3 | text = input('')
alphabet = 'abcdefghijklmnopqrstuvwxyz'
actual_letter = 'a'
count = 0
for letter in text:
value = abs(alphabet.index(actual_letter) - alphabet.index(letter))
if value > 13:
value = 26 - value
count += value
actual_letter = letter
print(count) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.