problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
You are given a rectangular board of M Γ N squares. Also you are given an unlimited number of standard domino pieces of 2 Γ 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squa... | 3 | rect=list(map(int,input().split()))
x=rect[0]*rect[1]
y=2
z=x//y
print(z) |
You are a coach of a group consisting of n students. The i-th student has programming skill a_i. All students have distinct programming skills. You want to divide them into teams in such a way that:
* No two students i and j such that |a_i - a_j| = 1 belong to the same team (i.e. skills of each pair of students in t... | 3 | q = int(input())
for i in range(q):
n = int(input())
a_array = sorted([int(x) for x in input().split()])
team = 0
for j in range(n-1):
if abs(a_array[j] - a_array[j+1]) == 1:
print(2+n-len(set(a_array)))
break
else:
print(1+n-len(set(a_array)))
|
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 | s=input()
j=['H','Q','9']
if(1<=len(s)<=100):
for i in range(len(j)):
if(j[i] in s):
print('YES')
break
else:
print('NO') |
In AtCoder Kingdom, Gregorian calendar is used, and dates are written in the "year-month-day" order, or the "month-day" order without the year.
For example, May 3, 2018 is written as 2018-5-3, or 5-3 without the year.
In this country, a date is called Takahashi when the month and the day are equal as numbers. For exam... | 3 | a,b=map(int,input().split())
if a>b:
print(a-1)
else:
print(a) |
A coordinate line has n segments, the i-th segment starts at the position li and ends at the position ri. We will denote such a segment as [li, ri].
You have suggested that one of the defined segments covers all others. In other words, there is such segment in the given set, which contains all other ones. Now you want... | 3 | n = int(input())
l = n * [0]
r = n * [0]
for i in range(n):
l[i], r[i] = map(int, input().split())
l_min = min(l)
r_max = max(r)
for i in range(n):
if l[i] == l_min and r[i] == r_max:
print(i + 1)
exit()
print(-1) |
Eugeny has array a = a1, a2, ..., an, consisting of n integers. Each integer ai equals to -1, or to 1. Also, he has m queries:
* Query number i is given as a pair of integers li, ri (1 β€ li β€ ri β€ n).
* The response to the query will be integer 1, if the elements of array a can be rearranged so as the sum ali + a... | 1 | n, m = map(int, raw_input().split())
s = raw_input().count('-')
for i in xrange(m):
l, r = map(int, raw_input().split())
print +((r-l) % 2 and r-l < 2*min(s, n-s)) |
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.
Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character... | 3 | s = input()
n = 0
p = 'a'
for c in s:
l = abs(ord(c) - ord(p))
n += min(l, 26 - l)
p = c
print(n)
|
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network.
Bu... | 3 | a=input()
length=len(a)
name=''.join(sorted(a))
count=0
for i in range(1,length,1):
if name[i] == name[i-1]:
count+=1
else:
count=count
temp=length-count
if temp %2 == 0:
print("CHAT WITH HER!")
else:
print("IGNORE HIM!")
|
Tomorrow is a difficult day for Polycarp: he has to attend a lectures and b practical classes at the university! Since Polycarp is a diligent student, he is going to attend all of them.
While preparing for the university, Polycarp wonders whether he can take enough writing implements to write all of the lectures and d... | 3 | import math
t=int(input())
for i in range(t):
a,b,c,d,k=list(map(int,input().split()))
pens=math.ceil(a/c)
pencils=math.ceil(b/d)
if pens+pencils>k:
print(-1)
else:
print(pens,pencils) |
Constanze is the smartest girl in her village but she has bad eyesight.
One day, she was able to invent an incredible machine! When you pronounce letters, the machine will inscribe them onto a piece of paper. For example, if you pronounce 'c', 'o', 'd', and 'e' in that order, then the machine will inscribe "code" onto... | 3 | f = [1, 2]
const = 10 ** 9 + 1
s = input()
if "m" in s or "w" in s:
print(0)
else:
ans = 1
const = 10 ** 9 + 7
check = False
count = 0
if s[0] == "u" or s[0] == "n":
check = True
count = 1
for i in range(1, len(s)):
f.append((f[-1] + f[-2]) % const)
if s[i] ==... |
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them.
Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain nu... | 1 | import re
pat = 'WUB'
s = raw_input()
print re.sub(pat, ' ', s).strip()
|
n children are standing in a circle and playing a game. Children's numbers in clockwise order form a permutation a1, a2, ..., an of length n. It is an integer sequence such that each integer from 1 to n appears exactly once in it.
The game consists of m steps. On each step the current leader with index i counts out ai... | 1 | from collections import Counter
N, M = map(int, raw_input().split())
L = map(int, raw_input().split())
A = [0 for _ in xrange(N)]
for i in xrange(M-1):
p = L[i]
a = (L[i+1] - L[i]) % N
if a == 0:
a = N
if A[p-1] == 0:
A[p-1] = a
elif A[p-1] != a:
print -1
exit()
s... |
Mr. Funt now lives in a country with a very specific tax laws. The total income of mr. Funt during this year is equal to n (n β₯ 2) burles and the amount of tax he has to pay is calculated as the maximum divisor of n (not equal to n, of course). For example, if n = 6 then Funt has to pay 3 burles, while for n = 25 he ne... | 3 | # Author : nitish420 --------------------------------------------------------------------
import os
import sys
from io import BytesIO, IOBase
mod=10**9+7
# sys.setrecursionlimit(10**6)
def isPrime(n) :
if (n <= 1) :
return False
if (n <= 3) :
return True
if (n % 2 == 0 or n % 3 == 0) :
return False
... |
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them.
Input
The first line contains integ... | 3 | n=input()
n=int(n)
s=input()
cnt=0
for i in range(len(s)-1):
if s[i] == s[i + 1]:
cnt+=1
print(cnt) |
The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations:
* d1 is the distance between the 1-st and the 2-nd station;
* d2 is the distance between the 2-nd and the 3-rd station;
...
* dn - 1 is the distance between the n - 1-th and the n-th station;
... | 3 | __author__ = "runekri3"
n = int(input())
distances = list(map(int, input().split()))
s, t = map(int, input().split())
s, t = min(s, t), max(s, t)
if s == t:
print("0")
else:
rightwise_sum = sum(distances[s - 1:t - 1])
leftwise_sum = sum(distances[:s-1]) + sum(distances[t-1:])
print(min(rightwise_sum,... |
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 | st=input()
su=input()
out=[]
if(len(st)==len(su)):
for i in range(len(st)):
if(st[i]==su[i]):
out.append('0')
else:
out.append('1')
for i in range(len(out)):
print(out[i],end="")
|
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 | n = int(input())
for i in range(n):
s = input()
f = s.find('1')
l = s[::-1].find('1')
print(s[f:-(l + 1)].count('0')) |
Search trees are data structures that support dynamic set operations including insert, search, delete and so on. Thus a search tree can be used both as a dictionary and as a priority queue.
Binary search tree is one of fundamental search trees. The keys in a binary search tree are always stored in such a way as to sat... | 3 | class Node:
__slots__ = ['key', 'left', 'right']
def __init__(self, key):
self.key = key
self.left = None
self.right = None
class BST:
def __init__(self):
self.root = None
def insert(self, key):
x = self.root
y = None
z = Node(key)
while x... |
There are n left boots and n right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings l and r, both of length n. The character l_i stands for the color of the i-th left boot and the character r_i stands for the color of the i-th right boot... | 3 | n=int(input())
s=input()
t=input()
fs=[0]*27
ft=[0]*27
for i in range(27):
fs[i]=[]
ft[i]=[]
for i in range(n):
if s[i]=='?':
fs[26].append(i+1)
else:
fs[ord(s[i])-ord('a')].append(i+1)
if t[i]=='?':
ft[26].append(i+1)
else:
ft[ord(t[i])-ord('a')].append(i+1)
pos1=[-1]*(n+1)
pos2=[0]*n
ct=0
for i in range... |
One day Vitaly was going home late at night and wondering: how many people aren't sleeping at that moment? To estimate, Vitaly decided to look which windows are lit in the house he was passing by at that moment.
Vitaly sees a building of n floors and 2Β·m windows on each floor. On each floor there are m flats numbered ... | 3 | n, m = input().split()
c=0
m,n=int(m),int(n)
for i in range(n):
a = list(map(int,input().split()))
for i in range(m):
if a[2*i] or a[2*i+1] : c+=1
print(c)
|
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear a... | 3 | from bisect import bisect_right
def answer(n,A):
ans=[A[0]]
for i in range(1,n):
if ans[-1]<A[i]:
ans.append(A[i])
else:
index=bisect_right(ans,A[i])
ans[index]=A[i]
return len(ans)
n=int(input())
arr=list(map(int,input().split()))
print(ans... |
Mad scientist Mike is busy carrying out experiments in chemistry. Today he will attempt to join three atoms into one molecule.
A molecule consists of atoms, with some pairs of atoms connected by atomic bonds. Each atom has a valence number β the number of bonds the atom must form with other atoms. An atom can form one... | 3 | x,y,z=map(int,input().split())
c=0
while((x+z)!=y):
c+=1
x-=1
z-=1
if(x<0 or z<0):
print("Impossible")
exit()
print(x,z,c) |
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it:
* deletes all the vowels,
* inserts a character "." before each consonant,
* repl... | 1 | vowels = ["A", "O", "Y", "E", "U", "I"]
s = raw_input().lower()
for v in vowels:
s = s.replace(v.lower(), '')
print '.'+'.'.join( list(s) )
|
You are given a rectangular board of M Γ N squares. Also you are given an unlimited number of standard domino pieces of 2 Γ 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squa... | 3 | M,N = map(int,input().split())
S = M*N
if (S%2==0):
b = S//2
print (b)
else:
b = (S//2)
print (b) |
Recently you have bought a snow walking robot and brought it home. Suppose your home is a cell (0, 0) on an infinite grid.
You also have the sequence of instructions of this robot. It is written as the string s consisting of characters 'L', 'R', 'U' and 'D'. If the robot is in the cell (x, y) right now, he can move to... | 3 | for i in range(int(input())):
s=input()
L=s.count('L')
R=s.count('R')
U=s.count('U')
D=s.count('D')
a=min(L,R)
b=min(U,D)
if a==0 and b!=0:b=1
if b==0 and a!=0:a=1
print(a*2+b*2)
print('R'*a+'U'*b+'L'*a+'D'*b ) |
Find the minimum area of a square land on which you can place two identical rectangular a Γ b houses. The sides of the houses should be parallel to the sides of the desired square land.
Formally,
* You are given two identical rectangles with side lengths a and b (1 β€ a, b β€ 100) β positive integers (you are given ... | 3 | t=int(input())
for _ in range(t):
a,b=map(int,input().split())
if 2*min(a,b)>=max(a,b):
print((2*min(a,b))**2)
else:
print((max(a,b))**2)
|
Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they ... | 3 |
n=int(input())
f=[]
for i in range(n):
x=input()
f.append(x)
print("NO")
for i in range(1,n):
a=f[0:i]
if f[i] in a:
print("YES")
else:
print("NO")
|
You are given two integers n and m (m < n). Consider a convex regular polygon of n vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length).
<image> Examples of convex regular polygons
Your task is to say if it is poss... | 3 | t=int(input())
for i in range(t):
n,m=map(int,input().split())
if(m>n):
print("NO")
elif(m==n):
print("YES")
else:
if(n%m==0):
print("YES")
else:
print("NO")
|
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network.
Bu... | 3 | s=input('')
list=[*s]
set_1=set(list)
if (len(set_1))%2==0:
print('CHAT WITH HER!')
else:
print('IGNORE HIM!') |
Let's call a positive integer composite if it has at least one divisor other than 1 and itself. For example:
* the following numbers are composite: 1024, 4, 6, 9;
* the following numbers are not composite: 13, 1, 2, 3, 37.
You are given a positive integer n. Find two composite integers a,b such that a-b=n.
I... | 3 | def isComposite(n):
# Corner cases
if (n <= 1):
return False
if (n <= 3):
return False
# This is checked so that we can skip
# middle five numbers in below loop
if (n % 2 == 0 or n % 3 == 0):
return True
i = 5
while(i * i <= n):
i... |
After returning from the army Makes received a gift β an array a consisting of n positive integer numbers. He hadn't been solving problems for a long time, so he became interested to answer a particular question: how many triples of indices (i, j, k) (i < j < k), such that aiΒ·ajΒ·ak is minimum possible, are there in the... | 3 | def fatorial(n):
if n == 0:
return 1
else:
return fatorial(n-1) * n
qtd = int(input())
valores = list(map(int, input().split()))
valores.sort()
if valores.count(valores[0]) == 1:
if valores.count(valores[1]) == 1:
print(valores.count(valores[2]))
else:
aux = valores.c... |
Utkarsh is forced to play yet another one of Ashish's games. The game progresses turn by turn and as usual, Ashish moves first.
Consider the 2D plane. There is a token which is initially at (0,0). In one move a player must increase either the x coordinate or the y coordinate of the token by exactly k. In doing so, the... | 3 | import sys
import math
input = sys.stdin.readline
t = int(input())
for test in range(t):
#n = int(input())
[d, k] = list(map(int, input().split(" ")))
#a = list(map(int, input().split(" ")))
h = []
#for i in range(d+1):
# h.append(math.floor(math.sqrt(d**2-i**2)))
m = (math.floor(math.sqrt(d**2/2))//k)*k
#p... |
The Fair Nut found a string s. The string consists of lowercase Latin letters. The Nut is a curious guy, so he wants to find the number of strictly increasing sequences p_1, p_2, β¦, p_k, such that:
1. For each i (1 β€ i β€ k), s_{p_i} = 'a'.
2. For each i (1 β€ i < k), there is such j that p_i < j < p_{i + 1} and s... | 3 | s = input()
k = 1
otvet = 1
for i in s:
if i == 'a':
k += 1
elif i == 'b':
otvet *= k
k = 1
print((otvet * k - 1) % (10 ** 9 + 7)) |
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th... | 3 | word=input()
u=0
l=0
for c in word:
if c.isupper():
u+=1
else:
l+=1
if l>=u:
print(word.lower())
else:
print(word.upper()) |
Let's call a string a phone number if it has length 11 and fits the pattern "8xxxxxxxxxx", where each "x" is replaced by a digit.
For example, "80123456789" and "80000000000" are phone numbers, while "8012345678" and "79000000000" are not.
You have n cards with digits, and you want to use them to make as many phone n... | 3 | n = int(input())
s = input()
c8 = s.count('8')
re = n-c8
t = n//11
print(min(c8,t))
|
Given is an integer x that is greater than or equal to 0, and less than or equal to 1. Output 1 if x is equal to 0, or 0 if x is equal to 1.
Constraints
* 0 \leq x \leq 1
* x is an integer
Input
Input is given from Standard Input in the following format:
x
Output
Print 1 if x is equal to 0, or 0 if x is equal ... | 3 | print(0 if input() == '1' else 1) |
Recently Polycarp noticed that some of the buttons of his keyboard are malfunctioning. For simplicity, we assume that Polycarp's keyboard contains 26 buttons (one for each letter of the Latin alphabet). Each button is either working fine or malfunctioning.
To check which buttons need replacement, Polycarp pressed som... | 3 | #n = int(input())
n = 0
for i in range(n):
l, r = [int(i) for i in input().split()]
k = 0
if l == 0:
l = 1
for j in range(l + 1, r + 1):
k += (2 ** bin(j).split("0b")[1].count("0") - l) * 2
print(k)
n = int(input())
for i in range(n):
a = input()
sim = ""
k = 0
ans =... |
You are given a positive integer N. Find the minimum positive integer divisible by both 2 and N.
Constraints
* 1 \leq N \leq 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
Output
Print the minimum positive integer divisible by both 2 and N.
Example... | 3 | n=int(input())
if n%2:print(2*n)
else:print(n) |
Bob is playing with 6-sided dice. A net of such standard cube is shown below.
<image>
He has an unlimited supply of these dice and wants to build a tower by stacking multiple dice on top of each other, while choosing the orientation of each dice. Then he counts the number of visible pips on the faces of the dice.
Fo... | 3 | # from collections import defaultdict
t=int(input())
x=list(map(int,input().strip().split()))
for i in range(t):
a=x[i]%14
b=x[i]//14
if(b>0 and a>0 and a<=6):
print("YES")
else:
print("NO") |
Vasya is writing an operating system shell, and it should have commands for working with directories. To begin with, he decided to go with just two commands: cd (change the current directory) and pwd (display the current directory).
Directories in Vasya's operating system form a traditional hierarchical tree structure... | 1 | n = int(raw_input())
cur = []
def apply(path, lst):
res = path
for dir in lst:
if dir == "..":
if len(res) != 0:
res.pop()
else:
res.append(dir)
return res
for i in xrange(n):
raw = raw_input().split()
if raw[0] == "pwd":
buf = '/'
... |
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 | m = int(input())
for i in range(m):
inp = input()
st = ""
if len(inp)>10:
st = inp[0]
st += str(len(inp)-2)
st += inp[len(inp)-1]
print(st)
else:
print(inp)
|
The 9-th grade student Gabriel noticed a caterpillar on a tree when walking around in a forest after the classes. The caterpillar was on the height h1 cm from the ground. On the height h2 cm (h2 > h1) on the same tree hung an apple and the caterpillar was crawling to the apple.
Gabriel is interested when the caterpill... | 3 | h1, h2= tuple(map(int, input().split()))
a, b= tuple(map(int, input().split()))
"""
a =2 #ΡΠΊΠΎΡΠΎΡΡΡ Π²Π²Π΅ΡΡ
b =1 #ΡΠΊΠΎΡΠΎΡΡΡ ΡΠΏΠΎΠ»Π·Π°Π½ΠΈΡ
h1 =1 #ΡΡΠ°ΡΡ ΡΠ΅ΡΠ²Ρ
h2 =300 #Π²ΡΡΠΎΡΠ° ΡΠ±Π»ΠΎΠΊΠ°
r = a #ΠΏΠ΅ΡΠ΅ΠΌΠ΅Π½Π½Π°Ρ ΡΠ΅ΠΊΡΡΠ΅Π³ΠΎ ΠΏΠΎΠ»ΠΎΠΆΠ΅Π½ΠΈΡ
"""
#if h2 < h1: #ΠΏΡΠ²Π΅ΡΡΠ΅ΠΌ ΠΊΠΎΡΡΠ΅ΠΊΡΠ½ΠΎΡΡΡ Π΄Π²ΠΈΠΆΠ΅Π½ΠΈΡ Π²Π²Π΅ΡΡ
#print('false')
day = 0
r = a*8+h1 #Π² ΠΏΠ΅ΡΠ²ΡΠΉ Π΄Π΅... |
Phoenix is playing with a new puzzle, which consists of n identical puzzle pieces. Each puzzle piece is a right isosceles triangle as shown below.
<image> A puzzle piece
The goal of the puzzle is to create a square using the n pieces. He is allowed to rotate and move the pieces around, but none of them can overlap an... | 3 | import os
from io import BytesIO, IOBase
import sys
import math
def main():
for j in range(int(input())):
n=int(input())
if n%2!=0:
print("NO")
else:
c=0
if int(math.sqrt(n//2))**2==n//2:
c=c+1
elif n%4==0 and int(math.sqrt(n//4))**2==n//4:
... |
Given N integers A_1, ..., A_N, compute A_1 \times ... \times A_N.
However, if the result exceeds 10^{18}, print `-1` instead.
Constraints
* 2 \leq N \leq 10^5
* 0 \leq A_i \leq 10^{18}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 ... A_N
Output
P... | 3 | _, *a = map(int, open(0).read().split())
ret = 1
for x in sorted(a):
ret *= x
if ret > 10 ** 18:
ret = -1; break
print(ret) |
Takahashi has N cards. The i-th of these cards has an integer A_i written on it.
Takahashi will choose an integer K, and then repeat the following operation some number of times:
* Choose exactly K cards such that the integers written on them are all different, and eat those cards. (The eaten cards disappear.)
For... | 3 | import sys
from collections import Counter
sys.setrecursionlimit(10 ** 6)
input = sys.stdin.readline
def main():
n = int(input())
aa = list(map(int, input().split()))
aa = list(Counter(aa).values())
aa.sort()
cs = [0]
s = 0
for a in aa:
s += a
cs += [s]
# print(aa)
... |
Takahashi made N problems for competitive programming. The problems are numbered 1 to N, and the difficulty of Problem i is represented as an integer d_i (the higher, the harder).
He is dividing the problems into two categories by choosing an integer K, as follows:
* A problem with difficulty K or higher will be for ... | 3 | n=int(input())
d=list(map(int,input().split()))
d.sort()
t=d[n//2]-d[n//2 -1]
print(t)
|
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 | #n = int(input())
out = ""
s = input()
if len(s) != 1:
arr = s.split('+')
arr.sort()
for i in range(len(arr)):
if i != len(arr)-1:
out += arr[i]+'+'
else:
out += arr[i]
print(out)
else:
print(s)
|
Polycarp has built his own web service. Being a modern web service it includes login feature. And that always implies password security problems.
Polycarp decided to store the hash of the password, generated by the following algorithm:
1. take the password p, consisting of lowercase Latin letters, and shuffle the l... | 3 | for i in range(int(input())):
s = input()
hesh = input()
symbols = list(sorted(set(s)))
kolvo = []
ans = 0
for i in range(len(symbols)):
kolvo.append(s.count(symbols[i]))
for i in range(len(hesh)-len(s)+1):
start = i
end = len(s)+i
s_kolvo = []
new_hes... |
The sequence of m integers is called the permutation if it contains all integers from 1 to m exactly once. The number m is called the length of the permutation.
Dreamoon has two permutations p_1 and p_2 of non-zero lengths l_1 and l_2.
Now Dreamoon concatenates these two permutations into another sequence a of length... | 3 | for t in range(int(input())):
n = int(input())
ar = list(map(int,input().split()))
mx = max(ar)
d=[]
for c in range(2):
if set(ar[:mx])==set(range(1,mx+1)) and set(ar[mx:])==set(range(1,n-mx+1)):
d.append(mx)
mx = n-mx
d = set(d)
print(len(d))
for x in d:
... |
A few years ago Sajjad left his school and register to another one due to security reasons. Now he wishes to find Amir, one of his schoolmates and good friends.
There are n schools numerated from 1 to n. One can travel between each pair of them, to do so, he needs to buy a ticket. The ticker between schools i and j co... | 1 | n=int(raw_input())
val=int(n/2)
if n%2==0:
print val-1
else:
print val |
For a given sequence of integers $A = \\{a_0, a_1, ..., a_{n-1}\\}$, perform the following operations.
* count($b, e, k$): print the number of the specific values $k$ in $a_b, a_{b+1}, ..., a_{e-1}$.
Constraints
* $1 \leq n \leq 1,000$
* $-1,000,000,000 \leq a_i, k_i \leq 1,000,000,000$
* $1 \leq q \leq 1,000$
* $0 ... | 3 | n = int(input())
l = list(map(int, input().split()))
q = int(input())
for i in range(q):
b, e, k = map(int, input().split())
print(l[b:e].count(k))
|
So the Beautiful Regional Contest (BeRC) has come to an end! n students took part in the contest. The final standings are already known: the participant in the i-th place solved p_i problems. Since the participants are primarily sorted by the number of solved problems, then p_1 β₯ p_2 β₯ ... β₯ p_n.
Help the jury distrib... | 3 | from bisect import bisect_right
def find_le(a, x):
'Find rightmost value less than or equal to x'
i = bisect_right(a, x)
return a[i-1]
def solve(drop_idx):
if len(drop_idx) < 3:
return (0, 0, 0)
g = drop_idx[0]
b = find_le(drop_idx, n//2)
s = -1
for idx in drop_idx:
if idx - g > g and b ... |
A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all n squad soldiers to line up on the parade ground.
By the military charter the soldiers should stand in the order of non-increasing of their h... | 3 | n = int(input())
nums_1 = input()
nums_1 = nums_1.split()
for i in range(n):
nums_1[i] = int(nums_1[i])
nums_2 = sorted(nums_1)
num_mayor = nums_2[n-1]
ind_mayor = 0
num_menor = nums_2[0]
ind_menor = 0
z = 0
for i in range(n):
if nums_1[i] == num_menor:
ind_menor = i
if nums_1[i] == num_mayor and z ... |
Give a pair of integers (A, B) such that A^5-B^5 = X. It is guaranteed that there exists such a pair for the given integer X.
Constraints
* 1 \leq X \leq 10^9
* X is an integer.
* There exists a pair of integers (A, B) satisfying the condition in Problem Statement.
Input
Input is given from Standard Input in the fo... | 3 | A= int(input())
for i in range(-119,119):
for j in range(-119,119):
if i**5-j**5 == A:
print(i,j)
exit() |
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them.
Input
The first line contains integ... | 3 |
n = int(input())
color = input()
counter = 0
for i in range (len(color)):
if i+1 < len(color) and color[i] + color[i+1] in ["RR", "GG", "BB"]:
counter += 1
else:
counter = counter
print(counter)
|
Petya and Vasya are playing a game. Petya's got n non-transparent glasses, standing in a row. The glasses' positions are indexed with integers from 1 to n from left to right. Note that the positions are indexed but the glasses are not.
First Petya puts a marble under the glass in position s. Then he performs some (pos... | 1 | '''
n, s, t = map(int, raw_input().split())
p = [0] + map(int, raw_input().split())
flag = [False]*(n+1)
cnt = 0
bp = s
while True:
if flag[bp] == True:
cnt = -1
break
if t == bp:
break
flag[bp] = True
bp = p[bp]
cnt += 1
print cnt
'''
from sys import stdin
def line():
... |
A permutation of length n is a sequence of integers from 1 to n of length n containing each number exactly once. For example, [1], [4, 3, 5, 1, 2], [3, 2, 1] are permutations, and [1, 1], [0, 1], [2, 2, 1, 4] are not.
There was a permutation p[1 ... n]. It was merged with itself. In other words, let's take two instanc... | 3 | T = int(input())
for _ in range(T):
n = int(input())
arr = list(map(int,input().split()))
mapp = {}
Str = []
for i in arr:
if (i not in mapp):
Str.append(i)
mapp[i] = 1
print(*Str,sep=" ") |
You planned a trip using trains and buses. The train fare will be A yen (the currency of Japan) if you buy ordinary tickets along the way, and B yen if you buy an unlimited ticket. Similarly, the bus fare will be C yen if you buy ordinary tickets along the way, and D yen if you buy an unlimited ticket.
Find the minimu... | 1 | print eval('+min(%s)'%('input(),'*2)*2) |
As every other little boy, Mike has a favorite toy to play with. Mike's favorite toy is a set of N disks. The boy likes to compose his disks in stacks, but there's one very important rule: the disks in a single stack must be ordered by their radiuses in a strictly increasing order such that the top-most disk will have ... | 1 | def bs(k,start,end,search):
mid =(start+end)/2
if(start==mid):
if(k[mid]>search):
k[mid] = search
else:
k[end] = search
return 0
# if(start == end):
# if(k[start] >search):
# k[start] = search
# else:
# k[start+1] = sear... |
Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be n problems, sorted by difficulty, i.e. problem 1 is the easiest and problem n is the hardest. Limak knows it will take him 5Β·i minutes to solve the i-th... | 1 | n,k = map(int, raw_input().split())
t = 240-k
c = 0
i = 1
while t>=5*i:
t-=5*i
i+=1
c+=1
#print t
print min(n,c)
|
Summer holidays! Someone is going on trips, someone is visiting grandparents, but someone is trying to get a part-time job. This summer Noora decided that she wants to earn some money, and took a job in a shop as an assistant.
Shop, where Noora is working, has a plan on the following n days. For each day sales manager... | 3 | x,y=map(int,input().split())
n=0
d=[0]*x
f=[]
for i in range(x):
a,b=map(int,input().split())
if b<a:
n=n+b
else:
n=n+a
if b>a:
if a*2<b:
d[i]=a
else:
d[i]=b-a
if d!=f:
d.sort()
for i in range(1,y+1):
n=n+d[-i]
print(n)
|
A permutation is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as pi. We'll call number n the size of permutation p1, p2, ..., pn.
Nickolas adores permutations. He likes some permutations more than the o... | 1 | n = input()
if n&1:
print -1
else:
i = 0
l = range(1, n+1)
while i < n:
l[i], l[i+1] = l[i+1], l[i]
i += 2
for _ in l:
print _, |
Let's call an array good if there is an element in the array that equals to the sum of all other elements. For example, the array a=[1, 3, 3, 7] is good because there is the element a_4=7 which equals to the sum 1 + 3 + 3.
You are given an array a consisting of n integers. Your task is to print all indices j of this a... | 3 | n=int(input())
h=list(map(int,input().split()))
def findall(lis,i):
output=[]
for r in range(len(lis)):
if lis[r]==i:
output.append(r+1)
return(output)
maximum=max(h)
tichu=-2*maximum+sum(h)
output=findall(h,tichu)
if h.index(maximum)+1 in output:
output.remove(h.index(maximum)+1)
hi... |
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 | #!/usr/bin/env python3
n = int(input())
x = 0
for n in range(n):
st = input()
if(st == 'X++' or st == '++X'):
x += 1
elif(st == 'X--' or st == '--X'):
x -= 1
print(x)
|
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr... | 3 | from sys import stdin
a, b = (stdin.readline().strip().upper() for _ in (0, 0))
print(-1 if a < b else 1 if a > b else 0)
|
You survived several months of exam wars and were able to enter ICPC University on a sunny day. On the day of admission, there was an enthusiastic recruitment of circles on the campus of the university, and you received a large number of pamphlets and returned. When you return to your room, you find one of the pamphlet... | 3 | while 1:
n=int(input())*2
if n==0:break
i,c=2,0
while i*i<n:
if not(n%i) and n//i%2!=i&1:c+=1
i+=1
print(c) |
From 1603 to 1867, people call that era the EDO era. EDO stands for Enhanced Driving Operation, the most advanced space navigation technology at the time, and was developed by Dr. Izy in 1603.
You are a space adventurer, flying around the universe and adventuring on various planets. During that adventure, you discover... | 3 | while True:
n = int(input())
if n==0:
break
grid = [[0 for i in range(21)] for i in range(21)]
for i in range(n):
x, y = list(map(int, input().split()))
grid[x][y] = 1
x, y = 10, 10
grid[x][y] = 0
m = int(input())
for i in range(m):
d, l = input().split()
l = int(l)
nx, ny = x,... |
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 | while True:
w = input()
if w.isdecimal() == True:
w = int(w)
if w >= 1 and w <= 100 :
break
if w % 2 == 0 and w != 2:
print("YES")
else:
print("NO") |
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the... | 3 | def minimumRoadWidth(n, h, a):
width = 0
for height in a:
if height > h:
width += 2
else:
width += 1
return width
n, h = input().split()
n, h = int(n), int(h)
a = input().split()
a = (int(x) for x in a)
print(minimumRoadWidth(n, h, a)) |
In the Bus of Characters there are n rows of seat, each having 2 seats. The width of both seats in the i-th row is w_i centimeters. All integers w_i are distinct.
Initially the bus is empty. On each of 2n stops one passenger enters the bus. There are two types of passengers:
* an introvert always chooses a row whe... | 3 | 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 = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.wri... |
Nothing is eternal in the world, Kostya understood it on the 7-th of January when he saw partially dead four-color garland.
Now he has a goal to replace dead light bulbs, however he doesn't know how many light bulbs for each color are required. It is guaranteed that for each of four colors at least one light is workin... | 3 | s=input()
r=s.index('R')%4
b=s.index('B')%4
y=s.index('Y')%4
g=s.index('G')%4
l=[0,0,0,0]
n=len(s)
for i in range(n):
if(s[i]=='!'):
l[i%4]+=1
print("{0} {1} {2} {3}".format(l[r],l[b],l[y],l[g])) |
For a given positive integer n denote its k-rounding as the minimum positive integer x, such that x ends with k or more zeros in base 10 and is divisible by n.
For example, 4-rounding of 375 is 375Β·80 = 30000. 30000 is the minimum integer such that it ends with 4 or more zeros and is divisible by 375.
Write a program... | 3 | def GCD(a,b):
if b>a:
a,b=b,a
while not b==0:
a,b=b,a%b
return(a)
def LCM(c,d):
e=c*d
return(e/GCD(c,d))
n, k = input().strip().split()
v=10**int(k)
print(int(LCM(int(n),v))) |
There are an integer sequence A_1,...,A_N consisting of N terms, and N buttons. When the i-th (1 β¦ i β¦ N) button is pressed, the values of the i terms from the first through the i-th are all incremented by 1.
There is also another integer sequence B_1,...,B_N. Takahashi will push the buttons some number of times so th... | 3 | n = int(input())
A, B = zip(*[tuple(map(int, input().split()))for _ in range(n)])
cnt = 0
for a, b in zip(A[::-1], B[::-1]):
cnt += -(-(cnt+a)//b)*b-(cnt+a)
print(cnt)
|
Sereja has an array a, consisting of n integers a1, a2, ..., an. The boy cannot sit and do nothing, he decided to study an array. Sereja took a piece of paper and wrote out m integers l1, l2, ..., lm (1 β€ li β€ n). For each number li he wants to know how many distinct numbers are staying on the positions li, li + 1, ...... | 1 | n,t = map(int,raw_input().split())
b = map(int,raw_input().split())
a = set()
l = [0] * n
for i in range(len(b) - 1, -1, -1):
a.add(b[i])
l[i] = len(a)
while t > 0:
q = int(raw_input())
q -= 1
print l[q]
t -= 1 |
While Vasya finished eating his piece of pizza, the lesson has already started. For being late for the lesson, the teacher suggested Vasya to solve one interesting problem. Vasya has an array a and integer x. He should find the number of different ordered pairs of indexes (i, j) such that ai β€ aj and there are exactly ... | 3 | from bisect import bisect_left
R=lambda:map(int,input().split())
n,x,k=R()
a=sorted(R())
print(sum(bisect_left(a,l+x)-bisect_left(a,max(u,l)) for u,l in ((u,((u-1)//x+k)*x) for u in a)))
# Made By Mostafa_Khaled |
You are given a string s of length n, which consists only of the first k letters of the Latin alphabet. All letters in string s are uppercase.
A subsequence of string s is a string that can be derived from s by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD... | 3 | from sys import stdin
from os import getenv
if getenv('ACM_ENV') == 'local': stdin = open('input.txt', 'r')
n, k = [int(x) for x in stdin.readline().split(" ")]
s = stdin.readline().strip()
chars = [0 for i in range(k)]
for c in s:
chars[ord(c) - ord('A')] += 1
m = n
for c in chars:
m = min(c, m)
print(m * ... |
The Resistance is trying to take control over all planets in a particular solar system. This solar system is shaped like a tree. More precisely, some planets are connected by bidirectional hyperspace tunnels in such a way that there is a path between every pair of the planets, but removing any tunnel would disconnect s... | 3 | import sys
import math
import bisect
def main():
n = int(input())
A = [0] * n
for i in range(n - 1):
a, b = map(int, input().split())
A[a-1] += 1
A[b-1] += 1
ans = 0
for i in range(n):
if A[i] == 1:
ans += 1
print(ans)
if __name__ == "__main__":
... |
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution.... | 3 | input1 = int(input())
i = 0
solvable = 0
while i < input1:
inputs = str(input())
counter = 0
for letter in inputs:
if letter == '1':
counter += 1
if counter >= 2:
solvable += 1
i += 1
print(solvable) |
You're given a row with n chairs. We call a seating of people "maximal" if the two following conditions hold:
1. There are no neighbors adjacent to anyone seated.
2. It's impossible to seat one more person without violating the first rule.
The seating is given as a string consisting of zeros and ones (0 means... | 3 | def pairs(a):
prev = 't'
for x in a:
if prev != 't':
yield prev,x
prev = x
def zeropair(p1,p2):
if p1[1] == str(0) and p1[0] == str(0) and p2[0] == str(0) and p2[1] == str(0):
return True
else: return False
b=int(input()) == 1
a = input()
lp = (1,1)
for x in pairs(a):... |
Given is a string S consisting of `L` and `R`.
Let N be the length of S. There are N squares arranged from left to right, and the i-th character of S from the left is written on the i-th square from the left.
The character written on the leftmost square is always `R`, and the character written on the rightmost square... | 3 | s = input()
n = len(s)
ans = [1]*n
for i in range(0, n-2):
if s[i] == "R" and s[i+1] == "R":
ans[i+2] += ans[i]
ans[i] = 0
for i in range(n-1, -1, -1):
if s[i] == "L" and s[i-1] == "L":
ans[i-2] += ans[i]
ans[i] = 0
print(*ans) |
Fafa owns a company that works on huge projects. There are n employees in Fafa's company. Whenever the company has a new project to start working on, Fafa has to divide the tasks of this project among all the employees.
Fafa finds doing this every time is very tiring for him. So, he decided to choose the best l employ... | 3 | n = int(input())
ans = 0
for i in range(2, n + 1):
if n % i == 0:
ans += 1
print(ans) |
A New Year party is not a New Year party without lemonade! As usual, you are expecting a lot of guests, and buying lemonade has already become a pleasant necessity.
Your favorite store sells lemonade in bottles of n different volumes at different costs. A single bottle of type i has volume 2i - 1 liters and costs ci r... | 3 | n, li = map(int, input().split())
c = list(map(int, input().split()))
for i in range(n-1):
if c[i] * 2 < c[i+1]:
c[i+1] = c[i] * 2
for i in range(n-2, -1, -1):
if c[i] > c[i+1]:
c[i] = c[i+1]
'''
p = c[0] * li
for i in range(n):
if 2**i >= li and p > c[i]:
p = c[i]
'''
i = n - 1
ans = 0
a = []
while li > 0:... |
You've got a 5 Γ 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix:
1.... | 3 | li = []
r = 0
col =0
mov=0
for i in range(5):
li.append(list(map(int,input().strip().split())))
#print(li)
for j in range(5):
if(li[i][j]==1):
r=i+1
col=j+1
if(r>3):
mov+=r-3
elif(r<3):
mov+=3-r
if(col>3):
mov+=col-3
elif(col<3):
mov+=3-col
print(mov) |
You have a plate and you want to add some gilding to it. The plate is a rectangle that we split into wΓ h cells. There should be k gilded rings, the first one should go along the edge of the plate, the second one β 2 cells away from the edge and so on. Each ring has a width of 1 cell. Formally, the i-th of these rings ... | 3 | w,h,k = map(int, input().split())
s = 0
i = 0
while i != k:
s += (w*h)-((w-2)*(h-2))
w -= 4
h -= 4
i += 1
print(s)
|
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,math
input=sys.stdin.readline
t=int(input())
for r in range(t):
n, k = map(int,input().split())
s = input().strip("\n")
ans = 0
l = []
for i in s:
l.append(i)
intervals = []
i = 0
left = []
right = []
while i < n:
if l[i] == "W":
i += 1
... |
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 | SS = int(input())
ans = set(list(map(int,input().split()))[1:])
for s in range(SS-1):
ans = ans.intersection(set(list(map(int,input().split()))[1:]))
for a in ans:
print(a,end=' ') |
Alice and Bob are decorating a Christmas Tree.
Alice wants only 3 types of ornaments to be used on the Christmas Tree: yellow, blue and red. They have y yellow ornaments, b blue ornaments and r red ornaments.
In Bob's opinion, a Christmas Tree will be beautiful if:
* the number of blue ornaments used is greater b... | 3 | y, b, r = map(int, input().split(" "))
r = r - 2
b = b - 1
y = min(y, b, r)
print(3 * y + 3)
|
Input Format
N K
a_1 a_2 a_3 ... a_N
Output Format
Print the minimum cost in one line. In the end put a line break.
Constraints
* 1 β€ K β€ N β€ 15
* 1 β€ a_i β€ 10^9
Scoring
Subtask 1 [120 points]
* N = K
Subtask 2 [90 points]
* N β€ 5
* a_i β€ 7
Subtask 3 [140 points]
* There are no additional constraint... | 3 | n,k=map(int,input().split())
a=list(map(int,input().split()))
ans = 10**12
for b in range(1<<n):
c = 0
for i in range(n):
if ((b>>i)&1) == 1:
c += 1
if c != k: continue
t = 0
h = 0
for i in range(n):
if ((b>>i)&1) == 0:
h = max(h, a[i])
contin... |
You are given 4n sticks, the length of the i-th stick is a_i.
You have to create n rectangles, each rectangle will consist of exactly 4 sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only... | 3 | q = int(input())
for i in range(q):
n = int(input())
cnt = dict()
now = list(map(int, input().split()))
for j in range(4 * n):
cnt[now[j]] = cnt.get(now[j], 0) + 1
cnt = sorted(list(cnt.items()))
f, s = 0, len(cnt) - 1
ans = cnt[0][0] * cnt[-1][0]
good = True
while f <= s and... |
Drazil is playing a math game with Varda.
Let's define <image> for positive integer x as a product of factorials of its digits. For example, <image>.
First, they choose a decimal number a consisting of n digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then th... | 3 | _ = input()
s = input()
print(''.join(sorted(s.replace('1','').replace('0','').replace('4','322').replace('6','53').replace('8','7222').replace('9','7332'),reverse=True))) |
Takahashi and Aoki will have a battle using their monsters.
The health and strength of Takahashi's monster are A and B, respectively, and those of Aoki's monster are C and D, respectively.
The two monsters will take turns attacking, in the order Takahashi's, Aoki's, Takahashi's, Aoki's, ... Here, an attack decreases ... | 3 | a,b,c,d=map(int,input().split())
a-=1
c-=1
ta=a//d
ao=c//b
print('Yes' if ta>=ao else 'No') |
Two players decided to play one interesting card game.
There is a deck of n cards, with values from 1 to n. The values of cards are pairwise different (this means that no two different cards have equal values). At the beginning of the game, the deck is completely distributed between players such that each player has a... | 3 | for _ in range(int(input())):
n,f,g=map(int,input().split())
f1=list(map(int,input().split()))
f2=list(map(int,input().split()))
if max(f1)>max(f2):
print("YES")
else:
print("NO")
|
It is lunch time at the Vibrant Gujarat Summit and all the investors are called for the executive lunch. When Bruce reached the lunch area, he found that the waiter was taking out bowls from a big box containing some amount of golden bowls and other bronze bowls. The bowls were taken out at random. Each dish contains e... | 1 | def f(val,t):
return val*(val-1)-(t*(t-1))/2;
def solve(t) :
lo=0;
hi=t;
while lo<=hi:
mid=(lo+hi)/2;
if (f(mid,t)<0):
lo=mid+1;
elif (f(mid,t)==0):
print(mid);
return;
else :
hi=mid-1;
t=int(raw_input());
solve(t); |
Little Susie, thanks to her older brother, likes to play with cars. Today she decided to set up a tournament between them. The process of a tournament is described in the next paragraph.
There are n toy cars. Each pair collides. The result of a collision can be one of the following: no car turned over, one car turned ... | 3 | n = int(input())
goodcars = []
for i in range(n):
a = [int(c) for c in input().split()]
good = True
for j in range(n):
if a[j] == 1 or a[j]==3:
good = False
break
if good:
goodcars.append(i+1)
print(len(goodcars))
if (len(goodcars) > 0):
print(' '.join(str(c... |
Tak performed the following action N times: rolling two dice. The result of the i-th roll is D_{i,1} and D_{i,2}.
Check if doublets occurred at least three times in a row. Specifically, check if there exists at lease one i such that D_{i,1}=D_{i,2}, D_{i+1,1}=D_{i+1,2} and D_{i+2,1}=D_{i+2,2} hold.
Constraints
* 3 \... | 3 | N=int(input())
j=0
J=0
for i in range(N):
D1,D2=map(int,input().split())
if D1==D2:
j+=1
if j>=3:
J=3
else:
j=0
if J>=3:
print('Yes')
else:
print('No') |
There are n cities in Bearland, numbered 1 through n. Cities are arranged in one long row. The distance between cities i and j is equal to |i - j|.
Limak is a police officer. He lives in a city a. His job is to catch criminals. It's hard because he doesn't know in which cities criminals are. Though, he knows that ther... | 3 | n, k = map(int, input().split(' '))
cities = list(map(int, input().split(' ')))
left, right, ans = k - 1 - 1, k, 1 if cities[k - 1] else 0
while left >= 0 and right < n:
ans += 2 if cities[left] and cities[right] else 0
left -= 1
right += 1
while left >= 0:
ans += (cities[left] == 1)
left -= 1
while... |
Ternary numeric notation is quite popular in Berland. To telegraph the ternary number the Borze alphabet is used. Digit 0 is transmitted as Β«.Β», 1 as Β«-.Β» and 2 as Β«--Β». You are to decode the Borze code, i.e. to find out the ternary number given its representation in Borze alphabet.
Input
The first line contains a nu... | 3 | code = input()
zero = '.'
one = '-.'
two = '--'
code = code.replace(two, '2')
code = code.replace(one, '1')
code = code.replace(zero, '0')
print(code) |
You are given two arrays of integers a_1,β¦,a_n and b_1,β¦,b_m.
Your task is to find a non-empty array c_1,β¦,c_k that is a subsequence of a_1,β¦,a_n, and also a subsequence of b_1,β¦,b_m. If there are multiple answers, find one of the smallest possible length. If there are still multiple of the smallest possible length, f... | 3 | t = int(input())
for x in range(t):
n, m = map(int, input().split())
na = list(map(int, input().split()))
ma = list(map(int, input().split()))
if n>m:
a = ma
b = na
else:
a = na
b = ma
for y in range(len(a)):
if a[y] in b:
print("YES")
... |
Alice guesses the strings that Bob made for her.
At first, Bob came up with the secret string a consisting of lowercase English letters. The string a has a length of 2 or more characters. Then, from string a he builds a new string b and offers Alice the string b so that she can guess the string a.
Bob builds b from a... | 3 | n=int(input())
for i in range(0,n):
text=input()
listy = ""
lent=len(text)
if(lent==2):
print(text)
else:
for i in range(0,lent,2):
listy+=text[i]
listy+=text[lent-1]
print(listy) |
Ilya is a very clever lion, he lives in an unusual city ZooVille. In this city all the animals have their rights and obligations. Moreover, they even have their own bank accounts. The state of a bank account is an integer. The state of a bank account can be a negative number. This means that the owner of the account ow... | 3 | #6-A. Ilya and Bank Account
s = input()
a = ''
b = ''
if int(s) > 0 :
print(s)
exit()
else:
a = s[:-1]
b = s[:-2] + s[-1]
#print(a)
#print(b)
if a == '-0': a = '0'
if b == '-0': b = '0'
if int(a) > int(b):
print(a)
else:
print(b)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.