source
stringclasses 3
values | instruction
stringlengths 23
3.97k
| input
stringclasses 1
value | output
stringlengths 1
3.75k
|
---|---|---|---|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya often uses public transport. The transport in the city is of two types: trolleys and buses. The city has *n* buses and *m* trolleys, the buses are numbered by integers from 1 to *n*, the trolleys are numbered by integers from 1 to *m*.
Public transport is not free. There are 4 types of tickets:
1. A ticket for one ride on some bus or trolley. It costs *c*1 burles; 1. A ticket for an unlimited number of rides on some bus or on some trolley. It costs *c*2 burles; 1. A ticket for an unlimited number of rides on all buses or all trolleys. It costs *c*3 burles; 1. A ticket for an unlimited number of rides on all buses and trolleys. It costs *c*4 burles.
Vasya knows for sure the number of rides he is going to make and the transport he is going to use. He asked you for help to find the minimum sum of burles he will have to spend on the tickets.
|
```python
import sys;
c1, c2, c3, c4 = map(int, sys.stdin.readline().split(' '));
nbBuses, nbTrolleys = map(int, sys.stdin.readline().split(' '));
buses = map(int, sys.stdin.readline().split(' '));
trolleys = map(int, sys.stdin.readline().split(' '));
minBusesCost = 0;
for nbRide in buses:
minBusesCost += min(c2, nbRide * c1);
minTrolleysCost = 0;
for nbRide in trolleys:
minTrolleysCost += min(c2, nbRide * c1);
# print(c1, c2, c3, c4, minBusesCost, minTrolleysCost);
minCost = min(
c4,
min(
c3,
minBusesCost
) +
min(
c3,
minTrolleysCost
)
);
print(minCost);
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya has got two number: *a* and *b*. However, Vasya finds number *a* too short. So he decided to repeat the operation of lengthening number *a* *n* times.
One operation of lengthening a number means adding exactly one digit to the number (in the decimal notation) to the right provided that the resulting number is divisible by Vasya's number *b*. If it is impossible to obtain the number which is divisible by *b*, then the lengthening operation cannot be performed.
Your task is to help Vasya and print the number he can get after applying the lengthening operation to number *a* *n* times.
|
```python
a,b,c=map(int,input().split())
for i in range(9):
y=a*10+i
#print(y)
if (y%b)==0:
#print(y)
y=y*(10**(c-1))
print(y)
exit(0)
print(-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Lavrenty, a baker, is going to make several buns with stuffings and sell them.
Lavrenty has *n* grams of dough as well as *m* different stuffing types. The stuffing types are numerated from 1 to *m*. Lavrenty knows that he has *a**i* grams left of the *i*-th stuffing. It takes exactly *b**i* grams of stuffing *i* and *c**i* grams of dough to cook a bun with the *i*-th stuffing. Such bun can be sold for *d**i* tugriks.
Also he can make buns without stuffings. Each of such buns requires *c*0 grams of dough and it can be sold for *d*0 tugriks. So Lavrenty can cook any number of buns with different stuffings or without it unless he runs out of dough and the stuffings. Lavrenty throws away all excess material left after baking.
Find the maximum number of tugriks Lavrenty can earn.
|
```python
n, m, c, d = map(int, raw_input().split())
arr=[0] * 1001
for i in range(c, n+1):
arr[i] = arr[i-c] + d
for l in range(0, m):
a, b, c, d = map(int, raw_input().split())
for i in range(0, a/b):
j = n
while(j >= c):
arr[j] = max(arr[j], arr[j - c] + d)
j -= 1
print arr[n]
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The little girl loves the problems on array queries very much.
One day she came across a rather well-known problem: you've got an array of $n$ elements (the elements of the array are indexed starting from 1); also, there are $q$ queries, each one is defined by a pair of integers $l_i$, $r_i$ $(1 \le l_i \le r_i \le n)$. You need to find for each query the sum of elements of the array with indexes from $l_i$ to $r_i$, inclusive.
The little girl found the problem rather boring. She decided to reorder the array elements before replying to the queries in a way that makes the sum of query replies maximum possible. Your task is to find the value of this maximum sum.
|
```python
n,q=map(int,input().split())
a=sorted(map(int,input().split()))
b=[0]*n
for _ in[0]*q:
l,r=map(int,input().split())
b[l-1]+=1
if r<n:b[r]-=1
c=[b[0]]
for i in range(1,n):c+=c[-1]+b[i],
c=sorted(c)
print(sum(a[i]*c[i] for i in range(n)))
```
|
|
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
number=input()
res=[]
for i in number:
if 5<=int(i):
res.append(9-int(i))
else:
res.append(int(i))
if res[0]==0:
res[0]=9
print(''.join(list(map(str,res))))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Soon a school Olympiad in Informatics will be held in Berland, *n* schoolchildren will participate there.
At a meeting of the jury of the Olympiad it was decided that each of the *n* participants, depending on the results, will get a diploma of the first, second or third degree. Thus, each student will receive exactly one diploma.
They also decided that there must be given at least *min*1 and at most *max*1 diplomas of the first degree, at least *min*2 and at most *max*2 diplomas of the second degree, and at least *min*3 and at most *max*3 diplomas of the third degree.
After some discussion it was decided to choose from all the options of distributing diplomas satisfying these limitations the one that maximizes the number of participants who receive diplomas of the first degree. Of all these options they select the one which maximizes the number of the participants who receive diplomas of the second degree. If there are multiple of these options, they select the option that maximizes the number of diplomas of the third degree.
Choosing the best option of distributing certificates was entrusted to Ilya, one of the best programmers of Berland. However, he found more important things to do, so it is your task now to choose the best option of distributing of diplomas, based on the described limitations.
It is guaranteed that the described limitations are such that there is a way to choose such an option of distributing diplomas that all *n* participants of the Olympiad will receive a diploma of some degree.
|
```python
x = int(input())
f = [0, 0]
s = [0, 0]
t = [0, 0]
str = input().split(' ')
f[0] = int(str[0])
f[1] = int(str[1])
str = input().split(' ')
s[0] = int(str[0])
s[1] = int(str[1])
str = input().split(' ')
t[0] = int(str[0])
t[1] = int(str[1])
maxf = x - s[0] - t[0]
if(maxf > f[1]):
maxf = f[1]
maxs = x - maxf - t[0]
if(maxs > s[1]):
maxs = s[1]
maxt = x - maxs - maxf
print("{0} {1} {2}".format(maxf, maxs, maxt))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky digits in it is a lucky number. He wonders whether number *n* is a nearly lucky number.
|
```python
n = input()
lucky_digits = n.count('4') + n.count('7')
lucky_count = 0
for digit in str(lucky_digits):
if digit == '4' or digit == '7':
lucky_count += 1
if lucky_count == len(str(lucky_digits)):
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
DZY loves chessboard, and he enjoys playing with it.
He has a chessboard of *n* rows and *m* columns. Some cells of the chessboard are bad, others are good. For every good cell, DZY wants to put a chessman on it. Each chessman is either white or black. After putting all chessmen, DZY wants that no two chessmen with the same color are on two adjacent cells. Two cells are adjacent if and only if they share a common edge.
You task is to find any suitable placement of chessmen on the given chessboard.
|
```python
def sol(row, col, board, new_board = ""):
for i in range(row):
for j in range(col):
if board[i][j] == "-": new_board += "-"
elif (i + j) % 2 == 0: new_board += "B"
else: new_board += "W"
new_board += "\n"
return new_board
if __name__ == "__main__":
row, col = map(int, input().split())
board = [[x for x in input()] for _ in range(row)]
board = sol(row, col, board)
print (board)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.
Now he wonders what is an average value of sum of digits of the number *A* written in all bases from 2 to *A*<=-<=1.
Note that all computations should be done in base 10. You should find the result as an irreducible fraction, written in base 10.
|
```python
a, f = int(input()), 0
k = a - 2
for i in range(2, a):
s = 0
b = a
while True:
s = s * 10 + b%i
if b // i == 0:
break
b = b//i
f += sum([int(i) for i in str(s)])
r = 2
while True:
if f%r == 0 and k%r == 0:
f //= r
k //= r
r = 2
else:
r = r + 1
if r > k:
break
print(f, "/", k, sep="")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given an array of *n* elements, you must make it a co-prime array in as few moves as possible.
In each move you can insert any positive integral number you want not greater than 109 in any place in the array.
An array is co-prime if any two adjacent numbers of it are co-prime.
In the number theory, two integers *a* and *b* are said to be co-prime if the only positive integer that divides both of them is 1.
|
```python
from math import *
n=int(input())
a=list(map(int,input().split(" ")))
l=[]
l.append(a[0])
for i in range(1,n):
if(gcd(a[i],a[i-1])!=1):
l.append(1)
l.append(a[i])
print(len(l)-n)
print(*l)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a tetrahedron. Let's mark its vertices with letters *A*, *B*, *C* and *D* correspondingly.
An ant is standing in the vertex *D* of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place.
You do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertex *D* to itself in exactly *n* steps. In other words, you are asked to find out the number of different cyclic paths with the length of *n* from vertex *D* to itself. As the number can be quite large, you should print it modulo 1000000007 (109<=+<=7).
|
```python
#!/usr/bin/env python3
def pow(b,e):
if e == 1:
return b
if e%2 == 0:
result = pow(b,e//2)
result = result * result
return result
else:
result = pow(b,e//2)
result = result * result * b
return result
return result
n = int(input(""))
if n%2 == 0:
print(((pow(3,n)+3)//4)%1000000007)
else:
print(((pow(3,n)-3)//4)%1000000007)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One day Kefa found *n* baloons. For convenience, we denote color of *i*-th baloon as *s**i* — lowercase letter of the Latin alphabet. Also Kefa has *k* friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. Help Kefa to find out, can he give out all his baloons, such that no one of his friens will be upset — print «YES», if he can, and «NO», otherwise. Note, that Kefa's friend will not upset, if he doesn't get baloons at all.
|
```python
n, k = [int(x) for x in input().split()]
l = list(input())
s = list(set(l))
f = -1
for i in s:
count = 0
for j in l:
if i == j:
count -= -1
f = max(f, count)
if f > k: print("NO")
else: print("YES")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Let's consider a table consisting of *n* rows and *n* columns. The cell located at the intersection of *i*-th row and *j*-th column contains number *i*<=×<=*j*. The rows and columns are numbered starting from 1.
You are given a positive integer *x*. Your task is to count the number of cells in a table that contain number *x*.
|
```python
n, x = map(int, input().split())
cn = 0
if n >= x:
cn += 2
n = x // 2+1
if x == 1:
cn -= 1
for i in range(2, n):
if x % i == 0:
cn += 1
print(cn)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Alice and Bob love playing one-dimensional battle ships. They play on the field in the form of a line consisting of *n* square cells (that is, on a 1<=×<=*n* table).
At the beginning of the game Alice puts *k* ships on the field without telling their positions to Bob. Each ship looks as a 1<=×<=*a* rectangle (that is, it occupies a sequence of *a* consecutive squares of the field). The ships cannot intersect and even touch each other.
After that Bob makes a sequence of "shots". He names cells of the field and Alice either says that the cell is empty ("miss"), or that the cell belongs to some ship ("hit").
But here's the problem! Alice like to cheat. May be that is why she responds to each Bob's move with a "miss".
Help Bob catch Alice cheating — find Bob's first move, such that after it you can be sure that Alice cheated.
|
```python
from bisect import bisect_left
def solve(n, k, a, m, x):
pre = [0]*(n+2)
pos = [0]*(n+2)
d = [-1]*(n+2)
for i in range(1, n+1):
pre[i] = pre[i-1] + (i in x)
pos[i] = pos[i-1] + ((i%(a+1)==0) and (i+a <= n) and (i-1 not in x) and (i+a not in x))
l = 1
r = m
while l <= r:
mid = (l+r)//2
d[mid] = pre[n] - pre[mid] - (pos[n] - pos[mid])
if d[mid] < k:
l = mid + 1
else:
r = mid - 1
if l > m:
return -1
else:
return l
n, b, a = map(int, input().split())
m = int(input())
x = list(map(int, input().split()))
print(solve(n,b,a,m,x))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.
|
```python
n=int(input())
x,y,z=[],[],[]
for i in range(n):
s=list(map(int,input().split()))
x.append(s[0])
y.append(s[1])
z.append(s[2])
if sum(x)==0 and sum(y)==0 and sum(z)==0:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Sonya decided that having her own hotel business is the best way of earning money because she can profit and rest wherever she wants.
The country where Sonya lives is an endless line. There is a city in each integer coordinate on this line. She has $n$ hotels, where the $i$-th hotel is located in the city with coordinate $x_i$. Sonya is a smart girl, so she does not open two or more hotels in the same city.
Sonya understands that her business needs to be expanded by opening new hotels, so she decides to build one more. She wants to make the minimum distance from this hotel to all others to be equal to $d$. The girl understands that there are many possible locations to construct such a hotel. Thus she wants to know the number of possible coordinates of the cities where she can build a new hotel.
Because Sonya is lounging in a jacuzzi in one of her hotels, she is asking you to find the number of cities where she can build a new hotel so that the minimum distance from the original $n$ hotels to the new one is equal to $d$.
|
```python
n,l=map(int,input().split())
li=list(map(int,input().split()))
count=0
for i in range(1,n):
k= li[i]-li[i-1]
if k-(2*l)==0:
count+=1
if k-(2*l)>0:
count+=2
print(count+2)
```
|
|
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
string = str(input())
text = 'hello'
pointer = 0
for j in range(len(string)):
if string[j] == text[pointer]:
pointer += 1
if pointer == len(text):
break
if pointer == len(text):
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Winnie-the-Pooh likes honey very much! That is why he decided to visit his friends. Winnie has got three best friends: Rabbit, Owl and Eeyore, each of them lives in his own house. There are winding paths between each pair of houses. The length of a path between Rabbit's and Owl's houses is *a* meters, between Rabbit's and Eeyore's house is *b* meters, between Owl's and Eeyore's house is *c* meters.
For enjoying his life and singing merry songs Winnie-the-Pooh should have a meal *n* times a day. Now he is in the Rabbit's house and has a meal for the first time. Each time when in the friend's house where Winnie is now the supply of honey is about to end, Winnie leaves that house. If Winnie has not had a meal the required amount of times, he comes out from the house and goes to someone else of his two friends. For this he chooses one of two adjacent paths, arrives to the house on the other end and visits his friend. You may assume that when Winnie is eating in one of his friend's house, the supply of honey in other friend's houses recover (most probably, they go to the supply store).
Winnie-the-Pooh does not like physical activity. He wants to have a meal *n* times, traveling minimum possible distance. Help him to find this distance.
|
```python
n = int(input())
a = int(input())
b = int(input())
c = int(input())
m = min(a,b,c)
if m == a:
n -= 1
dist = 0
if n > 0:
dist += n*a
print(dist)
elif m == b:
n -= 1
dist = 0
if n > 0:
dist += n*b
print(dist)
else:
n -= 1
dist = 0
if n>0:
n -= 1
dist += min(a,b)
if n>0:
dist += n*c
print(dist)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Polycarpus has been working in the analytic department of the "F.R.A.U.D." company for as much as *n* days. Right now his task is to make a series of reports about the company's performance for the last *n* days. We know that the main information in a day report is value *a**i*, the company's profit on the *i*-th day. If *a**i* is negative, then the company suffered losses on the *i*-th day.
Polycarpus should sort the daily reports into folders. Each folder should include data on the company's performance for several consecutive days. Of course, the information on each of the *n* days should be exactly in one folder. Thus, Polycarpus puts information on the first few days in the first folder. The information on the several following days goes to the second folder, and so on.
It is known that the boss reads one daily report folder per day. If one folder has three or more reports for the days in which the company suffered losses (*a**i*<=<<=0), he loses his temper and his wrath is terrible.
Therefore, Polycarpus wants to prepare the folders so that none of them contains information on three or more days with the loss, and the number of folders is minimal.
Write a program that, given sequence *a**i*, will print the minimum number of folders.
|
```python
n=int(input())
a=list(map(int,input().split()))
po=0
ne=0
no=0
l=[]
for i in range(n):
if(a[i]<0):
ne=ne+1
if(a[i]>=0):
po=po+1
if(ne==2):
l.append(po+ne)
po=0
ne=0
if(len(l)>0):
if(po>0 and ne==0 ):
l[-1]=l[-1]+po
if(ne>0 and po>0):
l.append(ne+po)
if(ne>0 and po==0):
l.append(ne)
else:
l.append(po+ne)
print(len(l))
print(*l)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Patrick has just finished writing a message to his sweetheart Stacey when he noticed that the message didn't look fancy. Patrick was nervous while writing the message, so some of the letters there were lowercase and some of them were uppercase.
Patrick believes that a message is fancy if any uppercase letter stands to the left of any lowercase one. In other words, this rule describes the strings where first go zero or more uppercase letters, and then — zero or more lowercase letters.
To make the message fancy, Patrick can erase some letter and add the same letter in the same place in the opposite case (that is, he can replace an uppercase letter with the lowercase one and vice versa). Patrick got interested in the following question: what minimum number of actions do we need to make a message fancy? Changing a letter's case in the message counts as one action. Patrick cannot perform any other actions.
|
```python
s = input()
n = len(s)
sml = list(map(lambda i: int('a' <= i <= 'z'), s))
cap = list(map(lambda i: int('A' <= i <= 'Z'), s))
prefsml = [0] * (n+1)
for i in range(n):
prefsml[i+1] = prefsml[i] + sml[i]
suffcap = [0] * (n+1)
for i in range(n-1, -1, -1):
suffcap[i] = suffcap[i+1] + cap[i]
res = 2e9
for i in range(n):
res = min(res, prefsml[i+1] + suffcap[i])
print(res - 1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Recently, a chaotic virus Hexadecimal advanced a new theorem which will shake the Universe. She thinks that each Fibonacci number can be represented as sum of three not necessary different Fibonacci numbers.
Let's remember how Fibonacci numbers can be calculated. *F*0<==<=0, *F*1<==<=1, and all the next numbers are *F**i*<==<=*F**i*<=-<=2<=+<=*F**i*<=-<=1.
So, Fibonacci numbers make a sequence of numbers: 0, 1, 1, 2, 3, 5, 8, 13, ...
If you haven't run away from the PC in fear, you have to help the virus. Your task is to divide given Fibonacci number *n* by three not necessary different Fibonacci numbers or say that it is impossible.
|
```python
n = int(input())
a=0
b=1
fibs = [a,b]
while(b<n):
newfib = a+b;
a = b
b = newfib
fibs.append(b)
test = fibs[-1-1] + fibs[-1-3] + fibs[-1-4]
if(len(fibs) == 0):
print("0 0 0 ")
exit()
elif(len(fibs) == 1):
print("0 0 1")
exit()
if n==test:
print("{} {} {}".format(fibs[-1-1], fibs[-1-3], fibs[-1-4]))
else:
print("I'm too stupid to solve this problem")
```
|
|
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
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 10 10:22:48 2023
@author: koray
"""
for word in input():
if len(word) > 10:
print(word[0] + str(len(word) - 2) + word[-1])
else:
print(word)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their average. Of course, with the usual sizes of data, it's nothing challenging — but why not make a similar programming contest problem while we're at it?
You're given a sequence of *n* data points *a*1,<=...,<=*a**n*. There aren't any big jumps between consecutive data points — for each 1<=≤<=*i*<=<<=*n*, it's guaranteed that |*a**i*<=+<=1<=-<=*a**i*|<=≤<=1.
A range [*l*,<=*r*] of data points is said to be almost constant if the difference between the largest and the smallest value in that range is at most 1. Formally, let *M* be the maximum and *m* the minimum value of *a**i* for *l*<=≤<=*i*<=≤<=*r*; the range [*l*,<=*r*] is almost constant if *M*<=-<=*m*<=≤<=1.
Find the length of the longest almost constant range.
|
```python
INT_MAX = float('inf')
def main():
n = int(input())
a = [int(i) for i in input().split()]
mx = -INT_MAX
l = 0
r = 1
while l < n:
while r < n:
if max(a[l:r + 1]) - min(a[l:r + 1]) <= 1:
mx = max(mx, r - l + 1)
r += 1
else:
break
l += 1
print(mx)
if __name__ == '__main__':
main()
```
|
|
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
n=int(input())
a=0
y1=0
for i in range(n):
x,y=[int(i) for i in input().split()]
if x<0:
a+=1
else:
y1+=1
if a<=1 or y1<=1:
print('YES')
else:
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The farmer Polycarp has a warehouse with hay, which can be represented as an *n*<=×<=*m* rectangular table, where *n* is the number of rows, and *m* is the number of columns in the table. Each cell of the table contains a haystack. The height in meters of the hay located in the *i*-th row and the *j*-th column is equal to an integer *a**i*,<=*j* and coincides with the number of cubic meters of hay in the haystack, because all cells have the size of the base 1<=×<=1. Polycarp has decided to tidy up in the warehouse by removing an arbitrary integer amount of cubic meters of hay from the top of each stack. You can take different amounts of hay from different haystacks. Besides, it is allowed not to touch a stack at all, or, on the contrary, to remove it completely. If a stack is completely removed, the corresponding cell becomes empty and no longer contains the stack.
Polycarp wants the following requirements to hold after the reorganization:
- the total amount of hay remaining in the warehouse must be equal to *k*, - the heights of all stacks (i.e., cells containing a non-zero amount of hay) should be the same, - the height of at least one stack must remain the same as it was, - for the stability of the remaining structure all the stacks should form one connected region.
The two stacks are considered adjacent if they share a side in the table. The area is called connected if from any of the stack in the area you can get to any other stack in this area, moving only to adjacent stacks. In this case two adjacent stacks necessarily belong to the same area.
Help Polycarp complete this challenging task or inform that it is impossible.
|
```python
print("_RANDOM_GUESS_1689592554.5392647")# 1689592554.539285
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
wHAT DO WE NEED cAPS LOCK FOR?
Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage.
Let's consider that a word has been typed with the Caps lock key accidentally switched on, if:
- either it only contains uppercase letters; - or all letters except for the first one are uppercase.
In this case we should automatically change the case of all letters. For example, the case of the letters that form words "hELLO", "HTTP", "z" should be changed.
Write a program that applies the rule mentioned above. If the rule cannot be applied, the program should leave the word unchanged.
|
```python
s = str(input())
uppercase_test = 0
uppercase_except_1 = 0
for i in range(len(s)):
if ord(s[i])>=65 and ord(s[i])<=90:
uppercase_test += 1
for i in range(1,len(s)):
if ord(s[i])>=65 and ord(s[i])<=90:
uppercase_except_1 += 1
if uppercase_except_1 == len(s)-1:
print(str(s[0]).upper()+str(s[1:]).lower())
elif uppercase_test == len(s):
print(str(s[0]).upper()+str(s[1:]).lower())
else:
print(s)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Linear Kingdom has exactly one tram line. It has *n* stops, numbered from 1 to *n* in the order of tram's movement. At the *i*-th stop *a**i* passengers exit the tram, while *b**i* passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it becomes empty.
Your task is to calculate the tram's minimum capacity such that the number of people inside the tram at any time never exceeds this capacity. Note that at each stop all exiting passengers exit before any entering passenger enters the tram.
|
```python
stations = int(input())
exist =0
privious_exist=0
for _ in range(stations):
privious_exist = exist
exit,enter = map(int,input().split(" "))
if _ == stations :
enter =0
exist = privious_exist + (enter - exit)
print(exist)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Tom is interested in power consumption of his favourite laptop. His laptop has three modes. In normal mode laptop consumes *P*1 watt per minute. *T*1 minutes after Tom moved the mouse or touched the keyboard for the last time, a screensaver starts and power consumption changes to *P*2 watt per minute. Finally, after *T*2 minutes from the start of the screensaver, laptop switches to the "sleep" mode and consumes *P*3 watt per minute. If Tom moves the mouse or touches the keyboard when the laptop is in the second or in the third mode, it switches to the first (normal) mode. Tom's work with the laptop can be divided into *n* time periods [*l*1,<=*r*1],<=[*l*2,<=*r*2],<=...,<=[*l**n*,<=*r**n*]. During each interval Tom continuously moves the mouse and presses buttons on the keyboard. Between the periods Tom stays away from the laptop. Find out the total amount of power consumed by the laptop during the period [*l*1,<=*r**n*].
|
```python
n, p1, p2, p3, t1, t2 = list(map(int, input().split(" ")))
l = []
for _ in range(n):
l += list(map(int, input().split(" ")))
p = 0
for i in range(len(l) // 2 - 1):
x = l[2 * i + 2] - l[2 * i + 1]
p += p1 * min(t1, x) + p2 * min(t2, max(0, x - t1)) + p3 * max(0, x - t1 - t2)
for i in range(len(l) // 2):
x = l[2 * i + 1] - l[2 * i]
p += p1 * x
print(p)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
As a result of Pinky and Brain's mysterious experiments in the Large Hadron Collider some portals or black holes opened to the parallel dimension. And the World Evil has crept to the veil between their world and ours. Brain quickly evaluated the situation and he understood that the more evil tentacles creep out and become free, the higher is the possibility that Brain will rule the world.
The collider's constriction is a rectangular grid rolled into a cylinder and consisting of *n* rows and *m* columns such as is shown in the picture below:
In this example *n*<==<=4, *m*<==<=5. Dotted lines are corridores that close each column to a ring, i. e. connect the *n*-th and the 1-th rows of the grid.
In the leftmost column of the grid the portals are situated and the tentacles of the World Evil are ready to creep out from there. In the rightmost column the exit doors are located. The tentacles can only get out through those doors. The segments joining the nodes of the grid are corridors.
Brain would be glad to let all the tentacles out but he faces a problem: the infinite number of tentacles can creep out of the portals, every tentacle possesses infinite length and some width and the volume of the corridors are, unfortunately, quite limited. Brain could approximately evaluate the maximal number of tentacles that will be able to crawl through every corridor.
Now help the mice to determine the maximal number of tentacles of the World Evil that will crawl out of the Large Hadron Collider.
|
```python
print("_RANDOM_GUESS_1689416376.18644")# 1689416376.1864593
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A social network for dogs called DH (DogHouse) has *k* special servers to recompress uploaded videos of cute cats. After each video is uploaded, it should be recompressed on one (any) of the servers, and only after that it can be saved in the social network.
We know that each server takes one second to recompress a one minute fragment. Thus, any server takes *m* seconds to recompress a *m* minute video.
We know the time when each of the *n* videos were uploaded to the network (in seconds starting from the moment all servers started working). All videos appear at different moments of time and they are recompressed in the order they appear. If some video appeared at time *s*, then its recompressing can start at that very moment, immediately. Some videos can await recompressing when all the servers are busy. In this case, as soon as a server is available, it immediately starts recompressing another video. The videos that await recompressing go in a queue. If by the moment the videos started being recompressed some servers are available, then any of them starts recompressing the video.
For each video find the moment it stops being recompressed.
|
```python
n, k = (int(p) for p in input().split())
InputVideo = []
DownLoad = []
OutputVideo = []
for o in range(n):
I, D = (int(v) for v in input().split())
InputVideo.append(I)
DownLoad.append(D)
i = 0
for j in range(k):
OutputVideo.append(InputVideo[i] + DownLoad[i])
i += 1
if i == n:
break
bzzz=len(OutputVideo)-k
while(i != n):
flag = 0
for l in range(bzzz,k):
if (InputVideo[i] >= OutputVideo[l]):
OutputVideo.append(InputVideo[i] + DownLoad[i])
flag = 1
break
if (flag == 0):
OutputVideo.append(min(OutputVideo[len(OutputVideo)-k:]) + DownLoad[i])
i += 1
for elem in OutputVideo:
print(elem)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Two players play a game.
Initially there are $n$ integers $a_1, a_2, \ldots, a_n$ written on the board. Each turn a player selects one number and erases it from the board. This continues until there is only one number left on the board, i. e. $n - 1$ turns are made. The first player makes the first move, then players alternate turns.
The first player wants to minimize the last number that would be left on the board, while the second player wants to maximize it.
You want to know what number will be left on the board after $n - 1$ turns if both players make optimal moves.
|
```python
n = int(input())
a = list(map(int, input().split()))
a.sort()
for i in range(n - 1):
if i % 2 == 0:
del a[-1]
elif i % 2 == 1:
del a[0]
print(a[0])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
This problem differs from one which was on the online contest.
The sequence *a*1,<=*a*2,<=...,<=*a**n* is called increasing, if *a**i*<=<<=*a**i*<=+<=1 for *i*<=<<=*n*.
The sequence *s*1,<=*s*2,<=...,<=*s**k* is called the subsequence of the sequence *a*1,<=*a*2,<=...,<=*a**n*, if there exist such a set of indexes 1<=≤<=*i*1<=<<=*i*2<=<<=...<=<<=*i**k*<=≤<=*n* that *a**i**j*<==<=*s**j*. In other words, the sequence *s* can be derived from the sequence *a* by crossing out some elements.
You are given two sequences of integer numbers. You are to find their longest common increasing subsequence, i.e. an increasing sequence of maximum length that is the subsequence of both sequences.
|
```python
n = int(input())
A = list(map(int, input().split()))
m = int(input())
B = list(map(int, input().split()))
F = [[0 for j in range(m)] for i in range(n)]
P = [0 for j in range(m)]
for i in range(n):
s = -1
t = 0
for j in range(m):
F[i][j] = F[i-1][j]
if A[i] > B[j] and F[i-1][j] > t:
s = j
t = F[i-1][j]
elif A[i] == B[j] and F[i-1][j] < t+1:
F[i][j] = t + 1
P[j] = s
R = []
l = 0
for j in range(m):
if F[n-1][l] < F[n-1][j]:
l = j
while l != -1:
R.append(B[l])
l = P[l]
print(len(R))
print(*R[::-1])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The Little Elephant has an integer *a*, written in the binary notation. He wants to write this number on a piece of paper.
To make sure that the number *a* fits on the piece of paper, the Little Elephant ought to delete exactly one any digit from number *a* in the binary record. At that a new number appears. It consists of the remaining binary digits, written in the corresponding order (possible, with leading zeroes).
The Little Elephant wants the number he is going to write on the paper to be as large as possible. Help him find the maximum number that he can obtain after deleting exactly one binary digit and print it in the binary notation.
|
```python
a = input()
for i in range(len(a)):
if a[i] == "0":
print(a[:i] + a[i + 1:])
quit()
print(a[:len(a) - 1])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
After the fourth season Sherlock and Moriary have realized the whole foolishness of the battle between them and decided to continue their competitions in peaceful game of Credit Cards.
Rules of this game are simple: each player bring his favourite *n*-digit credit card. Then both players name the digits written on their cards one by one. If two digits are not equal, then the player, whose digit is smaller gets a flick (knock in the forehead usually made with a forefinger) from the other player. For example, if *n*<==<=3, Sherlock's card is 123 and Moriarty's card has number 321, first Sherlock names 1 and Moriarty names 3 so Sherlock gets a flick. Then they both digit 2 so no one gets a flick. Finally, Sherlock names 3, while Moriarty names 1 and gets a flick.
Of course, Sherlock will play honestly naming digits one by one in the order they are given, while Moriary, as a true villain, plans to cheat. He is going to name his digits in some other order (however, he is not going to change the overall number of occurences of each digit). For example, in case above Moriarty could name 1, 2, 3 and get no flicks at all, or he can name 2, 3 and 1 to give Sherlock two flicks.
Your goal is to find out the minimum possible number of flicks Moriarty will get (no one likes flicks) and the maximum possible number of flicks Sherlock can get from Moriarty. Note, that these two goals are different and the optimal result may be obtained by using different strategies.
|
```python
import bisect
n = int(input())
s = list(input())
t = list(input())
s1 = ''
t1 = ''
for i in range(len(s)):
s1+=s[i]
t1+=t[i]
for i in range(len(s)):
s[i] = int(s[i])
t[i] = int(t[i])
s = sorted(s)
t = sorted(t)
s1 = sorted(s1)
t1 = sorted(t1)
win = 0
i = 0
while i<len(s):
j = 0
while(j<len(t)):
if t[j]>s[i]:
win+=1
del t[j]
break
else:
j+=1
i+=1
mark = 0
for i in range(len(t1)):
k = bisect.bisect_right(s1,t1[i])
if k-1>=0:
if t1[i] >= s1[k-1]:
mark+=1
del s1[k-1]
print(len(s1))
print(win)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A well-known art union called "Kalevich is Alive!" manufactures objects d'art (pictures). The union consists of *n* painters who decided to organize their work as follows.
Each painter uses only the color that was assigned to him. The colors are distinct for all painters. Let's assume that the first painter uses color 1, the second one uses color 2, and so on. Each picture will contain all these *n* colors. Adding the *j*-th color to the *i*-th picture takes the *j*-th painter *t**ij* units of time.
Order is important everywhere, so the painters' work is ordered by the following rules:
- Each picture is first painted by the first painter, then by the second one, and so on. That is, after the *j*-th painter finishes working on the picture, it must go to the (*j*<=+<=1)-th painter (if *j*<=<<=*n*); - each painter works on the pictures in some order: first, he paints the first picture, then he paints the second picture and so on; - each painter can simultaneously work on at most one picture. However, the painters don't need any time to have a rest; - as soon as the *j*-th painter finishes his part of working on the picture, the picture immediately becomes available to the next painter.
Given that the painters start working at time 0, find for each picture the time when it is ready for sale.
|
```python
m,n=map(int,input().split())
f=[[0 for i in range(0,n)] for j in range(0,m)]
for i in range(0,m):
a=list( map(int,input().split()) )
for j in range(0,n):
if i>0:
f[i][j]=max(f[i-1][j], f[i][j])
if j>0:
f[i][j]=max(f[i][j-1], f[i][j])
f[i][j]+=a[j]
print(f[i][n-1])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Alice got an array of length $n$ as a birthday present once again! This is the third year in a row!
And what is more disappointing, it is overwhelmengly boring, filled entirely with zeros. Bob decided to apply some changes to the array to cheer up Alice.
Bob has chosen $m$ changes of the following form. For some integer numbers $x$ and $d$, he chooses an arbitrary position $i$ ($1 \le i \le n$) and for every $j \in [1, n]$ adds $x + d \cdot dist(i, j)$ to the value of the $j$-th cell. $dist(i, j)$ is the distance between positions $i$ and $j$ (i.e. $dist(i, j) = |i - j|$, where $|x|$ is an absolute value of $x$).
For example, if Alice currently has an array $[2, 1, 2, 2]$ and Bob chooses position $3$ for $x = -1$ and $d = 2$ then the array will become $[2 - 1 + 2 \cdot 2,~1 - 1 + 2 \cdot 1,~2 - 1 + 2 \cdot 0,~2 - 1 + 2 \cdot 1]$ = $[5, 2, 1, 3]$. Note that Bob can't choose position $i$ outside of the array (that is, smaller than $1$ or greater than $n$).
Alice will be the happiest when the elements of the array are as big as possible. Bob claimed that the arithmetic mean value of the elements will work fine as a metric.
What is the maximum arithmetic mean value Bob can achieve?
|
```python
n, m = map(int, input().split())
x = y = z = 0
while m != 0:
m -= 1
a, b = map(int, input().split())
x += a
if b > 0:
y += b
else:
z += b
##print(x, y, z)
ans = (n * (n - 1) // 2) * y
if n & 1:
ans += ((n // 2) * ((n // 2) - 1) // 2) * z
else:
ans += ((((n - 1) // 2) * (((n - 1) // 2) - 1) // 2) + (n // 2)) * z
ans += x * n
print(ans / n)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given *n* integers *a*1,<=*a*2,<=...,<=*a**n*. Find the number of pairs of indexes *i*,<=*j* (*i*<=<<=*j*) that *a**i*<=+<=*a**j* is a power of 2 (i. e. some integer *x* exists so that *a**i*<=+<=*a**j*<==<=2*x*).
|
```python
from math import log2
n = int(input())
lista = [*map(int, input().split())]
a = 0
for _ in lista:
num = log2(_)
if num.is_integer() == True:
a += 1
print(a)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given two integers *n* and *k*. Find *k*-th smallest divisor of *n*, or report that it doesn't exist.
Divisor of *n* is any such natural number, that *n* can be divided by it without remainder.
|
```python
from math import sqrt
def kthDivisor(n, k):
p=int(sqrt(n))
alist=[]
for i in range(1,p+1,1):
if (n%i==0):
alist.append(i)
if (i !=p):
alist.append(int(n/i))
alist.sort()
print(alist)
if k >len(alist):
print(-1)
else:
return alist[k-1]
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a following process.
There is a platform with $n$ columns. $1 \times 1$ squares are appearing one after another in some columns on this platform. If there are no squares in the column, a square will occupy the bottom row. Otherwise a square will appear at the top of the highest square of this column.
When all of the $n$ columns have at least one square in them, the bottom row is being removed. You will receive $1$ point for this, and all the squares left will fall down one row.
You task is to calculate the amount of points you will receive.
|
```python
if __name__ == '__main__':
n, m = input().split()
n = int(n)
m = int(m)
squares = input().split(" ")
cont = [0] * n
for i in squares:
cont[int(i) - 1] += 1
print(min(cont))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Kefa decided to make some money doing business on the Internet for exactly *n* days. He knows that on the *i*-th day (1<=≤<=*i*<=≤<=*n*) he makes *a**i* money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence *a**i*. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.
Help Kefa cope with this task!
|
```python
dias = int(input())
dinero = list(map(int,input().split()))
canti_num_ord = 1
j = 1
for i in range(1,dias):
if dinero[i] >= dinero[i-1]:
j += 1
else:
canti_num_ord = j
j = 1
print(max(canti_num_ord,j))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Every year, hundreds of people come to summer camps, they learn new algorithms and solve hard problems.
This is your first year at summer camp, and you are asked to solve the following problem. All integers starting with 1 are written in one line. The prefix of these line is "123456789101112131415...". Your task is to print the *n*-th digit of this string (digits are numbered starting with 1.
|
```python
n = int(input())
if n < 10:
print(n)
elif n < 90 * 2 + 9:
x = (n - 10) // 2 + 10
if n % 2:
print(x % 10)
else:
print(x // 10)
elif n < 900 * 3 + 90 * 2 + 9:
x = (n - 10 - 90 * 2) // 3 + 100
print(x)
if (n - 10 - 90 * 2) % 3 == 1:
print(x % 10)
elif (n - 10 - 90 * 2) % 3 == 2:
print(x // 10 % 10)
else:
print(x // 100)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Tavas is a cheerleader in the new sports competition named "Pashmaks".
This competition consists of two part: swimming and then running. People will immediately start running *R* meters after they finished swimming exactly *S* meters. A winner is a such person that nobody else finishes running before him/her (there may be more than one winner).
Before the match starts, Tavas knows that there are *n* competitors registered for the match. Also, he knows that *i*-th person's swimming speed is *s**i* meters per second and his/her running speed is *r**i* meters per second. Unfortunately, he doesn't know the values of *R* and *S*, but he knows that they are real numbers greater than 0.
As a cheerleader, Tavas wants to know who to cheer up. So, he wants to know all people that might win. We consider a competitor might win if and only if there are some values of *R* and *S* such that with these values, (s)he will be a winner.
Tavas isn't really familiar with programming, so he asked you to help him.
|
```python
print("_RANDOM_GUESS_1689183198.028277")# 1689183198.0283232
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Zxr960115 is owner of a large farm. He feeds *m* cute cats and employs *p* feeders. There's a straight road across the farm and *n* hills along the road, numbered from 1 to *n* from left to right. The distance between hill *i* and (*i*<=-<=1) is *d**i* meters. The feeders live in hill 1.
One day, the cats went out to play. Cat *i* went on a trip to hill *h**i*, finished its trip at time *t**i*, and then waited at hill *h**i* for a feeder. The feeders must take all the cats. Each feeder goes straightly from hill 1 to *n* without waiting at a hill and takes all the waiting cats at each hill away. Feeders walk at a speed of 1 meter per unit time and are strong enough to take as many cats as they want.
For example, suppose we have two hills (*d*2<==<=1) and one cat that finished its trip at time 3 at hill 2 (*h*1<==<=2). Then if the feeder leaves hill 1 at time 2 or at time 3, he can take this cat, but if he leaves hill 1 at time 1 he can't take it. If the feeder leaves hill 1 at time 2, the cat waits him for 0 time units, if the feeder leaves hill 1 at time 3, the cat waits him for 1 time units.
Your task is to schedule the time leaving from hill 1 for each feeder so that the sum of the waiting time of all cats is minimized.
|
```python
print("_RANDOM_GUESS_1693418570.8905473")# 1693418570.8905644
```
|
|
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
n=input()
upp=0
for i in n:
if i.isupper():
upp+=1
if upp>len(n)/2:
n=n.upper()
else:
n=n.lower()
print(n)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings *a* and *b* of equal length are called equivalent in one of the two cases:
1. They are equal. 1. If we split string *a* into two halves of the same size *a*1 and *a*2, and string *b* into two halves of the same size *b*1 and *b*2, then one of the following is correct: *a*1 is equivalent to *b*1, and *a*2 is equivalent to *b*2 1. *a*1 is equivalent to *b*2, and *a*2 is equivalent to *b*1
As a home task, the teacher gave two strings to his students and asked to determine if they are equivalent.
Gerald has already completed this home task. Now it's your turn!
|
```python
try:
import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
# from math import *
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect, insort
from time import perf_counter
from fractions import Fraction
import copy
from copy import deepcopy
import time
starttime = time.time()
mod = int(pow(10, 9) + 7)
mod2 = 998244353
def data(): return sys.stdin.readline().strip()
def out(*var, end="\n"): sys.stdout.write(' '.join(map(str, var))+end)
def L(): return list(sp())
def sl(): return list(ssp())
def sp(): return map(int, data().split())
def ssp(): return map(str, data().split())
def l1d(n, val=0): return [val for i in range(n)]
def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)]
def A2(n,m): return [[0]*m for i in range(n)]
def A(n):return [0]*n
# sys.setrecursionlimit(int(pow(10,6)))
# from sys import stdin
# input = stdin.buffer.readline
# I = lambda : list(map(int,input().split()))
# import sys
# input=sys.stdin.readline
import math
import string
sys.stdin = open("input.txt", "r")
sys.stdout = open("output.txt", "w")
except:
pass
def compute_hash( s ):
"""
This will work work string consisting of only lower characters
If you want to do it for
- only upper characters: change ord("a") to ord("A")
- both lower and upper: change p to 53
"""
p = 31
mod = 10**9 + 7
hash_value = 0
p_pow = 1
H = [0]
for c in s:
hash_value = ( hash_value + ( ord(c) - ord("a") + 1) * p_pow ) % mod
p_pow = ( p_pow * p ) % mod
H.append(hash_value)
return H
a = input()
b = input()
Ha = compute_hash(a)
Hb = compute_hash(b)
n = len(a)
def rec(al,ar,bl,br):
if ar-al!=br-bl:
return False
hash_a = ((Ha[ar] - Ha[al-1])*pow(pow(31,al-1,mod),mod-2,mod))%mod
hash_b = ((Hb[br] - Hb[bl-1])*pow(pow(31,bl-1,mod),mod-2,mod))%mod
if hash_a == hash_b:
return True
if (ar-al+1)%2:
return False
mid = (ar-al+1)//2
ans = ( rec(al,al+mid-1,bl,bl+mid-1) & rec(al+mid,ar,bl+mid,br) ) | ( rec(al,al+mid-1,bl+mid,br) & rec(al+mid,ar,bl,bl+mid-1) )
# print(al, ar, bl, br, ans, hash_a, hash_b)
return ans
if rec(1,n,1,n):
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Sonya decided to organize an exhibition of flowers. Since the girl likes only roses and lilies, she decided that only these two kinds of flowers should be in this exhibition.
There are $n$ flowers in a row in the exhibition. Sonya can put either a rose or a lily in the $i$-th position. Thus each of $n$ positions should contain exactly one flower: a rose or a lily.
She knows that exactly $m$ people will visit this exhibition. The $i$-th visitor will visit all flowers from $l_i$ to $r_i$ inclusive. The girl knows that each segment has its own beauty that is equal to the product of the number of roses and the number of lilies.
Sonya wants her exhibition to be liked by a lot of people. That is why she wants to put the flowers in such way that the sum of beauties of all segments would be maximum possible.
|
```python
td=list(map(int,input().split()))
t=td[0]
d=td[1]
l=[]
for i in range(1,t+1):
if(i%2==0):
l.append("1")
else:
l.append("0")
for i in l:
print(i,end='')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
After the lessons *n* groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the *i*-th group consists of *s**i* friends (1<=≤<=*s**i*<=≤<=4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)?
|
```python
def min_number_of_taxis(n, groups):
count = [0] * 5
for group in groups:
count[group] += 1
taxis = count[4]
taxis += count[3]
count[1] = max(0, count[1] - count[3])
taxis += count[2] // 2
count[2] %= 2
if count[2] == 1:
taxis += 1
count[1] = max(0, count[1] - 2)
taxis += (count[1] + 3) // 4
return taxis
n = int(input())
groups = list(map(int, input().split()))
result = min_number_of_taxis(n, groups)
print(result)
```
|
|
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
def fib(limit):
a=[1,2]
while a[-1]<=limit:
a.append(a[-1]+a[-2])
return a
n=int(input())
lst=fib(n)
s=""
pos=0
for i in range(1,n+1):
if lst[pos]==i:
pos+=1
s+="O"
else:
s+="o"
print(s)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Consider the function *p*(*x*), where *x* is an array of *m* integers, which returns an array *y* consisting of *m*<=+<=1 integers such that *y**i* is equal to the sum of first *i* elements of array *x* (0<=≤<=*i*<=≤<=*m*).
You have an infinite sequence of arrays *A*0,<=*A*1,<=*A*2..., where *A*0 is given in the input, and for each *i*<=≥<=1 *A**i*<==<=*p*(*A**i*<=-<=1). Also you have a positive integer *k*. You have to find minimum possible *i* such that *A**i* contains a number which is larger or equal than *k*.
|
```python
n, k = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
cnt, ind, mx = 0, [], 0
for i in range(n):
if a[i] > 0:
cnt += 1
ind.append(i)
mx = max(mx, a[i])
def p(a):
pref = [0]
for i in range(len(a)):
pref.append(pref[-1] + a[i])
return pref
if cnt > 7 or mx >= k:
it = 0
while True:
mx = 0
for i in range(len(a)):
mx = max(mx, a[i])
if mx >= k:
print(it)
exit()
a = p(a)
it += 1
l, r = 0, k
while r - l > 1:
m = (l + r) >> 1
sum = 0
f = False
for i in ind:
c, j = a[i], n - 1 - i
if j > m:
continue
while j > 0:
c *= m + j - 1
j -= 1
j = i
while j > 0:
c //= j
j -= 1
sum += c
if sum >= k:
f = True
break
if f:
r = m
else:
l = m
print(r)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be *n* problems, sorted by difficulty, i.e. problem 1 is the easiest and problem *n* is the hardest. Limak knows it will take him 5·*i* minutes to solve the *i*-th problem.
Limak's friends organize a New Year's Eve party and Limak wants to be there at midnight or earlier. He needs *k* minutes to get there from his house, where he will participate in the contest first.
How many problems can Limak solve if he wants to make it to the party?
|
```python
n, m = list(map(int, input().split()))
total_time_dk = 4 * 60
min_time_dk = total_time_dk - m
total = 0
y = 0
for i in range(1, n+1):
answer_time = 5
x = answer_time * i
y += x
if min_time_dk - y >= 0:
total += 1
print(total)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Summer holidays! Someone is going on trips, someone is visiting grandparents, but someone is trying to get a part-time job. This summer Noora decided that she wants to earn some money, and took a job in a shop as an assistant.
Shop, where Noora is working, has a plan on the following *n* days. For each day sales manager knows exactly, that in *i*-th day *k**i* products will be put up for sale and exactly *l**i* clients will come to the shop that day. Also, the manager is sure, that everyone, who comes to the shop, buys exactly one product or, if there aren't any left, leaves the shop without buying anything. Moreover, due to the short shelf-life of the products, manager established the following rule: if some part of the products left on the shelves at the end of the day, that products aren't kept on the next day and are sent to the dump.
For advertising purposes manager offered to start a sell-out in the shop. He asked Noora to choose any *f* days from *n* next for sell-outs. On each of *f* chosen days the number of products were put up for sale would be doubled. Thus, if on *i*-th day shop planned to put up for sale *k**i* products and Noora has chosen this day for sell-out, shelves of the shop would keep 2·*k**i* products. Consequently, there is an opportunity to sell two times more products on days of sell-out.
Noora's task is to choose *f* days to maximize total number of sold products. She asks you to help her with such a difficult problem.
|
```python
planDays,chosenDays=map(int,input().split())
total=[0 for _ in range(planDays)]
for i in range(planDays):
products,clients=map(int,input().split())
if (i+1)% chosenDays ==0:
products=2*products
if products >= clients:
total[i]= clients
elif products < clients and products !=0 :
total[i]=clients
print(sum(total))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Amr is a young coder who likes music a lot. He always wanted to learn how to play music but he was busy coding so he got an idea.
Amr has *n* instruments, it takes *a**i* days to learn *i*-th instrument. Being busy, Amr dedicated *k* days to learn how to play the maximum possible number of instruments.
Amr asked for your help to distribute his free days between instruments so that he can achieve his goal.
|
```python
n, k = map(int,input().split())
sum=0
l2=[]
l=sorted([(x,i) for i,x in enumerate(map(int,input().split()),1)])
for i,j in l:
sum=sum+i
if(sum<=k):
l2.append(j)
print(len(l2))
for h in l2:
print(h, end=' ')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The new operating system BerOS has a nice feature. It is possible to use any number of characters '/' as a delimiter in path instead of one traditional '/'. For example, strings //usr///local//nginx/sbin// and /usr/local/nginx///sbin are equivalent. The character '/' (or some sequence of such characters) at the end of the path is required only in case of the path to the root directory, which can be represented as single character '/'.
A path called normalized if it contains the smallest possible number of characters '/'.
Your task is to transform a given path to the normalized form.
|
```python
s=input()
x=[s[0]]
for i in range(1,len(s)-1):
if s[i]!='/':
x.append(s[i])
elif s[i]=='/' and s[i+1]!='/':
x.append('/')
for k in range(len(x)):
print(x[k],end='')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are *n* flights that must depart today, the *i*-th of them is planned to depart at the *i*-th minute of the day.
Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first *k* minutes of the day, so now the new departure schedule must be created.
All *n* scheduled flights must now depart at different minutes between (*k*<=+<=1)-th and (*k*<=+<=*n*)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.
Helen knows that each minute of delay of the *i*-th flight costs airport *c**i* burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
|
```python
import itertools
k, n = map(int, input().split())
data = list(map(int, input().split()))
min_v = []
min_value = 99999
v = []
for i in range(k):
v.append(i + n + 1)
variants = list(itertools.permutations(v, k))
for variant in variants:
summ = 0
for i in range(len(variant)):
summ += (variant[i] - i - 1) * data[i]
if variant[i] - i - 1 < 0:
summ = 9999999
break
if summ <= min_value:
min_value = summ
min_v = variant
print(min_value)
print(min_v)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a rectangular board of *M*<=×<=*N* squares. Also you are given an unlimited number of standard domino pieces of 2<=×<=1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squares.
2. No two dominoes overlap.
3. Each domino lies entirely inside the board. It is allowed to touch the edges of the board.
Find the maximum number of dominoes, which can be placed under these restrictions.
|
```python
n=int(input())
m=int(input())
parameter=m*n
Maximum_number_of_dominoes=parameter//2
print(Maximum_number_of_dominoes)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One day Polycarp published a funny picture in a social network making a poll about the color of his handle. Many of his friends started reposting Polycarp's joke to their news feed. Some of them reposted the reposts and so on.
These events are given as a sequence of strings "name1 reposted name2", where name1 is the name of the person who reposted the joke, and name2 is the name of the person from whose news feed the joke was reposted. It is guaranteed that for each string "name1 reposted name2" user "name1" didn't have the joke in his feed yet, and "name2" already had it in his feed by the moment of repost. Polycarp was registered as "Polycarp" and initially the joke was only in his feed.
Polycarp measures the popularity of the joke as the length of the largest repost chain. Print the popularity of Polycarp's joke.
|
```python
from collections import defaultdict
post = defaultdict(list)
n = int(input())
for _ in range(n):
c, b, a = input().split()
post[a.lower()].append(c.lower())
posters = set(["polycarp"])
def dfs(person, count):
c = count
for friend in post[person]:
if friend in posters:
continue
posters.add(friend)
c = max(c, dfs(friend, count + 1))
# print(person, c)
return c
print(dfs("polycarp", 1))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
During the winter holidays, the demand for Christmas balls is exceptionally high. Since it's already 2018, the advances in alchemy allow easy and efficient ball creation by utilizing magic crystals.
Grisha needs to obtain some yellow, green and blue balls. It's known that to produce a yellow ball one needs two yellow crystals, green — one yellow and one blue, and for a blue ball, three blue crystals are enough.
Right now there are *A* yellow and *B* blue crystals in Grisha's disposal. Find out how many additional crystals he should acquire in order to produce the required number of balls.
|
```python
sh = [int(w) for w in input().split()]
e = [int(q) for q in input().split()]
a = sh[0]
b = sh[1]
x = e[0]
y = e[1]
z = e[2]
n = a+b
ka = 2*x+1*y
kb = 1*y+3*z
d = (ka+kb)-n
print(d)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number *a* and Antisimon receives number *b*. They also have a heap of *n* stones. The players take turns to make a move and Simon starts. During a move a player should take from the heap the number of stones equal to the greatest common divisor of the fixed number he has received and the number of stones left in the heap. A player loses when he cannot take the required number of stones (i. e. the heap has strictly less stones left than one needs to take).
Your task is to determine by the given *a*, *b* and *n* who wins the game.
|
```python
x=list(map(int,input().split()))
a=x[0]
b=x[1]
n=x[2]
if(n%2==0):
print("1")
else:
print("0")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
After seeing the "ALL YOUR BASE ARE BELONG TO US" meme for the first time, numbers *X* and *Y* realised that they have different bases, which complicated their relations.
You're given a number *X* represented in base *b**x* and a number *Y* represented in base *b**y*. Compare those two numbers.
|
```python
n1 = 0
n, b = map(int, input().split())
a = list(map(int, input().split()))
a.reverse()
for i in range(n):
n1 += a[i] * (b ** i)
n2 = 0
n, b = map(int, input().split())
a = list(map(int, input().split()))
a.reverse()
for i in range(n):
n2 += a[i] * (b ** i)
if n1 < n2:
print("<")
if n1 == n2:
print("=")
if n1 > n2:
print(">")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At 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
def sol():
s=input()
u=0
l=0
for i in s:
if ord(i)<93:
u=u+1
else:
l=l+1
if l>=u:
print(s.lower())
else:
print(s.upper())
sol()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Maria participates in a bicycle race.
The speedway takes place on the shores of Lake Lucerne, just repeating its contour. As you know, the lake shore consists only of straight sections, directed to the north, south, east or west.
Let's introduce a system of coordinates, directing the *Ox* axis from west to east, and the *Oy* axis from south to north. As a starting position of the race the southernmost point of the track is selected (and if there are several such points, the most western among them). The participants start the race, moving to the north. At all straight sections of the track, the participants travel in one of the four directions (north, south, east or west) and change the direction of movement only in bends between the straight sections. The participants, of course, never turn back, that is, they do not change the direction of movement from north to south or from east to west (or vice versa).
Maria is still young, so she does not feel confident at some turns. Namely, Maria feels insecure if at a failed or untimely turn, she gets into the water. In other words, Maria considers the turn dangerous if she immediately gets into the water if it is ignored.
Help Maria get ready for the competition — determine the number of dangerous turns on the track.
|
```python
n = int(intput())
for i in range(n+1):
m = input()
print((n-4)/2)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Gargari is jealous that his friend Caisa won the game from the previous problem. He wants to prove that he is a genius.
He has a *n*<=×<=*n* chessboard. Each cell of the chessboard has a number written on it. Gargari wants to place two bishops on the chessboard in such a way that there is no cell that is attacked by both of them. Consider a cell with number *x* written on it, if this cell is attacked by one of the bishops Gargari will get *x* dollars for it. Tell Gargari, how to place bishops on the chessboard to get maximum amount of money.
We assume a cell is attacked by a bishop, if the cell is located on the same diagonal with the bishop (the cell, where the bishop is, also considered attacked by it).
|
```python
import itertools
n = int(input())
arr = [list(map(int, input().split())) for i in range(n)]
r_diag = {}
for i in range(-n+1, n):
diag_total = 0
# for j in range(0, n):
# x, y = i+j, j
# if 0 <= x < n and 0 <= y < n:
# diag_total += arr[x][y]
r_diag[i%(2*n-1)] = sum([arr[i+j][j] for j in range(0, n) if 0<=(i+j)<n])
l_diag = {}
for i in range(0, 2*n -1):
# diag_total = 0
# for j in range(0, n):
# x, y = i-j, j
# if 0 <= x < n and 0 <= y < n:
# diag_total += arr[x][y]
l_diag[i] = sum([arr[i-j][j] for j in range(0, n) if 0<=(i-j)<n])
# print(r_diag.items(), l_diag.items())
# the top corner block is black
# best_val = None
# best_pos = None, None
# for x in range(0, n):
# for y in range(0, n):
# if (x+y) % 2:
# continue
# r = (x-y) % (2*n-1)
# l = (x+y) % (2*n-1)
# val = l_diag[l] + r_diag[r] - arr[x][y]
# if best_val is None or val >= best_val:
# best_val = val
# best_pos = x, y
# best_val_black = best_val
# best_pos_black = best_pos
best_val_black, black_x, black_y = max([
(l_diag[(x+y) % (2*n-1)] + r_diag[(x-y) % (2*n-1)] - arr[x][y], x, y)
for x, y in itertools.product(range(0, n), range(0, n))
if (x+y) % 2 == 0
])
best_val_white, white_x, white_y = max([
(l_diag[(x+y) % (2*n-1)] + r_diag[(x-y) % (2*n-1)] - arr[x][y], x, y)
for x, y in itertools.product(range(0, n), range(0, n))
if (x+y) % 2 == 1
])
# best_val = None
# best_pos = None, None
# for x in range(0, n):
# for y in range(0, n):
# if not ((x+y) % 2):
# continue
# r = (x-y) % (2*n-1)
# l = (x+y) % (2*n-1)
# val = l_diag[l] + r_diag[r] - arr[x][y]
# if best_val is None or val >= best_val:
# best_val = val
# best_pos = x, y
print(best_val_black + best_val_white)
print(*[i+1 for i in [black_x, black_y, white_x, white_y]])
```
|
|
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
def main():
n = int(input())
nums = map(int, input().split())
chunk = []
base = 0
for i in range(n + 1):
base ^= i
chunk.append(base)
Q = 0
for i, num in enumerate(nums):
q = num
chunks, res = divmod(n, i + 1)
q ^= chunk[res]
if chunks % 2 == 1:
q ^= chunk[i]
Q ^= q
print(Q)
main()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string *s* consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string *s* to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".
If string *s* has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.
Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
|
```python
n = int(input())
string = input()
alphabets = "abcdefghijklmnopqrstuvwxyz"
count = 0
flag = 1
for i in alphabets:
if i not in string:
count += 1
length = len(set(string))
if length > count or n > 26:
flag = 0
if(flag == 1):
print(n - len(string))
else:
print("-1")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are *n* drinks in his fridge, the volume fraction of orange juice in the *i*-th drink equals *p**i* percent.
One day Vasya decided to make himself an orange cocktail. He took equal proportions of each of the *n* drinks and mixed them. Then he wondered, how much orange juice the cocktail has.
Find the volume fraction of orange juice in the final drink.
|
```python
def code(*args):
arr, n = args
result = float(sum(arr)/n)
return "{:.12f}".format(result)
if __name__ == "__main__":
# Take inputs here
n = int(input())
arr = list(map(int, input().split()))
result = code(arr, n) # Pass arguments
print(result)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed *w* kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Billy are great fans of even numbers, that's why they want to divide the watermelon in such a way that each of the two parts weighs even number of kilos, at the same time it is not obligatory that the parts are equal. The boys are extremely tired and want to start their meal as soon as possible, that's why you should help them and find out, if they can divide the watermelon in the way they want. For sure, each of them should get a part of positive weight.
|
```python
n,w=list(map(int,input().split()))
while(n%2==0 and w%2==0):
if((n+w)%2==0)
print("YES")
else:
print("NO")
print("NO")
#5l7
```
|
|
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
a, b = map(int, input().split())
ans = 0
mn = min(a, b)
for i in range(1, mn + 1):
ans += i
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Reca company makes monitors, the most popular of their models is AB999 with the screen size *a*<=×<=*b* centimeters. Because of some production peculiarities a screen parameters are integer numbers. Recently the screen sides ratio *x*:<=*y* became popular with users. That's why the company wants to reduce monitor AB999 size so that its screen sides ratio becomes *x*:<=*y*, at the same time they want its total area to be maximal of all possible variants. Your task is to find the screen parameters of the reduced size model, or find out that such a reduction can't be performed.
|
```python
import sys
from collections import defaultdict as dd
from collections import deque
def eprint(*args):
print(*args, file=sys.stderr)
pl=1
from math import *
import copy
#sys.setrecursionlimit(10**6)
if pl:
input=sys.stdin.readline
def li():
return [int(xxx) for xxx in input().split()]
def fi():
return int(input())
def si():
return list(input().rstrip())
def mi():
return map(int,input().split())
d=[]
from bisect import *
from itertools import permutations
from bisect import *
f=[0 for i in range(100)]
for i in range(1,100):
if i==1:
f[i]=1
else:
f[i]=2*f[i-1]+1
#print(f[:15])
def rec(n,k):
s=[]
while n!=0:
n,r=n//k,n%k
#print(n,r)
if r<0:
r-=k
n+=1
#print(s,n,r)
s.append(r)
return s
a,b,x,y=mi()
a,b=max(a,b),min(a,b)
x,y=max(x,y),min(x,y)
l=1
r=10**10
ans=0
aa=[0,0]
while l<=r:
mid=(l+r)//2
if x*mid<=a and y*mid<=b:
ans=max(ans,x*y*mid**2)
aa=[x*mid,y*mid]
l=mid+1
else:
r=mid-1
print(*aa)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
"Night gathers, and now my watch begins. It shall not end until my death. I shall take no wife, hold no lands, father no children. I shall wear no crowns and win no glory. I shall live and die at my post. I am the sword in the darkness. I am the watcher on the walls. I am the shield that guards the realms of men. I pledge my life and honor to the Night's Watch, for this night and all the nights to come." — The Night's Watch oath.
With that begins the watch of Jon Snow. He is assigned the task to support the stewards.
This time he has *n* stewards with him whom he has to provide support. Each steward has his own strength. Jon Snow likes to support a steward only if there exists at least one steward who has strength strictly less than him and at least one steward who has strength strictly greater than him.
Can you find how many stewards will Jon support?
|
```python
n = int(input())
x = list(map(int,input().split()))
n = int(input())
x = list(map(int,input().split()))
x = [*set(x)]
c = 0
for i in x:
if i > min(x) and i <max(x):
c+=1
print(c)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Walking through the streets of Marshmallow City, Slastyona have spotted some merchants selling a kind of useless toy which is very popular nowadays – caramel spinner! Wanting to join the craze, she has immediately bought the strange contraption.
Spinners in Sweetland have the form of V-shaped pieces of caramel. Each spinner can, well, spin around an invisible magic axis. At a specific point in time, a spinner can take 4 positions shown below (each one rotated 90 degrees relative to the previous, with the fourth one followed by the first one):
After the spinner was spun, it starts its rotation, which is described by a following algorithm: the spinner maintains its position for a second then majestically switches to the next position in clockwise or counter-clockwise order, depending on the direction the spinner was spun in.
Slastyona managed to have spinner rotating for exactly *n* seconds. Being fascinated by elegance of the process, she completely forgot the direction the spinner was spun in! Lucky for her, she managed to recall the starting position, and wants to deduct the direction given the information she knows. Help her do this.
|
```python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
s = '^>v<'
ch2int = {}
for i, c in enumerate(s):
ch2int[c] = i
a, b, n = sys.stdin.read().split()
a = ch2int[a]; b = ch2int[b]; n = int(n)
iscw = s[a] == s[(b+n)%n]
isccw = s[a] == s[(b-n)%n]
if iscw and not isccw:
print('cw')
elif not iscw and isccw:
print('ccw')
else:
print('undefined')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Let's denote a function
You are given an array *a* consisting of *n* integers. You have to calculate the sum of *d*(*a**i*,<=*a**j*) over all pairs (*i*,<=*j*) such that 1<=≤<=*i*<=≤<=*j*<=≤<=*n*.
|
```python
def set(x) :
if(x not in m) :
m[x] = 0
n = int(input())
a = list(map(int, input().split()))
m = {}
ans, total = 0, 0
for i in range(0, n) :
x = a[i];
set(x), set(x - 1), set(x + 1)
ans = ans + (i - m[x] - m[x - 1] - m[x + 1]) * x;
ans = ans -(total - m[x] * x - m[x - 1] * (x - 1) - m[x + 1] * (x + 1));
m[x], total = m[x] + 1, total + x
print(ans)
```
|
|
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
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 29 22:39:01 2021
@author: Corey.Smith
"""
s = input()
i=0
for l in s:
i = [i,i+1][l.upper()==l]
print([s.lower(),s.upper()][i>len(s)/2])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Mike is trying rock climbing but he is awful at it.
There are *n* holds on the wall, *i*-th hold is at height *a**i* off the ground. Besides, let the sequence *a**i* increase, that is, *a**i*<=<<=*a**i*<=+<=1 for all *i* from 1 to *n*<=-<=1; we will call such sequence a track. Mike thinks that the track *a*1, ..., *a**n* has difficulty . In other words, difficulty equals the maximum distance between two holds that are adjacent in height.
Today Mike decided to cover the track with holds hanging on heights *a*1, ..., *a**n*. To make the problem harder, Mike decided to remove one hold, that is, remove one element of the sequence (for example, if we take the sequence (1,<=2,<=3,<=4,<=5) and remove the third element from it, we obtain the sequence (1,<=2,<=4,<=5)). However, as Mike is awful at climbing, he wants the final difficulty (i.e. the maximum difference of heights between adjacent holds after removing the hold) to be as small as possible among all possible options of removing a hold. The first and last holds must stay at their positions.
Help Mike determine the minimum difficulty of the track after removing one hold.
|
```python
n = int(input())
a = [int(x) for x in input().split()]
val = []
mv = 0
for i in range(1,n):
mv = max(mv,a[i]-a[i-1])
z = 1000
for i in range(1,n-1):
z = min(z, a[i+1]-a[i-1])
if z <= mv:
print(mv)
else:
print(z)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
In Aramic language words can only represent objects.
Words in Aramic have special properties:
- A word is a root if it does not contain the same letter more than once. - A root and all its permutations represent the same object. - The root $x$ of a word $y$ is the word that contains all letters that appear in $y$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". - Any word in Aramic represents the same object as its root.
You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
|
```python
n = int(input())
a = []
s = input().split()
ans = 0
for i in range(n):
if set(s[i]) not in a:
a.append(set(s[i]))
ans += 1
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There are *n* cities and *n*<=-<=1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads.
Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities.
Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link [https://en.wikipedia.org/wiki/Expected_value](https://en.wikipedia.org/wiki/Expected_value).
|
```python
from collections import defaultdict
def solve():
n = int(input())
graph = defaultdict(list)
for _ in range(n-1):
x,y = map(int, input().split())
graph[x].append(y)
graph[y].append(x)
dep = defaultdict(int)
dep[0]=-1
sum=0
total=0
def dfs(curr, par):
nonlocal sum
nonlocal total
dep[curr]=dep[par]+1
for nxt in graph[curr]:
if nxt!=par: dfs(nxt, curr)
if len(graph[curr])==1 :
sum+=dep[curr]
total+=1
dfs(1, 0)
print(sum/total)
solve()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Pasha loves his phone and also putting his hair up... But the hair is now irrelevant.
Pasha has installed a new game to his phone. The goal of the game is following. There is a rectangular field consisting of *n* row with *m* pixels in each row. Initially, all the pixels are colored white. In one move, Pasha can choose any pixel and color it black. In particular, he can choose the pixel that is already black, then after the boy's move the pixel does not change, that is, it remains black. Pasha loses the game when a 2<=×<=2 square consisting of black pixels is formed.
Pasha has made a plan of *k* moves, according to which he will paint pixels. Each turn in his plan is represented as a pair of numbers *i* and *j*, denoting respectively the row and the column of the pixel to be colored on the current move.
Determine whether Pasha loses if he acts in accordance with his plan, and if he does, on what move the 2<=×<=2 square consisting of black pixels is formed.
|
```python
n,m,k=map(int,input().split())
l = [[0 for _ in range(n+2)] for _ in range(m+2)]#baohuquan
temp=1
if k<=3:
print(0)
else:
for c in range(1,k+1):
j,i=map(int,input().split())
l[i][j]=1
if l[i][j+1]+l[i+1][j]+l[i+1][j+1]==3 or l[i][j+1]+l[i-1][j]+l[i-1][j+1]==3 or l[i][j-1]+l[i+1][j]+l[i][j-1]==3 or l[i][j-1]+l[i-1][j]+l[i-1][j-1]==3:
print(c)
temp=0
break
if temp==1:
print(0)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The cows have just learned what a primitive root is! Given a prime *p*, a primitive root is an integer *x* (1<=≤<=*x*<=<<=*p*) such that none of integers *x*<=-<=1,<=*x*2<=-<=1,<=...,<=*x**p*<=-<=2<=-<=1 are divisible by *p*, but *x**p*<=-<=1<=-<=1 is.
Unfortunately, computing primitive roots can be time consuming, so the cows need your help. Given a prime *p*, help the cows find the number of primitive roots .
|
```python
def power(x, y, p):
result = 1
x = x % p
while y > 0:
if y % 2 == 1:
result = (result * x) % p
y = y // 2
x = (x * x) % p
return result
def phi(n):
result = n
p = 2
while p * p <= n:
if n % p == 0:
while n % p == 0:
n //= p
result -= result // p
p += 1
if n > 1:
result -= result // n
return result
def count_primitive_roots(p):
phi_p = phi(p)
primitive_roots = 0
for x in range(2, p):
if power(x, phi_p, p) == 1:
primitive_roots += 1
return primitive_roots
p = int(input())
result = count_primitive_roots(p)
print(result)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
After waking up at *hh*:*mm*, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is *H* points, moreover each minute without food increases his hunger by *D* points.
At any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs *C* roubles and decreases hunger by *N* points. Since the demand for bakery drops heavily in the evening, there is a special 20% discount for buns starting from 20:00 (note that the cost might become rational). Of course, buns cannot be sold by parts.
Determine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero.
|
```python
import math
first = input().split(" ")
hh = int(first[0])
mm = int(first[1])
t = hh * 60 + mm
disc = 20 * 60
second = input().split(" ")
h = int(second[0])
d = int(second[1])
c = int(second[2])
n = int(second[3])
if(t > disc):
print(0.8 * math.ceil(h/float(n)) * c)
else:
wait = 0.8 * math.ceil((h + d * (disc-t))/float(n))
imme = math.ceil(h/float(n))
print(min(c * imme, c * wait))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?
You are given a set of digits, your task is to find the maximum integer that you can make from these digits. The made number must be divisible by 2, 3, 5 without a residue. It is permitted to use not all digits from the set, it is forbidden to use leading zeroes.
Each digit is allowed to occur in the number the same number of times it occurs in the set.
|
```python
import decimal
from errno import ETIMEDOUT
import heapq as hq
import os
import sys
from collections import Counter as ctr, deque as dq
etd=dq()
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = 'x' in file.mode or 'r' not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b'\n') + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode('ascii'))
self.read = lambda: self.buffer.read().decode('ascii')
self.readline = lambda: self.buffer.readline().decode('ascii')
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')
from math import *
from bisect import bisect_left as bl, insort
from bisect import bisect_right as br
from itertools import permutations
inp = lambda: int(input())
li = lambda: list(map(int, input().split()))
lb = lambda: list(map(int, input()))
ls = lambda: list(input())
bi = lambda n: bin(n).replace("0b", "0"*(18-int(log(n,2))-1))
def yn(f):
print('NYOE S'[f::2])
def main(__=1):
for _ in range(__):
n=inp()
a=li()
a.sort(reverse=True)
if a[-1]!=0:
print(-1)
else:
rmd1=[]
rmd2=[]
s=0
for i in range(n):
t=a[i]%3
s=(s+t)%3
if t==1:
rmd1.append(i)
elif t==2:
rmd2.append(i)
if s==0:
print("".join(map(str,a)))
elif s==1:
if len(rmd1)>0:
a.pop(rmd1[-1])
elif len(rmd2)>1:
a.pop(rmd2[-1])
a.pop(rmd2[-2])
else:
a=[0]
print("".join(map(str,a)))
else:
if len(rmd2)>0:
a.pop(rmd2[-1])
elif len(rmd1)>1:
a.pop(rmd1[-1])
a.pop(rmd1[-2])
else:
a=[0]
print("".join(map(str,a)))
if __name__ == "__main__":
main()
#main(inp())
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There are *n* pearls in a row. Let's enumerate them with integers from 1 to *n* from the left to the right. The pearl number *i* has the type *a**i*.
Let's call a sequence of consecutive pearls a segment. Let's call a segment good if it contains two pearls of the same type.
Split the row of the pearls to the maximal number of good segments. Note that each pearl should appear in exactly one segment of the partition.
As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
|
```python
#!/usr/bin/python3
n = int(input())
a = [int(x) for x in input().split()]
r = []
s = set()
l = 0
for i, x in enumerate(a):
if x in s:
r.append([l + 1, i + 1])
l = i + 1
s = set()
else:
s.add(x)
if l == 0:
print(-1)
else:
if s:
r[-1][1] = n
print(len(r))
print('\n'.join('{0} {1}'.format(p, q) for (p, q) in r))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.
Given a sequence *a* consisting of *n* integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it *a**k*) and delete it, at that all elements equal to *a**k*<=+<=1 and *a**k*<=-<=1 also must be deleted from the sequence. That step brings *a**k* points to the player.
Alex is a perfectionist, so he decided to get as many points as possible. Help him.
|
```python
# Read the number of elements in the sequence
n = int(input())
# Read the sequence of elements
elements = list(map(int, input().split()))
# Count the frequency of each element
frequency = {}
for num in elements:
frequency[num] = frequency.get(num, 0) + 1
# Initialize the dp array
dp = [0] * n
# Initialize dp[0] with the product of frequency and the value of the first element
dp[0] = frequency.get(elements[0], 0) * elements[0]
# Iterate through the sequence to calculate dp[i]
for i in range(1, n):
dp[i] = max(dp[i - 1], dp[i - 2] + frequency.get(elements[i], 0) * elements[i])
# The maximum points that can be earned will be the maximum value in the dp array
max_points = max(dp)
# Print the maximum points
print(max_points)
```
|
|
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 = [int(x) for x in input().split()]
p = [int(x) for x in input().split()]
i = 0
for j in range(len(p) - 1):
num = p[n[1]-1]
p.append(num)
p.pop(0)
i = i+1
if len(set(p)) == 1:
print(i)
else:
print(-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
PolandBall is a young, clever Ball. He is interested in prime numbers. He has stated a following hypothesis: "There exists such a positive integer *n* that for each positive integer *m* number *n*·*m*<=+<=1 is a prime number".
Unfortunately, PolandBall is not experienced yet and doesn't know that his hypothesis is incorrect. Could you prove it wrong? Write a program that finds a counterexample for any *n*.
|
```python
n = int(input())
flag = False
for i in range(1, n + 1):
tempNum = n * i + i
for j in range(2, int(tempNum / 2) + 1):
if tempNum % j == 0:
flag = True
break
if flag == True:
print(i)
break
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Array of integers is unimodal, if:
- it is strictly increasing in the beginning; - after that it is constant; - after that it is strictly decreasing.
The first block (increasing) and the last block (decreasing) may be absent. It is allowed that both of this blocks are absent.
For example, the following three arrays are unimodal: [5,<=7,<=11,<=11,<=2,<=1], [4,<=4,<=2], [7], but the following three are not unimodal: [5,<=5,<=6,<=6,<=1], [1,<=2,<=1,<=2], [4,<=5,<=5,<=6].
Write a program that checks if an array is unimodal.
|
```python
arr=[]
n=int(input("Number of elements in array:"))
for i in range(0,n):
ele=int(input())
arr.append(ele)
def f(m,n,flag):
if flag==1:
return m<n
elif flag==2:
return m==n
else:
return m>n
def is_unimodal(a, lst):
flag=1
for i in range(1,n):
if f(lst[i-1], lst[i], flag):
continue
else:
flag += 1
if f(lst[i-1], lst[i], flag):
continue
else:
flag += 1
if f(lst[i-1], lst[i], flag):
continue
else:
return "NO"
return "YES"
print(is_unimodal(n, arr))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
What joy! Petya's parents went on a business trip for the whole year and the playful kid is left all by himself. Petya got absolutely happy. He jumped on the bed and threw pillows all day long, until...
Today Petya opened the cupboard and found a scary note there. His parents had left him with duties: he should water their favourite flower all year, each day, in the morning, in the afternoon and in the evening. "Wait a second!" — thought Petya. He know for a fact that if he fulfills the parents' task in the *i*-th (1<=≤<=*i*<=≤<=12) month of the year, then the flower will grow by *a**i* centimeters, and if he doesn't water the flower in the *i*-th month, then the flower won't grow this month. Petya also knows that try as he might, his parents won't believe that he has been watering the flower if it grows strictly less than by *k* centimeters.
Help Petya choose the minimum number of months when he will water the flower, given that the flower should grow no less than by *k* centimeters.
|
```python
n=int(input())
f=list(map(int,input().split()))
s=k=0
while k<n and len(f)!=0:
k+=max(f)
f.remove(max(f))
s+=1
if len(f)==0:
print(-1)
else:
print(s)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second.
One day in 230 AD Shapur was trying to find out if any one can possibly do calculations faster than him. As a result he made a very great contest and asked every one to come and take part.
In his contest he gave the contestants many different pairs of numbers. Each number is made from digits 0 or 1. The contestants should write a new number corresponding to the given pair of numbers. The rule is simple: The *i*-th digit of the answer is 1 if and only if the *i*-th digit of the two given numbers differ. In the other case the *i*-th digit of the answer is 0.
Shapur made many numbers and first tried his own speed. He saw that he can perform these operations on numbers of length ∞ (length of a number is number of digits in it) in a glance! He always gives correct answers so he expects the contestants to give correct answers, too. He is a good fellow so he won't give anyone very big numbers and he always gives one person numbers of same length.
Now you are going to take part in Shapur's contest. See if you are faster and more accurate.
|
```python
a = input()
b = input()
aux = ""
if (len(a)%2 == 0):
for i in range(0,len(a),2):
if a[i] == b[i]:
aux = aux + "0"
else:
aux = aux + "1"
if (a[i+1] == b[i+1]):
aux = aux+"0"
else:
aux = aux+"1"
else:
if (a[0] == b[0]):
aux = aux+"0"
else:
aux = aux+"1"
for i in range(1,len(a),2):
if a[i] == b[i]:
aux = aux + "0"
else:
aux = aux + "1"
if (a[i+1] == b[i+1]):
aux = aux+"0"
else:
aux = aux+"1"
print(aux)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
It's been almost a week since Polycarp couldn't get rid of insomnia. And as you may already know, one week in Berland lasts *k* days!
When Polycarp went to a doctor with his problem, the doctor asked him about his sleeping schedule (more specifically, the average amount of hours of sleep per week). Luckily, Polycarp kept records of sleep times for the last *n* days. So now he has a sequence *a*1,<=*a*2,<=...,<=*a**n*, where *a**i* is the sleep time on the *i*-th day.
The number of records is so large that Polycarp is unable to calculate the average value by himself. Thus he is asking you to help him with the calculations. To get the average Polycarp is going to consider *k* consecutive days as a week. So there will be *n*<=-<=*k*<=+<=1 weeks to take into consideration. For example, if *k*<==<=2, *n*<==<=3 and *a*<==<=[3,<=4,<=7], then the result is .
You should write a program which will calculate average sleep times of Polycarp over all weeks.
|
```python
## 808B
n,k=map(int,input().split())
l=list(map(int,input().split()))
ans=0
if k>=n:
ans=sum(l)/(n-k+1)
print(ans)
else:
i=n-k+1
j=[l[i] for i in range(n-k+1)]
s=sum(j)
while i<n:
j.pop(0)
j.insert(i,l[i])
i+=1
# print(j)
s+=sum(j)
print(s/(n-k+1))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Theatre Square in the capital city of Berland has a rectangular shape with the size *n*<=×<=*m* meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size *a*<=×<=*a*.
What is the least number of flagstones needed to pave the Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square.
|
```python
n, m, a = [int(input()) for i in range(3)]
n1 = (n // a) + 1
m1 = (m // a ) + 1
print(n1 * m1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a permutation of integers from 1 to *n*. Exactly once you apply the following operation to this permutation: pick a random segment and shuffle its elements. Formally:
1. Pick a random segment (continuous subsequence) from *l* to *r*. All segments are equiprobable. 1. Let *k*<==<=*r*<=-<=*l*<=+<=1, i.e. the length of the chosen segment. Pick a random permutation of integers from 1 to *k*, *p*1,<=*p*2,<=...,<=*p**k*. All *k*! permutation are equiprobable. 1. This permutation is applied to elements of the chosen segment, i.e. permutation *a*1,<=*a*2,<=...,<=*a**l*<=-<=1,<=*a**l*,<=*a**l*<=+<=1,<=...,<=*a**r*<=-<=1,<=*a**r*,<=*a**r*<=+<=1,<=...,<=*a**n* is transformed to *a*1,<=*a*2,<=...,<=*a**l*<=-<=1,<=*a**l*<=-<=1<=+<=*p*1,<=*a**l*<=-<=1<=+<=*p*2,<=...,<=*a**l*<=-<=1<=+<=*p**k*<=-<=1,<=*a**l*<=-<=1<=+<=*p**k*,<=*a**r*<=+<=1,<=...,<=*a**n*.
Inversion if a pair of elements (not necessary neighbouring) with the wrong relative order. In other words, the number of inversion is equal to the number of pairs (*i*,<=*j*) such that *i*<=<<=*j* and *a**i*<=><=*a**j*. Find the expected number of inversions after we apply exactly one operation mentioned above.
|
```python
MAX = 500005
n = int(input())
v = [0]*MAX
AIB = [0]*MAX
AIB2 = [0]*MAX
def add1(pos, val):
global AIB
while pos < MAX:
AIB[pos] += val
pos += pos & (-pos)
def add2(pos, val):
global AIB2
while pos < MAX:
AIB2[pos] += val
pos += pos & (-pos)
def query1(pos):
ans = 0
if pos < 0: return 0
while pos >= 1:
ans += AIB[pos]
pos -= pos & (-pos)
return ans
def query2(pos):
ans = 0
if pos < 0: return 0
while pos >= 1:
ans += AIB2[pos]
pos -= pos & (-pos)
return ans
v = [int(x) for x in input().split()]
for i in range(len(v)):
v[i] = n - v[i] + 1
v.insert(0,0)
ans = 0; ans2 = 0
for i in range(1, n+1):
ans += 1 * (n-i+1) * query1(v[i]-1)
add1(v[i], i)
ans2 += query2(v[i]-1)
add2(v[i], 1)
ans3 = 0
for i in range(1, n+1):
ans3 += ((n-i+1) * (i-1) * i / 4) / (n * (n+1) / 2)
ans /= (n * (n+1) / 2)
ans = ans2 - ans + ans3
print("{:.10f}".format(ans))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a non-negative integer *n*, its decimal representation consists of at most 100 digits and doesn't contain leading zeroes.
Your task is to determine if it is possible in this case to remove some of the digits (possibly not remove any digit at all) so that the result contains at least one digit, forms a non-negative integer, doesn't have leading zeroes and is divisible by 8. After the removing, it is forbidden to rearrange the digits.
If a solution exists, you should print it.
|
```python
s = "00" + input()
l = len(s)
for i in range(l):
for j in range(i + 1, l):
for k in range(j + 1, l):
ans = s[i] + s[j] + s[k]
if (int(ans) % 8 == 0):
print("YES")
print(int(ans))
exit()
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
In a building where Polycarp lives there are equal number of flats on each floor. Unfortunately, Polycarp don't remember how many flats are on each floor, but he remembers that the flats are numbered from 1 from lower to upper floors. That is, the first several flats are on the first floor, the next several flats are on the second and so on. Polycarp don't remember the total number of flats in the building, so you can consider the building to be infinitely high (i.e. there are infinitely many floors). Note that the floors are numbered from 1.
Polycarp remembers on which floors several flats are located. It is guaranteed that this information is not self-contradictory. It means that there exists a building with equal number of flats on each floor so that the flats from Polycarp's memory have the floors Polycarp remembers.
Given this information, is it possible to restore the exact floor for flat *n*?
|
```python
n, m = map(int, input().split())
flats = {}
for i in range(m):
flat, floor = map(int, input().split())
if floor not in flats.keys():
flats[floor] = []
flats[floor].append(flat)
floors = sorted(flats.keys())
def check():
for i in range(1, len(floors)):
a,b=min(flats[floors[i]]), max(flats[floors[i-1]])
if a-b == 1:
return b, floors[i-1]
return False
side_flat=check()
if not side_flat:
print(-1)
exit()
else:
n_flats_floor=side_flat[0]//side_flat[1]
print((n-1)//n_flats_floor + 1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
As you may know, MemSQL has American offices in both San Francisco and Seattle. Being a manager in the company, you travel a lot between the two cities, always by plane.
You prefer flying from Seattle to San Francisco than in the other direction, because it's warmer in San Francisco. You are so busy that you don't remember the number of flights you have made in either direction. However, for each of the last *n* days you know whether you were in San Francisco office or in Seattle office. You always fly at nights, so you never were at both offices on the same day. Given this information, determine if you flew more times from Seattle to San Francisco during the last *n* days, or not.
|
```python
i = input()
i = int(i)
s = input()
if s[0] == 'S' and s[i-1] == 'F':
print ('YES')
else:
print ('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Fox Ciel saw a large field while she was on a bus. The field was a *n*<=×<=*m* rectangle divided into 1<=×<=1 cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes.
After seeing the field carefully, Ciel found that the crop plants of each cell were planted in following procedure:
- Assume that the rows are numbered 1 to *n* from top to bottom and the columns are numbered 1 to *m* from left to right, and a cell in row *i* and column *j* is represented as (*i*,<=*j*). - First, each field is either cultivated or waste. Crop plants will be planted in the cultivated cells in the order of (1,<=1)<=→<=...<=→<=(1,<=*m*)<=→<=(2,<=1)<=→<=...<=→<=(2,<=*m*)<=→<=...<=→<=(*n*,<=1)<=→<=...<=→<=(*n*,<=*m*). Waste cells will be ignored. - Crop plants (either carrots or kiwis or grapes) will be planted in each cell one after another cyclically. Carrots will be planted in the first cell, then kiwis in the second one, grapes in the third one, carrots in the forth one, kiwis in the fifth one, and so on.
The following figure will show you the example of this procedure. Here, a white square represents a cultivated cell, and a black square represents a waste cell.
Now she is wondering how to determine the crop plants in some certain cells.
|
```python
from queue import Queue
import numpy as np
import pandas as pd
from bisect import bisect_left
from sortedcontainers import SortedSet
def ColorfulFields():
n, m, k, t = map(int, input().split())
wastes = SortedSet()
for i in range(k):
x, y = map(int, input().split())
wastes.add((x-1) * m + y)
fruits = ["Carrots", "Kiwis", "Grapes"]
for i in range(t):
x, y = map(int, input().split())
cellNO = (x-1) * m + y
if cellNO in wastes:
print("Waste")
else:
wasteCount = bisect_left(wastes, cellNO)
print(fruits[(cellNO % 3 - 1) - wasteCount])
ColorfulFields()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.
Rules of the game are very simple: at first number of rounds *n* is defined. In every round each of the players throws a cubical dice with distinct numbers from 1 to 6 written on its faces. Player, whose value after throwing the dice is greater, wins the round. In case if player dice values are equal, no one of them is a winner.
In average, player, who won most of the rounds, is the winner of the game. In case if two players won the same number of rounds, the result of the game is draw.
Mishka is still very little and can't count wins and losses, so she asked you to watch their game and determine its result. Please help her!
|
```python
using namespace std;
int main()
{
int n;
while(cin>>n)
{
int p1=0,p2=0;
while(n--)
{
int P1,P2;
cin>>P1>>P2;
p1+=(P1>P2);
p2+=(P2>P1);
}
if(p1>p2)
cout<<"Mishka"<<endl;
else if(p1<p2)
cout<<"Chris"<<endl;
else
cout<<"Friendship is magic!^^"<<endl;
}
return 0;
}
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Polycarpus is an amateur businessman. Recently he was surprised to find out that the market for paper scissors is completely free! Without further ado, Polycarpus decided to start producing and selling such scissors.
Polycaprus calculated that the optimal celling price for such scissors would be *p* bourles. However, he read somewhere that customers are attracted by prices that say something like "Special Offer! Super price 999 bourles!". So Polycarpus decided to lower the price a little if it leads to the desired effect.
Polycarpus agrees to lower the price by no more than *d* bourles so that the number of nines at the end of the resulting price is maximum. If there are several ways to do it, he chooses the maximum possible price.
Note, Polycarpus counts only the trailing nines in a price.
|
```python
p,d=input().split()
s=p[::-1]
z=""
x=""
for i in range(len(d)):
if s[i]=="9":
z=z+"0"
x=x+z
else:
b=int("1"+s[i])-9
if int(str(b)+x)<=int(d):
x=x+str(b)
z=z+str(b)
s=str(int(p)-int(b))[::-1]
else:
break
print(int(p)-int(z[::-1]))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Nastya owns too many arrays now, so she wants to delete the least important of them. However, she discovered that this array is magic! Nastya now knows that the array has the following properties:
- In one second we can add an arbitrary (possibly negative) integer to all elements of the array that are not equal to zero. - When all elements of the array become equal to zero, the array explodes.
Nastya is always busy, so she wants to explode the array as fast as possible. Compute the minimum time in which the array can be exploded.
|
```python
i=input;i();print(len(set(i().split())-{'0'}))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Your friend has *n* cards.
You know that each card has a lowercase English letter on one side and a digit on the other.
Currently, your friend has laid out the cards on a table so only one side of each card is visible.
You would like to know if the following statement is true for cards that your friend owns: "If a card has a vowel on one side, then it has an even digit on the other side." More specifically, a vowel is one of 'a', 'e', 'i', 'o' or 'u', and even digit is one of '0', '2', '4', '6' or '8'.
For example, if a card has 'a' on one side, and '6' on the other side, then this statement is true for it. Also, the statement is true, for example, for a card with 'b' and '4', and for a card with 'b' and '3' (since the letter is not a vowel). The statement is false, for example, for card with 'e' and '5'. You are interested if the statement is true for all cards. In particular, if no card has a vowel, the statement is true.
To determine this, you can flip over some cards to reveal the other side. You would like to know what is the minimum number of cards you need to flip in the worst case in order to verify that the statement is true.
|
```python
s=input()
c=0
for i in range(len(s)):
if s[i] in ['a','e','i','o','u']:
c+=1
if s[i].isdigit():
if int(s[i])%2!=0:
c+=1
print (c)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Sereja and his friends went to a picnic. The guys had *n* soda bottles just for it. Sereja forgot the bottle opener as usual, so the guys had to come up with another way to open bottles.
Sereja knows that the *i*-th bottle is from brand *a**i*, besides, you can use it to open other bottles of brand *b**i*. You can use one bottle to open multiple other bottles. Sereja can open bottle with opened bottle or closed bottle.
Knowing this, Sereja wants to find out the number of bottles they've got that they won't be able to open in any way. Help him and find this number.
|
```python
# http://codeforces.com/problemset/problem/315/A
get=lambda:list(map(int,input().split()))
n=int(input())
a=[]
b=[]
for i in range (n):
x,y=get()
a.append(x)
b.append(y)
d=n
for i in range(n):
for j in range(n):
if a[i]==b[j] and i!=j:
d-=1
break
print(d)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Professor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest.
In total, *n* students will attend, and before the start, every one of them has some positive integer rating. Students are indexed from 1 to *n*. Let's denote the rating of *i*-th student as *a**i*. After the contest ends, every student will end up with some positive integer position. GukiZ expects that his students will take places according to their ratings.
He thinks that each student will take place equal to . In particular, if student *A* has rating strictly lower then student *B*, *A* will get the strictly better position than *B*, and if two students have equal ratings, they will share the same position.
GukiZ would like you to reconstruct the results by following his expectations. Help him and determine the position after the end of the contest for each of his students if everything goes as expected.
|
```python
n = int(input())
ratings = [(i,int(x)) for x in enumerate(input().split())]
out = [0]*n
ratings = sorted(ratings, key = lambda x: x[0], reverse=True)
pos = 0
score = 0
for r in rating:
r_score = r[1]
if r_score <> score:
score = r_score
pos +=1
out[r[0]] = pos
print (' '.join(str(x) for x in out))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a multiset of *n* integers. You should select exactly *k* of them in a such way that the difference between any two of them is divisible by *m*, or tell that it is impossible.
Numbers can be repeated in the original multiset and in the multiset of selected numbers, but number of occurrences of any number in multiset of selected numbers should not exceed the number of its occurrences in the original multiset.
|
```python
n, k, m = [int(z) for z in input().split()]
a = [int(z) for z in input().split()]
d = dict()
for i in range(n):
mod = a[i] % m
if mod in d:
d[mod].append(a[i])
else:
d[mod] = [a[i]]
for elem in d:
if len(d[elem]) >= k:
print("Yes")
for i in range(k):
print(d[elem][i], end=" ")
exit(0)
print("No")
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.