problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
You are given a string A. Find a string B, where B is a palindrome and A is a subsequence of B.
A subsequence of a string is a string that can be derived from it by deleting some (not necessarily consecutive) characters without changing the order of the remaining characters. For example, "cotst" is a subsequence of "c... | 3 |
#!/usr/bin/python3
import sys
s = sys.stdin.readline().strip()
print(s + s[::-1][1:])
sys.exit()
|
There was once young lass called Mary,
Whose jokes were occasionally scary.
On this April's Fool
Fixed limerick rules
Allowed her to trip the unwary.
Can she fill all the lines
To work at all times?
On juggling the words
Right around two-thirds
Sh... | 3 |
n = int(input())
for i in range(2, n):
if n % i == 0:
print(i, end = "")
print(n // i)
break
|
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Bi... | 3 | import sys
w = int(sys.stdin.readline())
if w %2 == 1 or w == 2:
print("NO")
else:
print("YES") |
An X-layered kagami mochi (X ≥ 1) is a pile of X round mochi (rice cake) stacked vertically where each mochi (except the bottom one) has a smaller diameter than that of the mochi directly below it. For example, if you stack three mochi with diameters of 10, 8 and 6 centimeters from bottom to top in this order, you have... | 3 | N = int(input())
D = [input() for _ in range(N)]
print(len(set(D))) |
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 | str1 = raw_input()
str2 = raw_input()
str1 = str1.lower()
str2 = str2.lower()
for i in range(len(str1)):
if str1[i] > str2[i]:
print 1
break
elif str1[i] < str2[i]:
print -1
break
elif i == len(str1) - 1:
print 0
break
|
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory.
George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living... | 3 | counter = 0
for i in range(int(input())):
x, y = map(int, input().split())
if y - x >= 2:
counter += 1
print(counter)
|
There is data on sales of your company. Your task is to write a program which identifies good workers.
The program should read a list of data where each item includes the employee ID i, the amount of sales q and the corresponding unit price p. Then, the program should print IDs of employees whose total sales proceeds ... | 1 | while True:
num = int(raw_input())
if num == 0: break
dic = {}
odr = []
for i in range(num):
uid, p, q = map(int, raw_input().split())
if dic.has_key(uid): dic[uid] += p * q
else:
dic[uid] = p * q
odr.append(uid)
if max(dic.values()) < 1000000: p... |
A string of length 6 consisting of lowercase English letters is said to be coffee-like if and only if its 3-rd and 4-th characters are equal and its 5-th and 6-th characters are also equal.
Given a string S, determine whether it is coffee-like.
Constraints
* S is a string of length 6 consisting of lowercase English l... | 3 | s = input()
print('Yes' if s[2] == s[3] and s[4] == s[5] else 'No') |
We will buy a product for N yen (the currency of Japan) at a shop.
If we use only 1000-yen bills to pay the price, how much change will we receive?
Assume we use the minimum number of bills required.
Constraints
* 1 \leq N \leq 10000
* N is an integer.
Input
Input is given from Standard Input in the following for... | 3 | n=int(input())
print((-(-n//1000))*1000-n) |
La Confiserie d'ABC sells cakes at 4 dollars each and doughnuts at 7 dollars each. Determine if there is a way to buy some of them for exactly N dollars. You can buy two or more doughnuts and two or more cakes, and you can also choose to buy zero doughnuts or zero cakes.
Constraints
* N is an integer between 1 and 10... | 3 | print('YNeos'[140910>>int(input())&1::2]) |
Given is an integer N. Find the number of digits that N has in base K.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^9
* 2 \leq K \leq 10
Input
Input is given from Standard Input in the following format:
N K
Output
Print the number of digits that N has in base K.
Examples
Input
11 2
O... | 3 | n, k = map(int, input().split())
import math
print(int(math.log(n,k)) + 1) |
Arkady's morning seemed to be straight of his nightmare. He overslept through the whole morning and, still half-asleep, got into the tram that arrived the first. Some time after, leaving the tram, he realized that he was not sure about the line number of the tram he was in.
During his ride, Arkady woke up several time... | 3 | # A. Determine Line
ans = set(range(1, 101))
for _ in range(int(input())):
# https://stackoverflow.com/questions/3697432/how-to-find-list-intersection
ans &= set(list(map(int, input().split()))[1:])
print(*ans)
|
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 | rownum = 0
moves = 0
for i in range(5):
row = input().split()
for column in range(5):
if(row[column] == '1'):
moves = abs(2 - rownum) + abs(2 - column)
rownum += 1
print(moves)
|
An African crossword is a rectangular table n × m in size. Each cell of the table contains exactly one letter. This table (it is also referred to as grid) contains some encrypted word that needs to be decoded.
To solve the crossword you should cross out all repeated letters in rows and columns. In other words, a lette... | 1 | import sys
n, m = map(int, raw_input().split())
g = []
for i in range(n):
g.append(raw_input())
row, col = {}, {}
for i in range(n):
for j, c in enumerate(g[i]):
if (i, c) not in row: row[i, c] = 0
if (j, c) not in col: col[j, c] = 0
row[i, c] += 1
col[j, c] += 1
for i in range(n... |
Let N be a positive integer.
There is a numerical sequence of length 3N, a = (a_1, a_2, ..., a_{3N}). Snuke is constructing a new sequence of length 2N, a', by removing exactly N elements from a without changing the order of the remaining elements. Here, the score of a' is defined as follows: (the sum of the elements ... | 3 | import heapq
n = int(input())
a = list(map(int,input().split()))
big_a = []
for i in range(n):
heapq.heappush(big_a,a[i])
small_a = []
for i in range(n):
heapq.heappush(small_a,-a[3*n-1-i])
now_big = sum(big_a)
now_small = -sum(small_a)
big_data = [now_big]
small_data = [now_small]
for k in range(n):
no... |
On the xy-plane, Snuke is going to travel from the point (x_s, y_s) to the point (x_t, y_t). He can move in arbitrary directions with speed 1. Here, we will consider him as a point without size.
There are N circular barriers deployed on the plane. The center and the radius of the i-th barrier are (x_i, y_i) and r_i, r... | 3 | from collections import defaultdict
import heapq
from math import sqrt
# -*- coding: utf-8 -*-
# python template for atcoder1
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline
def calc(b1, b2):
x1, y1, r1 = b1
x2, y2, r2 = b2
d = sqrt((x1-x2)**2+(y1-y2)**2)
return max(d-(r1+r2), 0)
... |
You are given a string s consisting of n lowercase Latin letters.
You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.
String s = s_1 s_2 ... s_n is lexicograp... | 1 |
n=int(raw_input())
s=raw_input()
"""
n=9
s='110011101'
if s[:n-1]==s[1:]:
print s[:n-1]
exit()
"""
for i in range(1,n):
if s[i-1]>s[i]:
print s[:i-1]+s[i:]
exit()
print s[:n-1]
exit()
|
This is the easy version of this problem. The only difference between easy and hard versions is the constraints on k and m (in this version k=2 and m=3). Also, in this version of the problem, you DON'T NEED to output the answer by modulo.
You are given a sequence a of length n consisting of integers from 1 to n. The s... | 3 | def fun(a):
return ((a-1)*a)//2
for y in range(int(input())):
n=int(input())
lst=list(map(int,input().split()))
lst.sort()
cnt=0
p=0
if n<3:
print('0')
else:
for i in range(2,n):
foo=0
while lst[i]-lst[p]>2:
foo=1
... |
Jzzhu has a big rectangular chocolate bar that consists of n × m unit squares. He wants to cut this bar exactly k times. Each cut must meet the following requirements:
* each cut should be straight (horizontal or vertical);
* each cut should go along edges of unit squares (it is prohibited to divide any unit choc... | 3 | l = input().split()
n = int(l[0])
m = int(l[1])
k = int(l[2])
if ( k <= n+m-2 ):
if ( k < n ):
outn = int((n / (k + 1))) * m
else:
outn = int(m / (k - n + 2))
if ( k < m):
outm = int( m / ( k + 1)) * n
else:
outm = int( n / ( k - m + 2 ))
print ("", max( outn, outm),... |
A coordinate line has n segments, the i-th segment starts at the position li and ends at the position ri. We will denote such a segment as [li, ri].
You have suggested that one of the defined segments covers all others. In other words, there is such segment in the given set, which contains all other ones. Now you want... | 1 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
class Segment(object):
def __init__(self, idx, *args):
self._idx = idx
self._l = args[0]
self._r = args[1]
self._range = (self._r - self._l)
def contains(self, s):
return self._l <= s._l and self._r >= s._r
def sortByR... |
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.
Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character... | 1 | #coding: utf-8
name = raw_input()
count = 0
alphabet = "abcdefghijklmnopqrstuvwxyz"
arrow = 0
for i in range(len(name)):
indexWhilePositive = arrow
stepsWhilePositive = 0
previusArrow = arrow
indexWhileNegative = arrow
stepsWhileNegative = 0
while(True):
if (indexWhilePositive > 25):
indexWhilePositive = ... |
You are given n strings s_1, s_2, …, s_n consisting of lowercase Latin letters.
In one operation you can remove a character from a string s_i and insert it to an arbitrary position in a string s_j (j may be equal to i). You may perform this operation any number of times. Is it possible to make all n strings equal?
In... | 3 | t = int(input())
for x in range(0, t):
i = int(input())
dict_char = {}
for y in range(0, i):
ip_str = input()
for char in ip_str:
if dict_char.get(char):
dict_char[char] += 1
else:
dict_char[char] = 1
code_break = False
for char... |
There are n piles of stones, where the i-th pile has a_i stones. Two people play a game, where they take alternating turns removing stones.
In a move, a player may remove a positive number of stones from the first non-empty pile (the pile with the minimal index, that has at least one stone). The first player who canno... | 3 |
t=int(input())
for i in range(t):
n=int(input())
ch=input()
L=[int(i)for i in ch.split()]
i=0
while i<n and L[i]==1:
i+=1
if i==n:
i+=1
if i%2:
print("Second")
else:
print("First")
|
Interaction
This is an interactive problem. You need to read participants' queries from standard input and print your responses to standard output. You don't know the number of queries upfront, so you'll need to process them as you get them; you'll know you're done once you reach the end of the file.
In each query,... | 3 | try:
while True:
x = input()
print("NO")
except:
pass
|
Chouti was tired of the tedious homework, so he opened up an old programming problem he created years ago.
You are given a connected undirected graph with n vertices and m weighted edges. There are k special vertices: x_1, x_2, …, x_k.
Let's define the cost of the path as the maximum weight of the edges in it. And th... | 3 | def main():
import sys
input = sys.stdin.readline
# def find(a):
# if par[a] == a:
# return a
# par[a] = find(par[a])
# return par[a]
def find(a):
upd = []
cur = a
while par[cur] != cur:
upd.append(cur)
cur = par[cur]
... |
There are N flowers arranged in a row. For each i (1 \leq i \leq N), the height and the beauty of the i-th flower from the left is h_i and a_i, respectively. Here, h_1, h_2, \ldots, h_N are all distinct.
Taro is pulling out some flowers so that the following condition is met:
* The heights of the remaining flowers ar... | 3 | import sys
input = sys.stdin.readline
n = int(input())
h = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
sellogn = []
seln = 0
selfunc = max
selone = 0
selb = []
def __init__(a, func=max, one=-10 ** 18):
global sellogn, seln, selfunc, selone, selb
sellogn = (len(a) - 1).bit_length... |
The School №0 of the capital of Berland has n children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value ti:
* ti = 1, if the i-th child is good at programming,
*... | 1 | n=input()
l=raw_input().split()
r=[[],[],[]]
for i in range(n):
r[{'1':0,'2':1,'3':2}[l[i]]].append(i+1)
n=min(map(len,r))
print n
for i in range(n):
print r[0].pop(),r[1].pop(),r[2].pop() |
Find the union of two sets $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and $B = \\{b_0, b_1, ..., b_{m-1}\\}$.
Constraints
* $1 \leq n, m \leq 200,000$
* $0 \leq a_0 < a_1 < ... < a_{n-1} \leq 10^9$
* $0 \leq b_0 < b_1 < ... < b_{m-1} \leq 10^9$
Input
The input is given in the following format.
$n$
$a_0 \; a_1 \; ... \; a... | 3 |
n = int(input())
a = list(map(int,input().split()))
m = int(input())
b = list(map(int,input().split()))
c = sorted(set(a)|set(b))
for d in c:print (d)
|
We have a grid of H rows and W columns. Initially, there is a stone in the top left cell. Shik is trying to move the stone to the bottom right cell. In each step, he can move the stone one cell to its left, up, right, or down (if such cell exists). It is possible that the stone visits a cell multiple times (including t... | 3 | h,w=map(int,input().split());c=0
for i in range(h):
a=input()
b=[]
for j in range(w):b.append(a[j])
c+=b.count("#")
print("Possible"if h+w-1==c else"Impossible") |
Ted has a pineapple. This pineapple is able to bark like a bulldog! At time t (in seconds) it barks for the first time. Then every s seconds after it, it barks twice with 1 second interval. Thus it barks at times t, t + s, t + s + 1, t + 2s, t + 2s + 1, etc.
<image>
Barney woke up in the morning and wants to eat the ... | 1 | t, s, x = map(int, raw_input().split())
if t % s == x % s and t <= x:
print "YES"
elif x % s == ( t + 1 ) % s and x > t + 1:
print "YES"
else:
print "NO"
|
Every year, hundreds of people come to summer camps, they learn new algorithms and solve hard problems.
This is your first year at summer camp, and you are asked to solve the following problem. All integers starting with 1 are written in one line. The prefix of these line is "123456789101112131415...". Your task is to... | 1 | s = []
n = []
i=0
while len(s)!=1001:
s.append(str(i))
i+=1
for i in range(1001):
if(len(s[i])==1):
n.append(s[i])
elif(len(s[i])==2):
n.append(int(s[i])/10)
n.append(int(s[i])%10)
elif(len(s[i])==3):
n.append((int(s[i])/10)/10)
n.append((int(s[i])/10)%10)
n.append(int(s[i])%10)
elif(len(s[i])==4):
... |
Nastya just made a huge mistake and dropped a whole package of rice on the floor. Mom will come soon. If she sees this, then Nastya will be punished.
In total, Nastya dropped n grains. Nastya read that each grain weighs some integer number of grams from a - b to a + b, inclusive (numbers a and b are known), and the wh... | 3 | import sys
def read_int():
return int(sys.stdin.readline())
def read_ints():
return list(map(int, sys.stdin.readline().split()))
t = read_int()
for j in range(t):
n, a, b, c, d = read_ints()
res = 'Yes' if n*(a-b) <= c+d and n*(a+b) >= c-d else 'No'
print(res)
|
You are given a sequence of integers of length n and integer number k. You should print any integer number x in the range of [1; 10^9] (i.e. 1 ≤ x ≤ 10^9) such that exactly k elements of given sequence are less than or equal to x.
Note that the sequence can contain equal elements.
If there is no such x, print "-1" (w... | 3 | n, k = map(int, input().split())
numbers_in_order = sorted(list(map(int, input().split())))
if k == 0:
if numbers_in_order[0] > 1:
print(numbers_in_order[0]-1)
else:
print(-1)
if k > 0:
if k == n:
print(numbers_in_order[k-1])
elif numbers_in_order[k-1] == numbers_in_order[k]:
... |
Ivan recently bought a detective book. The book is so interesting that each page of this book introduces some sort of a mystery, which will be explained later. The i-th page contains some mystery that will be explained on page a_i (a_i ≥ i).
Ivan wants to read the whole book. Each day, he reads the first page he didn'... | 3 | a = input()
lst = [int(x) for x in input().split()]
ans = 0
temp = 0
for i in range(int(a)):
if temp < lst[i]:
temp = lst[i]
if i + 1 < temp:
continue
ans += 1
print(ans)
|
Write a program which prints the central coordinate $(p_x, p_y)$ and the radius $r$ of a circumscribed circle of a triangle which is constructed by three points $(x_1, y_1)$, $(x_2, y_2)$ and $(x_3, y_3)$ on the plane surface.
Constraints
* $-100 \leq x_1, y_1, x_2, y_2, x_3, y_3 \leq 100$
* $ n \leq 20$
Input
Inpu... | 1 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
def calc_det(lis):
return lis[0]*lis[3]-lis[1]*lis[2]
def sq(x):
return x*x
for s in sys.stdin:
d = map(float, s.split() )
if len(d) == 1:
continue
x1,y1,x2,y2,x3,y3 = d[0],d[1],d[2],d[3],d[4],d[5]
d11 = 2*(x3-x2)
d12 = 2*(y3-y2)
d21 = 2*(... |
You got a job as a marketer in a pet shop, and your current task is to boost sales of cat food. One of the strategies is to sell cans of food in packs with discounts.
Suppose you decided to sell packs with a cans in a pack with a discount and some customer wants to buy x cans of cat food. Then he follows a greedy str... | 3 | import sys
sys.setrecursionlimit(10**5 + 5)
from collections import defaultdict as dft, deque
def ml():return list(map(int,input().split()))
def mp():return map(int,input().split())
def solve():
a,b=mp()
if a*2 >b:
print("YES")
else:
print("NO")
#t=1
t=int(input())
for _ in range(t):
... |
This is the easy version of the problem. The difference between the versions is the constraint on n and the required number of operations. You can make hacks only if all versions of the problem are solved.
There are two binary strings a and b of length n (a binary string is a string consisting of symbols 0 and 1). In ... | 3 | from fractions import Fraction
from collections import defaultdict
import math
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.... |
In this problem you are to calculate the sum of all integers from 1 to n, but you should take all powers of two with minus in the sum.
For example, for n = 4 the sum is equal to - 1 - 2 + 3 - 4 = - 4, because 1, 2 and 4 are 20, 21 and 22 respectively.
Calculate the answer for t values of n.
Input
The first line of... | 3 | from math import log
a = input()
b = []
for i in range(int(a)):
b.append(int(input()))
def sumLessPowersOfTwo(N):
# Sum of an AP is (n/2)*(a + l)
sumToN = int((N*(1 + N))//2)
# Sum of a GP is (a(r^n - 1)/(r-1), and a = 1, r - 1 = 1
# r = 2, and to find n
n = int(log(N, 2) + 1)
sumOfTwos =... |
Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths a, b, and c. Now he needs to find out some possible integer length d of the fourth straight fence segment so that he can build the fence using these four... | 3 | for _ in range(int(input())):
p,n,m = map(int,input().split())
print(p+n+m-1) |
A word or a sentence in some language is called a pangram if all the characters of the alphabet of this language appear in it at least once. Pangrams are often used to demonstrate fonts in printing or test the output devices.
You are given a string consisting of lowercase and uppercase Latin letters. Check whether thi... | 3 | po=int(input())
a=str(input())
a=a.lower()
a=" ".join(a)
a=a.split()
b=[]
for k in range (po):
letra=a[k]
bol=1
for t in range (len(b)):
if letra==b[t]:
bol=0
break
if bol==1:
b.append(letra)
if len(b)==26:
... |
A tourist hiked along the mountain range. The hike lasted for n days, during each day the tourist noted height above the sea level. On the i-th day height was equal to some integer hi. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. ... | 3 | n, m = [int(x) for x in input().split()]
d = []
h = []
s = 0
amax = 0
for i in range(m):
p, q = [int(x) for x in input().split()]
d.append(p)
h.append(q)
for i in range(m-1):
if abs((h[i+1]-h[i]))/(d[i+1]-d[i]) > 1:
print('IMPOSSIBLE')
s += 1
break
if s == 0:
for i in range(m... |
You are given an integer n.
You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times:
1. Replace n with n/2 if n is divisible by 2;
2. Replace n with 2n/3 if n is divisible by 3;
3. Replace n with 4n/5 if n is divisible by 5.
For example, you can repl... | 3 | for _ in range(int(input())):
n=int(input())
m,flag=0,False
while n>1:
if n%2==0:
n//=2
m+=1
elif n%3==0:
n=(n*2)//3
m+=1
elif n%5==0:
n=(n*4)//5
m+=1
else:
flag=True
break
pri... |
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 | from sys import stdin, stdout
def func():
n = int(stdin.readline().rstrip())
if n % 2 == 0 and n > 2:
stdout.write('YES\n')
else:
stdout.write('NO\n')
func()
|
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 | yes=input()
n=[]
for i in yes:
if i.isdigit():
n.append(int(i))
n.sort()
k=0
for i in yes:
if i.isdigit():
print(n[k],end="")
k+=1
else:
print(i,end="")
|
Little girl Susie went shopping with her mom and she wondered how to improve service quality.
There are n people in the queue. For each person we know time ti needed to serve him. A person will be disappointed if the time he waits is more than the time needed to serve him. The time a person waits is the total time wh... | 3 | input()
li = sorted(list(map(int, input().split())))[::-1]
s = 0
k = 0
while li:
a = li.pop()
if a>=s:
k += 1
s += a
print(k)
|
Polycarpus is a system administrator. There are two servers under his strict guidance — a and b. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program re... | 3 | l=[]
m=[]
n=[]
p=[]
a=int(input())
for i in range(a):
t,x,y=map(int,input().split())
if t==1:
l.append(x)
m.append(y)
else:
n.append(x)
p.append(y)
if sum(l)>=sum(m):
print("LIVE")
else:
print("DEAD")
if sum(n)>=sum(p):
print("LIVE")
else:
print("DEAD") |
You are given an integer n and an array a_1, a_2, …, a_n. You should reorder the elements of the array a in such way that the sum of MEX on prefixes (i-th prefix is a_1, a_2, …, a_i) is maximized.
Formally, you should find an array b_1, b_2, …, b_n, such that the sets of elements of arrays a and b are equal (it is equ... | 3 | t = int(input())
for i in range(t):
n = int(input())
l = [int(x) for x in input().split()]
l.sort()
nw=[]
print(l[0], end=' ')
for i in range(1, len(l), 1):
if l[i]!=l[i-1]:
print(l[i], end=' ')
else:
nw.append(l[i])
for i in range(len(nw)):
... |
When preparing a tournament, Codeforces coordinators try treir best to make the first problem as easy as possible. This time the coordinator had chosen some problem and asked n people about their opinions. Each person answered whether this problem is easy or hard.
If at least one of these n people has answered that th... | 3 | n=int(input())
a=list(map(int,input().split(" ")))
c=0
for i in a:
if i==1:
c=c+1
if c>=1:
print("HARD")
else:
print("EASY") |
New Year is coming and you are excited to know how many minutes remain before the New Year. You know that currently the clock shows h hours and m minutes, where 0 ≤ hh < 24 and 0 ≤ mm < 60. We use 24-hour time format!
Your task is to find the number of minutes before the New Year. You know that New Year comes when the... | 3 | def ri():
return int(input())
def rl():
return list(map(int, input().split()))
def solve():
h, m = rl()
print (60 - m + 60 * (24 - h - 1))
t = ri()
for i in range(t):
solve()
|
A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all n squad soldiers to line up on the parade ground.
By the military charter the soldiers should stand in the order of non-increasing of their h... | 3 |
n = int(input())
soldiers = list(map(int,input().split(' ')))
def maxAndmin(l):
ind_mx = 0
ind_mn = 0
for i in range(len(l)):
if l[i] > l[ind_mx]:
ind_mx = i
if l[i] <= l[ind_mn]:
ind_mn = i
return ind_mx,ind_mn
ind_mx,ind_mn = maxAndmin(s... |
You got a job as a marketer in a pet shop, and your current task is to boost sales of cat food. One of the strategies is to sell cans of food in packs with discounts.
Suppose you decided to sell packs with a cans in a pack with a discount and some customer wants to buy x cans of cat food. Then he follows a greedy str... | 3 | a=int(input())
v=list()
for i in range(a):
l,r=map(int,input().split())
if r-l<l:
v.append(1)
else:
v.append(0)
for i in range(a):
if v[i]==1:
print("YES")
else:
print("NO") |
You are given two strings a and b consisting of lowercase English letters, both of length n. The characters of both strings have indices from 1 to n, inclusive.
You are allowed to do the following changes:
* Choose any index i (1 ≤ i ≤ n) and swap characters a_i and b_i;
* Choose any index i (1 ≤ i ≤ n) and sw... | 3 | n=int(input())
a=input()
b=input()
o=0
for i in range(n//2):
if b[i]==b[n-1-i]:
o+=int(a[i]!=a[n-1-i])
else:
o+=2-len(set([a[i],a[n-1-i]])&set([b[i],b[n-1-i]]))
if n%2:
o+=int(a[n//2]!=b[n//2])
print(o) |
You are given a sequence of positive integers a1, a2, ..., an. Find all such indices i, that the i-th element equals the arithmetic mean of all other elements (that is all elements except for this one).
Input
The first line contains the integer n (2 ≤ n ≤ 2·105). The second line contains elements of the sequence a1, ... | 1 | n = int(raw_input())
s = map(int, raw_input().split())
z = sum(s)
r = [i + 1 for i in xrange(n) if abs((z - s[i]) / float(n - 1) - s[i]) < 1e-10]
print len(r)
if len(r) > 0:
print ' '.join(map(str, r))
|
You are given positive integers A and B.
If A is a divisor of B, print A + B; otherwise, print B - A.
Constraints
* All values in input are integers.
* 1 \leq A \leq B \leq 20
Input
Input is given from Standard Input in the following format:
A B
Output
If A is a divisor of B, print A + B; otherwise, print B -... | 3 | A, B = [int(i) for i in input().split()]
print(B+A) if B % A == 0 else print(B-A) |
For given an integer $n$, print all permutations of $\\{1, 2, ..., n\\}$ in lexicographic order.
Constraints
* $1 \leq n \leq 9$
Input
An integer $n$ is given in a line.
Output
Print each permutation in a line in order. Separate adjacency elements by a space character.
Examples
Input
2
Output
1 2
2 1
Inpu... | 3 | from itertools import permutations
n = int(input())
p = list(permutations((str(i) for i in range(1,n+1))))
# for i in p:
# print(*i)
ans = (' '.join(t) for t in p)
print('\n'.join(ans))
|
Small, but very brave, mouse Brain was not accepted to summer school of young villains. He was upset and decided to postpone his plans of taking over the world, but to become a photographer instead.
As you may know, the coolest photos are on the film (because you can specify the hashtag #film for such).
Brain took a ... | 3 | def decider(l):
for i in l:
if i=='C' or i=='M' or i=='Y':
return 1
return 0
n,m=map(int,input().split())
f=0
for i in range(n):
if f==1:
inp=input()
continue
p=decider(input().split())
if p==1:
f=1
if f:
print('#Color')
else:
print('#Black&White') |
You are given one integer number n. Find three distinct integers a, b, c such that 2 ≤ a, b, c and a ⋅ b ⋅ c = n or say that it is impossible to do it.
If there are several answers, you can print any.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 100)... | 3 | #!/usr/bin/env python
# coding: utf-8
# In[7]:
import math
def divisor(n):
for i in range(2,int(math.sqrt(n))+1):
if n%i==0:
k=n//i
for j in range(2,int(math.sqrt(k))+1):
if j!=i and k%j==0:
t=k//j
if t!=i and t!=j:
... |
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second.
One day in 230 AD Shapur was trying to find out if any one can possibly do... | 3 | number1 = input()
number2 = input()
list1 = [int(x) for x in number1]
list2 = [int(x) for x in number2]
for i in range(len(list1)):
if list1[i] != list2[i]:
list1[i] = 1
else:
list1[i] = 0
print("".join(map(str,list1))) |
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 | x,y=map(int,input().split())
i=0
while x<=y:
y*=2
x*=3
i+=1
print(i) |
AtCoDeer the deer found two rectangles lying on the table, each with height 1 and width W. If we consider the surface of the desk as a two-dimensional plane, the first rectangle covers the vertical range of [0,1] and the horizontal range of [a,a+W], and the second rectangle covers the vertical range of [1,2] and the ho... | 3 | W, a, b = map(int, input().split())
L = [b - (a + W), a - (b + W), 0]
print(max(L)) |
For the given integer n (n > 2) let's write down all the strings of length n which contain n-2 letters 'a' and two letters 'b' in lexicographical (alphabetical) order.
Recall that the string s of length n is lexicographically less than string t of length n, if there exists such i (1 ≤ i ≤ n), that s_i < t_i, and for a... | 3 | t=int(input())
while (t>0):
t=t-1
n,k=map(int,input().split())
i=1
while (k>i):
k-=i
i+=1
print('a'*(n-i-1)+'b'+'a'*(i-k)+'b'+'a'*(k-1)) |
The Department of economic development of IT City created a model of city development till year 2100.
To prepare report about growth perspectives it is required to get growth estimates from the model.
To get the growth estimates it is required to solve a quadratic equation. Since the Department of economic developmen... | 3 | abc = [int(i) for i in input().split()]
a = abc[0]
b = abc[1]
c = abc[2]
x = (-b+(((b**2)-((4*a)*c))**0.5))/(2*a)
y = (-b-(((b**2)-((4*a)*c))**0.5))/(2*a)
print(max(x,y))
print(min(x,y))
|
Polycarp came up with a new programming language. There are only two types of statements in it:
* "x := s": assign the variable named x the value s (where s is a string). For example, the statement var := hello assigns the variable named var the value hello. Note that s is the value of a string, not the name of a v... | 3 | def f(a):
Res = 0
for i in range(len(a) - 3):
if a[i:i + 4] == "haha":
Res += 1
return Res
for m in range(int(input())):
X = {}
for k in range(int(input())):
A = input().split()
if len(A) == 3:
X[A[0]] = [A[2][:3], A[2][-3:], f(A[2])]
else:
... |
Let us call a pair of integer numbers m-perfect, if at least one number in the pair is greater than or equal to m. Thus, the pairs (3, 3) and (0, 2) are 2-perfect while the pair (-1, 1) is not.
Two integers x, y are written on the blackboard. It is allowed to erase one of them and replace it with the sum of the number... | 1 | I=lambda:map(int, raw_input().split())
a,b,m=I()
a,b=min(a,b),max(a,b)
if b<m and a+b<=a: print -1;exit()
if b>=m: print 0;exit()
ans=(b-a+1)/b
a,b=b,a+ans*b
a,b=min(a,b),max(a,b)
while b<m:
a,b=a+b,b
ans+=1
a,b=min(a,b),max(a,b)
print ans |
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())
for _ in range(t):
n,x,a1,b1 = map(int, input().split())
b = max(a1,b1)
a = min(a1,b1)
cd = b-a
lsp = a-1
rsp = n-b
if (lsp+rsp) <= x:
print(n-1)
elif (lsp+rsp) > x:
print(cd+x) |
Polycarpus has an array, consisting of n integers a1, a2, ..., an. Polycarpus likes it when numbers in an array match. That's why he wants the array to have as many equal numbers as possible. For that Polycarpus performs the following operation multiple times:
* he chooses two elements of the array ai, aj (i ≠ j);
... | 1 | n=input()
a=map(int, raw_input().split())
s=sum(a)
if s%n==0:
print n
else:
print n-1 |
Pay attention to the non-standard memory limit in this problem.
In order to cut off efficient solutions from inefficient ones in this problem, the time limit is rather strict. Prefer to use compiled statically typed languages (e.g. C++). If you use Python, then submit solutions on PyPy. Try to write an efficient solut... | 3 | for t in range(int(input())):
n = int(input())
arr = list(map(int,input().split()))
dict={}
for i in range(n):
sum = arr[i]
for j in range(i+1,n):
sum+=arr[j]
if sum>n:
break
else:
if sum not in dict:
dict[sum]=1
ct = 0
for i in range(n):
if arr[i] in dict:
ct+=1
print(ct)
|
Joisino is working as a receptionist at a theater.
The theater has 100000 seats, numbered from 1 to 100000.
According to her memo, N groups of audiences have come so far, and the i-th group occupies the consecutive seats from Seat l_i to Seat r_i (inclusive).
How many people are sitting at the theater now?
Constrai... | 3 | a = 0
for i in range(int(input())):a -= eval(input().replace(' ', '-'))-1
print(a) |
Takahashi has a string S consisting of lowercase English letters.
Starting with this string, he will produce a new one in the procedure given as follows.
The procedure consists of Q operations. In Operation i (1 \leq i \leq Q), an integer T_i is provided, which means the following:
* If T_i = 1: reverse the string S... | 3 | S = input()
f = ""
b = ""
rev = False
for i in range(int(input())):
t = input().split()
if t[0] == "1":
rev ^= True
tmp = f
f = b
b = tmp
elif t[1] == "1":
f += t[2]
else:
b += t[2]
if rev: S = S[::-1]
f = f[::-1]
print(f + S + b)
|
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()
s1=''
l=s.split('WUB')
l2=[]
for i in l:
if i!='':
s1=s1+i+' '
s2=s1
print(s2) |
Several days ago you bought a new house and now you are planning to start a renovation. Since winters in your region can be very cold you need to decide how to heat rooms in your house.
Your house has n rooms. In the i-th room you can install at most c_i heating radiators. Each radiator can have several sections, but ... | 3 | from math import ceil, floor
n = int(input())
for _ in range(n):
n, s = map(int, input().split())
ans = 0
v1 = s // n
c2 = s % n
c1 = n - c2
# c1 = n - rem
ans += (v1**2) * c1
ans += ((v1 + 1)**2) * c2
print(ans)
|
A permutation of length n 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 in the array).
Let p be any permutation of length ... | 3 | N = int(input())
Ans = []
for i in range(N):
A = int(input())
B = list(map(int, input().split()))
Ans.append(B[::-1])
for i in Ans:
for j in i:
print(j, end =" ")
print() |
Naruto has sneaked into the Orochimaru's lair and is now looking for Sasuke. There are T rooms there. Every room has a door into it, each door can be described by the number n of seals on it and their integer energies a_1, a_2, ..., a_n. All energies a_i are nonzero and do not exceed 100 by absolute value. Also, n is e... | 3 | T = int(input())
for t in range(T):
n = int(input())
a = input()
a = [int(x) for x in a.split()]
b = []
for i in range(n // 2):
b.append(a[2 * i + 1])
b.append(-a[2 * i])
print(' '.join([str(x) for x in (b)]))
|
You are given a number n and an array b_1, b_2, …, b_{n+2}, obtained according to the following algorithm:
* some array a_1, a_2, …, a_n was guessed;
* array a was written to array b, i.e. b_i = a_i (1 ≤ i ≤ n);
* The (n+1)-th element of the array b is the sum of the numbers in the array a, i.e. b_{n+1} = a_1... | 3 | def main():
from sys import stdin, stdout
for _ in range(int(stdin.readline())):
n = int(stdin.readline())
arr = list(map(int,stdin.readline().split()))
arrsum = sum(arr)
mydict = {}
for i in range(len(arr)):
if arr[i] in mydict:
mydict[arr[i]... |
A permutation is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as pi. We'll call number n the size of permutation p1, p2, ..., pn.
Nickolas adores permutations. He likes some permutations more than the o... | 3 | n = int(input())
if n % 2 == 1:
print(-1)
else:
p = [i+1 if i % 2==1 else i-1 for i in range(1, n+1)]
print(' '.join([str(p2) for p2 in p]))
|
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm:
* if the last digit of the number is non-zero, she decreases the number by one;
* if the last digit of the number is ze... | 1 | def f(n,k):
for i in range(k):
if n%10==0:
n = n/10
else:
n = n-1
return n
input = raw_input().split()
n = int(input[0])
k = int(input[1])
print(f(n,k))
|
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())
first = [int(x) for x in input().split()]
second = [int(x) for x in input().split()]
third = [int(x) for x in input().split()]
first.sort()
third.sort()
ans = []
i, j = 0, 0
while i < len(first):
if j >= len(third) or first[i] != third[j]:
ans.append(first[i])
i += 1
continue
i += 1
j += 1
if ... |
There are n candies in a row, they are numbered from left to right from 1 to n. The size of the i-th candy is a_i.
Alice and Bob play an interesting and tasty game: they eat candy. Alice will eat candy from left to right, and Bob — from right to left. The game ends if all the candies are eaten.
The process consists o... | 3 | def solution(n,arr):
boolA, boolB = True, False
i = 0
currA,currB = [0],[0]
a,b = 0,n-1
while a<=b:
if boolA:
chA = 0
while chA<=currB[-1] and a<=b:
chA += arr[a]
a += 1
currA.append(chA)
boolA = False
... |
The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her n students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often oddl... | 3 | n, p = map(int, input().split())
px = list(map(int, input().split()))
diff = []
px.sort()
for i in range(p-1):
diff.append(px[i+1] - px[i])
sum = []
i =0
while(i < p-n+1):
k=0
for j in range(n-1):
k += diff[i+j]
sum.append(k)
i += 1
sum.sort()
# print(diff)
# print(sum)
print(sum[0])
|
Anna is a girl so brave that she is loved by everyone in the city and citizens love her cookies. She is planning to hold a party with cookies. Now she has a vanilla cookies and b chocolate cookies for the party.
She invited n guests of the first type and m guests of the second type to the party. They will come to the ... | 3 | import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
a, b, n, m = map(int, input().split())
if a+b < n+m:
print('No')
continue
if a > b:
if b >= m:
print('Yes')
else:
print('No')
else:
if a >= m:
print('Y... |
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,h = [int(x) for x in input().split(' ')]
ai = [int(x) for x in input().split(' ')]
c = 0
for i in ai:
if i > h: c += 2
else: c += 1
print(c) |
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.
The language is that peculiar as it has exactly one variable, called x. Also, there are two operations:
* Operation ++ increases the value of variable x by 1.
* Operation -- decreases the value of variable x by 1.... | 3 | n = int(input())
x = 0
for i in range(0,n):
s = input()
if s[1]== "+":
x+=1
else:
x-=1
print(x) |
Three friends are going to meet each other. Initially, the first friend stays at the position x = a, the second friend stays at the position x = b and the third friend stays at the position x = c on the coordinate axis Ox.
In one minute each friend independently from other friends can change the position x by 1 to the... | 3 | '''input
8
3 3 4
10 20 30
5 5 5
2 4 3
1 1000000000 1000000000
1 1000000000 999999999
3 2 5
3 2 6
'''
from sys import stdin
# main starts
q = int(stdin.readline().strip())
for _ in range(q):
cood = list(map(int, stdin.readline().split()))
cood.sort()
a, b, c = cood
if c - a >= 2:
a += 1
... |
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy... | 1 | n= int(raw_input())
l=[]
for _ in range(n):
i,j,k = map(int, raw_input().split())
l.append([i,j,k])
#print l
ii=0
jj=0
kk=0
for s in l:
ii =ii + s[0]
jj = jj + s[1]
kk = kk + s[2]
#print ii,jj,kk
if ii ==0 and jj == 0 and kk == 0:
print 'YES'
else:
print 'NO' |
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... | 1 | n = input()
mon = sorted(map(int, raw_input().strip().split()), reverse=True)
s = 0
a = sum(mon)/2 + 1
for i in range(n):
s = s + mon[i]
if s >= a:
break
print i+1 |
A frog lives on the axis Ox and needs to reach home which is in the point n. She starts from the point 1. The frog can jump to the right at a distance not more than d. So, after she jumped from the point x she can reach the point x + a, where a is an integer from 1 to d.
For each point from 1 to n is known if there is... | 3 | from sys import stdin,stdout
nmbr = lambda: int(input())
lst = lambda: list(map(int, input().split()))
PI=float('inf')
for _ in range(1):#nmbr()):
n,k=lst()
s=input()
dp=[PI]*n
dp[0]=0
for i in range(1,n):
if s[i]=='0':continue
for j in range(i-1,i-k-1,-1):
dp[i]=min(dp[i... |
Fox Ciel starts to learn programming. The first task is drawing a fox! However, that turns out to be too hard for a beginner, so she decides to draw a snake instead.
A snake is a pattern on a n by m table. Denote c-th cell of r-th row as (r, c). The tail of the snake is located at (1, 1), then it's body extends to (1,... | 1 | n,m=map(int,raw_input().split(' '))
for i in range(n):
if i%2==0:
print '#'*m
else:
if (i+1)%4==0:
print '#'+'.'*(m-1)
else:
print '.'*(m-1)+'#'
|
Our good friend Mole is trying to code a big message. He is typing on an unusual keyboard with characters arranged in following way:
qwertyuiop
asdfghjkl;
zxcvbnm,./
Unfortunately Mole is blind, so sometimes it is problem for him to put his hands accurately. He accidentally move... | 3 | ggg = input()
s = input()
s = list(s)
right = []
left = []
keyboard = 'qwertyuiopasdfghjkl;zxcvbnm,./'
if ggg == 'R':
for i in s:
right.append(keyboard[keyboard.index(i) - 1])
else:
for i in s:
left.append(keyboard[keyboard.index(i) + 1])
right = ''.join(right)
left = ''.join(left)
if ggg == 'R'... |
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 | word = input()
hello_word = 'hello'
i = 0
position = 0
positions = [0, 0, 0, 0, 0]
while i < len(hello_word):
meet_char = 0
while position < len(word) and meet_char == 0:
if word[position] == hello_word[i]:
positions[i] = position
meet_char = 1
position += 1
i += 1
... |
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory.
George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living... | 3 | c=0
n=int(input())
for i in range(n):
a,b=map(int,input().split())
if b-a>=2:
c+=1
print(c) |
You are both a shop keeper and a shop assistant at a small nearby shop. You have n goods, the i-th good costs a_i coins.
You got tired of remembering the price of each product when customers ask for it, thus you decided to simplify your life. More precisely you decided to set the same price for all n goods you have.
... | 3 | import math
q=int(input())
for i in range(q):
n=int(input())
A=[x for x in map(int, input().split())]
print(math.ceil(sum(A)/n)) |
A palindrome is a string that reads the same backward as forward. For example, the strings "z", "aaa", "aba", and "abccba" are palindromes, but "codeforces" and "ab" are not. You hate palindromes because they give you déjà vu.
There is a string s. You must insert exactly one character 'a' somewhere in s. If it is poss... | 3 | """
Author - Satwik Tiwari .
"""
#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from functools imp... |
You are playing one RPG from the 2010s. You are planning to raise your smithing skill, so you need as many resources as possible. So how to get resources? By stealing, of course.
You decided to rob a town's blacksmith and you take a follower with you. You can carry at most p units and your follower — at most f units.
... | 3 | from sys import stdin,stdout
from math import gcd,sqrt,factorial,pi
from collections import deque,defaultdict
input=stdin.readline
R=lambda:map(int,input().split())
I=lambda:int(input())
S=lambda:input().rstrip('\n')
L=lambda:list(R())
P=lambda x:stdout.write(x)
lcm=lambda x,y:(x*y)//gcd(x,y)
hg=lambda x,y:((y+x-1)//x)... |
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 | from collections import Counter
t=int(input())
while t>0:
t-=1
s=input()
l=len(s)
tmp=[]
st = [i for i in s]
c=Counter(st)
k=list(c.keys())
#print(c)
for x in k:
if c[x]%2 != 0:
tmp.append(x)
#print(tmp)
#tmp2=[]
i=0
while i<l-1:
ch=st[i]
if ch not in tmp:
if st[i+1] != ch:
tmp.append(ch... |
Every evening Vitalya sets n alarm clocks to wake up tomorrow. Every alarm clock rings during exactly one minute and is characterized by one integer ai — number of minute after midnight in which it rings. Every alarm clock begins ringing at the beginning of the minute and rings during whole minute.
Vitalya will defin... | 3 | import sys
import math as mt
import bisect
#input=sys.stdin.readline
#t=int(input())
t=1
def solve():
i,j,ans=0,0,0
ind=[0]*(n)
suma,ex=1,0
j=0
for i in range(n):
if j<n and ind[i]==0:
while j<n:
if l[j]-l[i]+1<=m:
if j-i+1-... |
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 | import sys
# import math
input = sys.stdin.readline
def int_array():
return list(map(int, input().strip().split()))
def str_array():
return input().strip().split()
def lower_letters():
lowercase = [chr(i) for i in range(97, 97+26)]
return lowercase
def upper_letters():
uppercase = [chr(i) fo... |
Tired of boring office work, Denis decided to open a fast food restaurant.
On the first day he made a portions of dumplings, b portions of cranberry juice and c pancakes with condensed milk.
The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes... | 3 | _=int(input())
for __ in range(_):
a,b,c=sorted(list(map(int,input().split())),reverse=True)
res=0
res+=min(1,a)+min(1,b)+min(1,c)
a-=min(1,a)
b-=min(1,b)
c-=min(1,c)
res+=min([1,a,b])
u=min([1,a,b])
a-=u
b-=u
res+=min([1,a,c])
u=min([1,a,c])
a-=u
c-=u
... |
Imp is watching a documentary about cave painting.
<image>
Some numbers, carved in chaotic order, immediately attracted his attention. Imp rapidly proposed a guess that they are the remainders of division of a number n by all integers i from 1 to k. Unfortunately, there are too many integers to analyze for Imp.
Imp ... | 3 | n,k=map(int,input().split())
l=[]
for i in range(1,min(k+1,30)):
if n%i in l:
print('No')
exit()
l.append(n%i)
print('Yes') |
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 | _ = input()
arr = input()
prev = arr[0]
count = 0
for current_letter in arr[1:]:
if current_letter == prev:
count += 1
else:
prev = current_letter
print(count)
|
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 | l = []
for _ in range(5):
l1 = list(map(int,input().split()))
l.append(l1)
for i in range(5):
for j in range(5):
if l[i][j] == 1:
r,c = i,j
print(abs(2-r)+abs(2-c)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.