problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:
* Tetrahedron. Tetrahedron has 4 triangular faces.
* Cube. Cube has 6 square faces.
* Octahedron. Octahedron has 8 triangular faces.
* Dodecahedron. Dodecahedron has 12 pentagonal faces.
*... | 3 | n = int(input())
cnt = 0
for i in range(n):
entry = input()
if entry == "Tetrahedron": cnt += 4
elif entry == "Cube": cnt += 6
elif entry == "Octahedron": cnt += 8
elif entry == "Dodecahedron": cnt += 12
elif entry == "Icosahedron": cnt += 20
print(cnt)
# 1524000567431
|
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word.
Note, that during capitalization all the letters except the first one remains unchanged.
Input
A single line contains a non-empty word. This word consists of lowercase and uppercase English letters.... | 3 | s = str(input())
f = list(s)
if (f[0].isupper()):
print(s)
else:
print(f[0].upper()+s[1:])
|
Little chef has just been introduced to the world of numbers! While experimenting with addition and multiplication operations, the little chef came up with the following problem:
Given an array A of non-negative integers, how many pairs of indices i and j exist such that A[i]*A[j] > A[i]+A[j] where i < j .
Now be... | 1 | cases=int(raw_input().strip())
while(cases):
n=int(raw_input().strip())
a=raw_input().strip()
a=map(int,a.split())
# print a
count=0
ct=0;
k=1
total=(n*(n-1))/2
for i in range(len(a)):
if ( a[i]==1 or a[i]==0):
count+=(n-k)
k+=1
if ( a[i]==2):
ct+=1
#print count," ",ct
ct= (ct*(ct-1))/2
prin... |
A tuple of positive integers {x1, x2, ..., xk} is called simple if for all pairs of positive integers (i, j) (1 β€ i < j β€ k), xi + xj is a prime.
You are given an array a with n positive integers a1, a2, ..., an (not necessary distinct). You want to find a simple subset of the array a with the maximum size.
A prime n... | 1 | from itertools import product
def get_primes_fast(n):
if n < 2:
return []
if n < 3:
return [2]
lmtbf = (n - 3) / 2
buf = [True] * (lmtbf + 1)
for i in xrange((int(n ** 0.5) - 3) / 2 + 1):
if buf[i]:
p = i + i + 3
s = p * (i + 1) + i
buf[... |
There is a function f(x), which is initially a constant function f(x) = 0.
We will ask you to process Q queries in order. There are two kinds of queries, update queries and evaluation queries, as follows:
* An update query `1 a b`: Given two integers a and b, let g(x) = f(x) + |x - a| + b and replace f(x) with g(x).
... | 3 | import heapq
Q = int(input())
qs = [tuple(map(int,input().split())) for i in range(Q)]
lq = []
rq = []
heapq.heapify(lq)
heapq.heapify(rq)
ans = 0
for q in qs:
if q[0] == 2:
print(-lq[0], ans)
continue
_,a,b = q
ans += b
heapq.heappush(lq, -a)
heapq.heappush(rq, a)
if -lq[0] > ... |
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")
|
At the school where Vasya is studying, preparations are underway for the graduation ceremony. One of the planned performances is a ball, which will be attended by pairs of boys and girls.
Each class must present two couples to the ball. In Vasya's class, a boys and b girls wish to participate. But not all boys and not... | 3 | import sys
read=sys.stdin.buffer.read;readline=sys.stdin.buffer.readline;input=lambda:sys.stdin.readline().rstrip()
#import bisect,string,math,time,functools,random,fractions
#from heapq import heappush,heappop,heapify
#from collections import deque,defaultdict,Counter
#from itertools import permutations,combinations,g... |
There are two persons, numbered 0 and 1, and a variable x whose initial value is 0. The two persons now play a game. The game is played in N rounds. The following should be done in the i-th round (1 \leq i \leq N):
* Person S_i does one of the following:
* Replace x with x \oplus A_i, where \oplus represents bitwise X... | 3 | def main():
t = int(input())
for _ in range(t):
n, a, s, m = int(input()), list(map(int, input().split())), input(), []
for i in range(n-1, -1, -1):
ans = a[i]
for j in m:
ans = min(ans, ans ^ j)
if s[i] == "0":
if ans:
... |
Today at the lesson of mathematics, Petya learns about the digital root.
The digital root of a non-negative integer is the single digit value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-d... | 3 | import sys
def print_root(k, x):
print(str(9*(k-1) + x))
def process_input():
num_process = int(sys.stdin.readline())
for i in range(num_process):
entry = str(sys.stdin.readline()).split()
print_root(int(entry[0]), int(entry[1]))
process_input() |
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits.
Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has on... | 3 | y=int(input())
for y in range(y+1,1000000007):
s=set(str(y))
if len(s)==4:
print(y)
break
|
Pashmak decided to give Parmida a pair of flowers from the garden. There are n flowers in the garden and the i-th of them has a beauty number bi. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty difference i... | 3 | import math
n = int(input())
arr = list(map(int, input().split()))
if len(set(arr)) == 1:
xxx = (n*(n-1)) // 2
print(0, xxx)
exit()
x = max(arr)
y = min(arr)
diff = x - y
z = arr.count(x)
zz = arr.count(y)
ans = z * zz
print(diff, ans)
|
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find ... | 1 | def luck(n):
while n:
y = n%10
if y!=4 and y!=7:
return 0
n //=10
return 1
def almost_l(n):
if luck(n):
return 1
for i in range(1,n//2+1):
if n%i==0 and luck(i) :
return 1
return 0
n = int(raw_input())
if almost_l(n):
print('YES')
else:
print('NO')
|
Someday, Drazil wanted to go on date with Varda. Drazil and Varda live on Cartesian plane. Drazil's home is located in point (0, 0) and Varda's home is located in point (a, b). In each step, he can move in a unit distance in horizontal or vertical direction. In other words, from position (x, y) he can go to positions (... | 3 |
a , b , s = map(int,input().split())
l = abs(a) + abs(b)
if l > s :
print('No')
exit()
else:
if (l - s ) % 2 == 0 :
print('Yes')
exit()
else:
print('No')
exit()
|
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits.
Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has on... | 3 | n=int(input())
numbers=[]
for i in range(10):
numbers.append(str(i))
num={}
m=n+1
while True:
flag=0
for i in numbers:
num[i] = 0
l=list(str(m))
for k in l:
num[k] += 1
for k in l:
if num[k]>1:
flag=1
break
if flag==0:
print(m)
... |
Vasya has a non-negative integer n. He wants to round it to nearest integer, which ends up with 0. If n already ends up with 0, Vasya considers it already rounded.
For example, if n = 4722 answer is 4720. If n = 5 Vasya can round it to 0 or to 10. Both ways are correct.
For given n find out to which integer will Vasy... | 3 | n = int(input())
rem = n%10
if rem<5:
print(n-rem)
else:
print(n+10-rem) |
Alice and Bob have decided to play the game "Rock, Paper, Scissors".
The game consists of several rounds, each round is independent of each other. In each round, both players show one of the following things at the same time: rock, paper or scissors. If both players showed the same things then the round outcome is a ... | 3 | r =lambda:[*map(int,input().split())]
t=r()[0];a=r();b=r();bmax=0
x=sum(min(a[i],b[(i+1)%3])for i in range(3))
n=t-sum(min(a[i],t-b[(i+1)%3])for i in range(3))
print(n,x) |
Finished her homework, Nastya decided to play computer games. Passing levels one by one, Nastya eventually faced a problem. Her mission is to leave a room, where a lot of monsters live, as quickly as possible.
There are n manholes in the room which are situated on one line, but, unfortunately, all the manholes are clo... | 3 | q, w = map(int, input().split())
z = q + (q + min(q - w, w - 1)) + q
print(z)
|
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... | 1 | num = []
numsum = 0
ans = 0
for x in raw_input().split():
num.append(int(x))
num.sort()
mid = num[len(num)/2]
for x in num:
ans += abs(x - mid)
print ans
|
Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1, p2, ..., pn.
Your task is to find such permutation p of length n, that the group of numbers |p1 - p2|, |p2 - p3|, ..., |pn - 1 - pn| has exactly k d... | 3 | import time,math,bisect,sys
from sys import stdin,stdout
from collections import deque
from fractions import Fraction
from collections import Counter
pi=3.14159265358979323846264338327950
def II(): # to take integer input
return int(stdin.readline())
def IO(): # to take string input
return stdin.readline()
def ... |
Two friends are on the coordinate axis Ox in points with integer coordinates. One of them is in the point x1 = a, another one is in the point x2 = b.
Each of the friends can move by one along the line in any direction unlimited number of times. When a friend moves, the tiredness of a friend changes according to the f... | 3 | #!/usr/bin/env python3
import sys
a = int(sys.stdin.readline().strip())
b = int(sys.stdin.readline().strip())
def tri(d):
return (d * (d + 1)) // 2
d = abs(a - b)
if d % 2 == 0:
tide = 2 * tri(d // 2)
else:
tide = tri((d - 1) // 2) + tri((d + 1) // 2)
print (tide)
|
You are given a string, consisting of lowercase Latin letters.
A pair of neighbouring letters in a string is considered ugly if these letters are also neighbouring in a alphabet. For example, string "abaca" contains ugly pairs at positions (1, 2) β "ab" and (2, 3) β "ba". Letters 'a' and 'z' aren't considered neighbou... | 3 | from collections import Counter
t=int(input())
for i in range(t):
s=str(input())
d=list(s)
l=Counter(d)
f=[[x,l[x]] for x in l]
f.sort(key=lambda x:x[0])
if len(f)==2:
if ord(f[1][0])==ord(f[0][0])+1:print("No answer")
else:print(s)
elif len(f)==3:
if ord(f[2][0])==ord(f[1][0])+1==ord(f[0][0])+2:print("No ... |
There are N items, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N), Item i has a weight of w_i and a value of v_i.
Taro has decided to choose some of the N items and carry them home in a knapsack. The capacity of the knapsack is W, which means that the sum of the weights of items taken must be at most W.
Find ... | 3 | N,W=map(int,input().split())
WV=[list(map(int,input().split())) for i in range(N)]
V=10**3
DP_V=[float("inf")]*(V*N+1)
DP_V[0]=0
for i in range(N):
for j in range(V*N,-1,-1):
if j+WV[i][1]<=V*N:
DP_V[j+WV[i][1]]=min(DP_V[j+WV[i][1]],DP_V[j]+WV[i][0])
for i in range(V*N,-1,-1):
if DP_V[i]<=... |
Vasya often uses public transport. The transport in the city is of two types: trolleys and buses. The city has n buses and m trolleys, the buses are numbered by integers from 1 to n, the trolleys are numbered by integers from 1 to m.
Public transport is not free. There are 4 types of tickets:
1. A ticket for one r... | 1 | C =[0] + [int(x) for x in raw_input().split(' ')]
# print "C",C
n, m = [int(x) for x in raw_input().split(' ')]
A = [int(x) for x in raw_input().split(' ')]
B = [int(x) for x in raw_input().split(' ')]
cost_A = [min(A[i]*C[1], C[2]) for i in range(n)]
cost_B = [min(B[i]*C[1], C[2]) for i in range(m)]
Case = [None]*5
... |
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had a red socks and b blue socks.
According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot.
Every day Vasya puts on new socks in the morning and ... | 3 | from sys import exit
info = input().split()
redsock = int(info[0])
bluesock = int(info[1])
hipsterpairs = 0
regularpairs = 0
if redsock < bluesock:
hipsterpairs = redsock
bluesock = bluesock - redsock
redsock = 0
regularpairs = bluesock//2
elif redsock == bluesock:
print(redsock, 0)
exit(0)
els... |
You are given a positive integer X. Find the largest perfect power that is at most X. Here, a perfect power is an integer that can be represented as b^p, where b is an integer not less than 1 and p is an integer not less than 2.
Constraints
* 1 β€ X β€ 1000
* X is an integer.
Input
Input is given from Standard Input ... | 3 | x=int(input())
ans=1
for i in range(40):
for j in range(2,15):
if i**j<=x and i**j>ans:
ans=i**j
print(ans) |
Polycarp likes arithmetic progressions. A sequence [a_1, a_2, ..., a_n] is called an arithmetic progression if for each i (1 β€ i < n) the value a_{i+1} - a_i is the same. For example, the sequences [42], [5, 5, 5], [2, 11, 20, 29] and [3, 2, 1, 0] are arithmetic progressions, but [1, 0, 1], [1, 3, 9] and [2, 3, 1] are ... | 3 | length = int(input())
l = input().split(" ")
l = [int(e) for e in l]
assert length == len(l)
if len(l) < 3:
print(0)
exit()
result = -1
for d0 in [-1, 0, 1]:
for d1 in [-1, 0, 1]:
for d2 in [-1, 0, 1]:
step = l[1] + d1 - (l[0] + d0)
if step != l[2] + d2 - (l[1] + d1):
... |
In the city of Saint Petersburg, a day lasts for 2^{100} minutes. From the main station of Saint Petersburg, a train departs after 1 minute, 4 minutes, 16 minutes, and so on; in other words, the train departs at time 4^k for each integer k β₯ 0. Team BowWow has arrived at the station at the time s and it is trying to co... | 3 | a = int(input(), 2)
s = 1
ans = 0
while s < a:
ans+= 1
s *= 4
print(ans) |
Milly is playing with an Array A of size N. She wants to convert this array into a magical array. This magical array satisfies the condition Ai-1 < Ai where i β [2, N] . She can add a value X to any element of this array any number of times. Your task is to tell her the minimum number of such addition of X are required... | 1 | #!/usr/bin/env python
__author__ = "rramchandani"
import sys
import math
def solve(n, x, arr):
if n != len(arr):
return -1
count = 0
for index in range(0, len(arr)-1):
if arr[index] >= arr[index+1]:
diff = arr[index] - arr[index+1]
val = int(math.ceil(float(diff + ... |
Beroffice text editor has a wide range of features that help working with text. One of the features is an automatic search for typos and suggestions of how to fix them.
Beroffice works only with small English letters (i.e. with 26 letters from a to z). Beroffice thinks that a word is typed with a typo if there are thr... | 3 | """
Author - Satwik Tiwari .
"""
#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from functools imp... |
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy... | 3 | n=int(input())
a=0
b=0
c=0
while n>0:
n=n-1
x,y,z=[int (i) for i in input().split()]
a=a+x
b=b+y
c=c+z
if(a==0 and b==0 and c==0):
print('YES')
else:
print('NO')
|
Mislove had an array a_1, a_2, β
β
β
, a_n of n positive integers, but he has lost it. He only remembers the following facts about it:
* The number of different numbers in the array is not less than l and is not greater than r;
* For each array's element a_i either a_i = 1 or a_i is even and there is a number (a_i)/(... | 3 | n, l, r = map(int, input().split())
res = n - l
for i in range(l):
res = res + (1 << i)
print(res, end=' ')
res = (n - r) * (1 << (r - 1))
for i in range(r):
res = res + (1 << i)
print(res)
|
You are given two arrays a and b, each consisting of n positive integers, and an integer x. Please determine if one can rearrange the elements of b so that a_i + b_i β€ x holds for each i (1 β€ i β€ n).
Input
The first line of input contains one integer t (1 β€ t β€ 100) β the number of test cases. t blocks follow, each d... | 3 | for _ in range(int(input())):
g=list(map(int,input().split()))
if g==[]:
n,x=map(int,input().split())
l=list(map(int,input().split()))
a=list(map(int,input().split()))
a=a[::-1]
f=0
for i in range(n):
if l[i]+a[i]>x:
f=1
break
if f==1:
print('No')
... |
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 | #!/usr/bin/env python3
import atexit
import io
import sys
_I_B = sys.stdin.read().splitlines()
input = iter(_I_B).__next__
_O_B = io.StringIO()
sys.stdout = _O_B
@atexit.register
def write():
sys.__stdout__.write(_O_B.getvalue())
def main():
n,m=map(int,input().split())
m1=[]
m2=[]
for _ in rang... |
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made lik... | 3 | n = input()
for _ in range(int(n)):
word = input()
if len(word) > 10:
l = len(word) - 2
word = word[0] + str(l) + word[-1]
print(word) |
Polycarp is going to participate in the contest. It starts at h_1:m_1 and ends at h_2:m_2. It is guaranteed that the contest lasts an even number of minutes (i.e. m_1 \% 2 = m_2 \% 2, where x \% y is x modulo y). It is also guaranteed that the entire contest is held during a single day. And finally it is guaranteed tha... | 3 | a=input()
b=input()
a1=a.split(':')
b1=b.split(':')
a2=int(a1[0])*60+int(a1[1])
b2=int(b1[0])*60+int(b1[1])
k3=b2-a2
k1=a2+k3//2
a1=k1//60
a2=k1%60
k=''
if len(str(a1))==2:
k+=str(a1)+':'
else:
k+='0'+str(a1)+':'
if len(str(a2))==2:
k+=str(a2)
else:
k+='0'+str(a2)
print(k)
|
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 | w = int(input())
print("NO" if w % 2 or w <= 2 else "YES")
|
Let's denote a function f(x) in such a way: we add 1 to x, then, while there is at least one trailing zero in the resulting number, we remove that zero. For example,
* f(599) = 6: 599 + 1 = 600 β 60 β 6;
* f(7) = 8: 7 + 1 = 8;
* f(9) = 1: 9 + 1 = 10 β 1;
* f(10099) = 101: 10099 + 1 = 10100 β 1010 β 101.
... | 3 | import math
def f(x):
x+=1
while(x%10 == 0):
x = x//10
return x
n = int(input())
c = 0
s = 0
if(n < 10):
print(9)
else:
c = 9
while(n >= 10):
n = f(n)
c+=1
print(c)
|
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended u... | 3 | #!/usr/bin/env python
# coding: utf-8
# In[9]:
s=input()
l=len(s)
Acount=Bcount=0
for i in range(l):
if (i+1)&1:
if s[i]=='-':
Bcount+=1
else:
Acount+=1
else:
if s[i]=='-':
Acount+=1
else:
... |
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 | # import sys
try:
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')
n = int(input())
ans = 0
for i in range(n):
c = 0
x, y, z = map(int, input().split())
if x == 1:
c += 1
if y == 1:
c += 1
if z == 1:
c += 1
if c>=2:
ans += 1
print(ans)
except:
pass |
Raju loves playing with maths.He is very fond of factorials.Now he is interested in knowing the last five digits n!(nth number factorial).
As he is not very good at programming , so he needs your help.
Your task is to print the last five digits of n!.
If number of digits is less than 5 then print the answer with leadi... | 1 | import math
for t in range(input()):
number=int(raw_input())
if number>=26:
print "00000"
continue
if number==1:
print "00001"
continue
if number==2:
print "00002"
continue
if number==3:
print "00006"
continue
if number==4:
print "00024"
continue
if number==5:
print "00120"
continue
if n... |
Vasiliy spent his vacation in a sanatorium, came back and found that he completely forgot details of his vacation!
Every day there was a breakfast, a dinner and a supper in a dining room of the sanatorium (of course, in this order). The only thing that Vasiliy has now is a card from the dining room contaning notes ho... | 3 | a=list(map(int,input().split(' ')))
print(sum(max(0,max(a)-x-1)for x in a)) |
There are two infinite sources of water:
* hot water of temperature h;
* cold water of temperature c (c < h).
You perform the following procedure of alternating moves:
1. take one cup of the hot water and pour it into an infinitely deep barrel;
2. take one cup of the cold water and pour it into an infin... | 3 | from math import ceil, floor
from decimal import Decimal
def calculate(x, y, n):
return Decimal(x * n + y * (n - 1)) / Decimal(2 * n - 1)
def ca(x, y):
return (x + y) / 2
for _ in range(int(input())):
x, y, c = map(int, input().split())
ans1 = 2
if (x + y) / 2 >= c:
print(ans1)
... |
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 β€ i β€ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is it... | 3 | n = int(input())
l = list(map(int,input().split()))
a = [1 for x in range(n)]
for i in range(1,n):
if(l[i-1]<=l[i]):
a[i]+=a[i-1]
print(max(a)) |
You are given a matrix a consisting of positive integers. It has n rows and m columns.
Construct a matrix b consisting of positive integers. It should have the same size as a, and the following conditions should be met:
* 1 β€ b_{i,j} β€ 10^6;
* b_{i,j} is a multiple of a_{i,j};
* the absolute value of the dif... | 3 | from math import *
l = 1
for i in range(2,17):
l = (l*i)//gcd(l,i)
a,b = map(int,input().split())
m = []
for i in range(a):
m.append(list(map(int,input().split())))
for j in range(b):
#n = input()
if((i+j) % 2):
print(l,end=" ")
else:
print(l+m[i][j]**4,end=" ")
print() |
Polycarp is reading a book consisting of n pages numbered from 1 to n. Every time he finishes the page with the number divisible by m, he writes down the last digit of this page number. For example, if n=15 and m=5, pages divisible by m are 5, 10, 15. Their last digits are 5, 0, 5 correspondingly, their sum is 10.
You... | 1 | q=int(input())
for i in xrange(q):
n,m=map(int,raw_input().split())
d={}
l=[m%10]
i=m+m
while(1):
if i%m==0:
x=i%10
if l[0]==x:
break
else:
l.append(x)
i+=m
if n==m:
print n%10
elif len(l)==0:
... |
You are a paparazzi working in Manhattan.
Manhattan has r south-to-north streets, denoted by numbers 1, 2,β¦, r in order from west to east, and r west-to-east streets, denoted by numbers 1,2,β¦,r in order from south to north. Each of the r south-to-north streets intersects each of the r west-to-east streets; the interse... | 3 | import sys
from io import BytesIO, IOBase
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.writ... |
You are given the array a consisting of n positive (greater than zero) integers.
In one move, you can choose two indices i and j (i β j) such that the absolute difference between a_i and a_j is no more than one (|a_i - a_j| β€ 1) and remove the smallest of these two elements. If two elements are equal, you can remove a... | 3 | t=int(input())
for _ in range(t):
n=int(input())
arr=list(map(int,input().split()))
arr.sort()
c=0
if(n==1):
c=1
print('YES')
for i in range(n-1):
if(abs(arr[i]-arr[i+1])>1):
print('NO')
c=1
break
if(c==0):
print('YES')
... |
The HR manager was disappointed again. The last applicant failed the interview the same way as 24 previous ones. "Do I give such a hard task?" β the HR manager thought. "Just raise number 5 to the power of n and get last two digits of the number. Yes, of course, n can be rather big, and one cannot find the power using ... | 3 | n = input("")
print (25) |
You are given an integer number n. The following algorithm is applied to it:
1. if n = 0, then end algorithm;
2. find the smallest prime divisor d of n;
3. subtract d from n and go to step 1.
Determine the number of subtrations the algorithm will make.
Input
The only line contains a single integer n (2 β€... | 3 | # cook your dish her
from math import sqrt
n = int(input())
subs = 0
if n%2 != 0:
for i in range(2, int(sqrt(n))+1):
if n%i == 0:
n = n-i
subs += 1
break
else:
n = 0
subs += 1
subs += n//2
print(subs) |
You are going to hold a competition of one-to-one game called AtCoder Janken. (Janken is the Japanese name for Rock-paper-scissors.) N players will participate in this competition, and they are given distinct integers from 1 through N. The arena has M playing fields for two players. You need to assign each playing fiel... | 3 | n, m = map(int, input().split())
gu = 1
ki = m - m%2 + 2
for i in range(1, m+1)[::-1]:
if i % 2 == 0:
print(gu, gu+i)
gu += 1
else:
print(ki, ki+i)
ki += 1 |
Vasya learns to type. He has an unusual keyboard at his disposal: it is rectangular and it has n rows of keys containing m keys in each row. Besides, the keys are of two types. Some of the keys have lowercase Latin letters on them and some of the keys work like the "Shift" key on standard keyboards, that is, they make ... | 3 | from math import sqrt
def dist(x1, y1, x2, y2):
return sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
n, m, x = map(int, input().split())
keys = set()
keys_pos = {}
cnt = 0
for i in range(n):
j = 0
for w in input():
try:
keys_pos[w].append([i, j])
except:
keys_pos[w] = [50 ** ... |
You are given the array a consisting of n positive (greater than zero) integers.
In one move, you can choose two indices i and j (i β j) such that the absolute difference between a_i and a_j is no more than one (|a_i - a_j| β€ 1) and remove the smallest of these two elements. If two elements are equal, you can remove a... | 1 | def solve(n, arr_a):
even = odd = 0
for i in xrange(0, n):
if arr_a[i] % 2 == 0:
even += 1
else:
odd += 1
if odd == 0 or (even == 0 and odd % 2 == 0):
return "NO"
else:
return "YES"
if __name__ == "__main__":
t = int(raw_input())
res... |
For god's sake, you're boxes with legs! It is literally your only purpose! Walking onto buttons! How can you not do the one thing you were designed for?
Oh, that's funny, is it? Oh it's funny? Because we've been at this for twelve hours and you haven't solved it either, so I don't know why you're laughing. You've got ... | 3 | test = int(input())
for t in range(test):
n = int(input())
l = list(map(int, input().split()))
flag = False
for i in range(n-1):
if l[i]<=l[i+1]:
flag = True
if flag:
print("YES")
else:
print("NO") |
Three friends are going to meet each other. Initially, the first friend stays at the position x = a, the second friend stays at the position x = b and the third friend stays at the position x = c on the coordinate axis Ox.
In one minute each friend independently from other friends can change the position x by 1 to the... | 3 | from sys import stdin
def input():
return int(stdin.readline())
def minput():
return map(int, stdin.readline().split())
def linput():
return list(map(int, stdin.readline().split()))
for _ in range(input()):
a, b, c = minput()
m = 9999999999999
for i in range(-1, 2):
for j in rang... |
Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be n problems, sorted by difficulty, i.e. problem 1 is the easiest and problem n is the hardest. Limak knows it will take him 5Β·i minutes to solve the i-th... | 3 | n,k=map(int,input().split())
sum=k
i=0
while i<=n:
sum+=i*5
if sum>240:
break
i+=1
print(i-1) |
You are given three integers A, B and C.
Determine if there exists an equilateral triangle whose sides have lengths A, B and C.
Constraints
* All values in input are integers.
* 1 \leq A,B,C \leq 100
Input
Input is given from Standard Input in the following format:
A B C
Output
If there exists an equilateral ... | 3 |
A,B,C = map(int,input().split())
print("Yes") if(A == B and C == B) else print("No") |
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 = input()
s = input()
ret = 0
i = 0
while (i < len(s)):
j = i+1
while (j < len(s) and s[i]==s[j]):
ret+=1
j+=1
i=j
print(ret) |
Denis was very sad after Nastya rejected him. So he decided to walk through the gateways to have some fun. And luck smiled at him! When he entered the first courtyard, he met a strange man who was selling something.
Denis bought a mysterious item and it was... Random permutation generator! Denis could not believed hi... | 3 | for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
now = 1
yes = 0
j = -1
counter = 0
while yes == 0 and counter != n:
elem = a[j]
for i in range(a[j], now - 1, -1):
if a[j] != i:
print('No')
yes = 1
... |
Arkady plays Gardenscapes a lot. Arkady wants to build two new fountains. There are n available fountains, for each fountain its beauty and cost are known. There are two types of money in the game: coins and diamonds, so each fountain cost can be either in coins or diamonds. No money changes between the types are allow... | 1 | import heapq
import bisect
def best_under_price(fountains, max_price):
res = 0
for f in fountains:
if f[0] > max_price:
return res
res = max(res, f[1])
return res
def best_under(fountains):
best = [0 for i in xrange(len(fountains))]
second_best = [0 for i in xrange(len(fountains))]
second_best[0] = -1
... |
A class of students wrote a multiple-choice test.
There are n students in the class. The test had m questions, each of them had 5 possible answers (A, B, C, D or E). There is exactly one correct answer for each question. The correct answer for question i worth a_i points. Incorrect answers are graded with zero points.... | 3 | n,m=map(int,input().split())
a=[0]*m
b=[0]*m
c=[0]*m
d=[0]*m
e=[0]*m
sum=0
for _ in range(n):
s=input()
for i in range(m):
if s[i]=="A":
a[i]+=1
elif s[i]=="B":
b[i]+=1
elif s[i]=="C":
c[i]+=1
elif s[i]=="D":
d[i]+=1
elif s[... |
Alyona has recently bought a miniature fridge that can be represented as a matrix with h rows and 2 columns. Initially there is only one shelf at the bottom of the fridge, but Alyona can install arbitrary number of shelves inside the fridge between any two rows. A shelf is two cells wide, does not occupy any space but ... | 3 | a,c=map(int,input().split())
b=list(map(int,input().split()))
mx=1
for i in range(1,a):
t=b[0:i+1]
t.sort(reverse=True)
q=c
for j in range(0,len(t),2):
q-=t[j]
if(q>=0):
mx=i+1
print(mx) |
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).
For a positive integer n, we call a... | 3 | import sys, math
import io, os
#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
#from itertools import permutations,combinations
def data(): ... |
There is a card game called "Durak", which means "Fool" in Russian. The game is quite popular in the countries that used to form USSR. The problem does not state all the game's rules explicitly β you can find them later yourselves if you want.
To play durak you need a pack of 36 cards. Each card has a suit ("S", "H", ... | 3 | import sys,math
sys.setrecursionlimit(10**8)
'''
def fun():
for i in range(16):
for j in range(4):
if i&(1<<j):
print(j,end='')
print()
import binarytree
from collections import deque
bst = binarytree.tree(height=4,is_perfect=True)
print(bst)
def s(bst):
if bst:
... |
You are given three integers a, b and x. Your task is to construct a binary string s of length n = a + b such that there are exactly a zeroes, exactly b ones and exactly x indices i (where 1 β€ i < n) such that s_i β s_{i + 1}. It is guaranteed that the answer always exists.
For example, for the string "01010" there ar... | 3 | a, b, x = map(int, input().split())
string_result = ''
if x % 2 == 0:
half = x // 2
zeros = '0' * (a - half)
ones = '1' * (b - half)
if a > b:
string_result = '01' * half
string_result += ones
string_result += zeros
if a <= b:
string_result = '10' * half
str... |
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it:
* deletes all the vowels,
* inserts a character "." before each consonant,
* repl... | 1 | str0 = raw_input("")
str0 = str0.lower()
str0 = str0.replace('a','')
str0 = str0.replace('e','')
str0 = str0.replace('i','')
str0 = str0.replace('o','')
str0 = str0.replace('u','')
str0 = str0.replace('y','')
str1 = ""
for i in str0 :
str1+='.'
str1+= i
print (str1)
|
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point x(x > 0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order ... | 1 | print (input()+4)//5
|
There are two standard ways to represent a graph $G = (V, E)$, where $V$ is a set of vertices and $E$ is a set of edges; Adjacency list representation and Adjacency matrix representation.
An adjacency-list representation consists of an array $Adj[|V|]$ of $|V|$ lists, one for each vertex in $V$. For each $u \in V$, th... | 3 | n = int(input())
for i in range(n):
nums = list(map(int, input().split()))
ans = ['0'] * n
for j in nums[2:]:
ans[j-1] = '1'
print(' '.join(ans))
|
Adilbek's house is located on a street which can be represented as the OX axis. This street is really dark, so Adilbek wants to install some post lamps to illuminate it. Street has n positions to install lamps, they correspond to the integer numbers from 0 to n - 1 on the OX axis. However, some positions are blocked an... | 1 | get = lambda: [int(x) for x in raw_input().split()]
n, m, k = get()
block = get()
a = get()
can = [1] * n
for x in block:
can[x] = 0
last_can = [0] * n
last = -1
for i in range(n):
last_can[i] = i if can[i] else last
last = last_can[i]
ans = 10**13
if can[0]:
for i in range(k):
step ... |
All cities of Lineland are located on the Ox coordinate axis. Thus, each city is associated with its position xi β a coordinate on the Ox axis. No two cities are located at a single point.
Lineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another city (bec... | 1 | R = lambda: map(int, raw_input().split())
def min_max(pos, l):
temp1 = 0
temp2 = 0
if pos - 1 >= 0:
temp1 = l[pos] - l[pos - 1]
if pos + 1 <= len(l) - 1:
temp2 = l[pos + 1] - l[pos]
Min = 0
if temp1 != 0 and temp2 != 0:
Min = min(temp1, temp2)
else:
Min = te... |
It's hard times now. Today Petya needs to score 100 points on Informatics exam. The tasks seem easy to Petya, but he thinks he lacks time to finish them all, so he asks you to help with one..
There is a glob pattern in the statements (a string consisting of lowercase English letters, characters "?" and "*"). It is kno... | 1 | R=raw_input
g=set(R())
p=R()
def ok(a,b):
if '?'==a:
return b in g
return a==b
def go(s):
i,j=0,len(s)
u,v=0,len(p)
while u<v and p[u]!='*':
if not (i<j and ok(p[u],s[i])):
return 0
u+=1
i+=1
while u<v and p[v-1]!='*':
v-=1
if not (i<j and ok(p[v],s[j-1])):
return 0
j... |
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 | # cook your dish here
# code
# ___________________________________
# | |
# | |
# | _, _ _ ,_ |
# | .-'` / \'-'/ \ `'-. |
# | / | | | | \ |
# | ; \_ _/ \_ _/ ; ... |
When Igor K. was a freshman, his professor strictly urged him, as well as all other freshmen, to solve programming Olympiads. One day a problem called "Flags" from a website called Timmy's Online Judge caught his attention. In the problem one had to find the number of three-colored flags that would satisfy the conditio... | 1 | modu = 10 ** 9 + 7
def S(x):
if x == 0:
return 0
if x & 1:
return 11 * pow(3, x / 2, modu) - 7
else:
return 19 * pow(3, x / 2 - 1, modu) - 7
def T(x):
return (S(x) + S((x + 1) / 2)) * pow(2, modu - 2, modu) % modu
[l, r] = [int(x) for x in raw_input().split(' ')]
print (T(r) - T(l - 1) + modu) % modu
|
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... | 1 | pepene = int(raw_input())
if (((pepene % 2)==0) and (pepene > 2)):
print "YES"
else:
print "NO" |
On Bertown's main street n trees are growing, the tree number i has the height of ai meters (1 β€ i β€ n). By the arrival of the President of Berland these trees were decided to be changed so that their heights formed a beautiful sequence. This means that the heights of trees on ends (the 1st one and the n-th one) should... | 3 | n = int(input())
b = []
a = []
for i in range(100005):
b.append(0)
a.append(0)
s = input()
a +=list(map(int, s.strip().split()))
mid = (n+1)//2
for i in range(1,mid+1):
if a[i]-i >=0 :
b[a[i]-i]+=1
for i in range(mid+1,n+1):
if a[i]-(n-i+1)>=0:
b[a[i]-(n-i+1)]+=1
ans = 0
for i in b:
ans ... |
Polycarp is preparing the first programming contest for robots. There are n problems in it, and a lot of robots are going to participate in it. Each robot solving the problem i gets p_i points, and the score of each robot in the competition is calculated as the sum of p_i over all problems i solved by it. For each prob... | 3 | n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
cnta=0
cntb=0
for i in range(n):
if a[i]==1 and b[i]==0:
cnta+=1
elif a[i]==0 and b[i]==1:
cntb+=1
if cnta==0:
print(-1)
else:
print(int((cnta+cntb)/cnta))
|
Your task is to implement a double linked list.
Write a program which performs the following operations:
* insert x: insert an element with key x into the front of the list.
* delete x: delete the first element which has the key of x from the list. If there is not such element, you need not do anything.
* deleteFirst... | 3 | from collections import deque
n=int(input())
que=deque()
for i in range(n):
command=input()
if command=="deleteFirst":que.popleft()
elif command=="deleteLast":que.pop()
else:
x,y=command.split()
if x=="insert":que.appendleft(y)
else:
if y in que:que.remove(y)
print(... |
Allen has a LOT of money. He has n dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are 1, 5, 10, 20, 100. What is the minimum number of bills Allen could receive after withdrawing his entire balance?
Input
The first... | 3 | #codeforces_996A
n = int(input())
print(n//100+(n%100)//20+((n%100)%20)//10+(((n%100)%20)%10)//5+(((n%100)%20)%10)%5) |
ZS the Coder is coding on a crazy computer. If you don't type in a word for a c consecutive seconds, everything you typed disappear!
More formally, if you typed a word at second a and then the next word at second b, then if b - a β€ c, just the new word is appended to other words on the screen. If b - a > c, then ever... | 3 | n,c=map(int,input().split())
sum=1
words=list(map(int,input().split()))
for k in range(1,n):
if words[k]-words[k-1]<=c:
sum+=1
else:
sum=1
print(sum)
|
A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters Β«+Β» and Β«1Β» into this sequence. For example, sequences Β«(())()Β», Β«()Β» and Β«(()(()))Β» are regular, while Β«)(Β», Β«(()Β» and Β«(()))(Β» are not.
One day Johnny got bracket sequence. He decided to remove some... | 3 | s=input()
l=[]
c=0
for i in s:
if(l==[]):
if(i=='('):
l.append(i)
else:
if(i=='('):
l.append(i)
else:
l.pop()
c=c+2
print(c)
|
You've got a 5 Γ 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix:
1.... | 3 | full_matrix = []
for i in range(5):
i = input()
z = i.split(" ")
full_matrix = full_matrix + z
test = full_matrix.index("1")
result = 0
if test == 12:
print(result)
else:
while test != 12:
if 12 - test >= 5:
test = test + 5
result = result + 1
elif 12 - test <... |
The football season has just ended in Berland. According to the rules of Berland football, each match is played between two teams. The result of each match is either a draw, or a victory of one of the playing teams. If a team wins the match, it gets w points, and the opposing team gets 0 points. If the game results in ... | 3 | x = 0
y = 0
def gcd (a, b):
global x, y
if a == 0:
x = 0
y = 1
return b
d = gcd(b % a, a)
x, y = y - (b // a) * x, x
return d
n, p, w, d = map(int, input().split())
g = gcd(w, d)
if p % g != 0:
print(-1)
exit(0)
x *= p // g
y *= p // g
w //= g
d //= g
if y < 0:
l = -1
r = 10**80 + 3
wh... |
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n Γ n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good:
* Elements of the main diagonal.
* Elements of the secondary diagonal.
* Elements of the "middle" row β the row which has exac... | 3 | n = int(input())
matrix, s =[], 0
for _ in range(n):
row = [int(x) for x in input().split()]
matrix.append(row)
for i in range(n):
s += matrix[i][i] + matrix[i][n - 1 - i] + matrix[i][n // 2] + matrix[n // 2][i]
s -= matrix[n // 2][n // 2] * 3
print(s) |
You've got a 5 Γ 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix:
1.... | 3 | arr=[]
for i in range(5):
arr.append(list(map(int, input().split())))
for j in range(5):
for k in range(5):
if arr[j][k]==1:
r=abs(j-2)+abs(k-2)
break
print(r)
|
You are given a positive integer n, it is guaranteed that n is even (i.e. divisible by 2).
You want to construct the array a of length n such that:
* The first n/2 elements of a are even (divisible by 2);
* the second n/2 elements of a are odd (not divisible by 2);
* all elements of a are distinct and positi... | 3 | t = int(input())
out = ''
while t > 0:
t -= 1
n = int(input())
if (n // 2) % 2 == 1:
out += 'NO\n'
continue
e = set()
o = set()
s_e = 0
s_o = 0
for i in range(2, n + 1, 2):
e.add(i)
s_e += i
for i in range(1, n - 1, 2):
o.add(i)
s_o += ... |
Given are two integer sequences of N elements each: A_1,...,A_N and B_1,...,B_N. Determine if it is possible to do the following operation at most N-2 times (possibly zero) so that, for every integer i from 1 to N, A_i \leq B_i holds:
* Choose two distinct integers x and y between 1 and N (inclusive), and swap the val... | 3 | N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
BA = [(b, a) for (b, a) in zip(B, A)]
BA.sort()
B, A = list(map(list, zip(*BA))) # BA.T
AI = [(a, i) for (i, a) in enumerate(A)]
AI.sort()
C, P = list(map(list, zip(*AI))) # AI.T
def can_divide_cycle(P):
start = P[1]
ncy... |
Ehab loves number theory, but for some reason he hates the number x. Given an array a, find the length of its longest subarray such that the sum of its elements isn't divisible by x, or determine that such subarray doesn't exist.
An array a is a subarray of an array b if a can be obtained from b by deletion of several... | 1 | from sys import stdin, stdout
t = input()
inp = stdin.readlines()
out = []
ptr = 0
while ptr < len(inp):
n = int(inp[ptr].strip()); ptr += 1
a = map(int, inp[ptr].strip().split()); ptr += 1
ans = len(set(a))
out.append(str(ans))
stdout.write("\n".join(out))
|
You are given a string S consisting of digits between `1` and `9`, inclusive. You can insert the letter `+` into some of the positions (possibly none) between two letters in this string. Here, `+` must not occur consecutively after insertion.
All strings that can be obtained in this way can be evaluated as formulas.
... | 3 | s = input()
n = len(s)-1
ans = 0
for i in range(2**n):
tmp=0
for j in range(n):
if (i>>j)&1:
ans+=int(s[tmp:j+1])
tmp=j+1
ans+=int(s[tmp:])
print(ans) |
You are given a following process.
There is a platform with n columns. 1 Γ 1 squares are appearing one after another in some columns on this platform. If there are no squares in the column, a square will occupy the bottom row. Otherwise a square will appear at the top of the highest square of this column.
When all ... | 3 | m, n = [int(x) for x in input().split()]
cols = [int(x) for x in input().split()]
ans = 0
arr = [0]*m
for i in cols:
arr[i-1] += 1
flag = True
for index in range(m):
if arr[index] > 0:
pass
else:
flag = False
break
if flag:
ans += 1
... |
A string s of length n can be encrypted by the following algorithm:
* iterate over all divisors of n in decreasing order (i.e. from n to 1),
* for each divisor d, reverse the substring s[1 ... d] (i.e. the substring which starts at position 1 and ends at position d).
For example, the above algorithm applied t... | 1 | def get(dtype=int):
return dtype(raw_input())
def read_array(dtype=int):
return [dtype(a) for a in raw_input().split()]
n = get()
A = raw_input()
A = list(A)
for i in range(1, n + 1):
if n % i == 0:
A[0:i] = A[0:i][::-1]
print "".join(A)
|
You are given two integers n and m. Calculate the number of pairs of arrays (a, b) such that:
* the length of both arrays is equal to m;
* each element of each array is an integer between 1 and n (inclusive);
* a_i β€ b_i for any index i from 1 to m;
* array a is sorted in non-descending order;
* array b ... | 3 | # -*- coding: utf-8 -*-
import sys
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a... |
Theatre Square in the capital city of Berland has a rectangular shape with the size n Γ m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a Γ a.
What is the least number of flagstones needed to pave the Square? It'... | 3 | n,m,a = map(int, input().split())
if n%a != 0 :
a1 = n + a - n%a
else:
a1 = n
if m%a != 0 :
a2 = m + a - m%a
else:
a2 = m
ans = (a1*a2)//(a**2)
print(ans)
|
Ujan decided to make a new wooden roof for the house. He has n rectangular planks numbered from 1 to n. The i-th plank has size a_i Γ 1 (that is, the width is 1 and the height is a_i).
Now, Ujan wants to make a square roof. He will first choose some of the planks and place them side by side in some order. Then he will... | 3 | t = int(input())
for _ in range(t):
n = int(input())
a = sorted(map(int, input().split()))[::-1]
ans = 0
for i in range(n):
if a[i] > i:
ans = i
print(ans + 1) |
Farmer John has a farm that consists of n pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is... | 3 | def readline():
return map(int, input().split())
def solve():
n = int(input())
prev, *d = sorted(readline())
s = 0
for i, curr in enumerate(d, start=1):
prev, x = curr, curr - prev
s -= x * (i * (n-i) - 1)
print(s)
def main():
t = int(input())
for __ in range(t):
... |
Alice has a string s. She really likes the letter "a". She calls a string good if strictly more than half of the characters in that string are "a"s. For example "aaabb", "axaa" are good strings, and "baca", "awwwa", "" (empty string) are not.
Alice can erase some characters from her string s. She would like to know wh... | 3 | s=input()
l=[]
k=[]
d=[]
for i in s:
if i!='a':
l.append(i)
m=len(l)
e=s.count('a')
for i in range(e):
d.append('a')
if m>=e:
q=l[0:e-1]
t=len(q)
print(e+t)
else:
print(len(s))
|
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them.
Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain nu... | 1 | s = raw_input().strip()
sProper = ''
i = 0
count = 0
while(i!=len(s)):
if s[i:i+3] == "WUB":
count += 1
if i!=0 and count==1:
sProper += ' '
i += 3
else:
count = 0
sProper += s[i]
i += 1
print sProper
|
You have n gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The i-th gift consists of a_i candies and b_i oranges.
During one move, you can choose some gift 1 β€ i β€ n and do one of the following operations:
* eat exactly... | 3 | t = int(input())
for _ in range(t):
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
steps = 0
mA = min(a)
mB = min(b)
for i in range(n):
if a[i] > mA and b[i] > mB:
total_required = min(a[i] - mA, b[i] - mB)
a[i] -= to... |
Long time ago Alex created an interesting problem about parallelogram. The input data for this problem contained four integer points on the Cartesian plane, that defined the set of vertices of some non-degenerate (positive area) parallelogram. Points not necessary were given in the order of clockwise or counterclockwis... | 3 | a1,b1 = map(int, input().split())
a2,b2 = map(int, input().split())
a3,b3 = map(int, input().split())
print(3)
print(a1+a2-a3, b1+b2-b3)
print(-a1+a2+a3, -b1+b2+b3)
print(a1-a2+a3, b1-b2+b3) |
Let's call left cyclic shift of some string t_1 t_2 t_3 ... t_{n - 1} t_n as string t_2 t_3 ... t_{n - 1} t_n t_1.
Analogically, let's call right cyclic shift of string t as string t_n t_1 t_2 t_3 ... t_{n - 1}.
Let's say string t is good if its left cyclic shift is equal to its right cyclic shift.
You are given str... | 3 | import sys
# import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
# import time,random,resource
# sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
mod2 = 998244353
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,... |
You are given a binary string s consisting of n zeros and ones.
Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should no... | 3 | t = int(input())
for _ in range(t):
n = int(input())
s = input()
pos_0 = []
pos_1 = []
a = [0] * n
count = 1
for i in range(n):
if s[i] == '0':
if pos_1 == []:
pos_0.append(count)
a[i] = count
count += 1
else:
... |
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 | raw_input()
line = map(int, raw_input().split())
n = {1:0, 2:0, 3:0, 4:0}
for i in line:
n[i] += 1
ncar = n[4] + n[3]
if n[1] <= n[3]:
n[1] = 0
fix = n[2]%2
ncar += n[2]/2 + fix
else:
n[1] -= n[3]
fix = n[2]%2
ncar += n[2]/2 + fix
if fix:
if n[1] < 3:
n[1] = 0
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.