problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
The sequence of integers a_1, a_2, ..., a_k is called a good array if a_1 = k - 1 and a_1 > 0. For example, the sequences [3, -1, 44, 0], [1, -99] are good arrays, and the sequences [3, 7, 8], [2, 5, 4, 1], [0] — are not.
A sequence of integers is called good if it can be divided into a positive number of good arrays.... | 1 | n = int(raw_input())
nums = list(map(int,raw_input().split()))
dp = [0 for x in range(n)]
combs = [[0 for x in range(1001)] for x in range(1001)]
for i in range(1001):
for j in range(i+1):
if not j:
combs[i][j] = 1
elif j:
combs[i][j] = combs[i-1][j]+combs[i-1][j-1]
for i in range(n-1,-1,-1):
if... |
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 | vasyaInput = input()
upperLetter = 0
lowerLetter = 0
for ch in vasyaInput:
if ch.isupper():
upperLetter += 1
elif ch.islower():
lowerLetter += 1
if lowerLetter >= upperLetter:
print(vasyaInput.lower())
else:
print(vasyaInput.upper())
|
Xenia lives in a city that has n houses built along the main ringroad. The ringroad houses are numbered 1 through n in the clockwise order. The ringroad traffic is one way and also is clockwise.
Xenia has recently moved into the ringroad house number 1. As a result, she's got m things to do. In order to complete the i... | 3 | first = input()
second = input()
n = int(str(first).split(' ')[0])
m = int(str(first).split(' ')[1])
ts = [1] + [int(i) for i in str(second).split(' ')]
sum = 0
for i in range(0, m):
sum += (ts[i+1] - ts[i]) % n
print(sum) |
You are the gym teacher in the school.
There are n students in the row. And there are two rivalling students among them. The first one is in position a, the second in position b. Positions are numbered from 1 to n from left to right.
Since they are rivals, you want to maximize the distance between them. If students a... | 3 | t=int(input())
while t>0:
n,x,a,b=map(int,input().split())
if a>b:
tmp=a
a=b
b=tmp
tmp=min(x,a-1)
a-=tmp
x-=tmp
tmp=min(x,n-b)
b+=tmp
print(b-a)
t-=1 |
You are given a positive integer n, it is guaranteed that n is even (i.e. divisible by 2).
You want to construct the array a of length n such that:
* The first n/2 elements of a are even (divisible by 2);
* the second n/2 elements of a are odd (not divisible by 2);
* all elements of a are distinct and positi... | 3 | for tc in range(0, int(input())):
n = int(input()) # length of array, even number
if (n // 2) % 2 != 0 or n % 2 != 0:
print("NO")
else:
left_half = [x for x in range(2,n+1,2)]
right_half = [l-1 for l in left_half[0:-1]]
right_half.append(sum(left_half) - sum(right_half))
full = [*left_half, *right_ha... |
Ashish and Vivek play a game on a matrix consisting of n rows and m columns, where they take turns claiming cells. Unclaimed cells are represented by 0, while claimed cells are represented by 1. The initial state of the matrix is given. There can be some claimed cells in the initial state.
In each turn, a player must ... | 3 | t = int(input())
for z in range(t):
n,m = [int(i) for i in input().split()]
l=[]
for i in range(n):
x = [int(j) for j in input().split()]
l.append(x)
c1 = c2 = 0
f = False
for i in range(n):
f = False
for j in range(m):
if(l[i][j] == 1):
... |
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Bi... | 1 | x = int(raw_input())
print "NO" if x == 2 or x % 2 == 1 else "YES" |
There is a robot on a coordinate plane. Initially, the robot is located at the point (0, 0). Its path is described as a string s of length n consisting of characters 'L', 'R', 'U', 'D'.
Each of these characters corresponds to some move:
* 'L' (left): means that the robot moves from the point (x, y) to the point (x... | 3 | from collections import defaultdict
t = int(input().strip())
dir_dict = {'L':(-1,0),'R':(1,0),'D':(0,-1),'U':(0,1)}
for _ in range(t):
n = int(input().strip())
s = input().strip()
path = defaultdict(int)
path[(0,0)] = 0
ans = (1,200010)
pos = (0,0)
for cur,i in enumerate(s,1):
pos =... |
You are given an array a_1, a_2, ..., a_n and an array b_1, b_2, ..., b_n.
For one operation you can sort in non-decreasing order any subarray a[l ... r] of the array a.
For example, if a = [4, 2, 2, 1, 3, 1] and you choose subbarray a[2 ... 5], then the array turns into [4, 1, 2, 2, 3, 1].
You are asked to determi... | 3 | from sys import stdin, stdout
from collections import defaultdict
t = int(stdin.readline())
inf = 10**6
def merge_sort(order, a):
if len(order) == 1:
return order, a
mid = (len(order) + 1) // 2
left_o, left_a = merge_sort(order[:mid], a[:mid])
right_o, right_a = merge_sort(order[mid:], a[mid:]... |
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 | #coding:utf-8
m,n = (int(x) for x in input().split())
print(m*n//2) |
When Serezha was three years old, he was given a set of cards with letters for his birthday. They were arranged into words in the way which formed the boy's mother favorite number in binary notation. Serezha started playing with them immediately and shuffled them because he wasn't yet able to read. His father decided t... | 3 | n = int(input())
s = input()
cn = s.count('n')
cz = s.count('z')
ans = '1 ' * cn + '0 ' * cz
print (ans)
|
A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not.
Ahcl wants to construct a beautiful string. He has a string s, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each c... | 3 | t = int(input())
for q in range(t):
s = input()
string = list(s)
bad = False
for i in range(0, len(s) - 1):
if s[i] == s[i + 1] and s[i] != '?':
bad = True
break
if bad:
print(-1)
else:
l = ['a', 'b', 'c']
for i in range(0, len(s)):
... |
Takahashi lives in another world. There are slimes (creatures) of 10000 colors in this world. Let us call these colors Color 1, 2, ..., 10000.
Takahashi has N slimes, and they are standing in a row from left to right. The color of the i-th slime from the left is a_i. If two slimes of the same color are adjacent, they ... | 3 | N = int(input())
a = list(input().split())
cnt = 0
for i in range(1, N):
if a[i] == a[i-1]:
a[i] = 'x'
cnt += 1
print(cnt)
|
There are two sisters Alice and Betty. You have n candies. You want to distribute these n candies between two sisters in such a way that:
* Alice will get a (a > 0) candies;
* Betty will get b (b > 0) candies;
* each sister will get some integer number of candies;
* Alice will get a greater amount of candie... | 3 | n=int(input())
for i in range(n):
m=int(input())
if m%2==0:
print(m//2-1)
else:
print(m//2) |
Vanya got an important task — he should enumerate books in the library and label each book with its number. Each of the n books should be assigned with a number from 1 to n. Naturally, distinct books should be assigned distinct numbers.
Vanya wants to know how many digits he will have to write down as he labels the bo... | 3 | def xxx(n):
total = 0
curr = 9
for i in range(n):
total += curr * (i + 1)
curr *= 10
return total
if __name__ == '__main__':
n = int(input())
l = len(str(n))
a = xxx(l - 1)
b = (n - 10 ** (l - 1) + 1) * l
print(a + b) |
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word.
Note, that during capitalization all the letters except the first one remains unchanged.
Input
A single line contains a non-empty word. This word consists of lowercase and uppercase English letters.... | 3 | str1=input()
str1=' '.join(str1[0].upper()+str1[1:] for str1 in str1.split())
print(str1) |
You are given two integer sequences of length N: a_1,a_2,..,a_N and b_1,b_2,..,b_N. Determine if we can repeat the following operation zero or more times so that the sequences a and b become equal.
Operation: Choose two integers i and j (possibly the same) between 1 and N (inclusive), then perform the following two ac... | 3 | n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
sum_a=sum(a)
sum_b=sum(b)
a_cnt,b_cnt=0,0
for aa,bb in zip(a,b):
if aa>bb:
a_cnt+=aa-bb
elif aa<bb:
b_cnt+=(bb-aa)//2
if a_cnt<=b_cnt:
print('Yes')
else:
print('No') |
Let's denote a k-step ladder as the following structure: exactly k + 2 wooden planks, of which
* two planks of length at least k+1 — the base of the ladder;
* k planks of length at least 1 — the steps of the ladder;
Note that neither the base planks, nor the steps planks are required to be equal.
For example... | 3 | test=int(input())
for _ in range(test):
n=int(input())
arr=list(map(int,input().split()))
arr.sort(reverse=True)
n=len(arr)
#print(arr)
print(min(arr[1]-1,n-2)) |
As you know, all the kids in Berland love playing with cubes. Little Petya has n towers consisting of cubes of the same size. Tower with number i consists of ai cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest a... | 1 | n,k=map(int,raw_input().split())
lis=map(int,raw_input().split())
ans=[]
for _ in range(k):
high=0
low=10**7
inhi=inlo=0
for i in range(n):
if lis[i]>high:
high=lis[i]
inhi=i
if lis[i]<low:
low=lis[i]
inlo=i
if high-low<=1:
brea... |
There are N people numbered 1 to N. Each person wears a red hat or a blue hat.
You are given a string s representing the colors of the people. Person i wears a red hat if s_i is `R`, and a blue hat if s_i is `B`.
Determine if there are more people wearing a red hat than people wearing a blue hat.
Constraints
* 1 \l... | 3 | a=input()
x=input()
b=x.count("B")
r=x.count("R")
if r>b:
print("Yes")
else:
print("No")
|
You went to the store, selling n types of chocolates. There are a_i chocolates of type i in stock.
You have unlimited amount of cash (so you are not restricted by any prices) and want to buy as many chocolates as possible. However if you buy x_i chocolates of type i (clearly, 0 ≤ x_i ≤ a_i), then for all 1 ≤ j < i at ... | 3 | # ANSHUL GAUTAM
# IIIT-D
from math import *
from copy import *
from string import * # alpha = ascii_lowercase
from random import *
from sys import stdin
from operator import * # d = sorted(d.items(), key=itemgetter(1))
from itertools import *
from collections import Counter # z = dict(Counter(l))
N = int(st... |
There are n slimes in a row. Each slime has an integer value (possibly negative or zero) associated with it.
Any slime can eat its adjacent slime (the closest slime to its left or to its right, assuming that this slime exists).
When a slime with a value x eats a slime with a value y, the eaten slime disappears, and ... | 3 | I=lambda:map(int,input().split())
#D
n=int(input())
a=list(I())
s=0
if n==1:
exit(print(a[0]))
if all(i>0 for i in a) :
print(sum(a) -2*min(a))
elif all(i<0 for i in a):
print(-(sum(a) - 2*max(a) ))
else:
for i in a:
s+=abs(i)
print(s)
|
Uncle Fyodor, Matroskin the Cat and Sharic the Dog live their simple but happy lives in Prostokvashino. Sometimes they receive parcels from Uncle Fyodor’s parents and sometimes from anonymous benefactors, in which case it is hard to determine to which one of them the package has been sent. A photographic rifle is obvio... | 3 |
l = []
for _ in range(3):
l.append(input())
lp = ['F', 'M', 'S']
if l.count('rock') == 1 and l.count('scissors') == 2:
print(lp[l.index('rock')])
elif l.count('paper') == 1 and l.count('rock') == 2:
print(lp[l.index('paper')])
elif l.count('scissors') == 1 and l.count('paper') == 2:
print(lp[l.index('scissors')])... |
Ayoub had an array a of integers of size n and this array had two interesting properties:
* All the integers in the array were between l and r (inclusive).
* The sum of all the elements was divisible by 3.
Unfortunately, Ayoub has lost his array, but he remembers the size of the array n and the numbers l and... | 3 | n, l, r = map(int, input().split())
total = r-l+1
rf, re = l%3, r%3
if rf==0: rf = 3
l, r = l+(3-rf), r-re
if rf==3: rf = 0
mod = int(1e9+7)
zeros = ((r-l)//3 + 1)%mod
ones = ((rf==1)*1 + (r-l)//3 + (re>=1)*1)%mod
twos = ((rf>=1)*1 + (r-l)//3 + (re==2)*1)%mod
#dp[i][j], size of array whose sum modulo 3 is j
dp = [ [N... |
The territory of Berland is represented by a rectangular field n × m in size. The king of Berland lives in the capital, located on the upper left square (1, 1). The lower right square has coordinates (n, m). One day the king decided to travel through the whole country and return back to the capital, having visited ever... | 1 | n, m = map (int, raw_input ().split ())
if n == 1 and m == 2:
print '0\n1 1\n1 2\n1 1'
elif n == 2 and m == 1:
print '0\n1 1\n2 1\n1 1'
elif n == 1:
print 1
print 1, m, 1, 1
print '\n'.join (map (lambda x: '1 ' + str (x), range (1, m + 1) + [1]))
elif m == 1:
print 1
print n, 1, 1, 1
pri... |
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true:
* Employee A is the immediate manag... | 3 | n = int(input())
p = [int(input()) for _ in range(n)]
r = 0
for i in range(n):
c = 0
while i >= 0:
i = p[i] - 1
c += 1
r = max(r, c)
print(r) |
You are given an array a of length 2n. Consider a partition of array a into two subsequences p and q of length n each (each element of array a should be in exactly one subsequence: either in p or in q).
Let's sort p in non-decreasing order, and q in non-increasing order, we can denote the sorted versions by x and y, r... | 3 | def res(n):
nu=s=1
for i in range(n):
nu=(nu*(2*n-i))%m
s=(s*(i+1))%m
return((nu*pow(s,m-2,m))%m)
m=998244353
n=int(input())
fg=sorted(list(map(int,input().split())))
f=abs((sum(fg[:n])-sum(fg[n:])))
print((f*res(n))%m)
#print(f) |
Xsquare got bored playing with the arrays all the time. Therefore, he has decided to play with the strings. Xsquare called a string P a "double string" if string P is not empty and can be broken into two strings A and B such that A + B = P and A = B. for eg : strings like "baba" , "blabla" , "lolo" are all double strin... | 1 | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
test_cases= int(raw_input())
for x in xrange(test_cases):
s = raw_input()
if len(s)>1:
print "No" if len(set(s)) == len(list(s)) else "Yes"
else:
print "No"
"""
char_array = [... |
"You must lift the dam. With a lever. I will give it to you.
You must block the canal. With a rock. I will not give the rock to you."
Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.
Hermit Lizard agreed to give Danik the lever. But to get a stone... | 3 | t=int(input())
while t>0:
n=int(input())
a=[int(x) for x in input().split()]
count=0
b=[0]*33
for i in range(n):
z=a[i]
c=0
while z>0:
z=z//2
c+=1
b[c]+=1
for i in range(len(b)):
if b[i]>1:
k=b[i]
count+=(k*(... |
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.
The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe... | 3 | ipt = input()
one = 0; two = 0; three = 0;
for i in range(len(ipt)):
if i%2 == 0:
if int(ipt[i]) == 1:
one += 1
elif int(ipt[i]) == 2:
two += 1
else:
three += 1
opt = ""
for i in range(one):
opt += "1+"
for i in range(two):
opt += "2+"
for i in r... |
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=input().strip().split(' ')
m,n=[int(m),int(n)]
ans=(m*n)//2
print(ans) |
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 - ... | 3 | print('0 0 {}'.format(int(input())))
|
Petr wants to make a calendar for current month. For this purpose he draws a table in which columns correspond to weeks (a week is seven consequent days from Monday to Sunday), rows correspond to weekdays, and cells contain dates. For example, a calendar for January 2017 should look like on the picture:
<image>
Petr ... | 3 | from calendar import monthrange
n , k = map(int,input().strip().split())
l1 = [0,1,2,3,4,5,6,7]
l2 = 7 - l1[k] + 1
NOD = max(monthrange(2017,n))
A = []
if 7 - l1[k] == 0:
A.append(1)
else:
A.append(7-l1[k]+1)
for i in range(A[0]+7,NOD + 1,7):
if i <= NOD:
A.append(i)
if NOD - i < 7 and (NOD - i ... |
After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer.
At the start of the day they have x ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. Each person in the q... | 1 | I = lambda: map(int, raw_input().split())
n, x = I()
s = x
sad = 0
for i in range(n):
sign, d = raw_input().split()
d = int(d)
if sign == '+':
s += d
else:
if s < d:
sad+=1
else:
s -= d
print s, sad
|
You are a lover of bacteria. You want to raise some bacteria in a box.
Initially, the box is empty. Each morning, you can put any number of bacteria into the box. And each night, every bacterium in the box will split into two bacteria. You hope to see exactly x bacteria in the box at some moment.
What is the minimu... | 3 | def fun(a,count):
if a!=1:
if a%2==0:
a=a/2
fun(a,count)
else:
count=count+1
a=(a-1)/2
fun(a,count)
elif a==1:
print(count)
a = int(input())
count = 1
fun(a,count) |
The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has n students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times.
The ... | 1 | m = [int(i) for i in raw_input().split()]
num_part = m[1]
l = [int(i) for i in raw_input().split()]
l.sort()
#[ 0, 0, 1, 4, 5 ]
for i in range(num_part):
l = [j+1 for j in l]
l = [i for i in l if i <= 5]
if len(l) < 3:
print 0
else:
print len(l)/3
|
Sereja and Dima play a game. The rules of the game are very simple. The players have n cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The ... | 1 | n = int (raw_input())
cards = map(int,raw_input().split())
result= [0,0]
for i in xrange(0,n):
if cards[0] > cards[-1]:
result[i%2] += cards[0]
del cards[0]
else:
result[i%2] += cards[-1]
del cards[-1]
print result[0], result[1] |
This is an interactive problem. Refer to the Interaction section below for better understanding.
Ithea and Chtholly want to play a game in order to determine who can use the kitchen tonight.
<image>
Initially, Ithea puts n clear sheets of paper in a line. They are numbered from 1 to n from left to right.
This game ... | 3 | def get_int(string, n):
i = j = k = 0
for s in string:
k += 1
for s in string:
if i == n - 1:
break
if s == ' ':
i += 1
j += 1
i = 0
while j < k:
if string[j] == ' ':
break
i = 10 * i + int(string[j])
j += 1
return i
def check_order(ls, n):
for i in ls:
if i == None:
return 0
for i ... |
You have an integer variable x. Initially, x=0.
Some person gave you a string S of length N, and using the string you performed the following operation N times. In the i-th operation, you incremented the value of x by 1 if S_i=`I`, and decremented the value of x by 1 if S_i=`D`.
Find the maximum value taken by x duri... | 3 | n,s=int(input()),str(input())
l=[0]
for i in s:
x= -1 if i=="D" else 1
l+=[l[-1]+x]
print(max(l)) |
You want to arrange n integers a1, a2, ..., an in some order in a row. Let's define the value of an arrangement as the sum of differences between all pairs of adjacent integers.
More formally, let's denote some arrangement as a sequence of integers x1, x2, ..., xn, where sequence x is a permutation of sequence a. The ... | 3 | n = int(input())
k = map(int,input().split())
mylist = sorted(list(k))
def myswap(mylist) :
mylist[-1], mylist[0] = mylist[0], mylist[-1]
return mylist
mylist = myswap(mylist)
for i in range(n) :
print(mylist[i],end = " ")
|
Anatoly lives in the university dorm as many other students do. As you know, cockroaches are also living there together with students. Cockroaches might be of two colors: black and red. There are n cockroaches living in Anatoly's room.
Anatoly just made all his cockroaches to form a single line. As he is a perfectioni... | 3 | # def I(): return(list(map(int,input().split())))
def solve(arr):
# print(arr)
f=min(arr.count("b"),arr.count("r"))
return len(arr)-f
n=int(input())
s=input()
accs0=[]
accs1=[]
for i in range(n):
if i%2==1:
if s[i]=='r':
accs0.append(s[i])
else:
accs1.append(s[i])
else:
if s[i]!='r':
accs0.append... |
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If... | 3 | _1 = '236a'
# count = 0
# l = [list(map(int, input().split())) for i in range(5)]
# for i in range(5):
# for j in range(5):
# if l[i][j] == 1:
#
# if i > 2:
# count += i - 2
# elif i < 2:
# count += 2 - i
# if j > 2:
# count... |
Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?
Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of th... | 1 | n=input()
b=['x'*(n+2)]
b+=['x'+raw_input()+'x' for i in range(n)]
b.append('x'*(n+2))
print 'YES' if all(all(not reduce(lambda x,y:x^y,(b[r+i+1][c+j] == 'o' for (i, j) in zip((-1,0,0,1),(0,-1,1,0)))) for c in range(1,n+1)) for r, x in enumerate(b[1:-1])) else 'NO' |
You are given two arrays a and b both consisting of n positive (greater than zero) integers. You are also given an integer k.
In one move, you can choose two indices i and j (1 ≤ i, j ≤ n) and swap a_i and b_j (i.e. a_i becomes b_j and vice versa). Note that i and j can be equal or different (in particular, swap a_2 w... | 3 | t=int(input())
for _ in range(t):
n,k=map(int,input().split())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
for i in range(k):
x=min(A)
y=max(B)
if(x<y):
a=A.index(x)
b=B.index(y)
A[a]=y
B[b]=x
print(sum(A)) |
There are N positive integers arranged in a circle.
Now, the i-th number is A_i. Takahashi wants the i-th number to be B_i. For this objective, he will repeatedly perform the following operation:
* Choose an integer i such that 1 \leq i \leq N.
* Let a, b, c be the (i-1)-th, i-th, and (i+1)-th numbers, respectively. ... | 3 | from pprint import pprint
import heapq
def solve(n, a, b):
b_pq = []
b_rev = {}
delete = []
for i, b_i in enumerate(b):
if b_i == a[i]:
continue
heapq.heappush(b_pq, (-1 * b_i, i))
count = 0
while b_pq:
tmp = heapq.heappop(b_pq)
# pprint(tmp)
... |
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it:
* deletes all the vowels,
* inserts a character "." before each consonant,
* repl... | 3 | s = input().lower()
except_chars = {"a", "o", "y", "e", "u", "i"}
output = []
for i in range(len(s)):
if s[i] not in except_chars:
output.append(s[i])
output = '.'.join(output)
print('.' + output)
|
You are given two lists of non-zero digits.
Let's call an integer pretty if its (base 10) representation has at least one digit from the first list and at least one digit from the second list. What is the smallest positive pretty integer?
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 9) — the length... | 3 | n,m=map(int,input().split())
t = set(map(int,input().split()))
r = set(map(int,input().split()))
result = t&r
if len(result) == 0:
if min(t) < min(r):
print(min(t),min(r),sep='')
else:
print(min(r),min(t),sep='')
else:
print(min(result)) |
Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number n. How many times can Gerald put a spell on it until the number becomes one-di... | 3 | n = int(input())
count = 0
while len(str(n)) != 1:
a = 0
for i in str(n):
a += int(i)
n = a
count += 1
print(count) |
Vanya has a table consisting of 100 rows, each row contains 100 cells. The rows are numbered by integers from 1 to 100 from bottom to top, the columns are numbered from 1 to 100 from left to right.
In this table, Vanya chose n rectangles with sides that go along borders of squares (some rectangles probably occur mult... | 1 | n = input()
lines = [map(int, raw_input().split()) for i in xrange(n)]
print sum([abs(i[2]-i[0]+1)*abs(i[3]-i[1]+1) for i in lines])
|
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; ")... | 1 | c1, c2, c3, c4 = input(), input(), input(), input()
print 1 if (c3 > 0 and c1 > 0 and c1 == c4) or (c3 == 0 and c1 == c4) else 0
|
A triangular number is the number of dots in an equilateral triangle uniformly filled with dots. For example, three dots can be arranged in a triangle; thus three is a triangular number. The n-th triangular number is the number of dots in a triangle with n dots on a side. <image>. You can learn more about these numbers... | 3 | def fun(n):
x = 1
while x <= n:
if x*(x+1) == 2*n:
return True
x += 1
return False
n = int(input().strip())
if fun(n):
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 | import sys
def input(): return sys.stdin.readline().strip()
def iinput(): return int(input())
def rinput(): return map(int, sys.stdin.readline().strip().split())
def get_list(): return list(map(int, sys.stdin.readline().strip().split()))
n= input()
n=list(n)
n1=sorted(n)
#print(n1)
count=len(n1)-1
for i in ... |
Theatre Square in the capital city of Berland has a rectangular shape with the size n × m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a × a.
What is the least number of flagstones needed to pave the Square? It'... | 3 | n=input().split()
v=[]
result=0
for i in n:
v.append(int(i))
if v[0]%v[2]==0:
result+=(v[0]//v[2])
if v[0]%v[2]!=0:
result+=(v[0]//v[2]+1)
if v[1]%v[2]==0:
result*=(v[1]//v[2])
if v[1]%v[2]!=0:
result*=((v[1]//v[2])+1)
if v[0]==v[1]==v[2]:
result=1
print(result)
|
When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their aver... | 3 | n = int(input())
a = []
a = list(map(int,input().split()))
r = 0
f = [0]*(10**5+5)
t = 0
j = 0
for i in range(n):
if(f[a[i]] == 0):
t += 1
f[a[i]] += 1
while(j<n and t>2):
if(f[a[j]] == 1):
t -= 1
f[a[j]] -= 1
j += 1
r = max(r,i-j+1)
print(r) |
Little Petya loves playing with squares. Mum bought him a square 2n × 2n in size. Petya marked a cell inside the square and now he is solving the following task.
The task is to draw a broken line that would go along the grid lines and that would cut the square into two equal parts. The cutting line should not have any... | 1 | n , x, y = [int(x) for x in raw_input().split()]
if (x == n/2 or x == n/2 + 1) and (y == n/2 or y == n/2 + 1):
print "NO"
else:
print "YES"
|
Vitya has just started learning Berlanese language. It is known that Berlanese uses the Latin alphabet. Vowel letters are "a", "o", "u", "i", and "e". Other letters are consonant.
In Berlanese, there has to be a vowel after every consonant, but there can be any letter after any vowel. The only exception is a consonant... | 3 | if __name__=="__main__":
s=str(input())
x=0
flag=0
if len(s)==1:
if s[0]!='a' and s[0]!='e' and s[0]!='i' and s[0]!='o' and s[0]!='u' and s[0]!='n':
print('NO')
else:
print("YES")
elif s[len(s)-1]!='a' and s[len(s)-1]!='e' and s[len(s)-1]!='i' and s[len(s)-1]!... |
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like.
Now let's imagine a typical morning in your family. You haven't w... | 3 | #!/usr/bin/env python3
n = int(input())
arr = [int(a) for a in input().split()]
arr.sort()
arr.reverse()
for i in range(1, len(arr) + 1):
if sum(arr[:i]) > sum(arr[i:]):
print(i)
break
|
For a positive integer n let's define a function f:
f(n) = - 1 + 2 - 3 + .. + ( - 1)nn
Your task is to calculate f(n) for a given integer n.
Input
The single line contains the positive integer n (1 ≤ n ≤ 1015).
Output
Print f(n) in a single line.
Examples
Input
4
Output
2
Input
5
Output
-3
Note
f(4)... | 3 | number = []
biggest = int(input())
if biggest % 2 == 0:
print(biggest // 2)
else:
print(biggest // 2 - biggest)
|
After winning gold and silver in IOI 2014, Akshat and Malvika want to have some fun. Now they are playing a game on a grid made of n horizontal and m vertical sticks.
An intersection point is any point on the grid which is formed by the intersection of one horizontal stick and one vertical stick.
In the grid shown be... | 3 | print('Akshat' if min(list(map(int, input().split()))) % 2 else 'Malvika')
|
You have two friends. You want to present each of them several positive integers. You want to present cnt1 numbers to the first friend and cnt2 numbers to the second friend. Moreover, you want all presented numbers to be distinct, that also means that no number should be presented to both friends.
In addition, the fir... | 3 | c1, c2, x, y = map(int, input().split())
def valid(m):
a = m - m // x
b = m - m // y - max(0, c1 - m // y + m // x // y)
return a >= c1 and b >= c2
l, r = 0, (1<<62)
while l+1 < r:
m = l + r >> 1
if valid(m):
r = m
else:
l = m
print(r)
|
You are given a text that consists of lowercase Latin letters, spaces and punctuation marks (dot, comma, exclamation mark and question mark). A word is defined as a sequence of consecutive Latin letters.
Your task is to add spaces to the text by the following rules:
* if there is no punctuation mark between two wor... | 1 | s= raw_input()
r = ",.?!"
for i in r:
s = s.replace(i,i+" ")
s = ' '.join(s.split())
for i in r:
s = s.replace(" "+i,i)
print(s) |
A string s of length n (1 ≤ n ≤ 26) is called alphabetical if it can be obtained using the following algorithm:
* first, write an empty string to s (i.e. perform the assignment s := "");
* then perform the next step n times;
* at the i-th step take i-th lowercase letter of the Latin alphabet and write it eithe... | 3 | import string
def solve(strng):
if 'a' not in strng:
return "NO"
if len(strng)>26:
return "NO"
alphabet_string = string.ascii_lowercase
sorted_char = sorted(strng)
sortedstrng = "".join(sorted_char)
if sortedstrng not in alphabet_string:
return "NO"
increasing =... |
Leha like all kinds of strange things. Recently he liked the function F(n, k). Consider all possible k-element subsets of the set [1, 2, ..., n]. For subset find minimal element in it. F(n, k) — mathematical expectation of the minimal element among all k-element subsets.
But only function does not interest him. He wan... | 3 | n = int(input())
a = [int(i) for i in input().split()]
b = [int(i) for i in input().split()]
u = [(b[i],i) for i in range(n)]
a.sort()
u.sort(reverse=True)
ans = [(u[i][1], a[i])for i in range(n)]
ans.sort()
r = [i[1] for i in ans]
print(*r) |
There are N integers written on a blackboard. The i-th integer is A_i.
Takahashi will repeatedly perform the following operation on these numbers:
* Select a pair of integers, A_i and A_j, that have the same parity (that is, both are even or both are odd) and erase them.
* Then, write a new integer on the blackboard ... | 3 | input()
print("YNEOS"[sum(map(int,input().split()))%2::2]) |
Polycarp wants to train before another programming competition. During the first day of his training he should solve exactly 1 problem, during the second day — exactly 2 problems, during the third day — exactly 3 problems, and so on. During the k-th day he should solve k problems.
Polycarp has a list of n contests, th... | 3 | n=int(input())
arr=list(map(int,input().split()))
arr.sort()
flag=0
index=0
count=1
ans=0
while(flag==0):
if(arr[index]>=count):
index+=1
count+=1
ans+=1
else:
index+=1
if(index==n):
flag=1
break
print(ans)
|
Polycarp lives on the coordinate axis Ox and travels from the point x=a to x=b. It moves uniformly rectilinearly at a speed of one unit of distance per minute.
On the axis Ox at the point x=c the base station of the mobile operator is placed. It is known that the radius of its coverage is r. Thus, if Polycarp is at a ... | 3 | t=int(input())
for i in range(t):
a,b,c,r= (int(x) for x in input().split())
left=max(min(a,b),c-r)
right=min(max(a,b),c+r)
print(max(a,b)-min(a,b)-max(0,right-left))
|
Polycarp plays "Game 23". Initially he has a number n and his goal is to transform it to m. In one move, he can multiply n by 2 or multiply n by 3. He can perform any number of moves.
Print the number of moves needed to transform n to m. Print -1 if it is impossible to do so.
It is easy to prove that any way to trans... | 3 | a,b=map(int, input().split())
if b%a==0:
c=b//a
j=k=0
while c%2==0 and c>0:
k+=1
c//=2
while c%3==0 and c>0:
j+=1
c//=3
if b//a==(2**k)*(3**j):
print(j+k)
else:
print(-1)
else:
print(-1)
|
Adilbek was assigned to a special project. For Adilbek it means that he has n days to run a special program and provide its results. But there is a problem: the program needs to run for d days to calculate the results.
Fortunately, Adilbek can optimize the program. If he spends x (x is a non-negative integer) days opt... | 3 | import math
t = int(input())
while t:
t-=1
n,d = map(int,input().split())
done = False
for i in range(int(math.sqrt(d))+1):
if i+math.ceil(d/(i+1))<=n:
print("YES")
done = True
break
if not done:
print("NO") |
Ringo is giving a present to Snuke.
Ringo has found out that Snuke loves yakiniku (a Japanese term meaning grilled meat. yaki: grilled, niku: meat). He supposes that Snuke likes grilled things starting with `YAKI` in Japanese, and does not like other things.
You are given a string S representing the Japanese name of ... | 3 | s = input()
if len(s)>=4 and s[:4] == 'YAKI':
print("Yes")
else:
print("No") |
Theatre Square in the capital city of Berland has a rectangular shape with the size n × m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a × a.
What is the least number of flagstones needed to pave the Square? It'... | 3 | import math
n,m,a=map(int,input().split())
if n>=1 and n<=1000000000 and m>=1 and m<=1000000000 and a>=1 and a<=1000000000:
a1=math.ceil(m/a)
a2=math.ceil(n/a)
print(a1*a2)
|
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made lik... | 3 | n = int(input())
for _ in range(n):
string = input()
if len(string) <= 10:
print(string)
else:
print(string[0] + str(len(string)-2) + string[-1]) |
Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first n. He writes down the followin... | 3 | n, k = map(int, input().split())
if n%2 == 0:
temp = n//2
else:
temp = n//2+1
if k <= temp:
print(2*k - 1)
else:
print(2*(k-temp)) |
You are given a string s, consisting of lowercase Latin letters. While there is at least one character in the string s that is repeated at least twice, you perform the following operation:
* you choose the index i (1 ≤ i ≤ |s|) such that the character at position i occurs at least two times in the string s, and del... | 3 | import re
import sys
exit=sys.exit
from bisect import bisect_left as bsl,bisect_right as bsr
from collections import Counter,defaultdict as ddict,deque
from functools import lru_cache
cache=lru_cache(None)
from heapq import *
from itertools import *
from math import inf
from pprint import pprint as pp
enum=enumerate
ri... |
Find the edit distance between given two words s1 and s2.
The disntace is the minimum number of single-character edits required to change one word into the other. The edits including the following operations:
* insertion: Insert a character at a particular position.
* deletion: Delete a character at a particular posi... | 3 | s1=input()
s2=input()
mp=[[0]*(len(s1)+1) for _ in range(len(s2)+1)]
#この問題でも先に0を用意
for n in range(1,len(s2)+1):
mp[n][0]+=mp[n-1][0]+1
for m in range(1,len(s1)+1):
mp[0][m]+=mp[0][m-1]+1
for i in range(1,len(s2)+1):
for j in range(1,len(s1)+1):
mp[i][j]=min(mp[i-1][j]+1,
mp[i][j... |
Snuke has an empty sequence a.
He will perform N operations on this sequence.
In the i-th operation, he chooses an integer j satisfying 1 \leq j \leq i, and insert j at position j in a (the beginning is position 1).
You are given a sequence b of length N. Determine if it is possible that a is equal to b after N oper... | 1 | N=input()
B=map(int, raw_input().split())
L=[]
for k in range(N):
for i in range(N-(k+1),-1,-1):
num=i+1
if B[i]==num:
L.append(B[i])
del B[i]
break
L.reverse()
if len(B)==0:
for x in L:
print x
else:
print -1
|
Vasya lives in a round building, whose entrances are numbered sequentially by integers from 1 to n. Entrance n and entrance 1 are adjacent.
Today Vasya got bored and decided to take a walk in the yard. Vasya lives in entrance a and he decided that during his walk he will move around the house b entrances in the direct... | 3 | a,b,c=map(int,input().split())
print((b+c-1)%a+1) |
Misha and Vanya have played several table tennis sets. Each set consists of several serves, each serve is won by one of the players, he receives one point and the loser receives nothing. Once one of the players scores exactly k points, the score is reset and a new set begins.
Across all the sets Misha scored a points ... | 3 | k, a, b = map(int, input().split())
count = a // k + b // k
print(-1 if (not count) or (a < k and b % k) or (b < k and a % k) else count)
|
We have N sticks with negligible thickness. The length of the i-th stick is A_i.
Snuke wants to select four different sticks from these sticks and form a rectangle (including a square), using the sticks as its sides. Find the maximum possible area of the rectangle.
Constraints
* 4 \leq N \leq 10^5
* 1 \leq A_i \leq ... | 3 | n=int(input())
L=list(map(int,input().split()))
L.sort(reverse=True)
import collections
d=collections.Counter(L)
M=0
m=[0,0]
for v in d:
if d[v]>=4:
M=max(M,v)
elif d[v]>=2:
m.append(v)
m.sort(reverse=True)
print(max(M**2,m[0]*m[1],M*m[0])) |
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word.
Note, that during capitalization all the letters except the first one remains unchanged.
Input
A single line contains a non-empty word. This word consists of lowercase and uppercase English letters.... | 3 | y=input()
print(y[0].capitalize()+y[1:len(y)]) |
You are given two integers a and b.
In one move, you can choose some integer k from 1 to 10 and add it to a or subtract it from a. In other words, you choose an integer k ∈ [1; 10] and perform a := a + k or a := a - k. You may use different values of k in different moves.
Your task is to find the minimum number of mo... | 1 | __author__ = 'Devesh Bajpai'
'''
https://codeforces.com/problemset/problem/1409/A
Solution: Since we can use all numbers from 1 to 10, we try greedily to employ 10 to either increase or decrease a so
that we get a and b only differ in units place. Now for that, we do one another move using the suitable number from 1
... |
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 = 1
tc = int(n ** 0.5)
c = 2
while c <= tc:
if n % c == 0:
ans += 1
if c * c < n:
ans += 1
c += 1
print(ans) |
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point x(x > 0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order ... | 3 | x = int(input())
mn = 1e18
for i in range(1, 6):
if not x%i:
mn = min(mn, x//i)
else:
mn = min(mn, 1+(x//i))
print(mn) |
Little Syed loves brute force. He thinks that brute force can be the solution to any problem in the world. You give him any question, and he'll have a brute force answer ready for you, almost all the time. His good friend Little Jhool (Like, always!) decides to teach him a lesson, by giving him problems which cannot be... | 1 | test = int(raw_input())
while(test):
test -= 1
num = int(raw_input())
diff = num
a = 0
cube = []
n = 1
while( n**3 < num):
cube.append(n**3)
n +=1
taxi = []
for i in range(0,len(cube)):
for j in range(i,len(cube)):
taxi.append(cube[i] + cube[j])
taxi.sort()
for each in taxi:
if each<num ... |
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())
a=[int(x) for x in input().split()]
ans=0
for i in range(n):
for j in range(n):
a[i],a[j]=a[j],a[i]
for k in range(n):
if a[k]==n:
r=k
if a[k]==1:
l=k
ans=max(ans,abs(r-l))
a[i],a[j]=a[j],a[i]
print(ans)
|
A and B are preparing themselves for programming contests.
B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.
Initially, the compiler displayed n compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix s... | 3 | n=int(input())
x = [int(x) for x in input().split()]
s=0
for i in range(n):
s+=x[i];
s1=0
x = [int(x) for x in input().split()]
for i in range(n-1):
s1+=x[i]
print(s-s1)
s=s1
s1=0
x = [int(x) for x in input().split()]
for i in range(n-2):
s1+=x[i]
print(s-s1)
|
You are given an integer n. In one move, you can either multiply n by two or divide n by 6 (if it is divisible by 6 without the remainder).
Your task is to find the minimum number of moves needed to obtain 1 from n or determine if it's impossible to do that.
You have to answer t independent test cases.
Input
The fi... | 3 | #!/usr/bin/python3
# Codeforces - Round #653 (Div. 3)
# Author: frostD
# Problem B - Multiply by 2, Divide by 6
def read_int():
n = int(input())
return n
def read_ints():
ints = [int(x) for x in input().split(" ")]
return ints
#---
def solve(n):
if n == 1:
return 0
moves = 0
while n != 1:
if n % 6... |
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 | n=int(input())
count=0
while n:
i=n%10
if i==4 or i==7:
count+=1
n//=10
valid=True
if count<4:
print('NO')
valid=False
while count and valid:
i=count%10
if i!=4 and i!=7:
print('NO')
valid=False
break
count//=10
if count==0 and valid:
print('YES') |
Cengiz recently learned Fibonacci numbers and now he is studying different algorithms to find them. After getting bored of reading them, he came with his own new type of numbers that he named XORinacci numbers. He defined them as follows:
* f(0) = a;
* f(1) = b;
* f(n) = f(n-1) ⊕ f(n-2) when n > 1, where ⊕ de... | 1 | t = int(input())
for i in range(t):
l=list(map(int,raw_input().split()))
if l[2]%3==0:
print l[0]
elif l[2]%3==1:
print l[1]
else:
print l[0]^l[1]
|
Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?
You are given a system of equations:
<image>
You should count, how many there are pai... | 1 | import sys
import math
filename = 'input.txt'
def main_loop(filename):
f=sys.stdin
#f=open(filename)
for line in f:
l = line.split(' ')
n = int(l[0])
m = int(l[1])
c = 0
for i in range (0, int(math.floor(math.sqrt(n))+1)):
b = n - i*i
if i+b*... |
You've got a 5 × 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix:
1.... | 3 | a = []
k = r = 0
for i in range(5):
a.append(list(map(int,input().split())))
for i in range(5):
for j in range(5):
if a[i][j] == 1:
k = j
r = i
print(abs(k+1-3)+abs(r+1-3)) |
You are given n integers a_1, a_2, ..., a_n, where n is odd. You are allowed to flip the sign of some (possibly all or none) of them. You wish to perform these flips in such a way that the following conditions hold:
1. At least (n - 1)/(2) of the adjacent differences a_{i + 1} - a_i for i = 1, 2, ..., n - 1 are grea... | 3 | t=int(input())
for i in range(t):
n=int(input())
a=list(map(int,input().split()))
ans=[]
for i in range(n):
if i%2==0:
ans.append(abs(a[i]))
else:
ans.append(-abs(a[i]))
print(*ans) |
You are given two integers A and B as the input. Output the value of A + B.
However, if A + B is 10 or greater, output `error` instead.
Constraints
* A and B are integers.
* 1 ≤ A, B ≤ 9
Input
Input is given from Standard Input in the following format:
A B
Output
If A + B is 10 or greater, print the string `e... | 1 | x, y = map(int, raw_input().split())
#a, b, c = raw_input().split()
if x+y>=10:
print "error"
else:
print x+y |
A Little Elephant from the Zoo of Lviv likes lucky strings, i.e., the strings that consist only of the lucky digits 4 and 7.
The Little Elephant has K favorite lucky strings A1, A2, ..., AK. He thinks that the lucky string S is good if either |S| ≥ 47 or for some j from 1 to K we have that Aj is a substring of S.
The ... | 1 | K,N=[int(x) for x in raw_input().split()]
arr=[]
for i in range (0,K):
arr.append(raw_input())
'''
for a in range(1,len(arr)):
for b in range(0,a):
if len(arr[b])>len(arr[a]):
save=arr[i]
for k in range(a-1,b+1,-1):
... |
Let's call some square matrix with integer values in its cells palindromic if it doesn't change after the order of rows is reversed and it doesn't change after the order of columns is reversed.
For example, the following matrices are palindromic:
<image>
The following matrices are not palindromic because they change... | 1 | import sys
import random, math
from collections import defaultdict
n = int(raw_input())
arr = [int(__) for __ in raw_input().split()]
d = defaultdict(int)
for el in arr:
d[el] += 1
if n % 2:
fl = 0
else:
fl = 1
c = 0
nums4, nums2 = [], []
for k in d:
if d[k] % 4 == 1 or d[k] % 4 == 3:
c = str(k... |
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... | 1 | a, n, b = map(int, raw_input().split())
print max(b * (b + 1) / 2 * a - n, 0) |
The dice are placed in the orientation shown in the figure below.
<image>
As shown in this figure, the dice used here have 1 on the upper side and 2 on the south side, and 3 on the east side. Since the sum of the facing faces of the dice is always 7, the invisible faces are 5 on the north side, 4 on the west side, a... | 3 | import sys
f = sys.stdin
ope = {'North':(1,5,2,3,0,4)
,'East' :(3,1,0,5,4,2)
,'West' :(2,1,5,0,4,3)
,'South':(4,0,2,3,5,1)
,'Right':(0,2,4,1,3,5)
,'Left' :(0,3,1,4,2,5)}
while True:
n = int(f.readline())
if n == 0:
break
xi = [1,2,3,4,5,6]
ret = 1
for _ in rang... |
It's a walking tour day in SIS.Winter, so t groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.
Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P":
* "A" corresponds to an angry... | 3 | t = int(input())
for _ in range(t):
n = int(input())
arr = list(input()) + ['A']
cnt = 0
for z in range(100):
for i in range(n - 1, -1, -1):
if arr[i] == 'A' and arr[i + 1] == 'P':
arr[i + 1] = 'A'
cnt = z + 1
print(cnt) |
You went to the store, selling n types of chocolates. There are a_i chocolates of type i in stock.
You have unlimited amount of cash (so you are not restricted by any prices) and want to buy as many chocolates as possible. However if you buy x_i chocolates of type i (clearly, 0 ≤ x_i ≤ a_i), then for all 1 ≤ j < i at ... | 1 | n = int(input())
l = map(int, raw_input().rstrip().split())[::-1]
res = l[0]
ma = l[0]
for i in range(1,n):
ma = max(min(l[i],ma-1),0)
res += ma
print res |
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had a red socks and b blue socks.
According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot.
Every day Vasya puts on new socks in the morning and ... | 3 | n,m = map(int,input().split())
print(min(m,n),abs(m-n)//2 ) |
You are given a range of positive integers from l to r.
Find such a pair of integers (x, y) that l ≤ x, y ≤ r, x ≠ y and x divides y.
If there are multiple answers, print any of them.
You are also asked to answer T independent queries.
Input
The first line contains a single integer T (1 ≤ T ≤ 1000) — the number of... | 3 | def ii(): return int(input())
def fi(): return float(input())
def si(): return input()
def mi(): return map(int,input().split())
def li(): return list(mi())
import math
t=ii()
for i in range(t):
l,r=mi()
print(l,l*2) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.