source
stringclasses 3
values | instruction
stringlengths 23
3.97k
| input
stringclasses 1
value | output
stringlengths 1
3.75k
|
---|---|---|---|
MatrixStudio/Codeforces-Python-Submissions
|
You have *n* distinct points on a plane, none of them lie on *OY* axis. Check that there is a point after removal of which the remaining points are located on one side of the *OY* axis.
|
```python
# https://codeforces.com/problemset/problem/900/A
left = 0
right = 0
for _ in range(int(input())):
x, y = map(int, input().split())
if x < 0:
left += 1
if x > 0:
right += 1
if left > 1 and right > 1:
print("NO")
break
else:
print("YES")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in *n* different shops in the city. It's known that the price of one bottle in the shop *i* is equal to *x**i* coins.
Vasiliy plans to buy his favorite drink for *q* consecutive days. He knows, that on the *i*-th day he will be able to spent *m**i* coins. Now, for each of the days he want to know in how many different shops he can buy a bottle of "Beecola".
|
```python
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 13 22:31:05 2023
@author: 刘婉婷 2300012258
"""
n = int(input())
beecola_price = list(map(int, input().split()))
beecola_price.sort()
q = int(input())
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] <= target:
left = mid + 1
else:
right = mid - 1
return left
for _ in range(q):
m = int(input())
num = binary_search(beecola_price, m)
print(num)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Roma works in a company that sells TVs. Now he has to prepare a report for the last year.
Roma has got a list of the company's incomes. The list is a sequence that consists of *n* integers. The total income of the company is the sum of all integers in sequence. Roma decided to perform exactly *k* changes of signs of several numbers in the sequence. He can also change the sign of a number one, two or more times.
The operation of changing a number's sign is the operation of multiplying this number by -1.
Help Roma perform the changes so as to make the total income of the company (the sum of numbers in the resulting sequence) maximum. Note that Roma should perform exactly *k* changes.
|
```python
n, k = map(int, input().split())
a = list(map(int, input().split()))
for i in range(n):
if k > 0 and a[i] < 0:
k -= 1
a[i] *= -1
a.sort()
a[0] *= (-1)**k
print(sum(a))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little Vasya went to the supermarket to get some groceries. He walked about the supermarket for a long time and got a basket full of products. Now he needs to choose the cashier to pay for the products.
There are *n* cashiers at the exit from the supermarket. At the moment the queue for the *i*-th cashier already has *k**i* people. The *j*-th person standing in the queue to the *i*-th cashier has *m**i*,<=*j* items in the basket. Vasya knows that:
- the cashier needs 5 seconds to scan one item; - after the cashier scans each item of some customer, he needs 15 seconds to take the customer's money and give him the change.
Of course, Vasya wants to select a queue so that he can leave the supermarket as soon as possible. Help him write a program that displays the minimum number of seconds after which Vasya can get to one of the cashiers.
|
```python
n=int(input())
a=input().split()
b=[int(i) for i in a]
min1=float('inf')
for i in range(n):
c=input().split()
d=[int(j) for j in c]
e=[j*5 for j in d]
if sum(e)+len(d)*15<min1:
min1= sum(e)+len(d)*15
print(min1)
```
|
|
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 vertical line is at least *x* and at most *y* pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than *x* or greater than *y*.
|
```python
from collections import defaultdict, deque, Counter
from sys import stdin, stdout
from heapq import heappush, heappop
import math
import io
import os
import math
import bisect
#?############################################################
def isPrime(x):
if(x == 1):
return False
for i in range(2, x):
if i*i > x:
break
if (x % i == 0):
return False
return True
#?############################################################
def ncr(n, r, p):
num = den = 1
for i in range(r):
num = (num * (n - i)) % p
den = (den * (i + 1)) % p
return (num * pow(den, p - 2, p)) % p
#?############################################################
def primeFactors(n):
l = []
while n % 2 == 0:
l.append(2)
n = n / 2
for i in range(3, int(math.sqrt(n))+1, 2):
while n % i == 0:
l.append(int(i))
n = n / i
if n > 2:
l.append(n)
return list(set(l))
#?############################################################
def power(x, y, p):
res = 1
x = x % p
if (x == 0):
return 0
while (y > 0):
if ((y & 1) == 1):
res = (res * x) % p
y = y >> 1
x = (x * x) % p
return res
#?############################################################
def sieve(n):
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
return prime
#?############################################################
def digits(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
#?############################################################
def ceil(n, x):
if (n % x == 0):
return n//x
return n//x+1
#?############################################################
def mapin():
return map(int, input().split())
#?############################################################
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
# python3 15.py<in>opgf
n, m, x, y = mapin()
l = [[0, 0] for i in range(m)]
for i in range(n):
dd = input()
l.append([0, 0])
for j in range(m):
if(dd[j] == "."):
l[j][0] += 1
else:
l[j][1] += 1
dp = [[0, 0] for i in range(m+1)]
pb, pw = [0], [0]
for i in range(m):
pb.append(pb[-1]+l[i][0])
pw.append(pw[-1]+l[i][1])
dp = [[float('inf')]*(m+1) for i in range(2)]
dp[0][0] = dp[1][0] = 0
for i in range(1, m+1):
for j in range(x, y+1):
if i-j >= 0:
dp[0][i] = min(dp[0][i], dp[1][i-j]+pb[i]-pb[i-j])
dp[1][i] = min(dp[1][i], dp[0][i-j]+pw[i]-pw[i-j])
print(min(dp[0][-1], dp[1][-1]))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
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.
|
```python
# Inicializar un contador para llevar un registro de las piedras que se deben quitar
contador = 0
# Recorrer los colores de las piedras
for i in range(1, n):
if s[i] == s[i - 1]:
contador += 1
# Imprimir la respuesta
print(contador)
```
|
|
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) two such words. More formally, word "nineteen" occurs in the string the number of times you can read it starting from some letter of the string. Of course, you shouldn't skip letters.
Help her to find the maximum number of "nineteen"s that she can get in her string.
|
```python
s=input()
print(min(s.count('i'),s.count('t'),s.count('n')//3,s.count('e')//3))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There are quite a lot of ways to have fun with inflatable balloons. For example, you can fill them with water and see what happens.
Grigory and Andrew have the same opinion. So, once upon a time, they went to the shop and bought $n$ packets with inflatable balloons, where $i$-th of them has exactly $a_i$ balloons inside.
They want to divide the balloons among themselves. In addition, there are several conditions to hold:
- Do not rip the packets (both Grigory and Andrew should get unbroken packets); - Distribute all packets (every packet should be given to someone); - Give both Grigory and Andrew at least one packet; - To provide more fun, the total number of balloons in Grigory's packets should not be equal to the total number of balloons in Andrew's packets.
Help them to divide the balloons or determine that it's impossible under these conditions.
|
```python
n=int(input())
a=list(map(int, input().split()))
m=min(a)
if m*2<sum(a):
print('1\n'+str(a.index(m)))
else:
print(-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Valera is a little boy. Yesterday he got a huge Math hometask at school, so Valera didn't have enough time to properly learn the English alphabet for his English lesson. Unfortunately, the English teacher decided to have a test on alphabet today. At the test Valera got a square piece of squared paper. The length of the side equals *n* squares (*n* is an odd number) and each unit square contains some small letter of the English alphabet.
Valera needs to know if the letters written on the square piece of paper form letter "X". Valera's teacher thinks that the letters on the piece of paper form an "X", if:
- on both diagonals of the square paper all letters are the same; - all other squares of the paper (they are not on the diagonals) contain the same letter that is different from the letters on the diagonals.
Help Valera, write the program that completes the described task for him.
|
```python
def check(lis,dia,oth,i,n):
if i == 0 or i == n-1:
if lis[0] != dia:
return False
if lis[len(lis)-1] != dia:
return False
for i in range(1,len(lis)-1):
if lis[i] != oth:
return False
return True
else:
for j in range(len(lis)):
if j == i:
if lis[j]!=dia:
return False
else:
if lis[j] != oth:
return False
return True
n = int(input())
l = input()
d = l[0]
other = l[1]
if check(l,d,other,0,n) == False:
print("NO")
exit()
for i in range(1,n):
l = input()
if check(l, d, other, i, n) == False:
print("NO")
exit()
print("YES")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Arkady is playing Battleship. The rules of this game aren't really important.
There is a field of $n \times n$ cells. There should be exactly one $k$-decker on the field, i. e. a ship that is $k$ cells long oriented either horizontally or vertically. However, Arkady doesn't know where it is located. For each cell Arkady knows if it is definitely empty or can contain a part of the ship.
Consider all possible locations of the ship. Find such a cell that belongs to the maximum possible number of different locations of the ship.
|
```python
import math
def possible(x, y, mat):
total = 0
if (mat[x][y] == 0):
return 0
else:
start = y - k+1
end = y
for i in range(k):
if ((start+i)>=0 and (start+i+k) <= n):
valid = True
for j in range(k):
if (mat[x][start+i+j] != 1):
valid = False
if valid:
total+=1
start = x - k+1
for i in range(k):
if ((start+i)>=0 and (start+i+k) <= n):
valid = True
for j in range(k):
if (mat[start+i+j][y] != 1):
valid = False
if valid:
total+=1
return total
strr = input()
nums = strr.split()
n = int(nums[0])
k = int(nums[1])
matr = []
for i in range(n):
lines = input()
line = []
for j in range(n):
if (lines[j] == '#'):
line.append(0)
else:
line.append(1)
matr.append(line)
cell = [1,1]
maxp = 0
for i in range(n):
for j in range(n):
pos = possible(i,j,matr)
if (pos > maxp):
maxp = pos
cell = [i+1, j+1]
print(cell[0], cell[1])
```
|
|
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 like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.
Thus, "localization" will be spelt as "l10n", and "internationalization» will be spelt as "i18n".
You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.
|
```python
c=input()
if len(c)>10:
print(c[1]+(len(c)-2)+c[-1])
else:
print(c)
```
|
|
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 English letters, string *s* is lexicographically smaller than string *t*. Vitaly wondered if there is such string that is lexicographically larger than string *s* and at the same is lexicographically smaller than string *t*. This string should also consist of lowercase English letters and have the length equal to the lengths of strings *s* and *t*.
Let's help Vitaly solve this easy problem!
|
```python
s = input()
t = input()
n = len(s)
ans = list(s)
for i in range(n):
c = ans[i]
ans[i] = chr(ord(c) + 1)
a = ''.join(ans)
if(a > s and a < t):
print(a)
break
ans[i] = c
else:
print("No such string")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A burglar got into a matches warehouse and wants to steal as many matches as possible. In the warehouse there are *m* containers, in the *i*-th container there are *a**i* matchboxes, and each matchbox contains *b**i* matches. All the matchboxes are of the same size. The burglar's rucksack can hold *n* matchboxes exactly. Your task is to find out the maximum amount of matches that a burglar can carry away. He has no time to rearrange matches in the matchboxes, that's why he just chooses not more than *n* matchboxes so that the total amount of matches in them is maximal.
|
```python
n, m = map(int, input().split())
num = []
for _ in range(m):
num.append(list(reversed(list(map(int, input().split())))))
num.sort(reverse=True)
# print(num)
sum = 0
for i in range(len(num)):
for x in range(num[i][1]):
if n == 0: break
else:
sum += num[i][0]
n -= 1
print(sum)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Innokentiy decides to change the password in the social net "Contact!", but he is too lazy to invent a new password by himself. That is why he needs your help.
Innokentiy decides that new password should satisfy the following conditions:
- the length of the password must be equal to *n*, - the password should consist only of lowercase Latin letters, - the number of distinct symbols in the password must be equal to *k*, - any two consecutive symbols in the password must be distinct.
Your task is to help Innokentiy and to invent a new password which will satisfy all given conditions.
|
```python
a = 'abcdefghijklmnopqrstuvwxyz'
n,k = map(int, input().split())
password = ""
a = a[:k]
while len(a) < n:
a = a+a[:1]
print(a[:n])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Xenia the mathematician has a sequence consisting of *n* (*n* is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three *a*,<=*b*,<=*c* the following conditions held:
- *a*<=<<=*b*<=<<=*c*; - *a* divides *b*, *b* divides *c*.
Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.
Help Xenia, find the required partition or else say that it doesn't exist.
|
```python
def solve(ans):
#print(ans)
for l in ans:
for i in range(len(l) - 1):
if (l[i] >= l[i + 1] or l[i + 1] % l[i] != 0):
return 0
return 1
n = int(input())
a = list(map(int,input().split()))
jump = n//3
ans=[]
a.sort()
#print(a)
for i in range(n//3):
tem=[]
for j in range(i,n,jump):
tem.append(a[j])
ans.append(tem)
f=solve(ans)
if(f==0):
print(-1)
else:
for i in ans:
print(*i)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vitya has just started learning Berlanese language. It is known that Berlanese uses the Latin alphabet. Vowel letters are "a", "o", "u", "i", and "e". Other letters are consonant.
In Berlanese, there has to be a vowel after every consonant, but there can be any letter after any vowel. The only exception is a consonant "n"; after this letter, there can be any letter (not only a vowel) or there can be no letter at all. For example, the words "harakiri", "yupie", "man", and "nbo" are Berlanese while the words "horse", "king", "my", and "nz" are not.
Help Vitya find out if a word $s$ is Berlanese.
|
```python
s=input()+''
output='YES'
t='aeiou'
n=len(s)
for i in range(n-1):
if s[i] not in t+'n' and s[i+1] not in t:
output='NO'
break
print(output)
```
|
|
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 *i*-th letter of her name should be 'O' (uppercase) if *i* is a member of Fibonacci sequence, and 'o' (lowercase) otherwise. The letters in the name are numbered from 1 to *n*. Fibonacci sequence is the sequence *f* where
- *f*1<==<=1, - *f*2<==<=1, - *f**n*<==<=*f**n*<=-<=2<=+<=*f**n*<=-<=1 (*n*<=><=2).
As her friends are too young to know what Fibonacci sequence is, they asked you to help Eleven determine her new name.
|
```python
n = int(input())
a = 1
b = 1
c = [1, 1]
while a < n and b < n:
a = a+b
c.append(a)
b = a+b
c.append(b)
d = []
for i in range(1, n+1):
if i in c:
d.append('O')
else:
d.append('o')
print(''.join(d))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Leha somehow found an array consisting of *n* integers. Looking at it, he came up with a task. Two players play the game on the array. Players move one by one. The first player can choose for his move a subsegment of non-zero length with an odd sum of numbers and remove it from the array, after that the remaining parts are glued together into one array and the game continues. The second player can choose a subsegment of non-zero length with an even sum and remove it. Loses the one who can not make a move. Who will win if both play optimally?
|
```python
n=int(input())
a=list(map(int,input().split()))
c=0
for i in range(n):
if a[i]%2==1:c+=1
if c>0:break
if c>0:print('First')
else:print('Second')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number *n*. How many times can Gerald put a spell on it until the number becomes one-digit?
|
```python
num=input()
numOfTran=0
while len(num) > 1 :
sumDig=0
for curr in num :
sumDig+=int(curr)
numOfTran+=1
num=str(sumDig)
print(numOfTran)
```
|
|
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. The decimal representation of the final number shouldn't start with a zero.
|
```python
x = input()
l = []
for i in str(x):
l.append(int(i))
for i in range(len(l)):
a=9-l[i]
if(a<l[i]):
l[i]=a
if(l[0]==0):
l[0]=9
for i in range(len(l)):
print(l[i],end="")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There are times you recall a good old friend and everything you've come through together. Luckily there are social networks — they store all your message history making it easy to know what you argued over 10 years ago.
More formal, your message history is a sequence of messages ordered by time sent numbered from 1 to *n* where *n* is the total number of messages in the chat.
Each message might contain a link to an earlier message which it is a reply to. When opening a message *x* or getting a link to it, the dialogue is shown in such a way that *k* previous messages, message *x* and *k* next messages are visible (with respect to message *x*). In case there are less than *k* messages somewhere, they are yet all shown.
Digging deep into your message history, you always read all visible messages and then go by the link in the current message *x* (if there is one) and continue reading in the same manner.
Determine the number of messages you'll read if your start from message number *t* for all *t* from 1 to *n*. Calculate these numbers independently. If you start with message *x*, the initial configuration is *x* itself, *k* previous and *k* next messages. Messages read multiple times are considered as one.
|
```python
n, k = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
dic = {}
for i in range(1, n + 1):
dic[i] = a[i-1]
counts = dict.fromkeys(dic)
for key, value in counts.items():
if key == 1:
counts[key] = set()
counts[key].add(key)
for i in range(1, k+1):
counts[key].add(key+i)
elif key == n:
counts[key] = set()
counts[key].add(key)
for i in range(1, k+1):
counts[key].add(key - i)
if dic[key] is not 0:
for item in counts[dic[key]]:
counts[key].add(item)
else:
counts[key] = set()
counts[key].add(key)
for i in range(1, k+1):
counts[key].add(key-i)
counts[key].add(key+i)
if dic[key] is not 0:
for item in counts[dic[key]]:
counts[key].add(item)
sol =[]
for value in counts.values():
sol.append(len(value))
print(sol)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Today, Wet Shark is given *n* integers. Using any of these integers no more than once, Wet Shark wants to get maximum possible even (divisible by 2) sum. Please, calculate this value for Wet Shark.
Note, that if Wet Shark uses no integers from the *n* integers, the sum is an even integer 0.
|
```python
n=int(input())
arr=([int(i) for i in input().split()])
sum=0
for i in range (n):
sum = sum + arr[i]
if sum%2==0:
sum=sum+0
else:
sum=sum-arr[n-1]
print(sum)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Polycarp takes part in a quadcopter competition. According to the rules a flying robot should:
- start the race from some point of a field, - go around the flag, - close cycle returning back to the starting point.
Polycarp knows the coordinates of the starting point (*x*1,<=*y*1) and the coordinates of the point where the flag is situated (*x*2,<=*y*2). Polycarp’s quadcopter can fly only parallel to the sides of the field each tick changing exactly one coordinate by 1. It means that in one tick the quadcopter can fly from the point (*x*,<=*y*) to any of four points: (*x*<=-<=1,<=*y*), (*x*<=+<=1,<=*y*), (*x*,<=*y*<=-<=1) or (*x*,<=*y*<=+<=1).
Thus the quadcopter path is a closed cycle starting and finishing in (*x*1,<=*y*1) and containing the point (*x*2,<=*y*2) strictly inside.
What is the minimal length of the quadcopter path?
|
```python
x1,y1 = map(int,input().split())
x2,y2 = map(int,input().split())
r = (x1 == x2) + (x1 == x2)
print(((abs(x1-x2) + 1)*2) + ((abs(y1-y2) + 1)*2) + r)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Let's call the roundness of the number the number of zeros to which it ends.
You have an array of *n* numbers. You need to choose a subset of exactly *k* numbers so that the roundness of the product of the selected numbers will be maximum possible.
|
```python
from collections import deque
def main():
n, k = [int(t) for t in input().split()]
numbers = [int(t) for t in input().split()]
product_counts = [get_product_count(number) for number in numbers]
number_counts = {}
for number in numbers:
if number in number_counts.keys():
number_counts[number] += 1
else:
number_counts[number] = 1
product_counts_by_two = deque(sorted(product_counts, key=cmp_to_key(two_first_comparator), reverse=True))
product_counts_by_five = deque(sorted(product_counts, key=cmp_to_key(five_first_comparator), reverse=True))
two_count = 0
five_count = 0
taken = 0
while taken < k:
if two_count < five_count:
next_number = product_counts_by_two.popleft()
else:
next_number = product_counts_by_five.popleft()
if number_counts[next_number.number] > 0:
two_count += next_number.two_count
five_count += next_number.five_count
number_counts[next_number.number] -= 1
taken += 1
print(min(two_count, five_count))
def cmp_to_key(mycmp):
class K:
def __init__(self, obj, *args):
self.obj = obj
def __lt__(self, other):
return mycmp(self.obj, other.obj) < 0
def __gt__(self, other):
return mycmp(self.obj, other.obj) > 0
def __eq__(self, other):
return mycmp(self.obj, other.obj) == 0
def __le__(self, other):
return mycmp(self.obj, other.obj) <= 0
def __ge__(self, other):
return mycmp(self.obj, other.obj) >= 0
def __ne__(self, other):
return mycmp(self.obj, other.obj) != 0
return K
def two_first_comparator(product_count_1, product_count_2):
if product_count_1.two_count < product_count_2.two_count:
return -1
if product_count_1.two_count > product_count_2.two_count:
return 1
if product_count_1.five_count < product_count_2.five_count:
return -1
if product_count_1.five_count > product_count_2.five_count:
return 1
return 0
def five_first_comparator(product_count_1, product_count_2):
if product_count_1.five_count < product_count_2.five_count:
return -1
if product_count_1.five_count > product_count_2.five_count:
return 1
if product_count_1.two_count < product_count_2.two_count:
return -1
if product_count_1.two_count > product_count_2.two_count:
return 1
return 0
def get_product_count(number):
two_count = calculate_product_count(number, 2)
five_count = calculate_product_count(number, 5)
return ProductCount(two_count, five_count, number)
def calculate_product_count(number, base):
product_count = 0
while number % base == 0:
product_count += 1
number //= base
return product_count
class ProductCount(object):
def __init__(self, two_count, five_count, number):
self.two_count = two_count
self.five_count = five_count
self.number = number
if __name__ == '__main__':
main()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
After winning gold and silver in IOI 2014, Akshat and Malvika want to have some fun. Now they are playing a game on a grid made of *n* horizontal and *m* vertical sticks.
An intersection point is any point on the grid which is formed by the intersection of one horizontal stick and one vertical stick.
In the grid shown below, *n*<==<=3 and *m*<==<=3. There are *n*<=+<=*m*<==<=6 sticks in total (horizontal sticks are shown in red and vertical sticks are shown in green). There are *n*·*m*<==<=9 intersection points, numbered from 1 to 9.
The rules of the game are very simple. The players move in turns. Akshat won gold, so he makes the first move. During his/her move, a player must choose any remaining intersection point and remove from the grid all sticks which pass through this point. A player will lose the game if he/she cannot make a move (i.e. there are no intersection points remaining on the grid at his/her move).
Assume that both players play optimally. Who will win the game?
|
```python
n , m = [int(i) for i in input().split()]
if n == 1 and m == 1 :
total = n + m
elif n == 1 or m == 1:
total = n + m - 1
else:
total = n + m
if int(total / 2) % 2 == 0:
print("Malvika")
else:
print("Akshat")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Eighth-grader Vova is on duty today in the class. After classes, he went into the office to wash the board, and found on it the number *n*. He asked what is this number and the teacher of mathematics Inna Petrovna answered Vova that *n* is the answer to the arithmetic task for first-graders. In the textbook, a certain positive integer *x* was given. The task was to add *x* to the sum of the digits of the number *x* written in decimal numeral system.
Since the number *n* on the board was small, Vova quickly guessed which *x* could be in the textbook. Now he wants to get a program which will search for arbitrary values of the number *n* for all suitable values of *x* or determine that such *x* does not exist. Write such a program for Vova.
|
```python
'''
http://codeforces.com/problemset/problem/875/A
'''
value = int(input())
def display(lst):
for item in lst.sort():
print(item)
def sum_a_string(str_digit):
result = 0
for i in str_digit:
result+=int(i)
return result
def get_sum(value):
count = 0
possible_digits = []
for num in range(value+1):
num = str(num)
result = int(num) + sum_a_string(num)
if result == value:
count += 1
possible_digits.append(int(num))
print(count)
return display(possible_digits)
get_sum(value)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
In this problem you will have to deal with a real algorithm that is used in the VK social network.
As in any other company that creates high-loaded websites, the VK developers have to deal with request statistics regularly. An important indicator reflecting the load of the site is the mean number of requests for a certain period of time of *T* seconds (for example, *T*<==<=60 *seconds*<==<=1 *min* and *T*<==<=86400 *seconds*<==<=1 *day*). For example, if this value drops dramatically, that shows that the site has access problem. If this value grows, that may be a reason to analyze the cause for the growth and add more servers to the website if it is really needed.
However, even such a natural problem as counting the mean number of queries for some period of time can be a challenge when you process the amount of data of a huge social network. That's why the developers have to use original techniques to solve problems approximately, but more effectively at the same time.
Let's consider the following formal model. We have a service that works for *n* seconds. We know the number of queries to this resource *a**t* at each moment of time *t* (1<=≤<=*t*<=≤<=*n*). Let's formulate the following algorithm of calculating the mean with exponential decay. Let *c* be some real number, strictly larger than one.
Thus, the mean variable is recalculated each second using the number of queries that came at that second. We can make some mathematical calculations and prove that choosing the value of constant *c* correctly will make the value of mean not very different from the real mean value *a**x* at *t*<=-<=*T*<=+<=1<=≤<=*x*<=≤<=*t*.
The advantage of such approach is that it only uses the number of requests at the current moment of time and doesn't require storing the history of requests for a large time range. Also, it considers the recent values with the weight larger than the weight of the old ones, which helps to react to dramatic change in values quicker.
However before using the new theoretical approach in industrial programming, there is an obligatory step to make, that is, to test its credibility practically on given test data sets. Your task is to compare the data obtained as a result of the work of an approximate algorithm to the real data.
You are given *n* values *a**t*, integer *T* and real number *c*. Also, you are given *m* moments *p**j* (1<=≤<=*j*<=≤<=*m*), where we are interested in the mean value of the number of queries for the last *T* seconds. Implement two algorithms. The first one should calculate the required value by definition, i.e. by the formula . The second algorithm should calculate the mean value as is described above. Print both values and calculate the relative error of the second algorithm by the formula , where *approx* is the approximate value, obtained by the second algorithm, and *real* is the exact value obtained by the first algorithm.
|
```python
n,T,c=map(float,input().split())
#n=int(n)
#T=int(T)
a=list(map(int,input().split()))
m=int(input())
p=list(map(int,input().split()))
real=0
summ=0
for i in range(m):
mean=0
for j in range(p[i]):
mean=(mean+a[j]/T)/c
k=p[i]-int(T)
if k<0:
k=0
summ=sum(a[k:(p[i])])
real=float(summ)/T
print('{:.6}'.format(real),'{:.6}'.format(float(mean)),'{:.6}'.format(float(abs(mean-real)/real)))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point *x*(*x*<=><=0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order to get to his friend's house.
|
```python
a=input()
b=int((a/5)+1)
c=int(a/5)
if a<5:
print(1)
elif a//5==0:
print(c)
else:
print(b)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There is a straight snowy road, divided into *n* blocks. The blocks are numbered from 1 to *n* from left to right. If one moves from the *i*-th block to the (*i*<=+<=1)-th block, he will leave a right footprint on the *i*-th block. Similarly, if one moves from the *i*-th block to the (*i*<=-<=1)-th block, he will leave a left footprint on the *i*-th block. If there already is a footprint on the *i*-th block, the new footprint will cover the old one.
At the beginning, there were no footprints. Then polar bear Alice starts from the *s*-th block, makes a sequence of moves and ends in the *t*-th block. It is known that Alice never moves outside of the road.
You are given the description of Alice's footprints. Your task is to find a pair of possible values of *s*,<=*t* by looking at the footprints.
|
```python
import sys
input = sys.stdin.readline
n = int(input())
s = input()[:-1]
if 'R' in s:
if 'L' in s:
print(s.index('R')+1, s.index('L'))
else:
print(s.index('R')+1, s.rindex('R') + 2)
else:
print(s.rindex('L')+1, s.index('L'))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot.
He wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fence corners at a single angle *a*.
Will the robot be able to build the fence Emuskald wants? In other words, is there a regular polygon which angles are equal to *a*?
|
```python
#include <iostream>
using namespace std;
int main()
{
int t, a;
cin >> t;
while (t--)
{
cin >> a;
if (360 % (180 - a) == 0)
{
cout << "YES" << endl;
}
else
{
cout << "NO" << endl;
}
}
return 0;
}
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Arpa is taking a geometry exam. Here is the last problem of the exam.
You are given three points *a*,<=*b*,<=*c*.
Find a point and an angle such that if we rotate the page around the point by the angle, the new position of *a* is the same as the old position of *b*, and the new position of *b* is the same as the old position of *c*.
Arpa is doubting if the problem has a solution or not (i.e. if there exists a point and an angle satisfying the condition). Help Arpa determine if the question has a solution or not.
|
```python
def vector_product(v1x, v1y, v2x, v2y):
return (v1x * v2y - v1y * v2x)
def len_sq(vx, vy):
return (vx * vx + vy * vy)
ax, ay, bx, by, cx, cy = (int(x) for x in input().split())
abx = bx - ax
aby = by - ay
bcx = cx - bx
bcy = cy - by
if vector_product(abx, aby, bcx, bcy) == 0:
print('No')
elif len_sq(abx, aby) != len_sq(bcx, bcy):
print('No')
else:
print('Yes')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Xenia lives in a city that has *n* houses built along the main ringroad. The ringroad houses are numbered 1 through *n* in the clockwise order. The ringroad traffic is one way and also is clockwise.
Xenia has recently moved into the ringroad house number 1. As a result, she's got *m* things to do. In order to complete the *i*-th task, she needs to be in the house number *a**i* and complete all tasks with numbers less than *i*. Initially, Xenia is in the house number 1, find the minimum time she needs to complete all her tasks if moving from a house to a neighboring one along the ringroad takes one unit of time.
|
```python
# Función para calcular el tiempo necesario para una tarea especÃfica
def calcular_tiempo_para_tarea(posicion_actual, tarea, n):
distancia = tarea - posicion_actual
if distancia >= 0:
tiempo_necesario = distancia
else:
tiempo_necesario = n + distancia
return tiempo_necesario
# Lectura de la entrada
n, m = map(int, input().split())
tareas = list(map(int, input().split()))
# Inicialización de variables
posicion_actual = 1
tiempo_total = 0
# Procesamiento de las tareas
for tarea in tareas:
tiempo_para_tarea_actual = calcular_tiempo_para_tarea(posicion_actual, tarea, n)
tiempo_total += tiempo_para_tarea_actual
posicion_actual = tarea
# Imprimir el resultado
print(tiempo_total)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A country has *n* cities. Initially, there is no road in the country. One day, the king decides to construct some roads connecting pairs of cities. Roads can be traversed either way. He wants those roads to be constructed in such a way that it is possible to go from each city to any other city by traversing at most two roads. You are also given *m* pairs of cities — roads cannot be constructed between these pairs of cities.
Your task is to construct the minimum number of roads that still satisfy the above conditions. The constraints will guarantee that this is always possible.
|
```python
n, m = map(int, input().split())
massa = []
x = 0
y = 0
z = 0
for i in range ( m ):
x, y = map(int, input().split())
if not( x in massa ):
massa.append( x )
if not ( y in massa ):
massa.append ( x )
for i in range( 1, ( n + 1 )):
if not ( i in massa ):
z = i
break
print( n - 1 )
for i in range( 1, ( n + 1 )):
if ( i != z ):
print ( z , i )
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not.
The next prime number after *x* is the smallest prime number greater than *x*. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that there is exactly one next prime number after each number. So 5 is not the next prime number for 2.
One cold April morning Panoramix predicted that soon Kakofonix will break free from his straitjacket, and this will be a black day for the residents of the Gallic countryside.
Panoramix's prophecy tells that if some day Asterix and Obelix beat exactly *x* Roman soldiers, where *x* is a prime number, and next day they beat exactly *y* Roman soldiers, where *y* is the next prime number after *x*, then it's time to wait for Armageddon, for nothing can shut Kakofonix up while he sings his infernal song.
Yesterday the Gauls beat *n* Roman soldiers and it turned out that the number *n* was prime! Today their victims were a troop of *m* Romans (*m*<=><=*n*). Determine whether the Gauls should wait for the black day after today's victory of Asterix and Obelix?
|
```python
n, m = map(int, input().split())
while n <= m:
n += 1
count = 0
for i in range(1, n+1):
if n % i == 0:
count += 1
if count == 2 and n == m:
print("YES")
break
elif count == 2 and n != m:
print("NO")
break
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You have *r* red, *g* green and *b* blue balloons. To decorate a single table for the banquet you need exactly three balloons. Three balloons attached to some table shouldn't have the same color. What maximum number *t* of tables can be decorated if we know number of balloons of each color?
Your task is to write a program that for given values *r*, *g* and *b* will find the maximum number *t* of tables, that can be decorated in the required manner.
|
```python
a,b,c = sorted(list(map(int,input().split())))
score = 0
while a>0 or b>0:
if a!=0 and c>b+1:
x = 2*a
a = 0
y = c-b
c = c-b+y%2
if y>=x:
score+=x//2
y = y-x
c+=y
else:
score +=y//2
a = x//2-y//2
elif a!=0 and c<=b+1:
score+=a
b = b-a
c = c-a
a = 0
elif a==0:
score+= min(b,c//2)
b = 0
else:
break
print(score)
```
|
|
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 gives this string to C and he appends some number of letters 'c' to the end of the string. However, since C is a good friend of A and B, the number of letters 'c' he appends is equal to the number of 'a' or to the number of 'b' in the string. It is also possible that the number of letters 'c' equals both to the number of letters 'a' and to the number of letters 'b' at the same time.
You have a string in your hands, and you want to check if it is possible to obtain the string in this way or not. If it is possible to obtain the string, print "YES", otherwise print "NO" (without the quotes).
|
```python
s=input().strip()
a_count=s.count('a')
b_count=s.count('b')
c_count=s.count('c')
arr=list(s)
arr1=arr.copy()
arr1.sort()
if a_count>0 and b_count>0 and (a_count==c_count or b_count==c_count) and arr==arr1:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Permutation *p* is an ordered set of integers *p*1,<=<=*p*2,<=<=...,<=<=*p**n*, consisting of *n* distinct positive integers, each of them doesn't exceed *n*. We'll denote the *i*-th element of permutation *p* as *p**i*. We'll call number *n* the size or the length of permutation *p*1,<=<=*p*2,<=<=...,<=<=*p**n*.
The decreasing coefficient of permutation *p*1,<=*p*2,<=...,<=*p**n* is the number of such *i* (1<=≤<=*i*<=<<=*n*), that *p**i*<=><=*p**i*<=+<=1.
You have numbers *n* and *k*. Your task is to print the permutation of length *n* with decreasing coefficient *k*.
|
```python
n, k = map(int, input().split())
if k == 0:
lst1 = []
for b in range(1, n+1):
lst1.append(b)
res1 = [str(r) for r in lst1]
print(' '.join(res1))
else:
lst = []
for x in range(k):
lst.append(n - x)
for y in range(k, n):
lst.append(y - k + 1)
res = [str(b) for b in lst]
print(' '.join(res))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Sereja loves number sequences very much. That's why he decided to make himself a new one following a certain algorithm.
Sereja takes a blank piece of paper. Then he starts writing out the sequence in *m* stages. Each time he either adds a new number to the end of the sequence or takes *l* first elements of the current sequence and adds them *c* times to the end. More formally, if we represent the current sequence as *a*1,<=*a*2,<=...,<=*a**n*, then after we apply the described operation, the sequence transforms into *a*1,<=*a*2,<=...,<=*a**n*[,<=*a*1,<=*a*2,<=...,<=*a**l*] (the block in the square brackets must be repeated *c* times).
A day has passed and Sereja has completed the sequence. He wonders what are the values of some of its elements. Help Sereja.
|
```python
n,k=map(int,input().split(" "))
li=list(map(int,input().split(" ",n)[:n]))
hs=[[0 for i in range(k)] for i in range(n//k)]
for i in range(n//k):
for j in range(k):
hs[i][j]=li[i+j]
ans=0
for i in range(k):
for j in range(n//k):
```
|
|
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 that as little as possible letters should be changed in the word. For example, the word HoUse must be replaced with house, and the word ViP — with VIP. If a word contains an equal number of uppercase and lowercase letters, you should replace all the letters with lowercase ones. For example, maTRIx should be replaced by matrix. Your task is to use the given method on one given word.
|
```python
s=input()
upp=0
low=0
for i in range(len(s)):
if 'a'<=s[i]<='z':
low+=1
else:
upp+=1
if low<upp:
s=s.upper()
else:
s=s.lower()
print(s)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array *a* consisting of *n* distinct integers.
Unfortunately, the size of *a* is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question correctly: is it possible to sort the array *a* (in increasing order) by reversing exactly one segment of *a*? See definitions of segment and reversing in the notes.
|
```python
n = int(input())
nums = [int(i) for i in input().split()]
start = 0
end = 0
sorted_ascend = sorted(nums)
# for i in range(1, n + 1):
# if nums[i] < nums[i - 1]:
# start = i
# if nums[i] >
if nums == sorted_ascend:
print('yes')
print('1 1')
elif sorted_ascend[::-1] == nums:
print(1, n)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw.
The first player wrote number *a*, the second player wrote number *b*. How many ways to throw a dice are there, at which the first player wins, or there is a draw, or the second player wins?
|
```python
a,b=map(int,input().split())
win,draw,lose=0,0,0
for i in range(1,7):
if abs(a-i)<abs(b-i):
win+=1
elif abs(a-i)==abs(b-i):
draw+=1
else:
lose+=1
print(win,draw,lose)
```
|
|
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 balls from his box in his move. Players alternate turns and the first player starts the game. The one who can't make a move loses. Your task is to determine who wins if both players play optimally.
|
```python
n_1,n_2,k_1,k_2=y.split()
n_1=int(n_1)
n_2=int(n_2)
k_1=int(k_1)
k_2=int(k_2)
a="First"
b="Second"
if n_1==n_2:
print(b)
if n_1>n_2:
print(a)
else:
print(b)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in *n* different shops in the city. It's known that the price of one bottle in the shop *i* is equal to *x**i* coins.
Vasiliy plans to buy his favorite drink for *q* consecutive days. He knows, that on the *i*-th day he will be able to spent *m**i* coins. Now, for each of the days he want to know in how many different shops he can buy a bottle of "Beecola".
|
```python
n = int(input())
x = sorted(list(map(int, input().split())))
q = int(input())
for _ in range(q):
k = int(input())
l, r = 0, len(x)-1
while l <= r:
m = (l+r) // 2
if x[m] > k:
r = m - 1
elif x[m] < k:
l = m + 1
elif x[m] == k:
print(m+1)
break
else:
print(m)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word *s*. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if Vasya types the word "ahhellllloou", it will be considered that he said hello, and if he types "hlelo", it will be considered that Vasya got misunderstood and he didn't manage to say hello. Determine whether Vasya managed to say hello by the given word *s*.
|
```python
need = "hello"
j = 0
for i in input():
if i == need[j]:
j += 1
if j == len(need):
break
print("YES" if j == len(need) else "NO")
```
|
|
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
s = input("this is input")
und = False
for x in s:
if x == '-' and not und:
und = True
elif und and x == '-':
und = False
print("2", end='')
elif und and x == '.':
print('1', end='')
und = False
else:
print('0', end='')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word *s*. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if Vasya types the word "ahhellllloou", it will be considered that he said hello, and if he types "hlelo", it will be considered that Vasya got misunderstood and he didn't manage to say hello. Determine whether Vasya managed to say hello by the given word *s*.
|
```python
word = input()
indexh = word.rindex("h")
indexe = word.rindex("e")
indexl1 = indexe + word[indexe:].find("l")
indexl2 = word.rindex("l")
indexo = word.rindex("o")
if indexh < indexe and indexe < indexl1 and indexl1<indexl2 and indexl2<indexo :
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya and Petya are playing a simple game. Vasya thought of number *x* between 1 and *n*, and Petya tries to guess the number.
Petya can ask questions like: "Is the unknown number divisible by number *y*?".
The game is played by the following rules: first Petya asks all the questions that interest him (also, he can ask no questions), and then Vasya responds to each question with a 'yes' or a 'no'. After receiving all the answers Petya should determine the number that Vasya thought of.
Unfortunately, Petya is not familiar with the number theory. Help him find the minimum number of questions he should ask to make a guaranteed guess of Vasya's number, and the numbers *y**i*, he should ask the questions about.
|
```python
n, s = int(input()) + 1, set()
for i in range(2, n):
for j in range(2, n):
if not i % j:
k = i
while not k % j:
k //= j
if k == 1:
s.add(i)
break
print(len(s), *s)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One spring day on his way to university Lesha found an array *A*. Lesha likes to split arrays into several parts. This time Lesha decided to split the array *A* into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array *A*.
Lesha is tired now so he asked you to split the array. Help Lesha!
|
```python
for i in range(int(input())):
t, lis = int(input()), list(map(int, input().split()))
a, b = lis[0], lis[1]
if a==b:
for j in range(2, t):
if lis[j] != a:
print(j + 1)
break
else:
if a == lis[2]:
print(2)
else:
print(1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.
One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained?
|
```python
import re
ct = 0
total = 0
y = input().strip()
h = " ".join(y)
c = re.split(r"\s+", h)
for i in c:
if i == '(':
ct += 1
elif i == ')' and ct != 0:
ct -= 1
total += 2
print(total)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
This winter is so cold in Nvodsk! A group of *n* friends decided to buy *k* bottles of a soft drink called "Take-It-Light" to warm up a bit. Each bottle has *l* milliliters of the drink. Also they bought *c* limes and cut each of them into *d* slices. After that they found *p* grams of salt.
To make a toast, each friend needs *nl* milliliters of the drink, a slice of lime and *np* grams of salt. The friends want to make as many toasts as they can, provided they all drink the same amount. How many toasts can each friend make?
|
```python
import math
n=int(input("Number of Friends: "))
k=int(input("Number of Cans: "))
l=int(input("Mililiter of Drink: "))
nl=int(input("Drink In Each Bottle: "))
totalmil=k*l
totalto=totalmil//nl
c=int(input("Number of Limes: "))
d=int(input("Number of Slices for Each Lime: "))
totalimeslices=c*d
p=int(input("Grams of Salt: "))
np=int(input("Salt in Each Drink: "))
salt=p//np
a=min(totalto,totalimeslices,salt)//n
print(a)
#5 100 10 1 19 90 4 3
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Two friends are on the coordinate axis *Ox* in points with integer coordinates. One of them is in the point *x*1<==<=*a*, another one is in the point *x*2<==<=*b*.
Each of the friends can move by one along the line in any direction unlimited number of times. When a friend moves, the tiredness of a friend changes according to the following rules: the first move increases the tiredness by 1, the second move increases the tiredness by 2, the third — by 3 and so on. For example, if a friend moves first to the left, then to the right (returning to the same point), and then again to the left his tiredness becomes equal to 1<=+<=2<=+<=3<==<=6.
The friends want to meet in a integer point. Determine the minimum total tiredness they should gain, if they meet in the same point.
|
```python
import math
a=int(input())
b=int(input())
diff=abs(a-b)
if diff==1:
print(1)
elif diff==2:
print(2)
else:
x=math.ceil(diff/2)
y=diff-x
s1=0
s2=0
print(x,y)
for i in range(x+1):
s1+=i
for j in range(y+1):
s2+=j
print(s1+s2)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are developing a new feature for the website which sells airline tickets: being able to sort tickets by price! You have already extracted the tickets' prices, so there's just the last step to be done...
You are given an array of integers. Sort it in non-descending order.
|
```python
arr = list(map(int, input().split()))
sz = arr[0]
arr = sorted(arr[1:])
for it in arr:
print(it, end=' ')
print()
for i in range(10000000):
a = 2 * 2 * 2
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are *n* watchmen on a plane, the *i*-th watchman is located at point (*x**i*,<=*y**i*).
They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen *i* and *j* to be |*x**i*<=-<=*x**j*|<=+<=|*y**i*<=-<=*y**j*|. Daniel, as an ordinary person, calculates the distance using the formula .
The success of the operation relies on the number of pairs (*i*,<=*j*) (1<=≤<=*i*<=<<=*j*<=≤<=*n*), such that the distance between watchman *i* and watchmen *j* calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
|
```python
lst = [[1.5,1.5]]
cnt = 0
for i in range(int(input())):
x,y = map(int,input().split())
for j in lst:
if x==j[0] or y==j[1]:
cnt += 1
lst.append([x,y])
print(cnt)
```
|
|
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 Xenia. She is only beginning to count, so she can calculate a sum only if the summands follow in non-decreasing order. For example, she can't calculate sum 1+3+2+1 but she can calculate sums 1+1+2 and 3+3.
You've got the sum that was written on the board. Rearrange the summans and print the sum in such a way that Xenia can calculate the sum.
|
```python
sentence = input()
splited = sentence.split("+")
splited.sort()
result_str = ""
for i in range(len(splited)):
result_str += f"{splited[i]}+"
print(result_str[:-1])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Olesya loves numbers consisting of *n* digits, and Rodion only likes numbers that are divisible by *t*. Find some number that satisfies both of them.
Your task is: given the *n* and *t* print an integer strictly larger than zero consisting of *n* digits that is divisible by *t*. If such number doesn't exist, print <=-<=1.
|
```python
x,y=(map(int,input().split()))
if x==1 and y==10:
print(-1)
elif x>=2 and y ==10:
for i in range((x)):
print('1',end="")
print(0)
else:
for i in range((x)):
print(y,end="")
```
|
|
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 like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.
Thus, "localization" will be spelt as "l10n", and "internationalization» will be spelt as "i18n".
You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.
|
```python
def check():
word = input()
if len(word) > 10:
word = word[0] + str(len(word) - 2) + word[len(word)-1]
return word
n = int(input())
a = []
for _ in range(n):
a.append(check())
print("\n".join(a))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones.
Once he thought about a string of length *n* consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and the other contains 1, then we are allowed to remove these two digits from the string, obtaining a string of length *n*<=-<=2 as a result.
Now Andreid thinks about what is the minimum length of the string that can remain after applying the described operation several times (possibly, zero)? Help him to calculate this number.
|
```python
s = input.split()[1]
while '01' in s or '10' in s:
if '01' in s:
i = s.index('01')
else:
i = s.index('10')
s = s[:i] + s[i+2:]
print(len(s))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You've got a 5<=×<=5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix:
1. Swap two neighboring matrix rows, that is, rows with indexes *i* and *i*<=+<=1 for some integer *i* (1<=≤<=*i*<=<<=5). 1. Swap two neighboring matrix columns, that is, columns with indexes *j* and *j*<=+<=1 for some integer *j* (1<=≤<=*j*<=<<=5).
You think that a matrix looks beautiful, if the single number one of the matrix is located in its middle (in the cell that is on the intersection of the third row and the third column). Count the minimum number of moves needed to make the matrix beautiful.
|
```python
array = []
for j in range(5):
x = [int(i)for i in input().split()]
array.append(x)
for x in range(5):
for y in range(5):
if array[x][y] == 1:
print(abs(x - 2) + abs(y - 2))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Mike and some bears are playing a game just for fun. Mike is the judge. All bears except Mike are standing in an *n*<=×<=*m* grid, there's exactly one bear in each cell. We denote the bear standing in column number *j* of row number *i* by (*i*,<=*j*). Mike's hands are on his ears (since he's the judge) and each bear standing in the grid has hands either on his mouth or his eyes.
They play for *q* rounds. In each round, Mike chooses a bear (*i*,<=*j*) and tells him to change his state i. e. if his hands are on his mouth, then he'll put his hands on his eyes or he'll put his hands on his mouth otherwise. After that, Mike wants to know the score of the bears.
Score of the bears is the maximum over all rows of number of consecutive bears with hands on their eyes in that row.
Since bears are lazy, Mike asked you for help. For each round, tell him the score of these bears after changing the state of a bear selected in that round.
|
```python
import re
def maxString(a,n):
y = 0
for i in range(n):
s2 = ''.join(a[i])
if '1' not in s2:
r = 0
else:
r = len(max(re.findall("1+",s2),key=len))
if(r > y):
y = r
return y
def flip(x):
if(x == '1'):
return '0'
else:
return '1'
n,m,q = map(int,input().split())
a = []
x = []
for i in range(n):
x = list(input().split())
a.append(x)
#y = maxString(a,n)
#print('y =',y)
for i in range(q):
p,q = map(int,input().split())
a[p-1][q-1] = flip(a[p-1][q-1])
print(maxString(a,n))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock.
The combination lock is represented by *n* rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has to turn some disks so that the combination of digits on the disks forms a secret combination. In one move, he can rotate one disk one digit forwards or backwards. In particular, in one move he can go from digit 0 to digit 9 and vice versa. What minimum number of actions does he need for that?
|
```python
n = input()
start_pos = input()
open_pos = input()
counter = 0
for i, j in zip(start_pos, open_pos):
i, j = int(i), int(j)
count_pos = 0
if i == j:
continue
elif i < j:
while i < j:
i += 1
count_pos += 1
else:
while i > j:
i -= 1
count_pos += 1
if count_pos > 5:
count_pos = 10 - count_pos
counter += count_pos
print(counter)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Let us define two functions *f* and *g* on positive integer numbers.
You need to process *Q* queries. In each query, you will be given three integers *l*, *r* and *k*. You need to print the number of integers *x* between *l* and *r* inclusive, such that *g*(*x*)<==<=*k*.
|
```python
def muli(n):
x = 1
for i in range(len(n)):
if(n[i]=='0'):
continue
x = x*(int(n[i]))
return (x)
n = int(input())
for i in range(n):
l,r,k = input().split(" ")
count = 0
for j in range(int(l),int(r)+1):
x = j
while(x>=10):
x = muli(str(x))
if(x == int(k)):
count+=1
print (count)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Today on a math lesson the teacher told Vovochka that the Euler function of a positive integer φ(*n*) is an arithmetic function that counts the positive integers less than or equal to n that are relatively prime to n. The number 1 is coprime to all the positive integers and φ(1)<==<=1.
Now the teacher gave Vovochka an array of *n* positive integers *a*1,<=*a*2,<=...,<=*a**n* and a task to process *q* queries *l**i* *r**i* — to calculate and print modulo 109<=+<=7. As it is too hard for a second grade school student, you've decided to help Vovochka.
|
```python
print("_RANDOM_GUESS_1689429994.5419617")# 1689429994.5419815
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
People in the Tomskaya region like magic formulas very much. You can see some of them below.
Imagine you are given a sequence of positive integer numbers *p*1, *p*2, ..., *p**n*. Lets write down some magic formulas:
Here, "mod" means the operation of taking the residue after dividing.
The expression means applying the bitwise *xor* (excluding "OR") operation to integers *x* and *y*. The given operation exists in all modern programming languages. For example, in languages C++ and Java it is represented by "^", in Pascal — by "xor".
People in the Tomskaya region like magic formulas very much, but they don't like to calculate them! Therefore you are given the sequence *p*, calculate the value of *Q*.
|
```python
n=int(input())
L=list(map(int,input().split()))
Q=0
X=[0]*1000001
for i in range(1,1000001):
X[i]=X[i-1]^i
for i in range(1,n+1):
Q^=L[i-1]
x=n%i
y=n//i
if(y%2==1):
Q^=X[i-1]
Q^=X[x]
print(Q)
```
|
|
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. However, it's easy to make a mistake during the «translation». Vasya translated word *s* from Berlandish into Birlandish as *t*. Help him: find out if he translated the word correctly.
|
```python
lang1=input()
lang2=input()
def reverse(st):
i=0
j=len(st)-1
st=list(st)
while(i<j):
st[i],st[j]=st[j],st[i]
i+=1
j-=1
return ''.join(x for x in st)
if(str(lang1)==str(reverse(lang2))):
print('YES')
else:
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Given an array *a*1,<=*a*2,<=...,<=*a**n* of *n* integers, find the largest number in the array that is not a perfect square.
A number *x* is said to be a perfect square if there exists an integer *y* such that *x*<==<=*y*2.
|
```python
import math
n = input()
a = list(map(int,input().split()))
a = sorted(a,reverse=True)
for i in a:
if i >0:
if math.sqrt(i)**2 != i:
print(i)
break
else:
print(i)
break
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Sereja has an *n*<=×<=*m* rectangular table *a*, each cell of the table contains a zero or a number one. Sereja wants his table to meet the following requirement: each connected component of the same values forms a rectangle with sides parallel to the sides of the table. Rectangles should be filled with cells, that is, if a component form a rectangle of size *h*<=×<=*w*, then the component must contain exactly *hw* cells.
A connected component of the same values is a set of cells of the table that meet the following conditions:
- every two cells of the set have the same value; - the cells of the set form a connected region on the table (two cells are connected if they are adjacent in some row or some column of the table); - it is impossible to add any cell to the set unless we violate the two previous conditions.
Can Sereja change the values of at most *k* cells of the table so that the table met the described requirement? What minimum number of table cells should he change in this case?
|
```python
# Idea is that all rows are either A or B where A flipped = B (same is true for columns)
#
# Thus, either n and m <= k and since max value of k == 10, we can just brute force all A
#
# Or, n or m > k. WLOG say m <= n.
# Then, if A/B is not one of the existing rows, the number of flips to change each row
# is at least 1 and thus total changes is at least m > k, which is impossible.
#
# Thus, if any A/B yields <= k changes, A/B must be one of the exiting rows.
# (WLOG we can assume A is since if B is, we can just swap A and B
# and this doesn't affect the possible values for the rows = {A, B} obviously)
n, m, k = map(int, input().split())
a = [list(map(int, input().split())) for i in range(n)]
# In the case of n or m > k, we will be iterating over rows/columns whichever is shorter
# It is easier to iterate over rows, so we transpose if we need to iterate over columns
if m > n:
b = [[0]*n for i in range(m)]
for i in range(n):
for j in range(m):
b[j][i] = a[i][j]
a = b
n, m = m, n
def cost_change(common_row):
cost = 0
for row in a:
diff = 0
for j, val in enumerate(row):
diff += common_row[j] != val
cost += min(diff, (m-diff))
return cost
ans = k+1
if n > k:
# row we change to must be a current row (otherwise the cost to change each row must be at least 1, so the total
# cost is at least m > k, which is impossible
for row in a:
ans = min(ans, cost_change(row))
else:
# row could be anything
for msk in range(1<<m):
row = [msk>>k&1 for k in range(m)]
ans = min(ans, cost_change(row))
print(-1 if ans == k+1 else ans)
```
|
|
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 like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.
Thus, "localization" will be spelt as "l10n", and "internationalization» will be spelt as "i18n".
You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.
|
```python
# your code goes here
test = int(input())
for i in range(test):
n = input()
l = len(n)
if(int(l)>10):
print(n[0]+str(l-2)+n[l-1])
else:
print(n)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One beautiful July morning a terrible thing happened in Mainframe: a mean virus Megabyte somehow got access to the memory of his not less mean sister Hexadecimal. He loaded there a huge amount of *n* different natural numbers from 1 to *n* to obtain total control over her energy.
But his plan failed. The reason for this was very simple: Hexadecimal didn't perceive any information, apart from numbers written in binary format. This means that if a number in a decimal representation contained characters apart from 0 and 1, it was not stored in the memory. Now Megabyte wants to know, how many numbers were loaded successfully.
|
```python
def main():
n = int(input())
ans = 0
for i in range(1, 2**10-1):
x = int(''.join(list(bin(i))[2:]))
if x <= n:
ans += 1
else:
break
print(ans)
main()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited *n* his friends there.
If there's one thing Petya likes more that receiving gifts, that's watching others giving gifts to somebody else. Thus, he safely hid the laptop until the next New Year and made up his mind to watch his friends exchanging gifts while he does not participate in the process. He numbered all his friends with integers from 1 to *n*. Petya remembered that a friend number *i* gave a gift to a friend number *p**i*. He also remembered that each of his friends received exactly one gift.
Now Petya wants to know for each friend *i* the number of a friend who has given him a gift.
|
```python
n=int(input())
gift=list(map9int,input().split()))
res=[0]*n
for i in range(n):
res[gift[i]-1]=i+1
print(*res)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
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.
|
```python
n=int(input())
a=list(map(int,input().split()))
if n==1:
print(1)
else:
l=[]
c=0
for i in range(n-1):
if a[i]<a[i+1]:
c+=1
else:
c+=1
l.append(c)
c=0
if a[-1]>a[-2]:
c+=1
l.append(c)
print(max(l))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Valera has got *n* domino pieces in a row. Each piece consists of two halves — the upper one and the lower one. Each of the halves contains a number from 1 to 6. Valera loves even integers very much, so he wants the sum of the numbers on the upper halves and the sum of the numbers on the lower halves to be even.
To do that, Valera can rotate the dominoes by 180 degrees. After the rotation the upper and the lower halves swap places. This action takes one second. Help Valera find out the minimum time he must spend rotating dominoes to make his wish come true.
|
```python
odd1=0
odd2=0
for _ in range(int(input())):
a,b=map(int,input().split())
if a%2!=0:
odd1+=1
if b%2!=0:
odd2+=1
if odd1%2==0 and odd2%2==0:
print(0)
elif odd1%2!=0 and odd2%2!=0:
print(1)
else:
print(-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
When new students come to the Specialized Educational and Scientific Centre (SESC) they need to start many things from the beginning. Sometimes the teachers say (not always unfairly) that we cannot even count. So our teachers decided to teach us arithmetics from the start. And what is the best way to teach students add and subtract? — That's right, using counting sticks! An here's our new task:
An expression of counting sticks is an expression of type:
Sign + consists of two crossed sticks: one vertical and one horizontal. Sign = consists of two horizontal sticks. The expression is arithmetically correct if *A*<=+<=*B*<==<=*C*.
We've got an expression that looks like *A*<=+<=*B*<==<=*C* given by counting sticks. Our task is to shift at most one stick (or we can shift nothing) so that the expression became arithmetically correct. Note that we cannot remove the sticks from the expression, also we cannot shift the sticks from the signs + and =.
We really aren't fabulous at arithmetics. Can you help us?
|
```python
#||+|=|||||
a = input()
list2 = list(a)
b = int(len(list2))
if b/2 != int(b/2):
print('Impossible')
else:
for i in range(b):
list2[i] = '|'
list2[int(b/2)] = '='
list2[1] = '+'
for i in range(b):
print(list2[i],end = '')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word *s*. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if Vasya types the word "ahhellllloou", it will be considered that he said hello, and if he types "hlelo", it will be considered that Vasya got misunderstood and he didn't manage to say hello. Determine whether Vasya managed to say hello by the given word *s*.
|
```python
s = str(input())
want_string = 'hello'
cnt = len(want_string)
li = []
cnt2 = 0
for i in s:
if i == want_string[cnt2]:
cnt2 += 1
cnt -= 1
if cnt == 0:
print('YES')
else:
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Eighth-grader Vova is on duty today in the class. After classes, he went into the office to wash the board, and found on it the number *n*. He asked what is this number and the teacher of mathematics Inna Petrovna answered Vova that *n* is the answer to the arithmetic task for first-graders. In the textbook, a certain positive integer *x* was given. The task was to add *x* to the sum of the digits of the number *x* written in decimal numeral system.
Since the number *n* on the board was small, Vova quickly guessed which *x* could be in the textbook. Now he wants to get a program which will search for arbitrary values of the number *n* for all suitable values of *x* or determine that such *x* does not exist. Write such a program for Vova.
|
```python
a=input()
a=int(a)
count=0
total=0
result=[]
for x in range(a):
count=0
for y in str(x):
count+=int(y)
if(count+x==a):
total+=1
result.append(x)
print(total)
for z in result:
print(z)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Holidays have finished. Thanks to the help of the hacker Leha, Noora managed to enter the university of her dreams which is located in a town Pavlopolis. It's well known that universities provide students with dormitory for the period of university studies. Consequently Noora had to leave Vičkopolis and move to Pavlopolis. Thus Leha was left completely alone in a quiet town Vičkopolis. He almost even fell into a depression from boredom!
Leha came up with a task for himself to relax a little. He chooses two integers *A* and *B* and then calculates the greatest common divisor of integers "*A* factorial" and "*B* factorial". Formally the hacker wants to find out GCD(*A*!,<=*B*!). It's well known that the factorial of an integer *x* is a product of all positive integers less than or equal to *x*. Thus *x*!<==<=1·2·3·...·(*x*<=-<=1)·*x*. For example 4!<==<=1·2·3·4<==<=24. Recall that GCD(*x*,<=*y*) is the largest positive integer *q* that divides (without a remainder) both *x* and *y*.
Leha has learned how to solve this task very effective. You are able to cope with it not worse, aren't you?
|
```python
def fact(n):
if n <= 1:
return 1
else:
return n*fact(n-1)
a, b = map(int, input().split())
print(fact(min(a, b)))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu".
Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something!
Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result.
|
```python
class solve:
def __init__(self):
s=input()
n=len(s)
ans=""
for i in range(n):
if ans=="" or ans[-1]!=s[i]:
ans+=s[i]
l+=1
else:
ans[-1]=0
final=""
for i in ans:
if i!=0:
final+=i
print(final)
obj=solve()
```
|
|
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 sequence.
The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
|
```python
n, k = map(int,input().split())
l = [int(i) for i in input().split()]
if len(set(l[k-1:n])) != 1:
print(-1)
else:
last=l[-1]
ans=-1
for i in range(n):
if l[i] !=last:
ans=i
print(ans+1)
```
|
|
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. One night, when everyone went to bed, someone took all the letters of our characters' names. Then he may have shuffled the letters and put them in one pile in front of the door.
The next morning it was impossible to find the culprit who had made the disorder. But everybody wondered whether it is possible to restore the names of the host and his guests from the letters lying at the door? That is, we need to verify that there are no extra letters, and that nobody will need to cut more letters.
Help the "New Year and Christmas Men" and their friends to cope with this problem. You are given both inscriptions that hung over the front door the previous night, and a pile of letters that were found at the front door next morning.
|
```python
line1 = list(map(str, input().strip()))
line2 = list(map(str, input().strip()))
line3 = list(map(str, input().strip()))
line3.sort()
line = line1+line2
line.sort()
if line == line3:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little Bolek has found a picture with *n* mountain peaks painted on it. The *n* painted peaks are represented by a non-closed polyline, consisting of 2*n* segments. The segments go through 2*n*<=+<=1 points with coordinates (1,<=*y*1), (2,<=*y*2), ..., (2*n*<=+<=1,<=*y*2*n*<=+<=1), with the *i*-th segment connecting the point (*i*,<=*y**i*) and the point (*i*<=+<=1,<=*y**i*<=+<=1). For any even *i* (2<=≤<=*i*<=≤<=2*n*) the following condition holds: *y**i*<=-<=1<=<<=*y**i* and *y**i*<=><=*y**i*<=+<=1.
We shall call a vertex of a polyline with an even *x* coordinate a mountain peak.
Bolek fancied a little mischief. He chose exactly *k* mountain peaks, rubbed out the segments that went through those peaks and increased each peak's height by one (that is, he increased the *y* coordinate of the corresponding points). Then he painted the missing segments to get a new picture of mountain peaks. Let us denote the points through which the new polyline passes on Bolek's new picture as (1,<=*r*1), (2,<=*r*2), ..., (2*n*<=+<=1,<=*r*2*n*<=+<=1).
Given Bolek's final picture, restore the initial one.
|
```python
n,k=map(int,input().split())
r=list(map(int,input().split()))
c=0
for i in range(len(r)//2):
if c==k:
break
elif r[(2*i)]<r[(2*i)+1]-1>r[(2*i)+2]:
r[(2*i)+1]=r[(2*i)+1]-1
c=c+1
print(*r)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Roma (a popular Russian name that means 'Roman') loves the Little Lvov Elephant's lucky numbers.
Let us remind you that lucky numbers are positive integers whose decimal representation only contains lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Roma's got *n* positive integers. He wonders, how many of those integers have not more than *k* lucky digits? Help him, write the program that solves the problem.
|
```python
# # RED CODER # #
n, k = map(int, input().split())
x = list(map(str, input().split()))[:n]
count = 0
for i in range(n):
if len(x[i]) <= k:
count += 1
print(count)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw.
The first player wrote number *a*, the second player wrote number *b*. How many ways to throw a dice are there, at which the first player wins, or there is a draw, or the second player wins?
|
```python
num_1, num_2 = map(int, input().split())
num_3, num_4, num_5 = 0, 0, 0
for i in range(1, 6 + 1):
if abs(num_1 - i) < abs(num_2 - i):
num_3 += 1
elif abs(num_1 - i) == abs(num_2 - i):
num_4 += 1
elif abs(num_1 - i) > abs(num_2 - i):
num_5 += 1
print(num_3, num_4, num_5)
# Wed Mar 09 2022 07:02:36 GMT+0000 (Coordinated Universal Time)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Arkady wants to water his only flower. Unfortunately, he has a very poor watering system that was designed for $n$ flowers and so it looks like a pipe with $n$ holes. Arkady can only use the water that flows from the first hole.
Arkady can block some of the holes, and then pour $A$ liters of water into the pipe. After that, the water will flow out from the non-blocked holes proportionally to their sizes $s_1, s_2, \ldots, s_n$. In other words, if the sum of sizes of non-blocked holes is $S$, and the $i$-th hole is not blocked, $\frac{s_i \cdot A}{S}$ liters of water will flow out of it.
What is the minimum number of holes Arkady should block to make at least $B$ liters of water flow out of the first hole?
|
```python
nh,totl,finl=[int(i) for i in input().split()]
l=[int(i) for i in input().split()]
count=0
fl=0
newl=l[1:]
k=0
summ=l[0]+sum(newl)
newl=sorted(newl,reverse=True)
while(True):
ans=(totl*l[0])/summ
if(ans>=finl):
break
else:
summ=summ-newl[k]
count+=1
k+=1
print(count)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Jafar has *n* cans of cola. Each can is described by two integers: remaining volume of cola *a**i* and can's capacity *b**i* (*a**i* <=≤<= *b**i*).
Jafar has decided to pour all remaining cola into just 2 cans, determine if he can do this or not!
|
```python
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
x=sum(a)
y=max(b)
b.remove(y)
z=max(b)
if y+z<x:
print('NO')
else:
print('YES')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Bessie the cow and her best friend Elsie each received a sliding puzzle on Pi Day. Their puzzles consist of a 2<=×<=2 grid and three tiles labeled 'A', 'B', and 'C'. The three tiles sit on top of the grid, leaving one grid cell empty. To make a move, Bessie or Elsie can slide a tile adjacent to the empty cell into the empty cell as shown below:
In order to determine if they are truly Best Friends For Life (BFFLs), Bessie and Elsie would like to know if there exists a sequence of moves that takes their puzzles to the same configuration (moves can be performed in both puzzles). Two puzzles are considered to be in the same configuration if each tile is on top of the same grid cell in both puzzles. Since the tiles are labeled with letters, rotations and reflections are not allowed.
|
```python
s=input()
g=input()
w=input()
q=input()
if s[0]=='X':
S1=s[1]+g[1]+g[0]
elif s[1]=='X':
S1=g[1]+g[0]+s[0]
elif g[1]=='X':
S1=g[0]+s[0]+s[1]
else:
S1=s+g[1]
if w[0]=='X':
S2=w[1]+q[1]+q[0]
elif w[1]=='X':
S2=q[1]+q[0]+w[0]
elif q[1]=='X':
S2=q[0]+q[0]+w[1]
else:
S2=w+q[1]
if S1==S2 or S1[1:]+S1[0]==S2 or S1[2]+S1[:2]==S2:
print('YES')
else:
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
If you have ever interacted with a cat, you have probably noticed that they are quite particular about how to pet them. Here is an approximate map of a normal cat.
However, some cats won't tolerate this nonsense from the humans. Here is a map of a grumpy cat.
You have met a cat. Can you figure out whether it's normal or grumpy?
|
```python
import sys
t = True
s = ["great","don't think so", "don't touch me","not bad", "cool"]
for i in range(10):
print(i,flush=True)
sys.stdout.flush()
t = input()
if t in s:
print("normal",flush=True)
t = False
break
if t:
print("grumpy",flush=True)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
After finishing eating her bun, Alyona came up with two integers *n* and *m*. She decided to write down two columns of integers — the first column containing integers from 1 to *n* and the second containing integers from 1 to *m*. Now the girl wants to count how many pairs of integers she can choose, one from the first column and the other from the second column, such that their sum is divisible by 5.
Formally, Alyona wants to count the number of pairs of integers (*x*,<=*y*) such that 1<=≤<=*x*<=≤<=*n*, 1<=≤<=*y*<=≤<=*m* and equals 0.
As usual, Alyona has some troubles and asks you to help.
|
```python
f = int(input(""))
s = int(input(""))
total =0
first = f
second = s
for step in range(5,f+s+1,5):
first =1
while first <= f:
if step - first <= 0:
break
elif step - first <= s:
total +=1
first +=1
print (total)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Limak is a grizzly bear who desires power and adoration. He wants to win in upcoming elections and rule over the Bearland.
There are *n* candidates, including Limak. We know how many citizens are going to vote for each candidate. Now *i*-th candidate would get *a**i* votes. Limak is candidate number 1. To win in elections, he must get strictly more votes than any other candidate.
Victory is more important than everything else so Limak decided to cheat. He will steal votes from his opponents by bribing some citizens. To bribe a citizen, Limak must give him or her one candy - citizens are bears and bears like candies. Limak doesn't have many candies and wonders - how many citizens does he have to bribe?
|
```python
candidates = int(input())
votes = [int(x) for x in input().split(' ')]
k = votes[0]
maxi = max(votes)
changed = 0
while k <= maxi:
changed += 1
maxi -= 1
k += 1
print(changed)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One day, the Grasshopper was jumping on the lawn and found a piece of paper with a string. Grasshopper became interested what is the minimum jump ability he should have in order to be able to reach the far end of the string, jumping only on vowels of the English alphabet. Jump ability is the maximum possible length of his jump.
Formally, consider that at the begginning the Grasshopper is located directly in front of the leftmost character of the string. His goal is to reach the position right after the rightmost character of the string. In one jump the Grasshopper could jump to the right any distance from 1 to the value of his jump ability.
The following letters are vowels: 'A', 'E', 'I', 'O', 'U' and 'Y'.
|
```python
s=input()
Vowels = ['A','E','I','O','U','Y']
length = len(s)
pos=[-1]
pos_len=0
for i in range(length):
if s[i] in Vowels:
pos.append(i+1)
pos_len+=1
if (pos_len>1):
MinL=max(MinL,pos[pos_len]-pos[pos_len-1])
else :
MinL=i+1;
#print(MinL)
#print(pos)
#print(length,' ',pos[pos_len])
if (pos_len == 0):
print(length+1)
else:
MinL=max(MinL,length-pos[pos_len]+1)
print(MinL)
print(pos)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
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.
But yesterday, he came to see "her" in the real world and found out "she" is actually a very strong man! Our hero is very sad and he is too tired to love again now. So he came up with a way to recognize users' genders by their user names.
This is his method: if the number of distinct characters in one's user name is odd, then he is a male, otherwise she is a female. You are given the string that denotes the user name, please help our hero to determine the gender of this user by his method.
|
```python
nom = set(map(str,input()))
n = len(nom)
if(n%2==0):
print("CHAT WITH HER!")
else:
print("IGNORE HIM!")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Polycarp has interviewed Oleg and has written the interview down without punctuation marks and spaces to save time. Thus, the interview is now a string *s* consisting of *n* lowercase English letters.
There is a filler word ogo in Oleg's speech. All words that can be obtained from ogo by adding go several times to the end of it are also considered to be fillers. For example, the words ogo, ogogo, ogogogo are fillers, but the words go, og, ogog, ogogog and oggo are not fillers.
The fillers have maximal size, for example, for ogogoo speech we can't consider ogo a filler and goo as a normal phrase. We should consider ogogo as a filler here.
To print the interview, Polycarp has to replace each of the fillers with three asterisks. Note that a filler word is replaced with exactly three asterisks regardless of its length.
Polycarp has dealt with this problem in no time. Can you do the same? The clock is ticking!
|
```python
def main():
n = int(input())
a = input()
i = 0
while i <= n - 1:
if a[i] != 'o':
print(a[i], end = '')
i += 1
elif i < n - 2:
if a[i + 1] == 'g' and a[i + 2] == 'o':
i += 3
while i < n - 1:
if a[i] == 'g' and a[i + 1] == 'o':
i += 2
else:
print("***", end = '')
break
else:
print("***", end ='')
else:
print(a[i], end = '')
i += 1
main()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.
For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two primes". Let's modify it. How about a statement like that: "each integer no less than 12 can be expressed as the sum of two composite numbers." Not like the Goldbach's conjecture, I can prove this theorem.
You are given an integer *n* no less than 12, express it as a sum of two composite numbers.
|
```python
n = int(input())
def compite(x):
total = 0
for j in range(1,x+1):
if x % j == 0:
total += 1
if total > 2:
return x
break
else:
total = total
return total
total1 = []
if n % 2 == 0:
a = int(n / 2)
if compite(a) == a:
total1.append([a,a])
else:
a = int(n/2) + 1
while True:
if compite(a) == a:
b = n - a
if compite(b) == b:
total1.append([a,b])
break
else:
a += 1
else:
a += 1
else:
c = int(n/2) + 1
while True:
if compite(c) == c:
d = n - c
if compite(d) == d:
total1.append([c,d])
break
else:
c += 1
else:
c += 1
for i in total1:
print(*i)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One fine October day a mathematics teacher Vasily Petrov went to a class and saw there *n* pupils who sat at the desks, two people at each desk. Vasily quickly realized that number *n* is even. Like all true mathematicians, Vasily has all students numbered from 1 to *n*.
But Vasily Petrov did not like the way the children were seated at the desks. According to him, the students whose numbers differ by 1, can not sit together, as they talk to each other all the time, distract others and misbehave.
On the other hand, if a righthanded student sits at the left end of the desk and a lefthanded student sits at the right end of the desk, they hit elbows all the time and distract each other. In other cases, the students who sit at the same desk, do not interfere with each other.
Vasily knows very well which students are lefthanders and which ones are righthanders, and he asks you to come up with any order that meets these two uncomplicated conditions (students do not talk to each other and do not bump their elbows). It is guaranteed that the input is such that at least one way to seat the students always exists.
|
```python
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char st[110];
int i,l;
int main()
{
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
scanf("%d",&l);
scanf("%s",st+1);
for(i=1;i<=l/2;i++)
{
if(st[i]=='L')
{
printf("%d %d\n",i,i+l/2);
}
if(st[i]=='R')
{
printf("%d %d\n",i+l/2,i);
}
}
return 0;
}
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
According to an old legeng, a long time ago Ankh-Morpork residents did something wrong to miss Fortune, and she cursed them. She said that at some time *n* snacks of distinct sizes will fall on the city, and the residents should build a Snacktower of them by placing snacks one on another. Of course, big snacks should be at the bottom of the tower, while small snacks should be at the top.
Years passed, and once different snacks started to fall onto the city, and the residents began to build the Snacktower.
However, they faced some troubles. Each day exactly one snack fell onto the city, but their order was strange. So, at some days the residents weren't able to put the new stack on the top of the Snacktower: they had to wait until all the bigger snacks fell. Of course, in order to not to anger miss Fortune again, the residents placed each snack on the top of the tower immediately as they could do it.
Write a program that models the behavior of Ankh-Morpork residents.
|
```python
m=int(input())
list1=list(map(int,input().split(' ')))
list2=list()
list3=list1.copy()
for i in range(len(list1)):
_max=max(list3)
list2.append(list1[i])
list3.remove(list1[i])
if(list1[i]== _max):
list2.sort(reverse=True)
for x in list2:
print(f'{x} ',end=' ')
list2.clear()
continue
print('')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The only king stands on the standard chess board. You are given his position in format "cd", where *c* is the column from 'a' to 'h' and *d* is the row from '1' to '8'. Find the number of moves permitted for the king.
Check the king's moves here [https://en.wikipedia.org/wiki/King_(chess)](https://en.wikipedia.org/wiki/King_(chess)).
|
```python
pos_king= input()
col= pos_king[0]
fil= int(pos_king[1])
moves=0
if fil==8 or fil==1:
if col=="a" or col=="h":
moves=3
else:
moves=5
elif 1<fil<8:
if col=="a" or col=="h":
moves=5
else:
moves=8
print(moves)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The map of Berland is a rectangle of the size *n*<=×<=*m*, which consists of cells of size 1<=×<=1. Each cell is either land or water. The map is surrounded by the ocean.
Lakes are the maximal regions of water cells, connected by sides, which are not connected with the ocean. Formally, lake is a set of water cells, such that it's possible to get from any cell of the set to any other without leaving the set and moving only to cells adjacent by the side, none of them is located on the border of the rectangle, and it's impossible to add one more water cell to the set such that it will be connected with any other cell.
You task is to fill up with the earth the minimum number of water cells so that there will be exactly *k* lakes in Berland. Note that the initial number of lakes on the map is not less than *k*.
|
```python
n, m, k = map(int, input().split())
mp = [list(input().strip()) for _ in range(n)]
w = {(r,c) for r,row in enumerate(mp) for c,cell in enumerate(row) if cell=="."}
lakes = []
while w:
lake = set()
q = [w.pop()]
while q:
r,c = q.pop()
if (r,c) in lake:
continue
w.discard((r,c))
lake.add((r,c))
q.extend(rc for rc in [(r,c-1),(r,c+1),(r-1,c),(r+1,c)] if rc in w)
if all(1 <= r < n-1 and 1 <= c < m-1 for r,c in lake):
lakes.append(lake)
assert len(lakes) >= k
lakes = sorted((len(lake), lake) for lake in lakes)
w = {rc for _,lake in lakes[:len(lakes)-k] for rc in lake}
for r,c in w:
mp[r][c]="#"
print(len(w))
for row in mp:
print("".join(row))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are *n* members, numbered 1 through *n*. *m* pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
|
```python
def find(p):
if id[p] == p:
return p
else:
id[p] = find(id[p]);
return id[p]
def union(u,v):
u = find(u)
v = find(v)
if u == v:
return
if size[u] > size[v]:
u,v=v,u
id[u] = v
size[v] += size[u]
n,m = map(int,input().split())
visited = [False]*(n+1)
arestas = [0] * (n+1)
size= [1] * (n+1)
id = [i for i in range(n+1)]
for i in range(m):
u,v = map(int,input().split())
arestas[u] +=1
arestas[v] +=1
union(u,v)
ans = 'YES'
for i in range(1,n):
if arestas[i] != 0:
if arestas[i] != size[find(i)] -1:
ans = 'NO'
break
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Very soon there will be a parade of victory over alien invaders in Berland. Unfortunately, all soldiers died in the war and now the army consists of entirely new recruits, many of whom do not even know from which leg they should begin to march. The civilian population also poorly understands from which leg recruits begin to march, so it is only important how many soldiers march in step.
There will be *n* columns participating in the parade, the *i*-th column consists of *l**i* soldiers, who start to march from left leg, and *r**i* soldiers, who start to march from right leg.
The beauty of the parade is calculated by the following formula: if *L* is the total number of soldiers on the parade who start to march from the left leg, and *R* is the total number of soldiers on the parade who start to march from the right leg, so the beauty will equal |*L*<=-<=*R*|.
No more than once you can choose one column and tell all the soldiers in this column to switch starting leg, i.e. everyone in this columns who starts the march from left leg will now start it from right leg, and vice versa. Formally, you can pick no more than one index *i* and swap values *l**i* and *r**i*.
Find the index of the column, such that switching the starting leg for soldiers in it will maximize the the beauty of the parade, or determine, that no such operation can increase the current beauty.
|
```python
n=int(input())
a=[]
b=[]
for i in range(n):
l,r=map(int,input().split())
a.append((l,r))
b.append((l,r))
a.sort(key=lambda x:(x[0],x[1]))
s1=0
s2=0
s3=0
s4=0
for i in range(n):
s1=s1+a[i][0]
s2=s2+a[i][1]
y1=abs(s1-s2)
z1=a[n-1][0]
z2=a[n-1][1]
x=abs(a[n-1][0]-a[n-1][1])
for i in range(n-2,-1,-1):
if((a[i][0]>a[i][1])):
if(abs(a[i][0]-a[i][1])>x):
z1=a[i][0]
z2=a[i][1]
for i in range(n):
s3=s3+a[i][0]
s4=s4+a[i][1]
s3=s3-z1+z2
s4=s4-z2+z1
y2=abs(s3-s4)
if(y1>=y2):
print(0)
else:
for i in range(n):
if(b[i][0]==z1 and b[i][1]==z2):
print(i+1)
break
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Manao is trying to open a rather challenging lock. The lock has *n* buttons on it and to open it, you should press the buttons in a certain order to open the lock. When you push some button, it either stays pressed into the lock (that means that you've guessed correctly and pushed the button that goes next in the sequence), or all pressed buttons return to the initial position. When all buttons are pressed into the lock at once, the lock opens.
Consider an example with three buttons. Let's say that the opening sequence is: {2, 3, 1}. If you first press buttons 1 or 3, the buttons unpress immediately. If you first press button 2, it stays pressed. If you press 1 after 2, all buttons unpress. If you press 3 after 2, buttons 3 and 2 stay pressed. As soon as you've got two pressed buttons, you only need to press button 1 to open the lock.
Manao doesn't know the opening sequence. But he is really smart and he is going to act in the optimal way. Calculate the number of times he's got to push a button in order to open the lock in the worst-case scenario.
|
```python
n = int(input())
print(n*(n*n+5)//6)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You can find anything whatsoever in our Galaxy! A cubical planet goes round an icosahedral star. Let us introduce a system of axes so that the edges of the cubical planet are parallel to the coordinate axes and two opposite vertices lay in the points (0,<=0,<=0) and (1,<=1,<=1). Two flies live on the planet. At the moment they are sitting on two different vertices of the cubical planet. Your task is to determine whether they see each other or not. The flies see each other when the vertices they occupy lie on the same face of the cube.
|
```python
# LUOGU_RID: 128753035
a,b,c=map(int,input().split())
d,e,f=map(int,input().split())
if ((a==d) or (b==e) or (c==f)):
print('YES')
else:
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Tavak and Seyyed are good friends. Seyyed is very funny and he told Tavak to solve the following problem instead of longest-path.
You are given *l* and *r*. For all integers from *l* to *r*, inclusive, we wrote down all of their integer divisors except 1. Find the integer that we wrote down the maximum number of times.
Solve the problem to show that it's not a NP problem.
|
```python
from math import sqrt
nums = input()
esp = nums.find(' ')
n1 = int(nums[0:esp])
n2 = int(nums[esp+1:])
vzs = [0,0,0,0,0]
def incrementa(i):
if(i==2):
vzs[0]+=1
elif(i==3):
vzs[1]+=1
elif(i==5):
vzs[2]+=1
elif(i==7):
vzs[3]+=1
else:
vzs[4]+=1
def divisors(n):
raiz = int(sqrt(n))
for i in [2,3,5,7,11]:
if(n % i == 0):
incrementa(i)
if((raiz*raiz) == n):
incrementa(raiz)
for i in range(n1,n2+1):
divisors(i)
maior=0
for i in range(1,len(vzs)):
if(vzs[i]>vzs[maior]):
maior=i
print(maior+2)
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.