problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
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 | print(3*(int(input()))**2) |
The recent All-Berland Olympiad in Informatics featured n participants with each scoring a certain amount of points.
As the head of the programming committee, you are to determine the set of participants to be awarded with diplomas with respect to the following criteria:
* At least one participant should get a dip... | 3 | n = int(input())
a = set(map(int,input().split()))
if 0 in a:
print(len(a) -1)
else:
print(len(a)) |
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=s.split('+')
l.sort()
s='+'.join(l)
print(s) |
Leo has developed a new programming language C+=. In C+=, integer variables can only be changed with a "+=" operation that adds the right-hand side value to the left-hand side variable. For example, performing "a += b" when a = 2, b = 3 changes the value of a to 5 (the value of b does not change).
In a prototype progr... | 3 | from math import ceil
t = int(input())
for x in range(t):
[a,b,n] = list(map(int, input().strip().split()))
moves = 0
temp = max(a,b)
b = min(a,b)
a = temp
while a <= n and b <= n:
if moves%2 == 0:
b += a
else:
a += b
moves += 1
print(moves) |
A class of students wrote a multiple-choice test.
There are n students in the class. The test had m questions, each of them had 5 possible answers (A, B, C, D or E). There is exactly one correct answer for each question. The correct answer for question i worth a_i points. Incorrect answers are graded with zero points.... | 3 | from collections import Counter
p,m = map(int,input().split())
a = []
for _ in range(p):
a.append(input())
p=list(map(int,input().split()))
b=list(map(lambda x:max(Counter(x).values()),list(zip(*a))))
s=0
for i in range(m):
s+=p[i]*b[i]
print(s) |
A large banner with word CODEFORCES was ordered for the 1000-th onsite round of Codeforcesω that takes place on the Miami beach. Unfortunately, the company that made the banner mixed up two orders and delivered somebody else's banner that contains someone else's word. The word on the banner consists only of upper-case ... | 1 | s = raw_input()
if any(s[:i] + s[j:] == 'CODEFORCES' for i in xrange(len(s)) for j in xrange(i + 1, len(s) + 1)):
print 'YES'
else:
print 'NO'
|
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.
Petya wonders eagerly what minimum lucky number has the sum of digits equal to n. Help him cope with... | 1 | a=input()
four=0
ans1=1000000000000000000
ans2=1000000000000000000
while four*4<=a:
remain=a-4*four
if(remain%7==0):
seven=remain/7
if(four+seven<ans1+ans2):
ans1,ans2=four,seven
elif(four+seven==ans1+ans2) and (four>ans1):
... |
The Quarkgo Empire Expeditionary Force is an evil organization that plans to invade the Earth. In keeping with the tradition of the invaders, they continued to send monsters at a pace of one every week, targeting the area around Tokyo in Japan. However, each time, five warriors calling themselves the Human Squadron Ear... | 3 |
N = int(input())
ans = 0
while N > 1:
N = (N+2) // 3
ans += 1
print (ans)
|
Constraints
* 1 ≤ |V| ≤ 100
* 0 ≤ |E| ≤ 9900
* -2 × 107 ≤ di ≤ 2 × 107
* There are no parallel edges
* There are no self-loops
Input
An edge-weighted graph G (V, E).
|V| |E|
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
|V| is the number of vertices and |E| is the number of edges in G. The graph vertices are named wi... | 3 | v, e = map(int, input().split())
inf = 2**32
dp = [[inf for _ in range(v)] for _ in range(v)]
'''
ワーシャルフロイドのアルゴリズム
動的計画法
'''
for i in range(v):
dp[i][i] = 0
for i in range(e):
s, t, d = map(int, input().split())
dp[s][t] = d
for k in range(v):
for i in range(v):
if dp[i][k] >= inf:
... |
A positive (strictly greater than zero) integer is called round if it is of the form d00...0. In other words, a positive integer is round if all its digits except the leftmost (most significant) are equal to zero. In particular, all numbers from 1 to 9 (inclusive) are round.
For example, the following numbers are roun... | 3 | for i in range(int(input())):
a = int(input())
l = [int(s) for s in str(a)]
nd = len(l) - l.count(0)
print(nd)
m = 1;
while a>0:
d = a % 10
if d != 0:
print(d*m, end = ' ')
m = m * 10
a = a//10
print() |
We have a large square grid with H rows and W columns. Iroha is now standing in the top-left cell. She will repeat going right or down to the adjacent cell, until she reaches the bottom-right cell.
However, she cannot enter the cells in the intersection of the bottom A rows and the leftmost B columns. (That is, there ... | 3 | """
fast way to compute a combination using inverse factorials
O(N) to construct tables -> O(1) to compute each combination
"""
def get_factorials(limit: int, MOD: int) -> list:
"""Compute a mod table of factorials (1-indexed)."""
factorials = [0] * (limit + 1)
factorials[0] = 1
x = 1
for i in ran... |
Colonel has n badges. He wants to give one badge to every of his n soldiers. Each badge has a coolness factor, which shows how much it's owner reached. Coolness factor can be increased by one for the cost of one coin.
For every pair of soldiers one of them should get a badge with strictly higher factor than the secon... | 1 | raw_input()
lista = map(int, raw_input().split())
lista.sort()
cont = 0
for i in xrange(1, len(lista)):
while lista[i] <= lista[i - 1]:
lista[i] += 1
cont += 1
print cont
|
Anton likes to play chess, and so does his friend Danik.
Once they have played n games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie.
Now Anton wonders, who won more games, he or Danik? Help him determine this.
Input
The first line of the input contains a... | 3 |
n = int(input())
scores = input()
count_a = scores.count("A")
count_d = len(scores) - count_a
if count_a > count_d:
print("Anton")
elif count_d > count_a:
print("Danik")
else:
print("Friendship")
|
You have array of n numbers a_{1}, a_{2}, …, a_{n}.
Rearrange these numbers to satisfy |a_{1} - a_{2}| ≤ |a_{2} - a_{3}| ≤ … ≤ |a_{n-1} - a_{n}|, where |x| denotes absolute value of x. It's always possible to find such rearrangement.
Note that all numbers in a are not necessarily different. In other words, some numb... | 3 | import sys
input=sys.stdin.readline
def printlist(l):
for i in l:
print(i,end=" ")
print()
t=int(input())
for r in range(t):
n=int(input())
templ=list(map(int,input().split()))
templ.sort()
i=0
j=n-1
ans=[]
while i<j:
ans.append(templ[j])
ans.append(templ[i])
... |
The circle line of the Roflanpolis subway has n stations.
There are two parallel routes in the subway. The first one visits stations in order 1 → 2 → … → n → 1 → 2 → … (so the next stop after station x is equal to (x+1) if x < n and 1 otherwise). The second route visits stations in order n → (n-1) → … → 1 → n → (n-1) ... | 3 | """
with open("input.txt") as f:
for line in f:
n, a, x, b, y = [int(x) for x in line.split()]
f.close()
f1 = open("output.txt", "w")
f1.write(slt(n, a, x, b, y))
f1.close()
"""
q, w, e, r, t = input().split()
def slt(n, a, x, b, y):
if b == a:
return "YES"
while b != y and a != x:
if b ... |
Allen has a LOT of money. He has n dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are 1, 5, 10, 20, 100. What is the minimum number of bills Allen could receive after withdrawing his entire balance?
Input
The first... | 3 | i=int(input())
c=0
while 1:
if i>=100:
i-=100
c+=1
elif i>=20:
i-=20
c+=1
elif i>=10:
i-=10
c+=1
elif i>=5:
i-=5
c+=1
elif i>=1:
i-=1
c+=1
else:
break
print(c) |
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 |
n, m, a = map(int, input().split())
print((n//a + (n % a != 0)) * (m // a + (m % a != 0)))
|
Shubham has an array a of size n, and wants to select exactly x elements from it, such that their sum is odd. These elements do not have to be consecutive. The elements of the array are not guaranteed to be distinct.
Tell him whether he can do so.
Input
The first line of the input contains a single integer t (1≤ t ≤... | 3 | # cook your dish here
T=int(input())
for i in range(T):
n,x=list(map(int,input().split()))
s=list(map(int,input().split()))
odd=0
even=0
for i in range(n):
if(s[i]%2!=0):
odd+=1
else:
even+=1
if(odd%2==0):
odd-=1
if(odd>0 and( x%2!=0 or even >0... |
Write a program which reads an integer $S$ [second] and converts it to $h:m:s$ where $h$, $m$, $s$ denote hours, minutes (less than 60) and seconds (less than 60) respectively.
Constraints
* $0 \leq S \leq 86400$
Input
An integer $S$ is given in a line.
Output
Print $h$, $m$ and $s$ separated by ':'. You do not n... | 3 | a=int(input())
h=a//3600
b=a%3600
m=b//60
s=b%60
print(f"{h}:{m}:{s}")
|
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Bi... | 3 | a=int(input())
if a>2 and a%2==0:
print("Yes")
else:
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 | year=int(input())
year=year+1
def distinct(year):
year=str(year)
count=0
for i in range(4):
for j in range(i+1,4):
if(year[i])==year[j]:
count=count+1
if(count==0):
print(year)
else:
year=int(year)
year=year+1
distinct(year)
distin... |
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 | from collections import Counter
import itertools
from functools import lru_cache
import sys
import math
###############################################################################
#Helper
def helper():
pass
###############################################################################
#Solver
def solve():
... |
There is an empty array. The following N operations will be performed to insert integers into the array. In the i-th operation (1≤i≤N), b_i copies of an integer a_i are inserted into the array. Find the K-th smallest integer in the array after the N operations. For example, the 4-th smallest integer in the array \\{1,2... | 3 | n,k=map(int,input().split())
l=[]
for i in range(n):
l.append(list(map(int,input().split())))
l.sort()
i=0
ans=0
while k>0:
k=k-l[i][1]
ans=l[i][0]
i=i+1
print(ans) |
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:
if i == n:
print("I love it", end="")
else:
print("I love that", end=" ")
elif i%2 != 0:
if i == n:
print("I hate it", end="")
else:
print("I hate that", end=" ")
|
You are given a set of n segments on the axis Ox, each segment has integer endpoints between 1 and m inclusive. Segments may intersect, overlap or even coincide with each other. Each segment is characterized by two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ m) — coordinates of the left and of the right endpoints.
Consider... | 3 | n,m=map(int,input().split())
s=list(range(1,m+1))
for i in range(n):
x,y=map(int,input().split())
for i in range(x,y+1):
if i in s:
s.remove(i)
print(len(s))
for h in range(len(s)):
print(s[h],end=' ')
|
"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=input().split(" ")
b=input().split(" ")
c=0
for i in range(0,len(b)):
if((int(b[(int(a[1]))-1])<=(int(b[i]))) and ((int(b[i]))>0)):
c+=1
print(c)
|
There are literally dozens of snooker competitions held each year, and team Jinotega tries to attend them all (for some reason they prefer name "snookah")! When a competition takes place somewhere far from their hometown, Ivan, Artsem and Konstantin take a flight to the contest and back.
Jinotega's best friends, team ... | 1 | def solve():
ln = input()
home = raw_input()
tripList = []
for i in range(ln):
tripList.append(raw_input())
used = []
cur = home
sign = True
while sign:
sign = False
for i in range(0,len(tripList)):
if tripList[i].startswith(cur) and i not in use... |
You are at a water bowling training. There are l people who play with their left hand, r people, who play with their right hand, and a ambidexters, who can play with left or right hand.
The coach decided to form a team of even number of players, exactly half of the players should play with their right hand, and exactl... | 3 | x=[int(i) for i in input().split()]
a=abs(x[0]-x[1])
if x[2]>a:
print(int(sum(x)/2)*2)
else:
print((min([x[0],x[1]])+x[2])*2)
|
There is a game called "I Wanna Be the Guy", consisting of n levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game.
Little X can pass only p levels of the game. And Little Y can pass only q levels of the game. You are given the indices of levels Little X can pass ... | 3 | a=input;print("I become the guy." if int(a())==len(set(a().split()[1:]).union(a().split()[1:])) else"Oh, my keyboard!") |
There are N children, numbered 1, 2, ..., N.
Snuke has decided to distribute x sweets among them. He needs to give out all the x sweets, but some of the children may get zero sweets.
For each i (1 \leq i \leq N), Child i will be happy if he/she gets exactly a_i sweets. Snuke is trying to maximize the number of happy ... | 3 | N, x=map(int, input().split())
a=list(map(int, input().split()))
a.sort()
i=0
while i<N and x>=a[i]:
x-=a[i]
i+=1
if i==N and x>0:
i-=1
print(i) |
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of n students doing yet another trick.
Let's assume that all these students are numbered from 1 to n. The teacher came to student a and put a hole in his badge. The student, ... | 3 | n=int(input())
p=[*map(int,input().split())]
r=[]
for i in range(n):
s=[1]*n
while s[i]:
s[i]=0
i=p[i]-1
r.append(i+1)
print(*r) |
Throughout Igor K.'s life he has had many situations worthy of attention. We remember the story with the virus, the story of his mathematical career and of course, his famous programming achievements. However, one does not always adopt new hobbies, one can quit something as well.
This time Igor K. got disappointed in ... | 1 | #!/usr/bin/python
import math
line = raw_input()
n,m,a,b = [int(x) for x in line.split()]
a -= 1
b -= 1
def find(n,m,a,b):
nrows = n/m
if n%m:
nrows += 1
arow = a/m
brow = b/m
if arow == brow:
return 1
if (b+1)%m == 0: #last in end
if a%m == 0: #first in start
... |
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 | nums = input().split('+')
print('+'.join(sorted(nums)))
|
Fox Ciel is playing a game with numbers now.
Ciel has n positive integers: x1, x2, ..., xn. She can do the following operation as many times as needed: select two different indexes i and j such that xi > xj hold, and then apply assignment xi = xi - xj. The goal is to make the sum of all numbers as small as possible.
... | 3 | from collections import deque
n=int(input())
li = deque(sorted(list(map(int, input().split()))))
g = li.popleft()
def gcd(a,b):
if a == b or a*b==0:return min(abs(a),abs(b))
else:
smaller = min(abs(a),abs(b));larger=max(abs(a),abs(b))
return gcd(larger-smaller,smaller)
while li and g!=1:
g=g... |
Let a be a matrix of size r × c containing positive integers, not necessarily distinct. Rows of the matrix are numbered from 1 to r, columns are numbered from 1 to c. We can construct an array b consisting of r + c integers as follows: for each i ∈ [1, r], let b_i be the greatest common divisor of integers in the i-th ... | 3 | #purvikaurraina
n,m=map(int,input().split())
if(n==m==1):
print(0)
elif(m==1):
for i in range(2,n+2):
print(i)
else:
for i in range(1,n+1):
for j in range(m):
print((n+1)*i+j*i,end=' ')
print()
|
Shaass has decided to hunt some birds. There are n horizontal electricity wires aligned parallel to each other. Wires are numbered 1 to n from top to bottom. On each wire there are some oskols sitting next to each other. Oskol is the name of a delicious kind of birds in Shaass's territory. Supposed there are ai oskols ... | 3 | n=int(input())
a=list(map(int,input().split()))
m=int(input())
for i in range(m):
x,y=map(int,input().split())
if n==1:
a[0]=0
else:
x=x-1
if x==0:
t1=y-1
t2=a[x]-y
a[x+1]+=t2
a[x]=0
elif x==n-1:
t1=y-1
t... |
You are given an array a of length n.
You are also given a set of distinct positions p_1, p_2, ..., p_m, where 1 ≤ p_i < n. The position p_i means that you can swap elements a[p_i] and a[p_i + 1]. You can apply this operation any number of times for each of the given positions.
Your task is to determine if it is poss... | 3 | te = int(input())
while te > 0:
te -= 1
x, y = list(map(int, input().split()))
numbers = list(map(int, input().split()))
positions = list(map(int, input().split()))
pos = [0]*x
for i in positions:
pos[i-1] = 1
# print(pos)
while True:
ok = False
for j in range... |
Given are integers A, B, and N.
Find the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N.
Here floor(t) denotes the greatest integer not greater than the real number t.
Constraints
* 1 ≤ A ≤ 10^{6}
* 1 ≤ B ≤ 10^{12}
* 1 ≤ N ≤ 10^{12}
* All values in input are i... | 3 | A,B,N = map(int,input().split())
x = min(N, B-1)
a = A*x//B - A*(x//B)
print(a)
|
Rudolf is on his way to the castle. Before getting into the castle, the security staff asked him a question:
Given two binary numbers a and b of length n. How many different ways of swapping two digits in a (only in a, not b) so that bitwise OR of these two numbers will be changed? In other words, let c be the bitwise... | 3 |
def cin(obj=list, type=int, sep=' '):
return obj(map(type, input().split(sep)))
n, = cin()
a = input()
b = input()
on = a.count('1')
z = 0
for x1, x2 in zip(a, b):
if x1 == '0' and x2 != '0': z += 1
ans = 0
for x1, x2 in zip(a, b):
if x1 == x2 == '0': ans += on
if x1 == '1' and x2 == '0': ans += z
p... |
The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups.
Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime.
If there is no police offi... | 3 | a=int(input())
l=list(map(int,input().split()))
k=0
sum=0
for a in l:
if(a>=1):
sum+=a
if(a==-1):
sum+=a
if(sum<0):
sum=0
k+=1
print(k) |
The king's birthday dinner was attended by k guests. The dinner was quite a success: every person has eaten several dishes (though the number of dishes was the same for every person) and every dish was served alongside with a new set of kitchen utensils.
All types of utensils in the kingdom are numbered from 1 to 100.... | 3 | n, k = map(int,input().split())
l1 = list(map(int,input().split()))
l_n = []
l2 = []
for i in l1:
if i not in l_n:
l_n.append(i)
l2.append(l1.count(i))
z = max(l2) // k + (max(l2) % k != 0)
print(z * len(l2) * k - n) |
Gerald is setting the New Year table. The table has the form of a circle; its radius equals R. Gerald invited many guests and is concerned whether the table has enough space for plates for all those guests. Consider all plates to be round and have the same radii that equal r. Each plate must be completely inside the ta... | 1 | from math import sin, pi
n, R, r = map(int, raw_input().split())
zero = -0.000000000057
if n == 1 and r <= R:
print 'YES'
elif n > 1 and (R - r) * sin(pi / n) - r >= zero:
print 'YES'
else:
print 'NO' |
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.
The language is that peculiar as it has exactly one variable, called x. Also, there are two operations:
* Operation ++ increases the value of variable x by 1.
* Operation -- decreases the value of variable x by 1.... | 3 | t=int(input())
h=0
for i in range(t):
a=input()
if a=="--X" or a =="X--":
h-=1
else:
h+=1
print(h) |
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find ... | 1 | import sys
num = int(raw_input())
lucky = [4, 7, 44, 47, 74, 77, 444, 474, 744, 774, 447, 477, 747, 777]
for x in lucky :
if (num % x == 0) :
print "YES"
sys.exit()
print "NO"
|
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 | import sys
def log(*a): print(*a, file=sys.stderr)
def line(): return sys.stdin.readline().split()
def iline(): return [int(i) for i in line()]
n, m, a = iline()
n = int((n + (a - 1)) / a)
m = int((m + (a - 1)) / a)
print(n * m)
|
You are given a sequence s consisting of n digits from 1 to 9.
You have to divide it into at least two segments (segment — is a consecutive sequence of elements) (in other words, you have to place separators between some digits of the sequence) in such a way that each element belongs to exactly one segment and if the ... | 3 | n = int(input())
def solve(s):
res = []
prev = 0
curr = "0"
for el in s:
curr += el
if int(curr) > prev:
res.append(int(curr))
prev = int(curr)
curr = ""
res[-1] = int(str(res[-1]) + curr)
return res
for _ in range(n):
input()
s = input()
res = solve(s)
if len(res) == 1:
print('NO')
else:
... |
Two neighboring kingdoms decided to build a wall between them with some gates to enable the citizens to go from one kingdom to another. Each time a citizen passes through a gate, he has to pay one silver coin.
The world can be represented by the first quadrant of a plane and the wall is built along the identity line (... | 3 | n=int(input())
s=input()
x=0
y=0
lst=[]
for i in s:
if i=="U":
x+=1
if x>y:
lst.append(1)
elif y>x:
lst.append(2)
elif i=="R":
y+=1
if x>y:
lst.append(1)
elif y>x:
lst.append(2)
j=0
for i in range(1,len(lst)):
if... |
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 | import math
m,n,a = input().split()
m = int(m)
n = int(n)
a = int(a)
if (m % a != 0 or n % a != 0) :
m1 = math.floor(m/a)
n1 = math.floor(n/a)
if n/a == int(n/a) :
c = (m1*n*a)/(a*a)
c += n1
elif m/a == int(m/a) :
c = (m*n1*a)/(a*a)
c += m1
else :
c = (m1*n1*a*a)/(a*a)
c += m1 + n1 + 1
else :
c = (... |
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr... | 3 | a = input()
b = input()
bool = 0
for i in range(len(a)):
# print(ord(a[i].lower()))
# break
if ord(a[i].lower()) < ord(b[i].lower()):
bool = 1
print(-1)
break
elif ord(a[i].lower()) > ord(b[i].lower()):
bool = 1
print(1)
break
if bool == 0:
print(0)
|
Alice and Bob like games. And now they are ready to start a new game. They have placed n chocolate bars in a line. Alice starts to eat chocolate bars one by one from left to right, and Bob — from right to left. For each chocololate bar the time, needed for the player to consume it, is known (Alice and Bob eat them with... | 3 | n=int(input())
bars=list(map(int,input().split()))
bars2=[]+bars
time=(sum(bars))
ATime=0
ANumber=0
for i in bars:
if ATime+i>(time/2):
break
else:
ATime+=i
ANumber+=1
bars2.pop(0)
BTime=time-ATime-bars2[0]
if BTime==ATime or BTime>ATime:
ANumber+=1
print(ANumber,n-ANumber... |
Gandalf the Grey is in trouble as Saurons eye Rearrived in the middle
world. Now he has to prepare for the war, But in order to defeat Sauron
he has to know the power of saurons eye on the day in which he wants to
attack.
According to the Elves(Good Friends of Gandalf),Gandalf came to know that
... | 1 | import sys
M = 10 ** 9 + 7
MAX_T = 10000
MAX_N = 10**12
_CUTOFF = 1536
cache = {}
results = []
def do_calc(n):
if n in cache:
return cache[n]
the_matrix = [3, 1, -1, 0]
result = power(the_matrix, n)[1]
if n not in cache:
cache[n] = result
return result
def power(matrix, n):
result = [1, 0, 0, ... |
Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to th... | 3 | l=list(map(int,input().split()))
f={}
for i in l:
if i in f:
f[i]+=1
else:
f[i]=1
print(4-len(f)) |
This problem is different from the easy version. In this version Ujan makes at most 2n swaps. In addition, k ≤ 1000, n ≤ 50 and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.
After struggling and failing many ... | 3 | for _ in range(int(input())):
n=int(input())
s1=input()
s2=input()
s1=[i for i in s1]
s2=[i for i in s2]
freq={}
for i in s1:
if i not in freq:
freq[i]=0
freq[i]+=1
for i in s2:
if i not in freq:
freq[i]=0
freq[i]+=1
f=True
... |
In some other world, today is the day before Christmas Eve.
Mr. Takaha is buying N items at a department store. The regular price of the i-th item (1 \leq i \leq N) is p_i yen (the currency of Japan).
He has a discount coupon, and can buy one item with the highest price for half the regular price. The remaining N-1 i... | 3 | N=int(input())
P=[int(input()) for i in range(N)]
P.sort()
print(sum(P)-P[-1]//2) |
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 | def main():
t = int(input())
for i in range(t):
a,b,c = map(int,input().split())
ans = 0
while b > 0 and c > 1:
b -= 1
c -= 2
ans += 3
while a > 0 and b > 1:
a -= 1
b -= 2
ans += 3
print(ans)
main(... |
Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be n problems, sorted by difficulty, i.e. problem 1 is the easiest and problem n is the hardest. Limak knows it will take him 5·i minutes to solve the i-th... | 3 | b=input().split(' ')
b[0]=int(b[0])
b[1]=int(b[1])
b[1]=240-b[1]
m=0
j=0
while j<b[0]:
m=m+1
if str(b[1]-(5*(j+1)+j*5))[0]=='-' or str(b[1]-(5*(j+1)+j*5))[0]=='0':
j=j+b[0]
j=j+1
b[1]=b[1]-5*m
if str(b[1])[0]=='-':
m=m-1
print(m) |
Victor tries to write his own text editor, with word correction included. However, the rules of word correction are really strange.
Victor thinks that if a word contains two consecutive vowels, then it's kinda weird and it needs to be replaced. So the word corrector works in such a way: as long as there are two consec... | 3 | n=int(input())
ch=input()
v="aeoiuy"
l = list(ch)
for x in range(0,n-1):
if(l[x] in v and l[x+1] in v ):
l[x+1]=''
a=''.join(l)
print(a) |
You are given strings S and T consisting of lowercase English letters.
You can perform the following operation on S any number of times:
Operation: Choose two distinct lowercase English letters c_1 and c_2, then replace every occurrence of c_1 with c_2, and every occurrence of c_2 with c_1.
Determine if S and T can ... | 3 | import collections
s=sorted(collections.Counter(input()).values())
t=sorted(collections.Counter(input()).values())
print("Yes" if s==t else "No") |
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 | print(sum(input().count('1')>1for x in [0]*int(input()))) |
You are a coach at your local university. There are n students under your supervision, the programming skill of the i-th student is a_i.
You have to create a team for a new programming competition. As you know, the more students some team has the more probable its victory is! So you have to create a team with the maxi... | 3 | import bisect
n = int(input())
a = sorted(map(int, input().split()))
high = 0
best = 1
low = 0
while high < n - 1:
high += 1
low = bisect.bisect_left(a, a[high] - 5, lo=low)
best = max(best, high - low + 1)
print(best) |
2N players are running a competitive table tennis training on N tables numbered from 1 to N.
The training consists of rounds. In each round, the players form N pairs, one pair per table. In each pair, competitors play a match against each other. As a result, one of them wins and the other one loses.
The winner of the... | 1 | def main():
n, a, b = map(int, raw_input().split())
if a < b:
a, b = b, a
if (a - b) % 2 == 0:
print (a - b) / 2
return
print min(b - 1, n - a) + (a - b - 1) / 2 + 1
main()
|
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 | s=input()
a=set(s)
ln = len(a)
if ln % 2 == 0 : #female
print("CHAT WITH HER!")
else : #male
print("IGNORE HIM!") |
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [... | 3 | import os
def a(x, y):
return x[0] + y[0], x[1] + y[1]
def f(nums):
n = len(nums)
dp_plus = [(0, 0)] * (n + 1)
dp_minus = [(0, 0)] * (n + 1)
for idx, x in enumerate(nums):
ii = idx + 1
if x > 0:
p, m = dp_plus, dp_minus
else:
p, m = dp_minus, dp_pl... |
During the break the schoolchildren, boys and girls, formed a queue of n people in the canteen. Initially the children stood in the order they entered the canteen. However, after a while the boys started feeling awkward for standing in front of the girls in the queue and they started letting the girls move forward each... | 3 | n = list(map(int, input().strip().split(' ')))
A = list(input())
L = A.copy()
for i in range(n[1]):
A = L.copy()
for i in range(0, n[0]-1):
if A[i]=='B' and A[i+1]=='G':
L[i], L[i+1] = L[i+1], L[i]
print(''.join(L)) |
Amr doesn't like Maths as he finds it really boring, so he usually sleeps in Maths lectures. But one day the teacher suspected that Amr is sleeping and asked him a question to make sure he wasn't.
First he gave Amr two positive integers n and k. Then he asked Amr, how many integer numbers x > 0 exist such that:
* D... | 1 | line = map(int, raw_input().split())
n = line[0]
k = line[1]
m = line[2]
t = [[0 for _ in xrange(k)] for _ in xrange(n)]
#base = 1
#for i in xrange(n):
# base *= 10
# top = base - 1
# r[i] = (int(top / k) + 1) % m
#r[0][i % k] += 1
#base = 1
#for i in xrange(1, n):
#base *= 10
#if (i == n - 1): ... |
Vanya is managed to enter his favourite site Codehorses. Vanya uses n distinct passwords for sites at all, however he can't remember which one exactly he specified during Codehorses registration.
Vanya will enter passwords in order of non-decreasing their lengths, and he will enter passwords of same length in arbitrar... | 3 | user_input=input()
first_line=user_input.split(' ')
n_passwords=int(first_line[0])
pass_limit=int(first_line[1])
passwords=[]
for i in range (n_passwords):
user_input=input()
passwords.extend([user_input])
passwords.sort(key=len)
correct_answer=input()
correct_length=len(correct_answer)
counter1=0
counter2... |
There are N towns located in a line, conveniently numbered 1 through N. Takahashi the merchant is going on a travel from town 1 to town N, buying and selling apples.
Takahashi will begin the travel at town 1, with no apple in his possession. The actions that can be performed during the travel are as follows:
* Move: ... | 3 |
def main():
buf = input()
buflist = buf.split()
N = int(buflist[0])
T = int(buflist[1])
buf = input()
buflist = buf.split()
A = list(map(int, buflist))
min_price = A[0]
max_price_diff = 0
max_diff_count = 0
for i in range(1, N):
if A[i] < min_price:
min_p... |
Snuke can change a string t of length N into a string t' of length N - 1 under the following rule:
* For each i (1 ≤ i ≤ N - 1), the i-th character of t' must be either the i-th or (i + 1)-th character of t.
There is a string s consisting of lowercase English letters. Snuke's objective is to apply the above operati... | 3 | import string
s = input()
ret = 100000000000000
for c in string.ascii_lowercase:
if c not in s:
continue;
x = s.split(c)
m = 0
for ss in x:
m = max(m, len(ss))
ret = min(ret, m)
print(ret) |
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy... | 3 | n = int(input())
lis = [0,0,0]
for i in range(n):
x,y,z=map(int,input().split())
lis[0] += x
lis[1] += y
lis[2] += z
if lis == [0,0,0]:
print('YES')
else:
print('NO')
|
Ujan decided to make a new wooden roof for the house. He has n rectangular planks numbered from 1 to n. The i-th plank has size a_i × 1 (that is, the width is 1 and the height is a_i).
Now, Ujan wants to make a square roof. He will first choose some of the planks and place them side by side in some order. Then he will... | 3 | for _ in range(int(input())):
N = int(input())
A = list(map(int,input().split()))
A.sort()
max = -1
for i in range(N):
m = min(A[i],N-i)
if m > max:
max = m
print(max)
|
Valera runs a 24/7 fast food cafe. He magically learned that next day n people will visit his cafe. For each person we know the arrival time: the i-th person comes exactly at hi hours mi minutes. The cafe spends less than a minute to serve each client, but if a client comes in and sees that there is no free cash, than ... | 1 | from __future__ import division
from collections import Counter as ctr
from math import ceil, log, factorial
def rl():
return [int(i) for i in raw_input().split()]
def rm(n=None):
if n is None:
n = input()
return [raw_input() for i in range(n)]
def rlm(n=None):
if n is None:
n = input... |
Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are n drinks in his fridge, the volume fraction of orange juice in the i-th drink equals pi percent.
One day Vasya decided to make himself an orange cocktail. He took equal proportions of ea... | 3 | n = int(input())
str = input()
strlist = str.split()
i = 0
count = 0
while i<n:
count += int(strlist[i])/100
i+=1
res = count/n
print(res*100) |
One day Jeff got hold of an integer sequence a1, a2, ..., an of length n. The boy immediately decided to analyze the sequence. For that, he needs to find all values of x, for which these conditions hold:
* x occurs in sequence a.
* Consider all positions of numbers x in the sequence a (such i, that ai = x). These... | 1 | n=input()
v={}
a=map(int,raw_input().split())
for i in range(n):
x=a[i]
if x in v:
v[x]=(i,-1 if v[x][1] and i-v[x][0]!=v[x][1] else i-v[x][0])
else:
v[x]=(i,0)
b=[(x,v[x][1]) for x in sorted(v.keys()) if v[x][1]>=0]
print len(b)
for x in b: print x[0],x[1] |
Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited n his friends there.
If t... | 3 | n=int(input())
a=list(map(int,input().split()))
for i in range (n):
b=a.index(i+1)
print(b+1,end=' ') |
Notes
Template in C
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 1000
* 1 ≤ timei ≤ 50000
* 1 ≤ length of namei ≤ 10
* 1 ≤ Sum of timei ≤ 1000000
Input
n q
name1 time1
name2 time2
...
namen timen
In the first line the number of processes n and the quantum q are given separated by a single space.
In the following n li... | 3 | import heapq
N,Q = map(int,input().split())
nati = []
for i in range(N):
na,ti = input().split()
nati.append([str(na),int(ti)])
now = 0
while nati:
na,ti = nati.pop(0)
if ti > Q:
ti-=Q
nati.append([na,ti])
now+=Q
else:
now+=ti
print(na,now)
|
Vasya has a non-negative integer n. He wants to round it to nearest integer, which ends up with 0. If n already ends up with 0, Vasya considers it already rounded.
For example, if n = 4722 answer is 4720. If n = 5 Vasya can round it to 0 or to 10. Both ways are correct.
For given n find out to which integer will Vasy... | 3 | import math,itertools,fractions,heapq,collections,bisect,sys,queue,copy
sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7
dd=[(-1,0),(0,1),(1,0),(0,-1)]
ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return [int(x) for x in sys.stdin.readline().split()]
# def LF(): return [float(x) for x in s... |
N programmers are going to participate in the preliminary stage of DDCC 20XX. Due to the size of the venue, however, at most 9 contestants can participate in the finals.
The preliminary stage consists of several rounds, which will take place as follows:
* All the N contestants will participate in the first round.
* W... | 3 | m = int(input())
dc = [list(map(int, input().split())) for i in range(m)]
a = 0
b = 0
for d,c in dc:
a += d*c
b += c
k = int((a-10)//9)+1
ans = b-1+k
print(ans) |
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true:
* Employee A is the immediate manag... | 3 | n = int(input())
a=[-1]*n
for i in range(n):
manager = int(input())-1
a[i]=manager
d=[0]*n
for cEmployee in range(n):
depth=0
employee = cEmployee
while a[employee]!=-2:
employee=a[employee]
depth+=1
d[cEmployee]=depth
print(max(d)+1)
|
You are given a set of 2n+1 integer points on a Cartesian plane. Points are numbered from 0 to 2n inclusive. Let P_i be the i-th point. The x-coordinate of the point P_i equals i. The y-coordinate of the point P_i equals zero (initially). Thus, initially P_i=(i,0).
The given points are vertices of a plot of a piecewis... | 1 | n,k=map(int,raw_input().split(" "))
if n>=k:
print "1"
else:
if(k%n>=0.5):
print ((k/n)+1)
else:
print k/n |
The great hero guards the country where Homer lives. The hero has attack power A and initial health value B. There are n monsters in front of the hero. The i-th monster has attack power a_i and initial health value b_i.
The hero or a monster is said to be living, if his or its health value is positive (greater than o... | 3 | from math import ceil
def hero(heroatt, herohp, n, monsteratt, monsterhp):
for i in range(n):
x = ceil(monsterhp[i]/heroatt)
y = ceil(herohp/monsteratt[i])
if y<x:
return "NO"
for i in range(n):
monsteratt[i] = [monsteratt[i],monsterhp[i]]
monsteratt.sort()
... |
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 | from math import ceil
x=input().split()
s=ceil(int(x[0])/int(x[2]))*ceil(int(x[1])/int(x[2]))
print(s) |
A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay i·k dollars for the i-th banana).
He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas?
Input
The first lin... | 3 | k,n,w=map(int,input().split())
s=k*(w)*(w+1)//2
if n>=s:
print(0)
else:
print(s-n) |
There are N cities numbered 1 through N, and M bidirectional roads numbered 1 through M. Road i connects City A_i and City B_i.
Snuke can perform the following operation zero or more times:
* Choose two distinct cities that are not directly connected by a road, and build a new road between the two cities.
After he... | 3 | from collections import Counter
N, M = map(int, input().split())
class UnionFind:
def __init__(self, n):
self.root = [i for i in range(n)]
def unite(self, x, y):
if not self.same(x, y):
self.root[self.find(y)] = self.find(x)
def find(self, x):
if x == self.root[x]:
... |
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 | import time
def calculateABC(anums):
anums.sort()
tot = anums[3]
ab = anums[0]
ac = anums[1]
bc = anums[2]
abc = []
abc.append(tot - ab)
abc.append(tot - ac)
abc.append(tot - bc)
return " ".join([str(x) for x in abc])
def solve():
anums = [int(x) for x in input().split()]... |
Tomorrow Peter has a Biology exam. He does not like this subject much, but d days ago he learnt that he would have to take this exam. Peter's strict parents made him prepare for the exam immediately, for this purpose he has to study not less than minTimei and not more than maxTimei hours per each i-th day. Moreover, th... | 3 | d,s=map(int,input().split())
q,w=[],[]
for i in range(d):
n,m=map(int,input().split())
q.append(n)
w.append(m)
if s>=sum(q) and s<=sum(w):
print("YES")
s-=sum(q)
for i in range(d):
if w[i]-q[i]>=s:q[i]+=s;break
else:s-=w[i]-q[i];q[i]=w[i]
print(*q)
else:print("NO") |
A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times b, b + a, b + 2a, b + 3a, ... and Morty screams at times d, d + c, d + 2c, d + 3c, ....
<image>
The Monster will catch them if at any point they scream at the same tim... | 3 | from sys import stdin, stdout
a, b = map(int, stdin.readline().split())
c, d = map(int, stdin.readline().split())
c1, d1 = max((c, d), (a, b), key = lambda x: x[1])
a1, b1 = min((c, d), (a, b), key = lambda x: x[1])
for y in range(10 ** 6):
if (d1 + c1 * y - b1) / a1 == int((d1 + c1 * y - b1) / a1) >= 0 and (d1 ... |
You are given a string S of length N consisting of lowercase English letters, and an integer K. Print the string obtained by replacing every character in S that differs from the K-th character of S, with `*`.
Constraints
* 1 \leq K \leq N\leq 10
* S is a string of length N consisting of lowercase English letters.
* N... | 3 | N = int(input())
S = input()
K = int(input())
t = S[K-1]
newS = [s if s == t else '*' for s in S]
print(''.join(newS)) |
To become a millionaire, M-kun has decided to make money by trading in the next N days. Currently, he has 1000 yen and no stocks - only one kind of stock is issued in the country where he lives.
He is famous across the country for his ability to foresee the future. He already knows that the price of one stock in the n... | 3 | N = int(input())
A = list(map(int, input().split()))
B = 1000
for i in range(N-1):
if A[i+1]>A[i]:
B = B//A[i]*A[i+1]+B%A[i]
print(B)
|
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr... | 3 | str1 = input().lower()
str2 = input().lower()
if str1 < str2:
print(-1)
if str1 > str2:
print(1)
if str1 == str2:
print(0) |
Just in case somebody missed it: this winter is totally cold in Nvodsk! It is so cold that one gets funny thoughts. For example, let's say there are strings with the length exactly n, based on the alphabet of size m. Any its substring with length equal to k is a palindrome. How many such strings exist? Your task is to ... | 1 | n, m, k = map(int, raw_input().split())
def mult(a, b): return a * b
P = 1000000007
if k > n or k == 1:
print reduce(mult, [m]*n) % P
elif k == n:
print reduce(mult, [m]*(n/2 + n%2)) % P
else:
print (m, m*m)[k % 2]
|
We have a sequence of length N, a = (a_1, a_2, ..., a_N). Each a_i is a positive integer.
Snuke's objective is to permute the element in a so that the following condition is satisfied:
* For each 1 ≤ i ≤ N - 1, the product of a_i and a_{i + 1} is a multiple of 4.
Determine whether Snuke can achieve his objective.
... | 1 | N=input()
#print N
a=map(int, raw_input().split())
#print a
cnt4=0
cnt2=0
kisuu=0
for i in range(len(a)):
#print a[i]
if a[i]%4==0:
cnt4+=1
elif a[i]%4!=0 and a[i]%2==0:
cnt2+=1
elif a[i]%2==1:
kisuu+=1
#print cnt4
#print cnt2
#print kisuu
if cnt4>0 and cnt2==0 and kisuu==0:
print 'Yes'
elif cnt4==kisuu:... |
You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft k torches. One torch can be crafted using one stick and one coal.
Hopefully, you've met a very handsome wandering trader who has two trade offers:
* exchange 1 stick for x sticks (you lose 1 stick and gain x sticks... | 3 | testcase=int(input())
for test in range(testcase):
x,y,k=map(int,input().split())
res=(k*(y+1)-x) // (x-1)
if (k*(y+1)-x)%(x-1)!=0:
res+=1
res=res+k+1
print(res) |
There is a string S consisting of digits `1`, `2`, ..., `9`. Lunlun, the Dachshund, will take out three consecutive digits from S, treat them as a single integer X and bring it to her master. (She cannot rearrange the digits.)
The master's favorite number is 753. The closer to this number, the better. What is the mini... | 3 | s=input()
xlist=[abs(int(s[i:i+3])-753) for i in range(len(s)-2)]
print(min(xlist)) |
Boboniu gives you
* r red balls,
* g green balls,
* b blue balls,
* w white balls.
He allows you to do the following operation as many times as you want:
* Pick a red ball, a green ball, and a blue ball and then change their color to white.
You should answer if it's possible to arrange all the b... | 3 | T = int(input())
for case in range(T):
r, g, b, w = [int(x) for x in input().split()]
even = []
even_count = 0
if(r%2 == 0):
even.append(r)
even_count +=1
if(g%2 == 0):
even.append(g)
even_count +=1
if(b%2 == 0):
even.append(b)
even_count +=1
... |
Anton likes to play chess, and so does his friend Danik.
Once they have played n games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie.
Now Anton wonders, who won more games, he or Danik? Help him determine this.
Input
The first line of the input contains a... | 3 | n = int(input())
score = input()
from collections import Counter
b = Counter(score)
if b['A'] > b['D']:
print('Anton')
elif b['D'] > b['A']:
print('Danik')
else:
print("Friendship")
|
[The Duck song](https://www.youtube.com/watch?v=MtN1YnoL46Q)
For simplicity, we'll assume that there are only three types of grapes: green grapes, purple grapes and black grapes.
Andrew, Dmitry and Michal are all grapes' lovers, however their preferences of grapes are different. To make all of them happy, the followi... | 1 | def grapes(demand, ava):
total_y = ava[0]+ava[1]-demand[0]
total_z = ava[0]+ava[1]+ava[2]-demand[0]-demand[1]
if demand[0]>ava[0]:
return False
elif total_y<demand[1]:
return False
elif total_z<demand[2]:
return False
return True
if __name__ ... |
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as... | 3 | n = int(input())
a = list(map(int, input().split()))
b = []
for i in range(n - 1):
b.append(abs(a[i] - a[i + 1]))
c = []
s = 1
summ = 0
for i in range(n - 1):
summ += s * b[i]
s = -s
c.append(summ)
c.sort()
if c[0] < 0:
print(c[n - 2] - c[0])
else:
print(c[n - 2]) |
You are given a integer n (n > 0). Find any integer s which satisfies these conditions, or report that there are no such numbers:
In the decimal representation of s:
* s > 0,
* s consists of n digits,
* no digit in s equals 0,
* s is not divisible by any of it's digits.
Input
The input consists of mult... | 1 |
# Problem : A. Bad Ugly Numbers
# Contest : Codeforces Global Round 7
# URL : https://codeforces.com/contest/1326/problem/A
# Memory Limit : 256 MB
# Time Limit : 1000 ms
# Powered by CP Editor (https://github.com/cpeditor/cpeditor)
"""
// Author : snape_here - Susanta Mukherjee
"""
from __future__ import di... |
After a team finished their training session on Euro football championship, Valeric was commissioned to gather the balls and sort them into baskets. Overall the stadium has n balls and m baskets. The baskets are positioned in a row from left to right and they are numbered with numbers from 1 to m, correspondingly. The ... | 1 | def f(n, m):
s = []
if m%2 == 1:
i = 1
t = (m + 1) / 2
s.append(str(t))
while i < t:
s.append(str(t-i))
s.append(str(t+i))
i += 1
else:
t = m / 2
z = m /2 +1
i = 0
while t-i > 0:
s.append(str(t-i))
s.append(str(z+i))
i += 1
s = list(s)
for i in xrange(1, n+1):
print s[(i-1)%len(... |
Let a and b be two arrays of lengths n and m, respectively, with no elements in common. We can define a new array merge(a,b) of length n+m recursively as follows:
* If one of the arrays is empty, the result is the other array. That is, merge(∅,b)=b and merge(a,∅)=a. In particular, merge(∅,∅)=∅.
* If both arrays a... | 3 | from collections import defaultdict, deque, Counter
from sys import stdin, stdout
from heapq import heappush, heappop
import math
import io
import os
import math
import bisect
#?############################################################
def isPrime(x):
for i in range(2, x):
if i*i > x:
brea... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.