problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
In the school computer room there are n servers which are responsible for processing several computing tasks. You know the number of scheduled tasks for each server: there are mi tasks assigned to the i-th server.
In order to balance the load for each server, you want to reassign some tasks to make the difference betw... | 3 | ans=0
n=int(input())
s=list(map(int,input().split()))
k1=sum(s)//n
k2=(sum(s)+n-1)//n
a1=a2=0
for i in s:
if i<k1:a1+=abs(i-k1)
elif i>k2:a2+=abs(i-k2)
print(max(a1,a2)) |
Luba has a ticket consisting of 6 digits. In one move she can choose digit in any position and replace it with arbitrary digit. She wants to know the minimum number of digits she needs to replace in order to make the ticket lucky.
The ticket is considered lucky if the sum of first three digits equals to the sum of las... | 3 | i = list(map(lambda c: int(c), input()))
d = sum([i[3]-i[0], i[4]-i[1], i[5]-i[2]])
if(d < 0):
i.reverse()
d *= -1
for z in range(3):
i[z] = 9 - i[z]
i = sorted(i)
i.reverse()
ir = 0
for (ind, z) in enumerate(i):
if ir >= d:
print(ind)
break
ir += z
# Made By Mostafa_Khaled |
An adult game master and N children are playing a game on an ice rink. The game consists of K rounds. In the i-th round, the game master announces:
* Form groups consisting of A_i children each!
Then the children who are still in the game form as many groups of A_i children as possible. One child may belong to at m... | 3 | k,*a = map(int,open(0).read().split())
a = a[::-1]
nmax = 2
nmin = 2
for i in range(k):
if nmax//a[i]-(nmin-1)//a[i]<=0:
print(-1)
exit()
nmin = ((nmin-1)//a[i]+1)*a[i]
nmax = (nmax//a[i])*a[i]+a[i]-1
print(nmin,nmax) |
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 | def Solve(a, b, n):
if (n < a) or (n < b):
return 0
count = 0
while (a <= n) and (b <= n):
if a < b:
a += b
else:
b += a
count += 1
return count
T = int(input())
for _ in range(T):
a, b, n = map(int, input().split())
print(Solve(a, b, n)) |
Vasya lives in a round building, whose entrances are numbered sequentially by integers from 1 to n. Entrance n and entrance 1 are adjacent.
Today Vasya got bored and decided to take a walk in the yard. Vasya lives in entrance a and he decided that during his walk he will move around the house b entrances in the direct... | 1 | n, a, b = map(int, raw_input().split())
k = a
if b > 0:
k += b % n
elif b < 0:
k += n + b % -n
k = k % n
if k == 0:
k = n
print k |
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 | for a0 in range(int(input())):
n=int(input())
d=0
x=n%10
while(n!=0):
n=n//10
d+=1
# print(n,d)
print(10*(x-1)+d*(d+1)//2) |
Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first n. He writes down the followin... | 3 | a,b=map(int,input().split())
if b<=((a+1)//2):
print(2*(b)-1)
elif b>a//2:
b=b-((a+1)//2)
print(2*b)
|
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them.
Input
The first line contains integ... | 3 | count = input()
stones = input()
removedStones = 0
for index, stone in enumerate(stones):
if (index + 1 < len(stones)):
nextStone = stones[index + 1]
if nextStone == stone:
removedStones += 1
print(removedStones)
|
New Year is coming and you are excited to know how many minutes remain before the New Year. You know that currently the clock shows h hours and m minutes, where 0 β€ hh < 24 and 0 β€ mm < 60. We use 24-hour time format!
Your task is to find the number of minutes before the New Year. You know that New Year comes when the... | 3 | #Codeforce 1283A
case=int(input())
for i in range(case):
h,m=(int(v) for v in input().split())
print(1440 - h*60 - m) |
One day Vasya decided to have a look at the results of Berland 1910 Football Championshipβs finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are n lines in that description each of which described one goal. Eve... | 3 | n = int(input())
f = input()
c = 1
for i in range(n-1):
a = input()
if a == f:
c+=1
else:
b = a
if c>n-c:
print(f)
else:
print(b)
|
Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first n. He writes down the followin... | 3 | import math
def evenodd(n,m):
if(m<=math.ceil(n/2)):
a=2*m-1
else:
f=m-math.ceil(n/2)
a=2*f
return(a)
n,m =map(int,input().split())
z=evenodd(n,m)
print(z)
|
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second.
One day in 230 AD Shapur was trying to find out if any one can possibly do... | 3 | def sumB(x,y):
z = []
for i in range(len(x)):
if x[i] == y[i]:
z.append(0)
else:
z.append(1)
return z
N = input()
M = input()
R = sumB(N,M)
R = list(map(str,R))
R = ''.join(R)
print(R)
# 1535838619880
|
Julia is going to cook a chicken in the kitchen of her dormitory. To save energy, the stove in the kitchen automatically turns off after k minutes after turning on.
During cooking, Julia goes to the kitchen every d minutes and turns on the stove if it is turned off. While the cooker is turned off, it stays warm. The s... | 3 | k,d,t = map(int, input().split())
from math import gcd
if gcd(k,d) == d or k >= t:
print(t)
exit(0)
from fractions import Fraction
r1a, r1b = Fraction(k, 1), Fraction(d - (k % d), 2)
r1 = r1a + r1b
rt = Fraction(t, 1)
m = rt // r1
r = rt % r1
b = m * k + m * (d - (k % d))
if r <= r1a:
print(b + float(r))
... |
wHAT DO WE NEED cAPS LOCK FOR?
Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage.
Let's consider that a word has been typed with the Caps lock key accidentall... | 3 | '''x = list(map(int, input().split()))
successful = 0
gradebook = []
for student in range(x[0])'''
x = input()
case_2 = list(x.upper())
case_2[0] = case_2[0].lower()
case_2 = "".join(case_2)
if x == case_2 or x == x.upper():
case = list(x)
for i in range(len(case)):
if case[i] == case[i].lower():
case[i] = c... |
Little girl Tanya climbs the stairs inside a multi-storey building. Every time Tanya climbs a stairway, she starts counting steps from 1 to the number of steps in this stairway. She speaks every number aloud. For example, if she climbs two stairways, the first of which contains 3 steps, and the second contains 4 steps,... | 3 | n=int(input())
m=list(map(int,input().split()))
print(m.count(1))
for i in range(1,len(m)):
if(m[i]==1):
print(m[i-1],end=" ")
print(m[n-1])
|
You are given an H Γ W grid.
The squares in the grid are described by H strings, S_1,...,S_H.
The j-th character in the string S_i corresponds to the square at the i-th row from the top and j-th column from the left (1 \leq i \leq H,1 \leq j \leq W).
`.` stands for an empty square, and `#` stands for a square containin... | 3 | h,w = map(int, input().split())
s = [list(input()) for _ in range(h)]
p = [-1,0,1]
for i in range(h):
for j in range(w):
count = 0
for ph in p:
for pw in p:
if (ph==0 and pw==0) or not(0<=i-ph<=h-1) or not(0<=j-pw<=w-1):
continue
if s[max(i-ph,0)][max(j-pw,0)]=='#':
c... |
Each day in Berland consists of n hours. Polycarp likes time management. That's why he has a fixed schedule for each day β it is a sequence a_1, a_2, ..., a_n (each a_i is either 0 or 1), where a_i=0 if Polycarp works during the i-th hour of the day and a_i=1 if Polycarp rests during the i-th hour of the day.
Days go ... | 3 | from itertools import cycle
# n = int(input())
# left = input()
# right = input()
# left_boots = {}
# right_boots = {}
# for i, l in enumerate(left):
# try:
# left_boots[l].append(i)
# except KeyError:
# left_boots[l] = [i]
# for i, r in enumerate(right):
# try:
# right_boots[r].appe... |
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 | # ---------------------------------------------------------------------------------------------------- #
#! /usr/local/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
# Copyright Β© 2017 pmxt <pmxt@Manjunathas-Air>
# ------------------------------------------------------------------------------------------------... |
For a given sequence A = {a0, a1, ... , an-1}, find the length of the longest increasing subsequnece (LIS) in A.
An increasing subsequence of A is defined by a subsequence {ai0, ai1, ... , aik} where 0 β€ i0 < i1 < ... < ik < n and ai0 < ai1 < ... < aik.
Constraints
* 1 β€ n β€ 100000
* 0 β€ ai β€ 109
Input
n
a0
a1
:
... | 3 | import bisect
n = int(input())
A =[]
for i in range(n):
A.append(int(input()))
L = [A[0]]
for i in A:
if L[-1] < i:
L.append(i)
else:
L[bisect.bisect_left(L, i)] = i
print(len(L))
|
Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity.
There are n columns of toy cubes in the box arranged in a line. The i-th column contains ai cubes. At first, the gravity in the box is pulling... | 3 | n = int(input())
listA = list(map(int, input().split()))
listA.sort()
for i in listA:
print(i, end=' ')
|
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 | import string
s=input()
lower=len(list(filter(lambda x: x in "abcdefghijklmnopqrstuvwxyz", s)))
upper=len(list(filter(lambda x: x in "ABCDEFGHIJKLMNOPQRSTUVWXYZ", s)))
if upper>lower:
s=s.upper()
else:
s=s.lower()
print(s)
|
According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw n people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check ... | 3 | a = ['ABSINTH', 'BEER', 'BRANDY', 'CHAMPAGNE', 'GIN', 'RUM', 'SAKE', 'TEQUILA', 'VODKA', 'WHISKEY', 'WINE','0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17']
k = 0
n = int(input())
for i in range(n):
s = str(input())
if s in a:
k+=1
print(k) |
In this problem you are to calculate the sum of all integers from 1 to n, but you should take all powers of two with minus in the sum.
For example, for n = 4 the sum is equal to - 1 - 2 + 3 - 4 = - 4, because 1, 2 and 4 are 20, 21 and 22 respectively.
Calculate the answer for t values of n.
Input
The first line of... | 3 | inputNum = int(input())
for inputs in range(0,inputNum):
n = int(input())
sum = int("0",36)
power = int("0",36)
while 2**power <= n:
sum -= 2 * (2**power)
power+=1
sum += ((1 + n) * n) >> 1
print(sum) |
Recently Anton found a box with digits in his room. There are k2 digits 2, k3 digits 3, k5 digits 5 and k6 digits 6.
Anton's favorite integers are 32 and 256. He decided to compose this integers from digits he has. He wants to make the sum of these integers as large as possible. Help him solve this task!
Each digit c... | 3 | k=[int(x) for x in input().split()]
num256=min(k[0],k[2],k[3])
k[0]=k[0]-num256
num32=min(k[0],k[1])
print(256*num256+32*num32)
|
Vasya claims that he had a paper square. He cut it into two rectangular parts using one vertical or horizontal cut. Then Vasya informed you the dimensions of these two rectangular parts. You need to check whether Vasya originally had a square. In other words, check if it is possible to make a square using two given rec... | 3 | for _ in range(int(input())):
a1, b1 = list(map(int, input().split()))
a2, b2 = list(map(int, input().split()))
if a1 == a2 == b1 + b2 or a1 == b2 == a2 + b1 or a2 == b1 == a1 + b2 or b1 == b2 == a2 + a1:
print('Yes')
else:
print('No') |
Vasya owns a cornfield which can be defined with two integers n and d. The cornfield can be represented as rectangle with vertices having Cartesian coordinates (0, d), (d, 0), (n, n - d) and (n - d, n).
<image> An example of a cornfield with n = 7 and d = 2.
Vasya also knows that there are m grasshoppers near the fie... | 3 | cor=input()
cor=cor.split(' ')
cor[0]=int(cor[0])
cor[1]=int(cor[1])
cuz=int(input())
a=[[0 for i in range(2)] for j in range(cuz)]
for i in range(cuz):
l=input()
l=l.split(' ')
l[0]=int(l[0])
l[1]=int(l[1])
a[i][0]=l[0]
a[i][1]=l[1]
for i in range(cuz):
if a[i][0]+a[i][1]-cor[1]>=0 and a[i]... |
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory.
George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living... | 3 | n = int(input())
freeRooms = 0
for i in range(n):
p, q = map(int, input().split())
if(q-p >= 2):
freeRooms += 1
print(freeRooms) |
Kuro is living in a country called Uberland, consisting of n towns, numbered from 1 to n, and n - 1 bidirectional roads connecting these towns. It is possible to reach each town from any other. Each road connects two towns a and b. Kuro loves walking and he is planning to take a walking marathon, in which he will choos... | 3 | from collections import defaultdict
n, flower, bee = list(map(int, input().split()))
roads = {}
for _ in range(n-1):
x, y = list(map(int, input().split()))
if x not in roads:
roads[x] = [y]
else:
roads[x].append(y)
if y not in roads:
roads[y] = [x]
else:
roads[y].appe... |
You are given two strings s and t. The string s consists of lowercase Latin letters and at most one wildcard character '*', the string t consists only of lowercase Latin letters. The length of the string s equals n, the length of the string t equals m.
The wildcard character '*' in the string s (if any) can be replace... | 3 | n,m=map(int,input().split())
s=input()
t=input()
if '*' in s:
if m<n-1:
print('NO')
else:
if s[0]=='*':
if s[1:n]==t[m-n+1:m]:
print('YES')
else:
print('NO')
elif s[n-1]=='*':
if s[0:n-1]==t[0:n-1]:
print... |
Recently, a chaotic virus Hexadecimal advanced a new theorem which will shake the Universe. She thinks that each Fibonacci number can be represented as sum of three not necessary different Fibonacci numbers.
Let's remember how Fibonacci numbers can be calculated. F0 = 0, F1 = 1, and all the next numbers are Fi = Fi - ... | 3 | print(0, 0, input())
|
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'... | 1 | import math
line = raw_input()
val = line.split()
n = int(val[0])
m = int(val[1])
a = int(val[2])
print int(math.ceil(n / (a*1.0)) * math.ceil(m / (a*1.0))) |
There is Kannon-do in the mountain behind Ichiro's house. There are 30 steps from the foot to this Kannon-do, and Ichiro goes to Kannon-do almost every day. Ichiro can go up the stairs up to 3 steps with one foot. While playing, I noticed that there are so many types of stair climbing (the number of steps to skip).
So... | 1 | L=[0]*30
L[0],L[1],L[2]=1,2,4
for i in range(3,30):
L[i]=L[i-1]+L[i-2]+L[i-3]
while True:
n=input()
if n==0:break
print L[n-1]/10/365+1 |
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 Γ n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.
So, user tncks0121 has ... | 3 | """""""""""""""""""""""""""""""""""""""""""""
| author: mr.math - Hakimov Rahimjon |
| e-mail: mr.math0777@gmail.com |
"""""""""""""""""""""""""""""""""""""""""""""
#inp = open("lepus.in", "r"); input = inp.readline; out = open("lepus.out", "w"); print = out.write
TN = 1
# =========================... |
There are three friend living on the straight line Ox in Lineland. The first friend lives at the point x1, the second friend lives at the point x2, and the third friend lives at the point x3. They plan to celebrate the New Year together, so they need to meet at one point. What is the minimum total distance they have to... | 3 | a,b,c=map(int,input().split())
aa=abs(b-a)+abs(a-c)
bb=abs(a-b)+abs(b-c)
cc=abs(a-c)+abs(b-c)
print(min(aa,bb,cc))
|
Kolya loves putting gnomes at the circle table and giving them coins, and Tanya loves studying triplets of gnomes, sitting in the vertexes of an equilateral triangle.
More formally, there are 3n gnomes sitting in a circle. Each gnome can have from 1 to 3 coins. Let's number the places in the order they occur in the ci... | 3 | import math
import sys
n=int(input())
mod=10**9+7
p3=1;p7=1
for i in range(3*n):
p3=(p3*3)%mod
for i in range(n):
p7=(p7*7)%mod
print((p3+mod-p7)%mod) |
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())
count = 0
for i in range(n):
mas = input().split()
a = bool(int(mas[0]))
b = bool(int(mas[1]))
c = bool(int(mas[2]))
if (b and (a or c)) or (a and c):
count += 1
print(count) |
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm:
* if the last digit of the number is non-zero, she decreases the number by one;
* if the last digit of the number is ze... | 3 | n,k=map(str,input().split())
count=0
t=int(k)
while(t):
if n[len(n)-1]=="0":
n=str(int(n)//10)
else:
n=str(int(n)-1)
t=t-1
print(int(n)) |
Tomorrow is a difficult day for Polycarp: he has to attend a lectures and b practical classes at the university! Since Polycarp is a diligent student, he is going to attend all of them.
While preparing for the university, Polycarp wonders whether he can take enough writing implements to write all of the lectures and d... | 3 | import math
t = int(input())
for i in range(t):
a, b, c, d, k = map(int, input().split())
x = math.ceil(a / c)
y = math.ceil(b / d)
ans = x + y
if x + y <= k:
print(str(x) + " " + str(y))
else:
print(-1) |
Nick had received an awesome array of integers a=[a_1, a_2, ..., a_n] as a gift for his 5 birthday from his mother. He was already going to explore its various properties but after unpacking he was disappointed a lot because the product a_1 β
a_2 β
... a_n of its elements seemed to him not large enough.
He was ready t... | 3 | n=int(input())
l=list(map(int,input().split()))
ans=[0]*n
neg=0
for i in l:
if i<0:
neg+=1
if neg%2==0:
if n%2==0:
for i in range(n):
if l[i]<0:
ans[i]=l[i]
else:
ans[i]=-1-l[i]
for i in ans:
print (i,end=" ")
else:
for i in range(n):
if l[i]<0:
ans[i]=l[i]
else:
ans[i]=-1-l[i]... |
A well-known art union called "Kalevich is Alive!" manufactures objects d'art (pictures). The union consists of n painters who decided to organize their work as follows.
Each painter uses only the color that was assigned to him. The colors are distinct for all painters. Let's assume that the first painter uses color 1... | 1 | pictures, painters = map(int, raw_input().split())
inp = []
for i in range(pictures):
inp.append(map(int, raw_input().split()))
inp = zip(*inp)
p = inp[0]
last = [0] * pictures
last[0] = p[0]
for i in range(1, pictures):
last[i] = last[i-1] + p[i]
for j in range(1, painters):
p = inp[j]
this = [0] * pictures
th... |
You are given two non-negative integers L and R. We will choose two integers i and j such that L \leq i < j \leq R. Find the minimum possible value of (i \times j) \mbox{ mod } 2019.
Constraints
* All values in input are integers.
* 0 \leq L < R \leq 2 \times 10^9
Input
Input is given from Standard Input in the fol... | 3 | l,r=map(int,input().split())
ans=2018
for i in range(l,r+1):
for j in range(i+1,r+1):
ans=min(ans,(i*j)%2019)
if ans==0:
print(0)
exit()
print(ans) |
The ancient Berlanders believed that the longer the name, the more important its bearer is. Thus, Berland kings were famous for their long names. But long names are somewhat inconvenient, so the Berlanders started to abbreviate the names of their kings. They called every king by the first letters of its name. Thus, the... | 3 | from sys import stdin
n=int(stdin.readline().strip())
s=[stdin.readline().strip() for i in range(n)]
dp=[[0 for i in range(26)] for j in range(26)]
now=1
last=0
for i in range(n):
a,b=ord(s[i][0])-97,ord(s[i][-1])-97
for j in range(26):
if dp[j][a]>0:
dp[j][b]=max(dp[j][b],dp[j][a]+len(s[i])... |
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 | a=int(input())
for i in range(a):
b=int(input())
if b==1 or b==2:
print(0)
continue
if(b%2>0):
print(int(b/2))
elif(b%2==0):
print(int((b/2)-1)) |
The School β0 of the capital of Berland has n children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value ti:
* ti = 1, if the i-th child is good at programming,
*... | 3 | n=int(input())
x=[int(i) for i in input().split()]
cnt1=0
cnt2=0
cnt3=0
l1=[]
l2=[]
l3=[]
for i in range(n):
if x[i]==1:
cnt1+=1
l1.append(i+1)
elif x[i]==2:
cnt2+=1
l2.append(i+1)
else:
cnt3+=1
l3.append(i+1)
z=min(cnt3,cnt2,cnt1)
print(z)
for i in range(z):
... |
<image>
As some of you know, cubism is a trend in art, where the problem of constructing volumetrical shape on a plane with a combination of three-dimensional geometric shapes comes to the fore.
A famous sculptor Cicasso, whose self-portrait you can contemplate, hates cubism. He is more impressed by the idea to tran... | 3 | n=int(input(''))
arr=input('').split(' ')
for i in range(n):
arr[i]=int(arr[i])
arr.sort(reverse=True)
tmp=0
for i in range(1,n):
tmp+=arr[i]
print(max(0,arr[0]+1-tmp)) |
There is a tree with N vertices, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N - 1), the i-th edge connects Vertex x_i and y_i.
Taro has decided to paint each vertex in white or black. Here, it is not allowed to paint two adjacent vertices both in black.
Find the number of ways in which the vertices can be pa... | 3 | from collections import deque
mod = 10**9+7
n = int(input())
g = [[] for _ in range(n)]
for _ in range(n-1):
x, y = map(int, input().split())
g[x-1].append(y-1)
g[y-1].append(x-1)
visited = [False]*n
q = deque([0])
lst = [] # 0γζ Ήγ¨γγ¦γζ·±γι ηΉγγθ¦γγγ
while q:
v = q.popleft()
visited[v] = True
lst.a... |
Today, Mezo is playing a game. Zoma, a character in that game, is initially at position x = 0. Mezo starts sending n commands to Zoma. There are two possible commands:
* 'L' (Left) sets the position x: =x - 1;
* 'R' (Right) sets the position x: =x + 1.
Unfortunately, Mezo's controller malfunctions sometimes. ... | 3 | #reading
x=int(input())
string1=input()
#printing
print(x+1)
|
Can you imagine our life if we removed all zeros from it? For sure we will have many problems.
In this problem we will have a simple example if we removed all zeros from our life, it's the addition operation. Let's assume you are given this equation a + b = c, where a and b are positive integers, and c is the sum of a... | 3 | n = (input())
m = (input())
k = int(n) + int(m)
p = str(k)
n1=n.replace('0', '')
p1 = p.replace('0', '')
m1 = m.replace('0', '')
if(int(n1) + int(m1) == int(p1)):
print("YES")
else:
print("NO") |
We have held a popularity poll for N items on sale. Item i received A_i votes.
From these N items, we will select M as popular items. However, we cannot select an item with less than \dfrac{1}{4M} of the total number of votes.
If M popular items can be selected, print `Yes`; otherwise, print `No`.
Constraints
* 1 \... | 3 | N,M,*A = map(int,open(0).read().split())
A.sort()
A.reverse()
A2=A[:M]
j = sum(A) / (4*M)
print("Yes" if all(a>=j for a in A2) else "No") |
Little C loves number Β«3Β» very much. He loves all things about it.
Now he has a positive integer n. He wants to split n into 3 positive integers a,b,c, such that a+b+c=n and none of the 3 integers is a multiple of 3. Help him to find a solution.
Input
A single line containing one integer n (3 β€ n β€ 10^9) β the integ... | 3 | #yeh dil maange more
n = int(input())
if (n-2)%3!=0:print(1,1,n-2)
else:print(1,2,n-3) |
A lot of people in Berland hates rain, but you do not. Rain pacifies, puts your thoughts in order. By these years you have developed a good tradition β when it rains, you go on the street and stay silent for a moment, contemplate all around you, enjoy freshness, think about big deeds you have to do.
Today everything ... | 3 | import math
str=input('').split(' ');
d=int(str[0]);
h=int(str[1]);
v=int(str[2]);
e=int(str[3]);
tmp=d*d/4*math.pi
if tmp*e<v:
print('YES')
print(tmp*h/(v-tmp*e))
else:
print('NO') |
Ania has a large integer S. Its decimal representation has length n and doesn't contain any leading zeroes. Ania is allowed to change at most k digits of S. She wants to do it in such a way that S still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with?
Input
The first... | 3 | n,k = map(int,input().split())
S = list(input())
i = 0
if k==0 and len(S)==1:
print(*S)
exit()
if len(S)==1:
print('0')
exit()
while k!=0:
if i>=len(S):
print(*S,sep='')
exit()
if int(S[0])>1:
S[0] = 1
k -= 1
if i>0:
if int(S[i])>0:
S[i] =... |
Student Valera is an undergraduate student at the University. His end of term exams are approaching and he is to pass exactly n exams. Valera is a smart guy, so he will be able to pass any exam he takes on his first try. Besides, he can take several exams on one day, and in any order.
According to the schedule, a stud... | 3 | n = int(input())
a = []
for i in range(n):
a.append(tuple(map(int, input().split())))
a.sort()
curr = 0
for t in a:
if t[1] >= curr:
curr = t[1]
else:
curr = t[0]
print(curr) |
You are given a rectangular matrix of size n Γ m consisting of integers from 1 to 2 β
10^5.
In one move, you can:
* choose any element of the matrix and change its value to any integer between 1 and n β
m, inclusive;
* take any column and shift it one cell up cyclically (see the example of such cyclic shift belo... | 3 | import sys
import math
from collections import defaultdict,deque
import heapq
n,m=map(int,sys.stdin.readline().split())
arr=[]
for i in range(n):
l=list(map(int,sys.stdin.readline().split()))
arr.append(l)
ans=0
for i in range(m):
dic=defaultdict(int)
cnt=0
vis=defaultdict(int)
for j in range(n)... |
To quickly hire highly skilled specialists one of the new IT City companies made an unprecedented move. Every employee was granted a car, and an employee can choose one of four different car makes.
The parking lot before the office consists of one line of (2n - 2) parking spaces. Unfortunately the total number of cars... | 3 | n=int(input())
if n==2:
print(4)
elif n==3:
print(24)
else:
print((4*2*3*(4**(n-3)))+(4*(n-3)*(3**2)*(4**(n-4)))) |
Dolphin loves programming contests. Today, he will take part in a contest in AtCoder.
In this country, 24-hour clock is used. For example, 9:00 p.m. is referred to as "21 o'clock".
The current time is A o'clock, and a contest will begin in exactly B hours. When will the contest begin? Answer in 24-hour time.
Constrain... | 1 | #ABC057A
a,b=map(int,raw_input().split())
print (a+b)%24
|
The only difference between the easy and the hard versions is the maximum value of k.
You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one β from 1 to 2... | 3 | ind,lst,string=1,[0],''
for i in range(1,30000):
lst.append(lst[-1]+ind)
string+=str(i)
ind+=len(str(i+1))
q=int(input())
from bisect import bisect
for a in range(q):
k=int(input())
i=bisect(lst,k)
k-=lst[i-1]
if k==0:print(str(i-1)[-1])
else:print(string[k-1]) |
We have a point A with coordinate x = n on OX-axis. We'd like to find an integer point B (also on OX-axis), such that the absolute difference between the distance from O to B and the distance from A to B is equal to k.
<image> The description of the first test case.
Since sometimes it's impossible to find such point ... | 1 | def f(n,k):
if k>n: return k-n
else: return int(k%2!=n%2)
for t in xrange(int(raw_input())):
n,k=map(int,raw_input().split())
print f(n,k)
|
You are given a rooted tree with n vertices. The vertices are numbered from 1 to n, the root is the vertex number 1.
Each vertex has a color, let's denote the color of vertex v by cv. Initially cv = 0.
You have to color the tree into the given colors using the smallest possible number of steps. On each step you can c... | 3 | n = int(input())
f = [0, 0] + list(map(int, input().split()))
c = [0] + list(map(int, input().split()))
ans = 0
for i in range(2, n + 1):
if c[i] != c[f[i]]: ans += 1
ans += 1
print(ans) |
Being tired of participating in too many Codeforces rounds, Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.
He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits ... | 3 | def main():
from sys import stdin,stdout
for _ in range(int(stdin.readline())):
x,y,a,b = map(int,stdin.readline().split())
#print(x,y,a,b)
a+=b
#print(a)
#print(y%a,x%a)
if y%a -x%a == 0:
stdout.write(str((y-x)//a)+'\n')
else:
std... |
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())
s = str(input())
if n > 2*s.count('A'):
print('Danik')
elif n < 2*s.count('A'):
print('Anton')
else:
print('Friendship')
|
You are both a shop keeper and a shop assistant at a small nearby shop. You have n goods, the i-th good costs a_i coins.
You got tired of remembering the price of each product when customers ask for it, thus you decided to simplify your life. More precisely you decided to set the same price for all n goods you have.
... | 3 | S,R = 0,""
for i in range(int(input())):
X=int(input())
L=list(map(int,input().split()))
S=sum(L)
if S%X==0:
R+=str(int(S/X))+"\n"
else:
while S%X!=0: S+=1
R+=str(int(S/X))+"\n"
print(R) |
The new operating system BerOS has a nice feature. It is possible to use any number of characters '/' as a delimiter in path instead of one traditional '/'. For example, strings //usr///local//nginx/sbin// and /usr/local/nginx///sbin are equivalent. The character '/' (or some sequence of such characters) at the end of ... | 1 | s = raw_input()
ret = [s[0]]
for i in range(1,len(s)):
if s[i] =="/" and s[i-1] == "/":
continue
else:
ret.append(s[i])
if len(ret) == 1:
print " ".join(ret)
else:
if ret[-1] == "/":
print "".join(ret[:-1])
else:
print "".join(ret)
|
You are given a positive integer n, written without leading zeroes (for example, the number 04 is incorrect).
In one operation you can delete any digit of the given integer so that the result remains a positive integer without leading zeros.
Determine the minimum number of operations that you need to consistently ap... | 3 | u = list(map(int, list(input())))
n = len(u)
d = []
for i in range(1, 100001):
d.append(list(map(int, list(str(i * i)))))
ans = []
for k in d:
if len(k) > n:
break
m = 0
j = 0; i = 0
while i < n and j < len(k):
if u[i] == k[j]:
i += 1; j += 1
else:
i +... |
There are N points in a D-dimensional space.
The coordinates of the i-th point are (X_{i1}, X_{i2}, ..., X_{iD}).
The distance between two points with coordinates (y_1, y_2, ..., y_D) and (z_1, z_2, ..., z_D) is \sqrt{(y_1 - z_1)^2 + (y_2 - z_2)^2 + ... + (y_D - z_D)^2}.
How many pairs (i, j) (i < j) are there such ... | 3 | N, D = map(int, input().split())
X = [list(map(int, input().split())) for _ in range(N)]
ans = 0
for i in range(N):
for j in range(i+1, N):
if (sum([(X[i][k] - X[j][k]) ** 2 for k in range(D)]) ** 0.5 ).is_integer():
ans += 1
print(ans)
|
Manao is trying to open a rather challenging lock. The lock has n buttons on it and to open it, you should press the buttons in a certain order to open the lock. When you push some button, it either stays pressed into the lock (that means that you've guessed correctly and pushed the button that goes next in the sequenc... | 3 | def main():
num_buttons = int(input())
print(num_buttons + (num_buttons**2)*(num_buttons + 1)//2 -
(num_buttons)*(num_buttons + 1)*(2*num_buttons + 1) // 6)
main()
|
You have a given integer n. Find the number of ways to fill all 3 Γ n tiles with the shape described in the picture below. Upon filling, no empty spaces are allowed. Shapes cannot overlap.
<image> This picture describes when n = 4. The left one is the shape and the right one is 3 Γ n tiles.
Input
The only line cont... | 3 | import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
import random
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.r... |
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());print(a*min(n,b-1)//b) |
Vasya has recently got a job as a cashier at a local store. His day at work is L minutes long. Vasya has already memorized n regular customers, the i-th of which comes after t_{i} minutes after the beginning of the day, and his service consumes l_{i} minutes. It is guaranteed that no customer will arrive while Vasya is... | 3 | n, L, a = map(int,input().split())
if(n==0):
print(L//a)
elif(n==1):
t, l = map(int,input().split())
h=0
if(t>=a):
h = h + t//a
L = L -t - l
h = h + L//a
print(h)
else:
o = []
c=0
for _ in range(n):
m = list(map(int,input().split()))
o.append(m)
for i ... |
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy... | 3 | x = y = z = 0
for i in range(int(input())):
vector = list(map(lambda x: int(x), input().split()))
x += vector[0]
y += vector[1]
z += vector[2]
if x == y == z == 0:
print('YES')
else:
print('NO') |
This is the easy version of the problem. The difference between the versions is that in the easy version all prices a_i are different. You can make hacks if and only if you solved both versions of the problem.
Today is Sage's birthday, and she will go shopping to buy ice spheres. All n ice spheres are placed in a row ... | 3 | n = int(input())
a = sorted(list(map(int, input().split())))
val = 0
b, c = a[:n//2], a[n//2:-1]
sol = [a[-1]]
d = []
b_ptr, c_ptr = len(b)-1, len(c)-1
while True:
if b_ptr<0 or c_ptr<0:break
cc = c[c_ptr]
while b_ptr>=0:
if b[b_ptr]>=cc:
d.append(b[b_ptr])
b_ptr-=1
e... |
HQ9+ is a joke programming language which has only four one-character instructions:
* "H" prints "Hello, World!",
* "Q" prints the source code of the program itself,
* "9" prints the lyrics of "99 Bottles of Beer" song,
* "+" increments the value stored in the internal accumulator.
Instructions "H" and "Q"... | 3 | st = input()
cst = ['H', 'Q', '9']
for i in cst:
if i in st:
print('YES')
break
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 |
def factorial(n):
return 1 if (n == 1 or n == 0) else n * factorial(n - 1)
n=int(input())
print(factorial(n)//((n//2)*n)) |
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word s. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if... | 3 | inputs = input()
word="hello"
for i in range(len(inputs)):
if word=="":
break
if inputs[i]==word[0]:
word=word[1:]
if word=="":
print("YES")
else:
print("NO") |
Given a permutation p of length n, find its subsequence s_1, s_2, β¦, s_k of length at least 2 such that:
* |s_1-s_2|+|s_2-s_3|+β¦+|s_{k-1}-s_k| is as big as possible over all subsequences of p with length at least 2.
* Among all such subsequences, choose the one whose length, k, is as small as possible.
If mul... | 3 | from math import fabs
def main():
test = int(input())
for _ in range(test):
n = int(input())
ara = [int(num) for num in input().split()]
if n == 2:
ans = ara
else:
ans = []
ans.append(ara[0])
left = 0
mid = 1
... |
The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has n students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times.
The ... | 3 | n, k = map(int, input().split())
icpc = list(map(int, input().split()))
pp = []
for i in range(n):
if (icpc[i] + k <= 5):
pp.append(icpc[i])
print(len(pp) // 3)
|
Greg is a beginner bodybuilder. Today the gym coach gave him the training plan. All it had was n integers a1, a2, ..., an. These numbers mean that Greg needs to do exactly n exercises today. Besides, Greg should repeat the i-th in order exercise ai times.
Greg now only does three types of exercises: "chest" exercises,... | 1 | n=input();l=map(int,raw_input().split())
d={'chest':0,'biceps':0,'back':0}
s=0;i=0
while i<n:
s+=1
if s==1: d['chest']+=l[i]
elif s==2: d['biceps']+=l[i]
elif s==3: d['back']+=l[i]
else:
s=0;i-=1
i+=1
for i in d:
if d[i]==max(d.values()):
print i
break
|
You've been in love with Coronavirus-chan for a long time, but you didn't know where she lived until now. And just now you found out that she lives in a faraway place called Naha.
You immediately decided to take a vacation and visit Coronavirus-chan. Your vacation lasts exactly x days and that's the exact number of d... | 3 | n,x=map(int,input().split());D=list(map(int,input().split()));Ans=[];D+=D;D=D[::-1];d=0;p=0;q=0;tot=0;ans=0
for i in D:Ans.append(i*(i+1)//2)
while p<2*n and q<2*n:
while p<2*n and q<2*n and d+D[p]<x:d+=D[p];tot+=Ans[p];p+=1
if p==q:k=D[p]-x+d;tot+=Ans[p]-k*(k+1)//2;ans=max(ans,tot);d=0;tot=0;p+=1;q+=1
... |
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... | 1 | n = int(raw_input())
l = int(raw_input())
power=0
x=1
while power<l:
power = n**x
if power==l:
print "YES"
print x-1
else:
x+=1
if power>l:
print "NO" |
Kolya got an integer array a_1, a_2, ..., a_n. The array can contain both positive and negative integers, but Kolya doesn't like 0, so the array doesn't contain any zeros.
Kolya doesn't like that the sum of some subsegments of his array can be 0. The subsegment is some consecutive segment of elements of the array.
Y... | 3 | n = int(input())
a = list(map(int,input().split()))
arr = set()
arr.add(0)
x=0
ans=0
for i in a:
x+=i;
if x in arr:
ans += 1
arr = set()
arr.add(0)
x = i
arr.add(x)
print(ans) |
Musicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well.
There are n cities in Berland. People can travel between cities using two-directional train routes; there are exactly m routes, i-th route can be used to go from c... | 3 | from heapq import heappush,heappop,heapify
import sys
input=sys.stdin.readline
n,m=map(int,input().split())
graph=[[] for i in range(n+1)]
for _ in range(m):
u,v,w=map(int,input().split())
graph[u].append((v,2*w))
graph[v].append((u,2*w))
ans=[int(i) for i in input().split()]
heap=[(ans[i],i+1) for i in ran... |
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them.
Input
The first line contains integ... | 1 | n=input();c=raw_input()
print sum(p==n for p, n in zip(c[1:],c)) |
Holidays have finished. Thanks to the help of the hacker Leha, Noora managed to enter the university of her dreams which is located in a town Pavlopolis. It's well known that universities provide students with dormitory for the period of university studies. Consequently Noora had to leave ViΔkopolis and move to Pavlopo... | 3 | import math
a,b=map(int,input().split())
print(math.factorial(min(a,b)))
#print(math.gcd(math.factorial(a),math.factorial(b)))
|
You have an array a_1, a_2, ..., a_n. All a_i are positive integers.
In one step you can choose three distinct indices i, j, and k (i β j; i β k; j β k) and assign the sum of a_j and a_k to a_i, i. e. make a_i = a_j + a_k.
Can you make all a_i lower or equal to d using the operation above any number of times (possibl... | 3 | for _ in range(int(input())):
n, d = map(int, input().split())
a = list(map(int, input().split()))
flag = True
for i in range(n):
if a[i] > d:
flag = False
if flag == True:
print("YES")
continue
# If changes are required
a.sort()
immature = a[0] + a[1]... |
Two foxes Jiro and Saburo are playing a game called 1D Reversi. This game is played on a board, using black and white stones. On the board, stones are placed in a row, and each player places a new stone to either end of the row. Similarly to the original game of Reversi, when a white stone is placed, all black stones b... | 3 | S=input()
n=len(S)
c=0
for i in range(n-1):
if S[i] != S[i+1]:
c+=1
print(c) |
Okabe needs bananas for one of his experiments for some strange reason. So he decides to go to the forest and cut banana trees.
Consider the point (x, y) in the 2D plane such that x and y are integers and 0 β€ x, y. There is a tree in such a point, and it has x + y bananas. There are no trees nor bananas in other point... | 3 | def sumRectangle(x,y):
s = 0
a = (y+1)*(y)//2
b = (y+1)*(x+1)*x//2
return a*(x+1)+b
m,b = [int(x) for x in input().split(' ')]
mx = -1
for y in range(b+1):
sumR = sumRectangle((b-y)*m,y)
if sumR > mx:
mx=sumR
print(mx)
|
An n Γ n table a is defined as follows:
* The first row and the first column contain ones, that is: ai, 1 = a1, i = 1 for all i = 1, 2, ..., n.
* Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the remaining elements are defin... | 3 | n = int(input())
table = [[-1 for i in range(n)]for j in range(n)]
for k in range(n):
table[0][k] = 1
table[k][0] = 1
# print(table)
maxx = 1
for c in range(1, n):
for r in range(1 , n):
table[c][r] = table[c-1][r] + table[c][r-1]
if maxx < table[c][r] : maxx = table[c][r]
print(maxx)
|
Lord Omkar has permitted you to enter the Holy Church of Omkar! To test your worthiness, Omkar gives you a password which you must interpret!
A password is an array a of n positive integers. You apply the following operation to the array: pick any two adjacent numbers that are not equal to each other and replace them ... | 3 | #!/usr/bin/pypy3
# import sys
# sys.stdin = open("/home/vaibhav/python/input.txt", "r")
# sys.stdout = open("/home/vaibhav/python/output.txt", "w")
for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
x = max(a)
if a.count(x) == n:
print(n)
else:
print(1... |
Andrey received a postcard from Irina. It contained only the words "Hello, Andrey!", and a strange string consisting of lowercase Latin letters, snowflakes and candy canes. Andrey thought that this string is an encrypted message, and decided to decrypt it.
Andrey noticed that snowflakes and candy canes always stand af... | 3 | s=input()
k=int(input())
ans=""
cane=0
flake=0
l=0
for i in s:
if i=="*":
flake+=1
elif i=="?":
cane+=1
else:
l+=1
if l==k:
for i in s:
if i!="*" and i!="?":
ans+=i
print(ans)
elif l<k:
t=k-l
flag=0
if flake!=0:
for i in range(len(s)):
... |
Vasya lives in a strange world. The year has n months and the i-th month has ai days. Vasya got a New Year present β the clock that shows not only the time, but also the date.
The clock's face can display any number from 1 to d. It is guaranteed that ai β€ d for all i from 1 to n. The clock does not keep information ab... | 1 | d = int(raw_input())
n = int(raw_input())
a = map(int, raw_input().split())
ans = 0
for i in range(1, n):
day = a[i - 1] % d + 1
if day != 1:
ans += d - day + 1
print ans |
Toad Zitz has an array of integers, each integer is between 0 and m-1 inclusive. The integers are a_1, a_2, β¦, a_n.
In one operation Zitz can choose an integer k and k indices i_1, i_2, β¦, i_k such that 1 β€ i_1 < i_2 < β¦ < i_k β€ n. He should then change a_{i_j} to ((a_{i_j}+1) mod m) for each chosen integer i_j. The i... | 3 | def f(x):
curr=0
for i in range(n):
if(curr>=m):
return 0
if(x<m-arr[i]):
if(arr[i]+x<curr):
return 0
curr=max(curr,arr[i])
else:
start=(x+arr[i])%m
if(curr>start):
curr=max(curr,arr[i])
retur... |
Giga Tower is the tallest and deepest building in Cyberland. There are 17 777 777 777 floors, numbered from - 8 888 888 888 to 8 888 888 888. In particular, there is floor 0 between floor - 1 and floor 1. Every day, thousands of tourists come to this place to enjoy the wonderful view.
In Cyberland, it is believed t... | 3 | def if8(b):
if b<0:
b=-b
while b>0:
if b%10 ==8:
return True
b=b//10
return False
a = int(input())
b=a+1
while not if8(b):
b +=1
print(b-a)
|
Two deer, AtCoDeer and TopCoDeer, are playing a game called Honest or Dishonest. In this game, an honest player always tells the truth, and an dishonest player always tell lies. You are given two characters a and b as the input. Each of them is either `H` or `D`, and carries the following information:
If a=`H`, AtCoDe... | 1 | a, b = raw_input().split()
print "H" if (a=="H") == (b=="H") else "D" |
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are ... | 3 | """
βββ βββββββ βββ βββββββ βββββββ βββ ββββββ
βββββββββββββββ βββββββββββββββββββββββββββββ
ββββββ ββββββ ββββββββββββββββββββββββββββ
ββββββ ββββββ βββββββ βββββββββ βββ βββββββ
βββββββββββββββ βββββββββββββββββ βββ βββββββ
βββ βββββββ βββ ββββββββ βββββββ βββ ββββββ
""" ... |
Little Petya is learning to play chess. He has already learned how to move a king, a rook and a bishop. Let us remind you the rules of moving chess pieces. A chessboard is 64 square fields organized into an 8 Γ 8 table. A field is represented by a pair of integers (r, c) β the number of the row and the number of the co... | 3 | x, y, x1, y1 = map(int, input().split())
a, b, c = 0, 0, 0
def ladya(x, y, x1, y1):
global a
if x == x1 or y == y1:
a = 1
else:
a = 2
def slon(x, y, x1, y1):
global b
if (x + y) % 2 == (x1 + y1) % 2:
b = 2
if abs(x - x1) == abs(y - y1):
b = 1
def kin... |
You are given two n Γ m matrices containing integers. A sequence of integers is strictly increasing if each next number is greater than the previous one. A row is strictly increasing if all numbers from left to right are strictly increasing. A column is strictly increasing if all numbers from top to bottom are strictly... | 3 | from collections import defaultdict, deque
from heapq import heappush, heappop
from math import inf
ri = lambda : map(int, input().split())
def solve():
n,m = ri()
A = []
for _ in range(n):
A.append(list(ri()))
B = []
for _ in range(n):
B.append(list(ri()))
for i in range(n):
... |
A family consisting of father bear, mother bear and son bear owns three cars. Father bear can climb into the largest car and he likes it. Also, mother bear can climb into the middle car and she likes it. Moreover, son bear can climb into the smallest car and he likes it. It's known that the largest car is strictly larg... | 1 | v1, v2, v3, vm = map(int, raw_input().split())
s1 = v1 * 2
s2 = v2 * 2
mn1, mx1 = v3, v3 * 2
mn2, mx2 = vm, vm * 2
min_s3 = max(mn1, mn2)
max_s3 = min(mx1, mx2)
if min_s3 <= max_s3 and min_s3 * 2 < s2:
print s1
print s2
print min_s3
else:
print '-1'
|
After you had helped George and Alex to move in the dorm, they went to help their friend Fedor play a new computer game Β«Call of Soldiers 3Β».
The game has (m + 1) players and n types of soldiers in total. Players Β«Call of Soldiers 3Β» are numbered form 1 to (m + 1). Types of soldiers are numbered from 0 to n - 1. Each ... | 3 | def main():
s = input().split()
n = int(s[0])
m = int(s[1])
k = int(s[-1])
players = []
for i in range(m):
player = int(input())
players.append(player)
fedor = int(input())
army = []
for i in range(n):
army.append(fedor%2)
fedor = fedor // 2
output... |
We have N+M balls, each of which has an integer written on it.
It is known that:
* The numbers written on N of the balls are even.
* The numbers written on M of the balls are odd.
Find the number of ways to choose two of the N+M balls (disregarding order) so that the sum of the numbers written on them is even.
It c... | 3 | N,M = map(int,input().split())
print((N-1)*N//2+(M-1)*M//2) |
Takahashi is going to buy N items one by one.
The price of the i-th item he buys is A_i yen (the currency of Japan).
He has M discount tickets, and he can use any number of them when buying an item.
If Y tickets are used when buying an item priced X yen, he can get the item for \frac{X}{2^Y} (rounded down to the nea... | 3 | from heapq import*;N,M,*A=map(lambda x:-int(x),open(0).read().split());heapify(A)
for _ in range(-M):heappush(A,0-heappop(A)//-2)
print(-sum(A)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.