problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
Luke Skywalker gave Chewbacca an integer number x. Chewbacca isn't good at numbers but he loves inverting digits in them. Inverting digit t means replacing it with digit 9 - t.
Help Chewbacca to transform the initial number x to the minimum possible positive number by inverting some (possibly, zero) digits. The decim... | 3 | # number = list(input())
# inverted_number = ''
# for i in range(len(number)):
# if (9 - int(number[i])) < int(number[i]):
# if i == 0 and int(number[i]) == 9:
# inverted_number += '{}'.format('9')
# else:
# inverted_digit = 9 - int(number[i])
# inverted_number +... |
You are given a non-empty string s=s_1s_2... s_n, which consists only of lowercase Latin letters. Polycarp does not like a string if it contains at least one string "one" or at least one string "two" (or both at the same time) as a substring. In other words, Polycarp does not like the string s if there is an integer j ... | 3 | for _ in range(int(input())):
s=input();i=0;r=[]
while i<len(s):
if'twone'==s[i:i+5]:i+=3;r+=i,
if s[i:i+3] in('one','two'): r+=i+2,
i+=1
print(len(r),*r) |
The official capital and the cultural capital of Berland are connected by a single road running through n regions. Each region has a unique climate, so the i-th (1 ≤ i ≤ n) region has a stable temperature of ti degrees in summer.
This summer a group of m schoolchildren wants to get from the official capital to the cul... | 1 | n,m=map(int,raw_input().split())
res = 0
for t in range(n):
a,b,c,d=map(int,raw_input().split())
if a+1>b:
res+=d+c*m
continue
s=(m/(b-a))+(m%(b-a)!=0)
x=s*d
res+=min(x,d+c*m)
print res
|
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc.... | 3 | a=input()
b=input()
c=b[::-1]
if c==a:
print("YES")
else:
print("NO")
|
Given are integers A, B, and N.
Find the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N.
Here floor(t) denotes the greatest integer not greater than the real number t.
Constraints
* 1 ≤ A ≤ 10^{6}
* 1 ≤ B ≤ 10^{12}
* 1 ≤ N ≤ 10^{12}
* All values in input are i... | 3 | A,B,N=map(int,input().split())
k = min(B-1,N)
print(int(A*k/B)) |
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits.
Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has on... | 3 | year_str = input()
temp = 0
while True:
test = False
year_int = int(year_str) + 1
year_str = str(year_int)
for i in range(0,4):
for j in range(0,4):
if i == j:
continue
if year_str[i] == year_str[j]:
test = True
if test == False:
... |
John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3.
A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge.
John has been pa... | 1 |
def Cn2(n):
return n*(n-1)/2
def Cn3(n):
return n*(n-1)*(n-2)/6
def main():
k = input()
n = 3
while k >= Cn3(n+1):
n += 1
k -= Cn3(n)
ans = range(n)
while k > 0:
m = 2
while k >= Cn2(m+1):
m += 1
k -= Cn2(m)
ans.append(m)
siz... |
The preferred way to generate user login in Polygon is to concatenate a prefix of the user's first name and a prefix of their last name, in that order. Each prefix must be non-empty, and any of the prefixes can be the full name. Typically there are multiple possible logins for each person.
You are given the first and ... | 3 | a=input().split()
b=[]
for i in range(len(a[0])):
b.append(a[0][:i+1]+a[1][0])
b.sort()
print(b[0])
|
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... | 3 | from math import *
n = int(input())
s = list(map(int,input().split()))
l = (s[0]*s[1])//gcd(s[0],s[1])
g= gcd(s[0],s[1])
for i in s[2:]:
l= gcd(l,(i*g)//gcd(i,g))
g= gcd(g,i)
print(l) |
You are given three integers, A, B and C.
Among them, two are the same, but the remaining one is different from the rest.
For example, when A=5,B=7,C=5, A and C are the same, but B is different.
Find the one that is different from the rest among the given three integers.
Constraints
* -100 \leq A,B,C \leq 100
* A, B ... | 1 | a = raw_input().split()
if a[0] == a[1]:
print a[2]
elif a[0] == a[2]:
print a[1]
else:
print a[0] |
You are given an array a of length n.
You are also given a set of distinct positions p_1, p_2, ..., p_m, where 1 ≤ p_i < n. The position p_i means that you can swap elements a[p_i] and a[p_i + 1]. You can apply this operation any number of times for each of the given positions.
Your task is to determine if it is poss... | 3 | YES = 'YES'
NO = 'NO'
def solve(a,p):
bridge = [1]* (len(a)-1)
sorted_a = list(a)
sorted_a.sort()
for i in p:
bridge[i-1] = 0
# if bridge sum is zero return YES
if sum(bridge) == 0:
return YES
groups = []
temp_group = [a[0]]
for index,i in enumerate(bridge):
if i==0:
temp_grou... |
You have a list of numbers from 1 to n written from left to right on the blackboard.
You perform an algorithm consisting of several steps (steps are 1-indexed). On the i-th step you wipe the i-th number (considering only remaining numbers). You wipe the whole number (not one digit).
<image>
When there are less than ... | 3 | n = int(input())
while n!=0:
a,b = map(int,input().split())
print(2*b)
n-=1 |
Alice got many presents these days. So she decided to pack them into boxes and send them to her friends.
There are n kinds of presents. Presents of one kind are identical (i.e. there is no way to distinguish two gifts of the same kind). Presents of different kinds are different (i.e. that is, two gifts of different ki... | 3 | from sys import stdin
import math
n, m = list(map(int, stdin.readline().rstrip().split()))
def power(x, y, p) :
res = 1
x = x % p
while (y > 0) :
if ((y & 1) == 1) :
res = (res * x) % p
y = y >> 1
x = (x * x) % p
return res
c = 10**9 +7
s = p... |
Vasya has n burles. One bottle of Ber-Cola costs a burles and one Bars bar costs b burles. He can buy any non-negative integer number of bottles of Ber-Cola and any non-negative integer number of Bars bars.
Find out if it's possible to buy some amount of bottles of Ber-Cola and Bars bars and spend exactly n burles.
I... | 3 | n=int(input())
a=int(input())
b=int(input())
x=0
flag=0
while x<=n:
if (n-x)%b==0:
print('YES')
print(x//a,(n-x)//b)
flag=1
break
else:
x+=a
if flag==0:
print('NO')
|
Kostya likes Codeforces contests very much. However, he is very disappointed that his solutions are frequently hacked. That's why he decided to obfuscate (intentionally make less readable) his code before upcoming contest.
To obfuscate the code, Kostya first looks at the first variable name used in his program and rep... | 3 | if __name__ == "__main__":
obfuscation = list(input())
letters = list("abcdefghijklmnopqrstuvwxyz")
if len(obfuscation) == 1:
if obfuscation[0] == 'a':
print("YES")
else:
print("NO")
else:
while len(obfuscation) > 0:
if obfuscation[0] == lette... |
Snuke has two boards, each divided into a grid with N rows and N columns. For both of these boards, the square at the i-th row from the top and the j-th column from the left is called Square (i,j).
There is a lowercase English letter written in each square on the first board. The letter written in Square (i,j) is S_{i... | 3 | n = int(input())
s = [list(input()) for _ in range(n)]
res = 0
for b in range(n):
judge = True
d = [['']*n for _ in range(n)]
for i in range(n):
for j in range(n):
d[i][(j+b)%n] = s[i][j]
for i in range(n):
for j in range(n):
if d[i][j] != d[j][i]:
... |
There is a data which provides heights (in meter) of mountains. The data is only for ten mountains.
Write a program which prints heights of the top three mountains in descending order.
Constraints
0 ≤ height of mountain (integer) ≤ 10,000
Input
Height of mountain 1
Height of mountain 2
Height of mountain 3
.
.
He... | 1 | import sys
import operator
# l = sys.stdin.readline()
l= []
for i in xrange(10):
l.append(int(sys.stdin.readline()))
first = max(l)
print(first)
del l[l.index(first)]
first = max(l)
print(first)
del l[l.index(first)]
first = max(l)
print(first)
del l[l.index(first)] |
You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") a and b. Then you try to turn a into b using two types of operations:
* Write parity(a... | 3 | A = list(input())
B = list(input())
zA = A.count('1')
zA += zA & 1
if zA >= B.count('1'):
print("YES")
else:
print("NO") |
It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices.
It is known that the i-th contestant will eat si slices of pizza, and gain ai ... | 3 | n, S = 0, 0
s = []
a = []
b = []
class node:
def __init__(self, x, id):
self.x = x
self.id = id
return
def __lt__(self, p):
return self.x < p.x
c = []
i , f = 0, 0
ans, sum, a1, a2 = 0, 0, 0, 0
s1, s2 = 0, 0
line = input().split()
n, S = int(line[0]), int(line[1])
for i in rang... |
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like.
Now let's imagine a typical morning in your family. You haven't w... | 3 | input()
ls = sorted([int(x) for x in input().split()], reverse=True)
for i in range(len(ls)+1):
if sum(ls[0:i]) > sum(ls[i:]): break
print(i) |
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 | for _ in range(int(input())):
n=int(input())
lst=[int(i) for i in input().split()]
set1=set(lst)
if len(set1)==1:
print(n)
else:
print(1)
|
When preparing a tournament, Codeforces coordinators try treir best to make the first problem as easy as possible. This time the coordinator had chosen some problem and asked n people about their opinions. Each person answered whether this problem is easy or hard.
If at least one of these n people has answered that th... | 3 | n=int(input())
x=(list(input().split()))
for i in x:
if(i=='1'):
print('HARD')
break
else:
print('EASY') |
There are n models in the shop numbered from 1 to n, with sizes s_1, s_2, …, s_n.
Orac will buy some of the models and will arrange them in the order of increasing numbers (i.e. indices, but not sizes).
Orac thinks that the obtained arrangement is beatiful, if for any two adjacent models with indices i_j and i_{j+1} ... | 3 | #include <CodeforcesSoutions(contestID = "1350",problemID = "B").h>
"""
Author : thekushalghosh
Team : CodeDiggers
I prefer Python language over the C++ language :p :D
Visit my website : thekushalghosh.github.io
"""
import sys,math,cmath,time
start_time = time.time()
tt = 0
#################... |
Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by n streets along the Eastern direction and m streets across the Southern direction. Naturally, this city has nm intersections. At any intersection of i-th Eastern street and j-th Southern street there is a monument... | 3 | import sys
DBG = not True
DBG2 = not True
n,m = map(int, input().split())
rows = []
for i in range(n):
rows.append(list(map(int, input().split())))
cols = []
for j in range(m):
cols.append([])
for i in range(n):
cols[j].append(rows[i][j])
if DBG:
print(n)
print(m)
print(rows)
print(cols)
d... |
Due to the coronavirus pandemic, city authorities obligated citizens to keep a social distance. The mayor of the city Semyon wants to light up Gluharniki park so that people could see each other even at night to keep the social distance.
The park is a rectangular table with n rows and m columns, where the cells of the... | 3 | import math
for _ in range(int(input())):
n,m = map(int,input().split())
p = m*n
if p % 2== 0:
print(p//2)
else:
print((p//2)+ 1)
|
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.
Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divi... | 3 | n = int(input())
len = n//2 - 1
print(len+1)
for i in range(len):
print(2)
if n%2!=0:
print(3)
else:
print(2)
|
There are n districts in the town, the i-th district belongs to the a_i-th bandit gang. Initially, no districts are connected to each other.
You are the mayor of the city and want to build n-1 two-way roads to connect all districts (two districts can be connected directly or through other connected districts).
If two... | 3 | import os
import sys
import math
import collections
import itertools
#from bisect import bisect_left as bl #c++ lowerbound bl(array,element)
#from bisect import bisect_right as br #c++ upperbound br(array,element)
def get_int(): return int(input())
def get_ints(): return map(int, input().sp... |
Let us define the FizzBuzz sequence a_1,a_2,... as follows:
* If both 3 and 5 divides i, a_i=\mbox{FizzBuzz}.
* If the above does not hold but 3 divides i, a_i=\mbox{Fizz}.
* If none of the above holds but 5 divides i, a_i=\mbox{Buzz}.
* If none of the above holds, a_i=i.
Find the sum of all numbers among the first... | 3 | N=int(input())
k=0
for i in range(N):
j=i+1
if (j%3!=0)and(j%5!=0):
k=k+j
print(k)
|
While sailing on a boat, Inessa noticed a beautiful water lily flower above the lake's surface. She came closer and it turned out that the lily was exactly H centimeters above the water surface. Inessa grabbed the flower and sailed the distance of L centimeters. Exactly at this point the flower touched the water surfac... | 3 | a=[float(x) for x in input().split()]
print((a[1]*a[1]-a[0]*a[0])/(2*a[0])) |
Little Petya very much likes playing with little Masha. Recently he has received a game called "Zero-One" as a gift from his mother. Petya immediately offered Masha to play the game with him.
Before the very beginning of the game several cards are lain out on a table in one line from the left to the right. Each card c... | 3 | # The first player always removes the 1s, if possible.
# The second player always removes the 0s if possible.
res = input()
possible = []
zero = res.count('0')
one = res.count('1')
question = res.count('?')
if (len(res) - 2) // 2 + 2 <= zero + question:
possible.append('00')
# The optimal play never removes th... |
Taro and Jiro will play the following game against each other.
Initially, they are given a sequence a = (a_1, a_2, \ldots, a_N). Until a becomes empty, the two players perform the following operation alternately, starting from Taro:
* Remove the element at the beginning or the end of a. The player earns x points, whe... | 3 | N=int(input())
a=list(map(int,input().split()))
ans=[[0 for e in range(N+1)] for f in range(N+1)]
for j in range(1,N+1):
ans[j][1]=a[j-1]
if N>1:
for i in range(2,N+1):
for j in range(1,N+2-i):
ans[j][i]=max(a[j-1]-ans[j+1][i-1],a[j+i-2]-ans[j][i-1])
print(ans[1][N])
|
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 | def fun(a,n):
m=a[0]
for i in range(1,n):
if a[i]-m>1:
return "NO"
m=a[i]
return "YES"
t=int(input())
for i in range(t):
n=int(input())
a=sorted(list(map(int,input().split())))
print(fun(a,n))
|
Marcin is a coach in his university. There are n students who want to attend a training camp. Marcin is a smart coach, so he wants to send only the students that can work calmly with each other.
Let's focus on the students. They are indexed with integers from 1 to n. Each of them can be described with two integers a_i... | 1 | n = 0
a = []
b = []
n = input()
a = map(int,raw_input().split())
b = map(int,raw_input().split())
pairset = set()
maxima = 0
for i in xrange(0,n):
if a[i] in pairset:
continue
for j in xrange(i+1,n):
if a[i] == a[j]:
pairset.add(a[i])
break
for i in xrange(0,n):
for aj in pairset:
if a[i] | aj == aj:... |
Write a program which performs the following operations to a binary search tree $T$ by adding delete operation to B: Binary Search Tree II.
* insert $k$: Insert a node containing $k$ as key into $T$.
* find $k$: Report whether $T$ has a node containing $k$.
* delete $k$: Delete a node containing $k$.
* print: Print t... | 3 |
class Node:
def __init__(self, key):
self.parent = None
self.right = None
self.left = None
self.key = key
def insert(root, z):
y = None
x = None
if root != None:
x = root
while x != None:
y = x
if z.key < x.key:
x = x.le... |
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 | n=int(input())
i=input()
i=i.lower()
#print(i)
s=set(i)
if len(s)==26:
print('YES')
else:
print('NO') |
Vasya is writing an operating system shell, and it should have commands for working with directories. To begin with, he decided to go with just two commands: cd (change the current directory) and pwd (display the current directory).
Directories in Vasya's operating system form a traditional hierarchical tree structure... | 3 | def pwd(dir):
if len(dic):
print('/' + '/'.join(dic) + '/')
else:
print('/')
def cd(com,dic):
com = com[3:]
ds = com.split('/')
if com[0] == '/':
dic = []
for d in ds:
if d == '..':
dic.pop()
elif len(d):
dic.append(d)
return dic
t = int(input())
dic = []
for _ in range(t):
com = input()
... |
Polycarp plays "Game 23". Initially he has a number n and his goal is to transform it to m. In one move, he can multiply n by 2 or multiply n by 3. He can perform any number of moves.
Print the number of moves needed to transform n to m. Print -1 if it is impossible to do so.
It is easy to prove that any way to trans... | 3 | #JMD
#Nagendra Jha-4096
import sys
import math
#import fractions
#import numpy
###File Operations###
fileoperation=0
if(fileoperation):
orig_stdout = sys.stdout
orig_stdin = sys.stdin
inputfile = open('W:/Competitive Programming/input.txt', 'r')
outputfile = open('W:/Competitive Programming/output... |
Consider a table of size n × m, initially fully white. Rows are numbered 1 through n from top to bottom, columns 1 through m from left to right. Some square inside the table with odd side length was painted black. Find the center of this square.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 115) — th... | 1 | n,m = map(int, raw_input().split())
a=[]
for i in range(n):
b=raw_input()
a.append(b)
p=0
k=0
for i in range(n):
for j in range(m):
if a[i][j]=='B' and p==0:
k=i
l=j
p=1
if a[k][j]=='B' and p==1:
o=j
if p==1:... |
Bran and his older sister Arya are from the same house. Bran like candies so much, so Arya is going to give him some Candies.
At first, Arya and Bran have 0 Candies. There are n days, at the i-th day, Arya finds ai candies in a box, that is given by the Many-Faced God. Every day she can give Bran at most 8 of her cand... | 3 | n, k = map(int,input().split())
a = list(map(int,input().split()))
Day = Candies = 0
for i in range(n):
Candies+=a[i]
if Candies <= 8:
k-=Candies
Candies = 0
else:
Candies-=8
k-=8
Day+=1
if k <= 0:
break
print(Day if k <= 0 else -1)
|
Greg has an array a = a1, a2, ..., an and m operations. Each operation looks as: li, ri, di, (1 ≤ li ≤ ri ≤ n). To apply operation i to the array means to increase all array elements with numbers li, li + 1, ..., ri by value di.
Greg wrote down k queries on a piece of paper. Each query has the following form: xi, yi, ... | 1 | from itertools import *
class RangeAdder:
def __init__(self, A):
self.A = [A[0]] + [A[i+1]-A[i] for i in xrange(len(A)-1)] + [-A[-1]]
def add(self, l, r, d):
self.A[l-1] += d
self.A[r ] -= d
return self
def recompose(self):
l = [self.A[0]]
for a in islice(self.A,1,len(self.A)-1):
... |
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... | 3 | v = "aeiouyAEIOUY"
q = input().strip()
a=[" "]
for c in q:
#print(c)
if c in v :
continue
if c.isupper():
a.append(c.lower())
continue
a.append(c)
print(".".join(a).strip())
|
Write a program which reads a word W and a text T, and prints the number of word W which appears in text T
T consists of string Ti separated by space characters and newlines. Count the number of Ti which equals to W. The word and text are case insensitive.
Constraints
* The length of W ≤ 10
* W consists of lower cas... | 3 | w = input().lower()
total = 0
while True:
s = input()
if s == "END_OF_TEXT":break
s = s.lower().split()
total += s.count(w)
print(total)
|
You are given a function f written in some basic language. The function accepts an integer value, which is immediately written into some variable x. x is an integer variable and can be assigned values from 0 to 2^{32}-1. The function contains three types of commands:
* for n — for loop;
* end — every command betw... | 3 | def catch_overflow(o):
stack = [1]
output = 0
for i in range(o):
n = input()
if n[:3] == 'for':
stack.append(min(2**32,stack[-1]*int(n[4:])))
elif n == 'end':
stack.pop()
else:
output += stack[-1]
if output >= 2**32:
... |
A card pyramid of height 1 is constructed by resting two cards against each other. For h>1, a card pyramid of height h is constructed by placing a card pyramid of height h-1 onto a base. A base consists of h pyramids of height 1, and h-1 cards on top. For example, card pyramids of heights 1, 2, and 3 look as follows:
... | 3 | def f(h):
return int((h / 2) * (3 * h + 1))
def how_many(n):
if n == 2:
return 1
elif n == 1:
return 0
for i in range(1, 26000):
fi = f(i)
if fi > n:
high = i - 2
less = f(i - 1)
total = n // less
n -= (n // less) * less
... |
The only king stands on the standard chess board. You are given his position in format "cd", where c is the column from 'a' to 'h' and d is the row from '1' to '8'. Find the number of moves permitted for the king.
Check the king's moves here https://en.wikipedia.org/wiki/King_(chess).
<image> King moves from the posi... | 3 | cb = input()
c = cb[0]
b = cb[1]
moves = 8
if b == '1' or b == '8':
moves -= 3
if c == 'a' or c == 'h':
moves -= 3
if moves == 2:
moves = 3
print(moves) |
Tomorrow is a difficult day for Polycarp: he has to attend a lectures and b practical classes at the university! Since Polycarp is a diligent student, he is going to attend all of them.
While preparing for the university, Polycarp wonders whether he can take enough writing implements to write all of the lectures and d... | 3 | from math import ceil
ct = int(input())
for c in range(ct):
a, b, c, d, k = [int(i) for i in input().split()]
r1 = ceil(a/c)
r2 = ceil(b/d)
if r1 + r2 <= k:
print(r1, r2)
else:
print(-1)
|
Two bears are playing tic-tac-toe via mail. It's boring for them to play usual tic-tac-toe game, so they are a playing modified version of this game. Here are its rules.
The game is played on the following field.
<image>
Players are making moves by turns. At first move a player can put his chip in any cell of any sm... | 1 | #Abhigyan Khaund - syl
# n = int(raw_input())
# v1,v2,v3,vm = map(int, raw_input().split())
c = [[],[],[],[],[],[],[],[],[],[]]
for i in range(3):
k = raw_input().split()
c[1].append(list(k[0]))
c[2].append(list(k[1]))
c[3].append(list(k[2]))
raw_input()
for i in range(3):
k = raw_input().split()
c[4].append(lis... |
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
You have to answer t independent test cases.
Input
The first line of the input co... | 3 | t=int(input())
for i in range(t):
x,y=map(int,input().split())
print((y-x%y)%y)
|
Sanket being a stud, wants to gift chocolates on "Chocolate Day" to a girl. He has N chocolates of different types. The chocolates are numbered from 1 to N. There are K types of chocolates, numbered from 1 to K. Also, there are infinite chocolates of each type. But, the girl is very demanding. She wants all chocolates... | 1 | from collections import Counter
for _ in range(int(raw_input())):
n, k = map(int, raw_input().split())
a = map(int, raw_input().split())
m = max(Counter(a).values())
print n - m |
We have a board with H horizontal rows and W vertical columns of squares. There is a bishop at the top-left square on this board. How many squares can this bishop reach by zero or more movements?
Here the bishop can only move diagonally. More formally, the bishop can move from the square at the r_1-th row (from the to... | 3 | h,w=map(int,input().split())
print(int(((h*w/2,w*(h//2)+(w+1)//2)[h&1],1)[h==1 or w==1])) |
You are given two integers a and b.
In one move, you can choose some integer k from 1 to 10 and add it to a or subtract it from a. In other words, you choose an integer k ∈ [1; 10] and perform a := a + k or a := a - k. You may use different values of k in different moves.
Your task is to find the minimum number of mo... | 3 | myList = []
for _ in range(int(input())):
a, b = list(map(int, input().split()))
if a == b:
myList.append(0)
else:
if abs(a - b) <= 10:
myList.append(1)
else:
q = abs(a - b) // 10
if (a - b) % 10 != 0:
myList.append(q + 1)
... |
The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her n students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often oddl... | 1 | import sys
def solve(n, m, data):
data.sort()
res = []
for i in xrange(m-n+1):
res.append(data[i+n-1] - data[i])
return min(res)
n, m = map(int, sys.stdin.readline().split())
data = map(int, sys.stdin.readline().split())
print str(solve(n, m, data))
|
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 | n = input()
c = 0
for i in xrange(n):
o = raw_input()
if(o.find("++") >= 0):
c+=1
elif(o.find("--") >= 0):
c-=1
print c; |
Alice is playing with some stones.
Now there are three numbered heaps of stones. The first of them contains a stones, the second of them contains b stones and the third of them contains c stones.
Each time she can do one of two operations:
1. take one stone from the first heap and two stones from the second heap (... | 3 | import sys,math,string,bisect
input=sys.stdin.readline
from collections import deque,defaultdict
L=lambda : list(map(int,input().split()))
Ls=lambda : list(input().split())
M=lambda : map(int,input().split())
I=lambda :int(input())
t=I()
for i in range(t):
stones=0
temp=L()
while(temp[1]>0 and temp[2]>1):
... |
Despite his bad reputation, Captain Flint is a friendly person (at least, friendly to animals). Now Captain Flint is searching worthy sailors to join his new crew (solely for peaceful purposes). A sailor is considered as worthy if he can solve Flint's task.
Recently, out of blue Captain Flint has been interested in ma... | 3 | t=int(input())
for _ in range(t):
n=int(input())
if(n>30):
if((n-30) not in [6,10,14]):
print('YES')
print(6,10,14,n-30)
else:
if(n==31):
print('NO')
else:
print('YES')
print('6','10','15',n-31)
else:
print('NO') |
The ABC number of a string T is the number of triples of integers (i, j, k) that satisfy all of the following conditions:
* 1 ≤ i < j < k ≤ |T| (|T| is the length of T.)
* T_i = `A` (T_i is the i-th character of T from the beginning.)
* T_j = `B`
* T_k = `C`
For example, when T = `ABCBC`, there are three triples of... | 3 | mo=10**9+7
s=input()
n=len(s)
dp=[[0]*(1+n) for i in range(3)]
cc=0
for i in range(n):
c=s[i]
if c=='A':
da,db,dc,dd=1,0,0,1
elif c=='B':
da,db,dc,dd=0,1,0,1
elif c=='C':
da,db,dc,dd=0,0,1,1
elif c=='?':
da,db,dc,dd=1,1,1,3
dp[0][i+1]=dp[0][i]*dd+da*pow(3... |
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 | a=5*[0]
for i in range(5):
a[i]=input().split()
for i in range(5):
for t in range(5):
if a[i][t]=='1':
#print(i,t)
v=abs(i-2)+abs(t-2)
print(v)
exit()
|
Nian is a monster which lives deep in the oceans. Once a year, it shows up on the land, devouring livestock and even people. In order to keep the monster away, people fill their villages with red colour, light, and cracking noise, all of which frighten the monster out of coming.
Little Tommy has n lanterns and Big Ban... | 3 | n, m = map(int, input().split())
a1 = [int(x) for x in input().split()]
a2 = [int(x) for x in input().split()]
a1.sort()
a2.sort()
ans1 = -1e18
ans2 = -1e18
for i in range(len(a1) - 1):
for j in a2:
ans1 = max(ans1, a1[i] * j)
for i in range(1, len(a1)):
for j in a2:
ans2 = max(ans2, a1[i] * ... |
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.
For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two ... | 3 | def main():
n = int(input())
if n % 2:
print(9, n - 9)
else:
print(8, n - 8)
if __name__ == "__main__":
main() |
Ashish and Vivek play a game on a matrix consisting of n rows and m columns, where they take turns claiming cells. Unclaimed cells are represented by 0, while claimed cells are represented by 1. The initial state of the matrix is given. There can be some claimed cells in the initial state.
In each turn, a player must ... | 3 | t = int(input().strip())
while t > 0:
n, m = map(int, input().strip().split())
rows = [0 for i in range(0, n)]
columns = [0 for j in range(0, m)]
for i in range(0, n):
y = [int(x) for x in input().split()]
for j in range(0, m):
if (y[j]):
rows[i] = 1
... |
Innokentiy decides to change the password in the social net "Contact!", but he is too lazy to invent a new password by himself. That is why he needs your help.
Innokentiy decides that new password should satisfy the following conditions:
* the length of the password must be equal to n,
* the password should con... | 3 | n, k = [int(x) for x in input().split()]
kc = k
alfabeto = list('abcdefghijklmnopqrstuvwxyz')
passw = ''
i = 0
while kc > 0:
passw += alfabeto[i]
kc -= 1
i += 1
i = 0
while len(passw) < n:
passw += passw[i]
i += 1
print(passw)
|
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... | 3 | s=input()
t=['a','e','u','i','o','y', 'A', 'E', 'U', "I", "O", "Y"]
for i in range (len(s)):
if s[i] not in t:
print(".",end="")
print(s[i].lower(),end="")
|
Find the minimum area of a square land on which you can place two identical rectangular a × b houses. The sides of the houses should be parallel to the sides of the desired square land.
Formally,
* You are given two identical rectangles with side lengths a and b (1 ≤ a, b ≤ 100) — positive integers (you are given ... | 3 | from collections import Counter
import math
import sys
from bisect import bisect,bisect_left,bisect_right
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def mod()... |
Today, Mezo is playing a game. Zoma, a character in that game, is initially at position x = 0. Mezo starts sending n commands to Zoma. There are two possible commands:
* 'L' (Left) sets the position x: =x - 1;
* 'R' (Right) sets the position x: =x + 1.
Unfortunately, Mezo's controller malfunctions sometimes. ... | 3 | n = int(input())
s = input()
neg = s.count('L')
pos = s.count('R')
print(neg+pos+1) |
Alicia has an array, a_1, a_2, …, a_n, of non-negative integers. For each 1 ≤ i ≤ n, she has found a non-negative integer x_i = max(0, a_1, …, a_{i-1}). Note that for i=1, x_i = 0.
For example, if Alicia had the array a = \{0, 1, 2, 0, 3\}, then x = \{0, 0, 1, 2, 2\}.
Then, she calculated an array, b_1, b_2, …, b_n: ... | 3 | n = int(input())
b = list(map(int , input().split() ))
a = list()
a.append(b[0])
a.append(b[1]+b[0])
m = max(a[0] , a[1])
for i in range(2,n) :
a.append(b[i] + m )
m = max(m ,a[i])
for i in range(n) :
print(a[i] , end= " ") |
Takahashi made N problems for competitive programming. The problems are numbered 1 to N, and the difficulty of Problem i is represented as an integer d_i (the higher, the harder).
He is dividing the problems into two categories by choosing an integer K, as follows:
* A problem with difficulty K or higher will be for ... | 3 | n = int(input())
l = [int(i) for i in input().split()]
l.sort()
print(l[n//2]-l[n//2-1]) |
During the quarantine, Sicromoft has more free time to create the new functions in "Celex-2021". The developers made a new function GAZ-GIZ, which infinitely fills an infinite table to the right and down from the upper left corner as follows:
<image> The cell with coordinates (x, y) is at the intersection of x-th row ... | 3 | for _ in range(int(input())):
x1, y1, x2, y2 = [int(x) for x in input().split()]
print(((x2 - x1) * (y2- y1)) + 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... | 3 | def main():
(n, m) = map(int, input().split(' '))
d = 0
while n > 0:
if d % m == 0:
n += 1
d += 1
n -= 1
return d - 1
print(main())
|
Takahashi, who works at DISCO, is standing before an iron bar. The bar has N-1 notches, which divide the bar into N sections. The i-th section from the left has a length of A_i millimeters.
Takahashi wanted to choose a notch and cut the bar at that point into two parts with the same length. However, this may not be po... | 3 | n=int(input())
a=list(map(int,input().split()))
sa=float("inf")
wa1=0
wa2=sum(a)
for i in range(n-1):
wa1+=a[i]
wa2-=a[i]
temp=abs(wa1-wa2)
sa=min(sa,temp)
print(sa) |
The professor is conducting a course on Discrete Mathematics to a class of N students. He is angry at the lack of their discipline, and he decides to cancel the class if there are fewer than K students present after the class starts.
Given the arrival time of each student, your task is to find out if the class gets ca... | 1 | for _ in range(input()):
n,k=map(int,raw_input().split())
a=map(int,raw_input().split())
c=0
for i in range(n):
if(a[i]<=0):
c+=1
if(c>=k):
print "NO"
else:
print "YES" |
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 | def main():
removed = 0
n = int(input())
stones = input()
previous = stones[0]
for i in range(1, n):
current = stones[i]
if(current == previous):
removed = removed + 1
previous = current
return removed
pri... |
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc.... | 3 | lang = list(input())
lang.reverse()
lang = ''.join(lang)
a_lang = input()
if a_lang == lang:
print('YES')
else:
print('NO') |
Once little Vasya read an article in a magazine on how to make beautiful handmade garland from colored paper. Vasya immediately went to the store and bought n colored sheets of paper, the area of each sheet is 1 square meter.
The garland must consist of exactly m pieces of colored paper of arbitrary area, each piece s... | 3 | import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
from math import *
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
f... |
Two people are playing a game with a string s, consisting of lowercase latin letters.
On a player's turn, he should choose two consecutive equal letters in the string and delete them.
For example, if the string is equal to "xaax" than there is only one possible turn: delete "aa", so the string will become "xx". A p... | 3 | b=input("")
a=[char for char in b]
sum=0
x=0
while(x<len(a)-1):
if(a[x]==a[x+1]):
sum+=1
a.pop(x)
a.pop(x)
if(x>0):
x=x-1
else:
x+=1
if(sum%2==0) :
print("No")
else:
print("Yes") |
A group of university students wants to get to the top of a mountain to have a picnic there. For that they decided to use a cableway.
A cableway is represented by some cablecars, hanged onto some cable stations by a cable. A cable is scrolled cyclically between the first and the last cable stations (the first of them ... | 3 | r,g,b=map(int,input().split())
kr,kg,kb=r//2+r%2,g//2+g%2,b//2+b%2
print(max((kr-1)*3+30,(kg-1)*3+31,(kb-1)*3+32))
|
There is a hotel with the following accommodation fee:
* X yen (the currency of Japan) per night, for the first K nights
* Y yen per night, for the (K+1)-th and subsequent nights
Tak is staying at this hotel for N consecutive nights. Find his total accommodation fee.
Constraints
* 1 \leq N, K \leq 10000
* 1 \leq ... | 3 | n,k,x,y = [int(input()) for _ in range(4)]
print(n*x-(x-y)*(max(0, n-k)))
|
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.
The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe... | 3 | s = input()
l = []
for i in s:
r = s.split("+")
num = []
for i in r:
x = int(i,10)
num.append(x)
num.sort()
str_num = []
for i in num:
str_num.append(str(i))
print("+".join(str_num))
|
Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to th... | 3 | a = input()
a = a.split(" ")
a = list(a)
b = set(a)
c = 4 - len(b)
print(c)
|
One day Vasya got hold of information on the Martian dollar course in bourles for the next n days. The buying prices and the selling prices for one dollar on day i are the same and are equal to ai. Vasya has b bourles. He can buy a certain number of dollars and then sell it no more than once in n days. According to Mar... | 3 | from sys import stdin, stdout
n, money = map(int, stdin.readline().split())
values = list(map(int, stdin.readline().split()))
ans = 0
for i in range(n):
ans = max(ans, (money // values[i]) * max(values[i:]) + money % values[i])
stdout.write(str(ans)) |
You might have remembered Theatre square from the [problem 1A](https://codeforces.com/problemset/problem/1/A). Now it's finally getting repaved.
The square still has a rectangular shape of n × m meters. However, the picture is about to get more complicated now. Let a_{i,j} be the j-th square in the i-th row of the pav... | 3 | import sys
input = sys.stdin.readline
I = lambda : list(map(int,input().split()))
t,=I()
for _ in range(t):
n,m,x,y = I()
an=0
for i in range(n):
g = input()
j=0
while j<m:
if g[j]=='.' and ( j!=m-1 and g[j+1]=='.'):
an+=min(2*x,y);j+=1
elif g[j]=='.':
an+=x
j+=1
print(an)
|
Let s be some string consisting of symbols "0" or "1". Let's call a string t a substring of string s, if there exists such number 1 ≤ l ≤ |s| - |t| + 1 that t = s_l s_{l+1} … s_{l + |t| - 1}. Let's call a substring t of string s unique, if there exist only one such l.
For example, let s = "1010111". A string t = "010... | 3 | n, k = map(int, input().split())
if k == 1:
print('1'+'0'*(n-1))
else:
t = (n-k)//2
a = ''.join(['0'+'1'*t]*(n//(t+1)))
if len(a) < n:
a += '0'
print(a+'1'*(n-len(a)))
|
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution.... | 3 | n = int(input())
count = 0
for i in range(n):
line = input()
a,b,c = [int(i) for i in line.split()]
if a + b + c >= 2:
count += 1
print(count) |
According to rules of the Berland fashion, a jacket should be fastened by all the buttons except only one, but not necessarily it should be the last one. Also if the jacket has only one button, it should be fastened, so the jacket will not swinging open.
You are given a jacket with n buttons. Determine if it is fasten... | 3 | def R(): return map(int, input().split())
def I(): return int(input())
def S(): return str(input())
def L(): return list(R())
from collections import Counter
import math
import sys
from itertools import permutations
import bisect
n=I()
a=L()
cnt=sum([a[i]==0 for i in range(n)])
print(['NO','YES'][(cnt==1 and n>... |
You are given an array of integers a_1,a_2,…,a_n. Find the maximum possible value of a_ia_ja_ka_la_t among all five indices (i, j, k, l, t) (i<j<k<l<t).
Input
The input consists of multiple test cases. The first line contains an integer t (1≤ t≤ 2 ⋅ 10^4) — the number of test cases. The description of the test cases ... | 3 | for _ in range(int(input())):
n = int(input())
a = sorted(list(map(int, input().split())))
print(max(a[n - 1] * a[n - 2] * a[n - 3] * a[n - 4] * a[n - 5], a[n - 1] * a[n - 2] * a[n - 3] * a[0] * a[1],
a[n - 1] * a[0] * a[1] * a[2] * a[3]))
|
Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.
Rules of the game are very simple: at first number of rounds n is defined. I... | 1 |
# coding: utf-8
# In[1]:
n = input()
m = 0;
k = 0;
for i in range(n):
a, b = raw_input().split(' ')
a = int(a)
b = int(b)
if a > b:
m += 1
elif b > a:
k +=1
if m > k:
print 'Mishka'
elif k > m:
print 'Chris'
else:
print 'Friendship is magic!^^'
# In[ ]:
|
There is a rectangular room, covered with square tiles. Each tile is colored either red or black. A man is standing on a black tile. From a tile, he can move to one of four adjacent tiles. But he can't move on red tiles, he can move only on black tiles.
Write a program to count the number of black tiles which he can r... | 3 | while True:
w, h = map(int, input().split())
if w == 0:
break
a = []
for i in range(h):
t = list(input())
a.append(t)
if '@' in t:
x = i
y = t.index('@')
stk = [[x, y]]
c = 1
while True:
if stk == []:
break
x... |
Little Petya loves training spiders. Petya has a board n × m in size. Each cell of the board initially has a spider sitting on it. After one second Petya chooses a certain action for each spider, and all of them humbly perform its commands. There are 5 possible commands: to stay idle or to move from current cell to som... | 1 |
def f(n,m):
if n<m:return f(m,n)
if m==1:
return (n+2)/3
if m==2:
return (n+2)/2
if m==3:
return (3*n+4)/4
if m==4:
if n==5 or n==6 or n==9:return n+1
else:return n
if m==5:
if n==7:return (6*n+6)/5
else:return (6*n+8)/5
if m==6:
if n%7==1:return (10*n+10)/7
else:retu... |
So, the New Year holidays are over. Santa Claus and his colleagues can take a rest and have guests at last. When two "New Year and Christmas Men" meet, thear assistants cut out of cardboard the letters from the guest's name and the host's name in honor of this event. Then the hung the letters above the main entrance. O... | 3 | s1 = input()
s2 = input()
s = input()
s3 = s1+s2
d_s = {}
d_s3 = {}
s_s3 = set(s3)
s_s = set(s)
for si in s_s3:
a = s3.count(si)
d_s3[si] = a
for si in s_s:
a = s.count(si)
d_s[si] = a
if d_s == d_s3:
print('YES')
else:
print('NO') |
There is an image with a height of H pixels and a width of W pixels. Each of the pixels is represented by either `.` or `*`. The character representing the pixel at the i-th row from the top and the j-th column from the left, is denoted by C_{i,j}.
Extend this image vertically so that its height is doubled. That is, p... | 3 | a, b = (int(_) for _ in input().split())
for i in range(a):
x = input()
print(x)
print(x)
|
Eighth-grader Vova is on duty today in the class. After classes, he went into the office to wash the board, and found on it the number n. He asked what is this number and the teacher of mathematics Inna Petrovna answered Vova that n is the answer to the arithmetic task for first-graders. In the textbook, a certain posi... | 3 | n = int(input())
ans = [i for i in range(max(0, n - 100), n) if i + sum(int(j) for j in str(i)) == n]
print(len(ans), '\n' + '\n'.join(map(str, ans))) |
There are n boys and m girls attending a theatre club. To set a play "The Big Bang Theory", they need to choose a group containing exactly t actors containing no less than 4 boys and no less than one girl. How many ways are there to choose a group? Of course, the variants that only differ in the composition of the trou... | 3 | import math
n,m,troupe = map(int,input().split(" "))
boys = 4
girls = troupe - 4
total = 0
if girls > m:
diff = girls - m
girls = m
boys += diff
calculated = []
while(girls > 0):
if boys > n:
break
if girls > m:
girls -= 1
boys += 1
continue
#print("boys",boys)
#print("girls",girls)
if not calculat... |
There are N integers, A_1, A_2, ..., A_N, written on a blackboard.
We will repeat the following operation N-1 times so that we have only one integer on the blackboard.
* Choose two integers x and y on the blackboard and erase these two integers. Then, write a new integer x-y.
Find the maximum possible value of the... | 3 | N = int(input())
A = list(map(int, input().split()))
# 全部+,-は無理だが、それ以外は任意に符号を決められる
plus = []
minus = []
for a in A:
if a >= 0:
plus.append(a)
else:
minus.append(a)
plus.sort()
plus.reverse()
minus.sort()
if len(plus) == 0:
plus.append(minus.pop())
if len(minus) == 0:
minus.append(plus.pop())
print(sum... |
Anton likes to play chess, and so does his friend Danik.
Once they have played n games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie.
Now Anton wonders, who won more games, he or Danik? Help him determine this.
Input
The first line of the input contains a... | 3 | n = int(input())
game = input()
A = game.count('A')
D = game.count('D')
if A > D:
print('Anton')
elif A < D:
print('Danik')
else:
print('Friendship')
|
There are N people numbered 1 to N. Each of them is either an honest person whose testimonies are always correct or an unkind person whose testimonies may be correct or not.
Person i gives A_i testimonies. The j-th testimony by Person i is represented by two integers x_{ij} and y_{ij}. If y_{ij} = 1, the testimony say... | 3 | n=int(input())
l=[[] for i in range(n)]
for i in range(n):
a=int(input())
for j in range(a):
x,y=map(int,input().split())
l[i].append([x-1,y])
ans=0
for i in range(2**n):
z=str(format(i,('0'+str(n)+'b')))
f=1
for k in range(n):
if f:
if int(z[k]):
for m in l[k]:
if z[m[0]]!... |
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.
Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character... | 3 | alf = 'abcdefghijklmnopqrstuvwxyz'
s = input().split()[0]
cur = 'a'
povs = 0
for i in range(len(s)):
povs += min (abs(alf.find(s[i]) - alf.find(cur)), min(abs (- alf.find(s[i]) + 26 + alf.find(cur)), alf.find(s[i]) + 26 - alf.find(cur)))
cur = s[i]
print (povs) |
This winter is so cold in Nvodsk! A group of n friends decided to buy k bottles of a soft drink called "Take-It-Light" to warm up a bit. Each bottle has l milliliters of the drink. Also they bought c limes and cut each of them into d slices. After that they found p grams of salt.
To make a toast, each friend needs nl ... | 3 | # Soft Drinking
n,k,l,c,d,p,nl,np=map(int,input().split())
x=min((k*l)//nl,c*d,p//np)
print(x//n) |
A string is called a k-string if it can be represented as k concatenated copies of some string. For example, the string "aabaabaabaab" is at the same time a 1-string, a 2-string and a 4-string, but it is not a 3-string, a 5-string, or a 6-string and so on. Obviously any string is a 1-string.
You are given a string s, ... | 3 | from collections import Counter
k = int(input())
s = input()
countdict = Counter(s)
chars = [i for i in countdict]
lens = [countdict[i] for i in countdict]
possible = True
base = ''
for i in range(len(lens)):
if lens[i] % k != 0:
possible = False
break
base = base + chars[i]*(lens[i]//k)
if not possible:
pr... |
There is a sequence X of length N, where every element is initially 0. Let X_i denote the i-th element of X.
You are given a sequence A of length N. The i-th element of A is A_i. Determine if we can make X equal to A by repeating the operation below. If we can, find the minimum number of operations required.
* Choose... | 3 | import sys
read = sys.stdin.read
N, *A = map(int, read().split())
if A[0] != 0:
print(-1)
exit()
answer = 0
A.append(0)
for i in range(N):
if A[i + 1] - A[i] > 1:
print(-1)
exit()
if A[i + 1] <= A[i]:
answer += A[i]
print(answer) |
We have a large square grid with H rows and W columns. Iroha is now standing in the top-left cell. She will repeat going right or down to the adjacent cell, until she reaches the bottom-right cell.
However, she cannot enter the cells in the intersection of the bottom A rows and the leftmost B columns. (That is, there ... | 3 | H, W, A, B = map(int, input().split())
def cmb(n, r, mod):
if ( r<0 or r>n ):
return 0
r = min(r, n-r)
return g1[n] * g2[r] * g2[n-r] % mod
mod = 10**9+7
N = max(H,W)*2
g1 = [1, 1]
g2 = [1, 1]
inverse = [0, 1]
for i in range(2, N+1):
g1.append((g1[-1] * i) % mod)
inverse.append((-inverse[m... |
On a chessboard with a width of n and a height of n, rows are numbered from bottom to top from 1 to n, columns are numbered from left to right from 1 to n. Therefore, for each cell of the chessboard, you can assign the coordinates (r,c), where r is the number of the row, and c is the number of the column.
The white ki... | 3 | n = int(input())
x, y = map(int, input().split())
z = max(x, y) - 1
m = n - min(x, y)
if z <= m:
print('White')
else:
print('Black') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.