source
stringclasses 3
values | instruction
stringlengths 23
3.97k
| input
stringclasses 1
value | output
stringlengths 1
3.75k
|
---|---|---|---|
MatrixStudio/Codeforces-Python-Submissions
|
Vitaly has an array of *n* distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold:
1. The product of all numbers in the first set is less than zero (<=<<=0). 1. The product of all numbers in the second set is greater than zero (<=><=0). 1. The product of all numbers in the third set is equal to zero. 1. Each number from the initial array must occur in exactly one set.
Help Vitaly. Divide the given array.
|
```python
n=int(input())
l=list(map(int,input().split()))
l1=[]
l2=[]
l3=[]
for i in range(len(l)):
if l[i]<0:
l1.append(l[i])
elif l[i]==0:
l2.append(l[i])
else:
l3.append(l[i])
if len(l1)%2==0:
l2.append(l1[0])
l1=l1[1:]
if len(l3)==0:
l3.append(l1[0])
l1=l1[1:]
l3.append(l1[0])
l1=l1[1:]
l1.insert(0,len(l1))
l2.insert(0,len(l2))
l3.insert(0,len(l3))
for i in l1:
print(i,end=' ')
print()
for i in l3:
print(i,end=' ')
print()
for i in l2:
print(i,end=' ')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
*n* soldiers stand in a circle. For each soldier his height *a**i* is known. A reconnaissance unit can be made of such two neighbouring soldiers, whose heights difference is minimal, i.e. |*a**i*<=-<=*a**j*| is minimal. So each of them will be less noticeable with the other. Output any pair of soldiers that can form a reconnaissance unit.
|
```python
a=int(input())
m=map(int,input().split())
liste=list(m)
sonuclar=[]
cevap=[]
for i in range(a-1):
m=abs(liste[i]-liste[i+1])
sonuclar.append(m)
sonuclar.append(abs(liste[0]-liste[-1]))
for x in range(len(sonuclar)):
if sonuclar[x]==min(sonuclar) and x+1!=len(sonuclar):
cevap.append(str(x+1))
cevap.append(str(x+2))
break
if sonuclar[x]==min(sonuclar) and x+1==len(sonuclar):
cevap.append(str(x + 1))
cevap.append("1")
break
print(cevap[0]+" "+cevap[1])
```
|
|
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
inpu = input()
m = int(inpu.split()[0])
n = int(inpu.split()[1])
s = n*m
print( s//2)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Anastasia loves going for a walk in Central Uzhlyandian Park. But she became uninterested in simple walking, so she began to collect Uzhlyandian pebbles. At first, she decided to collect all the pebbles she could find in the park.
She has only two pockets. She can put at most *k* pebbles in each pocket at the same time. There are *n* different pebble types in the park, and there are *w**i* pebbles of the *i*-th type. Anastasia is very responsible, so she never mixes pebbles of different types in same pocket. However, she can put different kinds of pebbles in different pockets at the same time. Unfortunately, she can't spend all her time collecting pebbles, so she can collect pebbles from the park only once a day.
Help her to find the minimum number of days needed to collect all the pebbles of Uzhlyandian Central Park, taking into consideration that Anastasia can't place pebbles of different types in same pocket.
|
```python
def main():
n, m = map(int, input().split())
print((sum((x + m - 1) // m for x in map(int, input().split())) + 1) // 2)
if __name__ == '__main__':
main()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Valera is a collector. Once he wanted to expand his collection with exactly one antique item.
Valera knows *n* sellers of antiques, the *i*-th of them auctioned *k**i* items. Currently the auction price of the *j*-th object of the *i*-th seller is *s**ij*. Valera gets on well with each of the *n* sellers. He is perfectly sure that if he outbids the current price of one of the items in the auction (in other words, offers the seller the money that is strictly greater than the current price of the item at the auction), the seller of the object will immediately sign a contract with him.
Unfortunately, Valera has only *v* units of money. Help him to determine which of the *n* sellers he can make a deal with.
|
```python
n,v=map(int,input().split())
t=[]
k=[]
for i in range(n):
l=list(map(int,input().split()))
temp=list(l[1:])
temp.sort()
l=[l[0]]+temp
if v>l[1]:
k.append(l[0])
print(len(k))
for i in range(len(k)):
if i==(len(k)-1):
print(k[i])
else:
print(k[i],end=' ')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Luke Skywalker got locked up in a rubbish shredder between two presses. R2D2 is already working on his rescue, but Luke needs to stay alive as long as possible. For simplicity we will assume that everything happens on a straight line, the presses are initially at coordinates 0 and *L*, and they move towards each other with speed *v*1 and *v*2, respectively. Luke has width *d* and is able to choose any position between the presses. Luke dies as soon as the distance between the presses is less than his width. Your task is to determine for how long Luke can stay alive.
|
```python
(a,b,c,d)=input().split()
a=int(a)
b=int(b)
c=int(c)
d=int(c)
x=(b-a)/(c+d)
print(x)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One day in the IT lesson Anna and Maria learned about the lexicographic order.
String *x* is lexicographically less than string *y*, if either *x* is a prefix of *y* (and *x*<=≠<=*y*), or there exists such *i* (1<=≤<=*i*<=≤<=*min*(|*x*|,<=|*y*|)), that *x**i*<=<<=*y**i*, and for any *j* (1<=≤<=*j*<=<<=*i*) *x**j*<==<=*y**j*. Here |*a*| denotes the length of the string *a*. The lexicographic comparison of strings is implemented by operator < in modern programming languages.
The teacher gave Anna and Maria homework. She gave them a string of length *n*. They should write out all substrings of the given string, including the whole initial string, and the equal substrings (for example, one should write out the following substrings from the string "aab": "a", "a", "aa", "ab", "aab", "b"). The resulting strings should be sorted in the lexicographical order. The cunning teacher doesn't want to check all these strings. That's why she said to find only the *k*-th string from the list. Help Anna and Maria do the homework.
|
```python
n=int(input())
l=list(map(int,input().split()))
ones=l.count(1)
two=l.count(2)
three=l.count(3)
four=l.count(4)
sum=four
while(three>0 and ones>0):
three-=1
ones-=1
sum+=1
while three>0:
three-=1
sum+=1
while two>0 and two>2:
two-=2
sum+=1
while two>0 and ones>0:
two-=1
if ones>1:
ones-=2
sum+=1
else:
ones-=1
sum+=1
while two>0:
two-=1
sum+=1
while ones>0:
ones-=1
sum+=1
print(sum)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it:
- deletes all the vowels, - inserts a character "." before each consonant, - replaces all uppercase consonants with corresponding lowercase ones.
Vowels are letters "A", "O", "Y", "E", "U", "I", and the rest are consonants. The program's input is exactly one string, it should return the output as a single string, resulting after the program's processing the initial string.
Help Petya cope with this easy task.
|
```python
string = input()
string = list(string)
vowel = ['a','A','e','E','o','O','i','I','u','U','y','Y']
consonant = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','z']
for i in range(0, len(vowel)):
while(vowel[i] in string):
string.remove(vowel[i])
ans = ""
for i in range(0, len(string)):
ans += str(string[i])
string = ans.lower()
string = list(string)
for i in range(0, len(string)):
if string[i] in consonant:
string[i] = "." + str(string[i])
ans = ""
for i in range(0, len(string)):
ans += str(string[i])
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Johny likes numbers *n* and *k* very much. Now Johny wants to find the smallest integer *x* greater than *n*, so it is divisible by the number *k*.
|
```python
n,k=list(map(int,input().split()))
c=k//n
print(n*(c+1))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.
The pasture is a rectangle consisting of *R*<=×<=*C* cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.
Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.
|
```python
import sys
import math
#to read string
get_string = lambda: sys.stdin.readline().strip()
#to read list of integers
get_list = lambda: list( map(int,sys.stdin.readline().strip().split()) )
#to read integers
get_int = lambda: int(sys.stdin.readline())
#--------------------------------WhiteHat010--------------------------------------#
n,m = get_list()
matrix = []
for i in range(n):
matrix.append(list(get_string()))
flag = True
for i in range(n):
if 'SW' in ''.join(matrix[i]) or 'WS' in ''.join(matrix[i]) :
flag = False
break
if matrix[i][0] == 'S' and matrix[i][1] == '.':
matrix[i][1] = 'D'
if matrix[i][-1] == 'S' and matrix[i][-2] == '.':
matrix[i][-2] = 'D'
for j in range(1,m-1):
if matrix[i][j] == 'S' and matrix[i][j+1] == '.':
matrix[i][j+1] = 'D'
if matrix[i][j] == 'S' and matrix[i][j-1] == '.':
matrix[i][j-1] = 'D'
for j in range(m):
if not flag:
break
temp = matrix[0][j]
for i in range(1,n-1):
temp += matrix[i][j]
if (matrix[i][j] == 'S' and matrix[i+1][j] == '.'):
matrix[i][j+1] = 'D'
if (matrix[i][j] == '.' and matrix[i+1][j] == 'S'):
matrix[i][j] = 'D'
temp += matrix[-1][j]
if 'SW' in temp or "WS" in temp:
flag = False
break
if flag:
print("YES")
for i in range(n):
print(''.join(matrix[i]))
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya is going to the Olympics in the city Ntown by train. The boy wants to read the textbook to prepare for the Olympics. He counted that he needed *k* hours for this. He also found that the light in the train changes every hour. The light is measured on a scale from 0 to 100, where 0 is very dark, and 100 is very light.
Vasya has a train lighting schedule for all *n* hours of the trip — *n* numbers from 0 to 100 each (the light level in the first hour, the second hour and so on). During each of those hours he will either read the whole time, or not read at all. He wants to choose *k* hours to read a book, not necessarily consecutive, so that the minimum level of light among the selected hours were maximum. Vasya is very excited before the upcoming contest, help him choose reading hours.
|
```python
n,k=map(int,input().split())
for i in range(n):
a=list(map(int,input().split()))
b=sorted(a)
c=n-k
print(b[c])
print(1,3,4)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The following problem is well-known: given integers *n* and *m*, calculate
where 2*n*<==<=2·2·...·2 (*n* factors), and denotes the remainder of division of *x* by *y*.
You are asked to solve the "reverse" problem. Given integers *n* and *m*, calculate
|
```python
n=int(input())
m=int(input())
x=2**n
if n>=1 and n<=10**8 and m>=1 and m<=10**8:
print(m%x)
else:
print('error')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
As you may know, MemSQL has American offices in both San Francisco and Seattle. Being a manager in the company, you travel a lot between the two cities, always by plane.
You prefer flying from Seattle to San Francisco than in the other direction, because it's warmer in San Francisco. You are so busy that you don't remember the number of flights you have made in either direction. However, for each of the last *n* days you know whether you were in San Francisco office or in Seattle office. You always fly at nights, so you never were at both offices on the same day. Given this information, determine if you flew more times from Seattle to San Francisco during the last *n* days, or not.
|
```python
input()
s = input()
cur = s[0]
StoF = 0
FtoS = 0
for c in s:
if c != cur:
cur = c
if c == 'F':
StoF += 1
else:
FtoS += 1
if StoF > FtoS:
print("YES")
else:
print("NO")
```
|
|
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
# Domino squares
M,N=input().split()
M=int(M)
N=int(N)
print(int(M*N/2))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Couple Cover, a wildly popular luck-based game, is about to begin! Two players must work together to construct a rectangle. A bag with *n* balls, each with an integer written on it, is placed on the table. The first player reaches in and grabs a ball randomly (all balls have equal probability of being chosen) — the number written on this ball is the rectangle's width in meters. This ball is not returned to the bag, and the second player reaches into the bag and grabs another ball — the number written on this ball is the rectangle's height in meters. If the area of the rectangle is greater than or equal some threshold *p* square meters, the players win. Otherwise, they lose.
The organizers of the game are trying to select an appropriate value for *p* so that the probability of a couple winning is not too high and not too low, but they are slow at counting, so they have hired you to answer some questions for them. You are given a list of the numbers written on the balls, the organizers would like to know how many winning pairs of balls exist for different values of *p*. Note that two pairs are different if either the first or the second ball is different between the two in pair, and two different balls with the same number are considered different.
|
```python
import sys
input = sys.stdin.buffer.readline
n = int(input())
l = 3 * pow(10, 6) + 5
cnt = [0] * l
for i in list(map(int, input().split())):
cnt[i] += 1
c1, c2 = [0] * l, [0] * l
m0 = pow(10, 8)
for i in range(1, l):
ci = cnt[i]
if i * i < l:
j = i * i
c1[j] += ci * (ci - 1) // m0
c2[j] += ci * (ci - 1) % m0
if c2[j] > m0:
c1[j] += 1
c2[j] %= m0
else:
break
j = i * (i + 1)
while j < l:
cj = cnt[j // i]
c1[j] += 2 * ci * cj // m0
c2[j] += 2 * ci * cj % m0
if c2[j] > m0:
c1[j] += 1
c2[j] %= m0
j += i
n0 = n * (n - 1)
for i in range(1, l):
c1[i] += c1[i - 1]
c2[i] += c2[i - 1]
if c2[i] > m0:
c1[i] += 1
c2[i] %= m0
m = int(input())
for i in list(map(int, input().split())):
ans = n0 - (m0 * c1[i - 1] + c2[i - 1])
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vladik is a competitive programmer. This year he is going to win the International Olympiad in Informatics. But it is not as easy as it sounds: the question Vladik face now is to find the cheapest way to get to the olympiad.
Vladik knows *n* airports. All the airports are located on a straight line. Each airport has unique id from 1 to *n*, Vladik's house is situated next to the airport with id *a*, and the place of the olympiad is situated next to the airport with id *b*. It is possible that Vladik's house and the place of the olympiad are located near the same airport.
To get to the olympiad, Vladik can fly between any pair of airports any number of times, but he has to start his route at the airport *a* and finish it at the airport *b*.
Each airport belongs to one of two companies. The cost of flight from the airport *i* to the airport *j* is zero if both airports belong to the same company, and |*i*<=-<=*j*| if they belong to different companies.
Print the minimum cost Vladik has to pay to get to the olympiad.
|
```python
x = input().split()
y = input()
z = []
for i in y:
z.append(i)
if y[int(x[1])-1] == y[int(x[2])-1]:
print('0')
elif y[int(x[1])-1] != y[int(x[2])-1]:
print('1')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a set of *n* vectors on a plane. For each vector you are allowed to multiply any of its coordinates by -1. Thus, each vector *v**i*<==<=(*x**i*,<=*y**i*) can be transformed into one of the following four vectors:
- *v**i*1<==<=(*x**i*,<=*y**i*), - *v**i*2<==<=(<=-<=*x**i*,<=*y**i*), - *v**i*3<==<=(*x**i*,<=<=-<=*y**i*), - *v**i*4<==<=(<=-<=*x**i*,<=<=-<=*y**i*).
You should find two vectors from the set and determine which of their coordinates should be multiplied by -1 so that the absolute value of the sum of the resulting vectors was minimally possible. More formally, you should choose two vectors *v**i*, *v**j* (1<=≤<=*i*,<=*j*<=≤<=*n*,<=*i*<=≠<=*j*) and two numbers *k*1, *k*2 (1<=≤<=*k*1,<=*k*2<=≤<=4), so that the value of the expression |*v**i**k*1<=+<=*v**j**k*2| were minimum.
|
```python
dx = [1,-1,1,-1]
dy = [1,1,-1,-1]
def conv(x,y,idx):
d = (1e18-x)**2 + (1e18-y)**2
ret = []
for i in range(4):
ret.append((d,x*dx[i],y*dy[i],i+1,idx))
return ret
otpt = open(“output.txt”, “w”)
inpt = open("input.txt", "r")
p = []
n = int(inpt.readline())
for i in range(n):
inp = inpt.readline().split()
trt = conv(int(inp[0]),int(inp[1]),i+1)
p.extend(trt)
p.sort()
mn = 1e40
ans1 = (0,0,0,0,0)
ans2 = (0,0,0,0,0)
for i in range(len(p)):
cnt =0
for j in range(i+1,len(p)):
if cnt>100:
break
cnt = cnt + 1
if p[i][4]== p[j][4]:
continue
d = (p[i][1] - p[j][1])**2 + (p[i][2] - p[j][2])**2
if d < mn :
mn = d
ans1 = p[i]
ans2 = p[j]
otpt.write(ans1[4],ans1[3],ans2[4],ans2[4])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Polycarpus likes studying at school a lot and he is always diligent about his homework. Polycarpus has never had any problems with natural sciences as his great-great-grandfather was the great physicist Seinstein. On the other hand though, Polycarpus has never had an easy time with history.
Everybody knows that the World history encompasses exactly *n* events: the *i*-th event had continued from the year *a**i* to the year *b**i* inclusive (*a**i*<=<<=*b**i*). Polycarpus easily learned the dates when each of *n* events started and ended (Polycarpus inherited excellent memory from his great-great-granddad). But the teacher gave him a more complicated task: Polycaprus should know when all events began and ended and he should also find out for each event whether it includes another event. Polycarpus' teacher thinks that an event *j* includes an event *i* if *a**j*<=<<=*a**i* and *b**i*<=<<=*b**j*. Your task is simpler: find the number of events that are included in some other event.
|
```python
import sys
input = lambda: sys.stdin.readline().rstrip()
from heapq import *
N = int(input())
A = []
for _ in range(N):
a,b = map(int, input().split())
A.append((a,b))
A.sort(key=lambda x:x[1])
v = []
ans = 0
for a,b in A:
while v and -v[0]>a:
heappop(v)
ans+=1
heappush(v, (-a))
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in *n* different shops in the city. It's known that the price of one bottle in the shop *i* is equal to *x**i* coins.
Vasiliy plans to buy his favorite drink for *q* consecutive days. He knows, that on the *i*-th day he will be able to spent *m**i* coins. Now, for each of the days he want to know in how many different shops he can buy a bottle of "Beecola".
|
```python
n = int(input())
x = list(map(int, input().split()))
x.sort()
m = int(input())
for i in range(m):
mi = int(input())
l = 0
r = n
while l < r:
mid = (l + r) // 2
if x[mid] <= mi:
l = mid + 1
else:
r = mid
print(l)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Карта звёздного неба представляет собой прямоугольное поле, состоящее из *n* строк по *m* символов в каждой строке. Каждый символ — это либо «.» (означает пустой участок неба), либо «*» (означает то, что в этом месте на небе есть звезда).
Новое издание карты звёздного неба будет напечатано на квадратных листах, поэтому требуется найти минимально возможную сторону квадрата, в который могут поместиться все звезды. Границы искомого квадрата должны быть параллельны сторонам заданного прямоугольного поля.
|
```python
n, m = list(map(int, input().split()))
lst = []
for i in range(n):
lst.append(list(input().rstrip()))
stars = []
for i in range(n):
for j in range(m):
if lst[i][j] == '*':
stars.append([i, j])
min_x = 1e9
min_y = 1e9
max_x = -1e9
max_y = -1e9
for x in stars:
min_x = min(min_x, x[0])
min_y = min(min_y, x[1])
max_x = max(max_x, x[0])
max_y = max(max_x, x[1])
print(max(max_y - min_y, max_x - min_x) + 1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Duff is in love with lovely numbers! A positive integer *x* is called lovely if and only if there is no such positive integer *a*<=><=1 such that *a*2 is a divisor of *x*.
Malek has a number store! In his store, he has only divisors of positive integer *n* (and he has all of them). As a birthday present, Malek wants to give her a lovely number from his store. He wants this number to be as big as possible.
Malek always had issues in math, so he asked for your help. Please tell him what is the biggest lovely number in his store.
|
```python
n = int(input())
if n ==1:
print(0)
else:
s = n **0.5
for i in range(2,int(s)+1):
if n % i ==0:
if n % i**2 ==0:
n = n / i
print(int(n))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Catherine has a deck of *n* cards, each of which is either red, green, or blue. As long as there are at least two cards left, she can do one of two actions:
- take any two (not necessarily adjacent) cards with different colors and exchange them for a new card of the third color; - take any two (not necessarily adjacent) cards with the same color and exchange them for a new card with that color.
She repeats this process until there is only one card left. What are the possible colors for the final card?
|
```python
# strs = [input() for _ in range(3)]
def main():
n = int(input())
s = input()
r = g = b = 0
for c in s:
if c == 'R':
r += 1
elif c == 'G':
g += 1
else:
b += 1
ss = r + g + b
l = [(r, 'R'), (g, 'G'), (b, 'B')]
l.sort()
l1, l2, l3 = l
c1, s1 = l1
c2, s2 = l2
c3, s3 = l3
if ss >= 5:
if c2 > 0:
print('RGB')
else:
print(s3)
elif ss == 4:
if c1 > 0 or c2 == 2:
print('RGB')
else:
print(s1 + s2)
elif ss == 3:
if c1 == 1:
print('RGB')
elif c2 == 1:
print(s1 + s2)
else: # 003
print(s3)
elif ss == 2:
if c2 == 1:
print(s1)
else: # 002
print(s3)
else:
print(s3)
main()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put all the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items?
|
```python
z = input()
z += 'O'
s = 0
p = 0
for i in range(len(z)-1):
if s <= 5:
if z[i] == z[i+1]:
s += 1.5
else:
p += 1
s = 0
else:
p += 1
s = 0
print(p)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Ternary numeric notation is quite popular in Berland. To telegraph the ternary number the Borze alphabet is used. Digit 0 is transmitted as «.», 1 as «-.» and 2 as «--». You are to decode the Borze code, i.e. to find out the ternary number given its representation in Borze alphabet.
|
```python
### https://codeforces.com/problemset/problem/32/B
a = input()
a=list(a)
print(a)
n=len(a)
out=[]
i=0
while i<n:
if a[i]=='.':
out.append(0)
i=i+1
elif (a[i]=='-') & (a[i+1]=='.'):
out.append(1)
i=i+2
else:
out.append(2)
i=i+2
for num in out:
print(num, end='')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Hideo Kojima has just quit his job at Konami. Now he is going to find a new place to work. Despite being such a well-known person, he still needs a CV to apply for a job.
During all his career Hideo has produced *n* games. Some of them were successful, some were not. Hideo wants to remove several of them (possibly zero) from his CV to make a better impression on employers. As a result there should be no unsuccessful game which comes right after successful one in his CV.
More formally, you are given an array *s*1,<=*s*2,<=...,<=*s**n* of zeros and ones. Zero corresponds to an unsuccessful game, one — to a successful one. Games are given in order they were produced, and Hideo can't swap these values. He should remove some elements from this array in such a way that no zero comes right after one.
Besides that, Hideo still wants to mention as much games in his CV as possible. Help this genius of a man determine the maximum number of games he can leave in his CV.
|
```python
n = int(input())
games = input().replace(' ', '')
bad_idxs = [n for n in range(len(games)) if games.find('10', n) == n]
if len(bad_idxs) == 0:
print(len(games))
else:
counts = []
counts.append(len(games.replace('1', '')))
counts.append(len(games.replace('0', '')))
for bi in bad_idxs:
counts.append(len(games[0:bi + 1].replace('1', '')) + len(games[bi + 1:].replace('0', '')))
print(max(counts))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Absent-minded Masha got set of *n* cubes for her birthday.
At each of 6 faces of each cube, there is exactly one digit from 0 to 9. Masha became interested what is the largest natural *x* such she can make using her new cubes all integers from 1 to *x*.
To make a number Masha can rotate her cubes and put them in a row. After that, she looks at upper faces of cubes from left to right and reads the number.
The number can't contain leading zeros. It's not required to use all cubes to build a number.
Pay attention: Masha can't make digit 6 from digit 9 and vice-versa using cube rotations.
|
```python
n = int(input())
a = sorted([list(map(int, input().split())) for i in range(n)])
import itertools
for x in range(1,10**n):
good = False
s = str(x)
for p in itertools.permutations(a, len(s)):
good |= all([int(s[i]) in v for i, v in enumerate(p)])
if not good:
print(x-1)
exit(0)
print((10**n)-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The only king stands on the standard chess board. You are given his position in format "cd", where *c* is the column from 'a' to 'h' and *d* is the row from '1' to '8'. Find the number of moves permitted for the king.
Check the king's moves here [https://en.wikipedia.org/wiki/King_(chess)](https://en.wikipedia.org/wiki/King_(chess)).
|
```python
a=str(input())
col=a[0]
fil=a[1]
if (col=="a" or col=="h") and (int(fil)==1 or int(fil)==8):
print(3)
elif (col=="b" or col=="c" or col=="d" or col=="e" or col=="f" or col=="g") and (1<int(fil)<8):
print(8)
else:
print(5)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc. However, it's easy to make a mistake during the «translation». Vasya translated word *s* from Berlandish into Birlandish as *t*. Help him: find out if he translated the word correctly.
|
```python
print('YNEOS'[(list(reversed(input()))!=list(input()))::2])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc. However, it's easy to make a mistake during the «translation». Vasya translated word *s* from Berlandish into Birlandish as *t*. Help him: find out if he translated the word correctly.
|
```python
s1 = input()
s2 = input()
if s2 == s1[::-1]:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all *n* squad soldiers to line up on the parade ground.
By the military charter the soldiers should stand in the order of non-increasing of their height. But as there's virtually no time to do that, the soldiers lined up in the arbitrary order. However, the general is rather short-sighted and he thinks that the soldiers lined up correctly if the first soldier in the line has the maximum height and the last soldier has the minimum height. Please note that the way other solders are positioned does not matter, including the case when there are several soldiers whose height is maximum or minimum. Only the heights of the first and the last soldier are important.
For example, the general considers the sequence of heights (4, 3, 4, 2, 1, 1) correct and the sequence (4, 3, 1, 2, 2) wrong.
Within one second the colonel can swap any two neighboring soldiers. Help him count the minimum time needed to form a line-up which the general will consider correct.
|
```python
n = int(input())
a = list(map(int,input().split()))
ma = a.index(max(a))
mi = a[::-1].index(min(a[::-1]))
print(ma+mi-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Eighth-grader Vova is on duty today in the class. After classes, he went into the office to wash the board, and found on it the number *n*. He asked what is this number and the teacher of mathematics Inna Petrovna answered Vova that *n* is the answer to the arithmetic task for first-graders. In the textbook, a certain positive integer *x* was given. The task was to add *x* to the sum of the digits of the number *x* written in decimal numeral system.
Since the number *n* on the board was small, Vova quickly guessed which *x* could be in the textbook. Now he wants to get a program which will search for arbitrary values of the number *n* for all suitable values of *x* or determine that such *x* does not exist. Write such a program for Vova.
|
```python
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 4 22:21:53 2019
@author: Akshay
"""
n=int(input().strip())
i=0
def sumDig(n):
s=0
k=n
while n!=0:
s+=n%10
n=n//10
return k+s
arr=[]
while i!=n:
if sumDig(i)==n:
arr.append(i)
i+=1
print(len(arr))
for i in arr:
print(i)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands:
- Include a person to the chat ('Add' command). - Remove a person from the chat ('Remove' command). - Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command).
Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.
Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends *l* bytes to each participant of the chat, where *l* is the length of the message.
As Polycarp has no time, he is asking for your help in solving this problem.
|
```python
n = 0
t = 0
while True:
try:
cmd = input()
if cmd[0] == '+':
n += 1
elif cmd[0] == '-':
n -= 1
else:
m = cmd[cmd.index(':')+1:]
t += len(m)*n
except EOFError:
print(t)
exit(0)
```
|
|
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
n = int(input())
b = map(input().split(' '), int)
print(b.count(min(b)) * b.count(max(b)))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Blake is a CEO of a large company called "Blake Technologies". He loves his company very much and he thinks that his company should be the best. That is why every candidate needs to pass through the interview that consists of the following problem.
We define function *f*(*x*,<=*l*,<=*r*) as a bitwise OR of integers *x**l*,<=*x**l*<=+<=1,<=...,<=*x**r*, where *x**i* is the *i*-th element of the array *x*. You are given two arrays *a* and *b* of length *n*. You need to determine the maximum value of sum *f*(*a*,<=*l*,<=*r*)<=+<=*f*(*b*,<=*l*,<=*r*) among all possible 1<=≤<=*l*<=≤<=*r*<=≤<=*n*.
|
```python
from functools import reduce
n = int(input())
x = reduce(lambda a,b:a|b , map(int,input().split()))
y = reduce(lambda a,b:a|b , map(int,input().split()))
print(x+y)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups.
Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime.
If there is no police officer free (isn't busy with crime) during the occurrence of a crime, it will go untreated.
Given the chronological order of crime occurrences and recruit hirings, find the number of crimes which will go untreated.
|
```python
n = int(input())
s = []
s += map(int, input().split())
a, c, summ, po = 0, 0, 0, 0
for i in range(n):
if s[i] > 0:
po = 0
po += int(s[i])
elif s[i] == -1:
po -= 1
if po < 0:
c += 1
print(c)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Among other things, Bob is keen on photography. Especially he likes to take pictures of sportsmen. That was the reason why he placed himself in position *x*0 of a long straight racetrack and got ready to take pictures. But the problem was that not all the runners passed him. The total amount of sportsmen, training at that racetrack, equals *n*. And each of them regularly runs distances within a particular segment of the racetrack, which is the same for each sportsman. For example, the first sportsman runs from position *a*1 to position *b*1, the second — from *a*2 to *b*2
What is the minimum distance that Bob should move to have a chance to take pictures of each sportsman? Bob can take a picture of a sportsman, if he stands within the segment that this sportsman covers on the racetrack.
|
```python
from itertools import accumulate
def main():
n, x0 = map(int, input().split())
li = []
for _ in range(n):
a, b = map(int, input().split())
li.append([min(a, b), max(a, b)])
d = [0] * 1001
for i in range(n):
d[li[i][0]] += 1
if li[i][1] != 1001:
d[li[i][1]] -= 1
d = list(accumulate(d))
if n not in d:
print(-1)
else:
ind = []
for i in range(1001):
if d[i] == n:
ind.append(i)
ans = []
for el in ind:
ans.append(abs(el - x0))
print(min(ans))
if __name__ == '__main__':
main()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There is a given sequence of integers *a*1,<=*a*2,<=...,<=*a**n*, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other.
|
```python
n=int(input())
li=list(map(int,input().split(" ")))
print(n,li)
res=[]
res.append(li.count(1))
res.append(li.count(2))
res.append(li.count(3))
res.sort()
print(res[0]+res[1])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
New Year is coming in Line World! In this world, there are *n* cells numbered by integers from 1 to *n*, as a 1<=×<=*n* board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.
So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of *n*<=-<=1 positive integers *a*1,<=*a*2,<=...,<=*a**n*<=-<=1. For every integer *i* where 1<=≤<=*i*<=≤<=*n*<=-<=1 the condition 1<=≤<=*a**i*<=≤<=*n*<=-<=*i* holds. Next, he made *n*<=-<=1 portals, numbered by integers from 1 to *n*<=-<=1. The *i*-th (1<=≤<=*i*<=≤<=*n*<=-<=1) portal connects cell *i* and cell (*i*<=+<=*a**i*), and one can travel from cell *i* to cell (*i*<=+<=*a**i*) using the *i*-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (*i*<=+<=*a**i*) to cell *i* using the *i*-th portal. It is easy to see that because of condition 1<=≤<=*a**i*<=≤<=*n*<=-<=*i* one can't leave the Line World using portals.
Currently, I am standing at cell 1, and I want to go to cell *t*. However, I don't know whether it is possible to go there. Please determine whether I can go to cell *t* by only using the construted transportation system.
|
```python
def solve():
n, t = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
i = 1
while i < t:
i += a[i-1]
return i == t
# for _ in range(int(input())):
# print("YES" if solve() else "NO")
print("YES" if solve() else "NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Now it's time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. They've been best friends ever since primary school and hopefully, that can somehow help them in teamwork.
For each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing numbers 1 and 0. The boys are very superstitious. They think that they can do well at the Olympiad if they begin with laying all the cards in a row so that:
- there wouldn't be a pair of any side-adjacent cards with zeroes in a row; - there wouldn't be a group of three consecutive cards containing numbers one.
Today Vanya brought *n* cards with zeroes and *m* cards with numbers one. The number of cards was so much that the friends do not know how to put all those cards in the described way. Help them find the required arrangement of the cards or else tell the guys that it is impossible to arrange cards in such a way.
|
```python
n,m=list(map(int,input().split()))
#n: số thẻ có số 0
#m: số thẻ có số 1
#Không có 2 thẻ có số 0 liên tiếp
#Không có 3 thẻ có số 1 liên Tiếp
limit1=(n-1)*2+4
limit0=m+1
if m>limit1:
print(-1)
elif n>limit0:
print(-1)
else:
#Trường hợp 1 số 0 và 1 số 1 đan xen nhau
if m==n+1:
res="10"*n+"1"
elif m==n:
res="10"*n
elif m==n-1:
res="01"*m+"0"
#Đến lúc có 2 số 1 chen giữa các số 0
else:
succhuatoidakhoangtrongogiua=(n-1)*2
if m<=succhuatoidakhoangtrongogiua: #Chỉ cần số 2 lần số 1 ở trong là đủ rồi
solanthemso1=m-(n-1)
res=""
for i in range(solanthemso1):
res+="011"
for i in range(m-solanthemso1*2):
res+="01"
res+="0"
else:
#Cần thêm cả số 1 ở bên ngoài
#Làm như trên rồi thêm
res=""
for i in range(n-1):
res+="011"
res+="0"
so1bonus=m-res.count("1")
if so1bonus==1 or so1bonus==2:
res="1"*so1bonus+res
elif so1bonus==3:
res="11"+res+"1"
else:
res="11"+res+"11"
print(res)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock.
The combination lock is represented by *n* rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has to turn some disks so that the combination of digits on the disks forms a secret combination. In one move, he can rotate one disk one digit forwards or backwards. In particular, in one move he can go from digit 0 to digit 9 and vice versa. What minimum number of actions does he need for that?
|
```python
import os, sys
ii = lambda : int(input())
si = lambda : input()
li = lambda : list(map(int, input().split()))
lsi = lambda : list(map(str, input().split()))
try: sys.stdin = open(r"C:\Users\LIB-606\Desktop\input.txt",'r')
except : pass
import math
length = ii()
a = si()
b = si()
c = 0
for i,j in zip(a,b):
first = abs(int(i)-int(j))
second = abs(int(f'1{i}')-int(j))
third = abs(int(i)-int(f'1{j}'))
#print(first,second)
m = min([first,second, third])
c+=m
#print(c)
print(c)
'''
import math
x = ii()
#sq = math.sqrt(x)
c = 0
for i in range(1,(x//2)+1):
ans = divmod(x,i)
if ans[0]==ans[1]:
c+=1
print(ans)
print(c)
'''
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Given a sequence of integers *a*1,<=...,<=*a**n* and *q* queries *x*1,<=...,<=*x**q* on it. For each query *x**i* you have to count the number of pairs (*l*,<=*r*) such that 1<=≤<=*l*<=≤<=*r*<=≤<=*n* and *gcd*(*a**l*,<=*a**l*<=+<=1,<=...,<=*a**r*)<==<=*x**i*.
is a greatest common divisor of *v*1,<=*v*2,<=...,<=*v**n*, that is equal to a largest positive integer that divides all *v**i*.
|
```python
import collections
def gcd(a,b):
return gcd(b,a%b) if b!=0 else a
n=int(input())
arr=[int(i) for i in input().split()]
res=collections.defaultdict(int)
st=collections.defaultdict(int)
for i in arr:
temp=collections.defaultdict(int)
for j in st.keys():
val=gcd(j,i)
temp[val]+=st[j]
temp[i]+=1
st = temp
for i in st.keys():
res[i]+=st[i]
for _ in range(int(input())):
x=int(input())
print(res[x])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Pasha loves his phone and also putting his hair up... But the hair is now irrelevant.
Pasha has installed a new game to his phone. The goal of the game is following. There is a rectangular field consisting of *n* row with *m* pixels in each row. Initially, all the pixels are colored white. In one move, Pasha can choose any pixel and color it black. In particular, he can choose the pixel that is already black, then after the boy's move the pixel does not change, that is, it remains black. Pasha loses the game when a 2<=×<=2 square consisting of black pixels is formed.
Pasha has made a plan of *k* moves, according to which he will paint pixels. Each turn in his plan is represented as a pair of numbers *i* and *j*, denoting respectively the row and the column of the pixel to be colored on the current move.
Determine whether Pasha loses if he acts in accordance with his plan, and if he does, on what move the 2<=×<=2 square consisting of black pixels is formed.
|
```python
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 19 16:18:10 2023
@author: 苏柔德 2300011012
"""
import numpy as np
n, m, k = map(int, input().split())
x = np.full((n, m), 0)
flag = -1
for _ in range(k):
i, j = map(int, input().split())
x[i-1, j-1] = 1
for row in range(n-1):
for col in range(m-1):
if x[row, col] == 1 and x[row+1, col] == 1 and x[row, col+1] == 1 and x[row+1, col+1] == 1:
flag = _
break
if flag != -1:
break
if flag != -1:
break
if flag == -1:
print(0)
else:
print(flag)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had *a* red socks and *b* blue socks.
According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot.
Every day Vasya puts on new socks in the morning and throws them away before going to bed as he doesn't want to wash them.
Vasya wonders, what is the maximum number of days when he can dress fashionable and wear different socks, and after that, for how many days he can then wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Can you help him?
|
```python
a,b = map(int, input().split())
k=0
l=0
if a<b:
k=a
l=(b-a)//2
elif a>b:
k=b
l=(a-b)//2
else:
k=a
l=0
print (k, l)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Reforms continue entering Berland. For example, during yesterday sitting the Berland Parliament approved as much as *n* laws (each law has been assigned a unique number from 1 to *n*). Today all these laws were put on the table of the President of Berland, G.W. Boosch, to be signed.
This time mr. Boosch plans to sign 2*k* laws. He decided to choose exactly two non-intersecting segments of integers from 1 to *n* of length *k* and sign all laws, whose numbers fall into these segments. More formally, mr. Boosch is going to choose two integers *a*, *b* (1<=≤<=*a*<=≤<=*b*<=≤<=*n*<=-<=*k*<=+<=1,<=*b*<=-<=*a*<=≥<=*k*) and sign all laws with numbers lying in the segments [*a*; *a*<=+<=*k*<=-<=1] and [*b*; *b*<=+<=*k*<=-<=1] (borders are included).
As mr. Boosch chooses the laws to sign, he of course considers the public opinion. Allberland Public Opinion Study Centre (APOSC) conducted opinion polls among the citizens, processed the results into a report and gave it to the president. The report contains the absurdity value for each law, in the public opinion. As mr. Boosch is a real patriot, he is keen on signing the laws with the maximum total absurdity. Help him.
|
```python
n,k=[int(x) for x in input().split()]
arr=[int(x) for x in input().split()]
temp=[0]
curr=0
for i in arr:
curr+=i
temp.append(curr)
temp2=[]
#print(temp)
for i in range(k,n+1):
temp2.append(temp[i]-temp[i-k])
#print(temp2)
ans=0
l=len(temp2)
maxi=[0 for i in range(l)]
maxi[0]=temp2[0]
curr=maxi[0]
for i in range(1,l):
curr=max(curr,temp2[i])
maxi[i]=curr
#print(temp2)
#print(maxi)
for i in range(k,l):
if temp2[i]+maxi[i-k]>=ans:
a=i-k
b=i+1
ans=temp2[i]+maxi[i-k]
print(a,b)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little Petya often travels to his grandmother in the countryside. The grandmother has a large garden, which can be represented as a rectangle 1<=×<=*n* in size, when viewed from above. This rectangle is divided into *n* equal square sections. The garden is very unusual as each of the square sections possesses its own fixed height and due to the newest irrigation system we can create artificial rain above each section.
Creating artificial rain is an expensive operation. That's why we limit ourselves to creating the artificial rain only above one section. At that, the water from each watered section will flow into its neighbouring sections if their height does not exceed the height of the section. That is, for example, the garden can be represented by a 1<=×<=5 rectangle, where the section heights are equal to 4, 2, 3, 3, 2. Then if we create an artificial rain over any of the sections with the height of 3, the water will flow over all the sections, except the ones with the height of 4. See the illustration of this example at the picture:
As Petya is keen on programming, he decided to find such a section that if we create artificial rain above it, the number of watered sections will be maximal. Help him.
|
```python
n=int(input())
l=list(map(int,input().split()))
m=-1
for i in range(n):
c=1
for j in range(i,n-1):
if l[j]>=l[j+1]:
c+=1
else : break
for j in range(i,1,-1):
if l[j]>=l[j-1]:
c+=1
else : break
m=max(c,m)
print(m)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little Vasya went to the supermarket to get some groceries. He walked about the supermarket for a long time and got a basket full of products. Now he needs to choose the cashier to pay for the products.
There are *n* cashiers at the exit from the supermarket. At the moment the queue for the *i*-th cashier already has *k**i* people. The *j*-th person standing in the queue to the *i*-th cashier has *m**i*,<=*j* items in the basket. Vasya knows that:
- the cashier needs 5 seconds to scan one item; - after the cashier scans each item of some customer, he needs 15 seconds to take the customer's money and give him the change.
Of course, Vasya wants to select a queue so that he can leave the supermarket as soon as possible. Help him write a program that displays the minimum number of seconds after which Vasya can get to one of the cashiers.
|
```python
from sys import stdin
input=lambda :stdin.readline()[:-1]
n=int(input())
k=list(map(int,input().split()))
ans=float("inf")
for i in range(n):
m=list(map(int,input().split()))
curr=(len(m))*15+(sum(m))*5
ans=min(ans,curr)
print(ans)
```
|
|
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
mn = input()
m, n = [int(x) for x in mn.split()]
if m % 2 == 0 or n % 2 == 0:
ans = int((m*n) / 2)
else:
ans = int(((m*n) - 1) / 2)
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Kevin Sun has just finished competing in Codeforces Round #334! The round was 120 minutes long and featured five problems with maximum point values of 500, 1000, 1500, 2000, and 2500, respectively. Despite the challenging tasks, Kevin was uncowed and bulldozed through all of them, distinguishing himself from the herd as the best cowmputer scientist in all of Bovinia. Kevin knows his submission time for each problem, the number of wrong submissions that he made on each problem, and his total numbers of successful and unsuccessful hacks. Because Codeforces scoring is complicated, Kevin wants you to write a program to compute his final score.
Codeforces scores are computed as follows: If the maximum point value of a problem is *x*, and Kevin submitted correctly at minute *m* but made *w* wrong submissions, then his score on that problem is . His total score is equal to the sum of his scores for each problem. In addition, Kevin's total score gets increased by 100 points for each successful hack, but gets decreased by 50 points for each unsuccessful hack.
All arithmetic operations are performed with absolute precision and no rounding. It is guaranteed that Kevin's final score is an integer.
|
```python
a=[]
i=0
while i<2:
b=input().split()
a.append(b)
i=i+1
w=[500,1000,1500,2000,2500]
i=0
result=0
y=input().split()
result=result+100*int(y[0])
result=result-50*int(y[1])
while i<5:
c=0.3*w[i]
d=(1-int(a[0][i])/250)*w[i]-50*int(a[1][i])
result=result+max(c,d)
i=i+1
print(int(result))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Stepan had a favorite string *s* which consisted of the lowercase letters of the Latin alphabet.
After graduation, he decided to remember it, but it was a long time ago, so he can't now remember it. But Stepan remembers some information about the string, namely the sequence of integers *c*1,<=*c*2,<=...,<=*c**n*, where *n* equals the length of the string *s*, and *c**i* equals the number of substrings in the string *s* with the length *i*, consisting of the same letters. The substring is a sequence of consecutive characters in the string *s*.
For example, if the Stepan's favorite string is equal to "tttesst", the sequence *c* looks like: *c*<==<=[7,<=3,<=1,<=0,<=0,<=0,<=0].
Stepan asks you to help to repair his favorite string *s* according to the given sequence *c*1,<=*c*2,<=...,<=*c**n*.
|
```python
print("_RANDOM_GUESS_1689255733.378918")# 1689255733.378931
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Alice and Bob like games. And now they are ready to start a new game. They have placed *n* chocolate bars in a line. Alice starts to eat chocolate bars one by one from left to right, and Bob — from right to left. For each chocololate bar the time, needed for the player to consume it, is known (Alice and Bob eat them with equal speed). When the player consumes a chocolate bar, he immediately starts with another. It is not allowed to eat two chocolate bars at the same time, to leave the bar unfinished and to make pauses. If both players start to eat the same bar simultaneously, Bob leaves it to Alice as a true gentleman.
How many bars each of the players will consume?
|
```python
n = int(input())
arr = list(map(int, input().split()))
left = 0
right = n - 1
alice = arr[left]
bob = arr[right]
while left < right:
if alice - bob > 0:
if (right - 1) == left:
break
right -= 1
bob += arr[right]
elif alice - bob < 0:
if (left + 1) == right:
break
left += 1
alice += arr[left]
else:
if abs(left - right) == 1:
break
left += 1
right += 1
bob += arr[right]
alice += arr[left]
print('{0} {1}'.format(left + 1, right + 1))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Gerald has *n* younger brothers and their number happens to be even. One day he bought *n*2 candy bags. One bag has one candy, one bag has two candies, one bag has three candies and so on. In fact, for each integer *k* from 1 to *n*2 he has exactly one bag with *k* candies.
Help him give *n* bags of candies to each brother so that all brothers got the same number of candies.
|
```python
a=int(input())
for i in range(a):
b=[]
for j in range(a):
b+=[a*j+(j+i)%a+1]
print(' '.join(map(str,b)))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya decided to write an anonymous letter cutting the letters out of a newspaper heading. He knows heading *s*1 and text *s*2 that he wants to send. Vasya can use every single heading letter no more than once. Vasya doesn't have to cut the spaces out of the heading — he just leaves some blank space to mark them. Help him; find out if he will manage to compose the needed text.
|
```python
import sys
input = sys.stdin.readline
t = input().split()
s = input().split()
d1 = {chr(i + ord('a')) : 0 for i in range(26)}
d2 = {chr(i + ord('A')) : 0 for i in range(26)}
d2.update(d1)
for i in t:
for j in i:
d2[j] += 1
for i in s:
for j in i:
d2[j] -= 1
for i in d2.keys():
if(d2[i] < 0):
print("NO")
break
else:
print("YES")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Sereja has an array *a*, consisting of *n* integers *a*1, *a*2, ..., *a**n*. The boy cannot sit and do nothing, he decided to study an array. Sereja took a piece of paper and wrote out *m* integers *l*1,<=*l*2,<=...,<=*l**m* (1<=≤<=*l**i*<=≤<=*n*). For each number *l**i* he wants to know how many distinct numbers are staying on the positions *l**i*, *l**i*<=+<=1, ..., *n*. Formally, he want to find the number of distinct numbers among *a**l**i*,<=*a**l**i*<=+<=1,<=...,<=*a**n*.?
Sereja wrote out the necessary array elements but the array was so large and the boy was so pressed for time. Help him, find the answer for the described question for each *l**i*.
|
```python
def solution():
n,m = map(int, input().split())
arr = list(map(int, input().split()))
_set = set()
for i in range(len(arr))[::-1]:
_set.add(arr[i])
arr[i] = len(_set)
for _ in range(m):
val = int(input())
print(arr[val - 1])
def main():
t = 1
#t = int(input())
for _ in range(t):
solution()
main()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A sequence *a*0,<=*a*1,<=...,<=*a**t*<=-<=1 is called increasing if *a**i*<=-<=1<=<<=*a**i* for each *i*:<=0<=<<=*i*<=<<=*t*.
You are given a sequence *b*0,<=*b*1,<=...,<=*b**n*<=-<=1 and a positive integer *d*. In each move you may choose one element of the given sequence and add *d* to it. What is the least number of moves required to make the given sequence increasing?
|
```python
n,d=[int(e) for e in input().split()]
a=[int(e) for e in input().split()]
c=0
for i in range(1,n):
x=a[i]-a[i-1]
if x%d==0:
x=x//d+1
else:
x=(x+d-1)//d
a[i]+=d*x
c+=x
print(c)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Today is birthday of a Little Dasha — she is now 8 years old! On this occasion, each of her *n* friends and relatives gave her a ribbon with a greeting written on it, and, as it turned out, all the greetings are different. Dasha gathered all the ribbons and decided to throw away some of them in order to make the remaining set stylish. The birthday girl considers a set of ribbons stylish if no greeting written on some ribbon is a substring of another greeting written on some other ribbon. Let us recall that the substring of the string *s* is a continuous segment of *s*.
Help Dasha to keep as many ribbons as possible, so that she could brag about them to all of her friends. Dasha cannot rotate or flip ribbons, that is, each greeting can be read in a single way given in the input.
|
```python
print("_RANDOM_GUESS_1689182512.488632")# 1689182512.4886642
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Now it's time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. They've been best friends ever since primary school and hopefully, that can somehow help them in teamwork.
For each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing numbers 1 and 0. The boys are very superstitious. They think that they can do well at the Olympiad if they begin with laying all the cards in a row so that:
- there wouldn't be a pair of any side-adjacent cards with zeroes in a row; - there wouldn't be a group of three consecutive cards containing numbers one.
Today Vanya brought *n* cards with zeroes and *m* cards with numbers one. The number of cards was so much that the friends do not know how to put all those cards in the described way. Help them find the required arrangement of the cards or else tell the guys that it is impossible to arrange cards in such a way.
|
```python
z,o = list(map(int,input().split()))
if(o<z):
print(-1)
else:
cards=[]
while(z!=0):
cards.append("1")
cards.append("0")
o-=1
z-=1
if(o==2):
cards.append("1")
cards.append("1")
print("".join(cards))
elif(o==1):
cards.append("1")
print("".join(cards))
elif(o==0):
print("".join(cards))
else:
index=0
l=len(cards)
while(index<l and o!=0):
cards.insert(index,"1")
o-=1
index+=3
l = len(cards)
if(o==2):
cards.append("1")
cards.append("1")
print("".join(cards))
elif(o==1):
cards.append("1")
print("".join(cards))
elif(o==0):
print("".join(cards))
else:
print(-1)
```
|
|
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
n, b, d = map(int, input().split())
lst = [int(i) for i in input().split()]
c, h = 0, 0
for i in lst:
if i <= b:
c += i
if c > d:
h += 1
c = 0
print(h)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a string *s* consisting of lowercase Latin letters. Character *c* is called *k*-dominant iff each substring of *s* with length at least *k* contains this character *c*.
You have to find minimum *k* such that there exists at least one *k*-dominant character.
|
```python
s=input()
alpha=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
ans=1000000
for i in alpha:
occ=[]
for j in range(len(s)):
if(s[j]==i):
occ.append(j)
occ.append(len(s))
diff=[]
st=0
# print(occ)
for k in occ:
diff.append(k-st)
st=k
# diff.append(len(s)-1-k)
# print(diff)
z=max(diff)
# print(z)
ans=min(max(diff),ans)
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
In this problem you will have to help Berland army with organizing their command delivery system.
There are $n$ officers in Berland army. The first officer is the commander of the army, and he does not have any superiors. Every other officer has exactly one direct superior. If officer $a$ is the direct superior of officer $b$, then we also can say that officer $b$ is a direct subordinate of officer $a$.
Officer $x$ is considered to be a subordinate (direct or indirect) of officer $y$ if one of the following conditions holds:
- officer $y$ is the direct superior of officer $x$; - the direct superior of officer $x$ is a subordinate of officer $y$.
For example, on the picture below the subordinates of the officer $3$ are: $5, 6, 7, 8, 9$.
The structure of Berland army is organized in such a way that every officer, except for the commander, is a subordinate of the commander of the army.
Formally, let's represent Berland army as a tree consisting of $n$ vertices, in which vertex $u$ corresponds to officer $u$. The parent of vertex $u$ corresponds to the direct superior of officer $u$. The root (which has index $1$) corresponds to the commander of the army.
Berland War Ministry has ordered you to give answers on $q$ queries, the $i$-th query is given as $(u_i, k_i)$, where $u_i$ is some officer, and $k_i$ is a positive integer.
To process the $i$-th query imagine how a command from $u_i$ spreads to the subordinates of $u_i$. Typical DFS (depth first search) algorithm is used here.
Suppose the current officer is $a$ and he spreads a command. Officer $a$ chooses $b$ — one of his direct subordinates (i.e. a child in the tree) who has not received this command yet. If there are many such direct subordinates, then $a$ chooses the one having minimal index. Officer $a$ gives a command to officer $b$. Afterwards, $b$ uses exactly the same algorithm to spread the command to its subtree. After $b$ finishes spreading the command, officer $a$ chooses the next direct subordinate again (using the same strategy). When officer $a$ cannot choose any direct subordinate who still hasn't received this command, officer $a$ finishes spreading the command.
Let's look at the following example:
If officer $1$ spreads a command, officers receive it in the following order: $[1, 2, 3, 5 ,6, 8, 7, 9, 4]$.
If officer $3$ spreads a command, officers receive it in the following order: $[3, 5, 6, 8, 7, 9]$.
If officer $7$ spreads a command, officers receive it in the following order: $[7, 9]$.
If officer $9$ spreads a command, officers receive it in the following order: $[9]$.
To answer the $i$-th query $(u_i, k_i)$, construct a sequence which describes the order in which officers will receive the command if the $u_i$-th officer spreads it. Return the $k_i$-th element of the constructed list or -1 if there are fewer than $k_i$ elements in it.
You should process queries independently. A query doesn't affect the following queries.
|
```python
import sys
input = sys.stdin.readline
n, q = map(int, input().split())
d = [[] for _ in range(n+1)]
for i, j in enumerate(map(int, input().split())):
d[i+2].append(j)
d[j].append(i+2)
for i in d:
i.sort()
q = [(0, 1, -1)]
x = [0]*(n+1)
z = []
while q:
a, b, c = q.pop()
if a == 0:
z.append(b)
q.append((1, b, c))
for i in d[b][::-1]:
if i != c:
q.append((0, i, b))
else:
if len(d[b]) == 1:
x[b] = 1
else:
x[b] = 1 + sum(x[i] for i in d[b] if i != c)
y = [0]*(n+1)
for i, j in enumerate(z):
y[j] = i
for _ in range(m):
a, b = map(int, input().split())
if b > x[a]:
print(-1)
else:
print(z[y[a]+b-1])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Dreamoon loves summing up something for no reason. One day he obtains two integers *a* and *b* occasionally. He wants to calculate the sum of all nice integers. Positive integer *x* is called nice if and , where *k* is some integer number in range [1,<=*a*].
By we denote the quotient of integer division of *x* and *y*. By we denote the remainder of integer division of *x* and *y*. You can read more about these operations here: http://goo.gl/AcsXhT.
The answer may be large, so please print its remainder modulo 1<=000<=000<=007 (109<=+<=7). Can you compute it faster than Dreamoon?
|
```python
s=raw_input().split()
a,b=(int)(s[0]),(int)(s[1])
x=0
for k in range(1,a+1):
x=x+k*b+1
xx=0
for t in range(1,b+1):
xx=xx+i
print((xx*x)%1000000007)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a string $s$ consisting of $n$ lowercase Latin letters. Polycarp wants to remove exactly $k$ characters ($k \le n$) from the string $s$. Polycarp uses the following algorithm $k$ times:
- if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; - if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; - ... - remove the leftmost occurrence of the letter 'z' and stop the algorithm.
This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly $k$ times, thus removing exactly $k$ characters.
Help Polycarp find the resulting string.
|
```python
n,k=map(int,input().split())
l=list(input())
p=l.copy()
l.sort()
cnt=[0]*26
l2=[]
for i in range(k):
l2.append(l[i])
for x in l2:
cnt[ord(x)-97]+=1
print(cnt)
cnt2=[0]*26
ans=[]
for x in p:
if cnt[ord(x)-97]:
cnt[ord(x)-97]-=1
else:
ans.append(x)
ans="".join(ans)
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Now it's time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. They've been best friends ever since primary school and hopefully, that can somehow help them in teamwork.
For each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing numbers 1 and 0. The boys are very superstitious. They think that they can do well at the Olympiad if they begin with laying all the cards in a row so that:
- there wouldn't be a pair of any side-adjacent cards with zeroes in a row; - there wouldn't be a group of three consecutive cards containing numbers one.
Today Vanya brought *n* cards with zeroes and *m* cards with numbers one. The number of cards was so much that the friends do not know how to put all those cards in the described way. Help them find the required arrangement of the cards or else tell the guys that it is impossible to arrange cards in such a way.
|
```python
import math as mt
import collections as cc
def ncr(n,r):
import math as mt
return (mt.factorial(n)//((mt.factorial(n-r))*(mt.factorial(r))))
I=lambda:list(map(int,input().split()))
n,m=I()
if m>n*2+2:
print(-1)
elif n>m+1:
print(-1)
else:
new=''
if n<m:
while m:
if m-2>=0:
new+='11 '
#print('11',end='')
m-=2
elif m-1>=0:
new+='1'
#print('1'end='')
m-=1
new=new.split()
for i in new:
print(i,end='')
if n:
print('0',end='')
n-=1
else:
new='01'*n
if n==m+1:
new=new[:-1]
print(new)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Kolya Gerasimov loves kefir very much. He lives in year 1984 and knows all the details of buying this delicious drink. One day, as you probably know, he found himself in year 2084, and buying kefir there is much more complicated.
Kolya is hungry, so he went to the nearest milk shop. In 2084 you may buy kefir in a plastic liter bottle, that costs *a* rubles, or in glass liter bottle, that costs *b* rubles. Also, you may return empty glass bottle and get *c* (*c*<=<<=*b*) rubles back, but you cannot return plastic bottles.
Kolya has *n* rubles and he is really hungry, so he wants to drink as much kefir as possible. There were no plastic bottles in his 1984, so Kolya doesn't know how to act optimally and asks for your help.
|
```python
s = int(input())
a = int(input())
b = int(input())
c = int(input())
d = b-c
l = 0
if d < a:
l = s-b // d
s -= l * d
else:
l = s // a
s -= l * a
m = min(a,b)
if s >= m:
l += 1
print(l)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Petya is a big fan of mathematics, especially its part related to fractions. Recently he learned that a fraction is called proper iff its numerator is smaller than its denominator (*a*<=<<=*b*) and that the fraction is called irreducible if its numerator and its denominator are coprime (they do not have positive common divisors except 1).
During his free time, Petya thinks about proper irreducible fractions and converts them to decimals using the calculator. One day he mistakenly pressed addition button (<=+<=) instead of division button (÷) and got sum of numerator and denominator that was equal to *n* instead of the expected decimal notation.
Petya wanted to restore the original fraction, but soon he realized that it might not be done uniquely. That's why he decided to determine maximum possible proper irreducible fraction such that sum of its numerator and denominator equals *n*. Help Petya deal with this problem.
|
```python
upper=int(input())
emp=[1]
temp=[]
for num in range(1, upper + 1):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
emp.append(num)
for j in range(len(emp)):
if upper-emp[j] in emp and emp[j]<upper-emp[j]:
temp.append(emp[j])
temp.append(upper-emp[j])
print(temp[len(temp)-2],temp[len(temp)-1])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya lives in a strange world. The year has *n* months and the *i*-th month has *a**i* days. Vasya got a New Year present — the clock that shows not only the time, but also the date.
The clock's face can display any number from 1 to *d*. It is guaranteed that *a**i*<=≤<=*d* for all *i* from 1 to *n*. The clock does not keep information about the current month, so when a new day comes, it simply increases the current day number by one. The clock cannot display number *d*<=+<=1, so after day number *d* it shows day 1 (the current day counter resets). The mechanism of the clock allows you to increase the day number by one manually. When you execute this operation, day *d* is also followed by day 1.
Vasya begins each day checking the day number on the clock. If the day number on the clock does not match the actual day number in the current month, then Vasya manually increases it by one. Vasya is persistent and repeats this operation until the day number on the clock matches the actual number of the current day in the current month.
A year passed and Vasya wonders how many times he manually increased the day number by one, from the first day of the first month to the last day of the *n*-th month inclusive, considering that on the first day of the first month the clock display showed day 1.
|
```python
d=int(input())
n=int(input())
count=0
arr=[int(x) for x in input().split()]
for i in range(n-1):
if d>arr[i]:
count+=d-arr[i]
print(count)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You have a Petri dish with bacteria and you are preparing to dive into the harsh micro-world. But, unfortunately, you don't have any microscope nearby, so you can't watch them.
You know that you have $n$ bacteria in the Petri dish and size of the $i$-th bacteria is $a_i$. Also you know intergalactic positive integer constant $K$.
The $i$-th bacteria can swallow the $j$-th bacteria if and only if $a_i > a_j$ and $a_i \le a_j + K$. The $j$-th bacteria disappear, but the $i$-th bacteria doesn't change its size. The bacteria can perform multiple swallows. On each swallow operation any bacteria $i$ can swallow any bacteria $j$ if $a_i > a_j$ and $a_i \le a_j + K$. The swallow operations go one after another.
For example, the sequence of bacteria sizes $a=[101, 53, 42, 102, 101, 55, 54]$ and $K=1$. The one of possible sequences of swallows is: $[101, 53, 42, 102, \underline{101}, 55, 54]$ $\to$ $[101, \underline{53}, 42, 102, 55, 54]$ $\to$ $[\underline{101}, 42, 102, 55, 54]$ $\to$ $[42, 102, 55, \underline{54}]$ $\to$ $[42, 102, 55]$. In total there are $3$ bacteria remained in the Petri dish.
Since you don't have a microscope, you can only guess, what the minimal possible number of bacteria can remain in your Petri dish when you finally will find any microscope.
|
```python
import math as ma
n,k=map(int,input().split())
a=list(map(int,input().split()))
a.sort()
c=0
ll=len(a)
#print(*a)
for i in range(len(a)):
if(a[i+1]>a[i] and (a[i]+k)>=a[i+1]):
c+=1
print(ll-c)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Top-model Izabella participates in the competition. She wants to impress judges and show her mathematical skills.
Her problem is following: for given string, consisting of only 0 and 1, tell if it's possible to remove some digits in such a way, that remaining number is a representation of some positive integer, divisible by 64, in the binary numerical system.
|
```python
a=input()
if a.count('0')>=6 and a.count('1')>=1:
print('yes')
else:
print('no')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Gerald bought two very rare paintings at the Sotheby's auction and he now wants to hang them on the wall. For that he bought a special board to attach it to the wall and place the paintings on the board. The board has shape of an *a*1<=×<=*b*1 rectangle, the paintings have shape of a *a*2<=×<=*b*2 and *a*3<=×<=*b*3 rectangles.
Since the paintings are painted in the style of abstract art, it does not matter exactly how they will be rotated, but still, one side of both the board, and each of the paintings must be parallel to the floor. The paintings can touch each other and the edges of the board, but can not overlap or go beyond the edge of the board. Gerald asks whether it is possible to place the paintings on the board, or is the board he bought not large enough?
|
```python
a1, b1 = map(int, input().split())
a2, b2 = map(int, input().split())
a3, b3 = map(int, input().split())
def f(a, b, c, d):
if a + c <= a1 and max(b, d) <= b1:
print("YES")
exit(0)
for _ in range(2):
f(a2, b2, a3, b3)
f(b2, a2, a3, b3)
f(a2, b2, b3, a3)
f(b2, a2, b3, a3)
a1, b1 = b1, a1
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Levko loves tables that consist of *n* rows and *n* columns very much. He especially loves beautiful tables. A table is beautiful to Levko if the sum of elements in each row and column of the table equals *k*.
Unfortunately, he doesn't know any such table. Your task is to help him to find at least one of them.
|
```python
n,k = map(int,input().split())
T = [[0 for i in range(n)] for j in range(n)]
for i in range(n):
T[i][i] = k
for i in T:
for j in i:
print(j ,end = ' ')
print()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Petya is a big fan of mathematics, especially its part related to fractions. Recently he learned that a fraction is called proper iff its numerator is smaller than its denominator (*a*<=<<=*b*) and that the fraction is called irreducible if its numerator and its denominator are coprime (they do not have positive common divisors except 1).
During his free time, Petya thinks about proper irreducible fractions and converts them to decimals using the calculator. One day he mistakenly pressed addition button (<=+<=) instead of division button (÷) and got sum of numerator and denominator that was equal to *n* instead of the expected decimal notation.
Petya wanted to restore the original fraction, but soon he realized that it might not be done uniquely. That's why he decided to determine maximum possible proper irreducible fraction such that sum of its numerator and denominator equals *n*. Help Petya deal with this problem.
|
```python
n=int(input())
if n%2:
print(n//2,n//2 + 1)
elif n%4==0:
print(n//2 -1 ,n//2 + 1)
else:
print(n//2 -2 ,n//2 + 2)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Yaroslav has an array that consists of *n* integers. In one second Yaroslav can swap two neighboring array elements. Now Yaroslav is wondering if he can obtain an array where any two neighboring elements would be distinct in a finite time.
Help Yaroslav.
|
```python
from collections import Counter
n=int(input())
arr=list(map(int,input().split()))
#n<2*count or n+1>=2*count
print("YES" if all([arr.count(i)*2-1<=n for i in arr]) else "NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Theatre Square in the capital city of Berland has a rectangular shape with the size *n*<=×<=*m* meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size *a*<=×<=*a*.
What is the least number of flagstones needed to pave the Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square.
|
```python
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define endl '\n'
#define debug(n) cout<<(n)<<endl;
const ll INF = 2e18 + 99;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll n, m, a;
cin>>n>>m>>a;
ll c = (m % a == 0) ? (m / a) : (m / a + 1);
ll d = (n % a == 0) ? (n / a) : (n / a + 1);
cout<<(c * d)<<endl;
}
```
|
|
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=map(int,input().split())
r1=(k*l)//nl
r2=(c*d)
r3=p//np
r=[r1,r2,r3]
r.sort()
res=r[0]
print(res//n)
```
|
|
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
n, m = map(int, input().split())
board = []
for i in range(n):
board.append(list(input()))
def writeNbr(i, j):
if j + 1 < m:
if board[i][j + 1] == '.':
board[i][j + 1] = 'B'
if i + 1 < n:
if board[i+1][j] == '.':
board[i+1][j] = 'B'
for i in range(n):
for j in range(m):
if board[i][j] == '.':
board[i][j] = 'W'
writeNbr(i, j)
for i in range(n):
print(board[i])
```
|
|
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()
Q, A = 0, 0
for i in range(len(s)):
if s[i] == "Q":
Q += 1
elif s[i] == "A":
A += 1
print((Q - 1) * A)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Once Bob took a paper stripe of *n* squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into two pieces so that the sum of numbers from one piece is equal to the sum of numbers from the other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem?
|
```python
n=int(input())
arr=list(map(int,input().split()))
cums=sum(arr)
c=0
x=0
for i in range(n-1):
x+=arr[i]
if x==cums-x:
c+=1
print(c)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You have decided to watch the best moments of some movie. There are two buttons on your player:
1. Watch the current minute of the movie. By pressing this button, you watch the current minute of the movie and the player automatically proceeds to the next minute of the movie. 1. Skip exactly *x* minutes of the movie (*x* is some fixed positive integer). If the player is now at the *t*-th minute of the movie, then as a result of pressing this button, it proceeds to the minute (*t*<=+<=*x*).
Initially the movie is turned on in the player on the first minute, and you want to watch exactly *n* best moments of the movie, the *i*-th best moment starts at the *l**i*-th minute and ends at the *r**i*-th minute (more formally, the *i*-th best moment consists of minutes: *l**i*,<=*l**i*<=+<=1,<=...,<=*r**i*).
Determine, what is the minimum number of minutes of the movie you have to watch if you want to watch all the best moments?
|
```python
from math import *
#from math import comb as nCr
import sys
from sys import *
def gI(): return map(int, sys.stdin.readline().strip().split())
def gL(): return list(map(int, sys.stdin.readline().strip().split()))
t=stdin.readline
p=stdout.write
'''
for _ in range(int(t())):
n=int(t())
a,b=gI()
a=gL()
'''
n,x=gI()
f,cnt=1,0
for _ in range(n):
l,r=gI()
while(f<=r):
if(f+x<=l):f+=x
else:
cnt+=1
f+=1
f=r+1
p(str(cnt))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
This is an interactive problem. Refer to the Interaction section below for better understanding.
Ithea and Chtholly want to play a game in order to determine who can use the kitchen tonight.
Initially, Ithea puts *n* clear sheets of paper in a line. They are numbered from 1 to *n* from left to right.
This game will go on for *m* rounds. In each round, Ithea will give Chtholly an integer between 1 and *c*, and Chtholly needs to choose one of the sheets to write down this number (if there is already a number before, she will erase the original one and replace it with the new one).
Chtholly wins if, at any time, all the sheets are filled with a number and the *n* numbers are in non-decreasing order looking from left to right from sheet 1 to sheet *n*, and if after *m* rounds she still doesn't win, she loses the game.
Chtholly really wants to win the game as she wants to cook something for Willem. But she doesn't know how to win the game. So Chtholly finds you, and your task is to write a program to receive numbers that Ithea gives Chtholly and help her make the decision on which sheet of paper write this number.
|
```python
import sys
N, M, C = map(int,input().split())
ans = [0] * (N+1)
# ls, le = 1, N+1
# rs, re = N//2+1, N+1
for _ in range(M):
p = int(input())
ii = -1
if p < C//2+1:
for i in range(1, N+1):
if ans[i] == 0 or ans[i] > p:
ii = i
break
else:
for i in range(N, 0, -1):
if ans[i] == 0 or ans[i] < p:
ii = i
break
ans[ii] = p
print(ii)
sys.stdout.flush()
if all(x > 0 for x in ans[1:]):
exit(0)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Valera has got *n* domino pieces in a row. Each piece consists of two halves — the upper one and the lower one. Each of the halves contains a number from 1 to 6. Valera loves even integers very much, so he wants the sum of the numbers on the upper halves and the sum of the numbers on the lower halves to be even.
To do that, Valera can rotate the dominoes by 180 degrees. After the rotation the upper and the lower halves swap places. This action takes one second. Help Valera find out the minimum time he must spend rotating dominoes to make his wish come true.
|
```python
n = int(input())
upper_sum = 0 # Sum of numbers on upper halves
lower_sum = 0 # Sum of numbers on lower halves
odd_upper = 0 # Count of odd numbers on upper halves
odd_lower = 0 # Count of odd numbers on lower halves
for _ in range(n):
x, y = map(int, input().split())
upper_sum += x
lower_sum += y
odd_upper += x % 2
odd_lower += y % 2
# Check if the initial sums are already even
if upper_sum % 2 == 0 and lower_sum % 2 == 0:
print(0)
elif (odd_upper % 2 == 0 and odd_lower % 2 == 0) or (odd_upper % 2 == 1 and odd_lower % 2 == 1):
# If both upper and lower halves have even or odd counts of odd numbers, it's possible to achieve an even sum.
print(1)
else:
# If one half has an odd count of odd numbers and the other half has an even count, it's impossible.
print(-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A company has *n* employees numbered from 1 to *n*. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee *A* is said to be the superior of another employee *B* if at least one of the following is true:
- Employee *A* is the immediate manager of employee *B* - Employee *B* has an immediate manager employee *C* such that employee *A* is the superior of employee *C*.
The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.
Today the company is going to arrange a party. This involves dividing all *n* employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees *A* and *B* such that *A* is the superior of *B*.
What is the minimum number of groups that must be formed?
|
```python
def dfs(x, n = 0, m = -1):
color[x] = n
print(x, n, m)
for i in A[x] - set([m]):
dfs(i, n + 1, x)
n = int(input())
A = [set() for i in range(n)]
for i in range(n):
if (a:=int(input())) != -1: A[a - 1].add(i)
#print(A)
color, ind = [-1 for i in range(n)], 0
while -1 in color:
while color[ind] != -1: ind += 1
dfs(ind)
print(max(color) + 1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Kyoya Ootori has a bag with *n* colored balls that are colored with *k* different colors. The colors are labeled from 1 to *k*. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color *i* before drawing the last ball of color *i*<=+<=1 for all *i* from 1 to *k*<=-<=1. Now he wonders how many different ways this can happen.
|
```python
# import sys
# sys.stdin = open("309_Div2_ProbC.txt")
n = (int(input()))
binomial = [[0 for x in range(1010)] for x in range(1010)]
binomial[0][0] = 1
i = 1
row = len(binomial)
col = len(binomial[0])
while i< row:
binomial[i][0] = 1
i+=1
mod = int(1e9+7)
i =1
while i< row:
j=1
while j<col:
binomial[i][j] = (binomial[i-1][j-1]+binomial[i-1][j])%mod
j+=1
i+=1
result = 1
total = 0
for i in range(n):
x = (int(input()))
result = (result * (binomial[total+x-1][x-1]))%mod
total+=x
print(result)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The Cartesian coordinate system is set in the sky. There you can see *n* stars, the *i*-th has coordinates (*x**i*, *y**i*), a maximum brightness *c*, equal for all stars, and an initial brightness *s**i* (0<=≤<=*s**i*<=≤<=*c*).
Over time the stars twinkle. At moment 0 the *i*-th star has brightness *s**i*. Let at moment *t* some star has brightness *x*. Then at moment (*t*<=+<=1) this star will have brightness *x*<=+<=1, if *x*<=+<=1<=≤<=*c*, and 0, otherwise.
You want to look at the sky *q* times. In the *i*-th time you will look at the moment *t**i* and you will see a rectangle with sides parallel to the coordinate axes, the lower left corner has coordinates (*x*1*i*, *y*1*i*) and the upper right — (*x*2*i*, *y*2*i*). For each view, you want to know the total brightness of the stars lying in the viewed rectangle.
A star lies in a rectangle if it lies on its border or lies strictly inside it.
|
```python
# cook your dish here
import string
class solutions():
def __init__(self, n, c, stars):
self.n = n
self.c = c
self.stars = stars
def answer(self, Q):
t, x1, y1, x2, y2 = Q
Sum = 0
for i in range(len(self.stars)):
x,y,s = self.stars[i]
if x>=x1 and x<=x2 and y>=y1 and y<=y2:
Sum += (s + t)%(self.c + 1)
return Sum
if __name__ == "__main__":
n,q,c = tuple(map(int, input().split()))
stars = []
for i in range(n):
(x,y,s) = tuple(map(int, input().split()))
stars.append((x,y,s))
ob = solutions(n,c,stars)
# Q = []
for i in range(q):
(t, x1, y1, x2, y2) = tuple(map(int, input().split()))
print(ob.answer((t, x1, y1, x2, y2)))
```
|
|
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
def can_say_hello(s):
target_word = "hello"
target_index = 0
for char in s:
if char == target_word[target_index]:
target_index += 1
if target_index == len(target_word):
return "YES"
return "NO"
# Read input
s = input().strip()
# Check if Vasya can say hello
result = can_say_hello(s)
print(result)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc. However, it's easy to make a mistake during the «translation». Vasya translated word *s* from Berlandish into Birlandish as *t*. Help him: find out if he translated the word correctly.
|
```python
'''
Online Python Compiler.
Code, Compile, Run and Debug python program online.
Write your code in this editor and press "Run" button to execute it.
'''
n = input()
s=input()
def rev(s):
return s[::-1]
st=n.lower()
st1=s.lower()
if st==st1:
print("YES",end="\n")
else:
print("NO",end="\n")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Sereja has an array *a*, consisting of *n* integers *a*1, *a*2, ..., *a**n*. The boy cannot sit and do nothing, he decided to study an array. Sereja took a piece of paper and wrote out *m* integers *l*1,<=*l*2,<=...,<=*l**m* (1<=≤<=*l**i*<=≤<=*n*). For each number *l**i* he wants to know how many distinct numbers are staying on the positions *l**i*, *l**i*<=+<=1, ..., *n*. Formally, he want to find the number of distinct numbers among *a**l**i*,<=*a**l**i*<=+<=1,<=...,<=*a**n*.?
Sereja wrote out the necessary array elements but the array was so large and the boy was so pressed for time. Help him, find the answer for the described question for each *l**i*.
|
```python
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 25 13:26:04 2023
@author: 2000016913
"""
for _ in range(int(input())):
flag=False
n=int(input())
l=list(map(int, input().split()))
for i in range(n):
if flag:
break
for j in range(i+1,n):
max_=max(l[i:j+1])
min_=min(l[i:j+1])
if l[i]==max_ or l[j]==max_ or l[i]==min_ or l[j]==min_:
continue
else:
print(i+1,j+1)
flag=True
break
if not flag:
print(-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes.
You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consists of several words. For each language, all words are distinct, i.e. they are spelled differently. Moreover, the words of these languages have a one-to-one correspondence, that is, for each word in each language, there exists exactly one word in the other language having has the same meaning.
You can write down every word the professor says in either the first language or the second language. Of course, during the lecture you write down each word in the language in which the word is shorter. In case of equal lengths of the corresponding words you prefer the word of the first language.
You are given the text of the lecture the professor is going to read. Find out how the lecture will be recorded in your notes.
|
```python
n,m=map(int,input().split())
dct=dict()
for i in range(m):
a,b=input().split()
dct[a]=b
for i in input().split():
print([i,dct[i]][len(i)>len(dct[i])], end=" ")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
For a given positive integer *n* denote its *k*-rounding as the minimum positive integer *x*, such that *x* ends with *k* or more zeros in base 10 and is divisible by *n*.
For example, 4-rounding of 375 is 375·80<==<=30000. 30000 is the minimum integer such that it ends with 4 or more zeros and is divisible by 375.
Write a program that will perform the *k*-rounding of *n*.
|
```python
n, k = map(int, input().split())
s = 10 ** k
for d in [2, 5]:
while n % d == s % d == 0:
n //= d
s //= d
print(s)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a tetrahedron. Let's mark its vertices with letters *A*, *B*, *C* and *D* correspondingly.
An ant is standing in the vertex *D* of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place.
You do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertex *D* to itself in exactly *n* steps. In other words, you are asked to find out the number of different cyclic paths with the length of *n* from vertex *D* to itself. As the number can be quite large, you should print it modulo 1000000007 (109<=+<=7).
|
```python
x=int(input())
ans=[]
ans.append(3)
x-=2
while x!=0:
ans.reverse()
ans.append(ans[0]*2)
x-=1
print(sum(ans))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Theatre Square in the capital city of Berland has a rectangular shape with the size *n*<=×<=*m* meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size *a*<=×<=*a*.
What is the least number of flagstones needed to pave the Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square.
|
```python
import math
p, q, a = map(int, input().split())
horizontal = math.ceil(p / a)
vertical = math.ceil(q / a)
total = horizontal * vertical
print(total)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Valera has array *a*, consisting of *n* integers *a*0,<=*a*1,<=...,<=*a**n*<=-<=1, and function *f*(*x*), taking an integer from 0 to 2*n*<=-<=1 as its single argument. Value *f*(*x*) is calculated by formula , where value *bit*(*i*) equals one if the binary representation of number *x* contains a 1 on the *i*-th position, and zero otherwise.
For example, if *n*<==<=4 and *x*<==<=11 (11<==<=20<=+<=21<=+<=23), then *f*(*x*)<==<=*a*0<=+<=*a*1<=+<=*a*3.
Help Valera find the maximum of function *f*(*x*) among all *x*, for which an inequality holds: 0<=≤<=*x*<=≤<=*m*.
|
```python
n=int(input())
arr=list(map(int,input().split()))
s=input()[::]
sum=sum(arr)
sum2=0
flag=0
for i in range(n):
sum2+=int(s[i])*arr[i]
ans=0
for i in range(n-1,-1,-1):
sum-=arr[i]
if int(s[i])==1:
sum2-arr[i]
if sum>=arr[i]+sum2:
print(ans+sum)
flag=1
break
ans+=arr[i]
if flag==0:
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given an array of *n* integer numbers *a*0,<=*a*1,<=...,<=*a**n*<=-<=1. Find the distance between two closest (nearest) minimums in it. It is guaranteed that in the array a minimum occurs at least two times.
|
```python
t=int(input())
l=list(map(int,input().split()))
p=[]
m=min(l)
for i in range(t):
if(l[i]==m):
p.append(i)
m=p[1]-p[0]
j=1
while(j<len(p)-1):
if(p[j+1]-p[j]<m):
m=p[j+1]-p[j]
j+=1
print(m)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corresponding lowercase letter. Help Petya perform the comparison.
|
```python
a=list(input())
b=list(input())
a.sort()
b.sort()
if (a>b):
print(1)
if (b>a):
print(-1)
else:
print(0)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Kirill plays a new computer game. He came to the potion store where he can buy any potion. Each potion is characterized by two integers — amount of experience and cost. The efficiency of a potion is the ratio of the amount of experience to the cost. Efficiency may be a non-integer number.
For each two integer numbers *a* and *b* such that *l*<=≤<=*a*<=≤<=*r* and *x*<=≤<=*b*<=≤<=*y* there is a potion with experience *a* and cost *b* in the store (that is, there are (*r*<=-<=*l*<=+<=1)·(*y*<=-<=*x*<=+<=1) potions).
Kirill wants to buy a potion which has efficiency *k*. Will he be able to do this?
|
```python
l,r,x,y,k=[int(x) for x in input().split()]
f=l/x
s=r/y
t=l/y
f=r/x
if((f<=k<=s) or (s<=k<=f) or (t<=k<=f)or(f<=k<=t)):
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.
During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.
You have been given information on current inventory numbers for *n* items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to *n* by changing the number of as few items as possible. Let us remind you that a set of *n* numbers forms a permutation if all the numbers are in the range from 1 to *n*, and no two numbers are equal.
|
```python
n = int(input())
a = [int(i) for i in input().split(' ')]
m = {}
for i in range(1, 100001):
m[i] = []
zeroIndexes = []
for i in range(n):
m[a[i]].append(i)
for i in range(1, n+1):
if len(m[i])==0:
zeroIndexes.append(i)
for i in range(1, 100001):
if len(m[i])<2 and i<=n: continue
if len(m[i])==0: continue
a[m[i][-1]] = zeroIndexes[-1]
m[i].pop()
zeroIndexes.pop()
print(' '.join([str(s) for s in a]))
```
|
|
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
t=int(input())
L=[int(i) for i in input().split()]
D={}
first1=-1
first2=-1
for i in range(len(L)):
if L[i]%2==0:
if first2==-1:
first2=i
else:
if first1==-1:
first1=i
c=0
for i in range(3):
if(L[i]%2==0):
c+=1;
if c>=2:
print(first1+1)
else:
print(first2+1)
```
|
|
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
words = input().split()
a = int(words[0])
b = int(words[1])
if a == b:
print(a)
else:
print(1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At that as little as possible letters should be changed in the word. For example, the word HoUse must be replaced with house, and the word ViP — with VIP. If a word contains an equal number of uppercase and lowercase letters, you should replace all the letters with lowercase ones. For example, maTRIx should be replaced by matrix. Your task is to use the given method on one given word.
|
```python
a =input ()
number = len(a)
af=str(a)
small = 0
for y in range (number) :
if a[y] >= 'a':
small += 1
if (small >= number/2):
print (af.lower())
else:
print (af.upper ())
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Bizon the Champion is called the Champion for a reason.
Bizon the Champion has recently got a present — a new glass cupboard with *n* shelves and he decided to put all his presents there. All the presents can be divided into two types: medals and cups. Bizon the Champion has *a*1 first prize cups, *a*2 second prize cups and *a*3 third prize cups. Besides, he has *b*1 first prize medals, *b*2 second prize medals and *b*3 third prize medals.
Naturally, the rewards in the cupboard must look good, that's why Bizon the Champion decided to follow the rules:
- any shelf cannot contain both cups and medals at the same time; - no shelf can contain more than five cups; - no shelf can have more than ten medals.
Help Bizon the Champion find out if we can put all the rewards so that all the conditions are fulfilled.
|
```python
from math import ceil
a1, a2, a3=map(int, input().split())
b1, b2, b3=map(int, input().split())
n= int(input())
if n>= ceil((a1+a2+a3)/5)+ceil((b1+b2+b3)/10):
print('YES')
else:
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A magic number is a number formed by concatenation of numbers 1, 14 and 144. We can use each of these numbers any number of times. Therefore 14144, 141414 and 1411 are magic numbers but 1444, 514 and 414 are not.
You're given a number. Determine if it is a magic number or not.
|
```python
s = input()
if len(set(s)) <= 2 and "1" in s or "4" in s:
if s[0] != "1":
print("NO")
elif s.find("444") != -1:
print("NO")
else:
print("YES")
else:
print("NO")
```
|
|
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
a=input()
true=0
if "h" in a:
c=""
c=c+a[a.index("l")+1:len(a)]
if "e" in c:
d=""
d=d+c[c.index("l")+1:len(c)]
if "l" in d:
e=""
e=e+d[d.index("l")+1:len(d)]
if "l" in e:
f=""
f=f+e[e.index("l")+1:len(e)]
if "o" in f:
true=1
if true==1:
print("YES")
else:
print("NO")
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.