problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
You are given a rectangular board of M × N squares. Also you are given an unlimited number of standard domino pieces of 2 × 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squa... | 3 | print( eval("*".join(input().split(" ")))//2 )
|
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 | t=int(input())
l=list(map(int,input().split()))
sum=0
for i in range(len(l)):
sum+=l[i]
print(sum/len(l)) |
We have a graph with N vertices and M edges, and there are two people on the graph: Takahashi and Aoki.
The i-th edge connects Vertex U_i and Vertex V_i. The time it takes to traverse this edge is D_i minutes, regardless of direction and who traverses the edge (Takahashi or Aoki).
Takahashi departs Vertex S and Aoki ... | 3 | import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return [int(x) for x in sys.stdin.... |
Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then... | 3 | a, d = [input() for i in range(int(input()))], {}
for i in reversed(a):
if i not in d.keys() : print(i)
d[i] = 1 |
[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... | 3 | x,y,z=map(int,input().split())
a,b,c=map(int,input().split())
if(x>a or x+y>a+b or x+y+z>a+b+c):
print("NO")
else:
print("YES") |
Dawid has four bags of candies. The i-th of them contains a_i candies. Also, Dawid has two friends. He wants to give each bag to one of his two friends. Is it possible to distribute the bags in such a way that each friend receives the same amount of candies in total?
Note, that you can't keep bags for yourself or thro... | 3 | #%% 1230a Dawid and a bag of candies
a,b,c,d = sorted([int(x) for x in input().split()])
if a+d==(b+c) or (a+b+c)==d:
print('YES')
else:
print('NO') |
You are given two integers n and k. Your task is to find if n can be represented as a sum of k distinct positive odd (not divisible by 2) integers or not.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases.
The next t lines... | 3 | t = int(input())
for _ in range(0, t):
n, k = list(map(int, input().split()))
if (n % 2 == 0 and k % 2 == 1) or (n % 2 == 1 and k % 2 == 0) or (((1 + k*2) // 2) * (((k*2 - 1) // 2) + 1) > n):
print('NO')
else:
print('YES')
|
You are given an array a consisting of n integers. You have to find the length of the smallest (shortest) prefix of elements you need to erase from a to make it a good array. Recall that the prefix of the array a=[a_1, a_2, ..., a_n] is a subarray consisting several first elements: the prefix of the array a of length k... | 1 | from __future__ import division, print_function
import os,sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
def ii(): return int(input())
def si(): return input()
def mi(): return map(in... |
Two players decided to play one interesting card game.
There is a deck of n cards, with values from 1 to n. The values of cards are pairwise different (this means that no two different cards have equal values). At the beginning of the game, the deck is completely distributed between players such that each player has a... | 3 | import sys
t = int(sys.stdin.readline())
for i in range(t):
args = [int(x) for x in sys.stdin.readline().split()]
p1_cards = [int(x) for x in sys.stdin.readline().split()]
p2_cards = [int(x) for x in sys.stdin.readline().split()]
if max(p1_cards) > max(p2_cards):
sys.stdout.write("YES\n")
... |
You took a peek on Thanos wearing Infinity Gauntlet. In the Gauntlet there is a place for six Infinity Gems:
* the Power Gem of purple color,
* the Time Gem of green color,
* the Space Gem of blue color,
* the Soul Gem of orange color,
* the Reality Gem of red color,
* the Mind Gem of yellow color.
... | 3 | n = int(input())
d = {'purple': 'Power', 'green': 'Time', 'blue': 'Space', 'orange': 'Soul', 'red': 'Reality', 'yellow': 'Mind', }
f = {'purple', 'green', 'blue', 'orange', 'red', 'yellow', }
for i in range(n):
f -= {input()}
print(len(f))
for i in f:
print(d[i])
|
Foo was not amongst the most brilliant students of his class. So, he has some pending exams to clear. As the exams are approaching, this time he vowed to pass in all of them. This will only happen if he is not under stress. Foo's stress can be calculated using a simple function called Foo_function which depends upon th... | 1 | t=int(raw_input())
def calc(x):
global a
s=0
for i in xrange(3,-1,-1):
s+=(x**i)*a[3-i]
return s
def b_s(a,high):
low=0
#high=10**6
mid=(high+low)//2
#t=False
while low<=high:
#print mid
jk=calc(mid)
jkl=calc(mid+1)
if jk<=a[-1] and jkl>a[-1]:
... |
Sean is trying to save a large file to a USB flash drive. He has n USB flash drives with capacities equal to a1, a2, ..., an megabytes. The file size is equal to m megabytes.
Find the minimum number of USB flash drives needed to write Sean's file, if he can split the file between drives.
Input
The first line contai... | 1 | data = []
n = int(raw_input())
m = int(raw_input())
for i in range(n):
data.append(int(raw_input()))
data.sort(reverse=True)
count = 0
for i in range(n):
m -= data[i]
count += 1
if m <= 0:
break
print count
|
You might have heard about the next game in Lara Croft series coming out this year. You also might have watched its trailer. Though you definitely missed the main idea about its plot, so let me lift the veil of secrecy.
Lara is going to explore yet another dangerous dungeon. Game designers decided to use good old 2D e... | 3 | n,m,k = [int(x) for x in input().split()]
if k<n:
print(k+1,1)
else:
k = k-n+1
val = m-1
a = k//val
b = k%val
x = n-a+1
y = -1
if b!=0:
x-=1
if b==0:
if a%2==1:
y = m
else:
y = 2
else:
if a%2==1:
y = m+1-b
else:
y = 1+b
print(x,y)
|
Let's call two strings s and t anagrams of each other if it is possible to rearrange symbols in the string s to get a string, equal to t.
Let's consider two strings s and t which are anagrams of each other. We say that t is a reducible anagram of s if there exists an integer k ≥ 2 and 2k non-empty strings s_1, t_1, s_... | 3 | import io
import os
from collections import Counter, defaultdict, deque
alpha = "abcdefghijklmnopqrstuvwxyz"
assert len(alpha) == 26
def solve(S, Q, queries):
lettersToPref = [[0] for i in range(26)]
for i, x in enumerate(S):
for i, c in enumerate(alpha):
if c == x:
lett... |
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If... | 3 | n = input()
a = n.find('1111111')
b = n.find('0000000')
if a >= 0 or b >= 0:
print('YES')
else:
print('NO')
|
Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is n.
There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains 2 apartments, every other floor contains x apartments each. Apartments are numbered starting from one, from... | 3 | import math
T = int(input())
while(T>0):
n, x = [int(i) for i in input().split()]
if n<=2:
print(1)
else:
print(1 + math.ceil((n-2)/x))
T -= 1
|
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.
Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya'... | 3 | n,m=list(map(int,input().split()))
a=set(map(int,input().split()))
s=m
al=len(a)
b=[]
for i in range(1,m+1):
if i not in a:
if i<=s:
b.append(i)
s-=i
if i>s:break
print(len(b))
print(*b)
|
Ann has recently started commuting by subway. We know that a one ride subway ticket costs a rubles. Besides, Ann found out that she can buy a special ticket for m rides (she can buy it several times). It costs b rubles. Ann did the math; she will need to use subway n times. Help Ann, tell her what is the minimum sum of... | 1 | #!/usr/bin/python
from collections import deque
from collections import Counter
def ir():
return int(raw_input())
def ia():
line = raw_input()
line = line.split()
return map(int, line)
n, m, a, b = ia()
p1 = a*n
p2 = (n + m - 1) // m * b
p3 = n // m * b + n % m * a
print min(min(p1, p2)... |
This is an easier version of the problem. In this version n ≤ 1000
The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company ... | 3 | import sys
reader = (line.rstrip() for line in sys.stdin)
input = reader.__next__
n = int(input())
m = list(map(int, input().split()))
smaller_left = [-1] * n
stack = []
for i in reversed(range(n)):
val = m[i]
while stack and val < stack[-1][0]:
_, j = stack.pop()
smaller_left[j] = i
s... |
Mishka got an integer array a of length n as a birthday present (what a surprise!).
Mishka doesn't like this present and wants to change it somehow. He has invented an algorithm and called it "Mishka's Adjacent Replacements Algorithm". This algorithm can be represented as a sequence of steps:
* Replace each occurre... | 3 | n=int(input())
a=list(map(int,input().split()))
for i in range(n):
if a[i]%2==0:
a[i]=a[i]-1
for i in a:
print(i,end=' ')
|
After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum nu... | 1 | import math
n = int(raw_input())
a = [int(x) for x in raw_input().split()]
c1, c2, c3, c4 = 0, 0, 0, 0
count = 0
for i in range(n):
if a[i] == 4:
c4+=1
elif a[i] == 3:
c3 += 1
elif a[i] == 2:
c2 += 1
else:
c1 += 1
count = c4
count += c3
if c3>=c1:
c1 = 0
else:
c1 ... |
Chef is on a vacation these days, so his friend Chefza is trying to solve Chef's everyday tasks.
Today's task is to make a sweet roll. Rolls are made by a newly invented cooking machine. The machine is pretty universal - it can make lots of dishes and Chefza is thrilled about this.
To make a roll, Chefza has to set all... | 1 | for t in xrange(int(raw_input())):
a, b = map(int, raw_input().split())
ops = 0
while a > b or bin(a).count('1') > 1:
a >>= 1
ops += 1
while a != b:
a <<= 1
ops += 1
print ops |
There is a polyline going through points (0, 0) – (x, x) – (2x, 0) – (3x, x) – (4x, 0) – ... - (2kx, 0) – (2kx + x, x) – ....
We know that the polyline passes through the point (a, b). Find minimum positive value x such that it is true or determine that there is no such x.
Input
Only one line containing two positiv... | 1 | a,b = map(float,raw_input().split())
min_ = b
k = 1.0
s = (a+b)/float(2*b)
if int(s)==0:
print -1
else:
ss = int(s)
ans = (a+b)/float(2*ss)
print "%.11f"%ans
|
Recently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area.
To prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of n r... | 3 | n,m=map(int,input().split())
mod=10**9+7
if n>m:
n,m=m,n
if m==1:
print(2)
else:
DP=[[0]*2 for _ in range(m)]
DP[1][0]=2
DP[1][1]=2
for i in range(2,m):
DP[i][0]=DP[i-1][1]%mod
DP[i][1]=(DP[i-1][0]+DP[i-1][1])%mod
a=DP[m-1][0]+DP[m-1][1]
if n==1:
print(a%mod)
else:
ans=a-2
ans+=DP... |
A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not.
The next prime number after x is the smallest prime number greater than x. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that ... | 3 | def main():
[n, m] = [int(_) for _ in input().split()]
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53]
print('YES' if primes[primes.index(n) + 1] == m else 'NO')
if __name__ == '__main__':
main()
|
Anton likes to listen to fairy tales, especially when Danik, Anton's best friend, tells them. Right now Danik tells Anton a fairy tale:
"Once upon a time, there lived an emperor. He was very rich and had much grain. One day he ordered to build a huge barn to put there all his grain. Best builders were building that ba... | 1 | string1 = raw_input()
list1 = string1.split()
n = int(list1[0])
m = int(list1[1])
flag = True;
if m >= n:
print n
flag = False;
else:
num = (n-m)*2
l = 0
h = n
while l < h:
mid = (l+h)/2;
if num == mid*(mid + 1):
l =mid
break
elif num > mid*(mid + 1):
l = mid + 1
else:
h = mid
if flag == Tru... |
Little Petya has recently started attending a programming club. Naturally he is facing the problem of choosing a programming language. After long considerations he realized that Java is the best choice. The main argument in favor of choosing Java was that it has a very large integer data type, called BigInteger.
But h... | 3 | a=int(input())
if a>=-128 and a<=127:
print('byte')
elif a>=-32768 and a<=32767:
print('short')
elif a>=-2147483648 and a<=2147483647:
print('int')
elif a>=-9223372036854775808 and a<=9223372036854775807:
print('long')
else:
print('BigInteger')
|
Vova is playing a computer game. There are in total n turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is k.
During each turn Vova can choose what to do:
* If the current charge of his laptop battery is strictly gre... | 3 |
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from bisect import *
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
newl... |
You are given a grid of squares with H horizontal rows and W vertical columns, where each square is painted white or black. HW characters from A_{11} to A_{HW} represent the colors of the squares. A_{ij} is `#` if the square at the i-th row from the top and the j-th column from the left is black, and A_{ij} is `.` if t... | 3 | from collections import deque
h,w=list(map(int,input().split()))
a=[[c for c in input()] for _ in range(h)]
visit=[[0]*w for _ in range(h)]
q=deque()
for i in range(h):
for j in range(w):
if a[i][j]=='#':
deque.appendleft(q,(i,j,0))
visit[i][j]=1
ans=0
while len(q)>0:
i,j,cnt=d... |
Katie, Kuro and Shiro are best friends. They have known each other since kindergarten. That's why they often share everything with each other and work together on some very hard problems.
Today is Shiro's birthday. She really loves pizza so she wants to invite her friends to the pizza restaurant near her house to cele... | 1 | n = input()
if n == 0:
print(0)
elif n%2:
print((n+1)/2)
else:
print(n+1) |
Ilya is working for the company that constructs robots. Ilya writes programs for entertainment robots, and his current project is "Bob", a new-generation game robot. Ilya's boss wants to know his progress so far. Especially he is interested if Bob is better at playing different games than the previous model, "Alice".
... | 3 | def update_point(a_point,b_point,winner):
if winner=='a':
a_point+=1
elif winner=='b':
b_point+=1
return a_point,b_point
k,a,b=map(int,input().split())
A=[None]*3
for i in range(3):
A[i]=list(map(int,input().split()))
B=[None]*3
for i in range(3):
B[i]=list(map(int,input().split()))
winner_rules=[None]*3
for... |
Mishka got a six-faced dice. It has integer numbers from 2 to 7 written on its faces (all numbers on faces are different, so this is an almost usual dice).
Mishka wants to get exactly x points by rolling his dice. The number of points is just a sum of numbers written at the topmost face of the dice for all the rolls M... | 3 | t = int(input())
while t > 0:
t = t-1
n = int(input())
print((n+6)//7)
|
For a given polygon g, computes the area of the polygon.
g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≤ i ≤ n-1) are sides of g. The line segment connecting pn and p1 is also a side of the polygon.
Note that the polygon is not necessarily convex.
Constraints
... | 3 | n=int(input())
point=[]
x_1,y_1=[int(i) for i in input().split(" ")]
for _ in range(n-1):
x,y=[int(i) for i in input().split(" ")]
point.append([x-x_1,y-y_1])
a=0
for i in range(n-2):a+=point[i][0]*point[i+1][1] - point[i][1]*point[i+1][0]
print(a*0.5) |
You are given an array a consisting of n integer numbers.
Let instability of the array be the following value: max_{i = 1}^{n} a_i - min_{i = 1}^{n} a_i.
You have to remove exactly one element from this array to minimize instability of the resulting (n-1)-elements array. Your task is to calculate the minimum possible... | 3 | n = int(input())
a = list(map(int, input().split()))
if n==2:
print(0)
else:
a.sort()
if (a[n-1]-a[1]>a[n-2]-a[0]):
print(a[n-2]-a[0])
else:
print(a[n-1]-a[1])
|
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 | #!/usr/bin/env python3.6
def main(**kwargs):
weight = int(input())
print("YES") if (weight >= 4) & (weight % 2 == 0) else print("NO")
main()
exit()
|
A word or a sentence in some language is called a pangram if all the characters of the alphabet of this language appear in it at least once. Pangrams are often used to demonstrate fonts in printing or test the output devices.
You are given a string consisting of lowercase and uppercase Latin letters. Check whether thi... | 3 | input()
s = set(input().lower())
l = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
for i in l:
if not i in s:
print('NO')
break
else:
print('YES') |
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 | l=input().split('+')
l.sort()
print('+'.join(l))
|
Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings a and b of equal length are called equivalent in one of the two cases:
1. They are equal.
2. If we split string a into two halves of the same size a1 and a2, and string b into two halves of the same size b1 and b2... | 3 | def reorder(a):
length = len(a)
if length % 2 == 1:
return a
else:
p_a = reorder(a[:length//2])
s_a = reorder(a[length//2:])
if p_a < s_a:
return p_a + s_a
else:
return s_a + p_a
if reorder(input()) == reorder(input()):
print("YES")
else:
... |
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 | n=input()
if n.count("H")>0 or n.count("Q")>0 or n.count("9")>0:
print("YES")
else:
print("NO")
|
You are playing a computer game. In this game, you have to fight n monsters.
To defend from monsters, you need a shield. Each shield has two parameters: its current durability a and its defence rating b. Each monster has only one parameter: its strength d.
When you fight a monster with strength d while having a shiel... | 3 | import sys,bisect
input=sys.stdin.readline
MOD=998244353
def f(a,b):return a*pow(b,MOD-2,MOD)
n,m=map(int,input().split())
d=sorted(map(int,input().split()))
pref=[0]
for v in d:pref.append(pref[-1] + v)
out=[0]*m
for _ in range(m):
a,b=map(int,input().split());i=bisect.bisect_left(d,b)
if a<=n-i:out[_]=(pref[i]*f(n-... |
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
def flagstone():
inputList = list((input().split()))
n = int(inputList[0])
m = int(inputList[1])
a = int(inputList[2])
multipleAN = math.ceil(n/a)
multipleAM = math.ceil(m/a)
counterN = 0
counterM = 0
#print(n,m,a,multipleAN,multipleAM,counterN,counterM)
"""
while... |
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 | x = int(input(""))
if (x%2 == 0 and x!=2):
print('Yes')
else:
print('No') |
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 ... | 3 | t = int(input())
times = []
m_c = 0
last = "-1"
count = 1
while t:
n,k = input().split(" ")
time = n + k
if time==last:
count = count + 1
else:
if count > m_c:
m_c = count
count = 1
last = time
t-=1
print(max(m_c, count)) |
Let's call a list of positive integers a_0, a_1, ..., a_{n-1} a power sequence if there is a positive integer c, so that for every 0 ≤ i ≤ n-1 then a_i = c^i.
Given a list of n positive integers a_0, a_1, ..., a_{n-1}, you are allowed to:
* Reorder the list (i.e. pick a permutation p of \{0,1,...,n - 1\} and change... | 3 | n = int(input())
a = sorted(list(map(int, input().split())))
inf = 10**18
if n < 3:
print(a[0] - 1)
exit()
ans = sum(a) - n
for j in range(10**9):
c_p = 1
c_c = 0
for i in range(n):
c_c += abs(a[i] - c_p)
c_p *= j+1
if c_p > inf:
break
if c_p > inf:
br... |
Kana was just an ordinary high school girl before a talent scout discovered her. Then, she became an idol. But different from the stereotype, she is also a gameholic.
One day Kana gets interested in a new adventure game called Dragon Quest. In this game, her quest is to beat a dragon.
<image>
The dragon has a hit p... | 3 | def solve():
x,n,m = [int(x) for x in input().split(" ")]
for i in range(n):
if x>10:
x = x//2 + 10
for j in range(m):
x -= 10
if x <= 0:
print("YES")
else:
print("NO")
t = int(input())
for i in range(t):
solve()
|
A magic island Geraldion, where Gerald lives, has its own currency system. It uses banknotes of several values. But the problem is, the system is not perfect and sometimes it happens that Geraldionians cannot express a certain sum of money with any set of banknotes. Of course, they can use any number of banknotes of ea... | 3 |
n = int(input())
arr = list(map(int,input().strip().split()))
arr = sorted(arr)
if arr[0]==1:
print(-1)
else:
print(1) |
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).
Let p be any permutation of length ... | 3 | #!/usr/bin/env python3
# created : 2020. 12. 31. 23:59
import os
from sys import stdin, stdout
def solve(tc):
n = int(stdin.readline().strip())
seq = list(map(int, stdin.readline().split()))
print(' '.join(map(lambda x : str(x), seq[::-1])))
tcs = 1
tcs = int(stdin.readline().strip())
tc = 1
while tc ... |
Bessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play!
More specifically, he wants to get from (0,0) to (x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance betw... | 3 | import math
t=int(input())
for _ in range(t):
n,x=map(int,input().split())
a=list(map(int,input().split()))
if x in a:
print(1)
else:
k=max(a)
print(max(2,math.ceil(x/k)))
|
You are given three integers x, y and n. Your task is to find the maximum integer k such that 0 ≤ k ≤ n that k mod x = y, where mod is modulo operation. Many programming languages use percent operator % to implement it.
In other words, with given x, y and n you need to find the maximum possible integer from 0 to n tha... | 3 | t=int(input())
while(t>0):
x,y,n=[int(x) for x in input().split()]
rem=n%x
# print(rem)
if rem==y:
print(n)
elif rem>y:
print(n-(rem-y))
else:
print(n-(rem+x-y))
t-=1
|
You are given an array s consisting of n integers.
You have to find any array t of length k such that you can cut out maximum number of copies of array t from array s.
Cutting out the copy of t means that for each element t_i of array t you have to find t_i in s and remove it from s. If for some t_i you cannot find s... | 1 | N, K = map(int, raw_input().split())
A = map(int, raw_input().split())
def binsearch_upper(array):
lo, hi = 1, (10 ** 5) * 2
ret = hi+1
while lo <= hi:
mid = (lo + hi) // 2
key = sum((x[1] // mid for x in array))
if key < K:
hi = mid - 1
ret = mid
e... |
You are given a three-digit positive integer N.
Determine whether N is a palindromic number.
Here, a palindromic number is an integer that reads the same backward as forward in decimal notation.
Constraints
* 100≤N≤999
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output... | 3 | N = input()
print("Yes") if N[0] == N[2] else print("No") |
Counting sort can be used for sorting elements in an array which each of the n input elements is an integer in the range 0 to k. The idea of counting sort is to determine, for each input element x, the number of elements less than x as C[x]. This information can be used to place element x directly into its position in ... | 3 | # coding=utf-8
def counting_sort(A, B, k):
C = [0 for i in range(k+1)]
for a in A:
C[a] += 1
for i in range(1, k+1):
C[i] = C[i] + C[i-1]
for a in A[::-1]:
B[C[a]-1] = a
C[a] -= 1
return B
n = int(input())
A = list(map(int, input().split()))
k = max(A)
B = [0 f... |
Bob loves everything sweet. His favorite chocolate bar consists of pieces, each piece may contain a nut. Bob wants to break the bar of chocolate into multiple pieces so that each part would contain exactly one nut and any break line goes between two adjacent pieces.
You are asked to calculate the number of ways he can... | 3 | pieces = int(input())
order = list(map(int,input().split()))
first_1 = 0
consec = 1
ways = 1
exist_1 = 0
for i,piece in enumerate(order):
if piece == 1:
first_1 = i
exist_1 = 1
break
if exist_1 == 1:
for piece in order[first_1:]:
if piece == 1:
ways *= consec
... |
A long time ago in some far country lived king Copa. After the recent king's reform, he got so large powers that started to keep the books by himself.
The total income A of his kingdom during 0-th year is known, as well as the total income B during n-th year (these numbers can be negative — it means that there was a l... | 1 | A,B,n=[int(i)for i in raw_input().split()]
if A:
if B%A:
print'No solution'
else:
t=B/A
if t<0:
if n&1:
k=-int(.5+((-t)**(1./n)))
if k**n==t:
print k
else:
print'No solution'
e... |
Two players play a simple game. Each player is provided with a box with balls. First player's box contains exactly n1 balls and second player's box contains exactly n2 balls. In one move first player can take from 1 to k1 balls from his box and throw them away. Similarly, the second player can take from 1 to k2 balls f... | 1 | numbers = raw_input().split(" ")
player1Box = int(numbers[0])
player2Box = int(numbers[1])
player1Balls = int(numbers[2])
player2Balls = int(numbers[3])
if player1Box <= player2Box:
print "Second"
else:
print "First" |
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 | # cook your dish here
import math
# n=int(input())
# m=int(input())
# a=int(input())
nma = input()
arr=nma.split()
n=int(arr[0])
m=int(arr[1])
a=int(arr[2])
# public class Codechef
# {
# public static void main (String[] args) throws java.lang.Exception
# {
# double n,m,a;
# Scanner sc = new Scanner(System.... |
A matrix of size n × m is called nice, if all rows and columns of the matrix are palindromes. A sequence of integers (a_1, a_2, ... , a_k) is a palindrome, if for any integer i (1 ≤ i ≤ k) the equality a_i = a_{k - i + 1} holds.
Sasha owns a matrix a of size n × m. In one operation he can increase or decrease any numb... | 3 | def optimal(li):
li.sort()
ans1=ans2=0
val1=li[1]
val2=li[2]
for i in range(4):
ans1+=abs(li[i]-val1)
ans2+=abs(li[i]-val2)
return min(ans1,ans2)
def tp(li,n):
ans=0
for i in range(n//2):
ans+=abs(li[i]-li[n-i-1])
return ans
t=int(input())
for _ in ... |
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.
Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character... | 3 | x = [1]+[ord(i)-96 for i in input()]
print(sum([min((x[i]-x[i+1])%26, (x[i+1]-x[i])%26) for i in range(len(x)-1)])) |
Vasya has n pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every m-th day (at days with numbers m, 2m, 3m, ...) mom buys a pair of socks to Vasya. She does it late in the eve... | 1 | Socks,Cycle=map(int,raw_input().split())
Ans=0
Cyc=Cycle
while Socks:
Cyc-=1
if not Cyc:
Cyc=Cycle
Socks+=1
Socks-=1
Ans+=1
print Ans
|
Nastia has 2 positive integers A and B. She defines that:
* The integer is good if it is divisible by A ⋅ B;
* Otherwise, the integer is nearly good, if it is divisible by A.
For example, if A = 6 and B = 4, the integers 24 and 72 are good, the integers 6, 660 and 12 are nearly good, the integers 16, 7 are ne... | 3 | import sys,os,io
from sys import stdin,stdout
from math import log, gcd, ceil
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop
from bisect import bisect_left , bisect_right
import bisect
import math
input = stdin.readline
alphabets = list('abcdefghijklmnopqrstuvwxyz')
def isPr... |
You are given a string s consisting of exactly n characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.
Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string ... | 3 | n = int(input().strip())
a = list(input().strip())
c = [0,0,0]
d = {}
d[0]=[]
d[1]=[]
d[2]=[]
for i in a:
if i=="0":
c[0]+=1
d[0].append(i)
elif i=="1":
c[1]+=1
d[1].append(i)
else:
c[2]+=1
d[2].append(i)
p = n//3
r01 = 0
r10 = 0
r12 = 0
r21 = 0
r02 = 0
r20 = 0
if c[0]>p:
if c[1]>=p:
r02=c[0]-p
r12=... |
For an integer n not less than 0, let us define f(n) as follows:
* f(n) = 1 (if n < 2)
* f(n) = n f(n-2) (if n \geq 2)
Given is an integer N. Find the number of trailing zeros in the decimal notation of f(N).
Constraints
* 0 \leq N \leq 10^{18}
Input
Input is given from Standard Input in the following format:
... | 3 | n=int(input())
sum=0
if n%2==0:
a=n
while a>0:
a=a//5
sum+=a//2
print(sum) |
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them.
Input
The first line contains integ... | 3 | n=int(input())
word=input()
num=0
for i in range(n):
if i > 0 and word[i]==word[i-1]:
num=num+1
print(num) |
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())
c=0
u=0
b=list(input().split())
for i in b:
if i!='-1':
c=c+int(i)
else:
if c>0:
c=c-1
else:
u+=1
print(u) |
A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all n squad soldiers to line up on the parade ground.
By the military charter the soldiers should stand in the order of non-increasing of their h... | 3 | n=int(input())
l=list(map(int,input().split()))
m=0
k=n-1
for i in range(n):
if l[i]>l[m]:
m=i
if l[i]<=l[k]:
k=i
if k>m:
print(n+m-k-1)
else:
print(n+m-k-2)
|
Once upon a time a child got a test consisting of multiple-choice questions as homework. A multiple-choice question consists of four choices: A, B, C and D. Each choice has a description, and the child should find out the only one that is correct.
Fortunately the child knows how to solve such complicated test. The chi... | 3 | a = []
for i in range(4):
a.append(len(input()) - 2)
ans = list("ABCD")
tosc = ''
for i in range(4):
ok1 = 1;
ok2 = 1;
for j in range(4):
if i == j:
continue;
if a[i] < 2 * a[j]:
ok1 = 0
if a[i] * 2 > a[j]:
ok2 = 0
if any((ok1, ok2)):... |
For given integers m and n, compute mn (mod 1,000,000,007). Here, A (mod M) is the remainder when A is divided by M.
Constraints
* 1 ≤ m ≤ 100
* 1 ≤ n ≤ 109
Input
m n
Two integers m and n are given in a line.
Output
Print mn (mod 1,000,000,007) in a line.
Examples
Input
2 3
Output
8
Input
5 8
Output... | 3 | MAX = 1000000007
m, n = [int(x) for x in input().split(' ')]
bi_n = bin(n)
ans = 1
dig = m
for i in range(len(bi_n)-1, 1, -1):
if bi_n[i] == '1': ans *= dig
if ans >= MAX: ans %= MAX
dig *= dig
if dig >= MAX: dig %= MAX
print(ans)
|
The sequence of m integers is called the permutation if it contains all integers from 1 to m exactly once. The number m is called the length of the permutation.
Dreamoon has two permutations p_1 and p_2 of non-zero lengths l_1 and l_2.
Now Dreamoon concatenates these two permutations into another sequence a of length... | 1 | from __future__ import division, print_function
def main():
for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
front = [0]*n
back = [0]*n
max_so_far = 0
m2 = 0
d1 = {}
d2 = {}
for i in range(n):
max_s... |
Ivan has a robot which is situated on an infinite grid. Initially the robot is standing in the starting cell (0, 0). The robot can process commands. There are four types of commands it can perform:
* U — move from the cell (x, y) to (x, y + 1);
* D — move from (x, y) to (x, y - 1);
* L — move from (x, y) to (x... | 3 | x=int(input())
a=input()
R=0
L=0
U=0
D=0
for i in a:
if i == 'U' :
U+=1
if i == 'D' :
D+=1
if i == 'L' :
L+=1
if i == 'R' :
R+=1
p1=1
p2=1
if R < L :
p1=R*2
else:
p1=L*2
if D < U :
p2=D*2
else:
p2=U*2
print(p1+p2) |
Polycarp knows that if the sum of the digits of a number is divisible by 3, then the number itself is divisible by 3. He assumes that the numbers, the sum of the digits of which is divisible by 4, are also somewhat interesting. Thus, he considers a positive integer n interesting if its sum of digits is divisible by 4.
... | 3 | A = int(input())
while sum([int(x) for x in str(A)]) % 4 != 0:
A += 1
print(A)
|
Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be ... | 3 | import sys
from math import *
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int, minp().split())
n, k = mints()
c = n-k
r = []
j = c + 1
for i in range(1,min(c,k)+1):
r.append((j,i))
j += 1
for i in range(c+1,k+1):
r.append((j,c))
j += 1
res = 2
if c =... |
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()
row = raw_input()
results = []
result = 0
for count in "RGB":
for index, color in enumerate(row):
if index + 1 != n:
if color == row[index+1] == count:
#print(color + " " + row[index+1])
result += 1
else:
results.append(result)
#result = 0
print(result) |
For the multiset of positive integers s=\\{s_1,s_2,...,s_k\}, define the Greatest Common Divisor (GCD) and Least Common Multiple (LCM) of s as follow:
* \gcd(s) is the maximum positive integer x, such that all integers in s are divisible on x.
* lcm(s) is the minimum positive integer x, that divisible on all integ... | 1 | """Template for Python Competitive Programmers prepared by pa.n.ik, kabeer seth and Mayank Chaudhary """
# to use the print and division function of Python3
from __future__ import division, print_function
"""value of mod"""
MOD = 998244353
mod = 10**9 + 7
"""use resource"""
# import resource
# resource.setrlimit(res... |
Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands.
Monocarp's empire has n cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monum... | 3 | import time
#start_time = time.time()
#def TIME_(): print(time.time()-start_time)
import os, sys
from io import BytesIO, IOBase
from types import GeneratorType
from bisect import bisect_left, bisect_right
from collections import defaultdict as dd, deque as dq, Counter as dc
import math, string, heapq as h
BUFSIZE = 8... |
Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him.
One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For e... | 3 | n = int(input())
l = list(map(int,input().split()))
c=0
for i in range(1,n):
if l[i] > max(l[0:i]) or l[i] < min(l[0:i]):
c+=1
print(c)
|
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.
The language is that peculiar as it has exactly one variable, called x. Also, there are two operations:
* Operation ++ increases the value of variable x by 1.
* Operation -- decreases the value of variable x by 1.... | 1 | t = input()
x = 0
for i in range(t):
text = raw_input()
if '++' in text:
x+=1
if '--' in text:
x-=1
print x |
You are given two integers a and b. Determine if a+b=15 or a\times b=15 or neither holds.
Note that a+b=15 and a\times b=15 do not hold at the same time.
Constraints
* 1 \leq a,b \leq 15
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
a b
Output
If a+b=15,... | 3 | a, b = map(int, input().split())
print("+") if a+b==15 else print("*") if a*b==15 else print("x") |
Given three integers x, m and n. Evaluate (1 + x + x^ 2 + .. + x^ m) (mod n)
Input
First line of the input contains a single integer T representing number of test cases that follow.
For next T lines, each line contains three space separated integers x, m and n.
Output
Output exactly T lines each containing the... | 1 | T = int(raw_input())
for t in range(T):
x,m,n=map(int,raw_input().split())
if x == 1:
print (m+1)%n
else:
n=n*(x-1)
res = (pow(x, m+1, n)-1)
res = (res+n)%n
print int(res/(x-1)) |
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 | b = [[int(str(a) * i) for i in range(1, 5)] for a in range(1, 10)]
for _ in range(int(input())):
e = int(input())
c = 0
for a in b:
o = False
for t, i in enumerate(a):
c += t + 1
if i == e:
o = True
break
if o:
brea... |
There are two rival donut shops.
The first shop sells donuts at retail: each donut costs a dollars.
The second shop sells donuts only in bulk: box of b donuts costs c dollars. So if you want to buy x donuts from this shop, then you have to buy the smallest number of boxes such that the total number of donuts in them ... | 3 | from sys import stdin, stdout
import math
t = int(stdin.readline())
for _ in range(t):
a, b, c = map(int, stdin.readline().split())
ans = [-1, -1]
if c <= a:
ans[1] = b
elif c < a*b:
ans[0] = 1
ans[1] = b
elif c == a*b:
ans[0] = 1
else:
ans[0] = 1
pri... |
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some num... | 3 | n = int(input())
s = input()
c = 0
if n > 26:
print(-1)
else:
for i in range(n):
for j in range(i + 1, n):
if s[i] == s[j]:
c += 1
break
print(c)
|
"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 | n,k=map(int, input().split())
s = list(map(int, input().split()))
ans=0
for i in range(n):
if s[i-1]>0 and s[i-1]>=s[k-1]:
ans+=1
print (ans) |
Petya has a string of length n consisting of small and large English letters and digits.
He performs m operations. Each operation is described with two integers l and r and a character c: Petya removes from the string all characters c on positions between l and r, inclusive. It's obvious that the length of the string ... | 1 | from collections import defaultdict
import sys
input = raw_input
range = xrange
def lower_bound(A, x):
a = 0
b = len(A)
while a < b:
c = (a + b) >> 1
if A[c] < x:
a = c + 1
else:
b = c
return a
def upper_bound(A, x):
a = 0
b = len(A)
while ... |
Aoki loves numerical sequences and trees.
One day, Takahashi gave him an integer sequence of length N, a_1, a_2, ..., a_N, which made him want to construct a tree.
Aoki wants to construct a tree with N vertices numbered 1 through N, such that for each i = 1,2,...,N, the distance between vertex i and the farthest vert... | 3 | import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
"""
・直径の長さをdとする。だいたい、半径より下の長さは存在できない
・だいたいd/2より上は任意に足せる。ただし中心は1組のみ
"""
N,*A = map(int,read().split())
def test(A):
D = max(A)
r = (D+1)//2
counter = [0] * (D+1)
for x in A:
coun... |
Alice guesses the strings that Bob made for her.
At first, Bob came up with the secret string a consisting of lowercase English letters. The string a has a length of 2 or more characters. Then, from string a he builds a new string b and offers Alice the string b so that she can guess the string a.
Bob builds b from a... | 3 | t=int(input())
for _ in range(t):
s=input()
n=len(s)
st=""+s[0]
i=1
while(i<n-1):
if(s[i]==s[i+1]):
st+=s[i]
i+=1
else:
st += s[i]
i+=1
print(st+s[n-1]) |
There are n athletes in front of you. Athletes are numbered from 1 to n from left to right. You know the strength of each athlete — the athlete number i has the strength s_i.
You want to split all athletes into two teams. Each team must have at least one athlete, and each athlete must be exactly in one team.
You want... | 3 | tests = int(input())
for i in range(tests):
n = int(input())
arr = list(map(int,input().split()))
arr.sort()
maxv = 100000000
for i in range(n-1):
val = arr[i+1]-arr[i]
if val< maxv:
maxv = val
print(maxv)
|
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_lines = int(input(" "))
birds = list(map(int, (input(" ").split(" "))))
n_shoots = int(input(" "))
for x in range (n_shoots) :
xi,yi =(map(int, ( input(" ").split(" "))))
t = yi - 1
b = birds [xi-1] - yi
birds[xi-1] = 0
if (xi - 2) >= 0 :
birds[xi-2 ] = birds[xi-2] + t
if xi < len... |
After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer.
At the start of the day they have x ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. Each person in the q... | 3 | n,x=map(int,input().split())
c=0
for i in range(n):
*a, = input()
a = list(a)
if "+" in a:
del a[:2]
s=""
for i in a:
s+=i
x+=int(s)
elif "-" in a:
del a[:2]
s=""
for i in a:
s+=i
if int(s)>x:
c+=1
... |
You are given several queries. In the i-th query you are given a single positive integer ni. You are to represent ni as a sum of maximum possible number of composite summands and print this maximum number, or print -1, if there are no such splittings.
An integer greater than 1 is composite, if it is not prime, i.e. if... | 3 | for _ in range(int(input())):
n=int(input())
if n<4 or (n==5 or n==7 or n==11):
print(-1)
continue
r=n%4
if r==1:
print((n-9)//4+1)
elif r==3:
print((n-15)//4+2)
else:
print(n//4)
|
A competitive eater, Alice is scheduling some practices for an eating contest on a magical calendar. The calendar is unusual because a week contains not necessarily 7 days!
In detail, she can choose any integer k which satisfies 1 ≤ k ≤ r, and set k days as the number of days in a week.
Alice is going to paint some n... | 3 | t=int(input())
for i in range(t):
n,r=map(int,input().split())
if r<n:
an=(r*(r+1))//2
else:
n=n-1
an=(n*(n+1))//2
an=an+1
print(an)
|
Given is an integer N. Find the number of positive integers less than or equal to N that have an odd number of digits (in base ten without leading zeros).
Constraints
* 1 \leq N \leq 10^5
Input
Input is given from Standard Input in the following format:
N
Output
Print the number of positive integers less than ... | 3 | n = int(input())
print(len([l for l in list(map(str,range(1,n+1))) if len(l)%2==1])) |
You are given the current time in 24-hour format hh:mm. Find and print the time after a minutes.
Note that you should find only the time after a minutes, see the examples to clarify the problem statement.
You can read more about 24-hour format here <https://en.wikipedia.org/wiki/24-hour_clock>.
Input
The first line... | 3 | hh,mm=map(int,input().split(':'))
a=int(input())
m=(mm+a)%60
h=(mm+a)//60
h2=(hh+h)%24
print('{0:02d}:{1:02d}'.format(h2,m)) |
Nikolay has a lemons, b apples and c pears. He decided to cook a compote. According to the recipe the fruits should be in the ratio 1: 2: 4. It means that for each lemon in the compote should be exactly 2 apples and exactly 4 pears. You can't crumble up, break up or cut these fruits into pieces. These fruits — lemons, ... | 1 | a = int(raw_input())
b = int(raw_input())
c = int(raw_input())
print 7 * (min(a, b/2, c/4)) |
There are N cards placed on a grid with H rows and W columns of squares.
The i-th card has an integer A_i written on it, and it is placed on the square at the R_i-th row from the top and the C_i-th column from the left.
Multiple cards may be placed on the same square.
You will first pick up at most one card from eac... | 3 | import sys
sys.setrecursionlimit(10 ** 5)
class UnionFind:
def __init__(self, n):
self.table = [-1] * n
self.taken = [0] * n
def _root(self, x):
if self.table[x] < 0:
return x
else:
self.table[x] = self._root(self.table[x])
return self.tabl... |
An exam for n students will take place in a long and narrow room, so the students will sit in a line in some order. The teacher suspects that students with adjacent numbers (i and i + 1) always studied side by side and became friends and if they take an exam sitting next to each other, they will help each other for sur... | 1 | n=input()
if n==1:
print 1
print 1
elif n==2:
print 1
print 1
elif n==3:
print 2
print 1,3
else:
print n
if n%2==0:
for i in range(n-1,0,-2):
print i,
for i in range(n,0,-2):
print i,
else:
for i in range(n,0,-2):
... |
Given a sequence of numbers, find the absolute difference between the number of odd numbers and number of even numbers in a given sequence.
Input
The first line will contain the number of numbers in the sequence. And the second line will contain the sequence itself i.e. a series of integers separated by a space
Ou... | 1 | #!/usr/bin/python
count = int(raw_input())
nums = raw_input().split()
odd = 0
even = 0
for n in nums:
if int(n) % 2 == 0:
even = even + 1
else:
odd = odd + 1
print abs(odd - even) |
Recently Chef become very much interested in perfect squares. We all know Chef and his weird interests. Anyways Chef will be soon writing his masters thesis on perfect squares revealing what-not-known properties of perfect squares.
While doing his research, he happened to be confronted with some interesting perfect squ... | 1 | import sys
arr=[1,4,9,49,100,144,400,441,900,1444,4900,9409,10000,10404,11449,14400,19044,40000,40401,44100,44944,90000,144400,419904,490000,491401,904401,940900,994009,1000000,1004004,1014049,1040400,1100401,1144900,1440000,1904400,1940449,4000000,4004001,4040100,4410000,4494400,9000000,9909904,9941409,11909401,140100... |
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps:
1. Find the number that goes k-th in the current sequence and add the same number to the end of the sequence;
2. Delete the first number of the current s... | 1 | n,k = map(int,raw_input().split())
l = raw_input().split()
if l[k-1:len(l)] <> [l[k-1]] * (len(l)-k+1):
print -1
exit()
n = 0
for i in range(0,k)[::-1]:
if l[i] == l[k-1]:
n += 1
else:
break
print k - n |
You are given two integers x and y (it is guaranteed that x > y). You may choose any prime integer p and subtract it any number of times from x. Is it possible to make x equal to y?
Recall that a prime number is a positive integer that has exactly two positive divisors: 1 and this integer itself. The sequence of prime... | 3 | t=int(input())
for _ in range(t):
x,y=map(int,input().split())
r=x-y
if r==1:
print('NO')
else:
print('YES') |
There is a bookshelf which can fit n books. The i-th position of bookshelf is a_i = 1 if there is a book on this position and a_i = 0 otherwise. It is guaranteed that there is at least one book on the bookshelf.
In one move, you can choose some contiguous segment [l; r] consisting of books (i.e. for each i from l to r... | 3 | t = int(input())
for case in range(t):
n = int(input())
a = input()
ans = a[a.index('1'):a.rindex('1') + 1].count('0')
print(ans) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.