problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
A number is ternary if it contains only digits 0, 1 and 2. For example, the following numbers are ternary: 1022, 11, 21, 2002.
You are given a long ternary number x. The first (leftmost) digit of x is guaranteed to be 2, the other digits of x can be 0, 1 or 2.
Let's define the ternary XOR operation ⊙ of two ternary n... | 3 | #grng3n
t = int(input())
ans = []
for _ in range(t):
n = int(input())
a = input()
f = []
s = []
first = True
for i in a:
if i == '0':
f.append(0)
s.append(0)
if i == '1':
if first:
f.append(1)
s.append(0)
... |
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 math import ceil
n = int(input())
x = input().split()
a = x.count("4")
b = x.count("3")
c = x.count("2")
d = x.count("1")
ans = a + b + ceil(c/2)
t = b + 2 * (c%2)
if d <= t:
ans = ans
else:
ans = ans + ceil((d - t)/4)
print(int(ans))
|
Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks.
Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off.
You know that there will be n interesting minutes t1, t2, ..., tn. Yo... | 3 | n = int(input())
l = list(map(int, input().split()))
if n == 1:
if l[0] <= 15:
print(l[0] + 15)
else:
print(15)
exit()
if l[0] > 15:
print(15)
exit()
for i in range(n - 1):
if l[i + 1] - l[i] > 15:
h = (l[i] + 15)
if h > 90:
print(90)
exit(... |
When registering in a social network, users are allowed to create their own convenient login to make it easier to share contacts, print it on business cards, etc.
Login is an arbitrary sequence of lower and uppercase latin letters, digits and underline symbols («_»). However, in order to decrease the number of frauds ... | 3 | s = input()
n = int(input())
b = False
for i in range(n):
col = 0
s1 = input()
if len(s1) == len(s):
for i in range(len(s1)):
if s1[i].upper() == s[i].upper():
col += 1
if s1[i].upper() == 'O' and s[i] == '0':
col += 1
if s1[i] == '... |
You are given a multiset of n integers. You should select exactly k of them in a such way that the difference between any two of them is divisible by m, or tell that it is impossible.
Numbers can be repeated in the original multiset and in the multiset of selected numbers, but number of occurrences of any number in mu... | 3 | import sys
import math
import itertools
import collections
def ii(): return int(input())
def mi(): return map(int, input().split())
def li(): return list(map(int, input().split()))
def lcm(a, b): return abs(a * b) // math.gcd(a, b)
def wr(arr): return ' '.join(map(str, arr))
def revn(n): return str(n)[::-1]
def dd():... |
You have a garland consisting of n lamps. Each lamp is colored red, green or blue. The color of the i-th lamp is s_i ('R', 'G' and 'B' — colors of lamps in the garland).
You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garlan... | 1 | import sys
n = input()
def uncolor(x):
if x==1:
return "G"
elif x==2:
return "B"
else:
return "R"
def color(x):
if x=="R":
return 3
elif x=="G":
return 1
else:
return 2
data = map(color, raw_input())
print >> sys.stderr, data
data = data + [(d... |
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 | """
Author - Satwik Tiwari .
27th Sept , 2020 - Sunday
"""
#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import Byt... |
An n × n table a is defined as follows:
* The first row and the first column contain ones, that is: ai, 1 = a1, i = 1 for all i = 1, 2, ..., n.
* Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the remaining elements are defin... | 3 | n=int(input())
a=[[1 for x in range(n)] for x in range(n)]
for i in range(1,n):
for j in range(1,n):
a[i][j]=a[i-1][j]+a[i][j-1]
print(a[n-1][n-1]) |
Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play t matches of a digit game...
In each of t matches of the digit game, a positive integer is generated. It consists of n digits. The digits of this integer are numerated f... | 3 | for _ in range(int(input())):
n=int(input())
k=str(input())
if n%2==0:
ans=1
for i in range(1,n,2):
if int(k[i])%2==0:
ans=2
break
else:
ans=2
for j in range(0,n,2):
if int(k[j])%2==1:
ans=1
... |
We all know that a superhero can transform to certain other superheroes. But not all Superheroes can transform to any other superhero. A superhero with name s can transform to another superhero with name t if s can be made equal to t by changing any vowel in s to any other vowel and any consonant in s to any other cons... | 3 | str1 = input()
str2 = input()
yes = "Yes"
no = "No"
vowels = ["a", "e", "i", "o", "u"]
flag = 0;
list1 = list(str1)
list2 = list(str2)
if len(str1) == len(str2):
x = len(str1)
for i in range(x) :
if list1[i] in vowels and list2[i] in vowels :
flag += 1
else :
flag += 0
... |
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find ... | 3 | n = int(input())
def lucky(n):
multiples = []
for i in range(2, n+1):
if n%i==0:
multiples.append(str(i))
for i in multiples:
temp = 0
for j in i:
if j in ['4', '7']:
temp += 1
if temp==len(i):
return "YES"
return "NO"
print(lucky(n))
|
You are given two non-negative integers L and R. We will choose two integers i and j such that L \leq i < j \leq R. Find the minimum possible value of (i \times j) \mbox{ mod } 2019.
Constraints
* All values in input are integers.
* 0 \leq L < R \leq 2 \times 10^9
Input
Input is given from Standard Input in the fol... | 3 | L,R = map(int, input().split())
P = min(R, L+2018)
c = []
for i in range(L,P+1):
for j in range(L,P+1):
if i != j:
c.append((i * j) % 2019)
print(min(c)) |
There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct.
It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to bui... | 3 | n=int(input())
l=list(map(int,input().split()))
from random import choice
def quick(liste):
if len(liste)<=1:
return liste
tes=choice(liste)
kic=[i for i in liste if i<tes]
ber=[k for k in liste if k==tes]
boy=[m for m in liste if m>tes]
return quick(kic) + ber +quick(boy)
l=quick(l)
mi... |
Given is a tree T with N vertices. The i-th edge connects Vertex A_i and B_i (1 \leq A_i,B_i \leq N).
Now, each vertex is painted black with probability 1/2 and white with probability 1/2, which is chosen independently from other vertices. Then, let S be the smallest subtree (connected subgraph) of T containing all th... | 3 | import os
import sys
from collections import defaultdict
if os.getenv("LOCAL"):
sys.stdin = open("_in.txt", "r")
sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353
def div_mod(a, b, mod):
return a * pow(b, mod - 2, mod) % mod
N = int(sys.stdin.buffer.rea... |
Chokudai made a rectangular cake for contestants in DDCC 2020 Finals.
The cake has H - 1 horizontal notches and W - 1 vertical notches, which divide the cake into H \times W equal sections. K of these sections has a strawberry on top of each of them.
The positions of the strawberries are given to you as H \times W ch... | 3 | h,w,k=map(int,input().split())
ls=[[0 for t in range(w)] for s in range(h)]
p=1
for i in range(h):
row=list(input())
if "#" in row:
ch=0
for j in range(w):
if row[j]=="#":
if ch==0:
ls[i][j]=p
ch+=1
else:
p+=1
ls[i][j]=p
ch+=... |
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 | def result():
n,x=input().split()
n=int(n)
x=int(x)
ans=True
floor=1
ll=0
ul=2
while ans:
if ll<=n<=ul:
ans=False
else:
floor=floor+1
ll=ll+1
ul=ul+x
print(floor)
t=int(input())
while t>0:
result()
t=t-1 |
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If... | 3 | def main():
x = str(input())
count1 = 0
count0 = 0
notdan = True
for i in x:
if i == '1':
count1 += 1
count0 = 0
elif i == '0':
count0 += 1
count1 = 0
if count0 == 7 or count1 == 7:
print("YES")
notdan = ... |
After celebrating the midcourse the students of one of the faculties of the Berland State University decided to conduct a vote for the best photo. They published the photos in the social network and agreed on the rules to choose a winner: the photo which gets most likes wins. If multiple photoes get most likes, the win... | 1 | numOfVot=0
Id =0
dic={}
t=input()
for i in raw_input().split():
dic[i]=dic.get(i,0)+1
if(dic[i]>numOfVot):
numOfVot=dic[i]
Id=i
print(Id)
|
There is a frog staying to the left of the string s = s_1 s_2 … s_n consisting of n characters (to be more precise, the frog initially stays at the cell 0). Each character of s is either 'L' or 'R'. It means that if the frog is staying at the i-th cell and the i-th character is 'L', the frog can jump only to the left. ... | 3 |
for _ in range(int(input())):
s = list(input())
l = 1
ans = 1
for i in s:
if i == 'L':
l += 1
else:
ans = max(ans, l)
l = 1
ans = max(ans, l)
print(ans)
|
For an integer n not less than 0, let us define f(n) as follows:
* f(n) = 1 (if n < 2)
* f(n) = n f(n-2) (if n \geq 2)
Given is an integer N. Find the number of trailing zeros in the decimal notation of f(N).
Constraints
* 0 \leq N \leq 10^{18}
Input
Input is given from Standard Input in the following format:
... | 3 | n=int(input())
if n % 2 == 0:
ans = 0
c = 10
while c<=n:
ans += n//c
c *= 5
print(ans)
else:
print(0) |
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.
You are really curious about prime numbers. Let us remind you that a... | 1 | from bisect import bisect_left
M=10**5+10
p=[1]*M
p[0]=p[1]=0
for i in range(2,M):
if p[i]==1:
for j in range(i+i,M,i):
p[j]=0
prime=[]
for i in range(len(p)):
if p[i]==1:
prime.append(i)
#print prime[:10]
n,m=map(int,raw_input().split())
a=[]
d=[[0]*m for _ in range(n)]
for _ in ran... |
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 [0]*int(input()):
i = input()
a = (len(i) - 1) * 9
for j in range(1, 10):
if int(str(j) * len(i)) > int(i):
break
else:
a += 1
print(a) |
Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone.
In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules o... | 3 | l=input().split()
for i in range(4):
l[i]=int(l[i])
s=input()
s1=len(s)
m=0
for i in range(s1):
m+=l[int(s[i])-1]
print(m)
|
Ksusha the Squirrel is standing at the beginning of a straight road, divided into n sectors. The sectors are numbered 1 to n, from left to right. Initially, Ksusha stands in sector 1.
Ksusha wants to walk to the end of the road, that is, get to sector n. Unfortunately, there are some rocks on the road. We know that K... | 3 | n,k=list(map(int,input().split(" ")))
s=input()
print("YES" if "#"*(k) not in s else "NO") |
Vasily the Programmer loves romance, so this year he decided to illuminate his room with candles.
Vasily has a candles.When Vasily lights up a new candle, it first burns for an hour and then it goes out. Vasily is smart, so he can make b went out candles into a new candle. As a result, this new candle can be used like... | 3 | a,b = map(int,input().split())
res = a
rem = 0
while a > 0:
a += rem
s = a // b
res += s
rem = a % b
a = s
print(res) |
Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to th... | 3 | print(4 - len(set(map(int, input().split(' '))))) |
You are given a permutation p of the set {1, 2, ..., N}. Please construct two sequences of positive integers a_1, a_2, ..., a_N and b_1, b_2, ..., b_N satisfying the following conditions:
* 1 \leq a_i, b_i \leq 10^9 for all i
* a_1 < a_2 < ... < a_N
* b_1 > b_2 > ... > b_N
* a_{p_1}+b_{p_1} < a_{p_2}+b_{p_2} < ... < a... | 3 | n = int(input())
p = list(map(int, input().split()))
a = [3 * (i + 1) * pow(10, 4) for i in range(n)]
b = list(a)
b.reverse()
p.reverse()
for i in range(n):
a[p[i] - 1] -= i
print(" ".join(map(str, a)))
print(" ".join(map(str, b))) |
Find the number of palindromic numbers among the integers between A and B (inclusive). Here, a palindromic number is a positive integer whose string representation in base 10 (without leading zeros) reads the same forward and backward.
Constraints
* 10000 \leq A \leq B \leq 99999
* All input values are integers.
Inp... | 3 | a,b = map(int,input().split())
print(sum([i == i[::-1] for i in map(str,range(a,b+1))])) |
Find the number of palindromic numbers among the integers between A and B (inclusive). Here, a palindromic number is a positive integer whose string representation in base 10 (without leading zeros) reads the same forward and backward.
Constraints
* 10000 \leq A \leq B \leq 99999
* All input values are integers.
Inp... | 3 | A,B=map(int, input().split())
cnt=0
for i in range(A,B+1):
jun=str(i)
if jun==jun[::-1]:
cnt+=1
print(cnt) |
You are given array consisting of n integers. Your task is to find the maximum length of an increasing subarray of the given array.
A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray strictly greater than previous.
Input
The first line cont... | 1 | n = int(raw_input())
m = [int(i) for i in raw_input().split(' ')]
k = [ 1 for i in range(n)]
for i in range(1,n):
if m[i] > m[i-1]:
k[i] = k[i-1] + 1
print max(k)
|
After passing a test, Vasya got himself a box of n candies. He decided to eat an equal amount of candies each morning until there are no more candies. However, Petya also noticed the box and decided to get some candies for himself.
This means the process of eating candies is the following: in the beginning Vasya choos... | 3 | n=int(input())
def bs(m,temp):
vasya=0
while(temp>0):
if temp<=m:
vasya+=temp
break
vasya+=m
temp-=m
temp-=temp//10
if vasya*2>=n:
return True
else:
return False
lo,hi=1,n//2+1
while(lo<=hi):
m=(lo+hi)//2
if bs(m,n):
... |
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≤ i ≤ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is it... | 3 | n = int(input())
s = list(map(int, input().split(' ')))
nmax, maxss, cmaxss = 0, 0, 0
for x in s:
if x >= nmax:
nmax = x
cmaxss = cmaxss + 1
if cmaxss > maxss:
maxss = cmaxss
else:
cmaxss = 1
nmax = x
print(maxss) |
Alice and Bob are decorating a Christmas Tree.
Alice wants only 3 types of ornaments to be used on the Christmas Tree: yellow, blue and red. They have y yellow ornaments, b blue ornaments and r red ornaments.
In Bob's opinion, a Christmas Tree will be beautiful if:
* the number of blue ornaments used is greater b... | 3 | y,b,r = map(int, input().split())
a = 1
m = 2
c = 3
l = True
while l:
if a > y or m > b or c > r:
a = a - 1
m = m - 1
c = c - 1
l = False
break
a = a + 1
m = m + 1
c = c + 1
print(a + m + c) |
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.
To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem... | 3 | n,m=map(int,input().split())
from bisect import bisect_right as br
a=list(map(int,input().split()))
b=list(map(int,input().split()))
c=[0 for i in range(n)]
for i in b:
j=br(a,i)-1
if j==-1:continue
c[j]+=1
ans=0
for i in range(n-1,-1,-1):
if c[i]>0:
c[i]-=1
else:
ans+=1
c[i-1]+=c[i]
print(ans) |
Find out if it is possible to partition the first n positive integers into two non-empty disjoint sets S_1 and S_2 such that:
gcd(sum(S_1), sum(S_2)) > 1
Here sum(S) denotes the sum of all elements present in set S and gcd means the[greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor).
Ev... | 3 | n=int(input())
if n==1 or n==2:
print("No")
exit()
print("Yes")
print(1,n)
print(n-1,end=' ')
for i in range(1,n):
print(i,end=' ') |
In Berland the opposition is going to arrange mass walking on the boulevard. The boulevard consists of n tiles that are lain in a row and are numbered from 1 to n from right to left. The opposition should start walking on the tile number 1 and the finish on the tile number n. During the walk it is allowed to move from ... | 3 | n = int(input())
a = [int(c) for c in input().split()]
ans = 1e6 + 7
for i in range(n-1):
cur = max(a[i], a[i+1])
if cur < ans:
ans = cur
ans = min(ans, a[0], a[n-1])
print(ans) |
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 True:
if len(set(list(str(n)))) == 4:
print(n)
break
n+=1 |
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 | t=list(map(int,input().split()))
k=t[0]
n=t[1]
a=list(map(int,input().split()))
a.sort()
i=0
v=0
max=-1
while(i<n):
try:
if(max==-1):
max=a[i+k-1]-a[i]
elif(a[i+k-1]-a[i]<max):
max=a[i+k-1]-a[i]
except Exception as e:
break
i+=1
if(max==-1):
print(0)
v... |
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 | text=input()
if text.isupper():
text=text.lower()
elif len(text)!=1 and text[0].islower() and text[1:len(text)].isupper():
text=text[0].upper()+text[1:len(text)].lower()
elif len(text)==1 and text.islower():
text=text.upper()
print (text)
|
n students are taking an exam. The highest possible score at this exam is m. Let a_{i} be the score of the i-th student. You have access to the school database which stores the results of all students.
You can change each student's score as long as the following conditions are satisfied:
* All scores are integers ... | 3 | t = int(input())
for _ in range(t):
nm = list(map(int,input().split()))
a = list(map(int,input().split()))
n = nm[0]
m = nm[1]
som = sum(a)
if(som >= m):
print(m)
continue
else:
print(som)
|
You are given an array a_1, a_2, ... , a_n. Array is good if for each pair of indexes i < j the condition j - a_j ≠ i - a_i holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).
For example, if a = [1, 1, ... | 3 | import sys
input=sys.stdin.readline
t=int(input())
for i in range(t):
n=int(input())
robo=[int(i) for i in input().split()]
robo.sort(reverse=True)
print(*robo)
|
After lessons Nastya decided to read a book. The book contains n chapters, going one after another, so that one page of the book belongs to exactly one chapter and each chapter contains at least one page.
Yesterday evening Nastya did not manage to finish reading the book, so she marked the page with number k as the fi... | 3 | n = int(input())
s = []
for i in range(n):
l, r = map(int, input().split())
s.append([l, r])
k = int(input())
for i in range(n):
if k >= s[i][0] and k <= s[i][1]:
print(n-i)
break |
While walking down the street Vanya saw a label "Hide&Seek". Because he is a programmer, he used & as a bitwise AND for these two words represented as a integers in base 64 and got new word. Now Vanya thinks of some string s and wants to know the number of pairs of words of length |s| (length of s), such that their bit... | 3 | def sti(x):
o=0
x=x[::-1]
k=1
ans=1
for i in x:
l="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_"
o=l.index(i)*k
for i in range(0,6):
if (o&(2**i)==0):
ans=(ans*3)%1000000007
return ans
def bth(x):
x=x[::-1]
k=1
o... |
Let's call (yet again) a string good if its length is even, and every character in odd position of this string is different from the next character (the first character is different from the second, the third is different from the fourth, and so on). For example, the strings good, string and xyyx are good strings, and ... | 3 | def solve(string):
deleted = set()
current_idx = -1
current = ''
for i, c in enumerate(string):
if current == '':
current = c
current_idx = i
else:
if current == c:
deleted.add(i)
else:
current = ''
... |
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 | import math
n = int(input())
t = (input().split())
s = 0
x = 0
a = []
b = []
c = []
d = []
for i in range(n):
if int(t[i]) == 1:
a.append(t[i])
elif int(t[i]) == 2:
b.append(t[i])
elif int(t[i])==3:
c.append(t[i])
elif int(t[i])==4:
d.append(t[i])
if len(b)/2-len(b)//2 !=... |
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network.
Bu... | 3 | import sys
s = list(dict.fromkeys(list(sys.stdin.readline())[:-1]))
if len(s) % 2 != 0:
print("IGNORE HIM!")
else:
print("CHAT WITH HER!")
|
This is an easier version of the problem. In this version n ≤ 1000
The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company ... | 3 | def go():
n = int(input())
a = list(map(int,input().split()))
cand = [0]*n
mx = -1
bs =[]
for i in range(n):
cand[i]=a[i]
# cur = a[i]
for j in range(i+1,n):
cand[j]=min(cand[j-1],a[j])
for j in range(i-1,-1,-1):
cand[j] = min(cand[j + 1], ... |
Xsquare loves to play with strings a lot. Today, he has two strings S1 and S2 both consisting of lower case alphabets. Xsquare listed all subsequences of string S1 on a paper and all subsequences of string S2 on a separate paper. Xsquare wants to know whether there exists a string which is listed on both the papers.
X... | 1 | t = int(raw_input())
for i in range(t):
s1 = set(raw_input())
s2 = set(raw_input())
if s1.intersection(s2):
print 'Yes'
else:
print 'No' |
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 | L,B =map(int,input().split())
count = 0
while L <= B :
L*=3
B*=2
count+=1
print (count)
|
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 | while True:
try:
n=int(input())
m=input().split()
a=0
b=0
c=0
d=0
for i in range(n):
u=int(m[i])
if u==1:
a=a+1
elif u==2:
b=b+1
elif u==3:
c=c+1
elif u==4:
d=d+1
if b%2==0:
if a<=c:
s=(b/2)+c+d
if a>c:
... |
Luba is surfing the Internet. She currently has n opened tabs in her browser, indexed from 1 to n from left to right. The mouse cursor is currently located at the pos-th tab. Luba needs to use the tabs with indices from l to r (inclusive) for her studies, and she wants to close all the tabs that don't belong to this se... | 3 | s = input()
n, pos, l, r = list(map(int, s.split()))
time = 0
if l <= pos <= r:
time_1 = 0
if l > 1:
time_1 += pos - l + 1
if r < n:
time_1 += r - l + 1
time_2 = 0
if r < n:
time_2 += r - pos + 1
if l > 1:
time_2 += r - l + 1
time = time_1 if time_1 < time_2 ... |
Let's define a string <x> as an opening tag, where x is any small letter of the Latin alphabet. Each opening tag matches a closing tag of the type </x>, where x is the same letter.
Tegs can be nested into each other: in this case one opening and closing tag pair is located inside another pair.
Let's define the notion... | 1 | i = 0;
start = 0;
end = 0;
closingTag = 0;
blankCount = -2;
maxsize = 0
stacksize =0;
xml = raw_input()
maxsize = len(xml)
while (i < maxsize):
start = i
i= i + 1
if(xml[i] == '/'):
i = i + 1
closingTag = 1
else :
closingTag = 0
while(xml[i] != '>'):
i = i + 1
if(closingT... |
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 | i = int(input())
words = []
for t in range(i):
word = input()
words.append(word)
for w in words:
if len(w)>10:
print(w[0] + str(len(w)-2) + w[-1])
else:
print(w)
|
Hongcow likes solving puzzles.
One day, Hongcow finds two identical puzzle pieces, with the instructions "make a rectangle" next to them. The pieces can be described by an n by m grid of characters, where the character 'X' denotes a part of the puzzle and '.' denotes an empty part of the grid. It is guaranteed that th... | 3 | n,m = map(int,input().split())
puz = []
for x in range(n):
puz.append(input())
mix = 502
miy = 502
mx = -1
my = -1
numx = 0
for i in range(n):
for j in range(m):
if(puz[i][j] == "X"):
miy = min(miy,i)
my = max(my,i)
mix = min(mix,j)
mx = max(mx,j)
... |
Pig is visiting a friend.
Pig's house is located at point 0, and his friend's house is located at point m on an axis.
Pig can use teleports to move along the axis.
To use a teleport, Pig should come to a certain point (where the teleport is located) and choose where to move: for each teleport there is the rightmost ... | 3 | n, m = [int(num) for num in input().strip().split()]
curr = 0
for i in range(n):
a, b = [int(num) for num in input().strip().split()]
if a <= curr:
curr = max(curr, b)
else:
break
if curr < m:
print("NO")
else:
print("YES") |
In Disgaea as in most role-playing games, characters have skills that determine the character's ability to use certain weapons or spells. If the character does not have the necessary skill, he cannot use it. The skill level is represented as an integer that increases when you use this skill. Different character classes... | 1 | n,m,k = map(float, str(raw_input()).split())
new_s = {}
for i in xrange(int(n)):
line = raw_input().strip().split()
level = int(round(k*int(line[1]),2))
if level>=100:
new_s[line[0]] = level
for i in range(int(m)):
skill = raw_input().strip()
try:
new_s[skill]+=0
except KeyError:... |
Priority queue is a container of elements which the element with the highest priority should be extracted first.
For $n$ priority queues $Q_i$ ($i = 0, 1, ..., n-1$) of integers, perform a sequence of the following operations.
* insert($t$, $x$): Insert $x$ to $Q_t$.
* getMax($t$): Report the maximum value in $Q_t$. ... | 3 | # AOJ ITP2_2_C: Priority Queue
# Python3 2018.6.24 bal4u
import heapq
n, q = map(int, input().split())
Q = [[] for i in range(n)]
for i in range(q):
a = input().split()
t = int(a[1])
if a[0] == '0': heapq.heappush(Q[t], -int(a[2])) # insert
elif a[0] == '1' and Q[t]: print(-Q[t][0]) # getMax
elif a[0... |
Dr. Evil kidnapped Mahmoud and Ehab in the evil land because of their performance in the Evil Olympiad in Informatics (EOI). He decided to give them some problems to let them go.
Dr. Evil is interested in sets, He has a set of n integers. Dr. Evil calls a set of integers evil if the MEX of it is exactly x. the MEX of ... | 1 | from sys import stdin
n,k = map(int,stdin.readline().split())
a = map(int,stdin.readline().split())
ans = 0
for i in xrange(k):
if i not in a:
ans += 1
ans += a.count(k)
print ans |
You are given an array a of length 2n. Consider a partition of array a into two subsequences p and q of length n each (each element of array a should be in exactly one subsequence: either in p or in q).
Let's sort p in non-decreasing order, and q in non-increasing order, we can denote the sorted versions by x and y, r... | 3 | import itertools
import math
import sys
import os
from collections import defaultdict
from heapq import heapify, heappush, heappop
def is_debug():
return "PYPY3_HOME" not in os.environ
def stdin_wrapper():
data = '''5
13 8 35 94 9284 34 54 69 123 846
'''
for line in data.split('\n'):
yield... |
You are given a trapezoid. The lengths of its upper base, lower base, and height are a, b, and h, respectively.
<image>
An example of a trapezoid
Find the area of this trapezoid.
Constraints
* 1≦a≦100
* 1≦b≦100
* 1≦h≦100
* All input values are integers.
* h is even.
Input
The input is given from Standard Input i... | 3 | l = [int(input()) for i in range(1, 4)]
print((l[0] + l[1]) * l[2] // 2) |
So, the New Year holidays are over. Santa Claus and his colleagues can take a rest and have guests at last. When two "New Year and Christmas Men" meet, thear assistants cut out of cardboard the letters from the guest's name and the host's name in honor of this event. Then the hung the letters above the main entrance. O... | 3 | n=input()
m=input()
q=input()
l=n+m
print(["NO","YES"][sorted(l)==sorted(q)]) |
You are given a string S of length N. Among its subsequences, count the ones such that all characters are different, modulo 10^9+7. Two subsequences are considered different if their characters come from different positions in the string, even if they are the same as strings.
Here, a subsequence of a string is a conca... | 3 | from collections import Counter
n,s=int(input()),input();c=[s[i]for i in range(n)];a=Counter(c);ans=1
for i in a:ans*=a[i]+1
print((ans-1)%(10**9+7)) |
Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the... | 3 | def main():
largemodulus = 1000000007
maxofn = 300001
n = 0
answer = 0
powersoftwo = []
multiplier = 1
for _ in range(maxofn):
powersoftwo.append(multiplier)
if multiplier >= largemodulus:
multiplier = multiplier % largemodulus
multiplier *= 2
n = int(input())
hacked =... |
You are given two arrays A and B, each of size n. The error, E, between these two arrays is defined <image>. You have to perform exactly k1 operations on array A and exactly k2 operations on array B. In one operation, you have to choose one element of the array and increase or decrease it by 1.
Output the minimum poss... | 3 | def main():
n, k1, k2 = map(int, input().split())
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
c = [(abs(a[i] - b[i])) for i in range(n)]
s = sum(c)
if s >= (k1 + k2):
op = (k1 + k2)
while op > 0:
c = sorted(c)
c[-1] -= 1
... |
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≤ i ≤ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is it... | 3 | n=int(input())
string=input().split()
lis=[]
for value in string:
lis.append(int(value))
num=[0]*n
count=0
k,l=0,0
for i in range(n-1):
if lis[i]<=lis[i+1]:
num[l]+=1
else:
l+=1
continue
print(max(num)+1) |
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 | a = int(input())
b = input()
x = 0
for i in range(1,a):
if b[i-1]==b[i]:
x+=1
print(x) |
One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house.
Karlsson's gaze immediately fell on n wooden ... | 3 | n = int(input(""))
l = []
for i in range(n):
s = str(input(""))
l.append(s.split(" "))
c1 = 0
c2 = 0
for i in range(n):
if l[i][0] == '0':
c1 += 1
if l[i][1] == '0':
c2 += 1
t = min(c1, n-c1) + min(c2, n-c2)
print(t) |
A non-empty string is called palindrome, if it reads the same from the left to the right and from the right to the left. For example, "abcba", "a", and "abba" are palindromes, while "abab" and "xy" are not.
A string is called a substring of another string, if it can be obtained from that string by dropping some (possi... | 3 | print (''.join(sorted(([input() for i in range(2)])[1]))) |
Vasya has n pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every m-th day (at days with numbers m, 2m, 3m, ...) mom buys a pair of socks to Vasya. She does it late in the eve... | 3 | n, m = map(int, input().split())
s = n
while n >= m:
s +=1
n = n - m + 1
print(s)
|
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 | import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
import math
from functools import reduce
def factors(n):
return set(reduce(list.__add__,
([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))
def gift():
for _ in range(t):
n = int(input())
... |
Vanya walks late at night along a straight street of length l, lit by n lanterns. Consider the coordinate system with the beginning of the street corresponding to the point 0, and its end corresponding to the point l. Then the i-th lantern is at the point ai. The lantern lights all points of the street that are at the ... | 3 | n, l = list(map(int, input().split()))
a = list(map(int, input().split()))
a = sorted(a)
maxdist = 0
for i in range(n-1):
if max(a[i], a[i+1]) - min(a[i],a[i+1]) > maxdist:
maxdist = max(a[i], a[i+1]) - min(a[i],a[i+1])
print(max(maxdist/2, max(a[0], l-a[n-1])))
|
Bob watches TV every day. He always sets the volume of his TV to b. However, today he is angry to find out someone has changed the volume to a. Of course, Bob has a remote control that can change the volume.
There are six buttons (-5, -2, -1, +1, +2, +5) on the control, which in one press can either increase or decrea... | 3 | import math
t = int(input())
for __ in range(t):
a, b = map(int, input().split())
d = abs(b-a)
print(d//5 + math.ceil(d % 5 / 2))
|
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc.... | 3 | s = list(input())
s.reverse()
t = list(input())
print('YES' if(s == t) else 'NO') |
Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, inf... | 3 | input()
s = input()
if len(s)%2 == 0:
print(s[len(s)-2::-2], s[1::2], sep='')
else:
print(*(s[len(s)-2::-2], s[0], s[2::2]) if len(s)>1 else s, sep='')
|
There exists an island called Arpa’s land, some beautiful girls live there, as ugly ones do.
Mehrdad wants to become minister of Arpa’s land. Arpa has prepared an exam. Exam has only one question, given n, print the last digit of 1378n.
<image>
Mehrdad has become quite confused and wants you to help him. Please hel... | 3 | n=int(input())
if not n:
print(1)
else:
abc=[8, 4, 2, 6]
print(abc[(n-1)%4]) |
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... | 1 | year = int(raw_input())
while True:
year += 1
word = str(year)
if word[0] == word[1] or word[0] == word[2] or word[0] == word[3]:
pass
elif word[1] == word[2] or word[1] == word[3]:
pass
elif word[2] == word[3]:
pass
else:
break
print year
|
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like.
Now let's imagine a typical morning in your family. You haven't w... | 3 | line1 = input()
line2 = input()
nCoins = line1
vCoins = line2.split(' ')
arrCoins = list(map(int, vCoins))
total = 0
for x in vCoins:
total += int(x)
arrCoins.sort(reverse=True)
minCoins = 0
minVal = total/2
taken = 0
for x in arrCoins:
minCoins +=1
taken +=x
if taken > minVal:
break
print(minCoins)
... |
Alice and Bob have received three big piles of candies as a gift. Now they want to divide these candies as fair as possible. To do this, Alice takes one pile of candies, then Bob takes one of the other two piles. The last pile is split between Alice and Bob as they want: for example, it is possible that Alice takes the... | 3 | n = int(input())
for _ in range(n):
j = sum(map(int,input().split()))
print(j//2) |
It's a walking tour day in SIS.Winter, so t groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.
Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P":
* "A" corresponds to an angry... | 3 | t = int(input())
for i in range(t):
n = int(input())
s = list(input())
x = 0
changed = True
while changed:
changed = False
for i in reversed(range(len(s) - 1)):
if s[i] == 'A':
if s[i + 1] == 'P':
changed = True
s[i + 1]... |
Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns — from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1... | 1 |
n,m = [int(_) for _ in raw_input().split()]
s=[None]*n
for i in xrange(n):
s[i]=raw_input().replace(" ",'')
ans = [0] * 4
if '1' in s[0]:ans[0]=1
if '1' in s[n-1]:ans[1]-=1
for i in xrange(n):
if s[i][0] == '1':
ans[2]=1
break
for i in xrange(n):
if s[i][m-1] == '1':
ans[3]=1
break
if sum(... |
Jeff's got n cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got?
Jeff must make the number without leading zero. At that, we assume that number ... | 1 | n = int(raw_input())
cards = map(int, raw_input().split())
fives = cards.count(5)
zeros = len(cards) - fives
mult = fives*5
while (mult % 9):
if fives == 0:
break
fives -= 1
mult -= 5
if not zeros:
print -1
elif not fives:
print 0
else:
r = ["5"]*fives
for i in range(zeros):
... |
Polycarp has n coins, the value of the i-th coin is a_i. Polycarp wants to distribute all the coins between his pockets, but he cannot put two coins with the same value into the same pocket.
For example, if Polycarp has got six coins represented as an array a = [1, 2, 4, 3, 3, 2], he can distribute the coins into two ... | 3 | n=int(input())
p=list(map(int,input().split()))
l=[]
for i in range(n):
l.append(p.count(p[i]))
print(max(l))
|
There are three positive integers A, B and C written on a blackboard. E869120 performs the following operation K times:
* Choose one integer written on the blackboard and let the chosen integer be n. Replace the chosen integer with 2n.
What is the largest possible sum of the integers written on the blackboard after... | 3 | A,B,C,K = map(int,open(0).read().split())
print(A+B+C+max(A,B,C)*2**K-max(A,B,C)) |
Once again Tavas started eating coffee mix without water! Keione told him that it smells awful, but he didn't stop doing that. That's why Keione told his smart friend, SaDDas to punish him! SaDDas took Tavas' headphones and told him: "If you solve the following problem, I'll return it to you."
<image>
The problem is:... | 3 | s=str(input())
ans=0
for i in s:
ans*=2
if i=='4':
ans+=1
else:
ans+=2
print(ans)
|
Takahashi has N sticks that are distinguishable from each other. The length of the i-th stick is L_i.
He is going to form a triangle using three of these sticks. Let a, b, and c be the lengths of the three sticks used. Here, all of the following conditions must be satisfied:
* a < b + c
* b < c + a
* c < a + b
How... | 3 | from bisect import bisect
n = int(input())
l = sorted(list(map(int,input().split())))
ans = 0
for i in range(n-2):
for j in range(i+1,n-1):
ans += bisect(l,l[i]+l[j]-1)-j-1
print(ans) |
We have a grid with H rows and W columns. The square at the i-th row and the j-th column will be called Square (i,j).
The integers from 1 through H×W are written throughout the grid, and the integer written in Square (i,j) is A_{i,j}.
You, a magical girl, can teleport a piece placed on Square (i,j) to Square (x,y) by... | 3 | h, w, d = map(int, input().split())
index = [(0,0) for x in range(h*w+1)]
for i in range(1,h+1):
col = list(map(int, input().split()))
for j in range(1,w+1):
index[col[j-1]] = (i, j)
memo = [0 for x in range(h*w+1)]
l = 0
for l in range(1, h*w+1-d):
memo[l+d] = memo[l] + abs(index[l+d][0] - index[l... |
Levko loves tables that consist of n rows and n columns very much. He especially loves beautiful tables. A table is beautiful to Levko if the sum of elements in each row and column of the table equals k.
Unfortunately, he doesn't know any such table. Your task is to help him to find at least one of them.
Input
The ... | 3 | n,m=map(int,input().split())
ans=[[0 for i in range(n)] for j in range(n)]
for i in range(n):
for j in range(n):
if i==j:
ans[i][j]=m
for i in range(n):
print(*ans[i]) |
Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, inf... | 1 | t = (int(raw_input()))
txt = raw_input()
newtxt = ""
i = 0
while i < t:
if i%2 == t%2:
newtxt = txt[i] + newtxt
else:
newtxt = newtxt + txt[i]
i+=1
print newtxt
|
Takahashi has a string S of length N consisting of digits from `0` through `9`.
He loves the prime number P. He wants to know how many non-empty (contiguous) substrings of S - there are N \times (N + 1) / 2 of them - are divisible by P when regarded as integers written in base ten.
Here substrings starting with a `0`... | 3 | n,p = list(map(int,input().split()))
S = input()
if p == 2 or p == 5:
ans = 0
for i,s in enumerate(S):
if int(s)%p == 0:
ans += i+1
print(ans)
exit()
def MS(i,s,pre):
pre += int(s)*i
return pre%p
M = [0]*p
M[0] = 1
i = 1
pre = 0
for s in S[::-1]:
pre = MS(i,int(s),pre)
M[pre] += 1
i = i*... |
You are given two integers a and b.
In one move, you can choose some integer k from 1 to 10 and add it to a or subtract it from a. In other words, you choose an integer k ∈ [1; 10] and perform a := a + k or a := a - k. You may use different values of k in different moves.
Your task is to find the minimum number of mo... | 3 | for _ in range(int(input())):
a,b=list(map(int,input().split()))
if a==b:
print(0)
elif b>a:
if (b-a)%2==0:
print(2)
else:
print(1)
else:
if (a-b)%2==0:
print(1)
else:
print(2)
|
Valera runs a 24/7 fast food cafe. He magically learned that next day n people will visit his cafe. For each person we know the arrival time: the i-th person comes exactly at hi hours mi minutes. The cafe spends less than a minute to serve each client, but if a client comes in and sees that there is no free cash, than ... | 3 |
from collections import Counter
n = int(input())
l = []
for _ in range(n):
li = list(map(int, input().split()))
l.append(li[0] * 60 + li[1])
cc = Counter(l)
print(max(cc.values())) |
Let's denote correct match equation (we will denote it as CME) an equation a + b = c there all integers a, b and c are greater than zero.
For example, equations 2 + 2 = 4 (||+||=||||) and 1 + 2 = 3 (|+||=|||) are CME but equations 1 + 2 = 4 (|+||=||||), 2 + 2 = 3 (||+||=|||), and 0 + 1 = 1 (+|=|) are not.
Now, you ha... | 3 | for i in range(int(input())):
k = int(input())
if k < 4:
print(4 - k)
elif k % 2 == 0:
print(0)
else:
print(1) |
Petya has a rectangular Board of size n × m. Initially, k chips are placed on the board, i-th chip is located in the cell at the intersection of sx_i-th row and sy_i-th column.
In one action, Petya can move all the chips to the left, right, down or up by 1 cell.
If the chip was in the (x, y) cell, then after the oper... | 3 | from sys import stdin
from collections import deque
mod = 10**9 + 7
import sys
import random
# sys.setrecursionlimit(10**6)
from queue import PriorityQueue
# def rl():
# return [int(w) for w in stdin.readline().split()]
from bisect import bisect_right
from bisect import bisect_left
from collections import defaultdi... |
Shreyan is appearing for CAT examination and is stuck at a problem to find minimum value needed to be added or subtracted to make a number perfect square.You as his friend and a good programmer agrees to help him find the answer.
INPUT:
First line will contain no of test cases T (1 < T < 10000)
Next T lines will ha... | 1 | import math
test = int(raw_input())
while test>0 :
n = int(raw_input())
sq = math.sqrt(n)
f = math.floor(sq)
c = math.ceil(sq)
if int(f)**2 == n:
print("YES");
else:
f = int(f)**2
c = int(c)**2
c = c - n
f = n - f
if c<f:
print('+'+str(c))
else:
print('-'+str(f))
test-=1 |
You've got an array a, consisting of n integers: a1, a2, ..., an. Your task is to find a minimal by inclusion segment [l, r] (1 ≤ l ≤ r ≤ n) such, that among numbers al, al + 1, ..., ar there are exactly k distinct numbers.
Segment [l, r] (1 ≤ l ≤ r ≤ n; l, r are integers) of length m = r - l + 1, satisfying the given... | 3 | n, k = map(int, input().split())
a = list(map(int, input().split()))
d = {}
al = -1
ar = -1
for i in range(n):
#print('i is' + str(i))
if len(d) < k:
if a[i] not in d:
d[a[i]] = 1
else:
d[a[i]] += 1
#print(d)
if len(d) == k:
#print('WTF')
for j in range(i+1):
#print('OMG')
#print("j is "... |
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
t=int(input())
for i in range(t):
n=int(input())
l=list(map(int,input().split()))
s=sum(l)
p=s/n
q=math.ceil(p)
print(q) |
As a New Year's gift, Dolphin received a string s of length 19.
The string s has the following format: `[five lowercase English letters],[seven lowercase English letters],[five lowercase English letters]`.
Dolphin wants to convert the comma-separated string s into a space-separated string.
Write a program to perform th... | 3 | x = input()
x=x.replace(","," ")
print(x)
|
There is a building consisting of 10~000 apartments numbered from 1 to 10~000, inclusive.
Call an apartment boring, if its number consists of the same digit. Examples of boring apartments are 11, 2, 777, 9999 and so on.
Our character is a troublemaker, and he calls the intercoms of all boring apartments, till someone... | 3 | t = int(input())
for _ in range(t):
x = input()
a = int(x[0])
b = len(x)
res = (a-1)*10 + (b*(b+1))//2
print(res) |
You're given an integer n. For every integer i from 2 to n, assign a positive integer a_i such that the following conditions hold:
* For any pair of integers (i,j), if i and j are coprime, a_i ≠ a_j.
* The maximal value of all a_i should be minimized (that is, as small as possible).
A pair of integers is call... | 3 | prime=[2,3,5,7,11]
for i in range(12,100010):
for j in prime:
if i%j==0:
break
if j*j>i:
prime.append(i)
break
else:
prime.append(i)
d={}
for i in range(1,len(prime)+1):
d[prime[i-1]]=i
#print(prime)
n=int(input())
for i in range(2,n+1):
if i... |
Ujan has been lazy lately, but now has decided to bring his yard to good shape. First, he decided to paint the path from his house to the gate.
The path consists of n consecutive tiles, numbered from 1 to n. Ujan will paint each tile in some color. He will consider the path aesthetic if for any two different tiles wit... | 3 | import sys
try:
fin = open('in')
except:
fin = sys.stdin
n=int(fin.readline())
p=[]
i=2
while i*i<=n:
if n%i==0:
p.append(i)
while n%i==0:n//=i
i += 1
if n>1:p.append(n)
if len(p)==1:print(p[0])
else:print(1) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.