source
stringclasses 3
values | instruction
stringlengths 23
3.97k
| input
stringclasses 1
value | output
stringlengths 1
3.75k
|
---|---|---|---|
MatrixStudio/Codeforces-Python-Submissions
|
Vasily the bear has a favorite rectangle, it has one vertex at point (0,<=0), and the opposite vertex at point (*x*,<=*y*). Of course, the sides of Vasya's favorite rectangle are parallel to the coordinate axes.
Vasya also loves triangles, if the triangles have one vertex at point *B*<==<=(0,<=0). That's why today he asks you to find two points *A*<==<=(*x*1,<=*y*1) and *C*<==<=(*x*2,<=*y*2), such that the following conditions hold:
- the coordinates of points: *x*1, *x*2, *y*1, *y*2 are integers. Besides, the following inequation holds: *x*1<=<<=*x*2; - the triangle formed by point *A*, *B* and *C* is rectangular and isosceles ( is right); - all points of the favorite rectangle are located inside or on the border of triangle *ABC*; - the area of triangle *ABC* is as small as possible.
Help the bear, find the required points. It is not so hard to proof that these points are unique.
|
```python
# coding: utf-8
x, y = [int(i) for i in input().split()]
length = abs(x)+abs(y)
ans = []
if x < 0:
ans.append([-length,0])
else:
ans.append([length,0])
if y < 0:
ans.append([0,-length])
else:
ans.append([0,length])
ans.sort()
print(ans[0][0],ans[0][1],ans[1][0],ans[1][1])
```
|
|
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
values = input().split()
rows = int(values[0])
cols = int(values[1])
chessboard = []
for i in range(rows):
row = []
for j in range(cols):
if i % 2 == 0:
if j % 2 == 0:
row.append('B')
else:
row.append('W')
else:
if j % 2 == 0:
row.append('W')
else:
row.append('B')
chessboard.append(row)
for i in range(rows):
row = input()
for j in range(cols):
if row[j] == '-':
chessboard[i][j] = '-'
for i in range(rows):
for j in range(cols):
print(chessboard[i][j], end = "")
print()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little boy Valera studies an algorithm of sorting an integer array. After studying the theory, he went on to the practical tasks. As a result, he wrote a program that sorts an array of *n* integers *a*1,<=*a*2,<=...,<=*a**n* in the non-decreasing order. The pseudocode of the program, written by Valera, is given below. The input of the program gets number *n* and array *a*.
But Valera could have made a mistake, because he hasn't yet fully learned the sorting algorithm. If Valera made a mistake in his program, you need to give a counter-example that makes his program work improperly (that is, the example that makes the program sort the array not in the non-decreasing order). If such example for the given value of *n* doesn't exist, print -1.
|
```python
n = int(input())
if n < 3:
print(-1)
else:
print(2, 2, *([1] * (n-2)))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You're given a string of lower-case Latin letters. Your task is to find the length of its longest substring that can be met in the string at least twice. These occurrences can overlap (see sample test 2).
|
```python
s=input()
o=len(s)
k=0
for i in range(o):
r={0}
for j in range(o-i+1):
if s[j:j+i] in r:k=max(i,k)
else:r.add(s[j:j+i])
print(k)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
While Mike was walking in the subway, all the stuff in his back-bag dropped on the ground. There were several fax messages among them. He concatenated these strings in some order and now he has string *s*.
He is not sure if this is his own back-bag or someone else's. He remembered that there were exactly *k* messages in his own bag, each was a palindrome string and all those strings had the same length.
He asked you to help him and tell him if he has worn his own back-bag. Check if the given string *s* is a concatenation of *k* palindromes of the same length.
|
```python
tar = input()
k = int(input())
n = len(tar)
all = []
ans = True
for i in range(0,k):
all.append(tar[int(i*n/k):int((i+1)*(n/k))])
# print(all[i])
x = int(n/k/2)
# print(all[i][0:x])
# print(all[i][x:x*2][::-1])
ans &= (all[i][0:x] == all[i][x:x*2][::-1])
if ans:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You will receive 3 points for solving this problem.
Manao is designing the genetic code for a new type of algae to efficiently produce fuel. Specifically, Manao is focusing on a stretch of DNA that encodes one protein. The stretch of DNA is represented by a string containing only the characters 'A', 'T', 'G' and 'C'.
Manao has determined that if the stretch of DNA contains a maximal sequence of consecutive identical nucleotides that is of even length, then the protein will be nonfunctional. For example, consider a protein described by DNA string "GTTAAAG". It contains four maximal sequences of consecutive identical nucleotides: "G", "TT", "AAA", and "G". The protein is nonfunctional because sequence "TT" has even length.
Manao is trying to obtain a functional protein from the protein he currently has. Manao can insert additional nucleotides into the DNA stretch. Each additional nucleotide is a character from the set {'A', 'T', 'G', 'C'}. Manao wants to determine the minimum number of insertions necessary to make the DNA encode a functional protein.
|
```python
s=input()
l=len(s)
ans=0
i=0
while i<l:
j=i+1
while j<l and s[j]==s[i]:j+=1
if j-i&1==0:ans+=1
i=j
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Bob has a permutation of integers from 1 to *n*. Denote this permutation as *p*. The *i*-th element of *p* will be denoted as *p**i*. For all pairs of distinct integers *i*,<=*j* between 1 and *n*, he wrote the number *a**i*,<=*j*<==<=*min*(*p**i*,<=*p**j*). He writes *a**i*,<=*i*<==<=0 for all integer *i* from 1 to *n*.
Bob gave you all the values of *a**i*,<=*j* that he wrote down. Your job is to reconstruct any permutation that could have generated these values. The input will be formed so that it is guaranteed that there is at least one solution that is consistent with the information given.
|
```python
n=int(input())
X=[]
Y=[]
for i in range(n):
x=int(input())
y=int(input())
X.append(x)
Y.append(y)
d=(x-X[0])**2+(y-Y[0])**2
j=0
for i in range(1,n):
if (x-X[i])**2+(y-Y[i])**2<d:
d=(x-X[i])**2+(y-Y[i])**2
j=i
if j!=0:
d1=(X[j]-X[0])**2+(Y[j]-Y[0])**2
k=0
else:
k=1
d1=(X[j]-X[1])**2+(Y[j]-Y[1])**2
for i in range(1,n-1):
B=True
if (X[j]-X[i])**2+(Y[j]-Y[i])**2<d1 and i!=j and B==True:
k=i
print (1+i,1+j,1+k)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Bachgold problem is very easy to formulate. Given a positive integer *n* represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.
Recall that integer *k* is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and *k*.
|
```python
n = int(input())
if n % 2 == 0:
ans = n // 2
res = [2] * ans
else:
ans = (n-3) // 2
res = [2] * ans + [3]
print(ans+1)
print(*res)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given *n* numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given *n* numbers finds one that is different in evenness.
|
```python
n=int(input())
a=list(map(int,input().split()))
e=0
o=0
c=0
if(a[0]%2==0):
e=1
else:
o=1
if(a[1]%2==0):
if(e==0):
if(a[2]%2==0):
print(1)
else:
print(2)
if(e==1):
c=1
else:
if(o==0):
if(a[2]%2!=0):
print(1)
else:
print(2)
else:
c=2
if(c==1):
for i in range(2,n):
if(a[i]%2!=0):
print(i+1)
break
elif(c==2):
for i in range(2,n):
if(a[i]%2==0):
print(i+1)
break
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given *n* numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given *n* numbers finds one that is different in evenness.
|
```python
even, odd = 0, 0
z = int(input())
a = list(map(int,input().split()))
b = []
for i in range(z):
if a[i] % 2 == 0:
even += 1
b.append('0')
else:
odd += 1
b.append('1')
print(b.index('1' if even > odd else '0') + 1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya has a non-negative integer *n*. He wants to round it to nearest integer, which ends up with 0. If *n* already ends up with 0, Vasya considers it already rounded.
For example, if *n*<==<=4722 answer is 4720. If *n*<==<=5 Vasya can round it to 0 or to 10. Both ways are correct.
For given *n* find out to which integer will Vasya round it.
|
```python
n=int(input())
a=n%10
if a<=5:
print(n-a)
else:
print(n+(10-a))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
In mathematics, the Pythagorean theorem — is a relation in Euclidean geometry among the three sides of a right-angled triangle. In terms of areas, it states:
In any right-angled triangle, the area of the square whose side is the hypotenuse (the side opposite the right angle) is equal to the sum of the areas of the squares whose sides are the two legs (the two sides that meet at a right angle).
The theorem can be written as an equation relating the lengths of the sides *a*, *b* and *c*, often called the Pythagorean equation:
where *c* represents the length of the hypotenuse, and *a* and *b* represent the lengths of the other two sides.
Given *n*, your task is to count how many right-angled triangles with side-lengths *a*, *b* and *c* that satisfied an inequality 1<=≤<=*a*<=≤<=*b*<=≤<=*c*<=≤<=*n*.
|
```python
from math import ceil,sqrt
n=int(input())
amt=0
for a in range(1,n+1):
for b in range(a,n+1):
if (sqrt(a**2+b**2))==ceil((sqrt(a**2+b**2))) and (sqrt(a**2+b**2))<=n:
amt+=1
print(amt)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A big company decided to launch a new series of rectangular displays, and decided that the display must have exactly *n* pixels.
Your task is to determine the size of the rectangular display — the number of lines (rows) of pixels *a* and the number of columns of pixels *b*, so that:
- there are exactly *n* pixels on the display; - the number of rows does not exceed the number of columns, it means *a*<=≤<=*b*; - the difference *b*<=-<=*a* is as small as possible.
|
```python
n=int(input())
dmin=100000000
a=0
b=0
for i in range(1,n+1,1):
for k in range(1,n+1,1):
j=k
#print(i,j,sep=" ")
if i*j==n:
#print(i,j,sep=" ")
if i<=j:
#print(i,j,sep=" ")
minn=j-i
if minn<dmin:
#print(i,j,sep=" ")
dmin=minn
a=i
b=j
break
print(a,b)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Jack is working on his jumping skills recently. Currently he's located at point zero of the number line. He would like to get to the point *x*. In order to train, he has decided that he'll first jump by only one unit, and each subsequent jump will be exactly one longer than the previous one. He can go either left or right with each jump. He wonders how many jumps he needs to reach *x*.
|
```python
x = int(input("sayı girin: "))
x_now = 0
step_num = 0
step_size = 1
while x_now != x:
if x > x_now:
if x_now + step_size > x:
x_now -= step_size
else:
x_now += step_size
else:
if x_now - step_size < x:
x_now += step_size
else:
x_now -= step_size
step_num += 1
step_size += 1
print(step_num)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There are three friend living on the straight line *Ox* in Lineland. The first friend lives at the point *x*1, the second friend lives at the point *x*2, and the third friend lives at the point *x*3. They plan to celebrate the New Year together, so they need to meet at one point. What is the minimum total distance they have to travel in order to meet at some point and celebrate the New Year?
It's guaranteed that the optimal answer is always integer.
|
```python
input_str = input("Enter space-separated integers: ")
input_list = list(map(int, input_str.split()))
max_value = max(input_list)
min_value = min(input_list)
difference = max_value - min_value
print("The difference between the maximum and minimum values is:", difference)
```
|
|
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
m, n = map(int, input().split())
print(m * (n - (n%2))//2 + (n%2) * m//2)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Iahub got bored, so he invented a game to be played on paper.
He writes *n* integers *a*1,<=*a*2,<=...,<=*a**n*. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices *i* and *j* (1<=≤<=*i*<=≤<=*j*<=≤<=*n*) and flips all values *a**k* for which their positions are in range [*i*,<=*j*] (that is *i*<=≤<=*k*<=≤<=*j*). Flip the value of *x* means to apply operation *x*<==<=1 - *x*.
The goal of the game is that after exactly one move to obtain the maximum number of ones. Write a program to solve the little game of Iahub.
|
```python
n = int(input())
lis = list(map(int, input().split()))
cnt = 0
mx = 0
mxx = 0
for i in lis:
if i == 1:
cnt += 1
if mx:
mx -= 1
else:
mx += 1
mxx = max(mx, mxx)
print(cnt + mxx)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
This task is very simple. Given a string *S* of length *n* and *q* queries each query is on the format *i* *j* *k* which means sort the substring consisting of the characters from *i* to *j* in non-decreasing order if *k*<==<=1 or in non-increasing order if *k*<==<=0.
Output the final string after applying the queries.
|
```python
strLength, n = list(map(int, input().split()))
inputString = input()
for i in range(n):
start, end, method = list(map(int, input().split()))
firstPart = inputString[:start - 1]
lastPart = inputString[end:]
mainPart = inputString[start -1: end]
if method == 1:
reverseOrder = 0
else:
reverseOrder = 1
mainPart = ''.join(sorted(list(mainPart), reverse=reverseOrder))
inputString = firstPart + mainPart + lastPart
print(inputString)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth.
Now Diamond has given Bort a string consisting of only uppercase English letters of length *n*. There is a great number of "QAQ" in the string (Diamond is so cute!).
Bort wants to know how many subsequences "QAQ" are in the string Diamond has given. Note that the letters "QAQ" don't have to be consecutive, but the order of letters should be exact.
|
```python
s = input()
c = 0
first_q_count = 0
last_q_count = s.count("Q")
for i in range(len(s)):
char = s[i]
if char == "Q":
first_q_count += 1
last_q_count -= 1
if char == "A":
c += first_q_count * last_q_count
print(c)
```
|
|
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
length = int(input())
month = list(map(int, input().split()))
month.sort(reverse=True)
big = month[0]
days = 1
if length == 0:
print(0)
exit()
for i in range(1, 12):
if big >= length:
break
else:
big += month[i]
days += 1
if big >= length:
print(days)
else:
print(-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Given an array *a*1,<=*a*2,<=...,<=*a**n* of *n* integers, find the largest number in the array that is not a perfect square.
A number *x* is said to be a perfect square if there exists an integer *y* such that *x*<==<=*y*2.
|
```python
def isPerfect(num):
cnt = 0
for i in range(2,num):
if num%i==0:
cnt += 1
if cnt%2==0:
return False
else:
return True
n = int(input())
data = list(map(int, input().split()))
data.sort(reverse=True)
for num in data:
if not isPerfect(num):
print(num)
break
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be.
In order to make sure that he's right and restore the correct order of keys, Santa typed his favorite patter looking only to his keyboard.
You are given the Santa's favorite patter and the string he actually typed. Determine which pairs of keys could be mixed. Each key must occur in pairs at most once.
|
```python
p = input()
tec = input()
res = {}
fudeu = 0
for i in range(len(p)):
if p[i] != tec[i]:
if p[i] in res:
if res[p[i]] != tec[i]:
fudeu=1
elif tec[i] in res:
if res[tec[i]] != p[i]:
fudeu = 1
else:
res[p[i]] = tec[i]
if fudeu == 0:
print(len(res))
for i in res:
print(i,res[i])
else:
print(-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given *n* segments on the Ox-axis. You can drive a nail in any integer point on the Ox-axis line nail so, that all segments containing this point, are considered nailed down. If the nail passes through endpoint of some segment, this segment is considered to be nailed too. What is the smallest number of nails needed to nail all the segments down?
|
```python
n=int(input())
c=[]
for i in range(n):
x,y=map(int,input().split())
if x>y: x,y=y,x
c.append([x,0,i])
c.append([y,1,i])
c.sort()
ans=0
stack=[]
b=[]
for z in c:
if z[1]==0:
stack.append(z[2])
else:
if z[2] in stack:
ans+=1
b.append(z[0])
stack=[]
print(ans)
print(*b)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Cucumber boy is fan of Kyubeat, a famous music game.
Kyubeat has 16 panels for playing arranged in 4<=×<=4 table. When a panel lights up, he has to press that panel.
Each panel has a timing to press (the preffered time when a player should press it), and Cucumber boy is able to press at most *k* panels in a time with his one hand. Cucumber boy is trying to press all panels in perfect timing, that is he wants to press each panel exactly in its preffered time. If he cannot press the panels with his two hands in perfect timing, his challenge to press all the panels in perfect timing will fail.
You are given one scene of Kyubeat's panel from the music Cucumber boy is trying. Tell him is he able to press all the panels in perfect timing.
|
```python
k = int(input())
d={}
t=[]
for i in range(10):
d[i]=0
for i in range(4):
arr=input()
t.append(arr)
for i in range(4):
for j in range(4):
if t[i][j]==".":
continue
else:
d[int(t[i][j])]+=1
for i in range(9):
if d[i]>2*k:
print("NO")
break
else:
print("YES")
```
|
|
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
def min_changes(s: str) -> int:
n = len(s)
dp = [0] * (n + 1)
for i in range(1, n + 1):
if s[i - 1].isupper():
dp[i] = dp[i - 1]
else:
dp[i] = min(dp[i - 1] + 1, sum(1 for c in s if c.isupper()))
return dp[n]
s = input().strip()
print(min_changes(s))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Polycarp has created his own training plan to prepare for the programming contests. He will train for $n$ days, all days are numbered from $1$ to $n$, beginning from the first.
On the $i$-th day Polycarp will necessarily solve $a_i$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.
Determine the index of day when Polycarp will celebrate the equator.
|
```python
n=int(input())
a=list(map(int,input().split()))
s=sum(a)/2
ss=0
for i in range(n):
ss+=a[i]
if(ss>=s):
print(i+1)
break
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Mishka started participating in a programming contest. There are $n$ problems in the contest. Mishka's problem-solving skill is equal to $k$.
Mishka arranges all problems from the contest into a list. Because of his weird principles, Mishka only solves problems from one of the ends of the list. Every time, he chooses which end (left or right) he will solve the next problem from. Thus, each problem Mishka solves is either the leftmost or the rightmost problem in the list.
Mishka cannot solve a problem with difficulty greater than $k$. When Mishka solves the problem, it disappears from the list, so the length of the list decreases by $1$. Mishka stops when he is unable to solve any problem from any end of the list.
How many problems can Mishka solve?
|
```python
n, k = map(int, input().split())
ls = list(map(int, input().split()))
count = 0
while len(ls) > 0:
if ls[0] <= k:
count+=1
ls.pop(0)
else: break
while len(ls) > 0:
if ls[len(ls)-1] <= k:
count+=1
ls.pop(len(ls)-1)
else: break
print(count)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:
Vladik is at initial train station, and now *n* people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code *a**i* is known (the code of the city in which they are going to).
Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city *x*, then all people who are going to city *x* should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city *x*, either go to it and in the same railway carriage, or do not go anywhere at all.
Comfort of a train trip with people on segment from position *l* to position *r* is equal to XOR of all distinct codes of cities for people on the segment from position *l* to position *r*. XOR operation also known as exclusive OR.
Total comfort of a train trip is equal to sum of comfort for each segment.
Help Vladik to know maximal possible total comfort.
|
```python
n = int(input())
a = list(map(int,input().split()))
dl = dict()
dr = dict()
for i in range(n):
if a[i] not in dl:
dl[a[i]] = i
dr[a[i]] = i
def XOR(l):
c = list(set(l))
k = len(c)
x = c[0]
for i in range(1,k):
x ^= c[i]
return x
from collections import defaultdict
DP = defaultdict(int)
for i in range(n):
if dr[a[i]] > i:
DP[i] = DP[i-1]
else:
k = dl[a[i]]
xor = XOR(a[k:i+1])
DP[i] = max(DP[i-1],DP[k-1]+xor)
for j in range(k-1,-1,-1):
if dl[a[j]] == j and dr[a[j]] <= i:
xor ^= a[j]
DP[i] = max(DP[i],DP[j-1] + xor)
print(DP[n-1])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
This problem's actual name, "Lexicographically Largest Palindromic Subsequence" is too long to fit into the page headline.
You are given string *s* consisting of lowercase English letters only. Find its lexicographically largest palindromic subsequence.
We'll call a non-empty string *s*[*p*1*p*2... *p**k*] = *s**p*1*s**p*2... *s**p**k* (1 <=≤<= *p*1<=<<=*p*2<=<<=...<=<<=*p**k* <=≤<= |*s*|) a subsequence of string *s* = *s*1*s*2... *s*|*s*|, where |*s*| is the length of string *s*. For example, strings "abcb", "b" and "abacaba" are subsequences of string "abacaba".
String *x* = *x*1*x*2... *x*|*x*| is lexicographically larger than string *y* = *y*1*y*2... *y*|*y*| if either |*x*| > |*y*| and *x*1<==<=*y*1, *x*2<==<=*y*2, ...,<=*x*|*y*|<==<=*y*|*y*|, or there exists such number *r* (*r*<=<<=|*x*|, *r*<=<<=|*y*|) that *x*1<==<=*y*1, *x*2<==<=*y*2, ..., *x**r*<==<=*y**r* and *x**r*<=<=+<=<=1<=><=*y**r*<=<=+<=<=1. Characters in the strings are compared according to their ASCII codes. For example, string "ranger" is lexicographically larger than string "racecar" and string "poster" is lexicographically larger than string "post".
String *s* = *s*1*s*2... *s*|*s*| is a palindrome if it matches string *rev*(*s*) = *s*|*s*|*s*|*s*|<=-<=1... *s*1. In other words, a string is a palindrome if it reads the same way from left to right and from right to left. For example, palindromic strings are "racecar", "refer" and "z".
|
```python
s=input()
m=max(s)
while s.count(max(s))==1:
s.remove(max(s))
if s=="":
break
if s=="":
print(m)
else:
print(max(s)*s.count(max(s)))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (*u*,<=*v*) that belongs to the graph, *u* and *v* belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.
Dr. Evil gave Mahmoud and Ehab a tree consisting of *n* nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?
A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .
|
```python
import pprint
class Bipartite_Graph:
def __init__(self):
self.graph={
# 1:[2,4,3],
# 2:[1,3,5],
# 3:[2,4,1],
# 4:[5,3,1],
# 5:[4,2]
}
self.vis=set()
self.colored={}
self.bipartite=True
def add_edge(self,a,b):
if(not a in self.graph):
self.graph[a] = set()
if(not b in self.graph):
self.graph[b] = set()
self.graph[a].add(b)
self.graph[b].add(a)
def del_edge(self, a, b): #if not making bipartiness then delete
self.graph[a].remove(b)
self.graph[b].remove(a)
def dfs_util(self,v,visited,color=1):
# print(v)
visited.add(v)
self.vis=visited
if(v in self.colored and self.colored[v]!=color):
self.bipartite=False
return False
self.colored[v]=color
for neighbour in self.graph[v]:
if neighbour not in visited:
self.dfs_util(neighbour,visited,color*-1)
else:
if(self.colored[neighbour]==color): #if parent and child have the same color
self.bipartite=False
return False
def dfs(self): #handling disconnected graph DFS
visited = set()
self.vis=set()
for vertex in self.graph:
if vertex not in visited:
self.dfs_util(vertex, visited)
N=int(input())
arr=[int(x) for x in range(1,N+1)]
edges={}
for i in range(N-1): #making all the possible edges regardless of bipartiness
for j in range(i+1,N):
a,b=arr[i],arr[j]
key=str(a)+str(b)
edges[key]=[a,b]
# pprint.pprint(edges)
# #creating object of the class
Graph=Bipartite_Graph()
for i in range(N-1): #adding edges
a,b=[int(x) for x in input().split()]
Graph.add_edge(a,b)
# # #remove from the edges dictionary
key=str(a)+str(b)
if(key in edges):
del edges[key]
Graph.dfs()
print(Graph.graph)
print(Graph.colored)
count=0
for edge in edges:
a=int(edge[0])
b=int(edge[1])
if(Graph.colored[a]!=Graph.colored[b]):
# print(a,b)
count+=1
print(count)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
In a Berland's zoo there is an enclosure with camels. It is known that camels like to spit. Bob watched these interesting animals for the whole day and registered in his notepad where each animal spitted. Now he wants to know if in the zoo there are two camels, which spitted at each other. Help him to solve this task.
The trajectory of a camel's spit is an arc, i.e. if the camel in position *x* spits *d* meters right, he can hit only the camel in position *x*<=+<=*d*, if such a camel exists.
|
```python
n=int(input())
X=set()
XD=set()
for i in range(n):
x,d=list(map(int,input().split(' ')))
X.add(x)
XD.add(x+d)
if X&XD: print('YES')
else: print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a rectangular cake, represented as an *r*<=×<=*c* grid. Each cell either has an evil strawberry, or is empty. For example, a 3<=×<=4 cake may look as follows:
The cakeminator is going to eat the cake! Each time he eats, he chooses a row or a column that does not contain any evil strawberries and contains at least one cake cell that has not been eaten before, and eats all the cake cells there. He may decide to eat any number of times.
Please output the maximum number of cake cells that the cakeminator can eat.
|
```python
r, c = map(int, input().split())
cake = []
for i in range(r):
row = input()
cake.append(list(row))
row_count = 0
col_count = 0
for i in range(r):
has_strawberry = False
for j in range(c):
if cake[i][j] == 'S':
has_strawberry = True
break
if not has_strawberry:
row_count += 1
for j in range(c):
has_strawberry = False
for i in range(r):
if cake[i][j] == 'S':
has_strawberry = True
break
if not has_strawberry:
col_count += 1
max_cells = row_count * c + col_count * (r - row_count)
print(max_cells)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The nation of Panel holds an annual show called The Number Games, where each district in the nation will be represented by one contestant.
The nation has $n$ districts numbered from $1$ to $n$, each district has exactly one path connecting it to every other district. The number of fans of a contestant from district $i$ is equal to $2^i$.
This year, the president decided to reduce the costs. He wants to remove $k$ contestants from the games. However, the districts of the removed contestants will be furious and will not allow anyone to cross through their districts.
The president wants to ensure that all remaining contestants are from districts that can be reached from one another. He also wishes to maximize the total number of fans of the participating contestants.
Which contestants should the president remove?
|
```python
from typing import *
V = TypeVar("V")
class graph:
vertices:List[V]
graphDict:Dict[V,Set[V]]
def __init__(self,vertices,graphDict):
self.vertices = vertices
self.graphDict = graphDict
for v in vertices:
if not v in self.graphDict:
self.graphDict[v] = set()
def isEdge(self,a:V,b:V):
return b in self.graphDict[a]
def neighbours(self,a:V)->List[V]:
return self.graphDict.get(a,[])
def appendEdge(self,a:V,b:V):
assert not self.isEdge(a,b)
self.graphDict[a].add(b)
self.graphDict[b].add(a)
def deleteEdge(self,a:V,b:V):
assert self.isEdge(a,b)
self.graphDict[a].remove(b)
self.graphDict[b].remove(a)
def rootedEnumeration(self,root:V):
# Make sure graph is connected
S:Set[V] = set([root])
discovered:Set[V] = set()
decendentDict: Dict[V, List[V]] = dict()
ordering:List[V] = []
while bool(S):
v = S.pop()
if not v in discovered:
discovered.add(v)
ordering.append(v)
decendentDict[v] = self.graphDict[v] - discovered
for n in self.graphDict[v]:
S.add(n)
return decendentDict,ordering
def DFS(self,root:V):
return self.rootedEnumeration(root)[1]
def spanningTree(self,root:V):
decendents,order = self.rootedEnumeration(root)
return rootedTree(root,self.vertices,decendents,order)
@property
def connected(self)->bool:
v = self.vertices[0]
dfs = self.rootedEnumeration(v)
return (len(dfs) == len(self.vertices))
@staticmethod
def typicalTree():
G = graph([1,2,3,4,5],dict())
G.appendEdge(1,3)
G.appendEdge(1,4)
G.appendEdge(4,2)
G.appendEdge(4,5)
return G
#Custom Implementations here
class rootedTree:
vertices:List[V]
root:V
decendents:Dict[V,Set[V]]
parents:Dict[V,V]
order:List[V]
def __init__(self,root,vertices,decendents,order):
self.root = root
self.vertices = vertices
self.decendents = decendents
self.order = order
self.parents = dict()
for v in decendents:
for child in decendents[v]:
self.parents[child] = v
def decendentMax(G:graph,k:int):
T = G.spanningTree(len(G.vertices))
available:List[V] = [v for v in T.vertices if not bool(T.decendents[v])]
eliminated:Set[V] = set()
chosen:List[int] = []
while len(chosen) < k:
taking = min(available)
eliminated.add(taking)
chosen.append(taking)
available.remove(taking)
assert taking != T.root
p = T.parents[taking]
if(eliminated.issuperset(T.decendents[p])):
available.append(p)
assert len(chosen) == k
return chosen
def readInt():
return int(input())
def readLine():
return [int(s) for s in input().split(" ")]
vertices, k = readLine()
newGraph = graph(range(1,vertices+1),dict())
for _ in range(vertices-1):
a,b = readLine()
newGraph.appendEdge(a,b)
chosen = decendentMax(newGraph,k)
chosen.sort()
print(" ".join([str(c) for c in chosen]))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A string is called a *k*-string if it can be represented as *k* concatenated copies of some string. For example, the string "aabaabaabaab" is at the same time a 1-string, a 2-string and a 4-string, but it is not a 3-string, a 5-string, or a 6-string and so on. Obviously any string is a 1-string.
You are given a string *s*, consisting of lowercase English letters and a positive integer *k*. Your task is to reorder the letters in the string *s* in such a way that the resulting string is a *k*-string.
|
```python
k = int(input())
visited = {}
word = input()
for c in word:
if not c in visited:
visited[c] = 0
visited[c] += 1
result = []
for c in visited:
if visited[c] % k == 0:
result.append(c * (visited[c] // k))
else:
print(-1)
exit(0)
print(''.join(result) * k)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given two strings $s$ and $t$. In a single move, you can choose any of two strings and delete the first (that is, the leftmost) character. After a move, the length of the string decreases by $1$. You can't choose a string if it is empty.
For example:
- by applying a move to the string "where", the result is the string "here", - by applying a move to the string "a", the result is an empty string "".
You are required to make two given strings equal using the fewest number of moves. It is possible that, in the end, both strings will be equal to the empty string, and so, are equal to each other. In this case, the answer is obviously the sum of the lengths of the initial strings.
Write a program that finds the minimum number of moves to make two given strings $s$ and $t$ equal.
|
```python
a=str(input())
b=str(input())
ff=0
c=0
for l,i in enumerate(a):
for f,j in enumerate(b):
if(i==j):
ia=l
ib=f
stra=a[ia:]
strb=b[ib:]
if(stra==strb):
ff=ia+ib
c=1
break
if c==1:
break
print(ff)
#EEEEEEEEEEEEEEEEEE
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya has recently bought some land and decided to surround it with a wooden fence.
He went to a company called "Wooden board" that produces wooden boards for fences. Vasya read in the catalog of products that the company has at its disposal *n* different types of wood. The company uses the *i*-th type of wood to produce a board of this type that is a rectangular *a**i* by *b**i* block.
Vasya decided to order boards in this company and build a fence from them. It turned out that the storehouse of the company is so large that Vasya can order arbitrary number of boards of every type. Note that Vasya is allowed to turn the boards as he builds the fence. However, Vasya cannot turn square boards.
Vasya is required to construct a fence of length *l*, however, an arbitrary fence won't do. Vasya wants his fence to look beautiful. We'll say that a fence is beautiful if and only if the following two conditions are fulfilled:
- there are no two successive boards of the same type - the first board of the fence has an arbitrary length, and the length of each subsequent board equals the width of the previous one
In other words, the fence is considered beautiful, if the type of the *i*-th board in the fence is different from the *i*<=-<=1-th board's type; besides, the *i*-th board's length is equal to the *i*<=-<=1-th board's width (for all *i*, starting from 2).
Now Vasya wonders, how many variants of arranging a fence for his land exist. Your task is to count the number of different beautiful fences of length *l*.
Two fences will be considered the same if the corresponding sequences of fence boards types and rotations are the same, otherwise the fences are different. Since the sought number can be large enough, you need to calculate the answer modulo 1000000007 (109<=+<=7).
|
```python
mod = int(1e9+7)
n, len = map(int, input().split())
a = [0] * n
b = [0] * n
f = [[[0] * 2 for i in range(len+1)] for j in range(n)]
for i in range(n):
a[i], b[i] = map(int, input().split())
if a[i] <= len:
f[i][a[i]][0] += 1
if a[i] != b[i] and b[i] <= len:
f[i][b[i]][1] += 1
for i in range(len + 1):
for j in range(n):
for k in range(n):
if j == k: continue
if a[k] == a[j] and i + a[k] <= len:
f[k][i + a[k]][0] += f[j][i][1]
f[k][i + a[k]][0] %= mod
if a[k] == b[j] and i + a[k] <= len:
f[k][i + a[k]][0] += f[j][i][0]
f[k][i + a[k]][0] %= mod
if a[k] == b[k]: continue
if b[k] == a[j] and i + b[k] <= len:
f[k][i + b[k]][1] += f[j][i][1]
f[k][i + b[k]][1] %= mod
if b[k] == b[j] and i + b[k] <= len:
f[k][i + b[k]][1] += f[j][i][0]
f[k][i + b[k]][1] %= mod
ans = sum([(f[i][len][0] + f[i][len][1]) % mod for i in range(n)]) % mod
print(ans)
```
|
|
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
import sys,os,io,time,copy,math
from functools import lru_cache
if os.path.exists('input.txt'):
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
def is_sorted(arr):
if all(arr[i]<=arr[i+1] for i in range(len(arr)-1)):
return True
else:
return False
def main():
a,b,n=map(int,input().split())
if b<=10:
a1=-1
for i in range(10):
a1=a*10+i
if a1&b==0:
break
if a1==-1:
print(-1)
else:
print(a1,end="")
for i in range(n-2):
print(b,end="")
print("")
else:
a1=-1
for i in range(10):
a1=a*10+i
if a1&b==0:
break
print(a1)
main()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Once Bob needed to find the second order statistics of a sequence of integer numbers. Lets choose each number from the sequence exactly once and sort them. The value on the second position is the second order statistics of the given sequence. In other words it is the smallest element strictly greater than the minimum. Help Bob solve this problem.
|
```python
i = int(input())
l = [int(x) for x in input().split()]
l = sorted(set(l))
if len(l)==1:
print('NO')
else:
print(l[1])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
As technologies develop, manufacturers are making the process of unlocking a phone as user-friendly as possible. To unlock its new phone, Arkady's pet dog Mu-mu has to bark the password once. The phone represents a password as a string of two lowercase English letters.
Mu-mu's enemy Kashtanka wants to unlock Mu-mu's phone to steal some sensible information, but it can only bark *n* distinct words, each of which can be represented as a string of two lowercase English letters. Kashtanka wants to bark several words (not necessarily distinct) one after another to pronounce a string containing the password as a substring. Tell if it's possible to unlock the phone in this way, or not.
|
```python
def solution():
password = input()
num_words = int(input())
words = []
for _ in range(num_words):
words.append(input())
for x in range(num_words):
for y in range(num_words):
possible = words[x] + words[y]
if password in possible:
print('YES')
return
print('NO')
solution()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Someday, Drazil wanted to go on date with Varda. Drazil and Varda live on Cartesian plane. Drazil's home is located in point (0,<=0) and Varda's home is located in point (*a*,<=*b*). In each step, he can move in a unit distance in horizontal or vertical direction. In other words, from position (*x*,<=*y*) he can go to positions (*x*<=+<=1,<=*y*), (*x*<=-<=1,<=*y*), (*x*,<=*y*<=+<=1) or (*x*,<=*y*<=-<=1).
Unfortunately, Drazil doesn't have sense of direction. So he randomly chooses the direction he will go to in each step. He may accidentally return back to his house during his travel. Drazil may even not notice that he has arrived to (*a*,<=*b*) and continue travelling.
Luckily, Drazil arrived to the position (*a*,<=*b*) successfully. Drazil said to Varda: "It took me exactly *s* steps to travel from my house to yours". But Varda is confused about his words, she is not sure that it is possible to get from (0,<=0) to (*a*,<=*b*) in exactly *s* steps. Can you find out if it is possible for Varda?
|
```python
a,b,s =map(int,input().split())
x = abs(a) + abs(b)
print("NO" if s<x or (s-x)%2 else "YES")
```
|
|
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,n=map(int,input().split())
k=True
v=str(a)
for i in range(n):
c=-1
for j in range(9,-1,-1):
if int(v+str(j))%b==0:
c=j
break
if c==-1:
k=False
break
else:
v+=str(c)
if k:
print(v)
else:
print(-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given *n* points on a plane. All points are different.
Find the number of different groups of three points (*A*,<=*B*,<=*C*) such that point *B* is the middle of segment *AC*.
The groups of three points are considered unordered, that is, if point *B* is the middle of segment *AC*, then groups (*A*,<=*B*,<=*C*) and (*C*,<=*B*,<=*A*) are considered the same.
|
```python
def binser(mas, val):
first = 0
last = len(mas) - 1
index = -1
while (first <= last) and (index == -1):
mid = (first + last) // 2
if mas[mid] == val:
index = mid
else:
if val < mas[mid]:
last = mid - 1
else:
first = mid + 1
return index
koor = []
k_mid = 0
n = int(input())
for i in range(n):
koor.append(list(map(int, input().split())))
koor.sort()
for i in range(n - 1):
for j in range(i + 2, n):
e = (koor[i][0] + koor[j][0]) / 2
if (e - int(e)) == 0:
f = (koor[i][1] + koor[j][1]) / 2
if (f - int(f)) == 0:
if -1 != binser(koor[i + 1:j], [e, f]):
k_mid += 1
print(k_mid)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Valera is a lazy student. He has *m* clean bowls and *k* clean plates.
Valera has made an eating plan for the next *n* days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can eat dishes of the first type from bowls and dishes of the second type from either bowls or plates.
When Valera finishes eating, he leaves a dirty plate/bowl behind. His life philosophy doesn't let him eat from dirty kitchenware. So sometimes he needs to wash his plate/bowl before eating. Find the minimum number of times Valera will need to wash a plate/bowl, if he acts optimally.
|
```python
n,m,k=input.split()
n=int(n)
m=int(m)
k=int(k)
washed=0
for i in range(n):
a=int(input())
if a==1:
if m>0:
m=m-1
else:
washed=washed+1
elif a==2:
if k>0:
k=k-1
elif k<=0 and m>0:
m=m-1
else:
washed=washed+1
print(washed)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
In Arcady's garden there grows a peculiar apple-tree that fruits one time per year. Its peculiarity can be explained in following way: there are *n* inflorescences, numbered from 1 to *n*. Inflorescence number 1 is situated near base of tree and any other inflorescence with number *i* (*i*<=><=1) is situated at the top of branch, which bottom is *p**i*-th inflorescence and *p**i*<=<<=*i*.
Once tree starts fruiting, there appears exactly one apple in each inflorescence. The same moment as apples appear, they start to roll down along branches to the very base of tree. Each second all apples, except ones in first inflorescence simultaneously roll down one branch closer to tree base, e.g. apple in *a*-th inflorescence gets to *p**a*-th inflorescence. Apples that end up in first inflorescence are gathered by Arcady in exactly the same moment. Second peculiarity of this tree is that once two apples are in same inflorescence they annihilate. This happens with each pair of apples, e.g. if there are 5 apples in same inflorescence in same time, only one will not be annihilated and if there are 8 apples, all apples will be annihilated. Thus, there can be no more than one apple in each inflorescence in each moment of time.
Help Arcady with counting number of apples he will be able to collect from first inflorescence during one harvest.
|
```python
from collections import Counter,UserString
import sys
import threading
sys.setrecursionlimit(10000000)
try:
pass
#sys.stdin=open('test','r')
except:
pass
def main():
n=int(input())
a=[0,-1]+list(map(int,input().split()))
b=[[] for i in range(n+1)]
for i in range(2,n+1):
b[a[i]].append(i)
a.clear()
d=[0 for i in range(n)]
def dfs(i,l):
d[l]=d[l]+1
for i0 in b[i]:
dfs(i0,l+1)
def deff(a):
return a%2
dfs(1,0)
print(sum(list(map(deff,d))))
threading.stack_size=10000000
th=threading.Thread(target=main)
th.run()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One fine October day a mathematics teacher Vasily Petrov went to a class and saw there *n* pupils who sat at the desks, two people at each desk. Vasily quickly realized that number *n* is even. Like all true mathematicians, Vasily has all students numbered from 1 to *n*.
But Vasily Petrov did not like the way the children were seated at the desks. According to him, the students whose numbers differ by 1, can not sit together, as they talk to each other all the time, distract others and misbehave.
On the other hand, if a righthanded student sits at the left end of the desk and a lefthanded student sits at the right end of the desk, they hit elbows all the time and distract each other. In other cases, the students who sit at the same desk, do not interfere with each other.
Vasily knows very well which students are lefthanders and which ones are righthanders, and he asks you to come up with any order that meets these two uncomplicated conditions (students do not talk to each other and do not bump their elbows). It is guaranteed that the input is such that at least one way to seat the students always exists.
|
```python
fr = open('input.txt','r')
students = int(fr.readline())
text = fr.readline()
print(students)
print(text)
fw = open("output.txt","w")
fw.write("Ay 7AGA")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Kolya is going to make fresh orange juice. He has *n* oranges of sizes *a*1,<=*a*2,<=...,<=*a**n*. Kolya will put them in the juicer in the fixed order, starting with orange of size *a*1, then orange of size *a*2 and so on. To be put in the juicer the orange must have size not exceeding *b*, so if Kolya sees an orange that is strictly greater he throws it away and continues with the next one.
The juicer has a special section to collect waste. It overflows if Kolya squeezes oranges of the total size strictly greater than *d*. When it happens Kolya empties the waste section (even if there are no more oranges) and continues to squeeze the juice. How many times will he have to empty the waste section?
|
```python
a, b, d = map(int, input().split())
arr = list(map(int, input().split()))
ans = 0
bin = 0
for n in arr:
if n <= b:
bin += n
if bin > d:
ans += 1
bin = 0
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
This winter is so cold in Nvodsk! A group of *n* friends decided to buy *k* bottles of a soft drink called "Take-It-Light" to warm up a bit. Each bottle has *l* milliliters of the drink. Also they bought *c* limes and cut each of them into *d* slices. After that they found *p* grams of salt.
To make a toast, each friend needs *nl* milliliters of the drink, a slice of lime and *np* grams of salt. The friends want to make as many toasts as they can, provided they all drink the same amount. How many toasts can each friend make?
|
```python
n, k, l, c, d, p, nl, np = list(map(int, input().split()))
totML = k * l
totLP = c * d
toastML = totML // nl
totSalt = p // np
print(min(toastML, totLP, totSalt) // n)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Mahmoud has *n* line segments, the *i*-th of them has length *a**i*. Ehab challenged him to use exactly 3 line segments to form a non-degenerate triangle. Mahmoud doesn't accept challenges unless he is sure he can win, so he asked you to tell him if he should accept the challenge. Given the lengths of the line segments, check if he can choose exactly 3 of them to form a non-degenerate triangle.
Mahmoud should use exactly 3 line segments, he can't concatenate two line segments or change any length. A non-degenerate triangle is a triangle with positive area.
|
```python
#accumalated 2d matrix
# listy=[list(accumulate(row)) for row in accumulate([[i for i in list(map(int,input().split()))] for j in range(n)])]
import sys
input = lambda: sys.stdin.readline().rstrip()
x=int(input())
listy=list(map(int,input().split()))
listy.sort()
check =0
for i in range(0,x-2,3):
if((listy[i]+listy[i+1])>=listy[i+2]):
check =1
break
if(check):
print("YES")
else :
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A group of *n* friends enjoys playing popular video game Toda 2. There is a rating system describing skill level of each player, initially the rating of the *i*-th friend is *r**i*.
The friends decided to take part in the championship as a team. But they should have equal ratings to be allowed to compose a single team consisting of all *n* friends. So the friends are faced with the problem: how to make all their ratings equal.
One way to change ratings is to willingly lose in some matches. Friends can form a party consisting of two to five (but not more than *n*) friends and play a match in the game. When the party loses, the rating of each of its members decreases by 1. A rating can't become negative, so *r**i*<==<=0 doesn't change after losing.
The friends can take part in multiple matches, each time making a party from any subset of friends (but remember about constraints on party size: from 2 to 5 members).
The friends want to make their ratings equal but as high as possible.
Help the friends develop a strategy of losing the matches so that all their ratings become equal and the resulting rating is maximum possible.
|
```python
# coding=utf-8
"""Codeforces 730a solution."""
from operator import itemgetter
class CodeforcesTask730ASolution:
def __init__(self):
self.result = ''
self.players = 0
self.rating = []
def read_input(self):
self.players = int(input())
self.rating = [int(x) for x in input().split(" ")]
def process_task(self):
if self.players > 2:
moves = []
players = [[x + 1, self.rating[x]] for x in range(self.players)]
players.sort(key=itemgetter(1), reverse=True)
while players[1][1] != players[-1][1]:
players[0][1] = max(0, players[0][1] - 1)
players[1][1] = max(0, players[1][1] - 1)
moves.append([players[0][0], players[1][0]])
players.sort(key=itemgetter(1), reverse=True)
if players[0][1] != players[-1][1]:
added = False
for m in moves:
if not players[0][0] in m:
m.append(players[0][0])
players[0][1] = max(0, players[0][1] - 1)
added = True
break
if not added:
#print("edge case 1")
#print(players)
moves.append([players[-1][0], players[0][0]])
players[0][1] = max(0, players[0][1] - 1)
players[-1][1] = max(0, players[-1][1] - 1)
while players[0][1] != players[-1][1]:
players[0][1] = max(0, players[0][1] - 1)
players[1][1] = max(0, players[1][1] - 1)
moves.append([players[0][0], players[1][0]])
players.sort(key=itemgetter(1), reverse=True)
if players[0][1] != players[-1][1]:
added = False
for m in moves:
if not players[0][0] in m:
m.append(players[0][0])
players[0][1] = max(0, players[0][1] - 1)
added = True
break
if not added:
#print(players)
print("edge case 2")
players.sort(key=itemgetter(1), reverse=True)
print(players[-1][1])
print(len(moves))
for m in moves:
print("".join(["1" if x + 1 in m else "0" for x in range(self.players)]))
else:
if self.rating[0] == self.rating[1]:
print(self.rating[0])
print("0")
else:
print("0")
for x in range(max(self.rating)):
print("11")
def get_result(self):
return self.result
if __name__ == "__main__":
Solution = CodeforcesTask730ASolution()
Solution.read_input()
Solution.process_task()
print(Solution.get_result())
```
|
|
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
ca,cb = 0,0
t = int(input())
while t!=0:
a,b = map(int,input().split())
if a>b:
ca = ca + 1
if b>a:
cb = cb + 1
t-=1
if ca > cb:
print("Mishka")
elif cb > ca:
print("Chris")
else:
print("Friendship is magic!^^")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
When Petya went to school, he got interested in large numbers and what they were called in ancient times. For instance, he learned that the Russian word "tma" (which now means "too much to be counted") used to stand for a thousand and "tma tmyschaya" (which literally means "the tma of tmas") used to stand for a million.
Petya wanted to modernize the words we use for numbers and invented a word petricium that represents number *k*. Moreover, petricium la petricium stands for number *k*2, petricium la petricium la petricium stands for *k*3 and so on. All numbers of this form are called petriciumus cifera, and the number's importance is the number of articles la in its title.
Petya's invention brought on a challenge that needed to be solved quickly: does some number *l* belong to the set petriciumus cifera? As Petya is a very busy schoolboy he needs to automate the process, he asked you to solve it.
|
```python
from math import log
n = int(input())
l = int(input())
s = int(log(l,n))
y = s+1
if n**s==l:
print("YES")
print(s-1)
elif n**y==l:
print("YES")
print(y-1)
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Now Fox Ciel becomes a commander of Tree Land. Tree Land, like its name said, has *n* cities connected by *n*<=-<=1 undirected roads, and for any two cities there always exists a path between them.
Fox Ciel needs to assign an officer to each city. Each officer has a rank — a letter from 'A' to 'Z'. So there will be 26 different ranks, and 'A' is the topmost, so 'Z' is the bottommost.
There are enough officers of each rank. But there is a special rule must obey: if *x* and *y* are two distinct cities and their officers have the same rank, then on the simple path between *x* and *y* there must be a city *z* that has an officer with higher rank. The rule guarantee that a communications between same rank officers will be monitored by higher rank officer.
Help Ciel to make a valid plan, and if it's impossible, output "Impossible!".
|
```python
Print("I am jocking");;;
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Two boys decided to compete in text typing on the site "Key races". During the competition, they have to type a text consisting of *s* characters. The first participant types one character in *v*1 milliseconds and has ping *t*1 milliseconds. The second participant types one character in *v*2 milliseconds and has ping *t*2 milliseconds.
If connection ping (delay) is *t* milliseconds, the competition passes for a participant as follows:
1. Exactly after *t* milliseconds after the start of the competition the participant receives the text to be entered. 1. Right after that he starts to type it. 1. Exactly *t* milliseconds after he ends typing all the text, the site receives information about it.
The winner is the participant whose information on the success comes earlier. If the information comes from both participants at the same time, it is considered that there is a draw.
Given the length of the text and the information about participants, determine the result of the game.
|
```python
x,y,z,w=map(int,input().split())
p=max(x,y,z,w)
if (p-x)!=0:
print(p-x,end=' ')
if (p-y)!=0:
print(p-y,end=' ')
if (p-z)!=0:
print(p-z,end=' ')
if (p-w)!=0:
print(p-w,end=' ')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There is a very secret base in Potatoland where potato mash is made according to a special recipe. The neighbours from Porridgia decided to seize this recipe and to sell it to Pilauland. For this mission they have been preparing special agent Pearlo for many years. When, finally, Pearlo learned all secrets of espionage, he penetrated into the Potatoland territory and reached the secret base.
Now he is standing at the entrance, but to get inside he need to pass combination lock. Minute ago one of the workers entered the password on the terminal and opened the door. The terminal is a square digital keyboard 3<=×<=3 with digits from 1 to 9.
Pearlo knows that the password consists from distinct digits and is probably symmetric with respect to the central button of the terminal. He has heat sensor which allowed him to detect the digits which the worker pressed. Now he wants to check whether the password entered by the worker is symmetric with respect to the central button of the terminal. This fact can Help Pearlo to reduce the number of different possible password combinations.
|
```python
str1=""
for i in range(3):
str1+=input()
if str1==str1[::-1]:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Arkady wants to water his only flower. Unfortunately, he has a very poor watering system that was designed for $n$ flowers and so it looks like a pipe with $n$ holes. Arkady can only use the water that flows from the first hole.
Arkady can block some of the holes, and then pour $A$ liters of water into the pipe. After that, the water will flow out from the non-blocked holes proportionally to their sizes $s_1, s_2, \ldots, s_n$. In other words, if the sum of sizes of non-blocked holes is $S$, and the $i$-th hole is not blocked, $\frac{s_i \cdot A}{S}$ liters of water will flow out of it.
What is the minimum number of holes Arkady should block to make at least $B$ liters of water flow out of the first hole?
|
```python
import sys
import math
#to read string
get_string = lambda: sys.stdin.readline().strip()
#to read list of integers
get_int_list = lambda: list( map(int,sys.stdin.readline().strip().split()) )
#to read integers
get_int = lambda: int(sys.stdin.readline())
#to print fast
pt = lambda x: sys.stdout.write(str(x)+'\n')
#--------------------------------WhiteHat010--------------------------------------#
n,a,b = get_int_list()
lst = get_int_list()
s = a*(lst[0])/b
l = sorted(lst[1:])
total = lst[0]
count = 1
for i in l:
if total+i <= s:
total += i
count += 1
else:
break
print(n-count)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There is a given string *S* consisting of *N* symbols. Your task is to find the number of ordered pairs of integers *i* and *j* such that
1. 1<=≤<=*i*,<=*j*<=≤<=*N*
2. *S*[*i*]<==<=*S*[*j*], that is the *i*-th symbol of string *S* is equal to the *j*-th.
|
```python
s = str(input())
list1 = []
sum = 0
for x in s:
if x not in list1:
list1.append(x)
if s.count(x) > 1:
sum += (s.count(x) * s.count(x))
if sum == 0:
print(len(s))
else:
print(sum)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to *m*) at the end of the game, than wins the one of them who scored at least *m* points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points.
|
```python
import sys
#from math import gcd
#from bisect import bisect_left, bisect_right
read_line = lambda: sys.stdin.readline().strip()
read_intmap = lambda: map(int, read_line().split())
def testCase():
n = int(input())
players = dict()
for ind in range(1, n + 1):
name, score = read_line().split()
score = int(score)
if not name in players:
players[name] = [0, {0:0}] #curr score, rounds at which score acheived
curr, rec = players[name]
curr += score
if not curr in rec:
rec[curr] = ind
players[name] = [curr, rec]
maxScore = max([v[0] for k,v in players.items()])
minInd = n + 100
winner = None
for k,v in players.items():
rec = v[1]
tmpInd = 1e9
for k2, v2 in rec.items():
if k2 >= maxScore and v2 < tmpInd:
tmpInd = v2
if tmpInd < minInd:
minInd = tmpInd
winner = k
print(winner)
t = 1
#t = int(input())
for i in range(t):
testCase()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Greatest common divisor *GCD*(*a*,<=*b*) of two positive integers *a* and *b* is equal to the biggest integer *d* such that both integers *a* and *b* are divisible by *d*. There are many efficient algorithms to find greatest common divisor *GCD*(*a*,<=*b*), for example, Euclid algorithm.
Formally, find the biggest integer *d*, such that all integers *a*,<=*a*<=+<=1,<=*a*<=+<=2,<=...,<=*b* are divisible by *d*. To make the problem even more complicated we allow *a* and *b* to be up to googol, 10100 — such number do not fit even in 64-bit integer type!
|
```python
start , end = list(map(int ,input().split()))
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
res = start
for i in range(start +1 ,end):
res = gcd(res, i)
print(res)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it?
The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out the name of the company on a piece of paper in a line (horizontally, from left to right) with large English letters, then put this piece of paper in front of the mirror, then the reflection of the name in the mirror should perfectly match the line written on the piece of paper.
There are many suggestions for the company name, so coming up to the mirror with a piece of paper for each name wouldn't be sensible. The founders of the company decided to automatize this process. They asked you to write a program that can, given a word, determine whether the word is a 'mirror' word or not.
|
```python
# https://codeforces.com/contest/421/problem/B
# 1000
def palin(n,k):
for i in range(k//2):
if n[i]!=n[k-i-1]:
return False
return True
s=input()
l=['A','H','W','I','M','Y','X','O','T','U','V']
if palin(s,len(s)):
for i in s:
if i not in l:
print("NO")
exit()
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Polycarpus has a ribbon, its length is *n*. He wants to cut the ribbon in a way that fulfils the following two conditions:
- After the cutting each ribbon piece should have length *a*, *b* or *c*. - After the cutting the number of ribbon pieces should be maximum.
Help Polycarpus and find the number of ribbon pieces after the required cutting.
|
```python
import sys
sys.setrecursionlimit(500000000)
def f(n):
if n in memo.keys():
return memo[n]
ans = float("-inf")
if n == 0:
return 0
for length in l:
if n >= length:
ans = max(ans, 1 + f(n - length))
memo[n] = ans
return ans
memo = dict()
l = list(map(int, input().split()))
n, l = l[0], l[1:]
print(f(n))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There are *n* parliamentarians in Berland. They are numbered with integers from 1 to *n*. It happened that all parliamentarians with odd indices are Democrats and all parliamentarians with even indices are Republicans.
New parliament assembly hall is a rectangle consisting of *a*<=×<=*b* chairs — *a* rows of *b* chairs each. Two chairs are considered neighbouring if they share as side. For example, chair number 5 in row number 2 is neighbouring to chairs number 4 and 6 in this row and chairs with number 5 in rows 1 and 3. Thus, chairs have four neighbours in general, except for the chairs on the border of the hall
We know that if two parliamentarians from one political party (that is two Democrats or two Republicans) seat nearby they spent all time discussing internal party issues.
Write the program that given the number of parliamentarians and the sizes of the hall determine if there is a way to find a seat for any parliamentarian, such that no two members of the same party share neighbouring seats.
|
```python
import sys
n, a, b = map(int, input().split())
if n > a*b:
print(-1)
sys.exit(0)
par = []
for i in range(1, n+1, b):
s = ['0']*b
for j in range(b):
if i+j <= n:
s[j] = str(i+j)
par.append(s)
while len(par) < a:
par.append(['0']*b)
for i in range(a):
if i%2 == 0:
par[i].reverse()
print(' '.join(par[i]))
else:
print(' '.join(par[i]))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.
For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two primes". Let's modify it. How about a statement like that: "each integer no less than 12 can be expressed as the sum of two composite numbers." Not like the Goldbach's conjecture, I can prove this theorem.
You are given an integer *n* no less than 12, express it as a sum of two composite numbers.
|
```python
a=int(input())
if a%2==0:
print('4',a-4)
else:
print('9',a-9)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Karen is getting ready for a new school day!
It is currently hh:mm, given in a 24-hour format. As you know, Karen loves palindromes, and she believes that it is good luck to wake up when the time is a palindrome.
What is the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome?
Remember that a palindrome is a string that reads the same forwards and backwards. For instance, 05:39 is not a palindrome, because 05:39 backwards is 93:50. On the other hand, 05:50 is a palindrome, because 05:50 backwards is 05:50.
|
```python
c = [70, 140, 210, 280, 350, 601, 671, 741, 811, 881, 951, 1202, 1272, 1342, 1412, 1440]
d = input().split(':')
d = int(d[0]) * 60 + int(d[1])
m = 10000
for i in c:
if (i - d) >= 0 and (i - d) <= m:
m = i - d
print(m)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The Elements of Harmony are six supernatural artifacts representing subjective aspects of harmony. They are arguably the most powerful force in Equestria. The inside of Elements of Harmony can be seen as a complete graph with *n* vertices labeled from 0 to *n*<=-<=1, where *n* is a power of two, equal to 2*m*.
The energy in Elements of Harmony is in constant movement. According to the ancient book, the energy of vertex *u* in time *i* (*e**i*[*u*]) equals to:
Here *b*[] is the transformation coefficient — an array of *m*<=+<=1 integers and *f*(*u*,<=*v*) is the number of ones in the binary representation of number (*u* *xor* *v*).
Given the transformation coefficient and the energy distribution at time 0 (*e*0[]). Help Twilight Sparkle predict the energy distribution at time *t* (*e**t*[]). The answer can be quite large, so output it modulo *p*.
|
```python
def Bit(n) :
cnt = 0
while n :
if n & 1 : cnt += 1
n >>= 1
return cnt
b = [];
tmp = input().split();
m = int(tmp[0]); t = int(tmp[1]); kMod = int(tmp[2]);
n = 1 << m
a = input().split()
for i in range(n) : a[i] = int(a[i])
for i in range(n) : b.append(0)
v = input().split()
for i in range(m + 1) : v[i] = int(v[i])
for i in range(n) : b[i] = v[Bit(i)]
kMod <<= m
def Pow(a, b) :
ans = 1
while b :
if b & 1 : ans = ans * a % kMod
a = a * a % kMod
b >>= 1
return ans;
i = 2
while i <= n :
for j in range(0, n, i) :
for k in range(j, j + (i >> 1)) :
tx = (a[k] + a[k + (i >> 1)]) % kMod
ty = (kMod + a[k] - a[k + (i >> 1)]) % kMod
a[k] = tx; a[k + (i >> 1)] = ty
i <<= 1
i = 2
while i <= n :
for j in range(0, n, i) :
for k in range(j, j + (i >> 1)) :
tx = (b[k] + b[k + (i >> 1)]) % kMod
ty = (kMod + b[k] - b[k + (i >> 1)]) % kMod
b[k] = tx; b[k + (i >> 1)] = ty
i <<= 1
for i in range(n) : a[i] = a[i] * Pow(b[i], t) % kMod
i = 2
while i <= n :
for j in range(0, n, i) :
for k in range(j, j + (i >> 1)) :
tx = (a[k] + a[k + (i >> 1)]) % kMod
ty = (kMod + a[k] - a[k + (i >> 1)]) % kMod
a[k] = tx; a[k + (i >> 1)] = ty
i <<= 1
for i in range(n) : a[i] >>= m
kMod >>= m
for i in range(n) : print(a[i] % kMod)
```
|
|
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
def domino_piling(m: int, n: int) -> int:
return int((m * n) / 2)
if __name__ == '__main__':
[m, n] = [int(s) for s in input().split()]
print(domino_piling(m, n))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You've got array *a*[1],<=*a*[2],<=...,<=*a*[*n*], consisting of *n* integers. Count the number of ways to split all the elements of the array into three contiguous parts so that the sum of elements in each part is the same.
More formally, you need to find the number of such pairs of indices *i*,<=*j* (2<=≤<=*i*<=≤<=*j*<=≤<=*n*<=-<=1), that .
|
```python
n = int(input())
arr = [0]*n
temp = 0
inp = input().split()
for i in range(n):
arr[i] = int(inp[i])
temp += arr[i]
arr[i] = temp
if temp%3 != 0:
print(0)
exit()
first = 0
second = 0
third = 0
if temp == 0:
for i in arr:
if i == 0:
first += 1
print(first*(first-1)*(first-2)//6)
exit()
for i in arr:
if i == temp/3:
first += 1
elif i == (temp/3)*2:
second += 1
elif i == temp:
third += 1
print(first*second*third)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Pig is visiting a friend.
Pig's house is located at point 0, and his friend's house is located at point *m* on an axis.
Pig can use teleports to move along the axis.
To use a teleport, Pig should come to a certain point (where the teleport is located) and choose where to move: for each teleport there is the rightmost point it can move Pig to, this point is known as the limit of the teleport.
Formally, a teleport located at point *x* with limit *y* can move Pig from point *x* to any point within the segment [*x*;<=*y*], including the bounds.
Determine if Pig can visit the friend using teleports only, or he should use his car.
|
```python
li = []
n, m = map(int, input().split())
for i in range(n):
a, b = map(int, input().split())
li.append([a, b])
li.sort()
i = 0
while len(li) != 1 and li[i][1] >= li[i + 1][0]:
li[i][1] = max(li[i][1], li[i + 1][1])
del li[i + 1]
if len(li) == 0 and m == 0:
print("YES")
elif len(li) == 1 and li[-1][-1] >= m and li[-1][0] == 0:
print("YES")
else:
print("NO")
```
|
|
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
w = input()
s = 0
for i in w:
s += 1
try:
w = int(w)
quit()
except:
if s>=10:
print(w[0]+str(s-2)+w[-1])
else:print(w)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A rare article in the Internet is posted without a possibility to comment it. On a Polycarp's website each article has comments feed.
Each comment on Polycarp's website is a non-empty string consisting of uppercase and lowercase letters of English alphabet. Comments have tree-like structure, that means each comment except root comments (comments of the highest level) has exactly one parent comment.
When Polycarp wants to save comments to his hard drive he uses the following format. Each comment he writes in the following format:
- at first, the text of the comment is written; - after that the number of comments is written, for which this comment is a parent comment (i. e. the number of the replies to this comments); - after that the comments for which this comment is a parent comment are written (the writing of these comments uses the same algorithm).
For example, if the comments look like:
then the first comment is written as "hello,2,ok,0,bye,0", the second is written as "test,0", the third comment is written as "one,1,two,2,a,0,b,0". The whole comments feed is written as: "hello,2,ok,0,bye,0,test,0,one,1,two,2,a,0,b,0". For a given comments feed in the format specified above print the comments in a different format:
- at first, print a integer *d* — the maximum depth of nesting comments; - after that print *d* lines, the *i*-th of them corresponds to nesting level *i*; - for the *i*-th row print comments of nesting level *i* in the order of their appearance in the Policarp's comments feed, separated by space.
|
```python
def find_depth(line,depth,tree):
if(len(tree) < depth):
branch = list()
tree.append(branch)
tree[depth-1].append(line[0])
if(int(line[1]) == 0):
if(len(line)>0):
return [1,1,line[2:]]
else:
return [1,1]
else:
a = list()
length = int()
temp_line = line[2:]
for i in range(0,int(line[1])):
ans = find_depth(temp_line,depth+1,tree)
a.append(ans[0])
length += ans[1]
temp_line = ans[2]
return [max(a)+1,length+1,temp_line]
text = input().split(',')
total_word = int(len(text)/2)
max_depth = 1
depth = 1
tree = list()
temp_line = text[:]
while(total_word > 0):
ans = find_depth(temp_line,depth,tree)
max_depth = max(max_depth, ans[0])
temp_line = ans[2]
total_word -= ans[1]
print(max_depth)
for x in tree:
print(' '.join(str(y) for y in x))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them.
Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain number of words "WUB" before the first word of the song (the number may be zero), after the last word (the number may be zero), and between words (at least one between any pair of neighbouring words), and then the boy glues together all the words, including "WUB", in one string and plays the song at the club.
For example, a song with words "I AM X" can transform into a dubstep remix as "WUBWUBIWUBAMWUBWUBX" and cannot transform into "WUBWUBIAMWUBX".
Recently, Petya has heard Vasya's new dubstep track, but since he isn't into modern music, he decided to find out what was the initial song that Vasya remixed. Help Petya restore the original song.
|
```python
s = input()
ans = s.replace("WUB", " ").strip() #strip removes spaces at the beginning and end of the string
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given *n* numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given *n* numbers finds one that is different in evenness.
|
```python
n = int(input())
line = list(map(int, input().split()))
i = 0
j = 1
k = 2
if (line[0] % 2 == 0) and (line[1] % 2 == 0):
while k < n:
if (line[k] % 2 != 0):
print(k+1)
break
k += 1
elif ((line[0] % 2 != 0) or (line[1] % 2 == 0)) or ((line[0] % 2 == 0) or (line[1] % 2 != 0)):
while j < 2:
x = 1
if line[j-1] % 2 != 0:
print(x)
break
x += 1
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Mikhail walks on a 2D plane. He can go either up or right. You are given a sequence of Mikhail's moves. He thinks that this sequence is too long and he wants to make it as short as possible.
In the given sequence moving up is described by character U and moving right is described by character R. Mikhail can replace any pair of consecutive moves RU or UR with a diagonal move (described as character D). After that, he can go on and do some other replacements, until there is no pair of consecutive moves RU or UR left.
Your problem is to print the minimum possible length of the sequence of moves after the replacements.
|
```python
1. y=int(input())
2. txt=input()
3. n=len(txt)
4. D=['RU','UR']
5. i=0
6. while i < y-1:
7. if txt[i]+txt[i+1] in D:
8. n=n-1
9. i=i+2
10. else:
11. i=i+1
12. print(n)
```
|
|
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()
count = 0
for c in s:
if c in "aeiou":
count+=1
if c in "13579":
count += 1
print(count)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A family consisting of father bear, mother bear and son bear owns three cars. Father bear can climb into the largest car and he likes it. Also, mother bear can climb into the middle car and she likes it. Moreover, son bear can climb into the smallest car and he likes it. It's known that the largest car is strictly larger than the middle car, and the middle car is strictly larger than the smallest car.
Masha came to test these cars. She could climb into all cars, but she liked only the smallest car.
It's known that a character with size *a* can climb into some car with size *b* if and only if *a*<=≤<=*b*, he or she likes it if and only if he can climb into this car and 2*a*<=≥<=*b*.
You are given sizes of bears and Masha. Find out some possible integer non-negative sizes of cars.
|
```python
pai, mae, filho, maria = [int(x) for x in input().split(' ')]
def solve():
if filho > 2*maria or maria > 2*filho or maria >= mae:
return -1
if filho > maria:
return max(pai, 2*maria + 2), max(mae, 2*maria + 1), filho
return max(pai, 2*maria + 2), max(mae, 2*maria + 1), maria
x = solve()
if x == -1:
print(-1)
else:
print(x[0])
print(x[1])
print(x[2])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vanya got an important task — he should enumerate books in the library and label each book with its number. Each of the *n* books should be assigned with a number from 1 to *n*. Naturally, distinct books should be assigned distinct numbers.
Vanya wants to know how many digits he will have to write down as he labels the books.
|
```python
from sys import stdin, stdout
import math
n=int(stdin.readline())
i=0
j=1
ans=0
final=9*pow(10,i)
if(n<=9):
ans=n
else:
while(n>final):
n = n - final
ans+=final*j
j+=1
i+=1
final = 9 * pow(10, i)
ans+=n*j
stdout.write(str(ans)+"\n")
```
|
|
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
l=0
m=0
for i in range(int(input())):
a,b=map(int,input().split())
if a>b:
l=l+1
elif b>a:
m=m+1
if l>m:
print("Miskha")
elif(l<m):
print("Chris")
else:
print("Friendship is magic!^^")
```
|
|
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(float, input().split())
mid = 0.0
for i in range(int(m)):
x, d = map(float, input().split())
mid += x * n
if n % 2:
if d > 0:
mid += d * n * (n - 1) / 2.0
else:
mid += (n*n - 1) / 4 * d
else:
if d > 0:
mid += d * n * (n - 1) / 2.0
else:
mid += n*n / 4 * d
print("%.15f" % (mid / n))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Greatest common divisor *GCD*(*a*,<=*b*) of two positive integers *a* and *b* is equal to the biggest integer *d* such that both integers *a* and *b* are divisible by *d*. There are many efficient algorithms to find greatest common divisor *GCD*(*a*,<=*b*), for example, Euclid algorithm.
Formally, find the biggest integer *d*, such that all integers *a*,<=*a*<=+<=1,<=*a*<=+<=2,<=...,<=*b* are divisible by *d*. To make the problem even more complicated we allow *a* and *b* to be up to googol, 10100 — such number do not fit even in 64-bit integer type!
|
```python
a , b = map(int, input().split())
def gcd(a,b):
if b < a:
a , b = b, a
if b%a == 0:
return a
return gcd(a,b%a)
print(gcd(a,b))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vitya has just started learning Berlanese language. It is known that Berlanese uses the Latin alphabet. Vowel letters are "a", "o", "u", "i", and "e". Other letters are consonant.
In Berlanese, there has to be a vowel after every consonant, but there can be any letter after any vowel. The only exception is a consonant "n"; after this letter, there can be any letter (not only a vowel) or there can be no letter at all. For example, the words "harakiri", "yupie", "man", and "nbo" are Berlanese while the words "horse", "king", "my", and "nz" are not.
Help Vitya find out if a word $s$ is Berlanese.
|
```python
n=input()+"*"
s="Yes"
for i in range(len(s)-1):
if n[i] not in "aeiou" and n[i+1] not in "aeiou":
s="No"
else:
s="Yes"
print(s)
```
|
|
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
z = 0
m = input()
ls = ['h', 'e', 'l', 'l', 'o']
for i in range(len(m)):
if len(ls) == 0:
tm="YES"
break
if ls[0] == m[i]:
ls.remove(ls[0])
if len(ls) == 0:
tm = "YES"
if len(ls) != 0:
tm = "NO"
print(tm)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw.
The first player wrote number *a*, the second player wrote number *b*. How many ways to throw a dice are there, at which the first player wins, or there is a draw, or the second player wins?
|
```python
import math
a,b=map(int,input().split())
x=y=z=0
for n in range(1,7):
if math.fabs(n-a)>math.fabs(n-b):
x+=1
elif math.fabs(n-a)<math.fabs(n-b):
y+=1
else:
z+=1
print(y,z,x)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
DZY has a hash table with *p* buckets, numbered from 0 to *p*<=-<=1. He wants to insert *n* numbers, in the order they are given, into the hash table. For the *i*-th number *x**i*, DZY will put it into the bucket numbered *h*(*x**i*), where *h*(*x*) is the hash function. In this problem we will assume, that *h*(*x*)<==<=*x* *mod* *p*. Operation *a* *mod* *b* denotes taking a remainder after division *a* by *b*.
However, each bucket can contain no more than one element. If DZY wants to insert an number into a bucket which is already filled, we say a "conflict" happens. Suppose the first conflict happens right after the *i*-th insertion, you should output *i*. If no conflict happens, just output -1.
|
```python
p, n = map(int,input().split())
r, s = 0, {p}
while r < n:
x = int(input())%p
if x in s:
break
r += 1
s |= {x}
print([-1,r+1][r<n])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given several queries. In the *i*-th query you are given a single positive integer *n**i*. You are to represent *n**i* as a sum of maximum possible number of composite summands and print this maximum number, or print -1, if there are no such splittings.
An integer greater than 1 is composite, if it is not prime, i.e. if it has positive divisors not equal to 1 and the integer itself.
|
```python
q = int(input())
a = [4, 6, 8, 9]
for i in range(q):
n = int(input())
c = 0
if n % 2 == 1:
c = 1
n -= 9
if n < 0:
print(-1)
else:
if n % 4 == 0:
c += n // 4
elif n % 4 == 2 and n >= 6:
c += n // 4
else:
c = -1
print(c)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made 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
t = int(input())
for _ in range(t):
s = input()
l = len(s)
if l > 10:
r = s[0] + str(l - 2) + s[l-1]
print(r)
else:
print(s)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya has recently found out what a digital root of a number is and he decided to share his knowledge with you.
Let's assume that *S*(*n*) is the sum of digits of number *n*, for example, *S*(4098)<==<=4<=+<=0<=+<=9<=+<=8<==<=21. Then the digital root of number *n* equals to:
1. *dr*(*n*)<==<=*S*(*n*), if *S*(*n*)<=<<=10; 1. *dr*(*n*)<==<=*dr*(<=*S*(*n*)<=), if *S*(*n*)<=≥<=10.
For example, *dr*(4098)<=<==<=<=*dr*(21)<=<==<=<=3.
Vasya is afraid of large numbers, so the numbers he works with are at most 101000. For all such numbers, he has proved that *dr*(*n*)<=<==<=<=*S*(<=*S*(<=*S*(<=*S*(*n*)<=)<=)<=) (*n*<=≤<=101000).
Now Vasya wants to quickly find numbers with the given digital root. The problem is, he hasn't learned how to do that and he asked you to help him. You task is, given numbers *k* and *d*, find the number consisting of exactly *k* digits (the leading zeroes are not allowed), with digital root equal to *d*, or else state that such number does not exist.
|
```python
k,d=map(int,input().split())
x=1
for i in range(1,k):
x=x*10
print(x*d)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
According to rules of the Berland fashion, a jacket should be fastened by all the buttons except only one, but not necessarily it should be the last one. Also if the jacket has only one button, it should be fastened, so the jacket will not swinging open.
You are given a jacket with *n* buttons. Determine if it is fastened in a right way.
|
```python
n=int(input())
l=list(map(int,input().split()))
if l.count(0)==1 and l[-1]!=0:
print('YES')
else:
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
DZY has a sequence *a*, consisting of *n* integers.
We'll call a sequence *a**i*,<=*a**i*<=+<=1,<=...,<=*a**j* (1<=≤<=*i*<=≤<=*j*<=≤<=*n*) a subsegment of the sequence *a*. The value (*j*<=-<=*i*<=+<=1) denotes the length of the subsegment.
Your task is to find the longest subsegment of *a*, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing.
You only need to output the length of the subsegment you find.
|
```python
from collections import deque
from sys import stdin
lines = deque(line.strip() for line in stdin.readlines())
def nextline():
return lines.popleft()
def types(cast):
return tuple(int(x) for x in nextline().split())
def ints():
return types(int)
def strs():
return nextline().split()
def main():
# lines will now contain all of the input's lines in a list
(n,) = ints()
nums = ints()
if n == 1:
return n
inc = [1]*n
for i in range(1, n):
if nums[i] > nums[i-1]:
inc[i] = inc[i-1]+1
dec = [1]*n
for i in range(n-2, -1, -1):
if nums[i] < nums[i+1]:
dec[i] = dec[i+1]+1
m = max(inc[1], dec[-2])+1
for i in range(1, n-1):
if nums[i-1]+1 < nums[i+1]:
length = inc[i-1]+dec[i+1]+1
if length > m:
m = length
return m
if __name__ == '__main__':
print(main())
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Pashmak decided to give Parmida a pair of flowers from the garden. There are *n* flowers in the garden and the *i*-th of them has a beauty number *b**i*. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty difference is maximal possible!
Your task is to write a program which calculates two things:
1. The maximum beauty difference of flowers that Pashmak can give to Parmida. 1. The number of ways that Pashmak can pick the flowers. Two ways are considered different if and only if there is at least one flower that is chosen in the first way and not chosen in the second way.
|
```python
num = int(input())
flowers = sorted(list(map(int, input().split())))
firstdigit = [e for e in flowers[0:num//2] if e == flowers[0]]
lastdigit = [e for e in flowers[num//2::] if e == flowers[-1]]
difference = lastdigit[0] - firstdigit[0]
print(difference, len(firstdigit)*len(lastdigit))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You can not just take the file and send it. When Polycarp trying to send a file in the social network "Codehorses", he encountered an unexpected problem. If the name of the file contains three or more "x" (lowercase Latin letters "x") in a row, the system considers that the file content does not correspond to the social network topic. In this case, the file is not sent and an error message is displayed.
Determine the minimum number of characters to remove from the file name so after that the name does not contain "xxx" as a substring. Print 0 if the file name does not initially contain a forbidden substring "xxx".
You can delete characters in arbitrary positions (not necessarily consecutive). If you delete a character, then the length of a string is reduced by $1$. For example, if you delete the character in the position $2$ from the string "exxxii", then the resulting string is "exxii".
|
```python
n = int(input())
s = input()
k = ""
for var in s:
if var == "x":
k += "x"
else:
k += " "
cnt = 0
for var in k.split():
cnt += max(0, len(var)-2)
print(cnt)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There are well-known formulas: , , . Also mathematicians found similar formulas for higher degrees.
Find the value of the sum modulo 109<=+<=7 (so you should find the remainder after dividing the answer by the value 109<=+<=7).
|
```python
import sys
input = sys.stdin.readline
n, k = [int(i) for i in input().split()]
N = 10 ** 9 + 7
y = [0]
for i in range(1, k + 2):
y.append((y[-1] + pow(i, k, N)) % N)
if n < k + 2:
print(y[n] % N)
else:
m = k + 2
x = n
modinv = [1] * m
for i in range(2, m):
modinv[i] = (-(N // i) * modinv[N % i]) % N
invfac = [1]
for i in range(1, m):
invfac.append((invfac[-1]* modinv[i]) % N)
invneg_fac = [invfac[i] * (1 - 2 * (i & 1)) for i in range(m)]
xfac_down = [1]
for j in reversed(range(x - (m - 1), x + 1)):
xfac_down.append((xfac_down[-1]* j) % N)
xfac_up = [1]
for j in range(x - (m - 1), x + 1):
xfac_up.append((xfac_up[-1] * j) % N)
s = 0
for i, pr in enumerate(y):
pr = (pr * xfac_down[i]) % N
pr = (pr * xfac_up[m - 1 - i]) % N
pr = (pr * invfac[i]) % N
pr = (pr * invneg_fac[m - i - 1]) % N
s = (s + pr) % N
print(s)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There are *n* pictures delivered for the new exhibition. The *i*-th painting has beauty *a**i*. We know that a visitor becomes happy every time he passes from a painting to a more beautiful one.
We are allowed to arranged pictures in any order. What is the maximum possible number of times the visitor may become happy while passing all pictures from first to last? In other words, we are allowed to rearrange elements of *a* in any order. What is the maximum possible number of indices *i* (1<=≤<=*i*<=≤<=*n*<=-<=1), such that *a**i*<=+<=1<=><=*a**i*.
|
```python
input()
l=list(map(int,input().split()))
l=sorted(l)
count=0
for i in range(0,len(l)-1):
if l[0]<l[i+1]:
count+=1
print(count)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Recall that the bracket sequence is considered regular if it is possible to insert symbols '+' and '1' into it so that the result is a correct arithmetic expression. For example, a sequence "(()())" is regular, because we can get correct arithmetic expression insering symbols '+' and '1': "((1+1)+(1+1))". Also the following sequences are regular: "()()()", "(())" and "()". The following sequences are not regular bracket sequences: ")(", "(()" and "())(()".
In this problem you are given two integers *n* and *k*. Your task is to construct a regular bracket sequence consisting of round brackets with length 2·*n* with total sum of nesting of all opening brackets equals to exactly *k*. The nesting of a single opening bracket equals to the number of pairs of brackets in which current opening bracket is embedded.
For example, in the sequence "()(())" the nesting of first opening bracket equals to 0, the nesting of the second opening bracket equals to 0 and the nesting of the third opening bracket equal to 1. So the total sum of nestings equals to 1.
|
```python
n,m = map(int, input().split())
if m > n*(n - 1)//2:
print('Impossible')
else:
ans = []
cur = 0
acc = 0
for i in range(n):
while cur + acc > m:
ans.append(')')
acc -= 1
ans.append('(')
cur += acc
acc += 1
left_cnt = 0
for i in ans:
if i == '(':
left_cnt += 1
else:
left_cnt -= 1
for i in range(left_cnt):
ans.append(')')
print(''.join(ans))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a set of points on a straight line. Each point has a color assigned to it. For point *a*, its neighbors are the points which don't have any other points between them and *a*. Each point has at most two neighbors - one from the left and one from the right.
You perform a sequence of operations on this set of points. In one operation, you delete all points which have a neighbor point of a different color than the point itself. Points are deleted simultaneously, i.e. first you decide which points have to be deleted and then delete them. After that you can perform the next operation etc. If an operation would not delete any points, you can't perform it.
How many operations will you need to perform until the next operation does not have any points to delete?
|
```python
s = list(input())
k = 0
def check(s):
ind = []
for i, elem in enumerate(s):
if i == 0:
if s[i + 1] != elem:
ind.append(i)
elif i == len(s) - 1:
if s[i - 1] != elem:
ind.append(i)
else:
if s[i + 1] != elem:
ind.append(i)
elif s[i - 1] != elem:
ind.append(i)
return ind
n = 0
while s:
len_now = len(s)
delete = check(s)
for index in delete:
s.pop(index - n)
n += 1
n = 0
if len(s) == len_now:
break
k += 1
print(k)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting.
The game consists of multiple rounds. Its rules are very simple: in each round, a natural number *k* is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's score is multiplied by *k*2, and the loser's score is multiplied by *k*. In the beginning of the game, both Slastyona and Pushok have scores equal to one.
Unfortunately, Slastyona had lost her notepad where the history of all *n* games was recorded. She managed to recall the final results for each games, though, but all of her memories of them are vague. Help Slastyona verify their correctness, or, to put it another way, for each given pair of scores determine whether it was possible for a game to finish with such result or not.
|
```python
n=int(input())
for i in range(n):
a,b=[int(s) for s in input().split()]
l=0
a=a*b
r=10**6+1
while r-l>1:
m=(l+r)//2
k=m**3
if k<a:
l=m+1
elif k>a:
r=m
else:
print('Yes')
break
else:
if l**3==a or r**3==a:
print('Yes')
else:
print('No')
```
|
|
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
x=int(input())
students=""
place=[]
students=raw_input()
student=list(students)
for i in range(x + (x-1)):
place.append(0)
for i in range(x):
for j in range(x + (x-1)):
if student[i]<student[j] and student[i]!=' ' and student[j]!=' ':
place[i]+=1
place[i]+=1
for i in range(x):
print place[i],
```
|
|
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
number = int(input())
net_force = 0
for n in range(0, number):
forces = input().split()
for force in forces:
net_force+=int(force)
if net_force==0:
print("YES")
else:
print("NO")
```
|
|
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
n = int(input())
mx = 0
c = 0
for i in range(n):
a,b = map(int,input().split())
c -= a
c += b
if c > mx:
mx = c
print(mx)
```
|
|
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
enter=list(map(int,input().split()))
re_minute=240-enter[1]
list_of_five=[ x*5 for x in range(1,enter[0]+1)]
res=0
for i in range(0,enter[0]):
if re_minute >= list_of_five[i]:
re_minute=re_minute-list_of_five[i]
res+=1
else:break
print(res)
```
|
|
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
t=int(input())
chk="123456789101112131415"
if t<=21:
print(chk[t-1])
else:
print(chk[(t//2)-1])
```
|
|
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
def f(a,b,x,y):
if a>=b and a%x ==0 and (a*y//x)<=b :
return (a,(a*y//x))
if a<b and b%y ==0 and (b*x//y)<=a :
return (b,(b*x//y))
else:
return (0,0)
a,b,x,y=map(int,input().split())
print(*f(a,b,x,y))
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.