problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
Gildong is developing a game consisting of n stages numbered from 1 to n. The player starts the game from the 1-st stage and should beat the stages in increasing order of the stage number. The player wins the game after beating the n-th stage.
There is at most one checkpoint on each stage, and there is always a checkp... | 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... |
Blackjack is a type of card game played in casinos, where the game is played using cards with numbers from 1 to 13. The score of each card is decided as follows.
* 1 is 1 point or 11 points
* From 2 to 9, the score is as written.
* 10 points from 10 to 13
There are several participants in this game, including paren... | 3 | def solve():
c = list(map(int, input().split()))
c = [min(10, e) for e in c]
if c == [0]:
return 1
if len(c) > 21:
print(0)
return 0
else:
ans = 0
for bit in range(1 << len(c)):
s = 0
for i in range(len(c)):
if c[i]... |
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 | mass = []
new_mass = []
string = input()
mass.extend(string)
mass.append('x')
i = 0
while i < len(mass):
if mass[i] == '.':
new_mass.append('0')
elif mass[i] == '-' and mass[i+1] == '.':
new_mass.append('1')
i += 1
elif mass[i] == '-' and mass[i+1] == '-':
new_mass.append('2... |
There were n types of swords in the theater basement which had been used during the plays. Moreover there were exactly x swords of each type. y people have broken into the theater basement and each of them has taken exactly z swords of some single type. Note that different people might have taken different types of swo... | 3 | n = int(input())
l = list(map(int, input().split()))
def find_gcd(x, y):
while(y):
x, y = y, x % y
return x
lmax = max(l)
m = l.copy()
for i in range(len(m)):
m[i] = lmax-m[i]
# print(m)
num1=m[0]
num2=m[1]
gcd=find_gcd(num1,num2)
for i in range(2,len(m)):
gcd=find_gcd(gcd,m[i]... |
A prime number is a natural number which has exactly two distinct natural number divisors: 1 and itself. For example, the first four prime numbers are: 2, 3, 5 and 7.
Write a program which reads a list of N integers and prints the number of prime numbers in the list.
Constraints
1 β€ N β€ 10000
2 β€ an element of the ... | 3 | import math
N = int(input())
count = 0
for _ in range(N):
x = int(input())
for i in range(2,int(math.sqrt(x)+1)):
if x % i == 0:
break
else:
count += 1
print(count)
|
The USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of n haybale piles on the farm. The i-th pile contains a_i haybales.
However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an a... | 3 | ### A. Cow and Haybales
for _ in range(int(input())):
n,d=map(int, input().split())
arr=[int(x) for x in input().split()]
m=arr[0]
for i in range(1,n):
q=min(arr[i], d//i)
a=q*i;d-=a;m+=q
print(m) |
You have a coins of value n and b coins of value 1. You always pay in exact change, so you want to know if there exist such x and y that if you take x (0 β€ x β€ a) coins of value n and y (0 β€ y β€ b) coins of value 1, then the total value of taken coins will be S.
You have to answer q independent test cases.
Input
The... | 3 | for _ in range(int(input())):
a, b, n, S = [int(x) for x in input().split()]
print('YES' if (S - min(S // n, a)*n <= b) else 'NO') |
Write a program which reads an integer n and prints the factorial of n. You can assume that n β€ 20.
Input
An integer n (1 β€ n β€ 20) in a line.
Output
Print the factorial of n in a line.
Example
Input
5
Output
120 | 3 | def Factorial(n):
if n <= 1: return 1
return n*Factorial(n-1)
print(Factorial(int(input())))
|
You are given array consisting of n integers. Your task is to find the maximum length of an increasing subarray of the given array.
A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray strictly greater than previous.
Input
The first line cont... | 3 | input()
Array = list(map(int, input().split()))
ans = 0
greatestAns = 0
previousElement = 0
for element in Array:
if element > previousElement:
ans += 1
else:
ans = 1
previousElement = element
if ans > greatestAns:
greatestAns = ans
print(greatestAns) |
Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones.
Once he thought about a string of length n consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and ... | 3 | n = int(input())
s = input()
n1 = s.count("1")
n0 = n-n1
print(abs(n1-n0))
|
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):
if (sum((int(x) for x in input().split(' ')),0)>=2):
s+=1
print(s) |
DZY loves chessboard, and he enjoys playing with it.
He has a chessboard of n rows and m columns. Some cells of the chessboard are bad, others are good. For every good cell, DZY wants to put a chessman on it. Each chessman is either white or black. After putting all chessmen, DZY wants that no two chessmen with the sa... | 3 | neighbours = ((0, -1), (-1, 0), (0, 1), (1, 0))
def get_neighbours(mat, idx, idy, n, m, neighbour_val):
ans = []
for n_x, n_y in neighbours:
if 0 <= idx+n_x < n and 0 <= idy+n_y < m and mat[idx+n_x][idy+n_y] == ".":
ans.append((idx+n_x,idy+n_y, "B" if neighbour_val == "W" else "W"))
... |
We just discovered a new data structure in our research group: a suffix three!
It's very useful for natural language processing. Given three languages and three suffixes, a suffix three can determine which language a sentence is written in.
It's super simple, 100% accurate, and doesn't involve advanced machine learni... | 3 | n = int(input())
z=[]
for i in range(0,n):
s = input()
l=list(s)
if(l[-1]=="o"):
z.append("FILIPINO")
elif(l[-1]=="u"):
z.append("JAPANESE")
elif(l[-1]=="a"):
z.append("KOREAN")
for i in range(0,n):
print(z[i],"\r")
|
Omkar is building a waterslide in his water park, and he needs your help to ensure that he does it as efficiently as possible.
Omkar currently has n supports arranged in a line, the i-th of which has height a_i. Omkar wants to build his waterslide from the right to the left, so his supports must be nondecreasing in he... | 3 | for _ in range(int(input())):
sum=0
n = int(input())
ls=list(map(int,input().split()))
for i in range(n-1):
if ls[i]>ls[i+1]:
sum+=abs(ls[i+1]-ls[i])
print(sum)
|
Write a program which reads a sequence of integers $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and rotate specified elements by a list of the following operation:
* rotate($b, m, e$): For each integer $k$ ($0 \leq k < (e - b)$), move element $b + k$ to the place of element $b + ((k + (e - m)) \mod (e - b))$.
Constraints
* $1... | 3 | n = int(input())
a = list(map(int,input().split()))
q = int(input())
for i in range(q):
b,m,e = map(int,input().split())
s = a[b:e]
a = a[:b] + s[m-b:] + s[:m-b] + a[e:]
print(*a)
|
In this problem, a n Γ m rectangular matrix a is called increasing if, for each row of i, when go from left to right, the values strictly increase (that is, a_{i,1}<a_{i,2}<...<a_{i,m}) and for each column j, when go from top to bottom, the values strictly increase (that is, a_{1,j}<a_{2,j}<...<a_{n,j}).
In a given ma... | 3 | n , m =[int(i) for i in input().split()]
a = [[int(j) for j in input().split()] for i in range(n)]
wa = 0
for y in range(n):
if y != 0 and (a[y][0] <= a[y - 1][0] or a[y][m - 1] <= a[y - 1][m - 1]):
wa = 1
for y in range(m):
if y != 0 and (a[0][y] <= a[0][y - 1] or a[n - 1][y] <= a[n - 1][y - 1]):
... |
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.
* Determine the largest element in the sequence (if there is more than one, choose one). Decrease the value of this element... | 1 | b=input();a=b/50+49;b%=50;c=50-b;print"50\n"+(`a-b`+" ")*c+(`a+c`+" ")*b |
A stowaway and a controller play the following game.
The train is represented by n wagons which are numbered with positive integers from 1 to n from the head to the tail. The stowaway and the controller are initially in some two different wagons. Every minute the train can be in one of two conditions β moving or idle... | 1 | from sys import stdin
rints = lambda: [int(x) for x in stdin.readline().split()]
rstr = lambda: stdin.readline().strip()
mem = {'to head': -1, 'to tail': 1}
n, sto, con = rints()
dire, train, ans = mem[rstr()], rstr(), 'Stowaway'
for i in range(len(train)):
if train[i] == '1':
sto = -1
else:
... |
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.
Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya'... | 3 | s=input().split()
n=int(s[0])
m=int(s[1])
mas=input().split()
for i in range(n):
mas[i]=int(mas[i])
mas.sort()
mas.append(10**9)
mas.insert(0,0)
s=0
res=[]
flag=True
for i in range(n+1):
for y in range(mas[i]+1,mas[i+1]):
s=s+y
if s<=m:
res.append(y)
else:
... |
You are given three integers a, b and x. Your task is to construct a binary string s of length n = a + b such that there are exactly a zeroes, exactly b ones and exactly x indices i (where 1 β€ i < n) such that s_i β s_{i + 1}. It is guaranteed that the answer always exists.
For example, for the string "01010" there ar... | 3 | a,b,x=map(int,input().split())
if a<b:
a,b=b,a
c=['1','0']
else:
c=['0','1']
s=c[0]*(a-x//2)+c[1]*(b-(x-1)//2)
for i in range(x-1):
if i%2==0:
s+=c[0]
else:
s+=c[1]
print(s)
|
You are given an array A, consisting of n positive integers a_1, a_2, ..., a_n, and an array B, consisting of m positive integers b_1, b_2, ..., b_m.
Choose some element a of A and some element b of B such that a+b doesn't belong to A and doesn't belong to B.
For example, if A = [2, 1, 7] and B = [1, 3, 4], we can ... | 3 | n=int(input())
a=list(map(int,input().split()))
m=int(input())
b=list(map(int,input().split()))
flag=0
for i in range(n):
x=a[i]
for j in range(m):
y=b[j]
s=x+y
if(s not in a and s not in b):
flag=1
break
if(flag==1):
break
print(x,y) |
For a positive integer n let's define a function f:
f(n) = - 1 + 2 - 3 + .. + ( - 1)nn
Your task is to calculate f(n) for a given integer n.
Input
The single line contains the positive integer n (1 β€ n β€ 1015).
Output
Print f(n) in a single line.
Examples
Input
4
Output
2
Input
5
Output
-3
Note
f(4)... | 3 | n=int(input())
s=0
if n%2==0:
s=n//2
else: s=-(n//2+1)
print(s) |
You are given an array a_1, a_2, ..., a_n and an integer k.
You are asked to divide this array into k non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let f(i) be the index of subarray the i-th element belongs to. Subarrays are numbered from left to right and from... | 3 | def gns():
return list(map(int,input().split()))
n,k=gns()
ns=gns()
sm=[ns[-1]]
for i in reversed(range(n-1)):
sm.append(sm[-1]+ns[i])
ans=sm.pop()
sm.sort()
if k>1:
ans+=sum(sm[-k+1:])
print(ans)
|
Let's call a string a phone number if it has length 11 and fits the pattern "8xxxxxxxxxx", where each "x" is replaced by a digit.
For example, "80123456789" and "80000000000" are phone numbers, while "8012345678" and "79000000000" are not.
You have n cards with digits, and you want to use them to make as many phone n... | 3 | n = int(input())
a = input()
a0 = 0
a1 = 0
a2 = 0
a3 = 0
a4 = 0
a5 = 0
a6 = 0
a7 = 0
a8 = 0
a9 = 0
for i in a:
if i == '0':
a0 += 1
if i == '1':
a1 += 1
if i == '2':
a2 += 1
if i == '3':
a3 += 1
if i == '4':
a4 += 1
if i == '5':
a5 += 1
if i ==... |
While sailing on a boat, Inessa noticed a beautiful water lily flower above the lake's surface. She came closer and it turned out that the lily was exactly H centimeters above the water surface. Inessa grabbed the flower and sailed the distance of L centimeters. Exactly at this point the flower touched the water surfac... | 3 | (h, l) = (int(x) for x in input().split())
d = (l*l - h*h) / (2*h)
print(d) |
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 | for t in range(int(input())):
n,k = map(int,input().split())
l = list(input())
ans=0
if ('1' not in l):
l[0]='1'
ans=1
if '1' not in l[:k+1]:
l[0]='1'
ans=1
if '1' not in l[-k-1:]:
l[-1]='1'
ans+=1
for i in range(k,len(l)-k-1):
if '1' n... |
You are given a regular polygon with n vertices labeled from 1 to n in counter-clockwise order. The triangulation of a given polygon is a set of triangles such that each vertex of each triangle is a vertex of the initial polygon, there is no pair of triangles such that their intersection has non-zero area, and the tota... | 3 | n=int(input())
j=1
k=3
sum=0
for i in range(1,n-1):
sum=sum+(j*(k-1)*k)
k=k+1
print(sum)
|
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 | M,N = map(int, input().split())
nbofDominos = 0
if(M % 2 == 0):
nbofDominos = (M * N) / 2
else:
nbofDominos = (M * N) // 2
print(int(nbofDominos)) |
"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 | a,b=[int(x) for x in input().split()]
c=[int(x) for x in input().split()]
d=0
for x in range(a):
if c[x]>=c[b-1] and c[x]>0:
d+=1
print(d)
|
Let LCM(x, y) be the minimum positive integer that is divisible by both x and y. For example, LCM(13, 37) = 481, LCM(9, 6) = 18.
You are given two integers l and r. Find two integers x and y such that l β€ x < y β€ r and l β€ LCM(x, y) β€ r.
Input
The first line contains one integer t (1 β€ t β€ 10000) β the number of tes... | 3 | a = int(input())
for i in range(a):
st = str(input()).split(' ')
l = int(st[0])
r = int(st[1])
if r>= 2*l:
print(l,2*l)
else:
print(-1,-1) |
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network.
Bu... | 3 | str=input()
s=set()
for c in str:
s.add(c)
if(len(s)%2==0):
print("CHAT WITH HER!")
else:
print("IGNORE HIM!") |
Petya has n integers: 1, 2, 3, ..., n. He wants to split these integers in two non-empty groups in such a way that the absolute difference of sums of integers in each group is as small as possible.
Help Petya to split the integers. Each of n integers should be exactly in one group.
Input
The first line contains a s... | 1 | n = input()
sum1 = sum2 = now = 0
ans = []
for i in range(n,0,-1):
if sum1 > sum2:
sum2 += i
else:
sum1 += i
ans.append(i)
now += i
print now%2
print len(ans)
for i in ans:
print i, |
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 β€ i β€ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is it... | 3 | def kefa(arr, n):
i = 1
c = 1
maxi = 1
while(i < n):
if arr[i] >= arr[i-1]:
c += 1
maxi = max(maxi, c)
else:
c = 1
i += 1
return maxi
n = int(input())
arr = list(map(int, input().split()))
print(kefa(arr, n)) |
There are two sisters Alice and Betty. You have n candies. You want to distribute these n candies between two sisters in such a way that:
* Alice will get a (a > 0) candies;
* Betty will get b (b > 0) candies;
* each sister will get some integer number of candies;
* Alice will get a greater amount of candie... | 3 | from sys import stdin
from collections import deque
from math import sqrt, floor, ceil, log, log2, log10, pi, gcd, sin, cos, asin
def ii(): return int(stdin.readline())
def fi(): return float(stdin.readline())
def mi(): return map(int, stdin.readline().split())
def fmi(): return map(float, stdin.readline().split())
def... |
Karl likes Codeforces and subsequences. He wants to find a string of lowercase English letters that contains at least k subsequences codeforces. Out of all possible strings, Karl wants to find a shortest one.
Formally, a codeforces subsequence of a string s is a subset of ten characters of s that read codeforces from ... | 3 | k = int(input())
product = 1
lc = len("codeforces")
storage = [1] * lc
i = 0
while product < k:
v = storage[i]
storage[i] += 1
product /= v
product *= storage[i]
i = (i + 1) % lc
o = ""
for v, c in zip(storage, "codeforces"):
o += v * c
print(o)
|
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.
The valid sizes of T-shirts are either "M" or from 0 to 3 "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not.
Ther... | 3 | n=int(input())
a,b=[],[]
for i in range(n):
a.append(str(input()))
for i in range(n):
b.append(str(input()))
c,f=0,[False for i in range(n)]
for i in range(n):
l=len(b)
for j in range(l):
if a[i]==b[j]:
f[i]=True
b.pop(j)
break
#print(a,b,f)
l=len(b)
for i in range(l):
mn=len(b[i])
for j in ran... |
When preparing a tournament, Codeforces coordinators try treir best to make the first problem as easy as possible. This time the coordinator had chosen some problem and asked n people about their opinions. Each person answered whether this problem is easy or hard.
If at least one of these n people has answered that th... | 3 | n = int(input())
input_string = input()
if '1' in input_string:
print('HARD')
else:
print('EASY') |
You are given the array a consisting of n positive (greater than zero) integers.
In one move, you can choose two indices i and j (i β j) such that the absolute difference between a_i and a_j is no more than one (|a_i - a_j| β€ 1) and remove the smallest of these two elements. If two elements are equal, you can remove a... | 3 | testcases = int(input())
for t in range(testcases):
ans = 0
n = int(input())
odd = 0
even = 0
l = list(map(int,input().split()))
for i in range(n):
if l[i]%2==1:
odd+=1
else:
even+=1
if odd>=1 and even==0 and n%2==0:
ans = 'NO'
elif even>=1 and odd==0:
ans = 'NO'
else:
... |
Mikhail walks on a 2D plane. He can go either up or right. You are given a sequence of Mikhail's moves. He thinks that this sequence is too long and he wants to make it as short as possible.
In the given sequence moving up is described by character U and moving right is described by character R. Mikhail can replace an... | 3 | n = int(input())
s = input()
count = len(s)
i = 1
while i < len(s):
if (s[i] == "U" and s[i - 1] == "R") or (s[i] == "R" and s[i - 1] == "U"):
count -= 1
i += 1
i += 1
print(count) |
As you could know there are no male planes nor female planes. However, each plane on Earth likes some other plane. There are n planes on Earth, numbered from 1 to n, and the plane with number i likes the plane with number fi, where 1 β€ fi β€ n and fi β i.
We call a love triangle a situation in which plane A likes plane... | 3 | a=int(input())
l=input().split()
l.insert(0,0)
flag=False
for i in range(a):
if (l[i]==l[int(l[int(l[int(l[i])])])]) and l[i]!=l[int(l[i])] and l[int(l[int(l[i])])]!=l[int(l[i])]:
print ("YES")
flag=True
break
if flag==False:
print("NO")
|
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 | n=int(input())
while(True):
n+=1
a=n//1000
b=n//100%10
c=n//10%10
d=n%10
if(a!=b and a!=d and a!=c and b!=c and b!=d and c!=d):
break
print(n) |
You are given n arrays a_1, a_2, ..., a_n; each array consists of exactly m integers. We denote the y-th element of the x-th array as a_{x, y}.
You have to choose two arrays a_i and a_j (1 β€ i, j β€ n, it is possible that i = j). After that, you will obtain a new array b consisting of m integers, such that for every k ... | 3 | '''input
6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
'''
# A coding delight
from sys import stdin, stdout
import gc
gc.disable()
input = stdin.readline
from collections import defaultdict
def check(num):
bitmask = set()
for i in range(n):
b = 0
for j in range(m):
if arr[i][j] >= num:
... |
Alice is playing with some stones.
Now there are three numbered heaps of stones. The first of them contains a stones, the second of them contains b stones and the third of them contains c stones.
Each time she can do one of two operations:
1. take one stone from the first heap and two stones from the second heap (... | 3 | for _ in range(int(input())):
a, b, c = [int(x) for x in input().split()]
operations = min(c // 2, b)
b -= operations
operations += min(a, b // 2)
print(operations * 3) |
It is known that the area of a regular dodecagon inscribed in a circle of radius a is 3a^2.
Given an integer r, find the area of a regular dodecagon inscribed in a circle of radius r.
Constraints
* 1 \leq r \leq 100
* r is an integer.
Input
Input is given from Standard Input in the following format:
r
Output
... | 3 | #134
a = int(input())
print(3*a**2) |
Some country is populated by wizards. They want to organize a demonstration.
There are n people living in the city, x of them are the wizards who will surely go to the demonstration. Other city people (n - x people) do not support the wizards and aren't going to go to the demonstration. We know that the city administr... | 3 | n,x,y = input().split()
n=int(n)
x=int(x)
y=int(y)
p=(y/100)*n
if(p!=int(p)):
p=int(p+1)
else:
p=int(p)
r=p-x
if(r>=0):
print(r)
else:
print(0)
|
The last contest held on Johnny's favorite competitive programming platform has been received rather positively. However, Johnny's rating has dropped again! He thinks that the presented tasks are lovely, but don't show the truth about competitors' skills.
The boy is now looking at the ratings of consecutive participan... | 3 | import sys
from collections import Counter
T = int(input().strip())
for t in range(T):
n= int(input().strip())
# a,b = list(map(int, input().strip().split()))
res = 0
d= 1
while n+1 > d:
res += ( (n+1)//d + (1 if (n+1)%d else 0) ) - 1
d *= 2
print(res)
|
Duff is in love with lovely numbers! A positive integer x is called lovely if and only if there is no such positive integer a > 1 such that a2 is a divisor of x.
<image>
Malek has a number store! In his store, he has only divisors of positive integer n (and he has all of them). As a birthday present, Malek wants to g... | 3 | # Duff in Love
n = int(input())
i = 1
div = []
while i <= n and i < 10 ** 6:
if n % i == 0:
div.append(i)
i += 1
i = 1
while i < len(div):
if n % (div[i] ** 2) == 0:
n //= div[i]
i = 1
else:
i += 1
print(n)
|
PolandBall is a young, clever Ball. He is interested in prime numbers. He has stated a following hypothesis: "There exists such a positive integer n that for each positive integer m number nΒ·m + 1 is a prime number".
Unfortunately, PolandBall is not experienced yet and doesn't know that his hypothesis is incorrect. Co... | 3 | import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return list(map(int, sys.stdin.readline().spli... |
You are given two integers n and k. Your task is to find if n can be represented as a sum of k distinct positive odd (not divisible by 2) integers or not.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 10^5) β the number of test cases.
The next t lines... | 3 | for _ in range(int(input())):
n,m=map(int,input().split())
if n%2==m%2 and n>=m**2:
print("YES")
else:
print("NO") |
One day, n people (n is an even number) met on a plaza and made two round dances, each round dance consists of exactly n/2 people. Your task is to find the number of ways n people can make two round dances if each round dance consists of exactly n/2 people. Each person should belong to exactly one of these two round da... | 3 | # -*- coding: utf-8 -*-
"""
@author: Saurav Sihag
"""
rr = lambda: input().strip()
rri = lambda: int(rr())
# rri = lambda: int(stdin.readline())
rrm = lambda: [int(x) for x in rr().split()]
# stdout.write(str()+'\n')
from sys import stdin, stdout, setrecursionlimit
from math import ceil, factorial as fact
from heapq ... |
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 =map(int, input().split())
s =input()
t = set(s)
c =0
if k <= len(t):
c =len(s)
for i in t:
c =min(c,s.count(i))
print(c*k)
|
Some country is populated by wizards. They want to organize a demonstration.
There are n people living in the city, x of them are the wizards who will surely go to the demonstration. Other city people (n - x people) do not support the wizards and aren't going to go to the demonstration. We know that the city administr... | 3 | n , x , y = map(int,input('').split(" "))
s = (y * n)
if s % 100 !=0:
s = int(s / 100)
s = s+1
else :
s = int(s / 100)
if s < x:
ans = 0
else:
ans = s - x
print(ans) |
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.
Namely, it takes several iterations to calculate value v. At the first iteration, Xeni... | 1 | # import sys
# sys.stdin = open('d3.in')
n, m = [int(v) for v in raw_input().split()]
tree = [[int(v) for v in raw_input().split()]]
now_or = True
while len(tree[-1]) > 1:
last = tree[-1]
if now_or:
tree.append([last[i] | last[i+1] for i in xrange(0, len(last), 2)])
else:
tree.append([last[i] ^ last[i+1] for i... |
There is a building consisting of 10~000 apartments numbered from 1 to 10~000, inclusive.
Call an apartment boring, if its number consists of the same digit. Examples of boring apartments are 11, 2, 777, 9999 and so on.
Our character is a troublemaker, and he calls the intercoms of all boring apartments, till someone... | 3 | t = int(input())
for q in range(t):
n = input()
a = n[0]
ans = 0
if(int(a) !=1):
ans += (int(a)-1)*10
c = len(n)
ans += (c*(c+1))/2
print(int(ans)) |
You are given a string, consisting of lowercase Latin letters.
A pair of neighbouring letters in a string is considered ugly if these letters are also neighbouring in a alphabet. For example, string "abaca" contains ugly pairs at positions (1, 2) β "ab" and (2, 3) β "ba". Letters 'a' and 'z' aren't considered neighbou... | 3 | def check(s):
for i in range(len(s) - 1):
if abs(ord(s[i]) - ord(s[i + 1])) == 1:
return 0
return 1
t = int(input())
for _ in range(t):
o = list()
e = list()
s = input()
for i in range(len(s)):
if ord(s[i]) % 2 == 1:
o.append(s[i])
else:
... |
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word.
Note, that during capitalization all the letters except the first one remains unchanged.
Input
A single line contains a non-empty word. This word consists of lowercase and uppercase English letters.... | 3 | s=input();print(s[0].capitalize()+s[1::]) |
Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him.
One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For e... | 1 | n = int(raw_input())
act = map(int, raw_input().split())
col = 0
for i in range(1, n):
if act[i] > max(act[:i]) or act[i] < min(act[:i]):
col += 1
print col |
Today Johnny wants to increase his contribution. His plan assumes writing n blogs. One blog covers one topic, but one topic can be covered by many blogs. Moreover, some blogs have references to each other. Each pair of blogs that are connected by a reference has to cover different topics because otherwise, the readers ... | 1 | import collections
FAST_IO = 1
if FAST_IO:
import io, sys, atexit
rr = iter(sys.stdin.read().splitlines()).next
sys.stdout = _OUTPUT_BUFFER = io.BytesIO()
@atexit.register
def write():
sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
else:
rr = raw_input
rri = lambda: int(rr())
rrm = lam... |
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 | t=int(input())
for i in range(t):
a,b,x,y=map(int,input().split())
f=a*(b-y-1)
g=(a-x-1)*b
h=a*y
i=b*x
print(max(f,g,h,i)) |
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 | x,y=map(int,input().split())
y = y//2
print(x+y) |
Each evening after the dinner the SIS's students gather together to play the game of Sport Mafia.
For the tournament, Alya puts candies into the box, which will serve as a prize for a winner. To do that, she performs n actions. The first action performed is to put a single candy into the box. For each of the remainin... | 3 | import math
def f(n,k):
m = int(math.sqrt((n+k+1)<<1))
return n-m+1
n,k = list(map(int,input().split()))
print(f(n,k))
|
The Cereal Guy's friend Serial Guy likes to watch soap operas. An episode is about to start, and he hasn't washed his plate yet. But he decided to at least put in under the tap to be filled with water. The plate can be represented by a parallelepiped k Γ n Γ m, that is, it has k layers (the first layer is the upper one... | 3 | k, n, m = map(int, input().split())
visited = [[[False] * m for _ in range(n)] for _ in range(k)]
grid = []
input()
for i in range(k):
grid.append([])
for _ in range(n):
grid[-1].append(input())
input()
r, c = map(lambda x: int(x) - 1, input().split())
dirs = [(0, 0, 1), (0, 0, -1), (0, 1, 0), (0, -... |
There is an apple tree that bears apples of N colors. The N colors of these apples are numbered 1 to N, and there are a_i apples of Color i.
You and Lunlun the dachshund alternately perform the following operation (starting from you):
* Choose one or more apples from the tree and eat them. Here, the apples chosen at ... | 3 | n = int(input())
for i in range(n):
a = int(input())
if a % 2 == 1:
print("first")
exit(0)
print("second")
|
When Petya went to school, he got interested in large numbers and what they were called in ancient times. For instance, he learned that the Russian word "tma" (which now means "too much to be counted") used to stand for a thousand and "tma tmyschaya" (which literally means "the tma of tmas") used to stand for a million... | 3 | import sys
#my_file = sys.stdin
#my_file = open("input.txt", "r")
k = int(input())
l = int(input())
for i in range(1, l//k+1):
if k**i == l:
print("YES")
print(i-1)
break
elif k**i > l:
print("NO")
break
else:
print("NO") |
Polycarp has n coins, the value of the i-th coin is a_i. It is guaranteed that all the values are integer powers of 2 (i.e. a_i = 2^d for some non-negative integer number d).
Polycarp wants to know answers on q queries. The j-th query is described as integer number b_j. The answer to the query is the minimum number of... | 3 | #!/usr/bin/env python3
# encoding: utf-8
#----------
# Constants
#----------
DEGREE_ARRAY_SIZE = 32
#----------
# Functions
#----------
def convert(a):
from collections import Counter
b = [ 0 for i in range(DEGREE_ARRAY_SIZE) ]
for val, cnt in Counter(a).items():
b[val.bit_length()-1] += cnt
... |
One day Ms Swan bought an orange in a shop. The orange consisted of nΒ·k segments, numbered with integers from 1 to nΒ·k.
There were k children waiting for Ms Swan at home. The children have recently learned about the orange and they decided to divide it between them. For that each child took a piece of paper and wrote... | 3 | inp=list(map(int,input().split()))
n,k=inp
arr=[]
for i in range(k+1):
arr.append([])
from collections import Counter
a=list(map(int,input().split()))
for i in range(len(a)):
arr[i+1].append(a[i])
c=Counter(a)
j=1
for i in range(1,n*k+1):
if c[i]!=0:
continue
if len(arr[j])==n:
j+=1
... |
Sitting in a station waiting room, Joisino is gazing at her train ticket.
The ticket is numbered with four digits A, B, C and D in this order, each between 0 and 9 (inclusive).
In the formula A op1 B op2 C op3 D = 7, replace each of the symbols op1, op2 and op3 with `+` or `-` so that the formula holds.
The given in... | 1 | # coding: utf-8
s = raw_input()
for op1 in "+-":
for op2 in "+-":
for op3 in "+-":
e = s[0] + op1 + s[1] + op2 + s[2] + op3 + s[3]
if eval(e) == 7:
print e + "=7"
exit(0)
|
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If... | 3 | situation = input()
danger = 0
count1 = 0
count0 = 0
for i in range(len(situation)):
if situation[i] == '0':
count0 += 1
count1 = 0
else:
count0 = 0
count1 += 1
if count0 == 7:
danger = 1
break
if count1 == 7:
danger = 1
break
if danger... |
Tomorrow is a difficult day for Polycarp: he has to attend a lectures and b practical classes at the university! Since Polycarp is a diligent student, he is going to attend all of them.
While preparing for the university, Polycarp wonders whether he can take enough writing implements to write all of the lectures and d... | 3 | if __name__ == "__main__":
t=int(input())
for i in range(t):
a,b,c,d,k=map(int,input().split())
if a%c==0:
x=a//c
else:
x=a//c+1
if b%d==0:
y=b//d
else:
y=b//d+1
if x+y<=k:
print(x,end=' ')
pr... |
A student of z-school found a kind of sorting called z-sort. The array a with n elements are z-sorted if two conditions hold:
1. ai β₯ ai - 1 for all even i,
2. ai β€ ai - 1 for all odd i > 1.
For example the arrays [1,2,1,2] and [1,1,1,1] are z-sorted while the array [1,2,3,4] isnβt z-sorted.
Can you make the... | 1 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# p=[0*100]
# print p
def zsort(lists):
lists.sort()
newlist=[]
lens=len(lists)
newlist=[0 for k in range(lens)]
k=0
p=0
while k<lens:
newlist[k]=lists[p]
k+=2
p+=1
k=1
while k<lens:
newlist[k]=lists[p]
... |
Pasha has a wooden stick of some positive integer length n. He wants to perform exactly three cuts to get four parts of the stick. Each part must have some positive integer length and the sum of these lengths will obviously be n.
Pasha likes rectangles but hates squares, so he wonders, how many ways are there to spli... | 3 | import math
def PashaAndSticks(n):
if n%2==1:
return 0
cnt= math.floor(n/4)
if n%4==0:
return cnt-1
else:
return cnt
n = int(input())
print(PashaAndSticks(n)) |
You are given a string s consisting of lowercase Latin letters and q queries for this string.
Recall that the substring s[l; r] of the string s is the string s_l s_{l + 1} ... s_r. For example, the substrings of "codeforces" are "code", "force", "f", "for", but not "coder" and "top".
There are two types of queries:
... | 3 | from sys import stdin, stdout
read = stdin.readline
a = ord('a')
def get_bit(q): return 1 << ord(q) - a
SIZE = 1 << 17
TOP = 2 * SIZE - 2
def read_tree():
bits = list(map(get_bit, read()[:-1]))
bits += [0] * (2 * SIZE - len(bits))
i, j = 0, SIZE
while i < j:
bits[j] = bits[i] | bits[i + 1]
... |
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 | q = int(input())
for i in range(q):
s = str(input()).split()
n = int(s[0])
a = int(s[1])
b = int(s[2])
min_money = 2*n*(a+b)
k = n//2
money = b*k + (n-2*k)*a
if money < min_money:
min_money = money
k = 0
money = n*a
if money < min_money:
min_money = money
k = b - 2*a
money = b*k + (n-2*k)*a
if money ... |
The Little Elephant has got a problem β somebody has been touching his sorted by non-decreasing array a of length n and possibly swapped some elements of the array.
The Little Elephant doesn't want to call the police until he understands if he could have accidentally changed the array himself. He thinks that he could ... | 3 | n=int(input())
z=n*[0]
a=[int(i) for i in input().split()]
z[ : ]=a[ : ]
z.sort()
t=0
for i in range(n):
if z[i]!=a[i]:
t=t+1
if t>2:
print('NO')
else:
print('YES')
|
Along a road running in an east-west direction, there are A shrines and B temples. The i-th shrine from the west is located at a distance of s_i meters from the west end of the road, and the i-th temple from the west is located at a distance of t_i meters from the west end of the road.
Answer the following Q queries:
... | 3 | import sys
input = sys.stdin.readline
from bisect import bisect
inf = float('inf')
A,B,Q = map(int,input().split())
S = [-inf] + [int(input()) for _ in range(A)] + [inf]
T = [-inf] + [int(input()) for _ in range(B)] + [inf]
X = [int(input()) for _ in range(Q)]
for x in X:
ans = inf
si = bisect(S,x)
ti =... |
You are given a string s consisting of exactly n characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.
Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string ... | 3 | a = int(input())
s = str(input())
z = 0
o = 0
t = 0
for i in s:
if i == '0':
z += 1
if i == '1':
o += 1
if i == '2':
t += 1
num = a // 3
zn = num - z
on = num - o
tn = num - t
if z == o == t:
print(s)
else:
zm = 0
om = 0
tm = 0
s = list(s)
for i in range(0, a)... |
Roma (a popular Russian name that means 'Roman') loves the Little Lvov Elephant's lucky numbers.
Let us remind you that lucky numbers are positive integers whose decimal representation only contains lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Roma's got n positive integers.... | 3 | # bsdk idhar kya dekhne ko aaya hai, khud kr!!!
# from math import *
# from itertools import *
# import random
n, k = map(int, input().split())
arr = list(map(str, input().split()))
count_ = 0
for i in arr:
if (i.count("4") + i.count("7")) > k:
continue
else:
count_ += 1
print(count_)
|
Let's call a positive integer composite if it has at least one divisor other than 1 and itself. For example:
* the following numbers are composite: 1024, 4, 6, 9;
* the following numbers are not composite: 13, 1, 2, 3, 37.
You are given a positive integer n. Find two composite integers a,b such that a-b=n.
I... | 3 | def is_compound(n):
for i in range(2, n):
if(n % i == 0):
return True
return False
n = int(input())
a = 0
b = 0
for b in range(0, 10 ** 9):
if(is_compound(b)):
a = n + b
if(is_compound(a)):
break
else:
continue
print(a, b)
|
Polycarpus adores TV series. Right now he is ready to finish watching a season of a popular sitcom "Graph Theory". In total, the season has n episodes, numbered with integers from 1 to n.
Polycarpus watches episodes not one by one but in a random order. He has already watched all the episodes except for one. Which epi... | 3 | n=int(input())
watched=list(map(int,input().split()))
watched.sort()
for i in range(len(watched)):
if watched[i]!=i+1:
print(i+1)
break
if watched[i]==len(watched):
print(len(watched)+1) |
Tired of boring office work, Denis decided to open a fast food restaurant.
On the first day he made a portions of dumplings, b portions of cranberry juice and c pancakes with condensed milk.
The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes... | 3 | from itertools import chain, combinations
def powerset(iterable):
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
for _ in range(int(input())):
a = sorted(list(map(int, input().split())), r... |
Polycarp loves ciphers. He has invented his own cipher called repeating.
Repeating cipher is used for strings. To encrypt the string s=s_{1}s_{2} ... s_{m} (1 β€ m β€ 10), Polycarp uses the following algorithm:
* he writes down s_1 ones,
* he writes down s_2 twice,
* he writes down s_3 three times,
* ...
... | 3 | def ans(arr):
n = len(arr)
s = ''
if(n % 2):
#left
stop = n // 2
arr1 = arr[0 : stop] + [''] * n
arr2 = arr[stop + 1 :][::-1] + [''] * n
j, k = 0, 0
for i in range(n - 1):
if(i % 2 == 0):
s += arr1[j]
j += 1
... |
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 | x=input()
[k,n,w]=x.split(' ')
k=int(k)
n=int(n)
sum=0
for i in range(int(w)):
sum+=(i+1)*k
if n<sum:
print(abs(sum-n))
else:
print(0) |
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 | from string import ascii_lowercase as letters
s = input()
cnt = 0
idx = 0
for i in s:
pos = letters.find(i)
cnt += min(abs(idx - pos), 26 - abs(idx - pos))
idx = pos
print(cnt) |
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 | n = int(raw_input())
if (n == 35):
ans = 33940307968
elif (n >= 13):
ans = 2 ** n - 100 * 2**(n - 13)
else:
ans = 2**n
print ans
|
Takahashi wants to be a member of some web service.
He tried to register himself with the ID S, which turned out to be already used by another user.
Thus, he decides to register using a string obtained by appending one character at the end of S as his ID.
He is now trying to register with the ID T. Determine whether... | 3 | s = input()
t = input()
print("Yes" if t[:len(s)] == s else "No")
|
Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpr... | 3 | from fractions import Fraction
a = list(map(int,input().split()))
k = max(a)
l = (7-k)/6
print(Fraction(l).limit_denominator() if Fraction(l).limit_denominator()!=1 else '1/1' ) |
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If... | 3 | a=input()
k=1
prev=a[0]
b=False
for i in a[1:]:
if prev==i:
k+=1
else:
k=1
prev=i
if k==7:
b=True
if b:
print("YES")
else:
print("NO")
|
There are N one-off jobs available. If you take the i-th job and complete it, you will earn the reward of B_i after A_i days from the day you do it.
You can take and complete at most one of these jobs in a day.
However, you cannot retake a job that you have already done.
Find the maximum total reward that you can ea... | 3 | import sys
f=lambda:map(int,sys.stdin.readline().split())
n,m=f()
lt=sorted(tuple(map(int,input().split())) for _ in range(n))[::-1]
from heapq import *
q=[]
s=t=0
while t<m:
t+=1
while lt and lt[-1][0]==t:
a,b=lt.pop()
heappush(q,-b)
if q: s-=heappop(q)
print(s) |
Limak and Radewoosh are going to compete against each other in the upcoming algorithmic contest. They are equally skilled but they won't solve problems in the same order.
There will be n problems. The i-th problem has initial score pi and it takes exactly ti minutes to solve it. Problems are sorted by difficulty β it'... | 3 | n, c = map(int, input().split())
p = list(map(int, input().split()))
t = list(map(int, input().split()))
ti = 0
p1 = 0
for i in range(n):
ti += t[i]
p1 += max(0, p[i] - c * ti)
ti = 0
p2 = 0
for i in range(n - 1, -1, -1):
ti += t[i]
p2 += max(0, p[i] - c * ti)
if p1 > p2:
print('Limak')
elif p2 > p1... |
Jon fought bravely to rescue the wildlings who were attacked by the white-walkers at Hardhome. On his arrival, Sam tells him that he wants to go to Oldtown to train at the Citadel to become a maester, so he can return and take the deceased Aemon's place as maester of Castle Black. Jon agrees to Sam's proposal and Sam s... | 3 | def f(n):
if n <= 1:
return n
return 2 * f(n // 2) + n % 2
def g(n):
if n <= 1:
return 1
return 2 * g(n // 2) + 1
def solve(n, x):
global ans
if x == 0:
return
a1 = n // 2
a2 = n % 2
if n <= 1:
if x == 0:
return
else:
... |
Raccoon is fighting with a monster.
The health of the monster is H.
Raccoon can use N kinds of special moves. Using the i-th move decreases the monster's health by A_i. There is no other way to decrease the monster's health.
Raccoon wins when the monster's health becomes 0 or below.
If Raccoon can win without using... | 3 | h,n,*a=map(int,open(0).read().split())
print("Yes" if h<=sum(a) else "No") |
There are n districts in the town, the i-th district belongs to the a_i-th bandit gang. Initially, no districts are connected to each other.
You are the mayor of the city and want to build n-1 two-way roads to connect all districts (two districts can be connected directly or through other connected districts).
If two... | 3 | import math
from collections import deque
from sys import stdin, stdout, setrecursionlimit
from string import ascii_letters
letters = ascii_letters[:26]
from collections import defaultdict
#from functools import reduce
input = stdin.readline
print = stdout.write
for _ in range(int(input())):
n = int(input())
... |
A star is a figure of the following type: an asterisk character '*' in the center of the figure and four rays (to the left, right, top, bottom) of the same positive length. The size of a star is the length of its rays. The size of a star must be a positive number (i.e. rays of length 0 are not allowed).
Let's consider... | 1 | #coding:utf-8
n, m = map (int, raw_input ().split ())
a = ['']*n
u = [[0 for i in range (m)] for j in range (n)]
d = [[0 for i in range (m)] for j in range (n)]
l = [[0 for i in range (m)] for j in range (n)]
r = [[0 for i in range (m)] for j in range (n)]
for i in range (n):
a[i] = raw_input()
#print a[0][5] == '.'... |
A magic island Geraldion, where Gerald lives, has its own currency system. It uses banknotes of several values. But the problem is, the system is not perfect and sometimes it happens that Geraldionians cannot express a certain sum of money with any set of banknotes. Of course, they can use any number of banknotes of ea... | 1 | # #
# CodeForces
# Problem 560A
# Python 2
# #
# Number of moneys
n = input()
# Moneys
a = map(int, raw_input().split())
min_money = min(a)
if min_money>1:
print 1
else:
print -1
|
Two polar bears Menshykov and Uslada from the St.Petersburg zoo and elephant Horace from the Kiev zoo got six sticks to play with and assess the animals' creativity. Menshykov, Uslada and Horace decided to make either an elephant or a bear from those sticks. They can make an animal from sticks in the following way:
... | 1 | from collections import Counter
p = map(int, raw_input().split(' '))
c = Counter(p)
if len(c) > 3:
print "Alien"
elif len(c) == 3:
if 4 in c.values():
print "Bear"
else:
print "Alien"
elif len(c) == 1:
print "Elephant"
else:
if c[p[0]] == 2 or c[p[0]] == 4:
print "Elephant"... |
On her way to programming school tiger Dasha faced her first test β a huge staircase!
<image>
The steps were numbered from one to infinity. As we know, tigers are very fond of all striped things, it is possible that it has something to do with their color. So on some interval of her way she calculated two values β th... | 3 | [a, b] = list(map(int, input().split(" ")))
print("YES" if max(a-b, b-a) <= 1 and a+b > 0 else "NO")
|
Cat Furrier Transform is a popular algorithm among cat programmers to create longcats. As one of the greatest cat programmers ever exist, Neko wants to utilize this algorithm to create the perfect longcat.
Assume that we have a cat with a number x. A perfect longcat is a cat with a number equal 2^m - 1 for some non-ne... | 1 | from collections import deque
import random
import time
seed = int(time.time())
random.seed(seed)
def solve(x):
pos = 0
x2 = x
while x2 > 0:
x2 >>= 1
pos += 1
pos -= 1
it = 0
ops = []
x3 = x
while (x3 & (x3 + 1)) != 0:
it += 1
if it % 2 == 0:
... |
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th... | 3 | n = str(input())
cntr1 = 0
cntr2 = 0
for characters in n:
if characters.isupper():
cntr1 += 1
elif characters.islower():
cntr2 += 1
if cntr1 > cntr2:
print(n.upper())
else:
print(n.lower()) |
Takahashi has a deposit of 100 yen (the currency of Japan) in AtCoder Bank.
The bank pays an annual interest rate of 1 % compounded annually. (A fraction of less than one yen is discarded.)
Assuming that nothing other than the interest affects Takahashi's balance, in how many years does the balance reach X yen or abo... | 3 | x = int(input())
y = 100
n = 0
while y < x:
y += y//100
n += 1
print(n)
|
Recently, Norge found a string s = s_1 s_2 β¦ s_n consisting of n lowercase Latin letters. As an exercise to improve his typing speed, he decided to type all substrings of the string s. Yes, all (n (n + 1))/(2) of them!
A substring of s is a non-empty string x = s[a β¦ b] = s_{a} s_{a + 1} β¦ s_{b} (1 β€ a β€ b β€ n). For e... | 3 | from collections import deque
def solve(arr,alphabet):
last = 0
sections = []
for i in range(len(arr)):
if arr[i] not in alphabet:
sections.append(i-last)
last = i+1
sections.append(i-last+1)
last = i
result = 0
for section in sections:
result += sect... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.