problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is ... | 3 | s = input()
o = s.find('^')
a = list(int(s[i]) if s[i].isdigit() else 0 for i in range(len(s)))
summa = 0
for i in range(len(s)):
summa += (i-o) * a[i]
if summa < 0:
print ('left')
elif summa == 0:
print('balance')
else:
print('right') |
There is a circular pond with a perimeter of K meters, and N houses around them.
The i-th house is built at a distance of A_i meters from the northmost point of the pond, measured clockwise around the pond.
When traveling between these houses, you can only go around the pond.
Find the minimum distance that needs to ... | 3 | k,n=map(int,input().split())
a=list(map(int,input().split()))
l=[a[i+1]-a[i] for i in range(n-1)]
l.append(a[0]+k-a[-1])
print(k-max(l))
|
We have a string X, which has an even number of characters. Half the characters are `S`, and the other half are `T`.
Takahashi, who hates the string `ST`, will perform the following operation 10^{10000} times:
* Among the occurrences of `ST` in X as (contiguous) substrings, remove the leftmost one. If there is no occ... | 3 | X = input()
ans, sc = 0, 0
for x in X:
if x == 'T':
sc += 1
else:
sc -= 1
ans = max(ans, sc)
print(ans*2)
|
Little Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.
Now he wonders what is an average value of sum of digits of the number A written in all bases from 2 to A - 1.
Note that all computa... | 1 | def gcd(a,b):
if b == 0:
return a
return gcd(b,a%b)
a = input()
ans = []
for b in range(2,a):
x = a
m = []
while x != 0:
m += [x%b]
x = x / b
ansi = 0
for mi in m:
ansi += mi
ans += [ansi]
sm = sum(ans)
ln = len(ans)
gd = gcd(sm,ln)
sm /= gd
ln /= gd
print str(sm)+'/'+str(ln) |
You are given n chips on a number line. The i-th chip is placed at the integer coordinate x_i. Some chips can have equal coordinates.
You can perform each of the two following types of moves any (possibly, zero) number of times on any chip:
* Move the chip i by 2 to the left or 2 to the right for free (i.e. replace... | 3 | n=int(input())
a=list(map(int,input().split()))
o=0
e=0
for i in a:
if i%2==0:
e+=1
else:
o+=1
if e<o:
print(e)
else:
print(o) |
You have n barrels lined up in a row, numbered from left to right from one. Initially, the i-th barrel contains a_i liters of water.
You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels x and y (the x-th barrel shouldn't be empty) and pour any possible amount of wa... | 3 | for tt in range(int(input())):
n,k = map(int,input().split())
a = list(map(int,input().split()))
a.sort(reverse=True)
for i in range(1,n):
if k:
a[0] += a[i]
a[i] = 0
k -= 1
print(max(a) - min(a)) |
Vanya got n cubes. He decided to build a pyramid from them. Vanya wants to build the pyramid as follows: the top level of the pyramid must consist of 1 cube, the second level must consist of 1 + 2 = 3 cubes, the third level must have 1 + 2 + 3 = 6 cubes, and so on. Thus, the i-th level of the pyramid must have 1 + 2 + ... | 3 | s=int(input())
for a in range(1,100000):
if(s<(a*(a+1)*(a+2)/6)):
print(a-1)
break |
Ridhiman challenged Ashish to find the maximum valued subsequence of an array a of size n consisting of positive integers.
The value of a non-empty subsequence of k elements of a is defined as β 2^i over all integers i β₯ 0 such that at least max(1, k - 2) elements of the subsequence have the i-th bit set in their bin... | 3 | n=int(input())
b=list(map(int,input().split()))
if n==1:
print(b[0])
elif n==2:
print(b[0]|b[1])
else:
ans=0
for i in range(n):
for j in range(i+1,n):
for k in range(j+1,n):
ans=max(ans,b[i]|b[j]|b[k])
print(ans) |
Mishka wants to buy some food in the nearby shop. Initially, he has s burles on his card.
Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1 β€ x β€ s, buy food that costs exactly x burles and obtain βx/10β burles as a cashback (in other words, Mishka ... | 3 | # link: https://codeforces.com/problemset/problem/1296/B
if __name__ == "__main__":
t = int(input())
while t:
n = int(input())
if n<10:
print(n)
else:
minus = 1
while minus <= n:
minus = minus * 10
minus = minus // 10
... |
Notes
Template in C
Constraints
* 1 β€ n β€ 100000
* 1 β€ q β€ 1000
* 1 β€ timei β€ 50000
* 1 β€ length of namei β€ 10
* 1 β€ Sum of timei β€ 1000000
Input
n q
name1 time1
name2 time2
...
namen timen
In the first line the number of processes n and the quantum q are given separated by a single space.
In the following n li... | 1 | class process:
def __init__(self, name, time):
self.name = name
self.time = time
def main():
n, q = map(int, raw_input().split())
p = list()
for i in range(n):
name, time = raw_input().split()
p.append(process(name, int(time)))
s = 0
while len(p) > 0:
e ... |
Alice is the leader of the State Refactoring Party, and she is about to become the prime minister.
The elections have just taken place. There are n parties, numbered from 1 to n. The i-th party has received a_i seats in the parliament.
Alice's party has number 1. In order to become the prime minister, she needs to b... | 1 | n=input()
arr=map(int,raw_input().split())
s1=sum(arr)
a=arr[0]
na=[1]
s2=a
for i in range(1,n):
if arr[i]<=(a/2):
s2+=arr[i]
na.append(i+1)
if s2>(s1/2):
print len(na)
for i in na:
print i,
else:
print 0
|
Tavak and Seyyed are good friends. Seyyed is very funny and he told Tavak to solve the following problem instead of longest-path.
You are given l and r. For all integers from l to r, inclusive, we wrote down all of their integer divisors except 1. Find the integer that we wrote down the maximum number of times.
Solve... | 3 | import math
l, r = map(int, input().split())
res = 0
if r - l > 0:
res = 2
else:
for i in range(2, int(math.sqrt(r)) + 1):
if r % i == 0:
res = i
break
print(res if res else r) |
The only difference between easy and hard versions is constraints.
You are given a sequence a consisting of n positive integers.
Let's define a three blocks palindrome as the sequence, consisting of at most two distinct elements (let these elements are a and b, a can be equal b) and is as follows: [\underbrace{a, a, ... | 3 | t=int(input())
for _ in range(t):
n=int(input())
A=list(map(int,input().split()))
B={}
for i in range(n):
try:
B[A[i]].append(i)
except:
B[A[i]]=[i]
fa=0
flag=0
C={}
for i in B.keys():
C[i]=[0 for op in range(n)]
mv=1
j=0
... |
Alexandra has an even-length array a, consisting of 0s and 1s. The elements of the array are enumerated from 1 to n. She wants to remove at most n/2 elements (where n β length of array) in the way that alternating sum of the array will be equal 0 (i.e. a_1 - a_2 + a_3 - a_4 + ... = 0). In other words, Alexandra wants s... | 3 | from sys import stdin
"""
n=int(stdin.readline().strip())
n,m=map(int,stdin.readline().strip().split())
s=list(map(int,stdin.readline().strip().split()))
"""
n1=int(stdin.readline().strip())
for j in range(n1):
n=int(stdin.readline().strip())
s=list(map(int,stdin.readline().strip().split()))
x=s.count(1)
... |
The School β0 of the capital of Berland has n children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value ti:
* ti = 1, if the i-th child is good at programming,
*... | 3 | _ = input()
t_arr = list(map(int, input().split()))
v1 = {1 : [], 2: [], 3: []}
for t_idx in range(len(t_arr)):
v1[t_arr[t_idx]].append(t_idx+1)
num_trips = min(len(v1[1]), len(v1[2]), len(v1[3]))
if num_trips == 0:
print(0)
else:
print(num_trips)
for i in range(num_trips):
print(v1[1][i], v1[2]... |
Recently, a chaotic virus Hexadecimal advanced a new theorem which will shake the Universe. She thinks that each Fibonacci number can be represented as sum of three not necessary different Fibonacci numbers.
Let's remember how Fibonacci numbers can be calculated. F0 = 0, F1 = 1, and all the next numbers are Fi = Fi - ... | 1 | from __future__ import division, print_function
def main():
n = int(input())
if n <= 3:
if n == 0:
print("%d %d %d" %(0, 0, 0))
elif n == 1:
print("%d %d %d" %(0, 0, 1))
elif n == 2:
print("%d %d %d" %(0, 1, 1))
elif n == 3:
p... |
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them.
Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain nu... | 3 | s=input()
x=s.replace("WUB"," ")
if x[0]==" ":
print(x[1:])
else:
print(x) |
After a probationary period in the game development company of IT City Petya was included in a group of the programmers that develops a new turn-based strategy game resembling the well known "Heroes of Might & Magic". A part of the game is turn-based fights of big squadrons of enemies on infinite fields where every cel... | 3 | #!/usr/bin/env python3
import collections, itertools, functools, math
# 1 + 6 + 12 + 18 = 37
# 1, 6, 12, 18
def solve():
n = int(input())
return 1 + ((6*n)*(n+1))//2
if __name__ == '__main__':
print(solve())
|
You are given n chips on a number line. The i-th chip is placed at the integer coordinate x_i. Some chips can have equal coordinates.
You can perform each of the two following types of moves any (possibly, zero) number of times on any chip:
* Move the chip i by 2 to the left or 2 to the right for free (i.e. replace... | 3 | n = int(input())
x = list(map(int,input().split()))
odd = [x[i] for i in range(len(x)) if x[i]%2 != 0]
even = [x[i] for i in range(len(x)) if x[i]%2 == 0]
print(min(len(odd),len(even)))
|
Young boy Artem tries to paint a picture, and he asks his mother Medina to help him. Medina is very busy, that's why she asked for your help.
Artem wants to paint an n Γ m board. Each cell of the board should be colored in white or black.
Lets B be the number of black cells that have at least one white neighbor adja... | 3 | for _ in range(int(input())):
n, m = map(int,input().split())
print('W'+'\n'.join(['B'*m]*n)[1:]) |
N Soldiers are lined up for a memory test. They are numbered from 0 to N-1 from left to right.
In the test, there are M rounds. In each round, Captain selects one position. Soldier at that position will be numbered 0. All the soldiers to the right of selected position will be numbered one greater than the soldier to ... | 1 | T = input()
for _ in range(T):
n,m = map(int,raw_input().split())
arr = map(int,raw_input().split())
s = min(arr)
l = max(arr)
for i in range(n):
if abs(i-s)>abs(i-l):
print abs(i-s),
else:
print abs(i-l) |
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... | 1 | UPPER = 'QWERTYUIOPASDFGHJKLZXCVBNM'
LOWER = 'qwertyuiopasdfghjklzxcvbnm'
def case1(word):
ans = word[0] in LOWER
for e in word[1::]:
ans &= e in UPPER
return ans
def case2(word):
for e in ans:
if not e in UPPER: return False
return True
def change(word):
ans = ''
for e in... |
Today Patrick waits for a visit from his friend Spongebob. To prepare for the visit, Patrick needs to buy some goodies in two stores located near his house. There is a d1 meter long road between his house and the first shop and a d2 meter long road between his house and the second shop. Also, there is a road of length ... | 1 | '''
Created on 15-May-2016
@author: chirag
'''
inp=raw_input().split(" ")
d1=int(inp[0])
d2=int(inp[1])
d3=int(inp[2])
ans=min(d1,d2)+min(d1+d2,d3)+min(max(d1,d2),d3+min(d1,d2))
print ans |
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line.
Unfortunately, from time to ti... | 3 | n = input()
a = []
i = 1
if len(n) == 2:
print(0)
else:
while i < len(n):
a.append(n[i])
i += 3
print(len(list(set(a))))
|
Theatre Square in the capital city of Berland has a rectangular shape with the size n Γ m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a Γ a.
What is the least number of flagstones needed to pave the Square? It'... | 1 | n,m,a=map(int,raw_input().split())
x=(n+a-1)/a
y=(m+a-1)/a
print x*y
|
You received a notebook which is called Death Note. This notebook has infinite number of pages. A rule is written on the last page (huh) of this notebook. It says: "You have to write names in this notebook during n consecutive days. During the i-th day you have to write exactly a_i names.". You got scared (of course yo... | 3 |
n = str(input())
n = n.split()
limit = int(n[1])
names = str(input())
names = names.split()
# day_names = [int(i) for i in names]
count = 0
pages_list = []
if int(n[0]) >= 1 and int(n[0]) <= 200000:
if limit >= 1 and limit <= 1000000000:
for i in names:
page = 0
# for x in range(0... |
Write a program which reads $n$ dices constructed in the same way as Dice I, and determines whether they are all different. For the determination, use the same way as Dice III.
Constraints
* $2 \leq n \leq 100$
* $0 \leq $ the integer assigned to a face $ \leq 100$
Input
In the first line, the number of dices $n$ i... | 3 | class Dice:
D = {'E': (3, 1, 0, 5, 4, 2),
'W': (2, 1, 5, 0, 4, 3),
'S': (4, 0, 2, 3, 5, 1),
'N': (1, 5, 2, 3, 0, 4)}
def __init__(self, a, b, c, d, e, f):
self.nbrs = [a, b, c, d, e, f]
def rll(self, dr):
self.nbrs = [self.nbrs[i] for i in self.D[dr]]
def issam... |
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.
Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of o... | 3 | from sys import stdin
a = stdin.readline().rstrip()
b = stdin.readline().rstrip()
print(-1 if a==b else max(len(a),len(b)))
|
These days Arkady works as an air traffic controller at a large airport. He controls a runway which is usually used for landings only. Thus, he has a schedule of planes that are landing in the nearest future, each landing lasts 1 minute.
He was asked to insert one takeoff in the schedule. The takeoff takes 1 minute it... | 3 | n, s = map(int, input().split())
q = 0
for i in range(n):
a, b = map(int, input().split())
p = a * 60 + b
if i == 0 and p > s:
rec = 0
break
if p - q > s * 2 + 1:
rec = q + s + 1
break
q = p
rec = q + s + 1
h, m = rec // 60, rec % 60
print(h, m) |
Theatre Square in the capital city of Berland has a rectangular shape with the size n Γ m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a Γ a.
What is the least number of flagstones needed to pave the Square? It'... | 3 | import math
numbers = list(map(int, input().split()))
n = numbers[0]
m = numbers[1]
a = numbers[2]
result = math.ceil(n / a) * math.ceil(m / a)
print(result)
|
Vasya plays the sleuth with his friends. The rules of the game are as follows: those who play for the first time, that is Vasya is the sleuth, he should investigate a "crime" and find out what is happening. He can ask any questions whatsoever that can be answered with "Yes" or "No". All the rest agree beforehand to ans... | 3 | s = input()
cel = ''
alp = 'abcdefghijkmnlopqrstuwxyzABCDEFGHIJKMNLOPQRSTUWXYZ'
for i in range(len(s)-1, -1, -1):
if s[i] in alp:
cel += s[i]
break
if cel == '':
print('NO')
else:
if cel in "aeiouyAEIOUY":
print('YES')
else:
print('NO') |
Melody Pond was stolen from her parents as a newborn baby by Madame Kovarian, to become a weapon of the Silence in their crusade against the Doctor. Madame Kovarian changed Melody's name to River Song, giving her a new identity that allowed her to kill the Eleventh Doctor.
Heidi figured out that Madame Kovarian uses a... | 3 | r = int(input())
i = 1
while i * i <= r - 1:
if (r-1) % i == 0:
x = i
if ((r-1) / x - x - 1) % 2 == 0 and ((r-1) / x - x - 1) / 2 > 0:
print(str(x) + ' ' + str(int(((r-1) / x - x - 1)/2)))
exit()
i += 1
print("NO")
|
This morning, Roman woke up and opened the browser with n opened tabs numbered from 1 to n. There are two kinds of tabs: those with the information required for the test and those with social network sites. Roman decided that there are too many tabs open so he wants to close some of them.
He decided to accomplish this... | 1 | from collections import Counter
n,k=map(int,raw_input().split())
l=map(int,raw_input().split())
mx=0
d=Counter(l)
a=d[1]
b=d[-1]
for i in range(1,k+1):
c=0
c1=a
c2=b
temp=i+(c*k)
while temp<=n:
if l[temp-1]==1:
c1-=1
else:
c2-=1
c+=1
temp=i+(c*... |
Even if the world is full of counterfeits, I still regard it as wonderful.
Pile up herbs and incense, and arise again from the flames and ashes of its predecessor β as is known to many, the phoenix does it like this.
The phoenix has a rather long lifespan, and reincarnates itself once every a! years. Here a! denotes ... | 3 | score = [int(x) for x in input().split()]
a = score[0]
b = score[1]
if b-a >= 5:
print(0)
else:
res = 1
for i in range(b,a,-1):
res = res*i
print(res%10) |
Nicholas has an array a that contains n distinct integers from 1 to n. In other words, Nicholas has a permutation of size n.
Nicholas want the minimum element (integer 1) and the maximum element (integer n) to be as far as possible from each other. He wants to perform exactly one swap in order to maximize the distance... | 3 | n = int(input())
array = [i for i in map(int, input().split())]
#print(array)
if array[0] == 1 or array[0] == n or array[n - 1] == 1 or array[n - 1] == n:
print(n - 1)
else:
i = 1
while i < n - 3:
if array[i] == 1 or array[i] == n:
i_num = i
break
else:
... |
"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 | a = input().strip().split(" ")
b = input().strip().split(" ")
n = int(a[0])
k = int(a[1])
count = 0
for i in range(len(b)):
if int(b[i]) >= int(b[k-1]) and int(b[i]) > 0:
count += 1
print(count)
|
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 = input()
if a[0].islower():
a1 =a[0].upper()
else :
a1 =a[0].lower()
c=1
for i in range(1,len(a)):
if a[i].isupper():
a1 = a1 + a[i].lower()
c =c+1
if (c==len(a)):
print(a1)
else:
print(a) |
There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of ope... | 3 | def can(S, c):
ans = ''
nc = False
for i in range(len(S)):
if (S[i] != c and nc==False) or (S[i]==c and nc==True):
ans += str(i+1) + ' '
nc = True
else:
nc = False
if nc == True:
return False
return ans
n = int(input())
s = input()
ans = ... |
You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.
Input
The first line contains t... | 3 | na, nb = map(int, input().split())
k, m = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
print('YES' if max(A[:k]) < min(B[-m:]) else 'NO')
|
Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones.
Once he thought about a string of length n consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and ... | 1 | n = input()
print abs(n - 2*raw_input().count('0'))
|
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 | def solve():
kek = input()
a = sorted(list(map(int, input().split())))
if a[0] == a[-1]:
print(len(a))
else:
print(1)
[solve() for x in range(int(input()))]
|
Today, Osama gave Fadi an integer X, and Fadi was wondering about the minimum possible value of max(a, b) such that LCM(a, b) equals X. Both a and b should be positive integers.
LCM(a, b) is the smallest positive integer that is divisible by both a and b. For example, LCM(6, 8) = 24, LCM(4, 12) = 12, LCM(2, 3) = 6.
O... | 3 | x = int(input())
pri = []
i = 2
xx = x
while xx > 1 and i**2 <= x:
if xx%i == 0:
xx //= i
pri.append(i)
else:
i += 1
if xx > 1:
pri.append(xx)
d = {}
for i in pri:
d[i] = 0
for i in pri:
d[i] += 1
best = 1
nn = []
for i in d:
nn.append(i**d[i])
for i in range(2**len(d)):
kan = 1
dupa = []
for j in range(... |
"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())
scores = list(map(int,input().split()))
mark = scores[k-1]
count = 0
for score in scores:
if score>0 and score>=mark:
count+=1
print(count) |
There is a frog staying to the left of the string s = s_1 s_2 β¦ s_n consisting of n characters (to be more precise, the frog initially stays at the cell 0). Each character of s is either 'L' or 'R'. It means that if the frog is staying at the i-th cell and the i-th character is 'L', the frog can jump only to the left. ... | 3 | nCases = int(input())
for _ in range(nCases):
jumps = input()
bigJump = 1
curJump = 1
for j in jumps:
if j == 'L':
curJump += 1
if j == 'R':
bigJump = max(bigJump, curJump)
curJump = 1
print(max(bigJump, curJump))
... |
A penguin Rocher has n sticks. He has exactly one stick with length i for all 1 β€ i β€ n.
He can connect some sticks. If he connects two sticks that have lengths a and b, he gets one stick with length a + b. Two sticks, that were used in the operation disappear from his set and the new connected stick appears in his se... | 3 | '''
* Created by Syed Sanzam on
* Title:
* Problem Link:
* Editorial:
* Language:
* Comments:
'''
import sys
from collections import Counter
from collections import defaultdict
from collections import deque
#sys.stdin = open('input.txt','r')
t = int(input())
for i in range(t):
n = int(input())
if(n%2):... |
A new delivery of clothing has arrived today to the clothing store. This delivery consists of a ties, b scarves, c vests and d jackets.
The store does not sell single clothing items β instead, it sells suits of two types:
* a suit of the first type consists of one tie and one jacket;
* a suit of the second type ... | 3 | a = int(input())
b = int(input())
c = int(input())
d = int(input())
e = int(input())
f = int(input())
if f > e:
x = min(b,c,d)*f
d = d - min(b,c,d)
y = min(a,d)*e
print(x+y)
else:
x = min(a,d)*e
d = d - min(a,d)
y = min(b,c,d)*f
print(x+y) |
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Bi... | 3 | import sys
n = int(input())
if n % 2 == 0 and n > 2:
print("YES");
else:
print("NO") |
A string is called diverse if it contains consecutive (adjacent) letters of the Latin alphabet and each letter occurs exactly once. For example, the following strings are diverse: "fced", "xyz", "r" and "dabcef". The following string are not diverse: "az", "aa", "bad" and "babc". Note that the letters 'a' and 'z' are n... | 3 | def ev():
s = input()
mn = set(s)
if len(s) > len(mn):
print('No')
return
ls = list(mn)
ls.sort()
for i in range(1, len(ls)):
if (ord(ls[i]) - ord(ls[i - 1]) != 1):
print('No')
return
print('Yes')
return
n = int(input())
for i in range(n):... |
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Bi... | 3 | x = int(input())
if x >=1 and x<=100:
if x==2:
print("NO")
elif (x-2) % 2==0:
print("YES")
else :
print("NO")
|
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory.
George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living... | 3 | n = int(input())
count = 0
for _ in range(n):
a,b = map(int,input().split(" "))
if(b-a >=2):
count += 1
print(count) |
The Easter Rabbit laid n eggs in a circle and is about to paint them.
Each egg should be painted one color out of 7: red, orange, yellow, green, blue, indigo or violet. Also, the following conditions should be satisfied:
* Each of the seven colors should be used to paint at least one egg.
* Any four eggs lying ... | 3 | n=int(input())
c=['R','O','Y','G','B','I','V']
c1=['','G','GB','YGB','YGBI','OYGBI','OYGBIV']
i=n//7
arr=[]
arr+=c*i
j=n%7
arr+=c1[j]
print(*arr,sep='')
|
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 | tc = int(input())
for _ in range(tc):
a,b,c = list(map(int,input().split()))
ans = 100000000000
for i in [1,-1,0]:
aa = a+i
for j in [0,1,-1]:
bb= b+j
for k in [-1,1,0]:
cc = c+ k
# print("ss",abs(aa-bb)+abs(aa-cc)+abs(bb-cc))
... |
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 | arr=list(map(int,input().split()))
n=arr[0]
m=arr[1]
a=arr[2]
n=int(n)
m=int(m)
a=int(a)
r=((n+a-1)//a)
r1=((m+a-1)//a)
print(r*r1)
|
Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he... | 3 | def binarySearch(arr,x):
l=0
r=len(arr)-1
while l <= r:
mid = (l + r)//2;
if arr[mid] == x:
return mid
elif arr[mid] < x:
l = mid + 1
else:
r = mid - 1
return -1
n,p,q,r=map(int,input().split())
ar=list(map(int,input().split()))
dp=[]
inf=-9999999999999999999999999999999999999
for i in rang... |
Two polar bears Menshykov and Uslada from the St.Petersburg zoo and elephant Horace from the Kiev zoo got six sticks to play with and assess the animals' creativity. Menshykov, Uslada and Horace decided to make either an elephant or a bear from those sticks. They can make an animal from sticks in the following way:
... | 1 | s=map(int,raw_input().split())
x=False
for i in s:
if s.count(i)>=4:
for j in range(4):
s.remove(i)
x=True
if not x:
print 'Alien'
elif s[0]==s[1]:
print "Elephant"
else:
print "Bear" |
Pasha decided to invite his friends to a tea party. For that occasion, he has a large teapot with the capacity of w milliliters and 2n tea cups, each cup is for one of Pasha's friends. The i-th cup can hold at most ai milliliters of water.
It turned out that among Pasha's friends there are exactly n boys and exactly n... | 3 | n, w = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
#print(a)
bigCup = max(a)
def check(x): # x == 2*n*3
agar = x/(2*n*3)
for_girl = agar * 2
for_boy = for_girl * 2
#print(for_girl, for_boy, x)
if a[0] < for_girl or a[n] < for_boy:
return False
# for i in ran... |
Draw a frame which has a height of H cm and a width of W cm. For example, the following figure shows a frame which has a height of 6 cm and a width of 10 cm.
........#
........#
........#
........#
Constraints
* 3 β€ H β€ 300
* 3 β€ W β€ 300
Input
The input consists of multiple datasets. Each dataset consists of t... | 3 | while True:
h, w = map(int, input().split())
if h==w==0:
break
print('#'*w)
for _ in range(h-2):
print('#'+'.'*(w-2)+'#')
print('#'*w+'\n')
|
There is a circular pond with a perimeter of K meters, and N houses around them.
The i-th house is built at a distance of A_i meters from the northmost point of the pond, measured clockwise around the pond.
When traveling between these houses, you can only go around the pond.
Find the minimum distance that needs to ... | 1 | K, N = map(int, raw_input().split())
A = map(int, raw_input().split())
cmax = 0
for i in range(N-1):
if A[i+1]-A[i] > cmax:
cmax = A[i+1]-A[i]
if A[0]+K-A[N-1] > cmax:
cmax = A[0]+K-A[N-1]
print K-cmax
|
Neko loves divisors. During the latest number theory lesson, he got an interesting exercise from his math teacher.
Neko has two integers a and b. His goal is to find a non-negative integer k such that the least common multiple of a+k and b+k is the smallest possible. If there are multiple optimal integers k, he needs ... | 3 | from math import gcd
import sys
input=sys.stdin.buffer.readline
def lcm(x,y):
return (x*y)//gcd(x,y)
a, b = map(int, input().split())
'''
lcm(a+k, b+k) = (a+k)*(b+k) / gcd(a+k, b+k) = .../ gcd(a-b, b+k)
'''
i = 1
if a < b:
a, b = b, a
curr = lcm(a, b)
ans = 0
while i * i <= a - b:
if (a - b) % i == 0:... |
As shown in the following figure, there is a paper consisting of a grid structure where each cell is indicated by (x, y) coordinate system.
We are going to put drops of ink on the paper. A drop comes in three different sizes: Large, Medium, and Small. From the point of fall, the ink sinks into surrounding cells as sho... | 3 | if __name__ == '__main__':
DI = [[0 for _ in range(10)] for _ in range(10)]
while True:
try:
x,y,s = map(int,input().split(","))
if s == 0:
break
if s == 1:
#θͺθΊ«
DI[x][y] += 1
#up
if y >= 1 :
DI[x][y-1] += 1
#down
if y <= 8:
DI[x][y+1] += 1
#left
if x >= 1:
... |
There are n consecutive seat places in a railway carriage. Each place is either empty or occupied by a passenger.
The university team for the Olympiad consists of a student-programmers and b student-athletes. Determine the largest number of students from all a+b students, which you can put in the railway carriage so t... | 3 | n,a,b=map(int,input().split())
s=input()
ans=0
A,B=a,b
cnt=0
for i in s:
if(i=='*'):
if(cnt%2):
if(a>b):
a-=cnt//2+1
b-=cnt//2
else:
a-=cnt//2
b-=cnt//2+1
else:
a-=cnt//2
b-=... |
One Big Software Company has n employees numbered from 1 to n. The director is assigned number 1. Every employee of the company except the director has exactly one immediate superior. The director, of course, doesn't have a superior.
We will call person a a subordinates of another person b, if either b is an immediate... | 1 | import sys
from itertools import imap
def parseints(s, n):
r, i, x = [0] * n, 0, 0
for c in imap(ord, s):
if c == 32:
r[i], i, x = x, i + 1, 0
else:
x = x * 10 + c - 48
return r
n = input()
z = parseints(sys.stdin.read()[1:].replace('\n', ' '), 2 * n)
l = [0] * (n ... |
Snuke, a water strider, lives in a rectangular pond that can be seen as a grid with H east-west rows and W north-south columns. Let (i,j) be the square at the i-th row from the north and j-th column from the west.
Some of the squares have a lotus leaf on it and cannot be entered. The square (i,j) has a lotus leaf on i... | 3 | import sys
def input():
return sys.stdin.readline()[:-1]
from collections import deque
H, W, K = map(int, input().split())
sh, sw, gh, gw = map(int, input().split())
c = ["@" * (W+2)] + ["@" + input() + "@" for _ in range(H)] + ["@" * (W+2)]
INF = 10**6+5
dist = [[INF for _ in range(W+2)] for _ in range(H+2)]
dist[sh]... |
Polycarp wants to cook a soup. To do it, he needs to buy exactly n liters of water.
There are only two types of water bottles in the nearby shop β 1-liter bottles and 2-liter bottles. There are infinitely many bottles of these two types in the shop.
The bottle of the first type costs a burles and the bottle of the se... | 3 | num= int(input())
while(num!=0):
num-=1
n,a,b = map(int,input().split())
print(min(n*a,(n//2)*b+(n%2)*a)) |
ZS the Coder and Chris the Baboon are travelling to Udayland! To get there, they have to get on the special IOI bus. The IOI bus has n rows of seats. There are 4 seats in each row, and the seats are separated into pairs by a walkway. When ZS and Chris came, some places in the bus was already occupied.
ZS and Chris are... | 3 | n = int(input())
list = []
for i in range(n):
list.append(input())
match = 0
ans = "NO"
t = 0
for i in range(n):
match = 0
for k in range(5):
if t == 0:
if list[i][k] == "O":
match += 1
else:
match = 0;
if match == 2:
... |
This contest, AtCoder Beginner Contest, is abbreviated as ABC.
When we refer to a specific round of ABC, a three-digit number is appended after ABC. For example, ABC680 is the 680th round of ABC.
What is the abbreviation for the N-th round of ABC? Write a program to output the answer.
Constraints
* 100 β€ N β€ 999
I... | 3 | x=input()
print("ABC"+str(x))
|
You are given a bracket sequence s of length n, where n is even (divisible by two). The string s consists of n/2 opening brackets '(' and n/2 closing brackets ')'.
In one move, you can choose exactly one bracket and move it to the beginning of the string or to the end of the string (i.e. you choose some index i, remov... | 3 | for _ in range(int(input())):
n = int(input())
ans = 0
h = 0
for x in input():
if '(' == x:
h -= 1
else:
h += 1
ans = max(ans, h)
print(ans)
|
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find ... | 3 | from collections import Counter
a=int(input())
b=4
f=""
if(a<4):
print("NO")
elif(a%4==0 or a%7==0):
print("YES")
else:
while(b!=(a+1)):
c=str(b)
d=Counter(c)
e=[*d]
if((len(e)==2) and (e[0]=='4' or e[0]=='7') and (e[1]=='4' or e[1]=='7') and (a%b==0)):
f="YES"
... |
Recently, you found a bot to play "Rock paper scissors" with. Unfortunately, the bot uses quite a simple algorithm to play: he has a string s = s_1 s_2 ... s_{n} of length n where each letter is either R, S or P.
While initializing, the bot is choosing a starting index pos (1 β€ pos β€ n), and then it can play any numbe... | 3 | from collections import Counter
t = int(input())
for foo in range(t):
s = input()
cnt = Counter(s).most_common()
mc = cnt[0][0]
if mc == 'R': ans = 'P'
elif mc == 'S': ans = 'R'
elif mc == 'P': ans = 'S'
print(ans * len(s))
|
Two players play a simple game. Each player is provided with a box with balls. First player's box contains exactly n1 balls and second player's box contains exactly n2 balls. In one move first player can take from 1 to k1 balls from his box and throw them away. Similarly, the second player can take from 1 to k2 balls f... | 3 | a, b, c ,d = list(map(int, input().split()))
if (a > b):
print("First")
elif (b > a):
print("Second")
else:
if (c < d):
print("Second")
elif (d > c):
print("First")
else:
print("Second")
|
Being stuck at home, Ray became extremely bored. To pass time, he asks Lord Omkar to use his time bending power: Infinity Clock! However, Lord Omkar will only listen to mortals who can solve the following problem:
You are given an array a of n integers. You are also given an integer k. Lord Omkar wants you to do k ope... | 3 | '''
Auther: ghoshashis545 Ashis Ghosh
College: jalpaiguri Govt Enggineering College
'''
from os import path
import sys
from heapq import heappush,heappop
from functools import cmp_to_key as ctk
from collections import deque,defaultdict as dd
from bisect import bisect,bisect_left,bisect_right,insort,insort_lef... |
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d... | 3 | s = input()
if (s.count('7')+s.count('4'))==7 or (s.count('7')+s.count('4'))==4:
print('YES')
else:
print('NO') |
Two players play a simple game. Each player is provided with a box with balls. First player's box contains exactly n1 balls and second player's box contains exactly n2 balls. In one move first player can take from 1 to k1 balls from his box and throw them away. Similarly, the second player can take from 1 to k2 balls f... | 1 | # your code goes here
from sys import stdin
ar=map(int, stdin.readline().strip().split())
n=ar[0]
m=ar[1]
x=ar[2]
y=ar[3]
if n>m:
print 'First'
else:
print 'Second' |
Jamie has recently found undirected weighted graphs with the following properties very interesting:
* The graph is connected and contains exactly n vertices and m edges.
* All edge weights are integers and are in range [1, 109] inclusive.
* The length of shortest path from 1 to n is a prime number.
* The su... | 3 | n, m = map(int, input().split())
p = 700001
print(p, p)
for i in range(n - 2):
print(i + 1, i + 2, 1)
print(n - 1, n, p - n + 2)
m -= (n - 1)
for i in range(n):
for j in range(i + 2, n):
if m == 0:
exit()
m -= 1
print(i + 1, j + 1, 100000000)
|
The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a pla... | 1 | def mod():
from collections import Counter
n = input()
arr = [ raw_input() for i in xrange(n) ]
a = Counter()
b = []
for i in xrange(n):
nm, s = arr[i].split()
a[nm] += int(s)
b.append((nm, a[nm]))
mx = max(a.values())
print [nm for (nm, s) in b if s >= mx and a[nm] == mx][0]
mod()
|
On a strip of land of length n there are k air conditioners: the i-th air conditioner is placed in cell a_i (1 β€ a_i β€ n). Two or more air conditioners cannot be placed in the same cell (i.e. all a_i are distinct).
Each air conditioner is characterized by one parameter: temperature. The i-th air conditioner is set to ... | 3 | n = int(input())
for i in range(n):
input()
n, k = [int(x) for x in input().split()]
c = [2**32] * n
cond = [int(x) for x in input().split()]
temperatures = [int(x) for x in input().split()]
for i in range(k):
c[cond[i] - 1] = temperatures[i]
p = 2**32
lefts = [0] * n
... |
One day Kefa found n baloons. For convenience, we denote color of i-th baloon as si β lowercase letter of the Latin alphabet. Also Kefa has k friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. Help Kefa to find out, can he give out all his baloons, ... | 3 | ##n = int(input())
##a = list(map(int, input().split()))
##print(' '.join(map(str, res)))
[n, k] = list(map(int, input().split()))
s = input()
h = [0 for i in range(26)]
for i in range(n):
h[ord(s[i])-ord('a')] += 1
hmax = 0
for i in range(26):
hmax = max(hmax, h[i])
if hmax > k:
print('NO')
exit(0)... |
You are given an integer n (n β₯ 0) represented with k digits in base (radix) b. So,
$$$n = a_1 β
b^{k-1} + a_2 β
b^{k-2} + β¦ a_{k-1} β
b + a_k.$$$
For example, if b=17, k=3 and a=[11, 15, 7] then n=11β
17^2+15β
17+7=3179+255+7=3441.
Determine whether n is even or odd.
Input
The first line contains two integers b and... | 3 | b, k = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
n = 0
for i in range(0, k - 1):
n += a[i] * b
if a[k - 1] % 2 != 0:
n += 1
if n % 2 == 0:
print('even')
else:
print('odd')
|
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 | import math
bills = 0
n = int(input())
if(n%100 != n):
bills += math.floor(n/100)
n = n%100
if(n%20 != n):
bills += math.floor(n/20)
n = n%20
if(n%10 != n):
bills += math.floor(n/10)
n = n%10
if(n%5 != n):
bills += math.floor(n/5)
n = n%5
while n > 0:
bills += 1
n -=1
print(bills... |
Given is a positive integer N.
We will choose an integer K between 2 and N (inclusive), then we will repeat the operation below until N becomes less than K.
* Operation: if K divides N, replace N with N/K; otherwise, replace N with N-K.
In how many choices of K will N become 1 in the end?
Constraints
* 2 \leq N ... | 3 | n = int(input())
ans = [n]
if n != 2:
ans.append(n - 1)
for k in range(2, min(n - 1, 1000001)):
tmp = n
while tmp % k == 0:
tmp //= k
tmp %= k
if tmp == 1:
ans.append(k)
if 1000000 < n:
ks = [k for k in ans]
for k in ks:
if k < n - 1 and (n - 1) % k == 0:
... |
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 | a,b,c=map(int,input().split())
d=0
for i in range(1,c+1):
d=d+i*a
if((d-b)>0):
print(d-b)
else:
print("0") |
Vasya wants to turn on Christmas lights consisting of m bulbs. Initially, all bulbs are turned off. There are n buttons, each of them is connected to some set of bulbs. Vasya can press any of these buttons. When the button is pressed, it turns on all the bulbs it's connected to. Can Vasya light up all the bulbs?
If Va... | 3 | buttons, bulbs = map(int, input().split())
all_bulbs = []
for _ in range(buttons):
array = [int(item) for item in input().split()]
for bulb in array[1: ]:
if bulb not in all_bulbs:
all_bulbs.append(bulb)
if len(all_bulbs) == bulbs:
print('YES')
else:
print('NO') |
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())
count = 0
for i in range(n):
temp = input()
if temp.count("+") > 0:
count += 1
else:
count -= 1
print(count) |
As the guys fried the radio station facilities, the school principal gave them tasks as a punishment. Dustin's task was to add comments to nginx configuration for school's website. The school has n servers. Each server has a name and an ip (names aren't necessarily unique, but ips are). Dustin knows the ip and name of ... | 1 | n, m = map(int, raw_input().split())
d = {}
for i in range(n):
v = raw_input().split()
d[v[1]]=v[0]
for j in range(m):
h = raw_input().split()
w = h[1][:len(h[1])-1]
print h[0],h[1],'#'+d[w]
|
Two neighboring kingdoms decided to build a wall between them with some gates to enable the citizens to go from one kingdom to another. Each time a citizen passes through a gate, he has to pay one silver coin.
The world can be represented by the first quadrant of a plane and the wall is built along the identity line (... | 3 | n=int(input())
s=input()
x,y=0,0
bx,by=0,0
cnt=0
for i in range(0,len(s)-1):
if(s[i]=='R'):
x+=1
else:
y+=1
if(x==y):
if(s[i+1]=='R'):
if((x+1-y)*(bx-by)<0):
cnt+=1
else:
if((x-(y+1))*(bx-by)<0):
cnt+=1
bx,by=x,y
pri... |
There are three friend living on the straight line Ox in Lineland. The first friend lives at the point x1, the second friend lives at the point x2, and the third friend lives at the point x3. They plan to celebrate the New Year together, so they need to meet at one point. What is the minimum total distance they have to... | 3 | a = sorted(list(map(int, input().split())))
print(a[2] - a[0]) |
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Bi... | 3 | x=int(input())
c=0
for i in range(1,x) :
if i %2 ==0 :
if (x-i)%2==0 :
print('YES')
c+=1
break
if c==0 :
print('NO')
|
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second.
One day in 230 AD Shapur was trying to find out if any one can possibly do... | 3 | def ultra(slowo1, slowo2):
wynik = ""
for i in range(len(slowo1)):
if slowo1[i] != slowo2[i]:
wynik += "1"
else:
wynik += "0"
return wynik
slowo1 = input()
slowo2 = input()
print(ultra(slowo1, slowo2))
|
A string is called bracket sequence if it does not contain any characters other than "(" and ")". A bracket sequence is called regular if it it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, "", "(())" and "()()" are regular bracket sequences; ")... | 3 | def A():
cnt1 = int(input())
cnt2 = int(input())
cnt3 = int(input())
cnt4 = int(input())
if(cnt4!=cnt1):
print(0)
return
if(cnt3>0 and cnt1==cnt4==0):
print(0)
return
print(1)
A()
|
Mashmokh works in a factory. At the end of each day he must turn off all of the lights.
The lights on the factory are indexed from 1 to n. There are n buttons in Mashmokh's room indexed from 1 to n as well. If Mashmokh pushes button with index i, then each light with index not less than i that is still turned on turn... | 3 | n, m = map(int,input().split())
a = list(map(int, input().split()))
b = []
for i in range(n):
b.append(i+1)
e = []
for x in a:
while len(b) >= x:
b.pop(len(b)-1)
e.append(x)
e.reverse()
for i in range(len(e)):
print(e[i], end = (' '))
|
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 | #a, b = map(int, input().split())
n = list(map(int,input().split("+")))
n.sort()
l = len(n)
for i in range(l):
print(str(n[i]),end="")
if i != l - 1: print("+",end="")
|
You are given an array a[0 β¦ n-1] of length n which consists of non-negative integers. Note that array indices start from zero.
An array is called good if the parity of each index matches the parity of the element at that index. More formally, an array is good if for all i (0 β€ i β€ n - 1) the equality i mod 2 = a[i] m... | 3 | T = int(input())
def solve(arr):
a,b = 0,0
for i in range(0,len(arr)):
if i%2 == 1 and arr[i]%2 == 0:
a += 1
if i%2 == 0 and arr[i]%2 == 1:
b += 1
if a == b:
print(a)
else:
print(-1)
while T>0:
n = int(input())
arr = [int(el) for el in... |
A string t is called an anagram of the string s, if it is possible to rearrange letters in t so that it is identical to the string s. For example, the string "aab" is an anagram of the string "aba" and the string "aaa" is not.
The string t is called a substring of the string s if it can be read starting from some posi... | 1 | s=raw_input();
p=raw_input();
sa=26*[0]
pa=26*[0]
for c in p:
pa[ord(c)-ord('a')]+=1
c=0
qc=0
for i in xrange(len(s)):
if s[i] != '?':
sa[ord(s[i])-ord('a')]+=1
else:
qc+=1
if i >= len(p):
if s[i-len(p)] != '?':
sa[ord(s[i-len(p)])-ord('a')]-=1
else:
qc-=1
if i >= len(p)-1:
sum=0
flag=True
for ... |
Input
The input contains a single integer a (0 β€ a β€ 35).
Output
Output a single integer.
Examples
Input
3
Output
8
Input
10
Output
1024 | 1 | arr = [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]
inp = input()
print arr[inp-1]
|
You are given two strings of equal length s and t consisting of lowercase Latin letters. You may perform any number (possibly, zero) operations on these strings.
During each operation you choose two adjacent characters in any string and assign the value of the first character to the value of the second or vice versa.
... | 3 | for _ in range(int(input())):
a=set(input())
b=set(input())
for i in a:
if i in b:
print("YES")
a={}
break
if a!={}: print("NO") |
You are given a string s. Each character is either 0 or 1.
You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.
You may eras... | 3 | t=int(input())
q=list()
while t>0:
m=0
k=0
s=input()
if(s.count("1")):
loc=s.find("1")
else:
t=t-1
q.append(0)
continue
for item in s[loc:]:
if item=="1":
m+=k
k=0
else:
k+=1
loc+=1
q.append(m)
t-... |
Let quasi-palindromic number be such number that adding some leading zeros (possible none) to it produces a palindromic string.
String t is called a palindrome, if it reads the same from left to right and from right to left.
For example, numbers 131 and 2010200 are quasi-palindromic, they can be transformed to strin... | 3 | #!/usr/bin/env python3
import sys
w = sys.stdin.readline().strip()
a = w.rstrip('0')
b = len(w) - len(a)
c = a.lstrip('0')
d = len(a) - len(c)
if d > b:
print('NO')
else:
if c == c[::-1]:
print('YES')
else:
print('NO') |
Everyone loves a freebie. Especially students.
It is well-known that if in the night before exam a student opens window, opens the student's record-book and shouts loudly three times "Fly, freebie, fly!" β then flown freebie helps him to pass the upcoming exam.
In the night before the exam on mathematical analysis n ... | 3 | n = int(input())
p = list(map(int,input().split()))
T = int(input())
p.sort()
fs = 0
maxx = 0
for i in range(n):
while fs<n and p[fs]-p[i]<=T:
fs+=1
maxx = max(maxx,fs-i)
print(maxx) |
Polycarp has recently created a new level in this cool new game Berlio Maker 85 and uploaded it online. Now players from all over the world can try his level.
All levels in this game have two stats to them: the number of plays and the number of clears. So when a player attempts the level, the number of plays increases... | 3 | t=int(input())
for _ in range(t):
n=int(input())
a,b=0,0
flag=1
for i in range(n):
p,c=map(int,input().split())
if p<a or c<b or p-a<c-b:
flag=0
a,b=p,c
if(flag):
print("YES")
else:
print("NO") |
Valera has got n domino pieces in a row. Each piece consists of two halves β the upper one and the lower one. Each of the halves contains a number from 1 to 6. Valera loves even integers very much, so he wants the sum of the numbers on the upper halves and the sum of the numbers on the lower halves to be even.
To do t... | 3 | import sys
n = int(input())
s1 = 0
s2 = 0
n10 = 0
n01 = 0
for _ in range(n):
x, y = map(int, sys.stdin.readline().split())
s1 += x
s2 += y
if x%2 == 1:
if y%2 == 0:
n10 += 1
elif y%2 == 1:
n01 += 1
if (s1+s2)%2 == 1:
print(-1)
elif s1%2 == 0:
print(0)
elif n10 + n01 > 0:
print(1)
else:
p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.