problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
Input
The input contains a single integer a (1 ≤ a ≤ 30).
Output
Output a single integer.
Example
Input
3
Output
27 | 1 | print [4, 22, 27, 58, 85, 94, 121, 166, 202, 265, 274, 319, 346, 355, 378, 382, 391, 438, 454, 483, 517, 526, 535, 562, 576, 588, 627, 634, 636, 645, 648, 654, 663, 666, 690, 706, 728, 729, 762, 778, 825, 852, 861, 895, 913, 915, 922, 958, 985, 1086, 1111, 1165][int(raw_input())-1] |
Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.
Gildong lo... | 3 |
def add(i,s):
if(s==""):
return s+i
else:
half=len(s)//2
return s[:half]+i+s[half:]
def valid(i):
p1=0;p2=len(i)-1
while(p1<=p2):
if(i[p1]!=i[p2]):
return False
p1+=1
p2-=1
return True
def largepalin(d,m):
le=0
string=""
t=Tru... |
Let's denote a k-step ladder as the following structure: exactly k + 2 wooden planks, of which
* two planks of length at least k+1 — the base of the ladder;
* k planks of length at least 1 — the steps of the ladder;
Note that neither the base planks, nor the steps planks are required to be equal.
For example... | 3 | def ladder():
numberOfTimes = int(input());
for i in range(numberOfTimes):
count = 0
planks = int(input());
sizes = input().split();
for j in range(len(sizes)):
sizes[j] = int(sizes[j])
sizes.sort()
leftLeg = sizes[planks-1]-1
rightLeg = sizes[... |
The USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of n haybale piles on the farm. The i-th pile contains a_i haybales.
However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an a... | 3 | import sys
def fastio():
from io import StringIO
from atexit import register
global input
sys.stdin = StringIO(sys.stdin.read())
input = lambda : sys.stdin.readline().rstrip('\r\n')
sys.stdout = StringIO()
register(lambda : sys.__stdout__.write(sys.stdout.getvalue()))
fastio()
def debug(*va... |
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." — an excerpt from contest rules.
A total of n participants took part in the contest (n ≥ k), and you already know their scores. Calculate how many ... | 3 | n, k = map(int, input().split())
a = list(map(int, input().split()))
b = a[k-1]
kol = 0
for i in range(0,len(a)):
if a[i] >= b and a[i] != 0:
kol += 1
print(kol) |
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.
Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, seco... | 3 | t = int(input())
s = "I hate "
p = ["that I love ", "that I hate "]
for i in range(t-1):
s += p[i%2]
print(s+"it") |
Xenia lives in a city that has n houses built along the main ringroad. The ringroad houses are numbered 1 through n in the clockwise order. The ringroad traffic is one way and also is clockwise.
Xenia has recently moved into the ringroad house number 1. As a result, she's got m things to do. In order to complete the i... | 3 | while True:
try:
n,m=map(int,input().split())
l=input().split()
s=0
for i in range(m):
if i==0:
s=s+int(l[0])-1
else:
l[i]=int(l[i])
l[i-1]=int(l[i-1])
if l[i]>=l[i-1]:
s=s+l[i]-l[i-1]
else:
... |
You have n students under your control and you have to compose exactly two teams consisting of some subset of your students. Each student had his own skill, the i-th student skill is denoted by an integer a_i (different students can have the same skills).
So, about the teams. Firstly, these two teams should have the s... | 3 | a =int(input())
for _ in range(a):
x = int(input())
li = [0]*(x+1)
li1 = list(map(int, input().split()))
for i in li1:
li[i]+=1
b = max(li)
j= len(set(li1))
if j==b: j-=1
print(min(b,j))
|
You are given two segments [l_1; r_1] and [l_2; r_2] on the x-axis. It is guaranteed that l_1 < r_1 and l_2 < r_2. Segments may intersect, overlap or even coincide with each other.
<image> The example of two segments on the x-axis.
Your problem is to find two integers a and b such that l_1 ≤ a ≤ r_1, l_2 ≤ b ≤ r_2 an... | 3 | n = int(input())
for i in range(n):
a, b, c, d = map(int, input().split(" "))
if a != d:
print(a, d)
else:
print(b, c)
|
There are n kids, numbered from 1 to n, dancing in a circle around the Christmas tree. Let's enumerate them in a clockwise direction as p_1, p_2, ..., p_n (all these numbers are from 1 to n and are distinct, so p is a permutation). Let the next kid for a kid p_i be kid p_{i + 1} if i < n and p_1 otherwise. After the da... | 3 | from sys import stdin
input=stdin.readline
n=int(input())
a=[[] for i in range(n+1)]
for i in range(1,n+1):
a[i]=list(map(int,input().split()))
p=[0]*(n+1)
p[1]=1
a1,a2=a[1]
if a1 in a[a2]:
p[2]=a2
p[3]=a1
else:
p[2]=a1
p[3]=a2
for i in range(4,n+1):
p[i]=list(set(a[p[i-2]])&set(a[p[i-1]]))[0]
print(*p[1:]) |
You have a string s consisting of n characters. Each character is either 0 or 1.
You can perform operations on the string. Each operation consists of two steps:
1. select an integer i from 1 to the length of the string s, then delete the character s_i (the string length gets reduced by 1, the indices of characters ... | 3 | import sys
from collections import defaultdict
input=sys.stdin.readline
from math import ceil
for _ in range(int(input())):
n=int(input())
s=list(input().strip())
if len(set(s))==1:
print(1)
continue
lis=[1]
for i in range(n-1):
if s[i]==s[i+1]:
lis[-1]+=1
... |
wHAT DO WE NEED cAPS LOCK FOR?
Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage.
Let's consider that a word has been typed with the Caps lock key accidentall... | 3 |
# A. cAPS lOCK
# time limit per test0.5 second
# memory limit per test256 megabytes
# inputstandard input
# outputstandard output
# wHAT DO WE NEED cAPS LOCK FOR?
# Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it lead... |
Happy new year! The year 2020 is also known as Year Gyeongja (경자년, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.
There are two sequences of n strings s_1, s_2, s_3, …, s_{n} and m strings t_1, t_2, t_3, …, t_{m}. ... | 3 | n,m = input().split()
n = int(n)
m = int(m)
a =[a for a in input().split()]
b =[b for b in input().split()]
output = []
q = int(input())
for i in range(q):
num1 = num2 = int(input())
num1 %= n
if num1 == 0:
num1 = n
astring = a[num1-1]
num2 %= m
if num2 == 0:
num2 = m
bstri... |
Drazil has many friends. Some of them are happy and some of them are unhappy. Drazil wants to make all his friends become happy. So he invented the following plan.
There are n boys and m girls among his friends. Let's number them from 0 to n - 1 and 0 to m - 1 separately. In i-th day, Drazil invites <image>-th boy and... | 3 | import math
string = input()
numbers = string.split()
a, b = int(numbers[0]), int(numbers[1])
happyboys = list(map(int, input().split()))
del happyboys[0]
happygirls = list(map(int, input().split()))
del happygirls[0]
boys = [0 for x in range(a)]
girls = [0 for x in range(b)]
for x in happyboys:
boys[x] = 1
for x i... |
Adilbek was assigned to a special project. For Adilbek it means that he has n days to run a special program and provide its results. But there is a problem: the program needs to run for d days to calculate the results.
Fortunately, Adilbek can optimize the program. If he spends x (x is a non-negative integer) days opt... | 3 | import math
t = int(input())
results = []
for k in range(t):
nums = input().split()
n = int(nums[0])
d = int(nums[1])
result = 'NO'
for x in range(n):
total = x + math.ceil(d / (x + 1))
if total <= n:
result = 'YES'
break
results.append(result)
fo... |
Alena has successfully passed the entrance exams to the university and is now looking forward to start studying.
One two-hour lesson at the Russian university is traditionally called a pair, it lasts for two academic hours (an academic hour is equal to 45 minutes).
The University works in such a way that every day it... | 1 | #!/bin/sh
# -*- coding: utf-8 -*-
''''which python2 >/dev/null && exec python2 "$0" "$@" # '''
''''which python >/dev/null && exec python "$0" "$@" # '''
# raw_input
n = int(raw_input())
a = map(int, raw_input().split())
ans = a[0]
for i in xrange(1, n):
if a[i] == 1:
ans += 1
else:
if a... |
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.
Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with number... | 3 | import sys
import math
import bisect
from sys import stdin, stdout
from math import gcd, floor, sqrt, log
from collections import defaultdict as dd
from bisect import bisect_left as bl, bisect_right as br
from collections import Counter
#sys.setrecursionlimit(100000000)
inp = lambda: int(input())
strng = lambda: input(... |
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 ... | 3 | n=int(input())
if n%4==0 or n%7==0:
print("YES")
elif n%44==0 or n%47==0 or n%74==0 or n%77==0:
print("YES")
elif n%444==0 or n%447==0 or n%474==0 or n%477==0 or n%744==0 or n%747==0 or n%774==0 or n%777==0:
print("YES")
else:
print("NO")
|
Once upon a time a little frog whose name was Vasya decided to travel around his home swamp. Overall there are n mounds on the swamp, located on one line. The distance between the neighboring mounds is one meter. Vasya wants to visit all the mounds in one day; besides, he wants to visit each one exactly once. For that ... | 1 | t=[]
a=[x+1 for x in range(input())]
for x in zip(a,reversed(a)): t+=[x[0],x[1]]
print ' '.join(map(str,t[:len(a)]))
|
Today the kindergarten has a new group of n kids who need to be seated at the dinner table. The chairs at the table are numbered from 1 to 4n. Two kids can't sit on the same chair. It is known that two kids who sit on chairs with numbers a and b (a ≠ b) will indulge if:
1. gcd(a, b) = 1 or,
2. a divides b or b d... | 1 | #####################################
import atexit, io, sys
buffer = io.BytesIO()
sys.stdout = buffer
@atexit.register
def write(): sys.__stdout__.write(buffer.getvalue())
#####################################
for u in range(int(raw_input())):
n = int(raw_input())
for v in range(2*n, 4*n, 2):
print v,... |
Gennady owns a small hotel in the countryside where he lives a peaceful life. He loves to take long walks, watch sunsets and play cards with tourists staying in his hotel. His favorite game is called "Mau-Mau".
To play Mau-Mau, you need a pack of 52 cards. Each card has a suit (Diamonds — D, Clubs — C, Spades — S, or ... | 3 | A = input()
B = input().split()
for a in B :
if a[0]==A[0] or a[1]==A[1]:
print("YES")
break
else :
print("NO") |
You are given an array a of n integers, where n is odd. You can make the following operation with it:
* Choose one of the elements of the array (for example a_i) and increase it by 1 (that is, replace it with a_i + 1).
You want to make the median of the array the largest possible using at most k operations.
The... | 3 | n,k = [int(a) for a in input().split()]
a= list(map(int, input().split()))
m = n//2
a.sort()
l = 1
r = int(2e9)
while l != r:
mid = (l + r + 1) // 2
tmp = 0
for i in range(m,n):
if mid - a[i] > 0:
tmp += (mid - a[i])
if tmp > k:
r = mid - 1
if tmp <= k:
... |
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()
n = int(n)
for i in range(n):
string = input()
if len(string) > 10:
print(string[0] + str(len(string)-2) + string[len(string)-1])
else:
print(string)
|
Write a program which reads a rectangle and a circle, and determines whether the circle is arranged inside the rectangle. As shown in the following figures, the upper right coordinate $(W, H)$ of the rectangle and the central coordinate $(x, y)$ and radius $r$ of the circle are given.
Circle inside a rectangle
Cons... | 3 | w,h,x,y,r = [int(s) for s in input().split(' ')]
if r<=x and x<=w-r and r<=y and y<=h-r:
print('Yes')
else:
print('No') |
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 | from itertools import *
numbers="9876543210"
x=input()
l= len(x)
st= 1 if x[0]=='9' else 0
y=len( x)- st
minx=x
for assignment in product([0,1], repeat=y):
x2=""
if st==1:
x2+=x[0]
for i in range(st,len(x)):
x2+=numbers[int(x[i])] if assignment[i-st]==1 else x[i]
minx=min(x2,minx)
p... |
You are given three words s_1, s_2 and s_3, each composed of lowercase English letters, with spaces in between. Print the acronym formed from the uppercased initial letters of the words.
Constraints
* s_1, s_2 and s_3 are composed of lowercase English letters.
* 1 ≤ |s_i| ≤ 10 (1≤i≤3)
Input
Input is given from Stan... | 1 | #coding:utf-8
if __name__ == "__main__":
s1, s2, s3 = raw_input().split(" ")
print s1[0].upper() + s2[0].upper() + s3[0].upper()
|
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 | string = input().lower()
vowels = ['a','e','i','o','u','y']
newWord = [""]
for i in range(0,len(string)):
if string[i] in vowels:
pass
else:
newWord.append("."+ string[i])
print(*newWord,sep ="")
|
Arkady's morning seemed to be straight of his nightmare. He overslept through the whole morning and, still half-asleep, got into the tram that arrived the first. Some time after, leaving the tram, he realized that he was not sure about the line number of the tram he was in.
During his ride, Arkady woke up several time... | 3 | n=int(input())
hash=[0]*(101)
a=[int(x) for x in input().split()]
a.pop(0)
ans=a.copy()
for i in range(1,n):
a=list(ans)
b=[int(x) for x in input().split()]
ans.clear()
b.pop(0)
for j in range(len(b)):
for k in range(len(a)):
if(a[k]==b[j]):
ans.append(a[k])
for i... |
Captain Flint and his crew keep heading to a savage shore of Byteland for several months already, drinking rum and telling stories. In such moments uncle Bogdan often remembers his nephew Denis. Today, he has told a story about how Denis helped him to come up with an interesting problem and asked the crew to solve it.
... | 3 | t=int(input())
for you in range(t):
n=int(input())
z=(3*n)//4
print(z*'9',end="")
print((n-z)*'8') |
Petr wants to make a calendar for current month. For this purpose he draws a table in which columns correspond to weeks (a week is seven consequent days from Monday to Sunday), rows correspond to weekdays, and cells contain dates. For example, a calendar for January 2017 should look like on the picture:
<image>
Petr ... | 3 |
dayCount = [0 , 31 , 28 , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 , 31]
m, d = map(int, input().split())
d = d - 1
Ans = 1;
for i in range(dayCount[m]) :
if d == 7:
d = 0
Ans = Ans + 1
d = d + 1
print( Ans ) |
Chandu's girlfriend loves arrays that are sorted in non-increasing order. Today is her birthday. Chandu wants to give her some sorted arrays on her birthday. But the shop has only unsorted arrays. So, Chandu bought T unsorted arrays and is trying to sort them. But, he doesn't have much time to sort the arrays manually... | 1 | def bubbleSort(array, length):
for i in range(length-1):
for j in range(length-1-i):
if(array[j+1] > array[j]):
array[j+1], array[j] = array[j], array[j+1]
def merge(array, start, mid, end):
p = start
q = mid + 1
aux = []
#print "start = " + str(start)
#print... |
Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.
Reliable sources have informed the financier Anton of some information about the exchange rate of... | 1 | def py_1():
a = raw_input()
b = list(a)
blen = len(b)
mini = -1
c = int(b[-1])
for i in xrange(blen):
tmp = int(b[i])
if tmp%2 == 0 and tmp < c:
mini = i
break
if mini == -1:
i = blen - 1
while i >= 0:
tmp = int(b[i])
if tmp%2 == 0:
mini = i
break
i -= 1
if mini == -1:
print min... |
You're given an array a of length 2n. Is it possible to reorder it in such way so that the sum of the first n elements isn't equal to the sum of the last n elements?
Input
The first line contains an integer n (1 ≤ n ≤ 1000), where 2n is the number of elements in the array a.
The second line contains 2n space-separat... | 3 | n = int(input())
ar = sorted([int(i) for i in input().split()])
si = 0
sf = 0
for i in range(n):
si+=ar[i]
sf+=ar[(2*n)-1-i]
if(si != sf):
print(" ".join([str(i) for i in ar]))
else:
print(-1)
|
Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers a, b, c on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting e... | 3 | x=int(input())
y=int(input())
z=int(input())
print(max((x*y*z),(x+y+z),((x+y)*z),x+(y*z),((x*y)+z),(x*(y+z))))
|
problem
Hanako is playing with n (4 ≤ n ≤ 10) cards side by side. Each card has one integer between 1 and 99. Hanako chose k cards (2 ≤ k ≤ 4) from these cards and arranged them in a horizontal row to make an integer. How many kinds of integers can Hanako make in total?
For example, consider that you are given five c... | 3 | def s():
from itertools import permutations as P
for e in iter(input,'0'):
n,k=int(e),int(input())
C=[input()for _ in[0]*n]
print(len(set(''.join(s)for s in P(C,k))))
if'__main__'==__name__:s()
|
A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay i·k dollars for the i-th banana).
He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas?
Input
The first lin... | 3 | p=input()
word=p.split(" ")
a = [0,1,2]
count=0
for i in word:
a[count]=int(i)
count+=1
w=a[2]
k=a[0]
n=a[1]
cost=int((w*(w+1))/2)
cost=cost*k
if cost<n:
print("0")
else:
print(cost-n)
|
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 | import math
import sys
xy=[]
for i in range(3):
xy.append(list(map(int,input().split())))
print(3)
v=[[xy[2][0]-xy[1][0],xy[2][1]-xy[1][1]],
[xy[0][0]-xy[2][0],xy[0][1]-xy[2][1]],
[xy[1][0]-xy[0][0],xy[1][1]-xy[0][1]]]
for i in range(3):
print(xy[i][0]+v[i][0],xy[i][1]+v[i][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 | # cook your dish here
s=input()
a=""
for _ in s:
if _.lower() in ("a","e","i","o","u","y"):
continue
else:
a += "." + _.lower()
print(a)
|
There is a grid of square cells with H horizontal rows and W vertical columns. The cell at the i-th row and the j-th column will be denoted as Cell (i, j).
In Cell (i, j), a_{ij} coins are placed.
You can perform the following operation any number of times:
Operation: Choose a cell that was not chosen before and con... | 3 | H, W = map(int, input().split())
A = [list(map(int, input().split())) for _ in range(H)]
ans = []
for h in range(H - 1):
for w in range(W):
if A[h][w] % 2 == 1:
A[h][w] -= 1
A[h + 1][w] += 1
ans.append((h + 1, w + 1, h + 2, w + 1))
for w in range(W - 1):
if A[H - 1][... |
There are n kids, numbered from 1 to n, dancing in a circle around the Christmas tree. Let's enumerate them in a clockwise direction as p_1, p_2, ..., p_n (all these numbers are from 1 to n and are distinct, so p is a permutation). Let the next kid for a kid p_i be kid p_{i + 1} if i < n and p_1 otherwise. After the da... | 3 | N=int(input())
a=[]
for j in range(N):
a.append([])
for i in range(N):
n,m=map(int,input().split())
a[i].append(n)
a[i].append(m)
d=dict()
for j in range(1,N+1):
d[j]=0
c=[]
c.append(1)
d[1]=1
n=a[0][0]
m=a[0][1]
d[n]=1
d[m]=1
if n in a[m-1]:
c.append(m)
c.append(n)
elif m in a[n-1]:
c.a... |
For a positive integer n let's define a function f:
f(n) = - 1 + 2 - 3 + .. + ( - 1)nn
Your task is to calculate f(n) for a given integer n.
Input
The single line contains the positive integer n (1 ≤ n ≤ 1015).
Output
Print f(n) in a single line.
Examples
Input
4
Output
2
Input
5
Output
-3
Note
f(4)... | 3 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 9 22:59:49 2020
@author: jion
"""
n = int(input())
if n % 2 == 0:
print(n//2)
else:
print(n//2-n) |
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given n numbers finds one that is di... | 3 | # 4
# http://codeforces.com/problemset/problem/25/A
input();l=[int(x)%2 for x in input().split()]
print(l.index(sum(l)==1)+1) |
Polycarp found n segments on the street. A segment with the index i is described by two integers l_i and r_i — coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them.
Polycarp believes that a set of k segments is go... | 3 | import bisect
t=int(input())
for _ in range(t):
segments=[]
left=[]
right=[]
n=int(input())
for a_ in range(n):
l,r=map(int,input().split())
segments.append((l,r))
left.append(l)
right.append(r)
if(n==1):
print(0)
continue
left.sort()
right... |
HQ9+ is a joke programming language which has only four one-character instructions:
* "H" prints "Hello, World!",
* "Q" prints the source code of the program itself,
* "9" prints the lyrics of "99 Bottles of Beer" song,
* "+" increments the value stored in the internal accumulator.
Instructions "H" and "Q"... | 3 | a=input()
k=list(a)
y=len(k)
i=0
b=0
c=0
for i in range(y):
if(k[i]=='H' or k[i]=='Q' or k[i]=='9'):
b=b+1
else:
c=c+1
if(b>0):
print("YES")
else:
print("NO") |
You are given an integer n. In one move, you can either multiply n by two or divide n by 6 (if it is divisible by 6 without the remainder).
Your task is to find the minimum number of moves needed to obtain 1 from n or determine if it's impossible to do that.
You have to answer t independent test cases.
Input
The fi... | 3 | t=int(input())
for x in range(t):
y=int(input())
c=0
f=0
if y==1:
print('0')
continue
while(y!=1):
if y%6==0:
y=y//6
c+=1
elif y%3==0:
y=y*2
c+=1
else:
print('-1')
f=1
break
if f!=1:
print(c)
|
A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay i·k dollars for the i-th banana).
He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas?
Input
The first lin... | 3 | k,n,w=list(map(int,input().split()))
s=k
for i in range(2,w+1):
s=s+(i*k)
if(s<=n):
print("0")
else:
print(s-n)
|
Berland Football Cup starts really soon! Commentators from all over the world come to the event.
Organizers have already built n commentary boxes. m regional delegations will come to the Cup. Every delegation should get the same number of the commentary boxes. If any box is left unoccupied then the delegations will be... | 3 | n, m, a, b = [int(i) for i in input().split()]
print(min(n % m * b, (m - n % m) * a))
|
You like playing chess tournaments online.
In your last tournament you played n games. For the sake of this problem, each chess game is either won or lost (no draws). When you lose a game you get 0 points. When you win you get 1 or 2 points: if you have won also the previous game you get 2 points, otherwise you get 1 ... | 3 | import sys
import math as m
def fi():
return sys.stdin.readline()
if __name__ == '__main__':
for _ in range (int(fi())):
n,k = map(int, fi().split())
s = list(fi())
s.pop()
p = 0
q = 0
flag = 0
ans = 0
prev = 'L'
l = []
c = 0
for i in range (n):
if s[i] == 'W' and prev == 'L' :
ans +=1
... |
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob.
Right now, Limak and Bob weigh a and b respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight.
Limak eats a lot and his weight is tripled after every year, while Bob's weight... | 3 | l, b = map(int, input().split())
zero = 0
for i in range(b):
if l <= b:
l *= 3 ; b *= 2 ; zero += 1
print(zero)
|
A palindrome is a string t which reads the same backward as forward (formally, t[i] = t[|t| + 1 - i] for all i ∈ [1, |t|]). Here |t| denotes the length of a string t. For example, the strings 010, 1001 and 0 are palindromes.
You have n binary strings s_1, s_2, ..., s_n (each s_i consists of zeroes and/or ones). You ca... | 3 | # Author Name: Ajay Meena
# Codeforce : https://codeforces.com/profile/majay1638
import sys
import math
import bisect
import heapq
from bisect import bisect_right
from sys import stdin, stdout
# -------------- INPUT FUNCTIONS ------------------
def get_ints_in_variables(): return map(
int, sys.stdin.readline().s... |
Ilya lives in a beautiful city of Chordalsk.
There are n houses on the street Ilya lives, they are numerated from 1 to n from left to right; the distance between every two neighboring houses is equal to 1 unit. The neighboring houses are 1 and 2, 2 and 3, ..., n-1 and n. The houses n and 1 are not neighboring.
The ho... | 3 | """
n=int(z())
for _ in range(int(z())):
x=int(z())
l=list(map(int,z().split()))
n=int(z())
l=sorted(list(map(int,z().split())))[::-1]
a,b=map(int,z().split())
l=set(map(int,z().split()))
led=(6,2,5,5,4,5,6,3,7,6)
vowel={'a':0,'e':0,'i':0,'o':0,'u':0}
color4=["G", "GB", "YGB", "YGBI", "OYGBI" ,"OY... |
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().split("+")
s.sort()
for i in range(len(s)):
print(s[i],end = "")
if i != len(s)-1:
print("+",end = "") |
Lee just became Master in Codeforces, and so, he went out to buy some gifts for his friends. He bought n integers, now it's time to distribute them between his friends rationally...
Lee has n integers a_1, a_2, …, a_n in his backpack and he has k friends. Lee would like to distribute all integers in his backpack betwe... | 3 | for i in range(int(input())):
n,k=map(int,input().split())
g=list(map(int,input().split()))
f=list(map(int,input().split()))
g.sort(reverse=True)
f.sort(reverse=True)
pos1=f.count(1)
sum1=0
sum1+=2*sum(g[:pos1])
rear=n-1
t=pos1
for i in range(k-t):
sum1+=g[pos1]+g[rea... |
You are given positive integers X and Y. If there exists a positive integer not greater than 10^{18} that is a multiple of X but not a multiple of Y, choose one such integer and print it. If it does not exist, print -1.
Constraints
* 1 ≤ X,Y ≤ 10^9
* X and Y are integers.
Input
Input is given from Standard Input in... | 3 | import sys
input = sys.stdin.readline
x, y = map(int, input().split())
if x%y == 0:
ans = -1
else:
ans = x
print(ans) |
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 | mygroups = raw_input()
kids = raw_input()
kids = kids.split()
cars = 0
my4 = 0
my3 = 0
my2 = 0
my1 = 0
for i in kids:
if i == '4':
my4 += 1
elif i == '3':
my3 += 1
elif i == '2':
my2 += 1
else:
my1 += 1
cars += my4
cars += my3
my1 -= my3
if my2 % 2 == 0:
cars += my2... |
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 = input()
if s[0].islower():
t = s[0].upper() + s[1:]
print(t)
else:
print(s) |
Overlooking the captivating blend of myriads of vernal hues, Arkady the painter lays out a long, long canvas.
Arkady has a sufficiently large amount of paint of three colours: cyan, magenta, and yellow. On the one-dimensional canvas split into n consecutive segments, each segment needs to be painted in one of the colo... | 3 | n = int(input())
arr = list(input())
cnt = 0
def dfs(idx):
global cnt
for i in range(len(arr)-1):
if arr[i] == arr[i+1] and arr[i] != '?':
return
if idx == len(arr):
cnt += 1
if cnt == 2:
print("Yes")
exit(0)
return
if arr[i... |
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 | def possible_locations(moves):
return len(moves) + 1
useless = int(input())
movement = list(input())
print(useless + 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 | x = int(input())
y = input()
c = 0
sum = 0
while c < len(y):
sum = sum + int(y[c])
c += 2
if sum > 0:
print("HARD")
else:
print("EASY") |
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 | n = int(input())
li = list(map(int,input().split()))
li.sort(reverse = True)
total = 0
#print(li)
for i in range(len(li)):
total+=li[i]
l1 = []
for i in range(1,len(li)+1):
s = 0
for j in range(i):
s+=li[j]
#print(i,j,s)
if s>total-s:
l1.append(i)
... |
A competitive eater, Alice is scheduling some practices for an eating contest on a magical calendar. The calendar is unusual because a week contains not necessarily 7 days!
In detail, she can choose any integer k which satisfies 1 ≤ k ≤ r, and set k days as the number of days in a week.
Alice is going to paint some n... | 3 | t = int(input())
for _ in range(t):
n, r = map(int, input().split())
if n > r:
ans = r*(r+1)//2
else:
ans = 1 + n*(n-1)//2
print(ans)
|
You are given three integers x, y and n. Your task is to find the maximum integer k such that 0 ≤ k ≤ n that k mod x = y, where mod is modulo operation. Many programming languages use percent operator % to implement it.
In other words, with given x, y and n you need to find the maximum possible integer from 0 to n tha... | 3 | count = int(input())
import cmath
a = []
for i in range(0, count):
x, y, n = map(int, input().split())
count = int((n - y) / x)
a.append(count * x + y)
print(*a) |
PolandBall is a young, clever Ball. He is interested in prime numbers. He has stated a following hypothesis: "There exists such a positive integer n that for each positive integer m number n·m + 1 is a prime number".
Unfortunately, PolandBall is not experienced yet and doesn't know that his hypothesis is incorrect. Co... | 3 | n=int(input())
if n<=998:
print((int)(n+2))
else:
print((int)(n-2)) |
Recently, Norge found a string s = s_1 s_2 … s_n consisting of n lowercase Latin letters. As an exercise to improve his typing speed, he decided to type all substrings of the string s. Yes, all (n (n + 1))/(2) of them!
A substring of s is a non-empty string x = s[a … b] = s_{a} s_{a + 1} … s_{b} (1 ≤ a ≤ b ≤ n). For e... | 3 | #------------------------------what is this I don't know....just makes my mess faster--------------------------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = By... |
You are given two strings a and b consisting of lowercase English letters, both of length n. The characters of both strings have indices from 1 to n, inclusive.
You are allowed to do the following changes:
* Choose any index i (1 ≤ i ≤ n) and swap characters a_i and b_i;
* Choose any index i (1 ≤ i ≤ n) and sw... | 3 | from collections import Counter
n = int(input())
a = input()
b = input()
pre = 0
for i in range(n//2):
a1 = [a[i], a[n-i-1]]
b1 = [b[i], b[n-i-1]]
tot = len(Counter(a1+b1))
if(tot == 1):
pre+=0
if(tot == 2):
pre+=abs(len(Counter(a1))-len(Counter(b1)))
if(tot == 3):
if len... |
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 | import io
import sys
import math
def inverse(a, m):
u = 0
v = 1
while a != 0:
t = m // a
m -= t * a
a, m = m, a
u -= t * v
u, v = v, u
assert m == 1
return u
def main():
with sys.stdin as f:
n, p, w, d = map(int, f.readline().split())
g =... |
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.
The language is that peculiar as it has exactly one variable, called x. Also, there are two operations:
* Operation ++ increases the value of variable x by 1.
* Operation -- decreases the value of variable x by 1.... | 3 | n = int(input())
ans = 0
for i in range(n):
inp = input()
if inp == "++X" or inp == "X++":
ans+=1
elif inp == "--X" or inp == "X--":
ans-=1
print(ans) |
Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited n his friends there.
If t... | 3 | d={}
n=int(input())
l=list(map(int,input().split()))
for i in range(0,n):
d[l[i]]=i+1
s=""
#print(d)
for i in range(n):
s+=str(d[i+1])+" "
print(s)
|
An integer N is a multiple of 9 if and only if the sum of the digits in the decimal representation of N is a multiple of 9.
Determine whether N is a multiple of 9.
Constraints
* 0 \leq N < 10^{200000}
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output
If N is a multi... | 3 | s=input()
p=0
for x in s:
p+=int(x)
print("Yes" if p%9==0 else "No") |
Theatre Square in the capital city of Berland has a rectangular shape with the size n × m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a × a.
What is the least number of flagstones needed to pave the Square? It'... | 3 | from math import *
def th_square():
while True:
try:
n, m, a = input().split()
n = int(n)
m = int(m)
a = int(a)
assert 1 <= n <= 10 ** 9
assert 1 <= m <= 10 ** 9
assert 1 <= a <= 10 ** 9
except ValueError as error:... |
You have been blessed as a child of Omkar. To express your gratitude, please solve this problem for Omkar!
An array a of length n is called complete if all elements are positive and don't exceed 1000, and for all indices x,y,z (1 ≤ x,y,z ≤ n), a_{x}+a_{y} ≠ a_{z} (not necessarily distinct).
You are given one integer ... | 3 | n_tests = int(input())
for i in range(n_tests):
n = int(input())
ans = []
for i in range(n-1):
ans.append(1)
ans.append(1000)
for i in range(n):
print(ans[i], end = ' ')
print() |
Polycarp urgently needs a shovel! He comes to the shop and chooses an appropriate one. The shovel that Policarp chooses is sold for k burles. Assume that there is an unlimited number of such shovels in the shop.
In his pocket Polycarp has an unlimited number of "10-burle coins" and exactly one coin of r burles (1 ≤ r ... | 3 | import sys
def get_value(k, r):
temp = k
for i in range(1, 1000000000000):
temp*=i
if (temp-r) % 10 == 0 or temp%10 == 0:
return i
temp = k
def check(k, r):
if k-r % 10 == 0:
return True
else:
return False
def main():
sys_in = sys.stdin
s... |
Three poles stand evenly spaced along a line. Their heights are a, b and c meters, from left to right. We will call the arrangement of the poles beautiful if the tops of the poles lie on the same line, that is, b-a = c-b.
Determine whether the arrangement of the poles is beautiful.
Constraints
* 1 \leq a,b,c \leq 10... | 3 | a,b,c=map(int,input().split())
print("YES" if (b-a==c-b) else "NO") |
Inna loves sleeping very much, so she needs n alarm clocks in total to wake up. Let's suppose that Inna's room is a 100 × 100 square with the lower left corner at point (0, 0) and with the upper right corner at point (100, 100). Then the alarm clocks are points with integer coordinates in this square.
The morning has ... | 3 | x, y = set(), set()
for i in range(int(input())):
x1, y1 = map(int, input().split())
x.add(x1)
y.add(y1)
print(min(len(x), len(y)))
|
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 | n = int(input())
count = 0
for nom in [100, 20, 10, 5, 1]:
count += n // nom
n = n - (n // nom) * nom
print(count) |
Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers a, b, c on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting e... | 3 | a=int(input())
b=int(input())
c=int(input())
d=[a+b+c,a*b*c,a*b+c,a*(b+c),a+b*c,(a+b)*c]
print(max(d)) |
Eugeny loves listening to music. He has n songs in his play list. We know that song number i has the duration of ti minutes. Eugeny listens to each song, perhaps more than once. He listens to song number i ci times. Eugeny's play list is organized as follows: first song number 1 plays c1 times, then song number 2 plays... | 1 | # coding=utf-8
"""
B. Евгений и плейлист
ограничение по времени на тест:2 секунды
ограничение по памяти на тест:256 мегабайт
ввод:standard input
вывод:standard output
Евгений любит слушать музыку. В плейлисте Евгения играет n песен. Известно, что песня номер i имеет продолжительность ti минут. Каждую песню плейлиста Е... |
You're given an array a of length 2n. Is it possible to reorder it in such way so that the sum of the first n elements isn't equal to the sum of the last n elements?
Input
The first line contains an integer n (1 ≤ n ≤ 1000), where 2n is the number of elements in the array a.
The second line contains 2n space-separat... | 3 | n=int(input())
l=list(map(int,input().split()))
l1=[]
s1=sum(l)
for i in range(n):
l1.append(l[i])
s2=sum(l1)
if(len(set(l))==1):
print(-1)
elif(s2!=s1-s2):
for i in l:
print(i,end=" ")
print()
else:
l.sort()
for i in l:
print(i,end=" ")
print()
|
You are given an array a of length n and array b of length m both consisting of only integers 0 and 1. Consider a matrix c of size n × m formed by following rule: c_{i, j} = a_i ⋅ b_j (i.e. a_i multiplied by b_j). It's easy to see that c consists of only zeroes and ones too.
How many subrectangles of size (area) k con... | 3 | from math import sqrt
n, m, k = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
ans_a = []
ans_b = []
now = 0
for i in range(n):
if a[i] == 1:
now += 1
elif now != 0:
ans_a.append(now)
now = 0
if now != 0:
ans_a.append(now)
now = 0
f... |
Kana was just an ordinary high school girl before a talent scout discovered her. Then, she became an idol. But different from the stereotype, she is also a gameholic.
One day Kana gets interested in a new adventure game called Dragon Quest. In this game, her quest is to beat a dragon.
<image>
The dragon has a hit p... | 3 | t = int(input())
for i in range(t):
x, n, m = map(int, input().split())
for i in range(n):
y = x
z = x // 2 + 10
x = min(z, y)
if (m * 10) >= x:
print("YES")
else:
print("NO")
|
You are given three words s_1, s_2 and s_3, each composed of lowercase English letters, with spaces in between. Print the acronym formed from the uppercased initial letters of the words.
Constraints
* s_1, s_2 and s_3 are composed of lowercase English letters.
* 1 ≤ |s_i| ≤ 10 (1≤i≤3)
Input
Input is given from Stan... | 3 | a,b,c=input().split();print((a[0]+b[0]+c[0]).upper()) |
Xsquare loves to play with arrays a lot. Today, he has two arrays named as A and B. Each array consists of N positive integers.
Xsquare has decided to fulfill following types of queries over his array A and array B.
1 L R : Print the value of AL + BL+1 + AL+2 + BL+3 + ... upto R^th term.
2 L R : Print the value of... | 1 | line = raw_input().split()
N = int(line[0])
Q = int(line[1])
g = raw_input()
A = list(map(int,g.split()))
g = raw_input()
B = list(map(int,g.split()))
sumoddArrA = {}
sumevenArrA = {}
sumoddArrB = {}
sumevenArrB = {}
sOddTill = 0
sEvenTill = 0
for i in range(len(A)):
if (i+1)%2==0:
sEvenTill = sEvenTil... |
Dima and his friends have been playing hide and seek at Dima's place all night. As a result, Dima's place got messy. In the morning they decided that they need to clean the place.
To decide who exactly would clean the apartment, the friends want to play a counting-out game. First, all the guys stand in a circle, and t... | 3 | n = int(input()) + 1
s = sum(map(int, input().split()))
ans = 0
for i in range(1, 6):
if (s+i) % n != 1:
ans += 1
print(ans)
|
As a token of his gratitude, Takahashi has decided to give his mother an integer sequence. The sequence A needs to satisfy the conditions below:
* A consists of integers between X and Y (inclusive).
* For each 1\leq i \leq |A|-1, A_{i+1} is a multiple of A_i and strictly greater than A_i.
Find the maximum possible ... | 3 | X,Y=map(int,input().split())
cnt=0
while(Y>=X):
X*=2
cnt+=1
print(cnt) |
You are given an array a of length n consisting of zeros. You perform n actions with this array: during the i-th action, the following sequence of operations appears:
1. Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one;
2. Let ... | 1 | from __future__ import division, print_function
_interactive = False
def main():
import heapq as h
for _ in range(int(input())):
n = int(input())
ans = array_of(int, n)
heap = [(-n+1, 0, n-1)]
value = 1
while heap:
mlen, l, r = h.heappop(heap)
... |
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 | for i in range(int(input())):
lst = [int(i) for i in input().split()]
if len(set(lst)) == 1:
print(0)
elif len(set(lst)) == 2:
mn = min(lst)
mx = max(lst)
if lst.count(mn) == 2:
for ind, j in enumerate(lst):
if mn == j:
lst[ind]... |
Jzzhu has picked n apples from his big apple tree. All the apples are numbered from 1 to n. Now he wants to sell them to an apple store.
Jzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be greater... | 3 | """
Codeforces Round 257 Div 1 Problem C
Author : chaotic_iak
Language: Python 3.3.4
"""
def read(mode=2):
# 0: String
# 1: List of strings
# 2: List of integers
inputs = input().strip()
if mode == 0:
return inputs
if mode == 1:
return inputs.split()
if mode == 2:
... |
You are given an array d_1, d_2, ..., d_n consisting of n integer numbers.
Your task is to split this array into three parts (some of which may be empty) in such a way that each element of the array belongs to exactly one of the three parts, and each of the parts forms a consecutive contiguous subsegment (possibly, em... | 3 | noe = int(input())
arr = [int(x) for x in input().split()]
l, r = 0, noe-1
lsum, rsum, maxsum = 0, 0, 0
while l <= r:
if lsum >= rsum:
rsum += arr[r]
r-=1
else:
lsum += arr[l]
l += 1
if lsum == rsum:
maxsum = lsum
print(maxsum) |
You are given a tree with N vertices 1,2,\ldots,N, and positive integers c_1,c_2,\ldots,c_N. The i-th edge in the tree (1 \leq i \leq N-1) connects Vertex a_i and Vertex b_i.
We will write a positive integer on each vertex in T and calculate our score as follows:
* On each edge, write the smaller of the integers writ... | 3 | import sys
from collections import defaultdict as dd
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 6)
N = int(input())
e = dd(list)
for _ in range(N - 1):
u, v = map(int, input().split())
e[u].append(v)
e[v].append(u)
c = list(map(int, input().split()))
c.sort()
sm = sum(c) - c[-1]
res = [0] * (N + 1)
de... |
Drazil has many friends. Some of them are happy and some of them are unhappy. Drazil wants to make all his friends become happy. So he invented the following plan.
There are n boys and m girls among his friends. Let's number them from 0 to n - 1 and 0 to m - 1 separately. In i-th day, Drazil invites <image>-th boy and... | 3 | import sys
n,m = map(int,sys.stdin.readline().split())
men = [0]*n
women = [0]*m
inp1 = str(sys.stdin.readline()).split()
inp2 = str(sys.stdin.readline()).split()
b = int(inp1[0])
g = int(inp2[0])
allNeed = m+n
allBG = 0
for i in range(1,b+1):
men[int(inp1[i])] = 1
allBG += 1
for i in range(1,g+1):
wom... |
Takahashi, who lives on the number line, is now at coordinate X. He will make exactly K moves of distance D in the positive or negative direction.
More specifically, in one move, he can go from coordinate x to x + D or x - D.
He wants to make K moves so that the absolute value of the coordinate of the destination wil... | 3 | X, K, D = map(int, input().split())
X = abs(X)
N = X//D
if K<=N:
ans = X-K*D
else:
K -= N
X = X%D
ans = D-X if K&1 else X
print(ans)
|
Let's denote a k-step ladder as the following structure: exactly k + 2 wooden planks, of which
* two planks of length at least k+1 — the base of the ladder;
* k planks of length at least 1 — the steps of the ladder;
Note that neither the base planks, nor the steps planks are required to be equal.
For example... | 3 | for _ in range(int(input())):
n = int(input())
li = sorted(list(map(int, input().split())))
print(min(li[n - 2] - 1, n - 2))
|
During the archaeological research in the Middle East you found the traces of three ancient religions: First religion, Second religion and Third religion. You compiled the information on the evolution of each of these beliefs, and you now wonder if the followers of each religion could coexist in peace.
The Word of Uni... | 3 | import sys
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
n, q = map(int, input().split())
s = '!' + input()
nxt = [[n + 1] * (n + 2) for _ in range(26)]
for i in range(n - 1, -1, -1):
c = ord(s[i + 1]) - 97
for j in range(26):
nxt[j][i] = nxt[j][i + 1]
nxt[c][i] = i + 1
w... |
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 | pwd = 'pwd'
n = int(input())
commands = [''] * n
for i in range(n):
commands[i] = input()
path = ['']
for i in range(n):
command = commands[i]
if (command == pwd):
print('/'.join(path) + '/')
else:
path_to_go = command[3:]
dirs = []
if (path_to_go[0] == '/'):
... |
Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw.
The first player wrote number a, the second player wrote number b. How many ways ... | 3 | a, b = (int(s) for s in input().split())
a_win, mid, b_win = 0, 0, 0
for i in range(1, 7):
if abs(a-i) < abs(b-i):
a_win = a_win + 1
elif abs(a-i) == abs(b-i):
mid = mid + 1
else:
b_win = b_win + 1
print(a_win, mid, b_win)
|
Sherlock Holmes loves mind palaces! We all know that.
A mind palace, according to Mr. Holmes is something that lets him retrieve a given memory in the least time posible. For this, he structures his mind palace in a very special way. Let a NxM Matrix denote the mind palace of Mr. Holmes. For fast retrieval he keeps ea... | 1 | size=[int(x) for x in raw_input().split()]
dic={}
for i in xrange(0,size[0]):
mem=[int(x) for x in raw_input().split()]
for j in xrange(0,size[1]):
dic[mem[j]]=str(i)+" "+str(j)
q=input()
for k in xrange(0,q):
query=input()
if dic.has_key(query):
print dic[query]
else:
pr... |
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... | 3 | for i in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
n=len(set(a))
print(n) |
Long story short, shashlik is Miroslav's favorite food. Shashlik is prepared on several skewers simultaneously. There are two states for each skewer: initial and turned over.
This time Miroslav laid out n skewers parallel to each other, and enumerated them with consecutive integers from 1 to n in order from left to ri... | 3 | def try_start(start, n, k):
positions = []
pos = start
if pos > n:
return 1001, []
while pos <= n:
positions.append(pos)
if pos + 2 * k + 1 <= n:
pos += 2 * k + 1
continue
if pos + k >= n:
break
if pos == n:
break
... |
Consider some positive integer x. Its prime factorization will be of form x = 2^{k_1} ⋅ 3^{k_2} ⋅ 5^{k_3} ⋅ ...
Let's call x elegant if the greatest common divisor of the sequence k_1, k_2, ... is equal to 1. For example, numbers 5 = 5^1, 12 = 2^2 ⋅ 3, 72 = 2^3 ⋅ 3^2 are elegant and numbers 8 = 2^3 (GCD = 3), 2500 = 2... | 3 | from math import sqrt, log2
from sys import stdin
from bisect import bisect
import time
def all_primes(n):
res = []
for i in range(1, n+1):
prime = True
for j in range(2, min(int(sqrt(i))+2, i)):
if i % j == 0:
prime = False
break
if prime: re... |
Fox Ciel starts to learn programming. The first task is drawing a fox! However, that turns out to be too hard for a beginner, so she decides to draw a snake instead.
A snake is a pattern on a n by m table. Denote c-th cell of r-th row as (r, c). The tail of the snake is located at (1, 1), then it's body extends to (1,... | 3 | n, m= list(map(int, input().split()))
for i in range(1,n+1):
if (i % 2 == 1):
print("#" * m)
else:
if (i % 4 == 0):
print ("#" + "." * (m - 1))
else:
print("." * (m - 1) + "#") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.