source
stringclasses 3
values | instruction
stringlengths 23
3.97k
| input
stringclasses 1
value | output
stringlengths 1
3.75k
|
---|---|---|---|
MatrixStudio/Codeforces-Python-Submissions
|
You are given an integer *N*. Consider all possible segments on the coordinate axis with endpoints at integer points with coordinates between 0 and *N*, inclusive; there will be of them.
You want to draw these segments in several layers so that in each layer the segments don't overlap (they might touch at the endpoints though). You can not move the segments to a different location on the coordinate axis.
Find the minimal number of layers you have to use for the given *N*.
|
```python
import math
n = int(input())
print( (math.floor(i)+1) * (n-1) )
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
This is an interactive problem. In the output section below you will see the information about flushing the output.
Bear Limak thinks of some hidden number — an integer from interval [2,<=100]. Your task is to say if the hidden number is prime or composite.
Integer *x*<=><=1 is called prime if it has exactly two distinct divisors, 1 and *x*. If integer *x*<=><=1 is not prime, it's called composite.
You can ask up to 20 queries about divisors of the hidden number. In each query you should print an integer from interval [2,<=100]. The system will answer "yes" if your integer is a divisor of the hidden number. Otherwise, the answer will be "no".
For example, if the hidden number is 14 then the system will answer "yes" only if you print 2, 7 or 14.
When you are done asking queries, print "prime" or "composite" and terminate your program.
You will get the Wrong Answer verdict if you ask more than 20 queries, or if you print an integer not from the range [2,<=100]. Also, you will get the Wrong Answer verdict if the printed answer isn't correct.
You will get the Idleness Limit Exceeded verdict if you don't print anything (but you should) or if you forget about flushing the output (more info below).
|
```python
p = [2, 3, 4, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
a = []
for i in range(16):
print(p[i])
a.append(input())
if a.count('yes') > 1:
print('composite')
else:
print('prime')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Mishka got an integer array $a$ of length $n$ as a birthday present (what a surprise!).
Mishka doesn't like this present and wants to change it somehow. He has invented an algorithm and called it "Mishka's Adjacent Replacements Algorithm". This algorithm can be represented as a sequence of steps:
- Replace each occurrence of $1$ in the array $a$ with $2$; - Replace each occurrence of $2$ in the array $a$ with $1$; - Replace each occurrence of $3$ in the array $a$ with $4$; - Replace each occurrence of $4$ in the array $a$ with $3$; - Replace each occurrence of $5$ in the array $a$ with $6$; - Replace each occurrence of $6$ in the array $a$ with $5$; - $\dots$ - Replace each occurrence of $10^9 - 1$ in the array $a$ with $10^9$; - Replace each occurrence of $10^9$ in the array $a$ with $10^9 - 1$.
Note that the dots in the middle of this algorithm mean that Mishka applies these replacements for each pair of adjacent integers ($2i - 1, 2i$) for each $i \in\{1, 2, \ldots, 5 \cdot 10^8\}$ as described above.
For example, for the array $a = [1, 2, 4, 5, 10]$, the following sequence of arrays represents the algorithm:
$[1, 2, 4, 5, 10]$ $\rightarrow$ (replace all occurrences of $1$ with $2$) $\rightarrow$ $[2, 2, 4, 5, 10]$ $\rightarrow$ (replace all occurrences of $2$ with $1$) $\rightarrow$ $[1, 1, 4, 5, 10]$ $\rightarrow$ (replace all occurrences of $3$ with $4$) $\rightarrow$ $[1, 1, 4, 5, 10]$ $\rightarrow$ (replace all occurrences of $4$ with $3$) $\rightarrow$ $[1, 1, 3, 5, 10]$ $\rightarrow$ (replace all occurrences of $5$ with $6$) $\rightarrow$ $[1, 1, 3, 6, 10]$ $\rightarrow$ (replace all occurrences of $6$ with $5$) $\rightarrow$ $[1, 1, 3, 5, 10]$ $\rightarrow$ $\dots$ $\rightarrow$ $[1, 1, 3, 5, 10]$ $\rightarrow$ (replace all occurrences of $10$ with $9$) $\rightarrow$ $[1, 1, 3, 5, 9]$. The later steps of the algorithm do not change the array.
Mishka is very lazy and he doesn't want to apply these changes by himself. But he is very interested in their result. Help him find it.
|
```python
n = int(input())
a = input().split()
numbers = []
for item in a:
numbers.append(int(item))
m = max(numbers)
s = ''
for k in numbers:
s += str(k) + ' '
for i in range(1, m+1):
if s.__contains__(str(i)):
if i%2 == 1:
s = s.replace(str(i), str(i+1))
elif i%2 == 0:
s = s.replace(str(i), str(i - 1))
answer = s.split()
re = []
for ans in answer:
re.append(int(ans))
for final in re:
print(final, end=' ')
```
|
|
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
d = input()
e = input()
f = []
for i in d:
f.append(i)
f.reverse()
print("YES" if "".join(f) == e else "NO")
quit()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Alice got an array of length $n$ as a birthday present once again! This is the third year in a row!
And what is more disappointing, it is overwhelmengly boring, filled entirely with zeros. Bob decided to apply some changes to the array to cheer up Alice.
Bob has chosen $m$ changes of the following form. For some integer numbers $x$ and $d$, he chooses an arbitrary position $i$ ($1 \le i \le n$) and for every $j \in [1, n]$ adds $x + d \cdot dist(i, j)$ to the value of the $j$-th cell. $dist(i, j)$ is the distance between positions $i$ and $j$ (i.e. $dist(i, j) = |i - j|$, where $|x|$ is an absolute value of $x$).
For example, if Alice currently has an array $[2, 1, 2, 2]$ and Bob chooses position $3$ for $x = -1$ and $d = 2$ then the array will become $[2 - 1 + 2 \cdot 2,~1 - 1 + 2 \cdot 1,~2 - 1 + 2 \cdot 0,~2 - 1 + 2 \cdot 1]$ = $[5, 2, 1, 3]$. Note that Bob can't choose position $i$ outside of the array (that is, smaller than $1$ or greater than $n$).
Alice will be the happiest when the elements of the array are as big as possible. Bob claimed that the arithmetic mean value of the elements will work fine as a metric.
What is the maximum arithmetic mean value Bob can achieve?
|
```python
def findmin(size, changes):
avg = 0
for a, b in changes:
avg += a
if b == 0:
continue
if b > 0:
avg += (size - 1) / 2.0 * b
else:
avg += (size / 2) * (size / 2 + 1) / 2.0 * b / size
return avg
ina, inn = map(int, input().split(' '))
inx = []
for aa in range(inn):
inx.append(list(map(int, input().split(' '))))
print(findmin(ina, inx))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There is a square matrix *n*<=×<=*n*, consisting of non-negative integer numbers. You should find such a way on it that
- starts in the upper left cell of the matrix; - each following cell is to the right or down from the current cell; - the way ends in the bottom right cell.
Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros.
|
```python
import sys
input = sys.stdin.readline
from math import *
from bisect import *
from itertools import *
from functools import reduce, lru_cache
from collections import Counter, defaultdict
def main():
n = int(input())
B = [list(map(int, input().split())) for _ in range(n)]
def F(x, p):
r = 0
while not x % p:
r += 1
x //= p
return r
for x in range(n):
if not all(B[x]):
print(0)
print("D" * x + "R" * (n - 1) + "D" * (n - 1 - x))
return
B = ([[F(i, 2) for i in l] for l in B], [[F(i, 5) for i in l] for l in B])
def P(p):
T = B[p]
for i in range(1, n):
T[0][i] += T[0][i - 1]
T[i][0] += T[i - 1][0]
for x in range(1, n):
for y in range(1, n):
T[x][y] += min(T[x - 1][y], T[x][y - 1])
x, y, P = n - 1, n - 1, []
while x and y:
if T[x - 1][y] < T[x][y - 1]:
x -= 1
P.append("R")
else:
y -= 1
P.append("D")
P.extend(["R"] * x + ["D"] * y)
return T[-1][-1], "".join(P[::-1])
R = min(P(0), P(1))
print(R[0])
print(R[1])
if __name__ == "__main__":
main()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The polar bears are going fishing. They plan to sail from (*s**x*,<=*s**y*) to (*e**x*,<=*e**y*). However, the boat can only sail by wind. At each second, the wind blows in one of these directions: east, south, west or north. Assume the boat is currently at (*x*,<=*y*).
- If the wind blows to the east, the boat will move to (*x*<=+<=1,<=*y*). - If the wind blows to the south, the boat will move to (*x*,<=*y*<=-<=1). - If the wind blows to the west, the boat will move to (*x*<=-<=1,<=*y*). - If the wind blows to the north, the boat will move to (*x*,<=*y*<=+<=1).
Alternatively, they can hold the boat by the anchor. In this case, the boat stays at (*x*,<=*y*). Given the wind direction for *t* seconds, what is the earliest time they sail to (*e**x*,<=*e**y*)?
|
```python
t,sx,sy,ex,ey=map(int,input().split())
s=input()
h,v="Z","Z"
if(sx>ex):h="W"
elif(sx<ex):h="E"
if(sy>ey):v="S"
elif(sy<ey):v="N"
a,b=abs(sx-ex),abs(sy-ey);c=0
for i in s:
if(a or b):c+=1
if(h==i and a>0):
a-=1
if(v==i and b>0):
b-=1
if(a!=0 or b!=0):print(-1)
else:print(c)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
After the fourth season Sherlock and Moriary have realized the whole foolishness of the battle between them and decided to continue their competitions in peaceful game of Credit Cards.
Rules of this game are simple: each player bring his favourite *n*-digit credit card. Then both players name the digits written on their cards one by one. If two digits are not equal, then the player, whose digit is smaller gets a flick (knock in the forehead usually made with a forefinger) from the other player. For example, if *n*<==<=3, Sherlock's card is 123 and Moriarty's card has number 321, first Sherlock names 1 and Moriarty names 3 so Sherlock gets a flick. Then they both digit 2 so no one gets a flick. Finally, Sherlock names 3, while Moriarty names 1 and gets a flick.
Of course, Sherlock will play honestly naming digits one by one in the order they are given, while Moriary, as a true villain, plans to cheat. He is going to name his digits in some other order (however, he is not going to change the overall number of occurences of each digit). For example, in case above Moriarty could name 1, 2, 3 and get no flicks at all, or he can name 2, 3 and 1 to give Sherlock two flicks.
Your goal is to find out the minimum possible number of flicks Moriarty will get (no one likes flicks) and the maximum possible number of flicks Sherlock can get from Moriarty. Note, that these two goals are different and the optimal result may be obtained by using different strategies.
|
```python
n = int(input())
s = list(map(int, input()))
m = list(map(int, input()))
a, b = s.copy(), m.copy()
c, k = 0, 0
m.sort()
for i in range(len(s)):
for j in range(len(m)):
if m[j] >= s[i]:
c += 1
del m[j]
break
print(n - c)
b.sort()
for i in range(len(a)):
for j in range(len(b)):
if b[j] > a[i]:
k += 1
del b[j]
break
print(k)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Imp is in a magic forest, where xorangles grow (wut?)
A xorangle of order *n* is such a non-degenerate triangle, that lengths of its sides are integers not exceeding *n*, and the xor-sum of the lengths is equal to zero. Imp has to count the number of distinct xorangles of order *n* to get out of the forest.
Formally, for a given integer *n* you have to find the number of such triples (*a*,<=*b*,<=*c*), that:
- 1<=≤<=*a*<=≤<=*b*<=≤<=*c*<=≤<=*n*; - , where denotes the [bitwise xor](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of integers *x* and *y*. - (*a*,<=*b*,<=*c*) form a non-degenerate (with strictly positive area) triangle.
|
```python
import sys
input = sys.stdin.buffer.readline
def process(n):
answer = 0
for a in range(1, n+1):
for b in range(a, n+1):
c = a^b
if 1 <= a <= b <= c <= n and a+b > c:
answer+=1
sys.stdout.write(f'{answer}\n')
n = int(input())
process(n)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second.
One day in 230 AD Shapur was trying to find out if any one can possibly do calculations faster than him. As a result he made a very great contest and asked every one to come and take part.
In his contest he gave the contestants many different pairs of numbers. Each number is made from digits 0 or 1. The contestants should write a new number corresponding to the given pair of numbers. The rule is simple: The *i*-th digit of the answer is 1 if and only if the *i*-th digit of the two given numbers differ. In the other case the *i*-th digit of the answer is 0.
Shapur made many numbers and first tried his own speed. He saw that he can perform these operations on numbers of length ∞ (length of a number is number of digits in it) in a glance! He always gives correct answers so he expects the contestants to give correct answers, too. He is a good fellow so he won't give anyone very big numbers and he always gives one person numbers of same length.
Now you are going to take part in Shapur's contest. See if you are faster and more accurate.
|
```python
l=input()
j=input()
for i in range(len(l)):
if l[i]==j[i]:print('0',end='')
else:print('1',end='')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Permutation *p* is an ordered set of integers *p*1,<=<=*p*2,<=<=...,<=<=*p**n*, consisting of *n* distinct positive integers, each of them doesn't exceed *n*. We'll denote the *i*-th element of permutation *p* as *p**i*. We'll call number *n* the size or the length of permutation *p*1,<=<=*p*2,<=<=...,<=<=*p**n*.
The decreasing coefficient of permutation *p*1,<=*p*2,<=...,<=*p**n* is the number of such *i* (1<=≤<=*i*<=<<=*n*), that *p**i*<=><=*p**i*<=+<=1.
You have numbers *n* and *k*. Your task is to print the permutation of length *n* with decreasing coefficient *k*.
|
```python
def main():
n, k = map(int, input().split())
z = [f'{i}' for i in range(1, n + 1)]
x = list(reversed(z))[:k]
print((' '.join(x) + " " + ' '.join(z[:n - k])).strip())
if __name__ == '__main__':
main()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The Little Girl loves problems on games very much. Here's one of them.
Two players have got a string *s*, consisting of lowercase English letters. They play a game that is described by the following rules:
- The players move in turns; In one move the player can remove an arbitrary letter from string *s*. - If the player before his turn can reorder the letters in string *s* so as to get a palindrome, this player wins. A palindrome is a string that reads the same both ways (from left to right, and vice versa). For example, string "abba" is a palindrome and string "abc" isn't.
Determine which player will win, provided that both sides play optimally well — the one who moves first or the one who moves second.
|
```python
s = input()
freq = dict()
for ele in s:
if(ele not in freq):
freq[ele] = 1
else:
freq[ele] += 1
c = 0
for v in freq.values():
if(v%2==1):
c+=1
if(c==0):
print("First")
elif(c%2==1):
print("First")
else:
print("Second")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You have probably registered on Internet sites many times. And each time you should enter your invented password. Usually the registration form automatically checks the password's crypt resistance. If the user's password isn't complex enough, a message is displayed. Today your task is to implement such an automatic check.
Web-developers of the company Q assume that a password is complex enough, if it meets all of the following conditions:
- the password length is at least 5 characters; - the password contains at least one large English letter; - the password contains at least one small English letter; - the password contains at least one digit.
You are given a password. Please implement the automatic check of its complexity for company Q.
|
```python
import string
s = set(input())
print(('Too weak', 'Correct')[len(s) >= 5 and len(s & set(string.ascii_lowercase)) > 0 and \
len(s & set(string.ascii_uppercase)) > 0 and \
len(s & set(string.digits)) > 0])
```
|
|
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()
b="hello"
j=0
c=""
for i in range(0,len(a)):
if a[i]==b[j] and c!=b and j<=4:
c=c+b[j]
j=j+1
else:
continue
if c==b:
break
if c==b:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya loves long lucky numbers very much. He is interested in the minimum lucky number *d* that meets some condition. Let *cnt*(*x*) be the number of occurrences of number *x* in number *d* as a substring. For example, if *d*<==<=747747, then *cnt*(4)<==<=2, *cnt*(7)<==<=4, *cnt*(47)<==<=2, *cnt*(74)<==<=2. Petya wants the following condition to fulfil simultaneously: *cnt*(4)<==<=*a*1, *cnt*(7)<==<=*a*2, *cnt*(47)<==<=*a*3, *cnt*(74)<==<=*a*4. Petya is not interested in the occurrences of other numbers. Help him cope with this task.
|
```python
from math import *
from fractions import *
from sys import *
def li():
return list(map(int, input().split(" ")))
a = li()
if abs(a[2]-a[3]) > 1:
print(-1)
exit()
if a[2] == a[3]:
ans = "47"*a[2]+"4"
elif a[2] > a[3]:
ans = "47"*a[2]
else:
ans = "74"*a[3]
f = a[0]-ans.count("4")
s = a[1]-ans.count("7")
if s < 0 or f < 0:
ans = -1
elif s>0 or f>0:
s+=1
f+=1
if ans[:2] == "47":
ans = "4"*f + "7"*s + ans[2:]
else:
ans = "7"*s + "4"*f + ans[2:]
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality of the first laptop is higher (strictly greater) than the quality of the second laptop.
Please, check the guess of Alex. You are given descriptions of *n* laptops. Determine whether two described above laptops exist.
|
```python
for n in range(int(input())):
a,b=input().split()
if a!=b:
print("Happy Alex")
exit()
print("Poor Alex")
```
|
|
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())
a=list(map(int,input().split()))
s,s1=0,[]
for i in range(n):
s+=a[i]
s1.append(s)
s,s2=0,[]
for i in range(n):
s+=a[n-i-1]
s2=[s]+s2
ans=0
for i in range(n-1):
if s1[i]==s2[i+1]:
ans+=1
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
In the Bus of Characters there are $n$ rows of seat, each having $2$ seats. The width of both seats in the $i$-th row is $w_i$ centimeters. All integers $w_i$ are distinct.
Initially the bus is empty. On each of $2n$ stops one passenger enters the bus. There are two types of passengers:
- an introvert always chooses a row where both seats are empty. Among these rows he chooses the one with the smallest seats width and takes one of the seats in it; - an extrovert always chooses a row where exactly one seat is occupied (by an introvert). Among these rows he chooses the one with the largest seats width and takes the vacant place in it.
You are given the seats width in each row and the order the passengers enter the bus. Determine which row each passenger will take.
|
```python
n = int(input())
u = list(map(int, input().split()))
for i in range(n):
u[i] = (u[i], i)
h = list(map(int, list(input())))
def f(t):
return t[0]
k = 2 * n
p = [0] * k
ex = []
it = u[:]
it.sort(key = f)
ind = 0
for i in range(k):
if not h[i]:
p[i] = it[ind][1] + 1
ex.append(p[i])
ind += 1
else:
p[i] = ex[-1]
ex.pop()
for i in range(k):
print(p[i], end = ' ')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Summer holidays! Someone is going on trips, someone is visiting grandparents, but someone is trying to get a part-time job. This summer Noora decided that she wants to earn some money, and took a job in a shop as an assistant.
Shop, where Noora is working, has a plan on the following *n* days. For each day sales manager knows exactly, that in *i*-th day *k**i* products will be put up for sale and exactly *l**i* clients will come to the shop that day. Also, the manager is sure, that everyone, who comes to the shop, buys exactly one product or, if there aren't any left, leaves the shop without buying anything. Moreover, due to the short shelf-life of the products, manager established the following rule: if some part of the products left on the shelves at the end of the day, that products aren't kept on the next day and are sent to the dump.
For advertising purposes manager offered to start a sell-out in the shop. He asked Noora to choose any *f* days from *n* next for sell-outs. On each of *f* chosen days the number of products were put up for sale would be doubled. Thus, if on *i*-th day shop planned to put up for sale *k**i* products and Noora has chosen this day for sell-out, shelves of the shop would keep 2·*k**i* products. Consequently, there is an opportunity to sell two times more products on days of sell-out.
Noora's task is to choose *f* days to maximize total number of sold products. She asks you to help her with such a difficult problem.
|
```python
# Problem: B. Summer sell-off
# Contest: Codeforces - Codeforces Round #415 (Div. 2)
# URL: https://codeforces.com/contest/810/problem/B
# Memory Limit: 256 MB
# Time Limit: 1000 ms
# Powered by CP Editor (https://github.com/cpeditor/cpeditor)
from sys import stdin
def get_ints(): return list(map(int, stdin.readline().strip().split()))
n,f = get_ints()
a = []
b = []
for _ in range(n):
x,y = get_ints()
a.append([x,y])
sum =0
a = sorted(a,key= lambda day:day[1] if day[0] >0 else day[0],reverse = True )
for i in range(n):
if f >0:
a[i][0] *=2
f-=1
# print(a[i][1] , a[i][0])
sum+=min(a[i][1] , a[i][0])
print(sum)
```
|
|
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
x=int(input())
a=list(map(int,input().split()))
y=min(a)
f=9999999999
s=-111111
for i in range(len(a)):
if a[i]==y:
f=min(f,i-s)
s = i
print(f)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Luba is surfing the Internet. She currently has *n* opened tabs in her browser, indexed from 1 to *n* from left to right. The mouse cursor is currently located at the *pos*-th tab. Luba needs to use the tabs with indices from *l* to *r* (inclusive) for her studies, and she wants to close all the tabs that don't belong to this segment as fast as possible.
Each second Luba can either try moving the cursor to the left or to the right (if the cursor is currently at the tab *i*, then she can move it to the tab *max*(*i*<=-<=1,<=*a*) or to the tab *min*(*i*<=+<=1,<=*b*)) or try closing all the tabs to the left or to the right of the cursor (if the cursor is currently at the tab *i*, she can close all the tabs with indices from segment [*a*,<=*i*<=-<=1] or from segment [*i*<=+<=1,<=*b*]). In the aforementioned expressions *a* and *b* denote the minimum and maximum index of an unclosed tab, respectively. For example, if there were 7 tabs initially and tabs 1, 2 and 7 are closed, then *a*<==<=3, *b*<==<=6.
What is the minimum number of seconds Luba has to spend in order to leave only the tabs with initial indices from *l* to *r* inclusive opened?
|
```python
n,pos,l,r=[*map(int,input().split())]
if(l==1 and r==n):
print(0)
elif(l==1):
print((abs(r-pos))+1)
elif(r==n):
print(abs(pos-l)+1)
else:
print(min((pos-l)*2+abs(r-pos)+2,(pos-l)+abs(r-pos)*2+2))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10*k*.
In the given number of *n* Polycarp wants to remove the least number of digits to get a number that is divisible by 10*k*. For example, if *k*<==<=3, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by 103<==<=1000.
Write a program that prints the minimum number of digits to be deleted from the given integer number *n*, so that the result is divisible by 10*k*. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit).
It is guaranteed that the answer exists.
|
```python
n, k = input().split()
k = int(k)
tot = n.count('0')
if tot < k:
print(len(n)-1)
else:
zeros, ans = 0, 0
j = len(n)-1
while zeros < k:
if n[j] == '0':
zeros += 1
else:
ans += 1
j -= 1
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him.
One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For each contest where this coder participated, he wrote out a single non-negative number — the number of points his favorite coder earned in the contest. Vasya wrote out the points for the contest in the order, in which the contests run (naturally, no two contests ran simultaneously).
Vasya considers a coder's performance in a contest amazing in two situations: he can break either his best or his worst performance record. First, it is amazing if during the contest the coder earns strictly more points that he earned on each past contest. Second, it is amazing if during the contest the coder earns strictly less points that he earned on each past contest. A coder's first contest isn't considered amazing. Now he wants to count the number of amazing performances the coder had throughout his whole history of participating in contests. But the list of earned points turned out long and Vasya can't code... That's why he asks you to help him.
|
```python
n = int(input())
a = list(map(int,input().split()))
k=0
mx=a[0]
mn=a[0]
for i in a:
if i>mx:
mx=i
k+=1
elif i<mn:
mn=i
k+=1
print(k)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Bob programmed a robot to navigate through a 2d maze.
The maze has some obstacles. Empty cells are denoted by the character '.', where obstacles are denoted by '#'.
There is a single robot in the maze. Its start position is denoted with the character 'S'. This position has no obstacle in it. There is also a single exit in the maze. Its position is denoted with the character 'E'. This position has no obstacle in it.
The robot can only move up, left, right, or down.
When Bob programmed the robot, he wrote down a string of digits consisting of the digits 0 to 3, inclusive. He intended for each digit to correspond to a distinct direction, and the robot would follow the directions in order to reach the exit. Unfortunately, he forgot to actually assign the directions to digits.
The robot will choose some random mapping of digits to distinct directions. The robot will map distinct digits to distinct directions. The robot will then follow the instructions according to the given string in order and chosen mapping. If an instruction would lead the robot to go off the edge of the maze or hit an obstacle, the robot will crash and break down. If the robot reaches the exit at any point, then the robot will stop following any further instructions.
Bob is having trouble debugging his robot, so he would like to determine the number of mappings of digits to directions that would lead the robot to the exit.
|
```python
def check(perm) :
global sx, sy, dx, dy, m, n, instr
x = sx
y = sy
for d in instr :
dir = perm[ord(d) - ord('0')]
x = x + dx[dir]
y = y + dy[dir]
#if perm == [2, 3, 0, 1] :
# print(x, y)
if x < 0 or x >= m or y < 0 or y >= n :
return 0
if s[x][y] == '#' :
return 0
if s[x][y] == 'E' :
#print(perm)
return 1
return 0
m, n = map(int, input().split())
sx = sy = 0
ex = ey = 0
s = []
for i in range(0, m) :
s.append(input())
for j in range(0, len(s[i])) :
if s[i][j] == 'S' :
sx = i
sy = j
elif s[i][j] == 'E' :
ex = i
ey = j
instr = input()
dx = [-1, 0, 1, 0]
dy = [0, 1, 0, -1]
ans = 0
perm = [0] * 4
for i in range(0, 4) :
for j in range(0, 4) :
for k in range(0, 4) :
for l in range(0, 4) :
if i != j and i != k and i != l and j != k and j != l and k != l :
perm[0] = i
perm[1] = j
perm[2] = k
perm[3] = l
if check(perm) :
ans = ans + 1
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone.
In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules of the game, Jury must use this second to touch the corresponding strip to make the square go away. As Jury is both smart and lazy, he counted that he wastes exactly *a**i* calories on touching the *i*-th strip.
You've got a string *s*, describing the process of the game and numbers *a*1,<=*a*2,<=*a*3,<=*a*4. Calculate how many calories Jury needs to destroy all the squares?
|
```python
calory_for_strip = list(map(int, input().split()))
s = input()
calories_wasted = 0
for n in s:
calories_wasted += calory_for_strip[int(n) - 1]
print(calories_wasted)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Bash has set out on a journey to become the greatest Pokemon master. To get his first Pokemon, he went to Professor Zulu's Lab. Since Bash is Professor Zulu's favourite student, Zulu allows him to take as many Pokemon from his lab as he pleases.
But Zulu warns him that a group of *k*<=><=1 Pokemon with strengths {*s*1,<=*s*2,<=*s*3,<=...,<=*s**k*} tend to fight among each other if *gcd*(*s*1,<=*s*2,<=*s*3,<=...,<=*s**k*)<==<=1 (see notes for *gcd* definition).
Bash, being smart, does not want his Pokemon to fight among each other. However, he also wants to maximize the number of Pokemon he takes from the lab. Can you help Bash find out the maximum number of Pokemon he can take?
Note: A Pokemon cannot fight with itself.
|
```python
# LUOGU_RID: 122374120
#include <bits/stdc++.h>
#define F(i,s,e) for(int i=s;i<=e;i++)
using namespace std;
const int maxn=1e5+1000;
int a,t[maxn],ans,n,m;
int main()
{
scanf("%d",&n);
F(i,1,n){
scanf("%d",&a[i]);
m=1;
while(a>1){
if(m*m>a+2)break;
m++;
if(!(a%m)){
t[m]++;
while(!(a%m))
a/=m;
}
}
}
F(i,2,maxn){
ans=max(ans,t[i]);
}
cout<<ans<<'\n';
}
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Greg is a beginner bodybuilder. Today the gym coach gave him the training plan. All it had was *n* integers *a*1,<=*a*2,<=...,<=*a**n*. These numbers mean that Greg needs to do exactly *n* exercises today. Besides, Greg should repeat the *i*-th in order exercise *a**i* times.
Greg now only does three types of exercises: "chest" exercises, "biceps" exercises and "back" exercises. Besides, his training is cyclic, that is, the first exercise he does is a "chest" one, the second one is "biceps", the third one is "back", the fourth one is "chest", the fifth one is "biceps", and so on to the *n*-th exercise.
Now Greg wonders, which muscle will get the most exercise during his training. We know that the exercise Greg repeats the maximum number of times, trains the corresponding muscle the most. Help Greg, determine which muscle will get the most training.
|
```python
n=int(input())
chest=0
biceps=0
back=0
line=input().split()
if 1<=n<=20:
for i in range(0, n, 3):
if i<n:
chest+=int(line[i])
if i+1<n:
biceps+=int(line[i+1])
if i+2<n:
back+=int(line[i+2])
if chest>biceps and chest>back:
print('chest')
elif biceps>chest and biceps>back:
print('biceps')
else:
print('back')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
PolandBall is a young, clever Ball. He is interested in prime numbers. He has stated a following hypothesis: "There exists such a positive integer *n* that for each positive integer *m* number *n*·*m*<=+<=1 is a prime number".
Unfortunately, PolandBall is not experienced yet and doesn't know that his hypothesis is incorrect. Could you prove it wrong? Write a program that finds a counterexample for any *n*.
|
```python
def ispr(n):
if n == 2 or n == 3: return True
if n % 2 == 0 or n % 3 == 0 or n < 2: return False
k = 5
while k * k <= n:
if n % k == 0 or n % (k + 2) == 0: return False
k += 6
return True
n = int(input())
for x in range(1, 1001):
if not ispr(n * x + 1):
print(x)
break
else: pass
```
|
|
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
k=int(input())
l=list(map(int,input().split()))
l.sort()
m=(l[k-1]-l[0])
count=0
for i in range(k//2):
if max(l[k-1-i]-l[i],l[i]-l[k-1-i]>=m):
count+=1
print(m,count**2)
```
|
|
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
from collections import defaultdict
strx=input()
text=input()
dict1=defaultdict(int)
for l in strx:
dict1[l]+=1
for l in text:
if l.isalpha() and l in dict1 and dict1[l]!=0:
dict1[l]-=1
elif l.isalpha() and dict1[l]==0:
print('NO')
exit()
print('YES')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed *w* kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Billy are great fans of even numbers, that's why they want to divide the watermelon in such a way that each of the two parts weighs even number of kilos, at the same time it is not obligatory that the parts are equal. The boys are extremely tired and want to start their meal as soon as possible, that's why you should help them and find out, if they can divide the watermelon in the way they want. For sure, each of them should get a part of positive weight.
|
```python
W=int(input("enter weight from 1 to 100))
if W%2==0 and 1<=W<=100 :
Y=W/2
if Y %2==0:
print("YES")
else :
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
String can be called correct if it consists of characters "0" and "1" and there are no redundant leading zeroes. Here are some examples: "0", "10", "1001".
You are given a correct string *s*.
You can perform two different operations on this string:
1. swap any pair of adjacent characters (for example, "101" "110"); 1. replace "11" with "1" (for example, "110" "10").
Let *val*(*s*) be such a number that *s* is its binary representation.
Correct string *a* is less than some other correct string *b* iff *val*(*a*)<=<<=*val*(*b*).
Your task is to find the minimum correct string that you can obtain from the given one using the operations described above. You can use these operations any number of times in any order (or even use no operations at all).
|
```python
import numpy as np
m = input()
bin = int(input())
y = str(bin)
z = y.count('0')
print(np.binary_repr(2**z))
```
|
|
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
user_input = input()
answer = user_input.replace('--','2')
answer = answer.replace('-.','1')
answer = answer.replace('.','0')
print(answer)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Imp is watching a documentary about cave painting.
Some numbers, carved in chaotic order, immediately attracted his attention. Imp rapidly proposed a guess that they are the remainders of division of a number *n* by all integers *i* from 1 to *k*. Unfortunately, there are too many integers to analyze for Imp.
Imp wants you to check whether all these remainders are distinct. Formally, he wants to check, if all , 1<=≤<=*i*<=≤<=*k*, are distinct, i. e. there is no such pair (*i*,<=*j*) that:
- 1<=≤<=*i*<=<<=*j*<=≤<=*k*, - , where is the remainder of division *x* by *y*.
|
```python
from sys import stdin,stdout
n,k=map(int,input().split())
print(["Yes","No"][any((n+1)%i for i in range(2,k+1))])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A and B are preparing themselves for programming contests.
B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.
Initially, the compiler displayed *n* compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix some mistake and then another one mistake.
However, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared — the compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, compilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change.
Can you help B find out exactly what two errors he corrected?
|
```python
n = int(input())
l=list(map(int,input().split()))
l1 = list(map(int,input().split()))
l2 = list(map(int,input().split()))
for i in l:
if i not in l1:
print(i)
break
for i in l1:
if i not in l2:
print(i)
break
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given names of two days of the week.
Please, determine whether it is possible that during some non-leap year the first day of some month was equal to the first day of the week you are given, while the first day of the next month was equal to the second day of the week you are given. Both months should belong to one year.
In this problem, we consider the Gregorian calendar to be used. The number of months in this calendar is equal to 12. The number of days in months during any non-leap year is: 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31.
Names of the days of the week are given with lowercase English letters: "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday".
|
```python
d = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
a, b = input(), input()
x, y = d.index(a), d.index(b)
if (y - x) % 7 in {0, 2, 3}:
print('YES')
else:
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A coordinate line has *n* segments, the *i*-th segment starts at the position *l**i* and ends at the position *r**i*. We will denote such a segment as [*l**i*,<=*r**i*].
You have suggested that one of the defined segments covers all others. In other words, there is such segment in the given set, which contains all other ones. Now you want to test your assumption. Find in the given set the segment which covers all other segments, and print its number. If such a segment doesn't exist, print -1.
Formally we will assume that segment [*a*,<=*b*] covers segment [*c*,<=*d*], if they meet this condition *a*<=≤<=*c*<=≤<=*d*<=≤<=*b*.
|
```python
n = int(input())
a = 1000000001
b = i1 = -1
i2 = -2
for i in range(n):
x, y = map(int, input().split())
if x < a:
a = x
i1 = i
elif x == a and y > b:
i1 = i2 = i
b = y
if y > b:
b = y
i2 = i
elif y == b and x < a:
a = x
i1 = i2 = i
if i1 == i2:
print(i1 + 1)
else:
print(-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given *n*<=×<=*m* table. Each cell of the table is colored white or black. Find the number of non-empty sets of cells such that:
1. All cells in a set have the same color. 1. Every two cells in a set share row or column.
|
```python
n,m=map(int,input().split())
a = [list(map(int,input().split())) for x in range(n)]
s = 0
for row in a:
o,z=0,0
for i in row:
if i==0:
z+=1
else:
o+=1
s+=2**z-1
s+=2**o-1
for col in range(m):
o,z=0,0
for j in range(n):
if a[j][col]==0:
z+=1
else:
o+=1
s+=2**z-1-z
s+=2**o-1-o
print(s)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The HR manager was disappointed again. The last applicant failed the interview the same way as 24 previous ones. "Do I give such a hard task?" — the HR manager thought. "Just raise number 5 to the power of *n* and get last two digits of the number. Yes, of course, *n* can be rather big, and one cannot find the power using a calculator, but we need people who are able to think, not just follow the instructions."
Could you pass the interview in the machine vision company in IT City?
|
```python
n=int(input())
print(5**n,end="")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A coordinate line has *n* segments, the *i*-th segment starts at the position *l**i* and ends at the position *r**i*. We will denote such a segment as [*l**i*,<=*r**i*].
You have suggested that one of the defined segments covers all others. In other words, there is such segment in the given set, which contains all other ones. Now you want to test your assumption. Find in the given set the segment which covers all other segments, and print its number. If such a segment doesn't exist, print -1.
Formally we will assume that segment [*a*,<=*b*] covers segment [*c*,<=*d*], if they meet this condition *a*<=≤<=*c*<=≤<=*d*<=≤<=*b*.
|
```python
# Tran Duy_ Big 0 Blue
n = input()
n = int(n)
pos = -1
segment_areas = []
check = False
def iscovered(bigseg, smallseg):
return bigseg[0] <= smallseg[0] and bigseg[1] >= smallseg[1]
for i in range(1, n+1):
# Nhap segment
seg = list(map(int, input().split()))
if not segment_areas:
segment_areas.append(seg)
# Kiem tra segment moi vua nhap voi tat ca cac segment da co
# Neu new segment covers old segment nao do trong segment_areas, thi pop segment nho hon va append
# segment moi vao
# Neu chay den cuoi segment_areas ma new segment ko cover old segment nao het thi append
check = False
for j in range(len(segment_areas)):
if iscovered(seg, segment_areas[j]):
segment_areas.pop(j)
segment_areas.insert(j, seg)
pos = i
check = True
elif iscovered(segment_areas[j], seg):
break
if j == len(segment_areas)-1 and check is False:
segment_areas.append(seg)
if len(segment_areas) == 1:
print(pos)
else:
print(-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Sereja and Dima play a game. The rules of the game are very simple. The players have *n* cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The game ends when there is no more cards. The player who has the maximum sum of numbers on his cards by the end of the game, wins.
Sereja and Dima are being greedy. Each of them chooses the card with the larger number during his move.
Inna is a friend of Sereja and Dima. She knows which strategy the guys are using, so she wants to determine the final score, given the initial state of the game. Help her.
|
```python
def li():
return list(map(int,input().split()))
def gi(n):
return [list(map(int,input().split())) for _ in range(n)]
# File input
# import sys
# sys.stdin = open('user.txt','r')
n = int(input())
a = li()
s = d = 0
l , r = 0 , n - 1
while l <= r:
if a[l] > a[r]:
s += a[l]
l += 1
else:
s += a[r]
r -= 1
if l > r:
break
if a[l] > a[r]:
d += a[l]
l += 1
else:
d += a[r]
r -= 1
print(s,d)
```
|
|
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
def untreatedCrimes(n, events):
available = 0
untreated = 0
for event in events:
if event == -1:
if available == 0:
untreated += 1
else:
available -= 1
else:
available += event
return untreated
n = int(input().strip())
events = list(map(int, input().strip().split()))
print(untreatedCrimes(n, events))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Kefa decided to make some money doing business on the Internet for exactly *n* days. He knows that on the *i*-th day (1<=≤<=*i*<=≤<=*n*) he makes *a**i* money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence *a**i*. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.
Help Kefa cope with this task!
|
```python
t = int(input())
arr = list(map(int, input().split()))
count = 1
ans = 1
for i in range(len(arr) - 1):
if arr[i] <= arr[i+1]:
count+=1
else:
ans = max(count,ans)
count = 1
ans = max(count,ans)
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
It's one more school day now. Sasha doesn't like classes and is always bored at them. So, each day he invents some game and plays in it alone or with friends.
Today he invented one simple game to play with Lena, with whom he shares a desk. The rules are simple. Sasha draws *n* sticks in a row. After that the players take turns crossing out exactly *k* sticks from left or right in each turn. Sasha moves first, because he is the inventor of the game. If there are less than *k* sticks on the paper before some turn, the game ends. Sasha wins if he makes strictly more moves than Lena. Sasha wants to know the result of the game before playing, you are to help him.
|
```python
e,b=input().split()
e=int(e)
b=int(b)
ans=e//b
if(ans%2==1):
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Zane the wizard had never loved anyone before, until he fell in love with a girl, whose name remains unknown to us.
The girl lives in house *m* of a village. There are *n* houses in that village, lining in a straight line from left to right: house 1, house 2, ..., house *n*. The village is also well-structured: house *i* and house *i*<=+<=1 (1<=≤<=*i*<=<<=*n*) are exactly 10 meters away. In this village, some houses are occupied, and some are not. Indeed, unoccupied houses can be purchased.
You will be given *n* integers *a*1,<=*a*2,<=...,<=*a**n* that denote the availability and the prices of the houses. If house *i* is occupied, and therefore cannot be bought, then *a**i* equals 0. Otherwise, house *i* can be bought, and *a**i* represents the money required to buy it, in dollars.
As Zane has only *k* dollars to spare, it becomes a challenge for him to choose the house to purchase, so that he could live as near as possible to his crush. Help Zane determine the minimum distance from his crush's house to some house he can afford, to help him succeed in his love.
|
```python
n,m,k=map(int,input().split())
a=list(map(int,input().split()))
min1=float("inf")
for i in range(n):
if a[i]!=0 and a[i]<=k and min1>(abs( (m-1)-(a[i]) )*10):
min1=(abs( (m-1)-(i) )*10)
print(min1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Everyone loves a freebie. Especially students.
It is well-known that if in the night before exam a student opens window, opens the student's record-book and shouts loudly three times "Fly, freebie, fly!" — then flown freebie helps him to pass the upcoming exam.
In the night before the exam on mathematical analysis *n* students living in dormitory shouted treasured words. The *i*-th student made a sacrament at the time *t**i*, where *t**i* is the number of seconds elapsed since the beginning of the night.
It is known that the freebie is a capricious and willful lady. That night the freebie was near dormitory only for *T* seconds. Therefore, if for two students their sacrament times differ for more than *T*, then the freebie didn't visit at least one of them.
Since all students are optimists, they really want to know what is the maximal number of students visited by the freebie can be.
|
```python
import math
n = int(input())
a = list(map(int,input().strip().split()))[:n]
t=int(input())
a.sort()
c=0
for i in range(0,n-1,1):
if(math.fabs(a[i]-a[i+1])<=t):
c+=1
else:
continue
print(c)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word.
Note, that during capitalization all the letters except the first one remains unchanged.
|
```python
word=input()
print(word[0].upper()+word[1:len(word)])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to *m*) at the end of the game, than wins the one of them who scored at least *m* points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points.
|
```python
n = int(input())
players = dict()
winner = ('',0)
for round in range(n):
name, points = input().split()
points = int(points)
if name not in players:
players[name] = points
else:
players[name] += points
players_scores = list(players.values())
max_score = max(players_scores)
if players[name] > max_score:
winner = name, max_score
else:
max_index = players_scores.index(max_score)
players_names = list(players.keys())
winner = players_names[max_index], max_score
#print(players, winner, sep = ' winner= ')
print(winner[0])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
"What a pity it's already late spring," sighs Mino with regret, "one more drizzling night and they'd be gone."
"But these blends are at their best, aren't they?" Absorbed in the landscape, Kanno remains optimistic.
The landscape can be expressed as a row of consecutive cells, each of which either contains a flower of colour amber or buff or canary yellow, or is empty.
When a flower withers, it disappears from the cell that it originally belonged to, and it spreads petals of its colour in its two neighbouring cells (or outside the field if the cell is on the side of the landscape). In case petals fall outside the given cells, they simply become invisible.
You are to help Kanno determine whether it's possible that after some (possibly none or all) flowers shed their petals, at least one of the cells contains all three colours, considering both petals and flowers. Note that flowers can wither in arbitrary order.
|
```python
n=input()
a='ABC'
b='ACB'
c='BAC'
d='BCA'
e='CAB'
f='CBA'
x=n.split('.')
if a in n:
print('Yes')
elif b in n:
print('Yes')
elif c in n:
print('Yes')
elif d in n:
print('Yes')
elif e in n:
print('Yes')
elif f in n:
print('Yes')
else:
print('No')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area.
Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard.
Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules.
|
```python
def f(a):
if a[0][0] == a[1][0] and a[0][1] + a[1][1] == a[2][0] and a[0][0] + a[2][1] == a[2][0]:
try:
print(a[2][0])
ans = [''] * a[2][0]
for i in range(a[0][0]):
for j in range(a[0][1]):
ans[i] += a[0][2]
for i in range(a[1][0]):
for j in range(a[1][1]):
ans[i] += a[1][2]
for i in range(a[2][1]):
for j in range(a[2][0]):
ans[i+a[0][1]] += a[2][2]
for i in ans:
print(i)
except:
return
exit()
if a[0][0] == a[1][0] == a[2][0] and a[0][0] == a[0][1]+a[1][1] + a[2][1]:
try:
print(a[0][0])
ans = ['']*a[0][0]
for k in range(3):
for i in range(a[k][0]):
for j in range(a[k][1]):
ans[i] += a[k][2]
for i in ans:
print(i)
except:
return
exit()
import itertools
x1, y1, x2, y2, x3, y3 = map(int, input().split())
mas = [(x1, y1, 'A'), (x2, y2, 'B'), (x3, y3, 'C')]
for i in (itertools.permutations(mas)):
f(i)
mas = [(y1, x1, 'A'), (y2, x2, 'B'), (y3, x3, 'C')]
for i in (itertools.permutations(mas)):
f(i)
mas = [(y1, x1, 'A'), (x2, y2, 'B'), (x3, y3, 'C')]
for i in (itertools.permutations(mas)):
f(i)
mas = [(x1, y1, 'A'), (y2, x2, 'B'), (x3, y3, 'C')]
for i in (itertools.permutations(mas)):
f(i)
mas = [(x1, y1, 'A'), (x2, y2, 'B'), (y3, x3, 'C')]
for i in (itertools.permutations(mas)):
f(i)
mas = [(y1, x1, 'A'), (y2, x2, 'B'), (x3, y3, 'C')]
for i in (itertools.permutations(mas)):
f(i)
mas = [(y1, x1, 'A'), (x2, y2, 'B'), (y3, x3, 'C')]
for i in (itertools.permutations(mas)):
f(i)
mas = [(x1, y1, 'A'), (y2, x2, 'B'), (y3, x3, 'C')]
for i in (itertools.permutations(mas)):
f(i)
print(-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A number is called quasibinary if its decimal representation contains only digits 0 or 1. For example, numbers 0, 1, 101, 110011 — are quasibinary and numbers 2, 12, 900 are not.
You are given a positive integer *n*. Represent it as a sum of minimum number of quasibinary numbers.
|
```python
li=[]
ans=[]
for i in range(1,65) :
li.append(int(bin(i).replace("0b", "")));
a1=[]
a2=[]
temp1=0
temp2=0
n=int(input())
ans.append(0)
ans.append(1)
a1.append(0)
a1.append(1)
a2.append(0)
a2.append(1)
for i in range(2,n+1) :
count=0
for j in li :
if j<=i :
if count==0 :
ans1=1+ans[i-j]
count+=1
temp1=i-j
temp2=j
else :
if ans1>1+ans[i-j] :
ans1=1+ans[i-j]
temp1=i-j
temp2=j
else :
break
ans.append(ans1)
a1.append(temp1)
a2.append(temp2)
print(ans[n])
i=n
var=True
while var :
print(a2[i],end=" ")
i-=a2[i]
if i==0 :
break;
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There are *n* cards (*n* is even) in the deck. Each card has a positive integer written on it. *n*<=/<=2 people will play new card game. At the beginning of the game each player gets two cards, each card is given to exactly one player.
Find the way to distribute cards such that the sum of values written of the cards will be equal for each player. It is guaranteed that it is always possible.
|
```python
n = int(input())
N = list(map(int,input().split()))
s = 0
for i in range(n):
s += N[i]
ch = s // (n // 2)
print(ch)
for i in range(n -1):
for j in range(n -1):
if N[i] + N[j] == ch:
print(i, j)
N.remove(N[i])
N.remove(N[j])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You've got a 5<=×<=5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix:
1. Swap two neighboring matrix rows, that is, rows with indexes *i* and *i*<=+<=1 for some integer *i* (1<=≤<=*i*<=<<=5). 1. Swap two neighboring matrix columns, that is, columns with indexes *j* and *j*<=+<=1 for some integer *j* (1<=≤<=*j*<=<<=5).
You think that a matrix looks beautiful, if the single number one of the matrix is located in its middle (in the cell that is on the intersection of the third row and the third column). Count the minimum number of moves needed to make the matrix beautiful.
|
```python
cords = [0, 0]
def find_one_in_matrix_line(str_arr):
for k in range(0, 5):
if str_arr[k] == '1':
return k
return -1
for i in range(0, 5):
matrixLine = str(input()).split(" ")
j = find_one_in_matrix_line(matrixLine)
if j == -1:
continue
else:
cords = [i + 1, j + 1]
break
steps = 0
while cords[0] != 3 or cords[1] != 3:
if cords[0] < 3:
cords[0] += 1
steps += 1
if cords[0] > 3:
cords[0] -= 1
steps += 1
if cords[1] < 3:
cords[1] += 1
steps += 1
if cords[1] > 3:
cords[1] -= 1
steps += 1
print(steps)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her *n* students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often oddly shaped, interlocking and tessellating pieces).
The shop assistant told the teacher that there are *m* puzzles in the shop, but they might differ in difficulty and size. Specifically, the first jigsaw puzzle consists of *f*1 pieces, the second one consists of *f*2 pieces and so on.
Ms. Manana doesn't want to upset the children, so she decided that the difference between the numbers of pieces in her presents must be as small as possible. Let *A* be the number of pieces in the largest puzzle that the teacher buys and *B* be the number of pieces in the smallest such puzzle. She wants to choose such *n* puzzles that *A*<=-<=*B* is minimum possible. Help the teacher and find the least possible value of *A*<=-<=*B*.
|
```python
n,m=map(lambda x: int(x), input().split())
arr=sorted(list(map(lambda x: int(x), input().split())))
minn=500000
for i in range(n-1,m):
minn=min(minn,arr[i]-arr[i-n+1])
print(minn)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a sequence *a* consisting of *n* integers. Find the maximum possible value of (integer remainder of *a**i* divided by *a**j*), where 1<=≤<=*i*,<=*j*<=≤<=*n* and *a**i*<=≥<=*a**j*.
|
```python
import bisect
n = int(input())
arr = set(map(int,input().split()))
ls = sorted(arr)
ans = 0
mx = max(arr)
for c in ls[::-1]:
if c-1<ans:
break
kc = c+c
while kc<=2*mx:
ind = bisect.bisect_left(ls,kc)
ans = max(ans,ls[ind-1]%c)
kc+=c
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Small, but very brave, mouse Brain was not accepted to summer school of young villains. He was upset and decided to postpone his plans of taking over the world, but to become a photographer instead.
As you may know, the coolest photos are on the film (because you can specify the hashtag #film for such).
Brain took a lot of colourful pictures on colored and black-and-white film. Then he developed and translated it into a digital form. But now, color and black-and-white photos are in one folder, and to sort them, one needs to spend more than one hour!
As soon as Brain is a photographer not programmer now, he asks you to help him determine for a single photo whether it is colored or black-and-white.
Photo can be represented as a matrix sized *n*<=×<=*m*, and each element of the matrix stores a symbol indicating corresponding pixel color. There are only 6 colors:
- 'C' (cyan)- 'M' (magenta)- 'Y' (yellow)- 'W' (white)- 'G' (grey)- 'B' (black)
The photo is considered black-and-white if it has only white, black and grey pixels in it. If there are any of cyan, magenta or yellow pixels in the photo then it is considered colored.
|
```python
n, m = map(int, input().split())
colors = [list(map(str, input().split())) for _ in range(n)]
if any('C' in row or 'M' in row or 'Y' in row for row in colors):
print("#Color")
else:
print("#Black&White")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Beroffice text editor has a wide range of features that help working with text. One of the features is an automatic search for typos and suggestions of how to fix them.
Beroffice works only with small English letters (i.e. with 26 letters from a to z). Beroffice thinks that a word is typed with a typo if there are three or more consonants in a row in the word. The only exception is that if the block of consonants has all letters the same, then this block (even if its length is greater than three) is not considered a typo. Formally, a word is typed with a typo if there is a block of not less that three consonants in a row, and there are at least two different letters in this block.
For example:
- the following words have typos: "hellno", "hackcerrs" and "backtothefutttture"; - the following words don't have typos: "helllllooooo", "tobeornottobe" and "oooooo".
When Beroffice editor finds a word with a typo, it inserts as little as possible number of spaces in this word (dividing it into several words) in such a way that each of the resulting words is typed without any typos.
Implement this feature of Beroffice editor. Consider the following letters as the only vowels: 'a', 'e', 'i', 'o' and 'u'. All the other letters are consonants in this problem.
|
```python
s = input()
k = 0
vowel = "aeiou"
res = ""
for c in s:
if c in vowel:
k = 0
else:
k += 1
if k == 3:
res += " "
k = 0
res += c
print(res)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Small, but very brave, mouse Brain was not accepted to summer school of young villains. He was upset and decided to postpone his plans of taking over the world, but to become a photographer instead.
As you may know, the coolest photos are on the film (because you can specify the hashtag #film for such).
Brain took a lot of colourful pictures on colored and black-and-white film. Then he developed and translated it into a digital form. But now, color and black-and-white photos are in one folder, and to sort them, one needs to spend more than one hour!
As soon as Brain is a photographer not programmer now, he asks you to help him determine for a single photo whether it is colored or black-and-white.
Photo can be represented as a matrix sized *n*<=×<=*m*, and each element of the matrix stores a symbol indicating corresponding pixel color. There are only 6 colors:
- 'C' (cyan)- 'M' (magenta)- 'Y' (yellow)- 'W' (white)- 'G' (grey)- 'B' (black)
The photo is considered black-and-white if it has only white, black and grey pixels in it. If there are any of cyan, magenta or yellow pixels in the photo then it is considered colored.
|
```python
class Solution():
def brains_photos():
row, column = map(int, input().split())
colors = ["Y", "C", "M"]
for i in range(row):
color = input().split()
if 'Y' in color or 'C' in color or 'M' in color:
return '#Color'
return '#Black&White'
if __name__ == '__main__':
print(Solution.brains_photos())
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Mr. Santa asks all the great programmers of the world to solve a trivial problem. He gives them an integer *m* and asks for the number of positive integers *n*, such that the factorial of *n* ends with exactly *m* zeroes. Are you among those great programmers who can solve this problem?
|
```python
from sys import exit
m = int(input())
i = 4
pows = [5**i for i in range(100)]
while 1:
i += 1
l = 1
r = 100
while l < r:
cur = (l + r + 1) // 2
if i % pows[cur] == 0:
l = cur
else:
r = cur - 1
m -= l
if m == 0: break
if m < 0:
print(0)
exit(0)
print(5)
for j in range(i, i + 5):
print(j, end=' ')
```
|
|
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
a = input()
b = ['A', 'a', 'E', 'e', 'i', 'I', 'O', 'o', 'U', 'u', 'Y', 'y']
result = ''.join([char for char in a if char not in b])
upper = result.lower()
print('.',end = '')
result_string = '.'.join(upper)
print(result_string)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya has *n* pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every *m*-th day (at days with numbers *m*,<=2*m*,<=3*m*,<=...) mom buys a pair of socks to Vasya. She does it late in the evening, so that Vasya cannot put on a new pair of socks before the next day. How many consecutive days pass until Vasya runs out of socks?
|
```python
import math
n,m=map(int,input().split());c=n;c1=1
while n//m>=1:
if (n//m)%m !=0:
c+=(n//m)+1
else:
c+=(n//m)
n//=m
print(c-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:
- Tetrahedron. Tetrahedron has 4 triangular faces. - Cube. Cube has 6 square faces. - Octahedron. Octahedron has 8 triangular faces. - Dodecahedron. Dodecahedron has 12 pentagonal faces. - Icosahedron. Icosahedron has 20 triangular faces.
All five kinds of polyhedrons are shown on the picture below:
Anton has a collection of *n* polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
|
```python
n = int(input())
s= []
for i in range(n):
s.append(input())
val = { "Tetrahedron": 4,
"Cube":6,
"Octahedron": 8,
"Dodecahedron": 12,
"Icosahedron": 20
}
total = 0
for i in s:
total += val[i]
print(total)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Bob has a permutation of integers from 1 to *n*. Denote this permutation as *p*. The *i*-th element of *p* will be denoted as *p**i*. For all pairs of distinct integers *i*,<=*j* between 1 and *n*, he wrote the number *a**i*,<=*j*<==<=*min*(*p**i*,<=*p**j*). He writes *a**i*,<=*i*<==<=0 for all integer *i* from 1 to *n*.
Bob gave you all the values of *a**i*,<=*j* that he wrote down. Your job is to reconstruct any permutation that could have generated these values. The input will be formed so that it is guaranteed that there is at least one solution that is consistent with the information given.
|
```python
from sys import stdin as fin
# fin = open("wfr2016b.in", "r")
n = int(fin.readline())
ans = [None] * n
maxv = 1
for i in range(n):
line = tuple(map(int, fin.readline().split()))
cnt = [False] * (n + 1)
for j in range(n):
if not cnt[line[j]]:
cnt[line[j]] = True
else:
ans[i] = line[j]
maxv = max(maxv, line[j] + 1)
break
for num in ans:
if num is None:
print(maxv, end=' ')
maxv += 1
else:
print(num, end=' ')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed *w* kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Billy are great fans of even numbers, that's why they want to divide the watermelon in such a way that each of the two parts weighs even number of kilos, at the same time it is not obligatory that the parts are equal. The boys are extremely tired and want to start their meal as soon as possible, that's why you should help them and find out, if they can divide the watermelon in the way they want. For sure, each of them should get a part of positive weight.
|
```python
a=int(input())
if a %2==0 and a>2:
print("yes")
else:
print("no")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Some days ago, I learned the concept of LCM (least common multiple). I've played with it for several times and I want to make a big number with it.
But I also don't want to use many numbers, so I'll choose three positive integers (they don't have to be distinct) which are not greater than *n*. Can you help me to find the maximum possible least common multiple of these three integers?
|
```python
import math
t=int(input()))
if t<3:
print(t)
else:
if t%2==1:
ans=(t-1)*t*(t-2)
elif math.gcd(t,t-3)==1 and math.gcd(t-1,t-3)==1:
ans=max((t-1)*(t-2)*(t-3),t*(t-1)*(t-3))
else:
ans=(t-1)*(t-2)*(t-3)
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One particularly well-known fact about zombies is that they move and think terribly slowly. While we still don't know why their movements are so sluggish, the problem of laggy thinking has been recently resolved. It turns out that the reason is not (as previously suspected) any kind of brain defect – it's the opposite! Independent researchers confirmed that the nervous system of a zombie is highly complicated – it consists of *n* brains (much like a cow has several stomachs). They are interconnected by brain connectors, which are veins capable of transmitting thoughts between brains. There are two important properties such a brain network should have to function properly:
1. It should be possible to exchange thoughts between any two pairs of brains (perhaps indirectly, through other brains). 1. There should be no redundant brain connectors, that is, removing any brain connector would make property 1 false.
If both properties are satisfied, we say that the nervous system is valid. Unfortunately (?), if the system is not valid, the zombie stops thinking and becomes (even more) dead. Your task is to analyze a given nervous system of a zombie and find out whether it is valid.
|
```python
# Python program to check if a given directed graph is strongly
# connected or not
import sys
from collections import defaultdict
class Graph:
def __init__(self, V):
self.V = V
self.graph = defaultdict(list)
def addEdge(self, v, w):
# Add w to v ist.
self.graph[v].append(w)
# Add v to w list.
self.graph[w].append(v)
# A recursive function that uses visited[]
# and parent to detect cycle in subgraph
# reachable from vertex v.
def isCyclicUtil(self, v, visited, parent):
# Mark current node as visited
visited[v] = True
# Recur for all the vertices adjacent
# for this vertex
for i in self.graph[v]:
# If an adjacent is not visited,
# then recur for that adjacent
if visited[i] == False:
if self.isCyclicUtil(i, visited, v) == True:
return True
# If an adjacent is visited and not
# parent of current vertex, then there
# is a cycle.
elif i != parent:
return True
return False
# Returns true if the graph is a tree,
# else false.
def isTree(self):
# Mark all the vertices as not visited
# and not part of recursion stack
visited = [False] * self.V
# The call to isCyclicUtil serves multiple
# purposes. It returns true if graph reachable
# from vertex 0 is cyclcic. It also marks
# all vertices reachable from 0.
if self.isCyclicUtil(0, visited, -1) == True:
return False
# If we find a vertex which is not reachable
# from 0 (not marked by isCyclicUtil(),
# then we return false
for i in range(self.V):
if visited[i] == False:
return False
return True
def main():
s = sys.stdin.readline().split()
n, m = int(s[0]), int(s[1])
graph = Graph(n)
for _ in range(m):
s = sys.stdin.readline().split()
graph.addEdge(int(s[0]) - 1, int(s[1]) - 1)
return "Yes" if graph.isTree() else "No"
if __name__ == "__main__":
sys.stdout.write(main())
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
In the beginning of the new year Keivan decided to reverse his name. He doesn't like palindromes, so he changed Naviek to Navick.
He is too selfish, so for a given *n* he wants to obtain a string of *n* characters, each of which is either 'a', 'b' or 'c', with no palindromes of length 3 appearing in the string as a substring. For example, the strings "abc" and "abca" suit him, while the string "aba" doesn't. He also want the number of letters 'c' in his string to be as little as possible.
|
```python
n = int(input())
s = 'bbaa' * (n // 4 + 1)
s = s[:n]
print(s)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One fine October day a mathematics teacher Vasily Petrov went to a class and saw there *n* pupils who sat at the desks, two people at each desk. Vasily quickly realized that number *n* is even. Like all true mathematicians, Vasily has all students numbered from 1 to *n*.
But Vasily Petrov did not like the way the children were seated at the desks. According to him, the students whose numbers differ by 1, can not sit together, as they talk to each other all the time, distract others and misbehave.
On the other hand, if a righthanded student sits at the left end of the desk and a lefthanded student sits at the right end of the desk, they hit elbows all the time and distract each other. In other cases, the students who sit at the same desk, do not interfere with each other.
Vasily knows very well which students are lefthanders and which ones are righthanders, and he asks you to come up with any order that meets these two uncomplicated conditions (students do not talk to each other and do not bump their elbows). It is guaranteed that the input is such that at least one way to seat the students always exists.
|
```python
for case in range(int(input())):
n = int(input())
s = input()
for i in range(n):
if s[i] == 'L':
print(f"{i + 1} {i + 1 + n//2}")
else:
print(f"{i + 1 + n//2} {i + 1}")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
According to rules of the Berland fashion, a jacket should be fastened by all the buttons except only one, but not necessarily it should be the last one. Also if the jacket has only one button, it should be fastened, so the jacket will not swinging open.
You are given a jacket with *n* buttons. Determine if it is fastened in a right way.
|
```python
n = int(input())
l = list(map(int,input().split()))
if n == 1:
if l.count(0) == 1:
print("NO")
else:
print("YES")
else:
x = l.count(0)
if x == 1:
print("YES")
else:print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
In this problem you will write a simple generator of Brainfuck ([https://en.wikipedia.org/wiki/Brainfuck](https://en.wikipedia.org/wiki/Brainfuck)) calculators.
You are given an arithmetic expression consisting of integers from 0 to 255 and addition/subtraction signs between them. Output a Brainfuck program which, when executed, will print the result of evaluating this expression.
We use a fairly standard Brainfuck interpreter for checking the programs:
- 30000 memory cells.- memory cells store integers from 0 to 255 with unsigned 8-bit wraparound.- console input (, command) is not supported, but it's not needed for this problem.
|
```python
n = eval(input())
for i in range(n)L
print('+', end = '');
print('.')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Holidays have finished. Thanks to the help of the hacker Leha, Noora managed to enter the university of her dreams which is located in a town Pavlopolis. It's well known that universities provide students with dormitory for the period of university studies. Consequently Noora had to leave Vičkopolis and move to Pavlopolis. Thus Leha was left completely alone in a quiet town Vičkopolis. He almost even fell into a depression from boredom!
Leha came up with a task for himself to relax a little. He chooses two integers *A* and *B* and then calculates the greatest common divisor of integers "*A* factorial" and "*B* factorial". Formally the hacker wants to find out GCD(*A*!,<=*B*!). It's well known that the factorial of an integer *x* is a product of all positive integers less than or equal to *x*. Thus *x*!<==<=1·2·3·...·(*x*<=-<=1)·*x*. For example 4!<==<=1·2·3·4<==<=24. Recall that GCD(*x*,<=*y*) is the largest positive integer *q* that divides (without a remainder) both *x* and *y*.
Leha has learned how to solve this task very effective. You are able to cope with it not worse, aren't you?
|
```python
from math import factorial
from math import gcd
a, b = map(int, input().split())
af = factorial(a)
bf = factorial(b)
print(gcd(af, bf))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Fox Ciel is in the Amusement Park. And now she is in a queue in front of the Ferris wheel. There are *n* people (or foxes more precisely) in the queue: we use first people to refer one at the head of the queue, and *n*-th people to refer the last one in the queue.
There will be *k* gondolas, and the way we allocate gondolas looks like this:
- When the first gondolas come, the *q*1 people in head of the queue go into the gondolas. - Then when the second gondolas come, the *q*2 people in head of the remain queue go into the gondolas. ...- The remain *q**k* people go into the last (*k*-th) gondolas.
Note that *q*1, *q*2, ..., *q**k* must be positive. You can get from the statement that and *q**i*<=><=0.
You know, people don't want to stay with strangers in the gondolas, so your task is to find an optimal allocation way (that is find an optimal sequence *q*) to make people happy. For every pair of people *i* and *j*, there exists a value *u**ij* denotes a level of unfamiliar. You can assume *u**ij*<==<=*u**ji* for all *i*,<=*j* (1<=≤<=*i*,<=*j*<=≤<=*n*) and *u**ii*<==<=0 for all *i* (1<=≤<=*i*<=≤<=*n*). Then an unfamiliar value of a gondolas is the sum of the levels of unfamiliar between any pair of people that is into the gondolas.
A total unfamiliar value is the sum of unfamiliar values for all gondolas. Help Fox Ciel to find the minimal possible total unfamiliar value for some optimal allocation.
|
```python
#include <bits/stdc++.h>
namespace std {
template<class Fun>
class y_combinator_result {
Fun fun_;
public:
template<class T>
explicit y_combinator_result(T &&fun): fun_(std::forward<T>(fun)) {}
template<class ...Args>
decltype(auto) operator()(Args &&...args) {
return fun_(std::ref(*this), std::forward<Args>(args)...);
}
};
template<class Fun>
decltype(auto) y_combinator(Fun &&fun) {
return y_combinator_result<std::decay_t<Fun>>(std::forward<Fun>(fun));
}
} // namespace std
int main() {
using namespace std;
int N, K;
cin >> N >> K;
vector P(N + 1, vector<int>(N + 1, 0));
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= N; j++) {
cin >> P[i][j];
P[i][j] += P[i - 1][j] + P[i][j - 1] - P[i - 1][j - 1];
}
}
vector dp(K + 1, vector<int>(N + 1, 1 << 30));
auto dnq = y_combinator([&](auto self, int k, int l, int r, int p, int q) -> void {
if (r < l)
return;
if (p == q) {
for (int i = l; i <= r; i++)
dp[k][i] = dp[k - 1][p - 1] + P[i][i] - P[i][p - 1] - P[p - 1][i] + P[p - 1][p - 1];
return;
}
int m = (l + r) / 2, pos = -1;
for (int i = p; i <= q; i++) {
int val = dp[k - 1][i - 1] + P[m][m] - P[m][i - 1] - P[i - 1][m] + P[i - 1][i - 1];
if (dp[k][m] >= val) {
dp[k][m] = val;
pos = i;
}
}
self(k, l, m - 1, p, pos);
self(k, m + 1, r, pos, q);
});
dp[0][0] = 0;
for (int k = 1; k <= K; k++)
dnq(k, 1, N, 1, N);
cout << dp[K][N] / 2 << '\n';
}
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line.
Unfortunately, from time to time Anton would forget writing some letter and write it again. He asks you to count the total number of distinct letters in his set.
|
```python
x=set(input())
l=len(x)-2
if("," in x):
print(l-1)
else:
print(l)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
As a tradition, every year before IOI all the members of Natalia Fan Club are invited to Malek Dance Club to have a fun night together. Malek Dance Club has 2*n* members and coincidentally Natalia Fan Club also has 2*n* members. Each member of MDC is assigned a unique id *i* from 0 to 2*n*<=-<=1. The same holds for each member of NFC.
One of the parts of this tradition is one by one dance, where each member of MDC dances with a member of NFC. A dance pair is a pair of numbers (*a*,<=*b*) such that member *a* from MDC dances with member *b* from NFC.
The complexity of a pairs' assignment is the number of pairs of dancing pairs (*a*,<=*b*) and (*c*,<=*d*) such that *a*<=<<=*c* and *b*<=><=*d*.
You are given a binary number of length *n* named *x*. We know that member *i* from MDC dances with member from NFC. Your task is to calculate the complexity of this assignment modulo 1000000007 (109<=+<=7).
Expression denotes applying «XOR» to numbers *x* and *y*. This operation exists in all modern programming languages, for example, in C++ and Java it denotes as «^», in Pascal — «xor».
|
```python
M = 10 ** 9 + 7
def solve1(x):
n = len(x)
x = int(x, 2)
ans = 0
for a in range(2 ** n):
for c in range(2 ** n):
b = a ^ x
d = c ^ x
if a < c and b > d:
ans += 1
return ans % M
def solve2(x):
return int(x, 2) * pow(2, (len(x) - 1), M) % M
x = input()
# print(solve1(x))
print(solve2(x))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Max wants to buy a new skateboard. He has calculated the amount of money that is needed to buy a new skateboard. He left a calculator on the floor and went to ask some money from his parents. Meanwhile his little brother Yusuf came and started to press the keys randomly. Unfortunately Max has forgotten the number which he had calculated. The only thing he knows is that the number is divisible by 4.
You are given a string *s* consisting of digits (the number on the display of the calculator after Yusuf randomly pressed the keys). Your task is to find the number of substrings which are divisible by 4. A substring can start with a zero.
A substring of a string is a nonempty sequence of consecutive characters.
For example if string *s* is 124 then we have four substrings that are divisible by 4: 12, 4, 24 and 124. For the string 04 the answer is three: 0, 4, 04.
As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use gets/scanf/printf instead of getline/cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
|
```python
"""
Created on Sat Jan 12 23:33:17 2019
"""
s = input()
res = 0
for i in range(len(s)):
t = int(s[i])
if t % 4 == 0:
res += 1
if i > 0:
if (int(s[i - 1]) * 10 + t) % 4 == 0:
res += i
print(res)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
*n* hobbits are planning to spend the night at Frodo's house. Frodo has *n* beds standing in a row and *m* pillows (*n*<=≤<=*m*). Each hobbit needs a bed and at least one pillow to sleep, however, everyone wants as many pillows as possible. Of course, it's not always possible to share pillows equally, but any hobbit gets hurt if he has at least two pillows less than some of his neighbors have.
Frodo will sleep on the *k*-th bed in the row. What is the maximum number of pillows he can have so that every hobbit has at least one pillow, every pillow is given to some hobbit and no one is hurt?
|
```python
def read(type=int):
return type(input())
def read_arr(type=int):
return [type(token) for token in input().split()]
def runB():
n, m, k = read_arr()
ans = 1
m -= n
l = r = k
while r - l + 1 < n:
ans += 1
m -= (r - l + 1)
if l > 1:
l -= 1
if r < n:
r += 1
ans += (m // n)
print(ans)
runB()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
«One dragon. Two dragon. Three dragon», — the princess was counting. She had trouble falling asleep, and she got bored of counting lambs when she was nine.
However, just counting dragons was boring as well, so she entertained herself at best she could. Tonight she imagined that all dragons were here to steal her, and she was fighting them off. Every *k*-th dragon got punched in the face with a frying pan. Every *l*-th dragon got his tail shut into the balcony door. Every *m*-th dragon got his paws trampled with sharp heels. Finally, she threatened every *n*-th dragon to call her mom, and he withdrew in panic.
How many imaginary dragons suffered moral or physical damage tonight, if the princess counted a total of *d* dragons?
|
```python
import math
k, l, m, n, d= map(int, input().split())
check=[]
for i in range(d):
check.append(i+1)
for ks in range(math.floor(d/k)):
if (ks+1)*k in check:
check.remove((ks+1)*k)
for ls in range(math.floor(d/l)):
if (ls+1)*l in check:
check.remove((ls+1)*l)
for ms in range(math.floor(d/m)):
if (ms+1)*m in check:
check.remove((ms+1)*m)
for ns in range(math.floor(d/n)):
if (ns+1)*n in check:
check.remove((ns+1)*n)
print(d-len(check))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given array consisting of *n* integers. Your task is to find the maximum length of an increasing subarray of the given array.
A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray strictly greater than previous.
|
```python
n = int(input())
array = [int(x) for x in input().split()]
dp = [1]*(n+1)
dp[0] = 0
for i in range(0,n-1):
if array[i+1] > array[i]:
dp[i+2] = dp[i+1] +1
print(max(dp))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are *n* members, numbered 1 through *n*. *m* pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
|
```python
from collections import defaultdict
n, m = map(int, input().split())
d = defaultdict(list)
for i in range(m):
u, v = map(int, input().split())
d[u].append(v)
d[v].append(u)
for i in range(n):
d[i + 1].append(i + 1)
d[i + 1].sort()
v = [0] * (n + 1)
for i in range(1, n +1):
for j in d[i]:
if(d[j] != d[i]):
print("NO")
exit()
print("YES")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given two arrays *A* and *B* consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose *k* numbers in array *A* and choose *m* numbers in array *B* so that any number chosen in the first array is strictly less than any number chosen in the second array.
|
```python
def bol(a,b,k,m):
if a[k-1]<b[len(b)-m]:
print('YES')
else:
print('NO')
# print(a[k-1])
# print(b[len(b)-m])
n=list(map(int,input('').split()))
para=list(map(int,input('').split()))
a=list(map(int,input('').split()))
b=list(map(int,input('').split()))
bol(a,b,para[0],para[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
from sys import stdin
def main():
m, n = list(map(int, stdin.readline().strip().split()))
print(m * n // 2)
main()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.
Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character. The device consists of a wheel with a lowercase English letters written in a circle, static pointer to the current letter and a button that print the chosen letter. At one move it's allowed to rotate the alphabetic wheel one step clockwise or counterclockwise. Initially, static pointer points to letter 'a'. Other letters are located as shown on the picture:
After Grigoriy add new item to the base he has to print its name on the plastic tape and attach it to the corresponding exhibit. It's not required to return the wheel to its initial position with pointer on the letter 'a'.
Our hero is afraid that some exhibits may become alive and start to attack him, so he wants to print the names as fast as possible. Help him, for the given string find the minimum number of rotations of the wheel required to print it.
|
```python
s = input()
p, c = 'a', 0
for i in s:
l, r = ord(i)-97, ord(p)-97
n = min(l, r)
m = max(l, r)
s1 = n-m+26
s2 = m-n
c += min(s1, s2)
p = i
print(c)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Lolek and Bolek are about to travel abroad by plane. The local airport has a special "Choose Your Plane" offer. The offer's conditions are as follows:
- it is up to a passenger to choose a plane to fly on; - if the chosen plane has *x* (*x*<=><=0) empty seats at the given moment, then the ticket for such a plane costs *x* zlotys (units of Polish currency).
The only ticket office of the airport already has a queue of *n* passengers in front of it. Lolek and Bolek have not stood in the queue yet, but they are already wondering what is the maximum and the minimum number of zlotys the airport administration can earn if all *n* passengers buy tickets according to the conditions of this offer?
The passengers buy tickets in turn, the first person in the queue goes first, then goes the second one, and so on up to *n*-th person.
|
```python
n,m = list(map(int,input().split()))
left = list(map(int,input().split()))
right = left[:]
maxx = 0
minn = 0
for i in range(n):
temp=left.index(max(left))
maxx+=max(left)
left[temp] = left[temp]-1
for i in range(n):
temp=right.index(min(right))
#print('temp',temp)
if right[temp] == 0:
right.pop(temp)
else:
minn+=right[temp]
#print('minn',minn)
right[temp] = right[temp]-1
print(maxx,minn)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a sequence *a* consisting of *n* integers. Find the maximum possible value of (integer remainder of *a**i* divided by *a**j*), where 1<=≤<=*i*,<=*j*<=≤<=*n* and *a**i*<=≥<=*a**j*.
|
```python
from collections import defaultdict as dd
from sys import stdin
input = stdin.buffer.readline
L = lambda : list(map(int,input().split()))
n = L()[0]
A = L()
if n == 1:
print(0)
exit()
A.sort()
l = 0
r = A[-2]-1
if r == 0:
print(0)
exit()
divs_list = dd(set)
for i in range(n):
if A[i] == 1:
continue
x = A[i]
while( x <= A[-1] ):
divs_list[x].add( A[i] )
x += A[i]
def check( m ):
for i in range( n - 1, -1, -1 ):
if A[i] < m:
break
x = A[i] - m
y = divs_list[x]
for ele in y:
if ( ele > m ):
return True
return False
while( l <= r ):
m = ( l + r ) // 2
if check( m ):
l = m + 1
else:
r = m - 1
print( r )
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Professor GukiZ makes a new robot. The robot are in the point with coordinates (*x*1,<=*y*1) and should go to the point (*x*2,<=*y*2). In a single step the robot can change any of its coordinates (maybe both of them) by one (decrease or increase). So the robot can move in one of the 8 directions. Find the minimal number of steps the robot should make to get the finish position.
|
```python
w,h=map(int,input().split())
u,a=map(int,input().split())
print(max(abs(w-u),abs(h-a)))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Mishka is decorating the Christmas tree. He has got three garlands, and all of them will be put on the tree. After that Mishka will switch these garlands on.
When a garland is switched on, it periodically changes its state — sometimes it is lit, sometimes not. Formally, if *i*-th garland is switched on during *x*-th second, then it is lit only during seconds *x*, *x*<=+<=*k**i*, *x*<=+<=2*k**i*, *x*<=+<=3*k**i* and so on.
Mishka wants to switch on the garlands in such a way that during each second after switching the garlands on there would be at least one lit garland. Formally, Mishka wants to choose three integers *x*1, *x*2 and *x*3 (not necessarily distinct) so that he will switch on the first garland during *x*1-th second, the second one — during *x*2-th second, and the third one — during *x*3-th second, respectively, and during each second starting from *max*(*x*1,<=*x*2,<=*x*3) at least one garland will be lit.
Help Mishka by telling him if it is possible to do this!
|
```python
k1, k2, k3 = map(int, input().split())
a = []
for i in range(0, 1500 + 10) : a.append(0)
a[k1] += 1
a[k2] += 1
a[k3] += 1
if (a[1] > 0) : print('YES')
elif (a[2] >= 2) : print('YES')
elif (a[3] >= 3) : print('YES')
elif ((a[2] > 0) and (a[4] >= 2)) : print('YES')
else : print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If there are at least 7 players of some team standing one after another, then the situation is considered dangerous. For example, the situation 00100110111111101 is dangerous and 11110111011101 is not. You are given the current situation. Determine whether it is dangerous or not.
|
```python
import sys
input = sys.stdin.readline
############ ---- Input Functions ---- ############
def inp():
return int(input())
def inlt():
return list(map(int, input().split()))
def insr():
s = input()
return list(s[:len(s) - 1])
def invr():
return map(int, input().split())
st = insr()
j = 0
l = []
for i in range(len(st)):
j = i + 1
count = 0
while j < len(st):
if st[i] == st[j]:
count = count + 1
else:
break
j = j + 1
# Move the append statement here, after the inner loop
l.append(count + 1)
l.sort()
if l[len(l) - 1] >= 7:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The circle line of the Berland subway has *n* stations. We know the distances between all pairs of neighboring stations:
- *d*1 is the distance between the 1-st and the 2-nd station;- *d*2 is the distance between the 2-nd and the 3-rd station;...- *d**n*<=-<=1 is the distance between the *n*<=-<=1-th and the *n*-th station;- *d**n* is the distance between the *n*-th and the 1-st station.
The trains go along the circle line in both directions. Find the shortest distance between stations with numbers *s* and *t*.
|
```python
n=int(input())
a=list(map(int,input().split(' ')))
s,t=map(int,input().split(' '))
if s!=t:
s-=1
t-=1
temp1=a[s]
temp2=a[t]
a[s]=-1
a[t]=-1
b=a[max(s,t):n]+a[0:max(s,t)]
var1=sum(a[min(s,t)+1:max(s,t)])+temp2
var2=sum(b[b.index(-1)+1:n-1-b[::-1].index(-1)])+temp1
print(min(var1,var2))
else:
print(0)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given string *s*. Your task is to determine if the given string *s* contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order).
|
```python
a = input()
if 'AB' in a and 'BA' in a and abs(min(a.find('AB'), a.rfind('AB')) - min(a.find('BA'), a.rfind('BA'))) > 1:
print('YES')
else:
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given *n* points on a line with their coordinates *x**i*. Find the point *x* so the sum of distances to the given points is minimal.
|
```python
n = int(input())
x = input().split()
x = [int(i) for i in x]
x.sort()
if(n % 2 == 1):
print(x[n//2+1])
else:
print((x[n//2]+x[n//2-1])//2)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Andryusha is an orderly boy and likes to keep things in their place.
Today he faced a problem to put his socks in the wardrobe. He has *n* distinct pairs of socks which are initially in a bag. The pairs are numbered from 1 to *n*. Andryusha wants to put paired socks together and put them in the wardrobe. He takes the socks one by one from the bag, and for each sock he looks whether the pair of this sock has been already took out of the bag, or not. If not (that means the pair of this sock is still in the bag), he puts the current socks on the table in front of him. Otherwise, he puts both socks from the pair to the wardrobe.
Andryusha remembers the order in which he took the socks from the bag. Can you tell him what is the maximum number of socks that were on the table at the same time?
|
```python
n = int(input())
a = [int(x) for x in input().split()]
maxn = maxans = 0
used = [True] * n
for i in range(n * 2):
if used[a[i] - 1]:
used[a[i] - 1] = False
maxn += 1
elif not used[a[i] - 1]:
maxn -= 1
if maxn > maxans:
maxans = maxn
print(maxans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to the store and buy some few more horseshoes, not to lose face in front of his stylish comrades.
Fortunately, the store sells horseshoes of all colors under the sun and Valera has enough money to buy any four of them. However, in order to save the money, he would like to spend as little money as possible, so you need to help Valera and determine what is the minimum number of horseshoes he needs to buy to wear four horseshoes of different colors to a party.
|
```python
colors = list(map(int, input().split()))
i = 0
j = 1
same = 1
while True:
if i == 3:
break
while True:
if j == 4:
break
if colors[i] == colors[j]:
same += 1
j += 1
i += 1
print(same - 1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Today is Wednesday, the third day of the week. What's more interesting is that tomorrow is the last day of the year 2015.
Limak is a little polar bear. He enjoyed this year a lot. Now, he is so eager to the coming year 2016.
Limak wants to prove how responsible a bear he is. He is going to regularly save candies for the entire year 2016! He considers various saving plans. He can save one candy either on some fixed day of the week or on some fixed day of the month.
Limak chose one particular plan. He isn't sure how many candies he will save in the 2016 with his plan. Please, calculate it and tell him.
|
```python
help = list(input().split())
count_week = 366 // 7
if help[2] == 'week':
if int(help[0]) == 5 or int(help[0]) == 6 or int(help[0]) == 7:
print(53)
else:
print(52)
else:
if int(help[0]) == 29:
print(12)
elif int(help[0]) == 30:
print(11)
else:
print(7)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Once Bob got to a sale of old TV sets. There were *n* TV sets at that sale. TV set with index *i* costs *a**i* bellars. Some TV sets have a negative price — their owners are ready to pay Bob if he buys their useless apparatus. Bob can «buy» any TV sets he wants. Though he's very strong, Bob can carry at most *m* TV sets, and he has no desire to go to the sale for the second time. Please, help Bob find out the maximum sum of money that he can earn.
|
```python
n,m,= map(int, input().split())
arr= list(map(int, input().split()))
arr.sort()
sum=0
for i in range(m): sum+=arr[i]
print(-sum)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
When Petya went to school, he got interested in large numbers and what they were called in ancient times. For instance, he learned that the Russian word "tma" (which now means "too much to be counted") used to stand for a thousand and "tma tmyschaya" (which literally means "the tma of tmas") used to stand for a million.
Petya wanted to modernize the words we use for numbers and invented a word petricium that represents number *k*. Moreover, petricium la petricium stands for number *k*2, petricium la petricium la petricium stands for *k*3 and so on. All numbers of this form are called petriciumus cifera, and the number's importance is the number of articles la in its title.
Petya's invention brought on a challenge that needed to be solved quickly: does some number *l* belong to the set petriciumus cifera? As Petya is a very busy schoolboy he needs to automate the process, he asked you to solve it.
|
```python
import math
k,l=int(input()),int(input())
im=math.log(l,k)-1
if im==int(im):
print("YES",int(im),sep='\n')
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Noora is a student of one famous high school. It's her final year in school — she is going to study in university next year. However, she has to get an «A» graduation certificate in order to apply to a prestigious one.
In school, where Noora is studying, teachers are putting down marks to the online class register, which are integers from 1 to *k*. The worst mark is 1, the best is *k*. Mark that is going to the certificate, is calculated as an average of all the marks, rounded to the closest integer. If several answers are possible, rounding up is produced. For example, 7.3 is rounded to 7, but 7.5 and 7.8784 — to 8.
For instance, if Noora has marks [8,<=9], then the mark to the certificate is 9, because the average is equal to 8.5 and rounded to 9, but if the marks are [8,<=8,<=9], Noora will have graduation certificate with 8.
To graduate with «A» certificate, Noora has to have mark *k*.
Noora got *n* marks in register this year. However, she is afraid that her marks are not enough to get final mark *k*. Noora decided to ask for help in the internet, where hacker Leha immediately responded to her request. He is ready to hack class register for Noora and to add Noora any number of additional marks from 1 to *k*. At the same time, Leha want his hack be unseen to everyone, so he decided to add as less as possible additional marks. Please help Leha to calculate the minimal number of marks he has to add, so that final Noora's mark will become equal to *k*.
|
```python
from math import ceil,floor
def avg(l):
a=sum(l)/len(l)
f=int(str(a)[str(a).index(".")+1])
if f>=5:
a=ceil(a)
else:
a=floor(a)
return a
n, k = map(int, input().split())
marks = list(map(int, input().split()))
avgm=avg(marks)
count=0
while avgm!=k:
marks.append(k)
avgm=avg(marks)
count+=1
print(count)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Volodya has recently visited a very odd town. There are *N* tourist attractions in the town and every two of them are connected by a bidirectional road. Each road has some travel price (natural number) assigned to it and all prices are distinct. But the most striking thing about this town is that each city sightseeing tour has the same total price! That is, if we choose any city sightseeing tour — a cycle which visits every attraction exactly once — the sum of the costs of the tour roads is independent of the tour. Volodya is curious if you can find such price system with all road prices not greater than 1000.
|
```python
print("_RANDOM_GUESS_1689436872.9227185")# 1689436872.9227393
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Pasha has a wooden stick of some positive integer length *n*. He wants to perform exactly three cuts to get four parts of the stick. Each part must have some positive integer length and the sum of these lengths will obviously be *n*.
Pasha likes rectangles but hates squares, so he wonders, how many ways are there to split a stick into four parts so that it's possible to form a rectangle using these parts, but is impossible to form a square.
Your task is to help Pasha and count the number of such ways. Two ways to cut the stick are considered distinct if there exists some integer *x*, such that the number of parts of length *x* in the first way differ from the number of parts of length *x* in the second way.
|
```python
def pasha(m,n,x):
m = m + 2
x = x + 1
if m >= n:
print(x)
else:
pasha(m,n,x)
z = int(input())
x = 0
m = 2
if z%2 != 0:
Print(0)
else:
n = z/2
pasha(m,n,x)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Innokentiy decides to change the password in the social net "Contact!", but he is too lazy to invent a new password by himself. That is why he needs your help.
Innokentiy decides that new password should satisfy the following conditions:
- the length of the password must be equal to *n*, - the password should consist only of lowercase Latin letters, - the number of distinct symbols in the password must be equal to *k*, - any two consecutive symbols in the password must be distinct.
Your task is to help Innokentiy and to invent a new password which will satisfy all given conditions.
|
```python
n, k = map(int, input().split())
a = ''
for i in range(97, 97+k):
a += chr(i)
print(a*(n//k), end = '')
n -= (n//k)*k
print(a[:n])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Let *next*(*x*) be the minimum lucky number which is larger than or equals *x*. Petya is interested what is the value of the expression *next*(*l*)<=+<=*next*(*l*<=+<=1)<=+<=...<=+<=*next*(*r*<=-<=1)<=+<=*next*(*r*). Help him solve this problem.
|
```python
from bisect import bisect_left
s, e = [int(i) for i in input().split(" ")]
res = []
curr = []
def lucky_combinations(curr, ctr):
if 0 < ctr < len(str(e)) + 2 and (curr not in res):
res.append(int("".join(curr)))
if ctr == len(str(e)) + 2:
return
curr.append("4")
lucky_combinations(curr.copy(), ctr + 1)
curr.pop()
curr.append("7")
lucky_combinations(curr.copy(), ctr + 1)
curr.pop()
# def lucky_combinations(curr):
# res.append(curr)
# if curr > 10 * e:
# return
# lucky_combinations(curr * 10 + 4)
# lucky_combinations(curr * 10 + 7)
def find_ge(a, key):
"""Find smallest item greater-than or equal to key.
Raise ValueError if no such item exists.
If multiple keys are equal, return the leftmost.
"""
i = bisect_left(a, key)
if i == len(a):
raise ValueError("No item found with key at or above: %r" % (key,))
return a[i], i
lucky_combinations([], 0)
res.sort()
_, res_start_ind = find_ge(a=res, key=s)
total = 0
while s <= e:
next_lucky, ind = find_ge(res, s)
total += next_lucky * (min(next_lucky, e) - s + 1)
s = min(res[ind], e) + 1
print(total)
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.