problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
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... | 1 | #http://codeforces.com/problemset/problem/266/A
def stones():
n = int(raw_input().strip())
s = list(raw_input().strip())
lastChr = s[0]
count = 0
for c in s[1:]:
if c == lastChr:
count += 1
lastChr = c
return count
print stones()
|
wHAT DO WE NEED cAPS LOCK FOR?
Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage.
Let's consider that a word has been typed with the Caps lock key accidentall... | 3 | a = input()
if a == a.upper():
print(a.lower())
elif a[1:] == a[1:].upper():
print(a.capitalize())
else:
print(a) |
Every day, N passengers arrive at Takahashi Airport. The i-th passenger arrives at time T_i.
Every passenger arrived at Takahashi airport travels to the city by bus. Each bus can accommodate up to C passengers. Naturally, a passenger cannot take a bus that departs earlier than the airplane arrives at the airport. Also... | 3 | n, c, k = map(int, input().split())
t = [int(input()) for _ in range(n)]
t.sort()
ans = 1
earl = t[0]
count = 0
for i in range(n):
if t[i]-earl > k or count == c:
count = 0
earl = t[i]
ans += 1
count += 1
print(ans) |
From beginning till end, this message has been waiting to be conveyed.
For a given unordered multiset of n lowercase English letters ("multi" means that a letter may appear more than once), we treat all letters as strings of length 1, and repeat the following operation n - 1 times:
* Remove any two elements s and t... | 3 | k = int(input())
res, t = "", 0
chars = [chr(ord('a')+i) for i in range(26)]
for c in chars:
i = 0
while t + i <= k:
res += c
t += i
i += 1
print(res)
|
Despite his bad reputation, Captain Flint is a friendly person (at least, friendly to animals). Now Captain Flint is searching worthy sailors to join his new crew (solely for peaceful purposes). A sailor is considered as worthy if he can solve Flint's task.
Recently, out of blue Captain Flint has been interested in ma... | 3 | #3 smallest nearly primes are 6,10,14,15
#if n>30, it's possible. 6,10,14,n-30
t=int(input())
for _ in range(t):
n=int(input())
if n>30:
a=6
b=10
c=14
d=n-30
if d==6:
c=15
d=5
if d==10:
c=15
d=9
if d... |
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 | r=1
c=1
for i in range (0,5):
a = input().split()
if '1' in a:
r = i
c = a.index('1')
break
print(abs(r-2)+abs(c-2)) |
A permutation of length n is an array p=[p_1,p_2,...,p_n], which contains every integer from 1 to n (inclusive) and, moreover, each number appears exactly once. For example, p=[3,1,4,2,5] is a permutation of length 5.
For a given number n (n β₯ 2), find a permutation p in which absolute difference (that is, the absolut... | 3 | t=int(input())
for i in range(t):
n=int(input())
c=0
if n%5==0 or n%5==1:
t=1
while c!=n:
print(t,end=" ")
c+=1
if t%5==0:
t-=3
else:
t+=2
elif n%5==4:
t=2
while c!=n:
print(t,end=... |
It has been decided that a programming contest sponsored by company A will be held, so we will post the notice on a bulletin board.
The bulletin board is in the form of a grid with N rows and N columns, and the notice will occupy a rectangular region with H rows and W columns.
How many ways are there to choose where ... | 3 | n=int(input())
H=int(input())
W=int(input())
print((n-H+1)*(n-W+1)) |
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word s. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if... | 3 | s = input()
word = "hello"
ind = 0
for i in s:
if ind == 5:
break
if i == word[ind]:
ind += 1
if ind == 5:
print("YES")
else:
print("NO") |
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits.
Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has on... | 3 | n=int(input())
n+=1
while len(set(str(n)))<=3:
n+=1
print(n) |
Alexander is a well-known programmer. Today he decided to finally go out and play football, but with the first hit he left a dent on the new Rolls-Royce of the wealthy businessman Big Vova. Vladimir has recently opened a store on the popular online marketplace "Zmey-Gorynych", and offers Alex a job: if he shows his pro... | 3 | from math import gcd
for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
a.sort(reverse=True)
di = {}
for i in a:
di[i] = di.get(i, 0) + 1
ans = [a[0]] * di[a[0]]
val = a[0]
while di[val]:
a.remove(val)
di[val] -= 1
g = 1
... |
Easy and hard versions are actually different problems, so we advise you to read both statements carefully.
You are given a weighted rooted tree, vertex 1 is the root of this tree.
A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last differ... | 3 | import sys
import math
import bisect
from sys import stdin, stdout
from math import gcd, floor, sqrt, log
from collections import defaultdict as dd
from bisect import bisect_left as bl, bisect_right as br
from collections import Counter
from collections import deque
import heapq
import threading
sys.setrecursionlimit(... |
Little penguin Polo has an n Γ m matrix, consisting of integers. Let's index the matrix rows from 1 to n from top to bottom and let's index the columns from 1 to m from left to right. Let's represent the matrix element on the intersection of row i and column j as aij.
In one move the penguin can add or subtract number... | 3 |
def min_moves(l2,count=0):
if (len(l2)-1)%2==0:
median = l2[int((len(l2)-1)/2)]
else:
median = l2[int(((len(l2)-1)/2))+1]
for i in range(1,len(l2)):
if l2[i]%d != l2[i-1]%d:
return -1
for i in range(len(l2)):
if l2[i] < median:
diff = median - l2[i]
count+= diff/d
else:
if l2[i] > median:
... |
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 | # n=int(input())
# if(n%2==0):
# print("YES")
# else:
# print("NO")
# for _ in range(int(input())):
# n=(input())
# if(len(n)<=10):
# print(n)
# else:
# print(n[0]+str(len(n)-2)+n[len(n)-1])
# a=0
# for _ in range(int(input())):
# n=list(map(int,input().split()))
# count=0
... |
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob.
Right now, Limak and Bob weigh a and b respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight.
Limak eats a lot and his weight is tripled after every year, while Bob's weight... | 3 | from math import log
a,b = map(int,input().split())
print(int(log(b/a,1.5))+1)
|
Dreamoon wants to climb up a stair of n steps. He can climb 1 or 2 steps at each move. Dreamoon wants the number of moves to be a multiple of an integer m.
What is the minimal number of moves making him climb to the top of the stairs that satisfies his condition?
Input
The single line contains two space separated i... | 3 | import math
l=list(map(int,input().strip().split()))
a=l[0]
b=l[1]
c=math.ceil(a/2)
flag=0
for i in range(c,a+1):
if i%b==0:
print(i)
flag=1
break
if flag==0:
print(-1) |
After playing Neo in the legendary "Matrix" trilogy, Keanu Reeves started doubting himself: maybe we really live in virtual reality? To find if this is true, he needs to solve the following problem.
Let's call a string consisting of only zeroes and ones good if it contains different numbers of zeroes and ones. For exa... | 3 | n = int(input())
s = input()
z , o , = 0, 0
for i in range(len(s)):
if s[i]=='0': z+=1
else: o+=1
if z!=o : print(1,s,sep='\n')
else :
print(2)
print(s[0:-1],s[-1])
|
Mike is trying rock climbing but he is awful at it.
There are n holds on the wall, i-th hold is at height ai off the ground. Besides, let the sequence ai increase, that is, ai < ai + 1 for all i from 1 to n - 1; we will call such sequence a track. Mike thinks that the track a1, ..., an has difficulty <image>. In othe... | 1 | import copy
n=int(input())
list=[int(i) for i in raw_input().split()]
jg=[]
ans=[]
for i in range(1,n):
x=list[i]-list[i-1]
jg.append(x)
for i in range(n-2):
JG = copy.deepcopy(jg)
JG[i]=jg[i]+jg[i+1]
del JG[i+1]
ans.append(max(JG))
print min(ans) |
An array of integers p_1, p_2, ..., p_n is called a permutation if it contains each number from 1 to n exactly once. For example, the following arrays are permutations: [3, 1, 2], [1], [1, 2, 3, 4, 5] and [4, 3, 1, 2]. The following arrays are not permutations: [2], [1, 1], [2, 3, 4].
Polycarp invented a really cool p... | 1 | ###### ### ####### ####### ## # ##### ### #####
# # # # # # # # # # # # # ###
# # # # # # # # # # # # # ###
###### ######### # # # # # # ... |
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 | def main():
l=[]
for i in range(5):
l.append(list(map(int, input().strip().split())))
flag=1
for i in range(5):
for j in range(5):
if l[i][j]==1:
flag=0
break
if flag==0:
break
print(abs(i-2)+abs(j-2))
main() |
Comrade Dujikov is busy choosing artists for Timofey's birthday and is recieving calls from Taymyr from Ilia-alpinist.
Ilia-alpinist calls every n minutes, i.e. in minutes n, 2n, 3n and so on. Artists come to the comrade every m minutes, i.e. in minutes m, 2m, 3m and so on. The day is z minutes long, i.e. the day cons... | 3 | (n, m, z) = list(map(int, input().split()))
result = 0
for i in range(1, z + 1):
if i % n == 0 and i % m == 0:
result += 1
print(result) |
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 | for _ in [0]*int(input()):
s = input()
l = len(s)
if len(s)>10:
print(f"{s[0]}{len(s)-2}{s[-1]}")
else:
print(s) |
Dima has a hamsters farm. Soon N hamsters will grow up on it and Dima will sell them in a city nearby.
Hamsters should be transported in boxes. If some box is not completely full, the hamsters in it are bored, that's why each box should be completely full with hamsters.
Dima can buy boxes at a factory. The factory pr... | 1 | n,k=map(int,raw_input().split())
A=list(map(int,raw_input().split()))
maxi=n;
for i in range(1,len(A)+1):
if(n%A[i-1]<=maxi):
maxi=n%A[i-1]
left=n/A[i-1]
type1=i
print type1,left |
Due to the coronavirus pandemic, city authorities obligated citizens to keep a social distance. The mayor of the city Semyon wants to light up Gluharniki park so that people could see each other even at night to keep the social distance.
The park is a rectangular table with n rows and m columns, where the cells of the... | 3 | t=int(input())
import math
for _ in range(t):
n,m=map(int,input().split())
if(n%2==0):
print(m*(n//2))
else:
n-=1
print(m*(n//2)+math.ceil(m/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())
k=[]
for i in range(n):
l=input()
if l not in k:
k.append(l)
print("NO")
else:
print("YES")
|
For $n$ dynamic arrays $A_i$ ($i = 0, 1, ..., n-1$), perform a sequence of the following operations:
* pushBack($t$, $x$): Add element $x$ at the end of $A_t$.
* dump($t$): Print all elements in $A_t$.
* clear($t$): Clear $A_t$. If $A_t$ is empty, do nothing.
$A_i$ is a 0-origin array and it is empty in the initial... | 3 | from collections import deque
def main():
n,m = map(int,input().split())
dq = [deque() for _ in range(n)]
for _ in range(m):
q = list(map(int,input().split()))
if q[0] == 0:dq[q[1]].append(q[2])
elif q[0] == 1:print (' '.join(map(str,dq[q[1]])))
else :dq[q[1]].clear()
if ... |
Suppose you are performing the following algorithm. There is an array v_1, v_2, ..., v_n filled with zeroes at start. The following operation is applied to the array several times β at i-th step (0-indexed) you can:
* either choose position pos (1 β€ pos β€ n) and increase v_{pos} by k^i;
* or not choose any posit... | 3 | from math import factorial
from collections import Counter, defaultdict
from heapq import heapify, heappop, heappush
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.bu... |
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())
ta=(c-1)//b+1
ao=(a-1)//d+1
print('Yes') if ta<=ao else print('No') |
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=str(input())
c=0
while (len(n)>1):
n=str(sum(list(map(int,str(n)))))
c += 1
print(c) |
The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict o... | 1 | def my_key(item):
return order[item[1]]
order ={'rat':0, 'woman':1, 'child':1, 'man':2, 'captain':3}
people = input()
store = []
for i in range(people):
x = raw_input().split()
store.append((x[0],x[1]))
store.sort(key = my_key)
for i in store:
print(i[0])
|
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 | t=input()
x=[]
y=""
for i in range(len(t)):
if t[i] !='+':
x.append(int(t[i]))
x=sorted(x)
if len(x)>1:
for i in range(len(x)-1):
y=y+str(x[i])+'+'
y=y+str(x[len(x)-1])
else:
y=str(x[0])
print(y) |
Students in a class are making towers of blocks. Each student makes a (non-zero) tower by stacking pieces lengthwise on top of each other. n of the students use pieces made of two blocks and m of the students use pieces made of three blocks.
The students donβt want to use too many blocks, but they also want to be uniq... | 3 | n, m = map(int, input().split())
start = 0
end = 10**10
while (end - start > 1):
mid = (end + start) // 2
two = mid // 2 - mid // 6
three = mid // 3 - mid // 6
six = mid // 6
nn = n
mm = m
nn -= two
mm -= three
nn = max(nn, 0)
mm = max(mm, 0)
if (six >= nn + mm):
e... |
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... | 1 | x = raw_input()
y = raw_input()
x = x.lower()
y = y.lower()
if x > y:
print 1
elif x < y:
print -1
else:
print 0 |
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 | from math import ceil
q = input().split()
print(int(int(q[0])*int(q[1])/2)) |
There is a game called "I Wanna Be the Guy", consisting of n levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game.
Little X can pass only p levels of the game. And Little Y can pass only q levels of the game. You are given the indices of levels Little X can pass ... | 3 | '''
Codeforces 268A
@autor Yergali B
'''
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
a=a[1:]
b=b[1:]
c=sorted(a+b)
d=[]
for i in range(len(c)):
if c[i] not in d:
d.append(c[i])
print(('Oh, my keyboard!','I become the guy.')[len(d)==n])
|
Let's call an array t dominated by value v in the next situation.
At first, array t should have at least 2 elements. Now, let's calculate number of occurrences of each number num in t and define it as occ(num). Then t is dominated (by v) if (and only if) occ(v) > occ(v') for any other number v'. For example, arrays [1... | 3 | import sys
# input = sys.stdin.buffer.readline
input = sys.stdin.readline
from collections import deque
q = int(input())
for _ in range(q):
n = int(input())
x = list ( map(int,input().split()))
# s=set()
shortes =9999999999
dic ={}
# dq = deque()
for i in range(n):
if x[i] in dic.ke... |
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.
The language is that peculiar as it has exactly one variable, called x. Also, there are two operations:
* Operation ++ increases the value of variable x by 1.
* Operation -- decreases the value of variable x by 1.... | 1 | n = input()
x = 0
for i in range(n):
s = raw_input()
if 'X' in s and '+' in s:
x+=1
elif 'X' in s and '-' in s:
x -= 1
print x |
Roma works in a company that sells TVs. Now he has to prepare a report for the last year.
Roma has got a list of the company's incomes. The list is a sequence that consists of n integers. The total income of the company is the sum of all integers in sequence. Roma decided to perform exactly k changes of signs of sever... | 3 | import sys
import math
import collections
import bisect
def get_ints(): return map(int, sys.stdin.readline().strip().split())
def get_list(): return list(map(int, sys.stdin.readline().strip().split()))
def get_string(): return sys.stdin.readline().strip()
n,k=get_list()
arr=get_list()
neg=[]
pos=[]
for i in arr:
if... |
Your friend has n cards.
You know that each card has a lowercase English letter on one side and a digit on the other.
Currently, your friend has laid out the cards on a table so only one side of each card is visible.
You would like to know if the following statement is true for cards that your friend owns: "If a car... | 3 | s = input()
hv = ['a','e','i','o','u','1','3','5','7','9']
ans = 0
for i in range(len(s)):
if s[i] in hv:
ans += 1
print(ans) |
Alicia has an array, a_1, a_2, β¦, a_n, of non-negative integers. For each 1 β€ i β€ n, she has found a non-negative integer x_i = max(0, a_1, β¦, a_{i-1}). Note that for i=1, x_i = 0.
For example, if Alicia had the array a = \{0, 1, 2, 0, 3\}, then x = \{0, 0, 1, 2, 2\}.
Then, she calculated an array, b_1, b_2, β¦, b_n: ... | 3 | n=int(input())
b=list(map(int,input().split()))
a=[]
prevmax=0
for i in range(n):
if(i==0):
a.append(b[i])
prevmax=a[i]
else:
a.append(b[i]+max(0,prevmax))
if(a[i]>prevmax):
prevmax=a[i]
print(*a)
|
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." β an excerpt from contest rules.
A total of n participants took part in the contest (n β₯ k), and you already know their scores. Calculate how many ... | 3 | n, k= map(int, input().split())
separated_number = list(map(int, input().split()))
count=0
num = k-1
for i in separated_number:
if(i>0 and i>=separated_number[num]):
count = count+1
print(count) |
Alice and Bob play ping-pong with simplified rules.
During the game, the player serving the ball commences a play. The server strikes the ball then the receiver makes a return by hitting the ball back. Thereafter, the server and receiver must alternately make a return until one of them doesn't make a return.
The one ... | 3 | for _ in range(int(input())):
x,y=map(int,input().split())
print((x-1),y) |
Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is n.
There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains 2 apartments, every other floor contains x apartments each. Apartments are numbered starting from one, from... | 3 | for _ in range(int(input())):
n,x=map(int, input().split())
ans=1
val=2
while n>val:
ans+=1
val+=x
print(ans)
|
Gennady owns a small hotel in the countryside where he lives a peaceful life. He loves to take long walks, watch sunsets and play cards with tourists staying in his hotel. His favorite game is called "Mau-Mau".
To play Mau-Mau, you need a pack of 52 cards. Each card has a suit (Diamonds β D, Clubs β C, Spades β S, or ... | 3 | n=input()
x=list(map(str,input().split()))
k=0
for i in range(5):
if x[i][0]==n[0] or x[i][1]==n[1]:
k=1
break
if k==1:
print("YES")
else:
print("NO")
|
Note that this is the first problem of the two similar problems. You can hack this problem only if you solve both problems.
You are given a tree with n nodes. In the beginning, 0 is written on all edges. In one operation, you can choose any 2 distinct leaves u, v and any real number x and add x to values written on al... | 3 | import sys
input=sys.stdin.readline
from collections import deque
n=int(input())
if n==2:
print('YES')
exit()
if n==3:
print('NO')
exit()
Edges=[[] for _ in range(n)]
for _ in range(n-1):
u,v=map(lambda x: int(x)-1,input().split())
Edges[u].append(v)
Edges[v].append(u)
for i,E in enumerate(E... |
Find the least common multiple (LCM) of given n integers.
Constraints
* 2 β€ n β€ 10
* 1 β€ ai β€ 1000
* Product of given integers ai(i = 1, 2, ... n) does not exceed 231-1
Input
n
a1 a2 ... an
n is given in the first line. Then, n integers are given in the second line.
Output
Print the least common multiple of th... | 1 | def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a%b)
n = int(raw_input())
a = map(int, raw_input().split())
l = a[0]
for i in range(1,len(a)):
b = a[i]
g = gcd(l,b)
l = l*b/g
print l
|
Since Grisha behaved well last year, at New Year's Eve he was visited by Ded Moroz who brought an enormous bag of gifts with him! The bag contains n sweet candies from the good ol' bakery, each labeled from 1 to n corresponding to its tastiness. No two candies have the same tastiness.
The choice of candies has a direc... | 3 | n,k=map(int,input().split())
if k==1:
print(n)
else:
bits=len(bin(n)[2:])
print(2**bits-1) |
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 | from sys import *
from collections import *
input = stdin.readline
for _ in range(int(input())):
n = int(input())
a = list(map(int,input().split()))
b = [0]*(n)
c = [0]*(n)
d = defaultdict(lambda:0)
mx = 0
for i in range(n):
if(d[a[i]] == 1):
break
... |
Long story short, shashlik is Miroslav's favorite food. Shashlik is prepared on several skewers simultaneously. There are two states for each skewer: initial and turned over.
This time Miroslav laid out n skewers parallel to each other, and enumerated them with consecutive integers from 1 to n in order from left to ri... | 3 | inp = list(map(int, input().split()))
n = inp[0]
k = inp[1]
result = None
for i in range( 1, k + 2):
sub = []
j = i
while j <= n:
sub.append(j)
j += (k * 2) + 1
if j - k > n:
if (not result) or (len(result) > len(sub)):
result = sub
print(len(result))
out = ""
for x in result:
out += str(x) + " "... |
You are given a string s, consisting of n lowercase Latin letters.
A substring of string s is a continuous segment of letters from s. For example, "defor" is a substring of "codeforces" and "fors" is not.
The length of the substring is the number of letters in it.
Let's call some string of length n diverse if and o... | 3 | import sys
n = sys.stdin.readline()
fullstring = sys.stdin.readline().rstrip()
saved = fullstring[0]
flag = False
out = ''
for c in fullstring:
if c != saved:
out = saved + c
flag = True
break
if flag:
print("YES")
print(out)
else:
print("NO") |
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())
ss = []
for i in range(n):
ss.append(input())
als = [chr(i) for i in range(97, 97+26)]
for i in range(n):
ok = []
ng = []
tar = ss[i]
le = len(tar)
k = 0
naga = 1
con = 0
while (k < le -1):
if tar[k] != tar[k+1] and con == 0:
... |
Polycarp is preparing the first programming contest for robots. There are n problems in it, and a lot of robots are going to participate in it. Each robot solving the problem i gets p_i points, and the score of each robot in the competition is calculated as the sum of p_i over all problems i solved by it. For each prob... | 3 | # ------------------- fast io --------------------
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... |
You are given two arrays a and b, both of length n.
Let's define a function f(l, r) = β_{l β€ i β€ r} a_i β
b_i.
Your task is to reorder the elements (choose an arbitrary order of elements) of the array b to minimize the value of β_{1 β€ l β€ r β€ n} f(l, r). Since the answer can be very large, you have to print it modulo... | 3 | from operator import itemgetter
import functools
n=int(input())
a=[int(i) for i in input().split(" ")]
b=[int(i) for i in input().split(" ")]
b.sort()
id=[a[i]*(i+1)*(n-i) for i in range(n)]
id=sorted(id)
ans=0
for i in range(n):
ans+=id[i]*b[n-i-1]
ans%=998244353
print(ans) |
You are given a permutation of length n. Recall that the permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2, 3, 1, 5, 4] is a permutation, but [1, 2, 2] is not a permutation (2 appears twice in the array) and [1, 3, 4] is also not a permutation (n=3 but there is 4 ... | 3 | for _ in range(int(input())):
n = int(input())
l = list(map(int,input().split()))
k = [0]*n
v = n-1
i = 1
d = {}
for h in range(n):
d[l[h]] = h
for __t in range(n):
if v:
w = d[i]
i += 1
for t in range(w,-1,-1):
if t-1 >... |
There are three friend living on the straight line Ox in Lineland. The first friend lives at the point x1, the second friend lives at the point x2, and the third friend lives at the point x3. They plan to celebrate the New Year together, so they need to meet at one point. What is the minimum total distance they have to... | 3 | n = list(map(int,input().split()))
n.sort()
c = n[2] - n[0]
print(c) |
Hilbert's Hotel is a very unusual hotel since the number of rooms is infinite! In fact, there is exactly one room for every integer, including zero and negative integers. Even stranger, the hotel is currently at full capacity, meaning there is exactly one guest in every room. The hotel's manager, David Hilbert himself,... | 3 | t = int(input())
while t:
t += -1
n = int(input())
l = list(map(int, input().split()))
check = [0] * (n)
for i in range(n):
check[(i + l[i]) % n] = 1
if 0 in check: print("NO")
else: print("YES") |
In order to do some research, n^2 labs are built on different heights of a mountain. Let's enumerate them with integers from 1 to n^2, such that the lab with the number 1 is at the lowest place, the lab with the number 2 is at the second-lowest place, β¦, the lab with the number n^2 is at the highest place.
To transpor... | 3 | n=int(input())
a=[]
b=[]
temp=1
for i in range(n):
b=[]
for j in range(n):
b.append(temp)
temp+=1
a.append(b)
for i in range(n):
if(i%2==1):
a[i].reverse()
for i in range(n):
for j in range(n):
print(a[j][i],end=" ")
print() |
Twilight Sparkle was playing Ludo with her friends Rainbow Dash, Apple Jack and Flutter Shy. But she kept losing. Having returned to the castle, Twilight Sparkle became interested in the dice that were used in the game.
The dice has m faces: the first face of the dice contains a dot, the second one contains two dots, ... | 3 | line = input().split()
m = int(line[0])
n = int(line[1])
result = 0
for current in range(m, 0, -1):
result += current * (pow(current/m, n) - pow((current - 1)/m, n))
print(result)
|
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.
Petya recently learned to determine whether a string of lowercase Latin letters is lucky. For each i... | 3 | #!/usr/bin/env python3
stringLen = int(input())
abc = 'abcdefghijklmnopqrstuvwxyz'
counter = 0
luckyString = ''
for letter in range(stringLen):
letterIndex = counter % (len(abc))
counter += 1
if letter <= 3:
luckyString += (abc[letter])
elif letter >= 4:
luckyString += luckyString[lett... |
During the break the schoolchildren, boys and girls, formed a queue of n people in the canteen. Initially the children stood in the order they entered the canteen. However, after a while the boys started feeling awkward for standing in front of the girls in the queue and they started letting the girls move forward each... | 3 | nt=input().split(" ")
nt[0]=int(nt[0])
nt[1]=int(nt[1])
st=input()
l=list(st)
nst=""
while(nt[1]>0):
i=0
while i<nt[0]-1:
if(l[i]=="B" and l[i+1]=="G"):
l[i],l[i+1]=l[i+1],l[i]
i+=1
i+=1
nt[1]-=1
for i in range(nt[0]):
nst+=l[i]
print(nst) |
Once upon a time there were several little pigs and several wolves on a two-dimensional grid of size n Γ m. Each cell in this grid was either empty, containing one little pig, or containing one wolf.
A little pig and a wolf are adjacent if the cells that they are located at share a side. The little pigs are afraid of ... | 3 | #B. Little Pigs and Wolves
n,m = map(int,input().split())
matrix = []
for _ in range(n):
matrix.append(list(input()))
c = 0
for i in range(n):
for j in range(m):
if matrix[i][j] != 'P':
continue
if i>0 and matrix[i-1][j] == 'W':
matrix[i][j] = '.'
matrix[i-1][... |
Valeric and Valerko missed the last Euro football game, so they decided to watch the game's key moments on the Net. They want to start watching as soon as possible but the connection speed is too low. If they turn on the video right now, it will "hang up" as the size of data to watch per second will be more than the si... | 3 | tamanho_video_p_sg, tamanho_podem_baixar, duracao = input().split()
b = (int(tamanho_video_p_sg) * int(duracao)) #/int(tamanho_podem_baixar)
c = int(tamanho_podem_baixar)
aux = 0
aux2 = 0
while(True):
# if b > c or b > (c*int(duracao)):
if (c * int(duracao)) + aux2 < b:
aux = aux + 1
aux2 = aux... |
Ohana Matsumae is trying to clean a room, which is divided up into an n by n grid of squares. Each square is initially either clean or dirty. Ohana can sweep her broom over columns of the grid. Her broom is very strange: if she sweeps over a clean square, it will become dirty, and if she sweeps over a dirty square, it ... | 3 | n = int(input())
xxs = {}
sol = 1
for i in range(n):
xs = input()
if xs in xxs:
val = xxs[xs]
xxs[xs] = val + 1
sol = max(sol, val + 1)
else:
xxs[xs] = 1
print (sol)
|
A positive integer is called composite if it can be represented as a product of two positive integers, both greater than 1. For example, the following numbers are composite: 6, 4, 120, 27. The following numbers aren't: 1, 2, 3, 17, 97.
Alice is given a sequence of n composite numbers a_1,a_2,β¦,a_n.
She wants to choos... | 3 | import sys
primes = '''2 3 5 7 11 13 17 19 23 29 31'''.replace('\n','\t').split('\t')
primes = [int(x) for x in primes]
queries = int(sys.stdin.readline())
def queryFindFences():
colors = {}
count = int(sys.stdin.readline())
heights = sys.stdin.readline().strip().split()
complexNeighbors = [0]*count
... |
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 | aa = input().upper()
bb = input().upper()
x = len(aa)
u = 0
i = 0
while i < x:
if aa[i] > bb[i]:
u = 1
break
else:
if aa[i] < bb[i]:
u = -1
break
else:
i += 1
print(u) |
After a long party Petya decided to return home, but he turned out to be at the opposite end of the town from his home. There are n crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.
The crossroads are represented as a string s of length n, where s_i = A, if there is... | 3 |
import math
import bisect
def rints():
return list(map(int,input().split()))
t = int(input())
for _ in range(t):
a,b,p = rints()
s = input()
pos = len(s)-1
price = {'A': a, 'B': b}
total = 0
while pos>0 and total + price[s[pos-1]] <= p:
total += price[s[pos-1]]
means = s[p... |
Lee was cleaning his house for the party when he found a messy string under the carpets. Now he'd like to make it clean accurately and in a stylish way...
The string s he found is a binary string of length n (i. e. string consists only of 0-s and 1-s).
In one move he can choose two consecutive characters s_i and s_{i... | 3 | t = int(input())
for _ in range(t):
n = int(input())
s = list(input())
cnt0, cnt1 = -1, -1
for i in range(n):
if s[i] == "1":
cnt0 = i
break
for i in range(n):
if s[n - i - 1] == "0":
cnt1 = i
break
if min(cnt0, cnt1) == -1 or cnt0 ... |
Guy-Manuel and Thomas have an array a of n integers [a_1, a_2, ..., a_n]. In one step they can add 1 to any element of the array. Formally, in one step they can choose any integer index i (1 β€ i β€ n) and do a_i := a_i + 1.
If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and T... | 3 | x = int(input())
for i in range(x):
c=0
n=int(input())
l=list(map(int,input().split()))
for k in range(n):
if l[k]==0:
l[k]+=1
c+=1
if sum(l)==0:
print(c+1)
else:
print(c)
|
Calculate the minimum number of characters you need to change in the string s, so that it contains at least k different letters, or print that it is impossible.
String s consists only of lowercase Latin letters, and it is allowed to change characters only to lowercase Latin letters too.
Input
First line of input con... | 1 |
s = raw_input()
k = int(raw_input())
chars = [0] * (ord('z') - ord('a') + 1)
for c in s:
chars[ord(c) - ord('a')] += 1
d = sum([1 for c in chars if c != 0])
exc = 0
for c in chars:
if c > 1:
exc += c - 1
if k - d > exc or k > 26 or k > len(s):
print "impossible"
else:
print max(0, k - d)... |
One beautiful July morning a terrible thing happened in Mainframe: a mean virus Megabyte somehow got access to the memory of his not less mean sister Hexadecimal. He loaded there a huge amount of n different natural numbers from 1 to n to obtain total control over her energy.
But his plan failed. The reason for this w... | 1 | # -*- coding: utf-8 -*-
def calc_r(x):
if len(x) == 1:
if int(x) == 0:
return 1
return 2
r = calc_r(x[1:])
if int(x[0]) == 1:
return r + 2 ** (len(x) - 1)
elif int(x[0]) > 1:
return 2 ** len(x)
else:
return r
x = str(int(raw_input().strip()))
print... |
Johnny has recently found an ancient, broken computer. The machine has only one register, which allows one to put in there one variable. Then in one operation, you can shift its bits left or right by at most three positions. The right shift is forbidden if it cuts off some ones. So, in fact, in one operation, you can m... | 3 | import sys
lines = []
for line in sys.stdin:
if 'Exit' == line.rstrip():
break
lines.append(line)
t = int(lines[0])
for i in range(1,t+1):
a, b = [int(x) for x in lines[i].split(' ')][0], [int(x) for x in lines[i].split(' ')][1]
if a == b:
print(0)
continue
# the only time... |
Let LCM(x, y) be the minimum positive integer that is divisible by both x and y. For example, LCM(13, 37) = 481, LCM(9, 6) = 18.
You are given two integers l and r. Find two integers x and y such that l β€ x < y β€ r and l β€ LCM(x, y) β€ r.
Input
The first line contains one integer t (1 β€ t β€ 10000) β the number of tes... | 3 | for _ in range(int(input())):
l, r = map(int, input().split())
if r>=2*l:
print(l, 2*l)
else:
print(-1, -1) |
A progress bar is an element of graphical interface that displays the progress of a process for this very moment before it is completed. Let's take a look at the following form of such a bar.
A bar is represented as n squares, located in line. To add clarity, let's number them with positive integers from 1 to n from t... | 3 |
n,k,t = map(int,input().split())
x = t/100
u = n*k
d=[]
if k*n/u<=t/100:
print(*([k]*n))
else:
for i in range(1,n+1):
a=k*i
if a/u<x:
#print(a/u,x)
d.append(k)
else:
if a/u==x:
d.append(k)
print(*(d+[0]*(n-le... |
After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 β€ si β€ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum nu... | 3 | from collections import defaultdict
n = int(input())
A = [int(x) for x in input().split()]
taxi = 0
d = defaultdict(int)
for i in A:
d[i] += 1
if d[1] < d[3]:
taxi = d[3] + d[4] + ((d[2]-1) // 2) + 1
else:
taxi = d[3] + d[4] + (d[2] // 2)
d[1] = d[1] - d[3]
d[2] = d[2] % 2
if d[1] / 2 > d[2]:
... |
Iroha has a sequence of N strings S_1, S_2, ..., S_N. The length of each string is L.
She will concatenate all of the strings in some order, to produce a long string.
Among all strings that she can produce in this way, find the lexicographically smallest one.
Here, a string s=s_1s_2s_3...s_n is lexicographically sma... | 3 | n, l = map(int, input().split())
S = sorted(input() for _ in range(n))
print("".join(S)) |
You have two integers l and r. Find an integer x which satisfies the conditions below:
* l β€ x β€ r.
* All digits of x are different.
If there are multiple answers, print any of them.
Input
The first line contains two integers l and r (1 β€ l β€ r β€ 10^{5}).
Output
If an answer exists, print any of them. Oth... | 3 | l,r=map(int,input().split())
flag=0
def distinct(n):
a=[]
while n>0:
r=n%10
a.append(r)
n=n//10
if len(set(a))==len(a):
return True
else:
return False
for i in range(l,r+1):
s=distinct(i)
if s:
print(i)
flag=1
break
if flag==0:
print(-1) |
Hooray! Polycarp turned n years old! The Technocup Team sincerely congratulates Polycarp!
Polycarp celebrated all of his n birthdays: from the 1-th to the n-th. At the moment, he is wondering: how many times he turned beautiful number of years?
According to Polycarp, a positive integer is beautiful if it consists of ... | 3 | for _ in range(int(input())):
n = int(input())
if n >= 1 and n <= 9:
print(n)
else:
ans,i,d = 9,1,2
while int(str(i)*d) <= n:
ans += 1
i += 1
if i == 10:
... |
Vasya, or Mr. Vasily Petrov is a dean of a department in a local university. After the winter exams he got his hands on a group's gradebook.
Overall the group has n students. They received marks for m subjects. Each student got a mark from 1 to 9 (inclusive) for each subject.
Let's consider a student the best at some... | 3 |
## Running Time ===>>> 826 ms
data = input().split()
N, M = int(data[0]), int(data[1])
marks = [None] * N
for i in range(N):
marks[i] = input()
answer = 0
subj = []
if N == 1:
print(N)
else:
for i in range(N):
tmp_answer = 0
for col in range(M):
fla... |
Summer vacation ended at last and the second semester has begun. You, a Kyoto University student, came to university and heard a rumor that somebody will barricade the entrance of your classroom. The barricade will be built just before the start of the A-th class and removed by Kyoto University students just before the... | 3 | line = input().split()
N, A, B = int(line[0]), int(line[1]), int(line[2])
minus = 0
for i in range(N):
if A <= int(input()) < B:
minus += 1
print(N - minus) |
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them.
Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain nu... | 3 | s=input().split("WUB")
print(*s)
|
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())
s=list(input())
i=1
ans=0
while i<len(s):
if s[i]==s[i-1]:
s.pop(i)
ans+=1
else:
i+=1
print(ans)
|
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 | n=int(input())
x=x1=x1=a1=a2=a3=0
if(n>=0):
print(n)
else:
n=n*(-1)
a1=n//100
a2=(n%100)//10
a3=n%10
x1=a1*10+a2
x2=a1*10+a3
x=min(x1,x2)
print(x*(-1))
|
Marina loves strings of the same length and Vasya loves when there is a third string, different from them in exactly t characters. Help Vasya find at least one such string.
More formally, you are given two strings s1, s2 of length n and number t. Let's denote as f(a, b) the number of characters in which strings a and ... | 3 | n,t=map(int,input().split())
s1=input()
s2=input()
diff=0
same=0
for i in range(len(s1)):
if(s1[i]!=s2[i]):
diff+=1
else:
same+=1
if(diff>2*t):
print(-1)
exit()
ans=['' for i in range(n)]
count=t
if(diff<=t):
for i in range(len(s1)):
if(s1[i]!=s2[i]):
if(s1[i]!='a... |
How many hours do we have until New Year at M o'clock (24-hour notation) on 30th, December?
Constraints
* 1β€Mβ€23
* M is an integer.
Input
Input is given from Standard Input in the following format:
M
Output
If we have x hours until New Year at M o'clock on 30th, December, print x.
Examples
Input
21
Output... | 1 | #coding:utf-8
now = int(raw_input())
time = 48 - now
print time
|
There are N computers and N sockets in a one-dimensional world. The coordinate of the i-th computer is a_i, and the coordinate of the i-th socket is b_i. It is guaranteed that these 2N coordinates are pairwise distinct.
Snuke wants to connect each computer to a socket using a cable. Each socket can be connected to onl... | 3 | N,*E=map(int,open(0))
a,c=1,0
for _,d in sorted((e,2*(i<N)-1)for i,e in enumerate(E)):
if c*d<0:a=abs(a*c)%(10**9+7)
c+=d
print(a) |
Your task is to calculate the distance between two $n$ dimensional vectors $x = \\{x_1, x_2, ..., x_n\\}$ and $y = \\{y_1, y_2, ..., y_n\\}$.
The Minkowski's distance defined below is a metric which is a generalization of both the Manhattan distance and the Euclidean distance.
\\[ D_{xy} = (\sum_{i=1}^n |x_i - y_i|^p)... | 3 | import math
n = int(input())
X = list(map(int, input().split()))
Y = list(map(int, input().split()))
D = [abs(X[i]-Y[i]) for i in range(n)]
for p in [1, 2, 3, -1]:
if p == -1:
print(max(D))
else:
print(math.pow(sum([math.pow(D[i],p) for i in range(n)]),1/p))
|
According to rules of the Berland fashion, a jacket should be fastened by all the buttons except only one, but not necessarily it should be the last one. Also if the jacket has only one button, it should be fastened, so the jacket will not swinging open.
You are given a jacket with n buttons. Determine if it is fasten... | 3 | n=int(input())
x=[int(q) for q in input().split()]
if n==1:
if x[0]==0:
print("NO")
else:
print("YES")
else:
if x.count(0)==1:
print("YES")
else:
print("NO") |
Today, Mezo is playing a game. Zoma, a character in that game, is initially at position x = 0. Mezo starts sending n commands to Zoma. There are two possible commands:
* 'L' (Left) sets the position x: =x - 1;
* 'R' (Right) sets the position x: =x + 1.
Unfortunately, Mezo's controller malfunctions sometimes. ... | 3 | a=int(input())
s=input()
print(s.count('R')+s.count('L')+1)
|
The Little Elephant enjoys recursive functions.
This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows:
... | 1 | n = int(raw_input())
ans = []
for i in range(n):
if i == 0:
ans.append(str(n))
ans.append(' ')
elif i < n - 1:
ans.append(str(i))
ans.append(' ')
else:
ans.append(str(n - 1))
print ''.join(ans)
|
Gerald got a very curious hexagon for his birthday. The boy found out that all the angles of the hexagon are equal to <image>. Then he measured the length of its sides, and found that each of them is equal to an integer number of centimeters. There the properties of the hexagon ended and Gerald decided to draw on it.
... | 1 | a = [int(i) for i in raw_input().split()]
print sum(a[:3])**2-sum([a[2*i]**2 for i in xrange(3)]) |
You are given a integer n (n > 0). Find any integer s which satisfies these conditions, or report that there are no such numbers:
In the decimal representation of s:
* s > 0,
* s consists of n digits,
* no digit in s equals 0,
* s is not divisible by any of it's digits.
Input
The input consists of mult... | 3 | kt = int(input())
for t in range(kt):
n = int(input())
if n == 1:
print(-1)
continue
answer = [2 for i in range(n)]
summa = 2*n+1
answer[-1]=3
if summa % 3 == 0:
answer[0] = 3
for i in range(len(answer)):
print(answer[i], end="")
print()
|
You are given an array of n integers a_1,a_2,...,a_n.
You have to create an array of n integers b_1,b_2,...,b_n such that:
* The array b is a rearrangement of the array a, that is, it contains the same values and each value appears the same number of times in the two arrays. In other words, the multisets \\{a_1,a_... | 3 |
for t in range(int(input())):
n = int(input())
li = list(map(int, input().split()))
s = sum(li)
if s==0:
print("NO")
else:
print("YES")
if s>0:
li.sort()
li.reverse()
print(*li)
else:
li.sort()
print(*li)
... |
A permutation p is an ordered group of numbers p1, p2, ..., pn, consisting of n distinct positive integers, each is no more than n. We'll define number n as the length of permutation p1, p2, ..., pn.
Simon has a positive integer n and a non-negative integer k, such that 2k β€ n. Help him find permutation a of length 2n... | 1 | import sys
n , m = map(int , raw_input().split())
a = []
b = []
for i in range(n):
a.append(1 + i*2)
for i in range(n):
b.append(2 * (i+1))
for i in range(m):
a[i] , b[i] = b[i] , a[i]
for i in range(n):
print a[i],b[i],
|
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Bi... | 3 | import math
def tinh(a):
if(((a%2==0)and (a!=2)) or (a%4==0)) :
print("YES")
else:
print("NO")
if __name__ =="__main__":
b=int(input())
tinh(b)
|
The bear decided to store some raspberry for the winter. He cunningly found out the price for a barrel of honey in kilos of raspberry for each of the following n days. According to the bear's data, on the i-th (1 β€ i β€ n) day, the price for one barrel of honey is going to is xi kilos of raspberry.
Unfortunately, the b... | 3 | N, c = map(int, input().split())
A = list(map(int, input().split()))
cur = None
for i in range(1, len(A)):
if cur == None: cur = A[i - 1] - A[i]
else:
cur = max(cur, A[i - 1] - A[i])
if cur == None or cur - c < 0: print(0)
else:
print(cur - c) |
Mike has a string s consisting of only lowercase English letters. He wants to change exactly one character from the string so that the resulting one is a palindrome.
A palindrome is a string that reads the same backward as forward, for example strings "z", "aaa", "aba", "abccba" are palindromes, but strings "codeforc... | 3 | n=input()
c=0
for i in range(len(n)//2):
if n[i]!=n[len(n)-1-i]:
c+=1
if c==0:
if len(n)%2==0:
print("NO")
else:
print("YES")
elif c==1:
print("YES")
else:
print("NO") |
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 ... | 1 | m,d=map(int,raw_input().split())
ma=30
if m==1 or m==3 or m==5 or m==7 or m==8 or m==10 or m==12:
if d<=5:
print 5
else:
print 6
elif m==2:
if d==1:
print 4
else:
print 5
else:
if d<=6:
print 5
else:
print 6
|
Little C loves number Β«3Β» very much. He loves all things about it.
Now he has a positive integer n. He wants to split n into 3 positive integers a,b,c, such that a+b+c=n and none of the 3 integers is a multiple of 3. Help him to find a solution.
Input
A single line containing one integer n (3 β€ n β€ 10^9) β the integ... | 3 | n = int(input())
q = n // 3
r = n % 3
if r == 0:
if n == 3:
print(1, 1, 1)
elif n == 6:
print(2, 2, 2)
else:
if q % 3 == 0:
print(q - 2, q + 1, q + 1)
else:
print(q, q, q)
elif r == 1:
if n == 4:
print(2, 1, 1)
elif n == 7:
pri... |
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 | entrada = raw_input()
new_string = ""
for x in range(len(entrada)):
if entrada[x].lower() != "a" and entrada[x].lower() != "o" and entrada[x].lower() != "y" and entrada[x].lower() != "e" and entrada[x].lower() != "u" and entrada[x].lower() != "i":
new_string += "." + entrada[x].lower()
print new_string |
Andryusha is an orderly boy and likes to keep things in their place.
Today he faced a problem to put his socks in the wardrobe. He has n distinct pairs of socks which are initially in a bag. The pairs are numbered from 1 to n. Andryusha wants to put paired socks together and put them in the wardrobe. He takes the sock... | 3 | n=int(input())
l=map(int,input().split())
s={}
c=0
a=[]
for i in l:
if i not in s:
s[i]=1
c+=1
else:
c-=1
a.append(c)
print(max(a)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.