source stringclasses 3
values | instruction stringlengths 23 3.97k | input stringclasses 1
value | output stringlengths 1 3.75k |
|---|---|---|---|
MatrixStudio/Codeforces-Python-Submissions | Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d... | ```python
number = 0
n = input()
for i in range(len(n)):
if str(n)[i] == '7' or str(n)[i] == '4':
number += 1
if str(len(str(number))) in '47 74 444 447 474 477 744 747 774 777 4444 4447 \
4474 4477 4744 4747 4774 4777 7444':
print('YES')
else:
print('NO')
``` | |
MatrixStudio/Codeforces-Python-Submissions | Little penguin Polo adores integer segments, that is, pairs of integers [*l*; *r*] (*l*<=≤<=*r*).
He has a set that consists of *n* integer segments: [*l*1; *r*1],<=[*l*2; *r*2],<=...,<=[*l**n*; *r**n*]. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 uni... | ```python
n,k=map(int,input().split())
x=0
for i in range(0,n):
a,b=map(int,input().split())
if a<b:
x=x+1
if n==x:
print(n)
else:
print(0)
``` | |
MatrixStudio/Codeforces-Python-Submissions | You are given an array consisting of *n* non-negative integers *a*1,<=*a*2,<=...,<=*a**n*.
You are going to destroy integers in the array one by one. Thus, you are given the permutation of integers from 1 to *n* defining the order elements of the array are destroyed.
After each element is destroyed you have to find o... | ```python
def lowbit(i):
return i&-i
def update(idx,i):
while idx<=n:
bit[idx]+=i
idx+=lowbit(idx)
def get_sum(i):
res = 0
while i:
res+=bit[i]
i-=lowbit(i)
return res
def get_down(i):
if i-1 in point_set:
down_mapper[i] = get_down(i-1)
return down_map... | |
MatrixStudio/Codeforces-Python-Submissions | There are $n$ students in a school class, the rating of the $i$-th student on Codehorses is $a_i$. You have to form a team consisting of $k$ students ($1 \le k \le n$) such that the ratings of all team members are distinct.
If it is impossible to form a suitable team, print "NO" (without quotes). Otherwise print "YES"... | ```python
from collections import Counter
def isSq(n):
ans=int(n**0.5)
if ans**2==n:
return True
return False
def solve():
n,k=list(map(int,input().split()))
arr=[int(i) for i in input().split()]
count=Counter(arr)
if len(count)>=k:
print("YES")
else:
... | |
MatrixStudio/Codeforces-Python-Submissions | Jon fought bravely to rescue the wildlings who were attacked by the white-walkers at Hardhome. On his arrival, Sam tells him that he wants to go to Oldtown to train at the Citadel to become a maester, so he can return and take the deceased Aemon's place as maester of Castle Black. Jon agrees to Sam's proposal and Sam s... | ```python
def countOnes(n):
count = [0] * (n + 1)
count[1] = 1
for i in range(2, n + 1):
if i % 2 == 0:
count[i] = count[i // 2]
else:
count[i] = count[i // 2] + 1
return count
def solve(n, l, r):
count = countOnes(n)
return sum(count[l:r + 1]... | |
MatrixStudio/Codeforces-Python-Submissions | You have probably registered on Internet sites many times. And each time you should enter your invented password. Usually the registration form automatically checks the password's crypt resistance. If the user's password isn't complex enough, a message is displayed. Today your task is to implement such an automatic che... | ```python
inp=input()
small=0
uper=0
innt=0
for i in inp:
if i.islower():
small+=1
elif i.isupper():
uper+=1
elif i.isdigit():
innt+=1
print(small,uper,innt)
if small>=1 and uper>=1 and innt>=1 and len(inp)>=5:
print('Correct')
else:
print('Too weak')
``` | |
MatrixStudio/Codeforces-Python-Submissions | 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.... | ```python
s= input()
t= input()
def rev(s):
return s[::-1]
re=rev(s)
if(s !=' ' and t !=' '):
if re== t:
print("YES")
else:
print("NO")
else:
print("NO")
``` | |
MatrixStudio/Codeforces-Python-Submissions | Year 2118. Androids are in mass production for decades now, and they do all the work for humans. But androids have to go to school to be able to solve creative tasks. Just like humans before.
It turns out that high school struggles are not gone. If someone is not like others, he is bullied. Vasya-8800 is an economy-cl... | ```python
import math
a,b = map(int, input().split())
x = a * (math.log(b));
y = b * (math.log(a));
if y > x:
print(">")
elif x > y:
print("<")
elif x == y:
print("=")
``` | |
MatrixStudio/Codeforces-Python-Submissions | In this problem we consider a special type of an auction, which is called the second-price auction. As in regular auction *n* bidders place a bid which is price a bidder ready to pay. The auction is closed, that is, each bidder secretly informs the organizer of the auction price he is willing to pay. After that, the au... | ```python
n=int(input())
l=list(map(int,input().split()))
dic={}
for i in range(n):
a=l[:]
a.pop(i)
dic[i+1]=max(a)
c=list(dic.values())
c=list(set(c))
c.remove(max(c))
m=max(c)
for i in dic:
if dic[i]==m:
k=i
print(k,m)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Vasya's bicycle chain drive consists of two parts: *n* stars are attached to the pedal axle, *m* stars are attached to the rear wheel axle. The chain helps to rotate the rear wheel by transmitting the pedal rotation.
We know that the *i*-th star on the pedal axle has *a**i* (0<=<<=*a*1<=<<=*a*2<=<<=...<=<<... | ```python
n=int(input())
a=list(map(int,input().split()))
m=int(input())
b=list(map(int,input().split()))
ratio=[]
for i in a:
for j in b:
if(j%i==0):
ratio.appennd(j//i)
n=max(ratio)
print(ratio.count(n))
``` | |
MatrixStudio/Codeforces-Python-Submissions | They say "years are like dominoes, tumbling one after the other". But would a year fit into a grid? I don't think so.
Limak is a little polar bear who loves to play. He has recently got a rectangular grid with *h* rows and *w* columns. Each cell is a square, either empty (denoted by '.') or forbidden (denoted by '#').... | ```python
h, w = map(int, input().split())
s = []
for i in range(h):
s.append(list(input()))
s[i].append('#')
s.append(['#']*(w+1))
v = [[0]*(w+2)]
g = [[0]*(w+2)]
for i in range(h+1):
v.append([0]*(w+2))
g.append([0]*(w+2))
for i in range(len(s)):
count = 0
for j in ran... | |
MatrixStudio/Codeforces-Python-Submissions | A has a string consisting of some number of lowercase English letters 'a'. He gives it to his friend B who appends some number of letters 'b' to the end of this string. Since both A and B like the characters 'a' and 'b', they have made sure that at this point, at least one 'a' and one 'b' exist in the string.
B now gi... | ```python
p=input()
x=p.find("b")
y=p.find("c")
a=p[:x]
b=p[x:y]
c=p[y:]
if(a=="" or b=="" or c==""): print("NO")
else:
if(len(c)==len(a) or len(c)==len(b)): print("YES")
else: print("NO")
``` | |
MatrixStudio/Codeforces-Python-Submissions | 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... | ```python
n,k,m=[int(i) for i in input().split()]
l=[int(i) for i in input().split()]
lmain=[]
for i in range(n):
lmain.append(l[i])
l[i] = l[i]%m
l1=[]
for i in range(m):
l1.append(0)
for i in range(n):
l1[l[i]]+=1
f=0
save=-1
for i in range(m):
if (l1[i]>=k):
f=1
sa... | |
MatrixStudio/Codeforces-Python-Submissions | 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 *t**i* 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 t... | ```python
def max_happy_people(n, times):
times.sort() # Сортировка времен обслуживания по возрастанию
happy_count = 0 # Счетчик довольных людей
total_waiting_time = 0 # Общее время ожидания
for i in range(n):
if times[i] >= total_waiting_time: # Проверка условия для довольного челове... | |
MatrixStudio/Codeforces-Python-Submissions | Dwarfs have planted a very interesting plant, which is a triangle directed "upwards". This plant has an amusing feature. After one year a triangle plant directed "upwards" divides into four triangle plants: three of them will point "upwards" and one will point "downwards". After another year, each triangle plant divide... | ```python
n=int(input())
m=pow(10,9)+7
if n==0:
print(1)
else:
print((pow(2,2*n-1,m)+pow(2,n-1,m))%m)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Eleven wants to choose a new name for herself. As a bunch of geeks, her friends suggested an algorithm to choose a name for her. Eleven wants her name to have exactly *n* characters.
Her friend suggested that her name should only consist of uppercase and lowercase letters 'O'. More precisely, they suggested that the ... | ```python
a=int(input())
f=[1,1]
if a>2:
for i in range(3,a+1):
p=f[i-3]+f[i-2]
f.append(p)
for x in range(1,a+1):
if x in f:
print("O",end="")
else:
print("o",end="")
``` | |
MatrixStudio/Codeforces-Python-Submissions | 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... | ```python
a = input()
b = input()
c = (bin(int(a,2)+int(b,2)))
c = c.replace("0b","")
print(c)
``` | |
MatrixStudio/Codeforces-Python-Submissions | There always is something to choose from! And now, instead of "Noughts and Crosses", Inna choose a very unusual upgrade of this game. The rules of the game are given below:
There is one person playing the game. Before the beginning of the game he puts 12 cards in a row on the table. Each card contains a character: "X"... | ```python
n = int(input())
otv = []
result = ""
counter = 0
flag = True
for _ in range(n):
temp = input()
for i in range(12):
if 12 % (i+1) == 0 and temp[i] == "X":
for j in range((i*2)+1, 12, i+1):
if temp[j] != temp[i]:
flag = False
... | |
MatrixStudio/Codeforces-Python-Submissions | A triangular number is the number of dots in an equilateral triangle uniformly filled with dots. For example, three dots can be arranged in a triangle; thus three is a triangular number. The *n*-th triangular number is the number of dots in a triangle with *n* dots on a side. . You can learn more about these numbers fr... | ```python
n=int(input())
if n<0:
print('NO')
else:
sum,a=0,1
while(sum<=n):
sum=sum+a
if sum==n:
print('YES')
break
a=a+1
print('NO')
``` | |
MatrixStudio/Codeforces-Python-Submissions | As you could know there are no male planes nor female planes. However, each plane on Earth likes some other plane. There are *n* planes on Earth, numbered from 1 to *n*, and the plane with number *i* likes the plane with number *f**i*, where 1<=≤<=*f**i*<=≤<=*n* and *f**i*<=≠<=*i*.
We call a love triangle a situation ... | ```python
t= int(input())
l=list(map(int,(input().split())))
found=False
for i in range(len(l)):
start=l[i]-1
count=0
while count<2:
start=l[start]-1
count+=1
if start==i:
found=True
print("YES")
break
if not foun... | |
MatrixStudio/Codeforces-Python-Submissions | Recently Adaltik discovered japanese crosswords. Japanese crossword is a picture, represented as a table sized *a*<=×<=*b* squares, and each square is colored white or black. There are integers to the left of the rows and to the top of the columns, encrypting the corresponding row or column. The number of integers repr... | ```python
n = int(input())
s = tuple(input())
bCount = 0
temp = []
ans = []
for b in s:
n -= 1
if b == "B":
bCount += 1
elif b == "W":
ans.append(bCount)
bCount -= bCount
if n == 0:
ans.append(bCount)
print(ans)
``` | |
MatrixStudio/Codeforces-Python-Submissions | In Berland it is the holiday of equality. In honor of the holiday the king decided to equalize the welfare of all citizens in Berland by the expense of the state treasury.
Totally in Berland there are *n* citizens, the welfare of each of them is estimated as the integer in *a**i* burles (burle is the currency in Berl... | ```python
n = int(input())
a = [int(a) for a in input().split()]
m = max(a)
add = 0
for i in a:
add += (m-i)
print(add)
``` | |
MatrixStudio/Codeforces-Python-Submissions | You are given array *a* with *n* elements and the number *m*. Consider some subsequence of *a* and the value of least common multiple (LCM) of its elements. Denote LCM as *l*. Find any longest subsequence of *a* with the value *l*<=≤<=*m*.
A subsequence of *a* is an array we can get by erasing some elements of *a*. It... | ```python
import sys
n, m = map(int, sys.stdin.buffer.readline().decode('utf-8').split())
a = list(map(int, sys.stdin.buffer.readline().decode('utf-8').split()))
dp = [0]*(m+1)
for x in a:
if x <= m:
dp[x] += 1
for i in range(m, 0, -1):
for j in range(2, m+1):
if i*j > m:
... | |
MatrixStudio/Codeforces-Python-Submissions | Luke Skywalker gave Chewbacca an integer number *x*. Chewbacca isn't good at numbers but he loves inverting digits in them. Inverting digit *t* means replacing it with digit 9<=-<=*t*.
Help Chewbacca to transform the initial number *x* to the minimum possible positive number by inverting some (possibly, zero) digits.... | ```python
x = int(input())
x_str = str(x)
result = ''
if x_str[0] > '4':
result += str(9 - int(x_str[0]))
else:
result += x_str[0]
for digit in x_str[1:]:
result += min(digit, str(9 - int(digit)))
result_int = int(result)
print(result_int)
``` | |
MatrixStudio/Codeforces-Python-Submissions | According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw *n* people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can chec... | ```python
n = int(input())
a = []
b = []
for i in range(n):
s = input()
a.append(s)
for j in a:
if(j=="ABSINTH" or j=="BEER" or j=="BRANDY" or j=="CHAMPAGNE" or j=="GIN" or j=="RUM" or j=="SAKE" or j=="TEQUILA" or j=="VODKA" or j=="WHISKEY" or j=="WINE"):
b.append(j)
if(j=="0" or j=="1" or j=... | |
MatrixStudio/Codeforces-Python-Submissions | Limak and Radewoosh are going to compete against each other in the upcoming algorithmic contest. They are equally skilled but they won't solve problems in the same order.
There will be *n* problems. The *i*-th problem has initial score *p**i* and it takes exactly *t**i* minutes to solve it. Problems are sorted by diff... | ```python
def score(p, t, c):
x, s = 0, 0
for pi, ti in zip(p, t):
x += ti
s += max(0, pi - c * x)
return s
n, c = map(int, input().split())
p = list(map(int, input().split()))
t = list(map(int, input().split()))
s1 = score(p, t, c)
p.reverse()
t.reverse()
s2 = score(p, t, ... | |
MatrixStudio/Codeforces-Python-Submissions | Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry.
He bought *n* pieces of jewelry. The *i*-th piece has price equal to *i*<=+<=1, that is, the prices of the jewelry are 2,<=3,<=4,<=... *n*<=+<=1.
Watson gave Sherlock a challenge to color these jewelry pie... | ```python
# https://codeforces.com/problemset/problem/776/B
from math import sqrt
def is_prime(x):
if x == 2 or x == 3:
return True
if x%2 == 0 or x%3 == 0:
return False
tmp = 5
while tmp < sqrt(x) + 1:
if x % tmp == 0:
return False
tmp += 2
i... | |
MatrixStudio/Codeforces-Python-Submissions | 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... | ```python
n=int(input())
a=sum(list(map(int,input().split())))
b=sum(list(map(int,input().split())))
c=sum(list(map(int,input().split())))
print(a-b)
print(b-c)
``` | |
MatrixStudio/Codeforces-Python-Submissions | 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... | ```python
word = input()
znak = word[1]
word = word.replace(znak,'')
s=[]
for i in range(len(word)):
s.append(word[i])
s = sorted(s)
print(*s,sep=znak)
``` | |
MatrixStudio/Codeforces-Python-Submissions | 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 subsequ... | ```python
a=input()
a1=[]
a2=[]
for i in a:
a1.append(i)
a2.append(i)
a2.reverse()
if a1==a2:
print(a)
else:
a3=a1+a2
print(*a3,sep='')
``` | |
MatrixStudio/Codeforces-Python-Submissions | It seems that Borya is seriously sick. He is going visit *n* doctors to find out the exact diagnosis. Each of the doctors needs the information about all previous visits, so Borya has to visit them in the prescribed order (i.e. Borya should first visit doctor 1, then doctor 2, then doctor 3 and so on). Borya will get t... | ```python
n = int(input())
for i in range(n):
si, di = list(map(int, input().split()))
if i == 0:
sum = si
else:
while si < sum:
si += di
sum = si
print(sum)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Pasha has a wooden stick of some positive integer length *n*. He wants to perform exactly three cuts to get four parts of the stick. Each part must have some positive integer length and the sum of these lengths will obviously be *n*.
Pasha likes rectangles but hates squares, so he wonders, how many ways are there to ... | ```python
n = int(input())
if n%2==0:
n=n//5
print(n)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Little penguin Polo adores strings. But most of all he adores strings of length *n*.
One day he wanted to find a string that meets the following conditions:
1. The string consists of *n* lowercase English letters (that is, the string's length equals *n*), exactly *k* of these letters are distinct. 1. No two neighbo... | ```python
n,k=map(int,input().split())
if k>n:
print(-1)
elif k==1:
if n==1:
print('a')
else:
print(-1)
else:
alph=""
for i in range(26):
alph+=(chr(i+97))
ans=alph[:k]
n-=k
if n%2:
z=ans[0]+ans[1]+'ab'*(n//2)+'a'+ans[2:]
else:
z=ans[0]+ans[1]+'ab'*(n//2)+ans[2:]
print(z)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Phone number in Berland is a sequence of *n* digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three... | ```python
n = int(input())
s = input()
if n <= 3: print(s); exit()
else:
if n&1:
print(s[:3] + "-", end = "")
for i in range(3, n - 2, 2):
print(s[i:i+2] + "-", end = "")
print(s[n-2:])
else:
for i in range(0, n - 2, 2):
print(s[i:i+2] + "-", ... | |
MatrixStudio/Codeforces-Python-Submissions | You have *n* devices that you want to use simultaneously.
The *i*-th device uses *a**i* units of power per second. This usage is continuous. That is, in λ seconds, the device will use λ·*a**i* units of power. The *i*-th device currently has *b**i* units of power stored. All devices can store an arbitrary amount of pow... | ```python
def max_usage_time(n, p, devices):
total_power = sum(a for a, _ in devices)
min_time = min(b / (total_power - a) for a, b in devices)
return min_time if min_time * p >= 1 else -1
# Input
n, p = map(int, input().split())
devices = [tuple(map(int, input().split())) for _ in range(n)]
# Calculate a... | |
MatrixStudio/Codeforces-Python-Submissions | A boy Bob likes to draw. Not long ago he bought a rectangular graph (checked) sheet with *n* rows and *m* columns. Bob shaded some of the squares on the sheet. Having seen his masterpiece, he decided to share it with his elder brother, who lives in Flatland. Now Bob has to send his picture by post, but because of the w... | ```python
n, m = list(map(int, input().split()))
lst = [list(input()) for i in range(n)]
a = []
b = []
for i in range(n):
flag = True
for j in lst[i]:
if j == '*':
flag = False
if not flag:
a.append(i)
for x in range(m):
flag = True
for i in l... | |
MatrixStudio/Codeforces-Python-Submissions | 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 cho... | ```python
n = int(input())
l = 1
r = n
while(l != r):
mid = (l+r) // 2
k = n
t1 = 0
while(k > 0):
t1 +=min(mid,k)
k -= min(mid,k)
k -= k//10
if(t1 >= (n+1)//2):
r = mid
else:
l = mid+1
print(l)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Ivan's classes at the university have just finished, and now he wants to go to the local CFK cafe and eat some fried chicken.
CFK sells chicken chunks in small and large portions. A small portion contains 3 chunks; a large one — 7 chunks. Ivan wants to eat exactly *x* chunks. Now he wonders whether he can buy exactly ... | ```python
for _ in range(int(input())):
x=int(input())
if x%3==0 or x%7==0 or (x%7)%3==0:
print("YES")
else:
print("NO")
``` | |
MatrixStudio/Codeforces-Python-Submissions | Two players play a simple game. Each player is provided with a box with balls. First player's box contains exactly *n*1 balls and second player's box contains exactly *n*2 balls. In one move first player can take from 1 to *k*1 balls from his box and throw them away. Similarly, the second player can take from 1 to *k*2... | ```python
inputs = input()
n1 = int(inputs[0])
n2 = int(inputs[2])
k1 = int(inputs[4])
k2 = int(inputs[6])
if n1 >= n2 or n2 >= n1:
if k1 > k2:
print("First")
elif k2 > k1:
print("Second")
elif k1 == k2:
if n1 > n2:
print("First")
elif n2 > n1:
... | |
MatrixStudio/Codeforces-Python-Submissions | Ternary numeric notation is quite popular in Berland. To telegraph the ternary number the Borze alphabet is used. Digit 0 is transmitted as «.», 1 as «-.» and 2 as «--». You are to decode the Borze code, i.e. to find out the ternary number given its representation in Borze alphabet. | ```python
from math import ceil
def main():
trans = {
"--" : "2",
"-." : "1",
"." : "0",
}
code = input()
res = ""
ch = 0
while ch < len(code):
for key in trans:
if code[ch:ch+len(key)] == key:
ch += len(key)
... | |
MatrixStudio/Codeforces-Python-Submissions | You've got an *n*<=×<=*m* pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.
A picture is a barcode if the following conditions are fulfilled:
- All pixels in each column are of the same color. - The width of each monochrome ... | ```python
from sys import stdin
input = stdin.readline
n,m,x,y=map(int,input().split())
A=[input() for i in range(n)]
Z=[]
for j in range(m):
cnt=0
for i in range(n):
if A[i][j]=="#":
cnt+=1
Z.append(cnt)
# print(Z)
def rec(last,streak,i):
if i==m:
return 0 if x... | |
MatrixStudio/Codeforces-Python-Submissions | Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are *n* players (including Limak himself) and right now all of them have bids on the table. *i*-th of them has bid with size *a**i* dollars.
Each player can double his bid any number of times and triple his bid any nu... | ```python
#include <iostream>
#include <vector>
#define _USE_MATH_DEFINES
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <algorithm>
#include <climits>
using namespace std;
int main() {
int n;
cin >> n;
int razlozhenie, cur;
cin >> razlozhenie;
while(razlozhenie % 2 == 0)
ra... | |
MatrixStudio/Codeforces-Python-Submissions | After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer.
At the start of the day they have *x* ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. Each person in the... | ```python
n,x=input().split()
n=int(n);x=int(x)
distressed=0
for i in range(n):
a,b=input().split()
b=int(b)
if a=='+':
x+=b
elif x>=b:
x-=b
else:
distressed+=1
print(x,distressed)
``` | |
MatrixStudio/Codeforces-Python-Submissions | A dice is a cube, its faces contain distinct integers from 1 to 6 as black points. The sum of numbers at the opposite dice faces always equals 7. Please note that there are only two dice (these dices are mirror of each other) that satisfy the given constraints (both of them are shown on the picture on the left).
Alice... | ```python
n = int(input())
x = int(input())
hid = 7-x
for i in range(n):
hid = 7-x
a, b = map(int, input().split())
if hid in [7-a, 7-b, a, b]:
print("NO")
break
else:
x = hid
else:
print('YES')
``` | |
MatrixStudio/Codeforces-Python-Submissions | Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.
You've got string *s*<==<=*s*1*s*2... *s**n* (*n* is the length of the string), consisting only of characters "." and "#" and *m* queries. Each query is described by a pair of integers *l**i*,<... | ```python
def count_pref(s: str) -> list[int]:
pref = [0] * (len(s))
for i in range(1, len(pref)):
pref[i] += pref[i-1]
if s[i-1] == s[i]:
pref[i] += 1
return pref
def process(pref: list[int], queries: list[list[int]]) -> list[int]:
res = []
for query in queries:
... | |
MatrixStudio/Codeforces-Python-Submissions | The Little Elephant has an integer *a*, written in the binary notation. He wants to write this number on a piece of paper.
To make sure that the number *a* fits on the piece of paper, the Little Elephant ought to delete exactly one any digit from number *a* in the binary record. At that a new number appears. It consis... | ```python
n=input()
a=[x for x in n]
if n.count('0')>0:
a.remove('0')
print(''.join(a))
else:
del a[-1]
print(''.join(a))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Alice likes word "nineteen" very much. She has a string *s* and wants the string to contain as many such words as possible. For that reason she can rearrange the letters of the string.
For example, if she has string "xiineteenppnnnewtnee", she can get string "xnineteenppnineteenw", containing (the occurrences marked) ... | ```python
def printMatrix(matrix):
for matrixrow in matrix:
row = ''
for value in matrixrow:
row += str(value) + ' '
print(row)
n = int(input())
w = [[0 for i in range(n)] for i in range(n)]
a = [[0 for i in range(n)] for i in range(n)]
b = [[0 for i in range(n)] for... | |
MatrixStudio/Codeforces-Python-Submissions | While Mike was walking in the subway, all the stuff in his back-bag dropped on the ground. There were several fax messages among them. He concatenated these strings in some order and now he has string *s*.
He is not sure if this is his own back-bag or someone else's. He remembered that there were exactly *k* messages ... | ```python
s=input()
s=list(s)
p=int(input())
f=0
#lst = list(map(int, input().strip().split(' ')))
i=0
k=len(s)//p
while(i<=len(s)-k):
t=[]
for j in range(i,i+k):
t.append(s[j])
if s[i:i+k]==t[::-1]:
i+=k
else:
print('NO')
f=1
break
i... | |
MatrixStudio/Codeforces-Python-Submissions | In a Berland's zoo there is an enclosure with camels. It is known that camels like to spit. Bob watched these interesting animals for the whole day and registered in his notepad where each animal spitted. Now he wants to know if in the zoo there are two camels, which spitted at each other. Help him to solve this task.
... | ```python
x = []
d = []
for i in ' '*int(input()):
x2, d2 = map(int, input().split())
x.append(x2)
d.append(d2)
f = 0
kol = 0
for i in range(len(x)):
for j in range(len(x)):
if x[i]+d[i] == x[j] and x[j] + d[j] == x[i] and kol != 2:
f = 1
kol += 1
print('YES'... | |
MatrixStudio/Codeforces-Python-Submissions | There is a game called "I Wanna Be the Guy", consisting of *n* levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game.
Little X can pass only *p* levels of the game. And Little Y can pass only *q* levels of the game. You are given the indices of levels Little X can... | ```python
n=int(input())
list1=list( map(int,input().split()))
list2= list (map(int,input().split()))
MergedList=list1+list2
X=set(MergedList())
if len(X)==n:
print("I become the guy.")
else:
print("Oh, my keyboard!")
``` | |
MatrixStudio/Codeforces-Python-Submissions | Two boys decided to compete in text typing on the site "Key races". During the competition, they have to type a text consisting of *s* characters. The first participant types one character in *v*1 milliseconds and has ping *t*1 milliseconds. The second participant types one character in *v*2 milliseconds and has ping *... | ```python
s,v1,v2,t1,t2=map(int,input().split())
z1=s*v1+2*t1
z2=s*v2+2*t2
if z1>z2:
print("Second")
elif z2>z1:
print("First")
else:
print("Friendship")
``` | |
MatrixStudio/Codeforces-Python-Submissions | 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... | ```python
"""
abcd
bcad
abcd
"""
n = int(input())
s = input()
ans = [' '] * n
if len(s) % 2 == 0:
l = (n - 1) // 2
r = (n) // 2
i = 0
j = 1
ans[l] = s[i]
ans[r] = s[j]
while j + 2 < n:
j += 2
i += 2
l -= 1
r += 1
... | |
MatrixStudio/Codeforces-Python-Submissions | Eugeny has array *a*<==<=*a*1,<=*a*2,<=...,<=*a**n*, consisting of *n* integers. Each integer *a**i* equals to -1, or to 1. Also, he has *m* queries:
- Query number *i* is given as a pair of integers *l**i*, *r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*). - The response to the query will be integer 1, if the elements of a... | ```python
import sys
(n, m) = [int(x) for x in sys.stdin.readline().split()]
n_one = sys.stdin.readline().count("-")
one = n - n_one
for i in range(0, m):
(l, r) = [int(x) for x in sys.stdin.readline().split()]
q = r - l + 1
if q % 2 == 1:
print(0)
else:
if q / 2 <= one and... | |
MatrixStudio/Codeforces-Python-Submissions | You are given $n$ strings. Each string consists of lowercase English letters. Rearrange (reorder) the given strings in such a way that for every string, all strings that are placed before it are its substrings.
String $a$ is a substring of string $b$ if it is possible to choose several consecutive letters in $b$ in su... | ```python
n = int(input())
strings = dict()
length = []
for i in range(n):
a = input()
strings[len(a)] = a
length.append(len(a))
length.sort()
for j in range(n):
length[j] = strings[length[j]]
pos = True
for k in range(n - 1):
if length[k] not in length[k + 1]:
pos = False
if pos:
pri... | |
MatrixStudio/Codeforces-Python-Submissions | Duff is in love with lovely numbers! A positive integer *x* is called lovely if and only if there is no such positive integer *a*<=><=1 such that *a*2 is a divisor of *x*.
Malek has a number store! In his store, he has only divisors of positive integer *n* (and he has all of them). As a birthday present, Malek want... | ```python
import math
def check_square_division(n):
for i in range(2, math.floor(math.sqrt(n))):
if n % (i ** 2) == 0:
return False
return True
def main():
n= int(input())
divisors = []
for i in range(1, n+1):
if n % i == 0:
divisors.append(... | |
MatrixStudio/Codeforces-Python-Submissions | 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 *p**i* peopl... | ```python
n =input()
n =int(n)
X = 0
for i in range(1,n+1):
a, b =input().split()
a =int(a)
b =int(b)
if(b - a >= 2):
x=x+1
print(x)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Fedya studies in a gymnasium. Fedya's maths hometask is to calculate the following expression:
for given value of *n*. Fedya managed to complete the task. Can you? Note that given number *n* can be extremely large (e.g. it can exceed any integer type of your programming language). | ```python
def expression(n):
if (n%4):
return 0
else:
return 4
n = int(input())
result = expression(n)
print(result)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Your friend has recently learned about coprime numbers. A pair of numbers {*a*,<=*b*} is called coprime if the maximum number that divides both *a* and *b* is equal to one.
Your friend often comes up with different statements. He has recently supposed that if the pair (*a*,<=*b*) is coprime and the pair (*b*,<=*c*) i... | ```python
def gcd(a, b):
rem = 0
while b != 0:
rem = a%b
a = b
b = rem
return a
a, b = map(int, input().split())
if b-a == 1:
print (-1)
else:
found = False
for i in range(a, b+1):
for j in range(i+1, b+1):
for k in range(j+1, b+1)... | |
MatrixStudio/Codeforces-Python-Submissions | String can be called correct if it consists of characters "0" and "1" and there are no redundant leading zeroes. Here are some examples: "0", "10", "1001".
You are given a correct string *s*.
You can perform two different operations on this string:
1. swap any pair of adjacent characters (for example, "101" "110"... | ```python
n = int(input())
st = list(input())
if not "1" in st:
print(0)
quit()
print("1", end = "")
for i in st:
if i == "0":
print(i, end = "")
print()
``` | |
MatrixStudio/Codeforces-Python-Submissions | Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th... | ```python
data = input()
l=u = 0
for x in data:
if x.islower():
l+=1
else:
u+=1
if l>=u:
print(data.lower())
else:
print(data.upper())
``` | |
MatrixStudio/Codeforces-Python-Submissions | «Polygon» is a system which allows to create programming tasks in a simple and professional way. When you add a test to the problem, the corresponding form asks you for the test index. As in most cases it is clear which index the next test will have, the system suggests the default value of the index. It is calculated ... | ```python
n=int(input())
l=list(map(int,input().split()))
l.sort()
if l[0]>1:
print(1)
else:
for i in range(len(l)-1):
if l[i+1]-l[i]>1:
print(l[i]+1)
break
else:
print(l[-1]+1)
``` | |
MatrixStudio/Codeforces-Python-Submissions | On the way to Rio de Janeiro Ostap kills time playing with a grasshopper he took with him in a special box. Ostap builds a line of length *n* such that some cells of this line are empty and some contain obstacles. Then, he places his grasshopper to one of the empty cells and a small insect in another empty cell. The gr... | ```python
n,k = map(int,input().split())
s = input()
first = s.index('G')
last = s.index('T')
if first < last:
if s[first+k] == 'T':
print("YES")
elif s[first+k] == '#':
print("NO")
elif first+k > last:
print("NO")
elif s[first+k] == '.':
if s[(first+k)+1] == ... | |
MatrixStudio/Codeforces-Python-Submissions | An exam for *n* students will take place in a long and narrow room, so the students will sit in a line in some order. The teacher suspects that students with adjacent numbers (*i* and *i*<=+<=1) always studied side by side and became friends and if they take an exam sitting next to each other, they will help each other... | ```python
n=int(input())
if n==3:
print (2)
print ('1 3')
exit()
if n==2:
print (1)
print (1)
a=[]
b=[]
for i in range (1,n+1):
if i%2==0:
a.append(i)
else :
b.append(i)
c=a+b
print (n)
print (" ".join(map(str,c)))
``` | |
MatrixStudio/Codeforces-Python-Submissions | 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... | ```python
p=int(input())
for i in range(p):
sedd=input()
if(len(sedd)<=10):
print(sedd)
else:
print(sedd[0]+str(len(sedd)-2)+sedd[len(sedd)-1])
``` | |
MatrixStudio/Codeforces-Python-Submissions | A sum of *p* rubles is charged from Arkady's mobile phone account every day in the morning. Among the following *m* days, there are *n* days when Arkady will top up the account: in the day *d**i* he will deposit *t**i* rubles on his mobile phone account. Arkady will always top up the account before the daily payment wi... | ```python
n,p,m=map(int,input().split())
l2=[]
ld=[]
lt=[]
k=0
for i in range(n):
d,t=map(int,input().split())
ld.append(d)
lt.append(t)
for i in range(1,m+1):
if i in ld:
k+=lt[ld.index(i)]
l2.append(k)
s=0
for i in range(m):
if l2[i]<p*(i+1):
s+=1
print(s)
``` | |
MatrixStudio/Codeforces-Python-Submissions | 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... | ```python
def has_different_digits(year):
year_str = str(year)
return len(set(year_str)) == len(year_str)
def next_year(current_year):
current_year+=1
while has_different_digits(current_year) is not True:
current_year+=1
return current_year
y= int(input())
result = next_year... | |
MatrixStudio/Codeforces-Python-Submissions | Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of *n* vertices. Vertex 1 is the root of the tree.
Alice starts at vertex 1 and Bob starts at vertex *x* (*x*<=≠<=1). The moves are made in turns, Bob go... | ```python
import sys
sys.setrecursionlimit(10 ** 6)
n, x = map(int, input().split())
x -= 1
G = [[] for i in range(n)]
for i in range(n - 1):
a, b = map(int, input().split())
G[a - 1].append(b - 1)
G[b - 1].append(a - 1)
INF = float('inf')
dista = [0] * n
distb = [-1] * n
def dfsa(u, par, d)... | |
MatrixStudio/Codeforces-Python-Submissions | Several ages ago Berland was a kingdom. The King of Berland adored math. That's why, when he first visited one of his many palaces, he first of all paid attention to the floor in one hall. The floor was tiled with hexagonal tiles.
The hall also turned out hexagonal in its shape. The King walked along the perimeter of ... | ```python
a,b,c = map(int,input().split())
t = min(a,b,c)-1
s=a+b+c
p=0
for k in range(t):
s+=(s-3)
print(s*2-((t+1)*6))
``` | |
MatrixStudio/Codeforces-Python-Submissions | You are given a string *s* consisting only of characters 0 and 1. A substring [*l*,<=*r*] of *s* is a string *s**l**s**l*<=+<=1*s**l*<=+<=2... *s**r*, and its length equals to *r*<=-<=*l*<=+<=1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring.
You have to deter... | ```python
n=int(input())
c=[]
maxx=[]
for i in range(n):
m=int(input())
c.append(m)
if len(c)==2 :
if c.count(1)==c.count(0):
print(2)
else :
for a in range(n):
for b in range(n):
q=c[a:b]
if q.count(1)==q.count(0):
maxx.appen... | |
MatrixStudio/Codeforces-Python-Submissions | Sereja and Dima play a game. The rules of the game are very simple. The players have *n* cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. Th... | ```python
n=int(input())
l1=list(map(int,input().split()))
s=0
d=0
le=len(l1)
if(le%2==0):
while len(l1)>0:
if(l1[0]>=l1[-1]):
s=s+l1[0]
l1.pop(0)
else:
s=s+l1[-1]
l1.pop(-1)
if(l1[0]>=l1[-1]):
d=d+l1[0]
l... | |
MatrixStudio/Codeforces-Python-Submissions | Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $n - 2$ intermediate planets. Formally: we number all the planets from $1$ to $n$. $1$ is Earth, $n$ is Mars. Natasha will make exactly $n$ flights: $1 \to 2 \to \ldots n \to 1$.
Flight from $x$ to $y$ consists ... | ```python
import sys
from math import *
from collections import Counter,defaultdict,deque
input=sys.stdin.readline
mod=10**9+7
def get_ints():return map(int,input().split())
def get_int():return int(input())
def get_array():return list(map(int,input().split()))
def input():return sys.stdin.readline().strip()
... | |
MatrixStudio/Codeforces-Python-Submissions | 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... | ```python
a = list(input())
b= list(input())
c = list(input())
for i in c:
if i in a:
a.remove(i)
elif i in b:
b.remove(i)
else:
print("NO")
quit()
if len(a) ==0 and len(b)==0:
print("YES")
else:
print('NO')
``` | |
MatrixStudio/Codeforces-Python-Submissions | 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... | ```python
n=list(map(str,input().split()))
m=list(map(str,input().split()))
lst=[]
for i in n:
for j in m:
if i!=j:
x=1
lst.append(x)
else:
y=0
lst.append(y)
print(''.join(lst))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Petya loves lucky numbers. Everybody knows that positive integers are lucky if their decimal representation doesn't contain digits other than 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Lucky number is super lucky if it's decimal representation contains equal amount of digits 4 and 7. Fo... | ```python
import sys
n = sys.stdin.readline()
t = map(int, sys.stdin.readline().split())
count = {}
for i in xrange(-10, 11):
count[i] = 0;
ret = 0
for x in t:
count[x] += 1
for x in t:
ret += count[-x]
if x == 0:
ret -= 1
print ret / 2
``` | |
MatrixStudio/Codeforces-Python-Submissions | You are solving the crossword problem K from IPSC 2014. You solved all the clues except for one: who does Eevee evolve into? You are not very into pokemons, but quick googling helped you find out, that Eevee can evolve into eight different pokemons: Vaporeon, Jolteon, Flareon, Espeon, Umbreon, Leafeon, Glaceon, and Syl... | ```python
import re
input()
s = input()
arr = ['vaporeon', 'jolteon', 'flareon', 'espeon', 'umbreon', 'leafeon', 'glaceon', 'sylveon']
for res in arr:
if re.match(s, res):
print(res)
break
``` | |
MatrixStudio/Codeforces-Python-Submissions | Vasya wants to turn on Christmas lights consisting of *m* bulbs. Initially, all bulbs are turned off. There are *n* buttons, each of them is connected to some set of bulbs. Vasya can press any of these buttons. When the button is pressed, it turns on all the bulbs it's connected to. Can Vasya light up all the bulbs?
I... | ```python
n,m=map(int,input().split())
num=[(int(x) for x in input().split())for i in range(n)]
x=0
for i in range(m):
if i in num:
x+=1
print(['NO','YES'][x!=m])
``` | |
MatrixStudio/Codeforces-Python-Submissions | Lolek and Bolek are about to travel abroad by plane. The local airport has a special "Choose Your Plane" offer. The offer's conditions are as follows:
- it is up to a passenger to choose a plane to fly on; - if the chosen plane has *x* (*x*<=><=0) empty seats at the given moment, then the ticket for such a plane ... | ```python
def get_cost(command,zlotys,passengers,cost = 0):
while passengers:
cost += command(zlotys)
zlotys[zlotys.index(command(zlotys))] -= 1
if not zlotys[zlotys.index(command(zlotys))]:
zlotys.pop(zlotys.index(command(zlotys)))
passengers -= 1
... | |
MatrixStudio/Codeforces-Python-Submissions | There are *n* cards (*n* is even) in the deck. Each card has a positive integer written on it. *n*<=/<=2 people will play new card game. At the beginning of the game each player gets two cards, each card is given to exactly one player.
Find the way to distribute cards such that the sum of values written of the cards ... | ```python
def division():
n = int(input())
a = [(int(num), i) for i, num in enumerate(input().split(), 1)]
a.sort()
for i in range(n // 2):
print(a[i][1], a[n - 1 - i][1])
division()
``` | |
MatrixStudio/Codeforces-Python-Submissions | 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... | ```python
word1 = str(input()).lower()
word2 = str(input()).lower()
if (word1 == word2): print(0)
elif (word1 < word2): print(-1)
else: print(1)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Vitaly is a diligent student who never missed a lesson in his five years of studying in the university. He always does his homework on time and passes his exams in time.
During the last lesson the teacher has provided two strings *s* and *t* to Vitaly. The strings have the same length, they consist of lowercase Engli... | ```python
def charToInt(c): #'a'->0
return ord(c)-ord('a')
def intToChar(x): #0->'a'
return chr(ord('a')+x)
s=input()
t=input()
tt=[charToInt(c) for c in t]
ss=[charToInt(c) for c in s]
n=len(tt)
for i in range(n-1,-1,-1):
ss[i]+=1
if ss[i]==26:
ss[i]-=1
else:
bre... | |
MatrixStudio/Codeforces-Python-Submissions | Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given *n* numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given *n* numbers finds one that i... | ```python
def main():
n = int(input())
arr = list(map(int, input().split()))
even = 0
odd = 0
for i in arr:
if i % 2 == 0:
even += 1
else:
odd += 1
for i in range(n):
if even == 1:
if arr[i] % 2 == 0:
pr... | |
MatrixStudio/Codeforces-Python-Submissions | Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?
You are given a system of equations:
You should count, how many there are pairs of int... | ```python
# your code goes here# your code goes her
n,m=map(int,input().split())
diff= n-m
ans=0
for i in range(1001):
for j in range(1001):
eq=(i-j)*(i+j-1)
if eq==diff and (i*i+j)==n and (j*j+i)==m:
ans=ans+1
print(ans)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Jon fought bravely to rescue the wildlings who were attacked by the white-walkers at Hardhome. On his arrival, Sam tells him that he wants to go to Oldtown to train at the Citadel to become a maester, so he can return and take the deceased Aemon's place as maester of Castle Black. Jon agrees to Sam's proposal and Sam s... | ```python
n,l,r = map(int,input().split(' '))
x = n
len = 0
def lon(c):
if c > 0:
return 1 + lon(c // 2) + lon(c // 2)
else:
return 0
len =lon(x)
def f(n,left,right):
if right < l or left > r:
return 0
else:
mid = (left + right) // 2
if mid <= r and mid >= l:
... | |
MatrixStudio/Codeforces-Python-Submissions | Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands:
- Include a person... | ```python
ans = 0
try:
n = 0
while True:
s = input()
if s[0] == '+':
n += 1
elif s[0] == '-':
n -= 1
else:
ans += len(s.split(':')[1]) * n
except:
pass
print(ans)
``` | |
MatrixStudio/Codeforces-Python-Submissions | 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 zero,... | ```python
# for _ in range(int(input())):
n,k = input().split()
n = int(n)
k=int(k)
while k !=0:
if n%10 >=k:
n = n-k
k=0
elif n%10 ==0:
n = n//10
k -=1
else:
temp = n%10
n -= temp
k -=temp
# print(n)
print(n)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Yaroslav has an array that consists of *n* integers. In one second Yaroslav can swap two neighboring array elements. Now Yaroslav is wondering if he can obtain an array where any two neighboring elements would be distinct in a finite time.
Help Yaroslav. | ```python
n = int( input() )
a = list( map( int, input().strip().split( ' ' ) ) )
m = max( set( a ), key=a.count )
if (n == 1):
print( "YES" )
elif (m > n / 2):
print( "NO" )
else:
print( "YES" )
``` | |
MatrixStudio/Codeforces-Python-Submissions | A sequence *a*0,<=*a*1,<=...,<=*a**t*<=-<=1 is called increasing if *a**i*<=-<=1<=<<=*a**i* for each *i*:<=0<=<<=*i*<=<<=*t*.
You are given a sequence *b*0,<=*b*1,<=...,<=*b**n*<=-<=1 and a positive integer *d*. In each move you may choose one element of the given sequence and add *d* to it. What is the least... | ```python
n,d = map(int,input().split())
a = list(map(int,input().split()))
ans = 1
for i in range(1,n):
if a[i] <= a[i-1]:
ans += (a[i - 1] - a[i]) // d + 1
a[i] = d*((a[i - 1] - a[i]) // d + 1)
print(ans)
``` | |
MatrixStudio/Codeforces-Python-Submissions | You are given *n* switches and *m* lamps. The *i*-th switch turns on some subset of the lamps. This information is given as the matrix *a* consisting of *n* rows and *m* columns where *a**i*,<=*j*<==<=1 if the *i*-th switch turns on the *j*-th lamp and *a**i*,<=*j*<==<=0 if the *i*-th switch is not connected to the *j*... | ```python
def adding(a, b):
res = ""
tracker = True
for i in range(len(a)):
res += str(int(a[i]) + int(b[i]))
if int(a[i]) == 0 and int(b[i]) == 1:
tracker = False
return res, tracker
if __name__ == "__main__":
n, m = list(map(int, input().rstrip().split()))
... | |
MatrixStudio/Codeforces-Python-Submissions | In the beginning of the new year Keivan decided to reverse his name. He doesn't like palindromes, so he changed Naviek to Navick.
He is too selfish, so for a given *n* he wants to obtain a string of *n* characters, each of which is either 'a', 'b' or 'c', with no palindromes of length 3 appearing in the string as a su... | ```python
import random
n = int(input()) # the length of the string
options = ['a', 'b', 'c']
output = []
i = 0
while len(output) < n:
if i % 3 == 0:
i = 0
next = options[i]
output.append(next)
i += 1
print("".join(output))
``` | |
MatrixStudio/Codeforces-Python-Submissions | One day shooshuns found a sequence of *n* integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps:
1. Find the number that goes *k*-th in the current sequence and add the same number to the end of the sequence; 1. Delete the first number of the current ... | ```python
import math
def input_list_int():
return list(map(int, input().split()))
n, _k = input_list_int()
a = input_list_int()
k = _k - 1
s = False
el = a[k]
for i in range(k, n):
if a[i] != el:
print(-1)
exit()
j = 0
for i in range(k):
if a[i] != a[k+1]:
... | |
MatrixStudio/Codeforces-Python-Submissions | This problem's actual name, "Lexicographically Largest Palindromic Subsequence" is too long to fit into the page headline.
You are given string *s* consisting of lowercase English letters only. Find its lexicographically largest palindromic subsequence.
We'll call a non-empty string *s*[*p*1*p*2... *p**k*] = *s**p*1*... | ```python
ans = ""
s = input()
for m in range(1 << len(s)):
f = "".join([s[i] for i in range(len(s)) if m & (1 << i)])
if f == f[::-1]:
ans = max(ans,f)
print(ans)
``` | |
MatrixStudio/Codeforces-Python-Submissions | The input contains a single integer *a* (0<=≤<=*a*<=≤<=35).
Output a single integer. | ```python
n = int(input())
print(2 ** n if n < 35 else 33940307968)
``` | |
MatrixStudio/Codeforces-Python-Submissions | 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.... | ```python
s=input()
t=input()
print("YES") if s[::-1]==t else print("NO")
``` | |
MatrixStudio/Codeforces-Python-Submissions | Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number *a* and Antisimon receives number *b*. They also have a heap of *n* stones. The players take turns to make a move and Simon starts. During a move a player should take... | ```python
a, b, n = map(int, input().split())
while n > 0:
temp_a, temp_n = a, n
while temp_n > 0:
temp_a, temp_n = temp_n, temp_a % temp_n
n -= temp_a
if n > 0:
temp_b, temp_n = b, n
while temp_n > 0:
temp_b, temp_n = temp_b, temp_b % temp_n
... | |
MatrixStudio/Codeforces-Python-Submissions | Today Vasya visited a widely known site and learned that the continuation of his favourite game Codecraft II will appear after exactly *k* months. He looked at the calendar and learned that at the moment is the month number *s*. Vasya immediately got interested in what month Codecraft III will appear. Help him understa... | ```python
#include<bits/stdc++.h>
using namespace std;
int main(void){
string s;
cin>>s;
int k;
cin>>k;
map<string,int>m;
m["January"]=1;
m["February"]=2;
m["March"]=3;
m["April"]=4;
m["May"]=5;
m["June"]=6;
m["July"]=7;
m["August"]=8;
m["Septemb... | |
MatrixStudio/Codeforces-Python-Submissions | On one quiet day all of sudden Mister B decided to draw angle *a* on his field. Aliens have already visited his field and left many different geometric figures on it. One of the figures is regular convex *n*-gon (regular convex polygon with *n* sides).
That's why Mister B decided to use this polygon. Now Mister B must... | ```python
n,k=map(int,input().split())
if n==3:print("1 2 3")
else:
ans=3
t=180/n
for i in range(4,n+1):
if abs(k-(i-2)*t)<abs(k-(ans-2)*t):
ans=i
print(*[1,2,ans])
``` | |
MatrixStudio/Codeforces-Python-Submissions | You are given a sequence *a* consisting of *n* integers. Find the maximum possible value of (integer remainder of *a**i* divided by *a**j*), where 1<=≤<=*i*,<=*j*<=≤<=*n* and *a**i*<=≥<=*a**j*. | ```python
n=int(input())
b=list(map(int,input().split()))
b.sort()
k=-1
r=n-1
l=0
p=-1
for i in range(n):
m=b[i]*2-1
while l <= r:
mid=(r+l)//2
if b[mid]<=m:
k=mid
l=mid+1
else:
r=mid-1
p=max(p,b[k]%b[i])
print(p)
``` | |
MatrixStudio/Codeforces-Python-Submissions | You have two friends. You want to present each of them several positive integers. You want to present *cnt*1 numbers to the first friend and *cnt*2 numbers to the second friend. Moreover, you want all presented numbers to be distinct, that also means that no number should be presented to both friends.
In addition, the... | ```python
def check(mid,c1,c2,x,y):
facy=mid//y
facx=mid//x
one=facy
two=facx
cnt=mid
cnt-=(one+two)
cnt-=max((c1-one),0)
cnt-=max((c2-two),0)
return cnt>=0
c1,c2,x,y=map(int,input().strip().split())
lo=1
hi=10**9
ans=-1
while lo<=hi:
mid=(lo+hi)//2
if check... | |
MatrixStudio/Codeforces-Python-Submissions | ZS the Coder is coding on a crazy computer. If you don't type in a word for a *c* consecutive seconds, everything you typed disappear!
More formally, if you typed a word at second *a* and then the next word at second *b*, then if *b*<=-<=*a*<=≤<=*c*, just the new word is appended to other words on the screen. If *b*<... | ```python
n,c=map(int,input().split())
sum=1
words=list(map(int,input().split()))
for k in range(1,n):
if words[k]-words[k-1]<=c:
sum+=1
else:
sum=1
print(sum)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Your security guard friend recently got a new job at a new security company. The company requires him to patrol an area of the city encompassing exactly *N* city blocks, but they let him choose which blocks. That is, your friend must walk the perimeter of a region whose area is exactly *N* blocks. Your friend is quite ... | ```python
#http://codeforces.com/problemset/problem/859/B
#not done
import math
def GCD(a,b):
#print(a,b)
if a < b:
a, b = b, a
if a%b == 0:
return b
else:
return GCD(b,a%b)
def minLengthsCall(n):
RA = minLengths(n)
#if len(RA) > 2:
#RA.pop()... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.