problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
Boboniu likes bit operations. He wants to play a game with you.
Boboniu gives you two sequences of non-negative integers a_1,a_2,β¦,a_n and b_1,b_2,β¦,b_m.
For each i (1β€ iβ€ n), you're asked to choose a j (1β€ jβ€ m) and let c_i=a_i\& b_j, where \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise... | 1 | from __future__ import division, print_function
''' Hey stalker :) '''
INF = 10 ** 10
TEST_CASES = False
def main():
n, m = get_list()
ai = get_list()
bi = get_list()
options = []
for i in ai:
st = set([i & x for x in bi])
options.append(st)
ans = 0
for bit in range(32, -1... |
Your favorite shop sells n Kinder Surprise chocolate eggs. You know that exactly s stickers and exactly t toys are placed in n eggs in total.
Each Kinder Surprise can be one of three types:
* it can contain a single sticker and no toy;
* it can contain a single toy and no sticker;
* it can contain both a sing... | 3 | #problem 1 educational round div 2
#minimum suprise kinder required to get atleast one toy and one sticker
for _ in range(int(input())):
n,s,t= map(int,input().split())
required_sticker = n-s+1
required_toy = n-t+1
res = max(required_sticker,required_toy)
print(res) |
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.
The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe... | 3 | s=str(input())
l=list(map(int,s.split('+')))
l=sorted(l)
print('+'.join(map(str,l)))
|
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy... | 1 | import sys
n=int(sys.stdin.readline().strip())
sx=sy=sz=0
for i in range(n):
x,y,z=map(int,sys.stdin.readline().strip().split(' '))
sx+=x
sy+=y
sz+=z
if sx==0 and sy==0 and sz==0:
print 'YES'
else:
print 'NO'
|
Young boy Artem tries to paint a picture, and he asks his mother Medina to help him. Medina is very busy, that's why she asked for your help.
Artem wants to paint an n Γ m board. Each cell of the board should be colored in white or black.
Lets B be the number of black cells that have at least one white neighbor adja... | 3 | t = int(input())
out = ''
while t > 0:
t -= 1
n, m = [int(i) for i in input().split(' ')]
for i in range(n - 1):
out += 'B' + (m - 1) * 'W' + '\n'
out += m * 'B' + '\n'
print(out)
|
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.
The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe... | 3 | a = input()
arr = []
for i in range(0, len(a), 2):
arr.append(a[i])
arr = sorted(arr)
print('+'.join(arr))
|
Takahashi loves numbers divisible by 2.
You are given a positive integer N. Among the integers between 1 and N (inclusive), find the one that can be divisible by 2 for the most number of times. The solution is always unique.
Here, the number of times an integer can be divisible by 2, is how many times the integer can... | 3 | import math as mt
n=int(input())
print(2**int(mt.log2(n))) |
Find the minimum area of a square land on which you can place two identical rectangular a Γ b houses. The sides of the houses should be parallel to the sides of the desired square land.
Formally,
* You are given two identical rectangles with side lengths a and b (1 β€ a, b β€ 100) β positive integers (you are given ... | 3 | t = int(input())
for _ in range(t):
a,b = map(int,input().split())
if a>b:
b = 2*b
if b>=a:
print(b*b)
continue
else:
print(a*a)
continue
elif b>a:
a = 2*a
if b>=a:
print(b*b)
continue
els... |
Blake is a CEO of a large company called "Blake Technologies". He loves his company very much and he thinks that his company should be the best. That is why every candidate needs to pass through the interview that consists of the following problem.
We define function f(x, l, r) as a bitwise OR of integers xl, xl + 1, ... | 1 | def interview(st):
sum=0
for i in st:
sum|=i
return sum
n=int(input())
a = list(map(int,raw_input().split(" ")))
b = list(map(int,raw_input().split(" ")))
print(interview(a)+interview(b))
|
This is the first subtask of problem F. The only differences between this and the second subtask are the constraints on the value of m and the time limit. You need to solve both subtasks in order to hack this one.
There are n+1 distinct colours in the universe, numbered 0 through n. There is a strip of paper m centime... | 3 | def main():
line = input().split()
n = int(line[0])
line = input().split()
v = [int(x) for x in line]
mod = 998244353
dp = [[1] * (n + 5) for i in range(n + 5)]
for sz in range(2, n + 1):
for lo in range(1, n - sz + 2):
hi = lo + sz - 1
pos, num = -1, n... |
There are n piles of stones, where the i-th pile has a_i stones. Two people play a game, where they take alternating turns removing stones.
In a move, a player may remove a positive number of stones from the first non-empty pile (the pile with the minimal index, that has at least one stone). The first player who canno... | 3 | for _ in range(int(input())):
n = int(input())
a = [int(x) for x in input().split()]
ones = 0
for i in range(n):
if a[i] > 1:
print('Second') if i % 2 else print('First')
break
elif a[i] == 1:
ones += 1
if i == n - 1:
print('First')... |
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 | import sys
import math
#to read string
get_string = lambda: sys.stdin.readline().strip()
#to read list of integers
get_int_list = lambda: list( map(int,sys.stdin.readline().strip().split()) )
#to read non spaced string and elements are integers to list of int
get_intList_from_str = lambda: list(map(int,list(sys.stdin.... |
Given an integer N, find the base -2 representation of N.
Here, S is the base -2 representation of N when the following are all satisfied:
* S is a string consisting of `0` and `1`.
* Unless S = `0`, the initial character of S is `1`.
* Let S = S_k S_{k-1} ... S_0, then S_0 \times (-2)^0 + S_1 \times (-2)^1 + ... + S... | 3 | n = int(input())
ans = 0
base = 1
n = -n
while (n != 0):
p = abs(n % (-2))
n = (n + p) // (-2)
ans += p * base
base *= 10
print(ans)
|
Everybody in Russia uses Gregorian calendar. In this calendar there are 31 days in January, 28 or 29 days in February (depending on whether the year is leap or not), 31 days in March, 30 days in April, 31 days in May, 30 in June, 31 in July, 31 in August, 30 in September, 31 in October, 30 in November, 31 in December.
... | 3 | n = int(input())
a = list(map(int, input().split()))
leap = "312931303130313130313031"
str2 = "312831303130313130313031"
str2 = str2+str2+leap+str2+str2
strings = ''.join(str(x) for x in a)
if strings in str2:
print("YES")
else:
print("NO")
|
Princess'Gamble
Princess gambling
English text is not available in this practice contest.
One day, a brave princess in a poor country's tomboy broke the walls of her room, escaped from the castle, and entered the gambling hall where horse racing and other gambling were held. However, the princess who had never gambl... | 1 | while 1:
n,m,p=map(int,raw_input().split())
if n==0:break
x=[input() for i in range(n)]
if x[m-1]==0:
print 0
continue
print int((100-p)*sum(x)/float(x[m-1])) |
N problems are proposed for an upcoming contest. Problem i has an initial integer score of A_i points.
M judges are about to vote for problems they like. Each judge will choose exactly V problems, independently from the other judges, and increase the score of each chosen problem by 1.
After all M judges cast their vo... | 3 | #!/usr/bin/env python3
from itertools import accumulate
n, m, v, p = map(int, input().split())
a = sorted(map(int, input().split()))
cs = [0] + list(accumulate(a))
ans = p
rv = n - v
rp = n - p
for i in range(rp):
if a[i] + m < a[rp]:
continue
l = rp - i
if (cs[rp + 1] - cs[i + 1]) + (l - rv) * m <... |
You are given four integers a, b, x and y. Initially, a β₯ x and b β₯ y. You can do the following operation no more than n times:
* Choose either a or b and decrease it by one. However, as a result of this operation, value of a cannot become less than x, and value of b cannot become less than y.
Your task is to fi... | 3 | def lol(a, b, x, y, n):
minusa = min(n, a - x)
n -= minusa
a -= minusa
minusb = min(n, b - y)
b -= minusb
return a * b
for _ in range(int(input())):
a, b, x, y, n = [int(i) for i in input().split()]
if lol(a, b, x, y, n) < lol(b, a, y, x, n):
print(lol(a, b, x, y, n))
else:
... |
Two-gram is an ordered pair (i.e. string of length two) of capital Latin letters. For example, "AZ", "AA", "ZA" β three distinct two-grams.
You are given a string s consisting of n capital Latin letters. Your task is to find any two-gram contained in the given string as a substring (i.e. two consecutive characters of ... | 3 | n = int(input())
stroke = input()
strokes = []
count = {}
def count_of_str(stroke_per):
count = 0
for i in range(len(stroke) - 1):
if stroke[i] + stroke[i + 1] == stroke_per:
count += 1
return count
for i in range(len(stroke) - 1):
strokes.append(stroke[i] + stroke[i + 1])
for j i... |
The only difference between easy and hard versions are constraints on n and k.
You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most k most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals 0... | 3 | n,k = map(int,input().split())
a = list(map(int,input().split()))
b = []
for i in range(n):
if a[i] in b:
continue
elif len(b) < k:
b = [a[i]] + b
else:
b = [a[i]] + b[:len(b) - 1]
print(len(b))
print(*b) |
After playing Neo in the legendary "Matrix" trilogy, Keanu Reeves started doubting himself: maybe we really live in virtual reality? To find if this is true, he needs to solve the following problem.
Let's call a string consisting of only zeroes and ones good if it contains different numbers of zeroes and ones. For exa... | 3 | n=(int)(input())
s=input()
cb=0
ca=0
for i in range(n):
if (s[i]=='0'):
ca+=1
else:
cb+=1
if(ca!=cb):
print('1')
print(*s, sep='')
else:
print('2')
print(s[0], end=' ')
for i in range(1,n):
print(s[i], end='') |
Alice has a birthday today, so she invited home her best friend Bob. Now Bob needs to find a way to commute to the Alice's home.
In the city in which Alice and Bob live, the first metro line is being built. This metro line contains n stations numbered from 1 to n. Bob lives near the station with number 1, while Alice ... | 3 | n,q = [int (x) for x in input().split()]
a = [int (x) for x in input().split()]
b = [int (x) for x in input().split()]
t = False
if(a[0] == 1 and a[q-1] == 1):
print("YES")
elif(a[0] == 0):
print("NO")
else:
for x in range(q,n):
if(a[x] == 1 and b[x] == 1 and b[q-1 ] == 1):
t = True
... |
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 _ in range(t):
n = int(input())
s = input()
if "0" in s and "1" in s:
g = s.rindex("0")
h = s.index("1")
if g > h:
s = list(s)
s[h:g+1] = "0"
print("".join(s))
else:
print("".join(... |
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d... | 3 | k=input();k=(k.count("7")+k.count("4"));print("YES" if k!=0 and (k==4 or k==7) else "NO")
|
Amugae has a hotel consisting of 10 rooms. The rooms are numbered from 0 to 9 from left to right.
The hotel has two entrances β one from the left end, and another from the right end. When a customer arrives to the hotel through the left entrance, they are assigned to an empty room closest to the left entrance. Similar... | 3 | n = input()
cad = input()
rooms = '0' * 10
for c in cad:
if c == 'L':
index = rooms.find('0')
tmp = list(rooms)
tmp[index] = '1'
rooms = "".join(tmp)
elif c == 'R':
index = rooms.rfind('0')
tmp = list(rooms)
tmp[index] = '1'
rooms = "".join(tmp)
... |
You are given two positive integers n and k. Print the k-th positive integer that is not divisible by n.
For example, if n=3, and k=7, then all numbers that are not divisible by 3 are: 1, 2, 4, 5, 7, 8, 10, 11, 13 .... The 7-th number among them is 10.
Input
The first line contains an integer t (1 β€ t β€ 1000) β the ... | 3 | def f(x, y):
l = 0
r = y * y
while r - l > 1:
d = (l + r) // 2
if d - d // x >= y:
r = d
else:
l = d
return r
t = int(input())
for i in range(t):
n, k = map(int, input().split())
print(f(n, k))
|
You are given three positive (i.e. strictly greater than zero) integers x, y and z.
Your task is to find positive integers a, b and c such that x = max(a, b), y = max(a, c) and z = max(b, c), or determine that it is impossible to find such a, b and c.
You have to answer t independent test cases. Print required a, b a... | 3 | def three_pair_max(three):
three = sorted(three)
if three[1] != three[2]:
print("NO")
else:
print("YES")
print(f"{three[0]} {three[0]} {three[2]}")
t = int(input())
for i in range(t):
three = list(map(int, input().split()))
three_pair_max(three)
|
Over time, Alexey's mail box got littered with too many letters. Some of them are read, while others are unread.
Alexey's mail program can either show a list of all letters or show the content of a single letter. As soon as the program shows the content of an unread letter, it becomes read letter (if the program shows... | 1 | LIST, LETTER = 'list', 'letter'
if __name__ == '__main__':
n = int(raw_input())
L = ''.join(num for num in raw_input().split())
L = [int(num) for num in L.strip('0')]
state = LIST
nb_op = 0
for l in L:
if state == LIST:
if l == 0:
pass # don't need to do any... |
Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?
You are given a system of equations:
<image>
You should count, how many there are pai... | 3 | n,m=[int(i) for i in input().split()]
radical_min=int(max(n,m)**0.5)+1
tedad=0
zoj=set([])
for a in range(radical_min+1):
for b in range(radical_min+1):
if a**2+b==n and a+b**2==m:
zoj.add((a,b))
print(len(zoj)) |
Ilya is working for the company that constructs robots. Ilya writes programs for entertainment robots, and his current project is "Bob", a new-generation game robot. Ilya's boss wants to know his progress so far. Especially he is interested if Bob is better at playing different games than the previous model, "Alice".
... | 3 | f = lambda: list(map(int, input().split()))
g = lambda: [[0] * 4] + [[0] + f() for i in range(3)]
h = lambda x, y: x - 1 == y % 3
t = lambda a, b, u, v: (A[a][b], B[a][b], u + h(a, b), v + h(b, a))
k, a, b = f()
p = 2520
s, d = divmod(k,p)
#if s: s, d = s - 1, d + p
A, B = g(), g()
u = v = x = y = 0
for j in range(d): ... |
For god's sake, you're boxes with legs! It is literally your only purpose! Walking onto buttons! How can you not do the one thing you were designed for?
Oh, that's funny, is it? Oh it's funny? Because we've been at this for twelve hours and you haven't solved it either, so I don't know why you're laughing. You've got ... | 3 | for case in range(int(input())):
n = int(input())
lst = list(map(int, input().split()))
pointer = "NO"
for i in range(1, n):
if lst[i-1] <= lst[i]:
pointer = "YES"
break
print(pointer) |
One day Vasya decided to have a look at the results of Berland 1910 Football Championshipβs finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are n lines in that description each of which described one goal. Eve... | 3 | # -*- coding: utf-8 -*-
"""
Created on Sat Jul 13 11:43:30 2019
@author: avina
"""
d = {}
for i in range(int(input())):
a = input()
if a not in d:
d[a] =1
else:
d[a]+=1
e = ''
k=0
for i in d:
if k < d[i]:
k = d[i]
e = i
print(e) |
Aizu Gakuen High School holds a school festival every year. The most popular of these is the haunted house. The most popular reason is that 9 classes do haunted houses instead of 1 or 2 classes. Each one has its own unique haunted house. Therefore, many visitors come from the neighborhood these days.
Therefore, the sc... | 3 | e1,a1,b1=input().split()
e2,a2,b2=input().split()
e3,a3,b3=input().split()
e4,a4,b4=input().split()
e5,a5,b5=input().split()
e6,a6,b6=input().split()
e7,a7,b7=input().split()
e8,a8,b8=input().split()
e9,a9,b9=input().split()
print(e1,int(a1)+int(b1),int(a1)*200+int(b1)*300)
print(e2,int(a2)+int(b2),int(a2)*200+int(b2)... |
Today, Yasser and Adel are at the shop buying cupcakes. There are n cupcake types, arranged from 1 to n on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type i is an integer a_i. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.
Yasser, ... | 3 | def check(a,n):
ssum=0
for i in range(n):
ssum+=a[i]
if ssum<=0:
return True
ssum=0
for i in range(n-1,-1,-1):
ssum+=a[i]
if ssum<=0:
return True
return False
for _ in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
res=check(a,n)
if res:
print("NO")
else:
print("YES") |
This time Baby Ehab will only cut and not stick. He starts with a piece of paper with an array a of length n written on it, and then he does the following:
* he picks a range (l, r) and cuts the subsegment a_l, a_{l + 1}, β¦, a_r out, removing the rest of the array.
* he then cuts this range into multiple subrange... | 3 | import sys,os,io
from collections import defaultdict
import bisect
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
maxn = 100002
primes = []
spf = [0]*(maxn+1)
for i in range(2, maxn):
if spf[i]==0:
spf[i]=i
primes.append(i)
j = 0
while j < len(primes) and primes[j] <= spf[i] a... |
In the city of Ultima Thule job applicants are often offered an IQ test.
The test is as follows: the person gets a piece of squared paper with a 4 Γ 4 square painted on it. Some of the square's cells are painted black and others are painted white. Your task is to repaint at most one cell the other color so that the p... | 3 | x1=[]
x2=[]
x3=[]
x4=[]
x5=[]
x6=[]
x7=[]
x8=[]
x9=[]
lst1=[]
lst=[]
for z in range(4):
x=list(map(str,input()))
lst.extend(x)
#print('lst=',lst)
x1.append(lst[0])
x1.append(lst[1])
x1.append(lst[4])
x1.append(lst[5])
x2.append(lst[2])
x2.append(lst[3])
x2.append(lst[6])
x2.append(lst[7])
x3.append(lst[8... |
A long time ago in some far country lived king Copa. After the recent king's reform, he got so large powers that started to keep the books by himself.
The total income A of his kingdom during 0-th year is known, as well as the total income B during n-th year (these numbers can be negative β it means that there was a l... | 1 | a, b, n = map(int, raw_input().strip('\n').split())
for x in range(-1000, 1001):
if a * x**n == b:
print (x)
exit()
print "No solution"
|
You are given a string s consisting of n lowercase Latin letters. n is even.
For each position i (1 β€ i β€ n) in string s you are required to change the letter on this position either to the previous letter in alphabetic order or to the next one (letters 'a' and 'z' have only one of these options). Letter in every posi... | 3 | def solve(s, n):
i = 0
while i < n//2:
if s[i] != s[n-i-1]:
if abs(ord(s[i])-ord(s[n-i-1])) != 2:
return "NO"
i += 1
return "YES"
for _ in range(int(input())):
n = int(input())
s = input()
print(solve(s, n)) |
There was an electronic store heist last night.
All keyboards which were in the store yesterday were numbered in ascending order from some integer number x. For example, if x = 4 and there were 3 keyboards in the store, then the devices had indices 4, 5 and 6, and if x = 10 and there were 7 of them then the keyboards ... | 3 | def solve2(keyboards):
keyboards.sort()
#n=len(keyboards)
return keyboards[-1]-keyboards[0]+1-len(keyboards)
n = int(input())
keyboards = list(map(int, input().split(" ")))
print(solve2(keyboards)) |
You have been given a String S consisting of uppercase and lowercase English alphabets. You need to change the case of each alphabet in this String. That is, all the uppercase letters should be converted to lowercase and all the lowercase letters should be converted to uppercase. You need to then print the resultant St... | 1 | b=raw_input()
print b.swapcase() |
There are b boys and g girls participating in Olympiad of Metropolises. There will be a board games tournament in the evening and n participants have accepted the invitation. The organizers do not know how many boys and girls are among them.
Organizers are preparing red badges for girls and blue ones for boys.
Vasya ... | 3 | b=int(input())
g=int(input())
n=int(input())
if b>=n and g>=n:
print(n+1)
elif b>=n and g<n:
print(n+1-(n-g))
elif g>=n and b<n:
print(n+1-(n-b))
elif g<n and b<n:
print(n+1-(n-b)-(n-g))
|
You got a job as a marketer in a pet shop, and your current task is to boost sales of cat food. One of the strategies is to sell cans of food in packs with discounts.
Suppose you decided to sell packs with a cans in a pack with a discount and some customer wants to buy x cans of cat food. Then he follows a greedy str... | 1 | from __future__ import division, print_function
''' Hey stalker :) '''
INF = 10 ** 50
TEST_CASES = True
from collections import defaultdict, deque, Counter
from functools import reduce
from bisect import bisect_left
def main():
l, r = get_list()
print("YES") if r < 2*l else print("NO")
''' FastIO Footer: ... |
You are going to the beach with the idea to build the greatest sand castle ever in your head! The beach is not as three-dimensional as you could have imagined, it can be decribed as a line of spots to pile up sand pillars. Spots are numbered 1 through infinity from left to right.
Obviously, there is not enough sand o... | 3 | def main():
n, h = map(int, input().split())
l = -1
r = 10 ** 18
while (r - l != 1):
m = (r + l) // 2
t = m + h - 1
if (m > h):
if (t % 2 == 1):
j = t // 2 + 1 - h + 1
s = j * (j + 1) // 2 + j * (h - 1) + (m - j) * (m - j + 1) // 2
... |
Today Tavas got his test result as an integer score and he wants to share it with his girlfriend, Nafas.
His phone operating system is Tavdroid, and its keyboard doesn't have any digits! He wants to share his score with Nafas via text, so he has no choice but to send this number using words.
<image>
He ate coffee mi... | 1 | s = input()
def print_result(s):
numbers = {0:'zero', 1:'one',
2:'two', 3:'three',
4:'four', 5:'five',
6:'six', 7:'seven',
8:'eight', 9:'nine',
10:'ten', 11:'eleven',
12:'twelve', 13:'thirteen',
14:'fourteen', ... |
Ridhiman challenged Ashish to find the maximum valued subsequence of an array a of size n consisting of positive integers.
The value of a non-empty subsequence of k elements of a is defined as β 2^i over all integers i β₯ 0 such that at least max(1, k - 2) elements of the subsequence have the i-th bit set in their bin... | 3 | # https://codeforces.com/contest/1365/problem/E
import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
# do magic here
n = int(input())
arr = [int(x) for x in input().split()]
ans = 0
if n == 1:
ans = arr[0]
if n == 2:
ans = arr[0] | arr[1]
else:
for x in range(n):
for y in rang... |
We have a grid of H rows and W columns of squares. The color of the square at the i-th row from the top and the j-th column from the left (1 \leq i \leq H, 1 \leq j \leq W) is given to you as a character c_{i,j}: the square is white if c_{i,j} is `.`, and black if c_{i,j} is `#`.
Consider doing the following operation... | 3 | h, w, K = map(int, input().split())
c = []
for i in range(h):
a = list(str(input()))
c.append(a)
cnt = 0
blk = 0
for i in range(2 ** h):
for j in range(2 ** w):
for k in range(h):
for l in range(w):
if ((i >> k) & 1 == 0) and ((j >> l) & 1 == 0) and (c[k][l] == '#'):
blk += 1
if bl... |
You are given N items.
The value of the i-th item (1 \leq i \leq N) is v_i.
Your have to select at least A and at most B of these items.
Under this condition, find the maximum possible arithmetic mean of the values of selected items.
Additionally, find the number of ways to select items so that the mean of the values o... | 3 | N,A,B = [int(i) for i in input().split()]
v = [int(i) for i in input().split()]
v.sort()
v.reverse()
cum = [v[0]]
def comb(n, k):
if k>n:
return 0
ans = 1
for i in range(k):
ans *= n-i
for j in range(k):
ans = ans//(j+1)
return ans
for i in range(1,N):
cum += [cum[i-1] ... |
Bob is playing with 6-sided dice. A net of such standard cube is shown below.
<image>
He has an unlimited supply of these dice and wants to build a tower by stacking multiple dice on top of each other, while choosing the orientation of each dice. Then he counts the number of visible pips on the faces of the dice.
Fo... | 3 | def main():
t=int(input())
a=list(map(int,input().split()))
for x in a:
if x>14:
if 0<x%14<7:
print("YES")
else:
print("NO")
else:
print("NO")
main()
|
Sonya decided that having her own hotel business is the best way of earning money because she can profit and rest wherever she wants.
The country where Sonya lives is an endless line. There is a city in each integer coordinate on this line. She has n hotels, where the i-th hotel is located in the city with coordinate ... | 3 | n, d = map(int, input().split(' '))
arr = input().split(' ')
for i in range(n):
arr[i]=int(arr[i])+1
arr.sort()
count=2
for i in range(n):
if (arr[i]-arr[i-1]<2*d):
continue
if (arr[i]-arr[i-1]==2*d):
count+=1
continue
count+=2
print(count)
|
Among Johnny's numerous hobbies, there are two seemingly harmless ones: applying bitwise operations and sneaking into his dad's office. As it is usually the case with small children, Johnny is unaware that combining these two activities can get him in a lot of trouble.
There is a set S containing very important number... | 3 | cases=int(input())
for _ in range(cases):
n=int(input())
c=sorted(list(map(int,input().split())))
m=[]
for i in range(1,1024):
w=[]
for j in range(len(c)):
w.append(c[j]^i)
if sorted(w)==c:
m.append(i)
try:
print(min(m))
except:
print(-1)
|
You are given a string s consisting only of lowercase Latin letters.
You can rearrange all letters of this string as you wish. Your task is to obtain a good string by rearranging the letters of the given string or report that it is impossible to do it.
Let's call a string good if it is not a palindrome. Palindrome is... | 3 | for i in range(int(input())) :
s = input()
ar = [str(i) for i in s]
ar.sort()
print('-1' if ar[0] == ar[-1] else ''.join(ar))
|
Theatre Square in the capital city of Berland has a rectangular shape with the size n Γ m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a Γ a.
What is the least number of flagstones needed to pave the Square? It'... | 3 |
inputs = input()
values = inputs.split(" ")
m = int(values[0])
n = int(values[1])
a = int(values[2])
if m/a == int(m/a):
mside= int(m/a)
else:
mside= int(m/a) + 1
if n/a == int(n/a):
nside = int(n/a)
else:
nside = int(n/a) + 1
result = mside * nside
print(result) |
There are N blocks arranged in a row, numbered 1 to N from left to right. Each block has a weight, and the weight of Block i is A_i. Snuke will perform the following operation on these blocks N times:
* Choose one block that is still not removed, and remove it. The cost of this operation is the sum of the weights of t... | 3 | from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
fro... |
Let us denote by f(x, m) the remainder of the Euclidean division of x by m.
Let A be the sequence that is defined by the initial value A_1=X and the recurrence relation A_{n+1} = f(A_n^2, M). Find \displaystyle{\sum_{i=1}^N A_i}.
Constraints
* 1 \leq N \leq 10^{10}
* 0 \leq X < M \leq 10^5
* All values in input are ... | 1 | import os
import sys
from atexit import register
from io import BytesIO
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
sys.stdout = BytesIO()
register(lambda: os.write(1, sys.stdout.getvalue()))
input = lambda: sys.stdin.readline().rstrip('\r\n')
raw_input = lambda: sys.stdin.readline().rstrip('\r\n')
n,x,m = (i... |
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... | 1 | def main():
line = str(raw_input())
lineList = line.split()
M = int(lineList[0])
N = int(lineList[1])
dominoArea = 2
boardArea = M*N
print(boardArea/dominoArea)
main()
|
Ternary numeric notation is quite popular in Berland. To telegraph the ternary number the Borze alphabet is used. Digit 0 is transmitted as Β«.Β», 1 as Β«-.Β» and 2 as Β«--Β». You are to decode the Borze code, i.e. to find out the ternary number given its representation in Borze alphabet.
Input
The first line contains a nu... | 3 | s = list(input())
i = 0
l = []
while i < len(s):
if s[i] == '.':
l.append(0)
elif s[i+1] == '.':
l.append(1)
i += 1
elif s[i+1] == '-':
l.append(2)
i += 1
i += 1
for i in l:
print(i, end="")
|
Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play t matches of a digit game...
In each of t matches of the digit game, a positive integer is generated. It consists of n digits. The digits of this integer are numerated f... | 3 | t = int(input())
for _ in range(0,t):
n=int(input())
s=input()
f1=0
f2=0
if n%2==1:
for i in range(0,n,2):
if int(s[i]) % 2 == 1 :
f1=1
break
if f1==1:
print(1)
else:
print(2)
else:
for i in range(0... |
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 | t=input()
has=[0]*10
t=int(t)
t=t+1
t=str(t)
while True:
has=[0]*10
for x in t:
has[int(x)]=has[int(x)]+1
#print(has)
if has.count(1)==4:
print(t)
break
else:
t=int(t)
t=t+1
t=str(t)
|
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 | def mdc(a,b):
while b !=0:
resto = a % b
a = b
b = resto
return a
entrada = int(input())
for k in range(entrada):
a, b = list(map(int, input().split()))
resp = a % b
if(resp == 0):
print(0)
else:
print(b - resp)
|
Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, inf... | 1 | n = input()
word = raw_input()
if n == 1 or n == 2:
answer = word
else:
answer = word[n-2] + word[n-1]
count = n-3
while count >= 0:
letter = word[count]
length = len(answer)
median = length // 2
answer = answer[:median] + letter + answer[median:]
count -= 1
print... |
Write a program which reads a $ n \times m$ matrix $A$ and a $m \times 1$ vector $b$, and prints their product $Ab$.
A column vector with m elements is represented by the following equation.
\\[ b = \left( \begin{array}{c} b_1 \\\ b_2 \\\ : \\\ b_m \\\ \end{array} \right) \\]
A $n \times m$ matrix with $m$ column ve... | 1 | n,m=map(int,raw_input().split())
a=[]
for i in range(n):
a.append([int(v) for v in raw_input().split()])
b=[]
for i in range(m):
b.append(int(raw_input()))
for i in range(n):
ans=0
for j in range(m):
ans+=a[i][j]*b[j]
print ans |
Hanh lives in a shared apartment. There are n people (including Hanh) living there, each has a private fridge.
n fridges are secured by several steel chains. Each steel chain connects two different fridges and is protected by a digital lock. The owner of a fridge knows passcodes of all chains connected to it. A fridg... | 3 | def answer(people, steelCount, weights) :
if steelCount < people or people == 2 :
return print(-1)
totalFee = (sum(weights) * 2)
nodeRelations = []
for node in range(1, len(weights)) :
nodeRelations.append([node, node+1])
nodeRelations.append([len(weights), 1])
# if steelCount > people :
# rem... |
Given are strings s and t of length N each, both consisting of lowercase English letters.
Let us form a new string by alternating the characters of S and the characters of T, as follows: the first character of S, the first character of T, the second character of S, the second character of T, ..., the N-th character of... | 3 | a = int(input())
b, c = input().split()
for i in range(a):
print(b[i]+c[i], end="") |
Polycarp has guessed three positive integers a, b and c. He keeps these numbers in secret, but he writes down four numbers on a board in arbitrary order β their pairwise sums (three numbers) and sum of all three numbers (one number). So, there are four numbers on a board in random order: a+b, a+c, b+c and a+b+c.
You h... | 3 | sums = [int(x) for x in input().split()]
all_sum = max(sums)
abc = [str(all_sum - i) for i in sums if all_sum - i != 0]
print(" ".join(abc))
|
We have a string S consisting of uppercase English letters. Additionally, an integer N will be given.
Shift each character of S by N in alphabetical order (see below), and print the resulting string.
We assume that `A` follows `Z`. For example, shifting `A` by 2 results in `C` (`A` \to `B` \to `C`), and shifting `Y` ... | 3 | n = int(input())
s = input()
for x in s:
st = (ord(x) +n-65)%26
print(chr(65+st),end='') |
Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, inf... | 3 | n = int(input());
s = input();
if((n==1) or (n==2)):
print(s);
else:
s=list(s);
new=list(s);
front=0;
back=n-1;
i=n-1;
while(i>=0):
new[back]=s[i];
back=back-1;
i=i-1;
if(i>=0):
new[front]=s[i];
front=front+1;
i=i-1;
snew = ''.join(new);
print(snew);
|
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.
Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divi... | 3 | n=int(input())
k=n//2
p=[2 for x in range(k)]
p[0]+=n%2
print(k)
print(" ".join(map(str,p))) |
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 | t = int(input())
for i in range(t):
n = int(input())
s = input()
if n<11: print('NO')
else:
s = str(s)[:n-10]
if '8' not in s: print('NO')
else: print('YES')
|
Polycarp knows that if the sum of the digits of a number is divisible by 3, then the number itself is divisible by 3. He assumes that the numbers, the sum of the digits of which is divisible by 4, are also somewhat interesting. Thus, he considers a positive integer n interesting if its sum of digits is divisible by 4.
... | 1 | def sum_of_digits(a):
sum=0
for x in a:
sum+=int(x)
return sum
a=raw_input()
sum=sum_of_digits(a)
i=0
while i==0:
sum=sum_of_digits(a)
if sum%4==0:
break
else:
a=int(a)
a+=1
a=str(a)
print a
|
You are given an integer x of n digits a_1, a_2, β¦, a_n, which make up its decimal notation in order from left to right.
Also, you are given a positive integer k < n.
Let's call integer b_1, b_2, β¦, b_m beautiful if b_i = b_{i+k} for each i, such that 1 β€ i β€ m - k.
You need to find the smallest beautiful integer y,... | 3 | # # https://codeforces.com/contest/1269/problem/C
# xd, n = [int(n) for n in input().split()]
# x = [int(n) for n in input()]
# bs_i = set([x[i] for i in range(0, xd, n)])
# bs = []
# not_bs = []
# increased = False
# # for i, n in enumerate(x):
# # if i in bs_i:
# # bs.append(n)
# # else:
# # not_bs.append(n)
... |
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them.
Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain nu... | 3 | s = input()
i = 0
mas = s.split("WUB")
s = ""
masc = []
for i in mas:
if i != "":
masc.append(i)
print(" ".join(masc))
|
The game of Berland poker is played with a deck of n cards, m of which are jokers. k players play this game (n is divisible by k).
At the beginning of the game, each player takes n/k cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he... | 3 | num = int(input())
for _ in range(num):
n, m, k = [int(i) for i in input().split()]
if n // k >= m:
print(m)
else:
m -= n // k
if m % (k - 1) > 0:
print(n // k - (m // (k - 1) + 1))
else:
print(n // k - m // (k - 1)) |
For each positive integer n consider the integer Ο(n) which is obtained from n by replacing every digit a in the decimal notation of n with the digit (9 - a). We say that Ο(n) is the reflection of n. For example, reflection of 192 equals 807. Note that leading zeros (if any) should be omitted. So reflection of 9 equals... | 3 | inp1, inp2 = [int(i) for i in input().split()]
lista = list()
def reverse(n):
newStr = ""
for c in str(n):
newC = 9 - int(c)
newStr += str(newC)
l = len(str(n))
d = "9"*l
d = int(d)
newStr = d - int(n)
return int(newStr)
le = len(str(inp2)) - 1
digit = 5 * (10 ** le)
if dig... |
Ilya is a very clever lion, he lives in an unusual city ZooVille. In this city all the animals have their rights and obligations. Moreover, they even have their own bank accounts. The state of a bank account is an integer. The state of a bank account can be a negative number. This means that the owner of the account ow... | 3 | n = int(input())
if(n >= 0):
print(n)
else:
k = str(abs(n))
if(k[-1] < k[-2]):
l = ("-" + k[0: len(k) - 2] + k[len(k)-1])
print(int(l))
else:
l = ("-"+ k[0: len(k)-1])
print(int(l)) |
Petya has an array a consisting of n integers. He wants to remove duplicate (equal) elements.
Petya wants to leave only the rightmost entry (occurrence) for each element of the array. The relative order of the remaining unique elements should not be changed.
Input
The first line contains a single integer n (1 β€ n β€ ... | 3 | n=int(input())
l=list(map(int,input().split()))
s=set(l)
list1=[]
for i in range(len(l)):
if l[len(l)-i-1] not in list1:
list1.append(l[len(l)-i-1])
print(len(list1))
list1.reverse()
for i in list1:
print(i,end=" ") |
Arpa is taking a geometry exam. Here is the last problem of the exam.
You are given three points a, b, c.
Find a point and an angle such that if we rotate the page around the point by the angle, the new position of a is the same as the old position of b, and the new position of b is the same as the old position of c.... | 1 | import sys
import math
def readArray():return map(int,sys.stdin.readline().split())
def readString():return sys.stdin.readline().strip()
def readNum():return readString()
def exp(t,x):
MOD=1000000007
if(x==0):return 1
if(x==1):return t
if(x%2==1):return exp((t*t)%MOD,x/2)
def gcd(x,y):
if x%y==0:return ... |
In Berland, there is the national holiday coming β the Flag Day. In the honor of this event the president of the country decided to make a big dance party and asked your agency to organize it. He has several conditions:
* overall, there must be m dances;
* exactly three people must take part in each dance;
* eac... | 3 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 16 20:35:46 2013
@author: Praveen Kumar
"""
import sys
m,n = map(int, input().split())
d = [0]*(m+1);
for i in range(n):
a = list(map(int, input().split()))
b = [1,2,3]
for j in a:
if d[j] != 0:
b.remove(d[j])
a.remove(j)
i... |
Polycarp has guessed three positive integers a, b and c. He keeps these numbers in secret, but he writes down four numbers on a board in arbitrary order β their pairwise sums (three numbers) and sum of all three numbers (one number). So, there are four numbers on a board in random order: a+b, a+c, b+c and a+b+c.
You h... | 3 | s = input()
x = list(map(int, s.split()))
mx = max(x)
x.remove(mx)
print(mx-x[1], mx-x[2], mx-x[0])
|
Fedya studies in a gymnasium. Fedya's maths hometask is to calculate the following expression:
(1n + 2n + 3n + 4n) mod 5
for given value of n. Fedya managed to complete the task. Can you? Note that given number n can be extremely large (e.g. it can exceed any integer type of your programming language).
Input
The si... | 3 | n = eval(input())
n = n%4
print((1**n+2**n+3**n+4**n)%5) |
In the Kingdom of AtCoder, people use a language called Taknese, which uses lowercase English letters.
In Taknese, the plural form of a noun is spelled based on the following rules:
* If a noun's singular form does not end with `s`, append `s` to the end of the singular form.
* If a noun's singular form ends with `s`... | 3 | s = input()
print("{}".format(s+"es" if s[-1] == "s" else s+"s")) |
Petya and Vasya are playing a game. Petya's got n non-transparent glasses, standing in a row. The glasses' positions are indexed with integers from 1 to n from left to right. Note that the positions are indexed but the glasses are not.
First Petya puts a marble under the glass in position s. Then he performs some (pos... | 1 | inp = list(map(int,raw_input().split()))
n = int(inp[0])
s = int(inp[1])
t = int(inp[2])
p = list(map(int,raw_input().split()))
pp = [0]+list(p) # to make glasses index start from 1 not 0
ll=[] #to push all index that glass moved on it
operations = 0
check = 0
item2 = s
item =0
while 1:
# to check if glass moved on ... |
There are n people who want to participate in a boat competition. The weight of the i-th participant is w_i. Only teams consisting of two people can participate in this competition. As an organizer, you think that it's fair to allow only teams with the same total weight.
So, if there are k teams (a_1, b_1), (a_2, b_2)... | 3 | import sys
from collections import Counter
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)] for j in range(b)] for i in ... |
This is a harder version of the problem. In this version n β€ 500 000
The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the compan... | 3 | from sys import stdin
n = int(stdin.readline())
a = [int(x) for x in stdin.readline().split()]
stack = [(0,0)]
left = [0]
for i,x in enumerate(a):
i += 1
while stack[-1][0] > x:
stack.pop()
left.append(left[stack[-1][1]] + x*(i-stack[-1][1]))
stack.append((x,i))
stack = [(0,0)]
right = [0]
... |
Vasya and Petya are playing a simple game. Vasya thought of number x between 1 and n, and Petya tries to guess the number.
Petya can ask questions like: "Is the unknown number divisible by number y?".
The game is played by the following rules: first Petya asks all the questions that interest him (also, he can ask no ... | 3 | x = int(input())
primos = [True]*(x+1)
p = 2
res = ''
while p*p <= x and x != 1 and x != 2:
if primos[p]:
for i in range(p*p,x+1,p):
primos[i] = False
p += 1
for primo in range(x+1):
if primo == 0 or primo == 1:
continue
if primos[primo]:
p, aux = primo, primo
while p <= x:
res += ... |
Translator's note: in Russia's most widespread grading system, there are four grades: 5, 4, 3, 2, the higher the better, roughly corresponding to A, B, C and F respectively in American grading system.
The term is coming to an end and students start thinking about their grades. Today, a professor told his students that... | 3 | n = int(input()) # the number of Vasya's grades
grades = [int(i) for i in input().split()]
if sum(grades) / n < 4.5:
grades.sort()
j = 0
for i in range(n):
grades[i] = 5
j += 1
if sum(grades) / n >= 4.5:
break
print(j)
else:
print(0)
|
There is an ice cream shop named Ten Ice Cream. At this store, we always have 10 types of ice cream on the shelves. The store manager creates a daily graph showing how well ice cream is selling for reference in product development.
For such a store manager, you decided to create a program that displays the number of e... | 1 | while 1:
n=input()
if n==0:break
h=[0]*10
for i in range(n):
h[int(raw_input())]+=1
for i in range(10):
print "*"*h[i] if h[i] else "-" |
You are given the array a consisting of n elements and the integer k β€ n.
You want to obtain at least k equal elements in the array a. In one move, you can make one of the following two operations:
* Take one of the minimum elements of the array and increase its value by one (more formally, if the minimum value of ... | 3 | INF = int (2e9)
n, k = list (map (int, input ().split ()))
a = list (map (int, input ().split ()))
a.sort()
a = [(x, 0) for x in a]
ans = INF
ha = {}
tail = n - 1
p = 0
def lowerbound (x):
l, r = 0, tail - 1
while (l <= r) :
mid = (l + r) >> 1
if (a[mid][0] >= x) :
r = mid - 1
... |
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())
for i in range(1,n+1):
if i%2==0:
print("I love",end="")
else:
print("I hate",end="")
if i!=n:
print(" that",end="")
print(" ",end="")
print("it")
|
After Fox Ciel got off a bus, she found that the bus she was on was a wrong bus and she lost her way in a strange town. However, she fortunately met her friend Beaver Taro and asked which way to go to her castle. Taro's response to her was a string s, and she tried to remember the string s correctly.
However, Ciel fee... | 1 | import sys
#sys.stdin = file("input.txt", "r");
s, n = raw_input(), int(raw_input())
a = [0] * n
for i in xrange(n):
a[i] = raw_input()
ln, ind, ls = 0, 0, 0
for i in xrange(len(s) - 1, -1, -1):
ls += 1
for t in a:
if len(t) <= ls and s[i : i + len(t)] == t:
ls = len(t) - 1
if... |
Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity.
There are n columns of toy cubes in the box arranged in a line. The i-th column contains ai cubes. At first, the gravity in the box is pulling... | 3 | n = input()
print(*sorted(tuple(map(int, (input().split())))))
|
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 | t = int(input())
for _ in range(t):
n, x = map(int, input().split())
if n <= 2:
print (1)
else:
print ((n+x-3) // x + 1) |
PandeyG, a brilliant tennis player, decided to start a tournament in his colony. Now, since PandeyG is overly optimistic and ambitious - he tries to lure in as many people as he can from his colony for them to participate in his very own knockout type tennis tournament. What he fails to realize that, to have a knockout... | 1 | N = input('')
for i in range(N):
X = input('')
if X==0:
print(X)
else:
print(X-1) |
Olya loves energy drinks. She loves them so much that her room is full of empty cans from energy drinks.
Formally, her room can be represented as a field of n Γ m cells, each cell of which is empty or littered with cans.
Olya drank a lot of energy drink, so now she can run k meters per second. Each second she chooses... | 1 | from sys import *
f = lambda: map(int,raw_input().split())
n, m, k = f()
t = [[1e9 * (q == '.') for q in stdin.readline()] for i in range(n)]
t.append([0] * m)
a, b, c, d = [q - 1 for q in f()]
u = [(a, b)]
t[a][b] = l = 0
def g(i, x, y):
if i > k or t[x][y] < l: return 0
if t[x][y] > l:
t[x][y] = l
... |
Factorize a given integer n.
Constraints
* 2 β€ n β€ 109
Input
n
An integer n is given in a line.
Output
Print the given integer n and :. Then, print prime factors in ascending order. If n is divisible by a prime factor several times, the prime factor should be printed according to the number of times. Print a s... | 3 | # import numpy as np
import math
n = int(input());
orig = n
i = 2
l = []
while i<=math.sqrt(orig):
while n%i== 0:
n /= i
l.append(i)
i += 1
if n != 1:
l.append(int(n))
# if len(l) == 0:
# print("{0}: {1}".format(orig, orig))
# else:
print("{}:".format(orig), *l)
|
Polycarp wants to cook a soup. To do it, he needs to buy exactly n liters of water.
There are only two types of water bottles in the nearby shop β 1-liter bottles and 2-liter bottles. There are infinitely many bottles of these two types in the shop.
The bottle of the first type costs a burles and the bottle of the se... | 3 | from sys import stdin,stdout
import bisect
import math
def st():
return list(stdin.readline().strip())
def inp():
return int(stdin.readline())
def li():
return list(map(int,stdin.readline().split()))
def mp():
return map(int,stdin.readline().split())
def pr(n):
stdout.write(str(n)+"\n")
def... |
Sasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table M with n rows and n columns such that M_{ij}=a_i β
a_j where a_1, ..., a_n is some sequence of positive integers.
Of course, the girl decided to take it to school with her. But while she was having lunch, hoolig... | 3 | from math import sqrt
n = int(input())
m_s = [[int(i) for i in input().split()] for j in range(n)]
a_s = [0]*n
a_s[0] = int(sqrt(m_s[0][1]*m_s[1][2]*m_s[2][0]))//m_s[1][2]
a_s[-1] = int(sqrt(m_s[-2][-1]*m_s[-3][-2]*m_s[-1][-3]))//m_s[-2][-3]
for i in range(1,
n-1):
el = int(sqrt(m_s[i-1][i]*m_s[i][i+... |
You are given two strings s and t. The string s consists of lowercase Latin letters and at most one wildcard character '*', the string t consists only of lowercase Latin letters. The length of the string s equals n, the length of the string t equals m.
The wildcard character '*' in the string s (if any) can be replace... | 3 | a,b=map(int,input().split())
s1=str(input())
s2=str(input())
try:
l=s1.index("*")
if(s1[0:l:1]==s2[0:l:1] and s1[(-1):(-len(s1)+l):(-1)]==s2[(-1):(-len(s1)+l):(-1)]):
if(len(s2)>=len(s1)-1):
print("YES")
else:
print("NO")
else:
print("NO")
except:
if(s1==s... |
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word s. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if... | 1 | s = raw_input()
pattern = "hello"
cnt = 0
for x in s:
if cnt == 5:
break
if x == pattern[cnt]:
cnt += 1
if cnt == 5:
print "YES"
else:
print "NO" |
A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay iΒ·k dollars for the i-th banana).
He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas?
Input
The first lin... | 3 | cin = lambda:(map(int,input().split()))
k,w,n =cin()
res = (2*k + (n - 1)*k ) * n // 2;
print((0,res - w) [res>w])
|
A word or a sentence in some language is called a pangram if all the characters of the alphabet of this language appear in it at least once. Pangrams are often used to demonstrate fonts in printing or test the output devices.
You are given a string consisting of lowercase and uppercase Latin letters. Check whether thi... | 3 | def panagram(values):
if len(set(values))<26:
return 'NO'
else:
values=values.lower()
alphabets=[]
for i in range(26):
alphabets.append(chr(97+i))
values=list(set(list(values)))
values.sort()
if alphabets==values:
return 'Yes'
... |
Write a program which prints small/large/equal relation of given two integers a and b.
Constraints
* -1000 β€ a, b β€ 1000
Input
Two integers a and b separated by a single space are given in a line.
Output
For given two integers a and b, print
a < b
if a is less than b,
a > b
if a is greater than b, and
a... | 3 | a,b= map(int,input().split(" "))
if a > b:
print("a > b")
elif a < b:
print("a < b")
elif a == b:
print("a == b") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.