source
stringclasses 3
values | instruction
stringlengths 23
3.97k
| input
stringclasses 1
value | output
stringlengths 1
3.75k
|
---|---|---|---|
MatrixStudio/Codeforces-Python-Submissions
|
Devu is a dumb guy, his learning curve is very slow. You are supposed to teach him *n* subjects, the *i**th* subject has *c**i* chapters. When you teach him, you are supposed to teach all the chapters of a subject continuously.
Let us say that his initial per chapter learning power of a subject is *x* hours. In other words he can learn a chapter of a particular subject in *x* hours.
Well Devu is not complete dumb, there is a good thing about him too. If you teach him a subject, then time required to teach any chapter of the next subject will require exactly 1 hour less than previously required (see the examples to understand it more clearly). Note that his per chapter learning power can not be less than 1 hour.
You can teach him the *n* subjects in any possible order. Find out minimum amount of time (in hours) Devu will take to understand all the subjects and you will be free to do some enjoying task rather than teaching a dumb guy.
Please be careful that answer might not fit in 32 bit data type.
|
```python
n,x=map(int,input().split())
w=sorted(list(map(int,input().split())))
s,i=0,0
while True:
s+=(w[i]*x)
if x>1:
x-=1
i+=1
if i==n:
break
print (s)
```
|
|
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
val=int(input())
if (val % 2 == 0):
print(2)
else:
print(1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a graph with $n$ nodes and $m$ directed edges. One lowercase letter is assigned to each node. We define a path's value as the number of the most frequently occurring letter. For example, if letters on a path are "abaca", then the value of that path is $3$. Your task is find a path whose value is the largest.
|
```python
from collections import deque, defaultdict
n, m = map(int, input().split())
letters = input().strip()
graph = defaultdict(list)
indegree = [0] * n
q = deque([])
mat = [[0] * 26 for _ in range(n)]
for _ in range(m):
x, y = map(int, input().split())
graph[x-1].append(y-1)
indegree[y-1] += 1
for i in range(n):
if indegree[i] == 0:
q.append(i)
cnt = 0
while q:
cur = q.popleft()
cnt += 1
mat[cur][ord(letters[cur]) - ord('a')] += 1
for nei in graph[cur]:
for j in range(26):
mat[nei][j] = max(mat[nei][j], mat[cur][j])
indegree[nei] -= 1
if indegree[nei] == 0:
q.append(nei)
if cnt != n:
print(-1)
exit(0)
ans = 0
for i in range(len(mat)):
for j in range(26):
ans = max(ans, mat[i][j])
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.
Rules of the game are very simple: at first number of rounds *n* is defined. In every round each of the players throws a cubical dice with distinct numbers from 1 to 6 written on its faces. Player, whose value after throwing the dice is greater, wins the round. In case if player dice values are equal, no one of them is a winner.
In average, player, who won most of the rounds, is the winner of the game. In case if two players won the same number of rounds, the result of the game is draw.
Mishka is still very little and can't count wins and losses, so she asked you to watch their game and determine its result. Please help her!
|
```python
n = int(input())
m = 0
c = 0
for i in range(n):
x,y = map(int,input().split())
if x>y:
m = m+1
elif x<y:
c = c+1
if (m>c):
print("Mishka")
elif m<c:
print("Chris")
else:
print("Friendship is magic!^^")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not enough time to assign tanks into teams and the whole game will collapse!
There are exactly *n* distinct countries in the world and the *i*-th country added *a**i* tanks to the game. As the developers of the game are perfectionists, the number of tanks from each country is beautiful. A beautiful number, according to the developers, is such number that its decimal representation consists only of digits '1' and '0', moreover it contains at most one digit '1'. However, due to complaints from players, some number of tanks of one country was removed from the game, hence the number of tanks of this country may not remain beautiful.
Your task is to write the program that solves exactly the same problem in order to verify Gena's code correctness. Just in case.
|
```python
n=int(input())
ans=1
for i in range(0,n):
e=int(input())
ans*=e
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The following problem is well-known: given integers *n* and *m*, calculate
where 2*n*<==<=2·2·...·2 (*n* factors), and denotes the remainder of division of *x* by *y*.
You are asked to solve the "reverse" problem. Given integers *n* and *m*, calculate
|
```python
a = int(input())
b = int(input())
c = 2**a
print(b%c)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At that as little as possible letters should be changed in the word. For example, the word HoUse must be replaced with house, and the word ViP — with VIP. If a word contains an equal number of uppercase and lowercase letters, you should replace all the letters with lowercase ones. For example, maTRIx should be replaced by matrix. Your task is to use the given method on one given word.
|
```python
x=input()
a=x
lowercount=0
uppercount=0
x=list(map(str,str(x)))
for i in x:
if i==i.lower():
lowercount=lowercount+1
else:
uppercount=uppercount+1
if(lowercount>=uppercount):
a=a.lower()
else:
a=a.upper()
print(a)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You've got a rectangular parallelepiped with integer edge lengths. You know the areas of its three faces that have a common vertex. Your task is to find the sum of lengths of all 12 edges of this parallelepiped.
|
```python
l = list(map(int, input().split()))
a = int(((l[0]*l[2])//l[1])**0.5)
b = int(((l[0]*l[1])//l[2])**0.5)
c = int(((l[1]*l[2])//l[0])**0.5)
print(4*(a+b+c))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Theatre Square in the capital city of Berland has a rectangular shape with the size *n*<=×<=*m* meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size *a*<=×<=*a*.
What is the least number of flagstones needed to pave the Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square.
|
```python
n, m, a = map(int, input().split())
side1 = n % a
side2 = m % a
if side1 != 0:
val1 = n // a + 1
else:
val1 = n // a
if side2 != 0:
val2 = m // a + 1
else:
val2 = m // a
print(val1 * val2)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Permutation *p* is an ordered set of integers *p*1,<=<=<=*p*2,<=<=<=...,<=<=<=*p**n*, consisting of *n* distinct positive integers not larger than *n*. We'll denote as *n* the length of permutation *p*1,<=<=<=*p*2,<=<=<=...,<=<=<=*p**n*.
Your task is to find such permutation *p* of length *n*, that the group of numbers |*p*1<=-<=*p*2|,<=|*p*2<=-<=*p*3|,<=...,<=|*p**n*<=-<=1<=-<=*p**n*| has exactly *k* distinct elements.
|
```python
n, k = map(int, input().split(' '))
o = n - k
print(1, end = ' ')
for i in range(2, o + 1):
print(i, end = ' ')
mb = n
mm = o + 1
while mb >= mm:
print(mb, end = ' ')
mb -= 1
if mb >= mm:
print(mm, end = ' ')
mm += 1
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited *n* his friends there.
If there's one thing Petya likes more that receiving gifts, that's watching others giving gifts to somebody else. Thus, he safely hid the laptop until the next New Year and made up his mind to watch his friends exchanging gifts while he does not participate in the process. He numbered all his friends with integers from 1 to *n*. Petya remembered that a friend number *i* gave a gift to a friend number *p**i*. He also remembered that each of his friends received exactly one gift.
Now Petya wants to know for each friend *i* the number of a friend who has given him a gift.
|
```python
n=int(input())
p=list(map(int,input().split()))
s=list(range(1,101))
v=[]
for i in range(n):
c=p.index(min(p))
v.append(s[c])
p[c]=10000
print(*v)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry.
He bought *n* pieces of jewelry. The *i*-th piece has price equal to *i*<=+<=1, that is, the prices of the jewelry are 2,<=3,<=4,<=... *n*<=+<=1.
Watson gave Sherlock a challenge to color these jewelry pieces such that two pieces don't have the same color if the price of one piece is a prime divisor of the price of the other piece. Also, Watson asked him to minimize the number of different colors used.
Help Sherlock complete this trivial task.
|
```python
n=int(input())
isp=[1]*(n+2)
isp[1]=2
for i in range(2,n+2):
if isp[i]==1:
for j in range(i*i,n+2,i):
isp[i]=2
print(1 if n<=2 else 2)
print(' '.join(str(isp[i]) for i in range(2,n+2)))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given the current time in 24-hour format hh:mm. Find and print the time after *a* minutes.
Note that you should find only the time after *a* minutes, see the examples to clarify the problem statement.
You can read more about 24-hour format here [https://en.wikipedia.org/wiki/24-hour_clock](https://en.wikipedia.org/wiki/24-hour_clock).
|
```python
a,b=map(int,input().split(":"))
z=int(input())
k=z//60;z=z%60
a=(a+k)%24
if b+z>59:
a=(a+1)%24;b=(b+z)%60
else:b+=z
a=str(a);b=str(b)
if len(a)==1:a="0"+a
if len(b)==1:b="0"+b
print(a+":"+b)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The School №0 of the capital of Berland has *n* children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value *t**i*:
- *t**i*<==<=1, if the *i*-th child is good at programming, - *t**i*<==<=2, if the *i*-th child is good at maths, - *t**i*<==<=3, if the *i*-th child is good at PE
Each child happens to be good at exactly one of these three subjects.
The Team Scientific Decathlon Olympias requires teams of three students. The school teachers decided that the teams will be composed of three children that are good at different subjects. That is, each team must have one mathematician, one programmer and one sportsman. Of course, each child can be a member of no more than one team.
What is the maximum number of teams that the school will be able to present at the Olympiad? How should the teams be formed for that?
|
```python
n = int(input())
t = list(map(int, input().split()))
one = []
two = []
three = []
for i in range(n):
if t[i] == 1:
one.append(i+1)
elif t[i] == 2:
two.append(i+1)
else:
three.append(i+1)
minNumAmnt = min(len(one), len(two), len(three))
print(minNumAmnt)
for i in range(minNumAmnt):
print(f"{one[i]} {two[i]} {three[i]}")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Theatre Square in the capital city of Berland has a rectangular shape with the size *n*<=×<=*m* meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size *a*<=×<=*a*.
What is the least number of flagstones needed to pave the Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square.
|
```python
a,s,d=list(map(int,input().split()))
q=a*s
w=d*d
if(q%w==0):
print(int(q/w))
else:
print(q%w)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Iahub is very proud of his recent discovery, propagating trees. Right now, he invented a new tree, called xor-tree. After this new revolutionary discovery, he invented a game for kids which uses xor-trees.
The game is played on a tree having *n* nodes, numbered from 1 to *n*. Each node *i* has an initial value *init**i*, which is either 0 or 1. The root of the tree is node 1.
One can perform several (possibly, zero) operations on the tree during the game. The only available type of operation is to pick a node *x*. Right after someone has picked node *x*, the value of node *x* flips, the values of sons of *x* remain the same, the values of sons of sons of *x* flips, the values of sons of sons of sons of *x* remain the same and so on.
The goal of the game is to get each node *i* to have value *goal**i*, which can also be only 0 or 1. You need to reach the goal of the game by using minimum number of operations.
|
```python
'''input
10
2 1
3 1
4 2
5 1
6 2
7 5
8 6
9 8
10 5
1 0 1 1 0 1 0 1 0 1
1 0 1 0 0 1 1 1 0 1
'''
from sys import stdin, setrecursionlimit
from collections import defaultdict
setrecursionlimit(15000)
def counter(num):
if num == 0:
return 1
else:
return 0
def flip_me(original, count, index):
if count % 2 == 0:
return original[index]
else:
return counter(original[index])
def dfs(graph, visited, ans, original, goal, change, node):
visited[node] = True
value = flip_me(original, change[node], node - 1)
add = 0
if goal[node - 1] == value:
pass
else:
add = 1
ans.append(node)
for i in graph[node]:
if visited[i] == False:
for j in graph[i]:
if visited[j] == False:
change[j] += change[node] + add
dfs(graph, visited, ans, original, goal, change, i)
def calculate(graph, original, goal):
visited = dict()
change = dict()
for i in graph:
visited[i] = False
change[i] = 0
ans = []
dfs(graph, visited, ans, original, goal, change, 1)
return ans
# main starts
n = int(stdin.readline().strip())
graph = defaultdict(list)
for _ in range(n - 1):
u, v = list(map(int, stdin.readline().split()))
graph[u].append(v)
graph[v].append(u)
original = list(map(int, stdin.readline().split()))
goal = list(map(int, stdin.readline().split()))
count = [0]
ans = calculate(graph, original, goal)
print(len(ans))
for i in ans:
print(i)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Mr. Kitayuta has kindly given you a string *s* consisting of lowercase English letters. You are asked to insert exactly one lowercase English letter into *s* to make it a palindrome. A palindrome is a string that reads the same forward and backward. For example, "noon", "testset" and "a" are all palindromes, while "test" and "kitayuta" are not.
You can choose any lowercase English letter, and insert it to any position of *s*, possibly to the beginning or the end of *s*. You have to insert a letter even if the given string is already a palindrome.
If it is possible to insert one lowercase English letter into *s* so that the resulting string will be a palindrome, print the string after the insertion. Otherwise, print "NA" (without quotes, case-sensitive). In case there is more than one palindrome that can be obtained, you are allowed to print any of them.
|
```python
def is_p(s):
return s==s[::-1]
s=input()
for i in range(len(s)):
for c in 'abcdefghijklmnopqrstuvwxyz':
if is_p(s[:i]+c+s[i:]):
print(s[:i]+c+s[i:])
exit(0)
print("NA")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Polycarp has interviewed Oleg and has written the interview down without punctuation marks and spaces to save time. Thus, the interview is now a string *s* consisting of *n* lowercase English letters.
There is a filler word ogo in Oleg's speech. All words that can be obtained from ogo by adding go several times to the end of it are also considered to be fillers. For example, the words ogo, ogogo, ogogogo are fillers, but the words go, og, ogog, ogogog and oggo are not fillers.
The fillers have maximal size, for example, for ogogoo speech we can't consider ogo a filler and goo as a normal phrase. We should consider ogogo as a filler here.
To print the interview, Polycarp has to replace each of the fillers with three asterisks. Note that a filler word is replaced with exactly three asterisks regardless of its length.
Polycarp has dealt with this problem in no time. Can you do the same? The clock is ticking!
|
```python
import re
input()
print(re.sub(r'o(go)+',"*"*3,input()))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a chessboard of size 1<=×<=*n*. It is guaranteed that *n* is even. The chessboard is painted like this: "BWBW...BW".
Some cells of the board are occupied by the chess pieces. Each cell contains no more than one chess piece. It is known that the total number of pieces equals to .
In one step you can move one of the pieces one cell to the left or to the right. You cannot move pieces beyond the borders of the board. You also cannot move pieces to the cells that are already occupied.
Your task is to place all the pieces in the cells of the same color using the minimum number of moves (all the pieces must occupy only the black cells or only the white cells after all the moves are made).
|
```python
n = int(input())
n = n/2
a = [int(x) for x in input().split(" ")]
sorted(a)
p1 = 1
p2 = 2
r1 = 0
r2 = 0
for element in a:
r1 = r1 + abs(element-p1)
r2 = r2 + abs(element-p2)
p1 = p1 + 2
p2 = p2 + 2
print(min(r1, r2))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number *a* and Antisimon receives number *b*. They also have a heap of *n* stones. The players take turns to make a move and Simon starts. During a move a player should take from the heap the number of stones equal to the greatest common divisor of the fixed number he has received and the number of stones left in the heap. A player loses when he cannot take the required number of stones (i. e. the heap has strictly less stones left than one needs to take).
Your task is to determine by the given *a*, *b* and *n* who wins the game.
|
```python
a,b,n = map(int, input().split())
i = 0
b1 = n
b2 = n
a1 = a
a2 = b
while n>=0:
if i%2 == 0:
while b1>0:
c = a1
a1 = b1
b1 = c%a1
n -= a1
i += 1
b2 = n
else:
while b2>0:
c = a2
a2 = b2
b2 = c%a2
n -= a2
i += 1
b1 = n
if i % 2 ==0:
print(0)
else:
print(1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Let's call an undirected graph $G = (V, E)$ relatively prime if and only if for each edge $(v, u) \in E$ $GCD(v, u) = 1$ (the greatest common divisor of $v$ and $u$ is $1$). If there is no edge between some pair of vertices $v$ and $u$ then the value of $GCD(v, u)$ doesn't matter. The vertices are numbered from $1$ to $|V|$.
Construct a relatively prime graph with $n$ vertices and $m$ edges such that it is connected and it contains neither self-loops nor multiple edges.
If there exists no valid graph with the given number of vertices and edges then output "Impossible".
If there are multiple answers then print any of them.
|
```python
from fractions import gcd
n,m = map(int,input().split())
sol = []
for i in range(1,n+1):
for j in range(i+1,n+1):
if gcd(i,j) == 1:
sol.append('{} {}'.format(i,j))
if len(sol)>=m:break
if len(sol)>=m:
print ('Possible')
print ('\n'.join(sol[:m]))
else:
print ('Impossible')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
When Valera has got some free time, he goes to the library to read some books. Today he's got *t* free minutes to read. That's why Valera took *n* books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to *n*. Valera needs *a**i* minutes to read the *i*-th book.
Valera decided to choose an arbitrary book with number *i* and read the books one by one, starting from this book. In other words, he will first read book number *i*, then book number *i*<=+<=1, then book number *i*<=+<=2 and so on. He continues the process until he either runs out of the free time or finishes reading the *n*-th book. Valera reads each book up to the end, that is, he doesn't start reading the book if he doesn't have enough free time to finish reading it.
Print the maximum number of books Valera can read.
|
```python
a,b=map(int, input().split())
A=list(map(int, input().split()))
t=0
k=0
for x in A:
t+=x
if t>b:
t-=A[k]
k+=1
print(a-k)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.
|
```python
n=int(input())
s=int()
f=0
for k in range(n):
s=0
m=0
r=0
a=[int(i) for i in input().split(" ")]
for i in range(len(a)):
s=s+a[i]
m=m+s
f=f+m
if m>0:
r=r+1
elif m<0:
r=r-1
k=k+r
if f==0 and k<=n:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer.
At the start of the day they have *x* ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. Each person in the queue wants either to take several ice cream packs for himself and his friends or to give several ice cream packs to Kay and Gerda (carriers that bring ice cream have to stand in the same queue).
If a carrier with *d* ice cream packs comes to the house, then Kay and Gerda take all his packs. If a child who wants to take *d* ice cream packs comes to the house, then Kay and Gerda will give him *d* packs if they have enough ice cream, otherwise the child will get no ice cream at all and will leave in distress.
Kay wants to find the amount of ice cream they will have after all people will leave from the queue, and Gerda wants to find the number of distressed kids.
|
```python
n_x = input().split();
n = int(n_x[0]);
x = int(n_x[1]);
dis_count = 0;
for i in range(n):
inp = input().split();
if inp[0] == '+':
x += int(inp[1]);
else:
if int(inp[1]) < x:
x -= int(inp[1]);
else:
dis_count += 1;
print(x," ",dis_count);
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya has got two number: *a* and *b*. However, Vasya finds number *a* too short. So he decided to repeat the operation of lengthening number *a* *n* times.
One operation of lengthening a number means adding exactly one digit to the number (in the decimal notation) to the right provided that the resulting number is divisible by Vasya's number *b*. If it is impossible to obtain the number which is divisible by *b*, then the lengthening operation cannot be performed.
Your task is to help Vasya and print the number he can get after applying the lengthening operation to number *a* *n* times.
|
```python
def main():
a,b,n=map(int,input().split())
mon = a
cnt = 0
non_exist = False
while n!=0:
for i in range(1,10):
if (a*10+i) %b == 0:
a = a*10+i
break
n-=1
if mon == a:
print(-1)
else:
print(a)
main()
```
|
|
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
s=input()
if ord(s[0])>90:
a=chr(ord(s[0])-32)
c=a
for i in range(1,len(s)):
c+=str(s[i])
print(c)
else:
print(s)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There are *n* cities in Bearland, numbered 1 through *n*. Cities are arranged in one long row. The distance between cities *i* and *j* is equal to |*i*<=-<=*j*|.
Limak is a police officer. He lives in a city *a*. His job is to catch criminals. It's hard because he doesn't know in which cities criminals are. Though, he knows that there is at most one criminal in each city.
Limak is going to use a BCD (Bear Criminal Detector). The BCD will tell Limak how many criminals there are for every distance from a city *a*. After that, Limak can catch a criminal in each city for which he is sure that there must be a criminal.
You know in which cities criminals are. Count the number of criminals Limak will catch, after he uses the BCD.
|
```python
# Problem Link: https://codeforces.com/problemset/problem/680/B
# Problem Status:
# -------------------- SEPARATOR --------------------
def TheAmazingFunction(Arr: list, A):
Answer = 0
i = A - 1
j = A - 1
while i >= 0 or j < len(Arr):
if i == j:
if Arr[i] == 1:
Answer += 1
else:
if i >= 0 and j < len(Arr):
if Arr[i] + Arr[j] == 2:
Answer += 2
else:
if i >= 0:
Answer += Arr[i]
else:
Answer += Arr[j]
i -= 1
j += 1
return Answer
# -------------------- SEPARATOR --------------------
N, A_ = list(map(int, input().split()))
Arr_ = list(map(int, input().split()))
print(TheAmazingFunction(Arr_, A_))
# -------------------- SEPARATOR --------------------
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One day Vasya came across three Berland coins. They didn't have any numbers that's why Vasya didn't understand how their denominations differ. He supposed that if one coin is heavier than the other one, then it should be worth more. Vasya weighed all the three pairs of coins on pan balance scales and told you the results. Find out how the deminations of the coins differ or if Vasya has a mistake in the weighting results. No two coins are equal.
|
```python
dict_ = {'A':1,'B':1,'C':1}
def solve_dict(dict_):
items = sorted(dict_.values())
for j in range(1,len(items)):
if items[j] - items[j-1] > 1:
return 'Impossible'
return ''.join(sorted(dict_, key=dict_.get))
for i in range(3):
s = input()
a = s[0]
b = s[2]
sign = s[1]
if sign == '>':
if (not(dict_[a] > dict_[b])):
dict_[a] = dict_[b] + 1
else:
if (not(dict_[b] > dict_[a])):
dict_[a] = dict_[b] - 1
print(solve_dict(dict_))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a rectangular board of *M*<=×<=*N* squares. Also you are given an unlimited number of standard domino pieces of 2<=×<=1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squares.
2. No two dominoes overlap.
3. Each domino lies entirely inside the board. It is allowed to touch the edges of the board.
Find the maximum number of dominoes, which can be placed under these restrictions.
|
```python
M = int(input("M = "))
N = int(input("N = "))
print((N // 2) * M + (N % 2) * (M // 2))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings *a* and *b* of equal length are called equivalent in one of the two cases:
1. They are equal. 1. If we split string *a* into two halves of the same size *a*1 and *a*2, and string *b* into two halves of the same size *b*1 and *b*2, then one of the following is correct: *a*1 is equivalent to *b*1, and *a*2 is equivalent to *b*2 1. *a*1 is equivalent to *b*2, and *a*2 is equivalent to *b*1
As a home task, the teacher gave two strings to his students and asked to determine if they are equivalent.
Gerald has already completed this home task. Now it's your turn!
|
```python
def sortString(str):
length = len(str)
if (length % 2 != 0):
return str
length //= 2
left = sortString(str[:length])
right = sortString(str[length:])
if left < right:
return left + right
else:
return right + left
a = input()
b = input()
print("YES" if sortString(a) == sortString(b) else "NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya wonders eagerly what minimum lucky number has the sum of digits equal to *n*. Help him cope with the task.
|
```python
n = int(input())
ans = ""
printou = False
hasSeven = False
hasFour = False
while(n>0):
if n >= 7 and n-7 >= 4:
n-=7
ans+="7"
hasSeven = True
elif n >=4:
n-=4
ans+="4"
hasFour = True
else:
print(-1)
printou = True
break
if(not printou):
if hasSeven and hasFour:
print(ans[::-1])
else:
print(-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot.
He wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fence corners at a single angle *a*.
Will the robot be able to build the fence Emuskald wants? In other words, is there a regular polygon which angles are equal to *a*?
|
```python
t = int(input())
for i in range(t):
a = int(input())
n = 3
while n < 180:
if a == 180*(n-2)/n:
print('YES')
break
else:
n += 1
if n >= 180:
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There are *n* cities numbered from 1 to *n* in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build *k* new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
|
```python
from collections import defaultdict
def dijkstra(graph, start, end):
import heapq
heap = [(0, start)] # cost from start node,end node
visited = set()
while heap:
(cost, u) = heapq.heappop(heap)
if u in visited:
continue
visited.add(u)
if u == end:
return cost
for v, c in graph[u]:
if v in visited:
continue
next_item = cost + c
heapq.heappush(heap, (next_item, v))
return -1
def main():
n = int(input())
graph = defaultdict(list)
for i in range(n):
row = list(map(int, input().split()))
for j in range(n):
graph[i].append((j, row[j]))
graph[j].append((i, row[j]))
ans = []
k = int(input())
for _ in range(k):
a,b,c = map(int, input().split())
a-=1
b-=1
graph[a].append((b, c))
graph[b].append((a, c))
tot = 0
for u in range(n):
for v in range(u):
cur = dijkstra(graph, u, v)
tot += cur
ans.append(tot)
print(*ans)
main()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A family consisting of father bear, mother bear and son bear owns three cars. Father bear can climb into the largest car and he likes it. Also, mother bear can climb into the middle car and she likes it. Moreover, son bear can climb into the smallest car and he likes it. It's known that the largest car is strictly larger than the middle car, and the middle car is strictly larger than the smallest car.
Masha came to test these cars. She could climb into all cars, but she liked only the smallest car.
It's known that a character with size *a* can climb into some car with size *b* if and only if *a*<=≤<=*b*, he or she likes it if and only if he can climb into this car and 2*a*<=≥<=*b*.
You are given sizes of bears and Masha. Find out some possible integer non-negative sizes of cars.
|
```python
v1,v2,v3,vm=map(int,input().split())
if vm>2*v3:
print(-1)
else:
if v1-2*vm >0 and v2 -2*v3 >0:
print(v1,v2,v3)
else:
print(-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited *n* his friends there.
If there's one thing Petya likes more that receiving gifts, that's watching others giving gifts to somebody else. Thus, he safely hid the laptop until the next New Year and made up his mind to watch his friends exchanging gifts while he does not participate in the process. He numbered all his friends with integers from 1 to *n*. Petya remembered that a friend number *i* gave a gift to a friend number *p**i*. He also remembered that each of his friends received exactly one gift.
Now Petya wants to know for each friend *i* the number of a friend who has given him a gift.
|
```python
x=int(input());a=input().split();print(*[a.index(str(i+1))+1for i in range(x)])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number *a* and Antisimon receives number *b*. They also have a heap of *n* stones. The players take turns to make a move and Simon starts. During a move a player should take from the heap the number of stones equal to the greatest common divisor of the fixed number he has received and the number of stones left in the heap. A player loses when he cannot take the required number of stones (i. e. the heap has strictly less stones left than one needs to take).
Your task is to determine by the given *a*, *b* and *n* who wins the game.
|
```python
a,b,n=[int(i) for i in input().split()]
for i in range(100):
if i%2==0:
if n==0:
print(1)
break
elif n%a==0:
n=n-a
else:
n-=1
else:
if n==0:
print(0)
break
elif n%b==0:
n=n-b
else:
n-=1
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.
Thus, "localization" will be spelt as "l10n", and "internationalization» will be spelt as "i18n".
You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.
|
```python
t=int(input())
for i in range(t):
a=input()
n=len(a)
s1 = a[0]
l1 = a[-1]
length=len(a[1:-1])
if n>10:
print(f"{s1}{length}{l1}")
else:
print(a)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Olesya loves numbers consisting of *n* digits, and Rodion only likes numbers that are divisible by *t*. Find some number that satisfies both of them.
Your task is: given the *n* and *t* print an integer strictly larger than zero consisting of *n* digits that is divisible by *t*. If such number doesn't exist, print <=-<=1.
|
```python
from collections import defaultdict
import math
def pug_func(s: str) -> int:
n, t = s.split(" ")
n = int(n)
t = int(t)
num = 10 ** (n - 1)
for i in range(1, 11):
if (num * i) % t == 0:
return num * i
return -1
t = input()
x = pug_func(t)
print(x)
# t = int(input())
# lista_ans = []
# for _ in range(t):
# n = input()
# line = input()
# lista_ans.append(line)
# for ans in lista_ans:
# x = pug_func(ans)
# print(x)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At that as little as possible letters should be changed in the word. For example, the word HoUse must be replaced with house, and the word ViP — with VIP. If a word contains an equal number of uppercase and lowercase letters, you should replace all the letters with lowercase ones. For example, maTRIx should be replaced by matrix. Your task is to use the given method on one given word.
|
```python
def word(s):
c = 0
for i in s:
print(ord(i))
if 97<=ord(i)<=122:
c += 1
else:
c -= 1
print(c)
print(c)
if c >=0 :
return s.lower()
return s.upper()
print(word(input()))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Once when Gerald studied in the first year at school, his teacher gave the class the following homework. She offered the students a string consisting of *n* small Latin letters; the task was to learn the way the letters that the string contains are written. However, as Gerald is too lazy, he has no desire whatsoever to learn those letters. That's why he decided to lose some part of the string (not necessarily a connected part). The lost part can consist of any number of segments of any length, at any distance from each other. However, Gerald knows that if he loses more than *k* characters, it will be very suspicious.
Find the least number of distinct characters that can remain in the string after no more than *k* characters are deleted. You also have to find any possible way to delete the characters.
|
```python
s = input()
k = int(input())
t = 'a'
fr = [0] * 26
for i in s:
fr[ord('a') - 97]+=1
while k != 0:
try:
x = min(i for i in fr if i > 0)
except:
x = 0
if x == 0:
break
if k >= x:
fr[fr.index(x)] = 0
k -= x
else:
k = 0
ans = ""
c = 0
for i in range(26):
if fr[i]:
ans += chr(ord('a') + i)
c+=1
print(c, '\n', ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little Petya is learning to play chess. He has already learned how to move a king, a rook and a bishop. Let us remind you the rules of moving chess pieces. A chessboard is 64 square fields organized into an 8<=×<=8 table. A field is represented by a pair of integers (*r*,<=*c*) — the number of the row and the number of the column (in a classical game the columns are traditionally indexed by letters). Each chess piece takes up exactly one field. To make a move is to move a chess piece, the pieces move by the following rules:
- A rook moves any number of fields horizontally or vertically. - A bishop moves any number of fields diagonally. - A king moves one field in any direction — horizontally, vertically or diagonally.
Petya is thinking about the following problem: what minimum number of moves is needed for each of these pieces to move from field (*r*1,<=*c*1) to field (*r*2,<=*c*2)? At that, we assume that there are no more pieces besides this one on the board. Help him solve this problem.
|
```python
# MC521 - Desafios de Programacao I - 1s2021
# Contest: 21/05/2021
# Problema D: Rook, Bishop and King
# leitura da posicao inicial e final
r1, c1, r2, c2 = map(int, input().split())
# movimentos necessarios para a torre
R = 0
if(r1 != r2): R += 1
if(c1 != c2): R += 1
# movimentos necessarios para o bispo
B = 0
if(abs(c2-c1) == abs(r2-r1) > 0):
if(abs(c2-c1) == abs(r2-r1)): B = 1
else: B = 2
# movimentos necessarios para o rei
K = abs(c2-c1)
if(abs(r2-r1) > abs(c2-c1)):
K = abs(r2-r1)
# imprime
print("{} {} {}".format(R, B, K))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity.
There are *n* columns of toy cubes in the box arranged in a line. The *i*-th column contains *a**i* cubes. At first, the gravity in the box is pulling the cubes downwards. When Chris switches the gravity, it begins to pull all the cubes to the right side of the box. The figure shows the initial and final configurations of the cubes in the box: the cubes that have changed their position are highlighted with orange.
Given the initial configuration of the toy cubes in the box, find the amounts of cubes in each of the *n* columns after the gravity switch!
|
```python
n = int(input())
cubes = list(map(int, input().split()))
# Sort the array in non-decreasing order
cubes.sort()
# Output the sorted array
print(*cubes)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a string *s* consisting of |*s*| small english letters.
In one move you can replace any character of this string to the next character in alphabetical order (a will be replaced with b, s will be replaced with t, etc.). You cannot replace letter z with any other letter.
Your target is to make some number of moves (not necessary minimal) to get string abcdefghijklmnopqrstuvwxyz (english alphabet) as a subsequence. Subsequence of the string is the string that is obtained by deleting characters at some positions. You need to print the string that will be obtained from the given string and will be contain english alphabet as a subsequence or say that it is impossible.
|
```python
s = list(input())
alph = "abcdefghijklmnopqrstuvwxyz"
ind = 0
for i, char in enumerate(s):
if ind == ord(char) - 97:
ind += 1
elif ind == ord(char) - 97 + 1:
s[i] = chr(ord(char) + 1)
ind += 1
if ind == 26:
print("".join(s))
else:
print(-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?
You are given a system of equations:
You should count, how many there are pairs of integers (*a*,<=*b*) (0<=≤<=*a*,<=*b*) which satisfy the system.
|
```python
n, m, answer = 0, 0, 0
n, m = map(int, input().split())
i = 0
while i * i <= n and i <= m:
b = n - i * i
if i + b * b == m:
answer += 1
i += 1
print(answer)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Codeforces user' handle color depends on his rating — it is red if his rating is greater or equal to 2400; it is orange if his rating is less than 2400 but greater or equal to 2200, etc. Each time participant takes part in a rated contest, his rating is changed depending on his performance.
Anton wants the color of his handle to become red. He considers his performance in the rated contest to be good if he outscored some participant, whose handle was colored red before the contest and his rating has increased after it.
Anton has written a program that analyses contest results and determines whether he performed good or not. Are you able to do the same?
|
```python
s = 'NO'
for _ in range(int(input())):
t = input().split(' ')
if 2400 <= int(t[1]) < int(t[2]):
s = 'YES'
print(s)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number *a* and Antisimon receives number *b*. They also have a heap of *n* stones. The players take turns to make a move and Simon starts. During a move a player should take from the heap the number of stones equal to the greatest common divisor of the fixed number he has received and the number of stones left in the heap. A player loses when he cannot take the required number of stones (i. e. the heap has strictly less stones left than one needs to take).
Your task is to determine by the given *a*, *b* and *n* who wins the game.
|
```python
a, b, c = [int(x) for x in input().split()]
def nod(lhs, rhs):
if rhs==0:
return lhs
else:
return nod(rhs, lhs%rhs)
d=nod(a,c)
k=0
while c>0:
if k==0:
d=nod(a,c)
else:
d=nod(b,c)
c -= d
k = (k + 1) % 2
print((k + 1) % 2)
```
|
|
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
s = list(input())
s.pop(0)
s.pop()
s = ''.join(s)
s = set(s.split(', '))
print(len(s))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Valera is a collector. Once he wanted to expand his collection with exactly one antique item.
Valera knows *n* sellers of antiques, the *i*-th of them auctioned *k**i* items. Currently the auction price of the *j*-th object of the *i*-th seller is *s**ij*. Valera gets on well with each of the *n* sellers. He is perfectly sure that if he outbids the current price of one of the items in the auction (in other words, offers the seller the money that is strictly greater than the current price of the item at the auction), the seller of the object will immediately sign a contract with him.
Unfortunately, Valera has only *v* units of money. Help him to determine which of the *n* sellers he can make a deal with.
|
```python
n,v = map(int,input().split())
l1 = []
for i in range(n):
k = list(map(int,input().split()))
if min(k[1:]) < v:
l1.append(i+1)
print(len(l1))
print(*l1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob.
Right now, Limak and Bob weigh *a* and *b* respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight.
Limak eats a lot and his weight is tripled after every year, while Bob's weight is doubled after every year.
After how many full years will Limak become strictly larger (strictly heavier) than Bob?
|
```python
num = input().split(" ")
i=0
a,b = int(num[0]),int(num[1])
while(True):
a *= 3
b *= 2
i += 1
if(a>b):
print(i)
break
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
As you may know, MemSQL has American offices in both San Francisco and Seattle. Being a manager in the company, you travel a lot between the two cities, always by plane.
You prefer flying from Seattle to San Francisco than in the other direction, because it's warmer in San Francisco. You are so busy that you don't remember the number of flights you have made in either direction. However, for each of the last *n* days you know whether you were in San Francisco office or in Seattle office. You always fly at nights, so you never were at both offices on the same day. Given this information, determine if you flew more times from Seattle to San Francisco during the last *n* days, or not.
|
```python
int(input());k=input();print("YES" if k.count("SF")>k.count("FS") else "NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
One day Petya came across an interval of numbers [*a*,<=*a*<=+<=*l*<=-<=1]. Let *F*(*x*) be the number of lucky digits of number *x*. Find the minimum *b* (*a*<=<<=*b*) such, that *F*(*a*) = *F*(*b*), *F*(*a*<=+<=1) = *F*(*b*<=+<=1), ..., *F*(*a*<=+<=*l*<=-<=1) = *F*(*b*<=+<=*l*<=-<=1).
|
```python
import itertools
def F(x):
q = 0
for i in str(x):
if i == '4' or i == '7':
q += 1
return q
a, l = map(lambda x: int(x), input().split())
Fa = [F(i) for i in range(a, a+l)]
for b in itertools.count(a+1):
for i in range(l):
if Fa[i] != F(b+i):
break
else:
print(b)
break
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Recently, you bought a brand new smart lamp with programming features. At first, you set up a schedule to the lamp. Every day it will turn power on at moment $0$ and turn power off at moment $M$. Moreover, the lamp allows you to set a program of switching its state (states are "lights on" and "lights off"). Unfortunately, some program is already installed into the lamp.
The lamp allows only good programs. Good program can be represented as a non-empty array $a$, where $0 < a_1 < a_2 < \dots < a_{|a|} < M$. All $a_i$ must be integers. Of course, preinstalled program is a good program.
The lamp follows program $a$ in next manner: at moment $0$ turns power and light on. Then at moment $a_i$ the lamp flips its state to opposite (if it was lit, it turns off, and vice versa). The state of the lamp flips instantly: for example, if you turn the light off at moment $1$ and then do nothing, the total time when the lamp is lit will be $1$. Finally, at moment $M$ the lamp is turning its power off regardless of its state.
Since you are not among those people who read instructions, and you don't understand the language it's written in, you realize (after some testing) the only possible way to alter the preinstalled program. You can insert at most one element into the program $a$, so it still should be a good program after alteration. Insertion can be done between any pair of consecutive elements of $a$, or even at the begining or at the end of $a$.
Find such a way to alter the program that the total time when the lamp is lit is maximum possible. Maybe you should leave program untouched. If the lamp is lit from $x$ till moment $y$, then its lit for $y - x$ units of time. Segments of time when the lamp is lit are summed up.
|
```python
m,n=map(int,input().split())
l1=[]
l=[0]+list(map(int,input().split()))+[n]
for i in range(m+1):
l1+=[l[i+1]-l[i]]
l3=max(sum(l[::2]),sum(l[1::2]))
for i in range(0,len(l1),2):
if l1[i]!=1:
l3=max(l3,sum(l1[:i+1:2])-1+sum(l1[i+1::2]))
for i in range(1, len(l1), 2):
if l1[i] != 1:
l3=max(l3, sum(l1[:i:2]) - 1 + sum(l1[i::2]))
print(l3)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At that as little as possible letters should be changed in the word. For example, the word HoUse must be replaced with house, and the word ViP — with VIP. If a word contains an equal number of uppercase and lowercase letters, you should replace all the letters with lowercase ones. For example, maTRIx should be replaced by matrix. Your task is to use the given method on one given word.
|
```python
a = input()
zag = sum(map(str.isupper, a))
stro = sum(map(str.islower, a))
if zag == stro:
print(a.lower())
elif zag > stro:
print(a.upper())
else:
print(a.lower())
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
To stay woke and attentive during classes, Karen needs some coffee!
Karen, a coffee aficionado, wants to know the optimal temperature for brewing the perfect cup of coffee. Indeed, she has spent some time reading several recipe books, including the universally acclaimed "The Art of the Covfefe".
She knows *n* coffee recipes. The *i*-th recipe suggests that coffee should be brewed between *l**i* and *r**i* degrees, inclusive, to achieve the optimal taste.
Karen thinks that a temperature is admissible if at least *k* recipes recommend it.
Karen has a rather fickle mind, and so she asks *q* questions. In each question, given that she only wants to prepare coffee with a temperature between *a* and *b*, inclusive, can you tell her how many admissible integer temperatures fall within the range?
|
```python
rec = [0]*200001
n,q,r = map(int,input().split())
arr = []
for _ in range(n):
a,b=map(int,input().split())
arr.append((a,b))
for i in arr:
for x in range(i[0],i[1]+1):
rec[x]+=1
for _ in range(r):
a,b=map(int,input().split())
ans = 0
for i in range(a,b+1):
if rec[i]>=q:
ans+=1
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a set of integer numbers, initially it is empty. You should perform *n* queries.
There are three different types of queries:
- 1 *l* *r* — Add all missing numbers from the interval [*l*,<=*r*] - 2 *l* *r* — Remove all present numbers from the interval [*l*,<=*r*] - 3 *l* *r* — Invert the interval [*l*,<=*r*] — add all missing and remove all present numbers from the interval [*l*,<=*r*]
After each query you should output MEX of the set — the smallest positive (MEX <=≥<=1) integer number which is not presented in the set.
|
```python
from collections import defaultdict
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def f(z, l, r):
j = l // m
c = 0
if z == 0:
return
elif z == 1:
for i in range(l, r):
c += 1 - a[i]
a[i] = 1
elif z == 2:
for i in range(l, r):
c -= a[i]
a[i] = 0
else:
for i in range(l, r):
c += 1 - 2 * a[i]
a[i] ^= 1
cnt[j] += c
return
n = int(input())
tlr = []
d = defaultdict(lambda : set())
d[0].add(1)
mod = pow(10, 9) + 7
for _ in range(n):
t, l, r = map(int, input().split())
d[l // mod].add(l % mod)
d[(l - 1) // mod].add((l - 1) % mod)
d[r // mod].add(r % mod)
d[(r + 1) // mod].add((r + 1) % mod)
tlr.append((str(t), str(l), str(r)))
if 0 in d[0]:
d[0].remove(0)
s = []
for i in sorted(d.keys()):
u = i * mod
for j in sorted(d[i]):
s.append(str(u + j))
d = dict()
ls = len(s)
for i in range(ls):
d[s[i]] = i
m = 357
u = (ls // m + min(ls % m, 1) + 1) * m
v = u // m
a = [0] * u
b = [0] * v
cnt = [0] * v
ans = []
for t0, l0, r0 in tlr:
t, l, r = int(t0), d[l0], d[r0]
x, y = l // m, r // m
if t < 3:
for i in range(x + 1, y):
b[i] = t
else:
for i in range(x + 1, y):
b[i] ^= 3
if x == y:
f(b[x], x * m, l)
f(b[x], r + 1, (x + 1) * m)
if t < 3:
f(t, l, r + 1)
else:
f(t ^ b[x], l, r + 1)
else:
f(b[x], x * m, l)
f(b[y], r + 1, (y + 1) * m)
if t < 3:
f(t, l, (x + 1) * m)
f(t, y * m, r + 1)
else:
f(t ^ b[x], l, (x + 1) * m)
f(t ^ b[y], y * m, r + 1)
b[x], b[y] = 0, 0
i = 0
while (not cnt[i] ^ m and not b[i]) or (not cnt[i] and b[i] == 3) or b[i] == 1:
i += 1
i *= m
f(b[i // m], i // m * m, i // m * m + m)
b[i // m] = 0
while i < len(s) - 1 and a[i]:
if b[i // m]:
f(b[i // m], i // m * m, i // m * m + m)
b[i // m] = 0
i += 1
ans0 = s[i]
ans.append(ans0)
sys.stdout.write("\n".join(map(str, ans)))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Petya is a big fan of mathematics, especially its part related to fractions. Recently he learned that a fraction is called proper iff its numerator is smaller than its denominator (*a*<=<<=*b*) and that the fraction is called irreducible if its numerator and its denominator are coprime (they do not have positive common divisors except 1).
During his free time, Petya thinks about proper irreducible fractions and converts them to decimals using the calculator. One day he mistakenly pressed addition button (<=+<=) instead of division button (÷) and got sum of numerator and denominator that was equal to *n* instead of the expected decimal notation.
Petya wanted to restore the original fraction, but soon he realized that it might not be done uniquely. That's why he decided to determine maximum possible proper irreducible fraction such that sum of its numerator and denominator equals *n*. Help Petya deal with this problem.
|
```python
import math
n=int(input())
p,q=n//2,n-n//2
while math.gcd(a,b)!=1:p,q=p-1,q+1
print(p,q)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string *s* consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string *s* to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".
If string *s* has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.
Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
|
```python
from collections import Counter
n=int(input())
s=str(input())
count=Counter(s)
c=0
for value in count.values():
if value>=2:
c=c+(value-1)
print(c)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The School №0 of the capital of Berland has *n* children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value *t**i*:
- *t**i*<==<=1, if the *i*-th child is good at programming, - *t**i*<==<=2, if the *i*-th child is good at maths, - *t**i*<==<=3, if the *i*-th child is good at PE
Each child happens to be good at exactly one of these three subjects.
The Team Scientific Decathlon Olympias requires teams of three students. The school teachers decided that the teams will be composed of three children that are good at different subjects. That is, each team must have one mathematician, one programmer and one sportsman. Of course, each child can be a member of no more than one team.
What is the maximum number of teams that the school will be able to present at the Olympiad? How should the teams be formed for that?
|
```python
n=int(input())
a=list(map(int,input().split()))
l=min(a.count(1),a.count(2),a.count(3))
for i in range(l):
print(a.index(1)+1,a.index(2)+1,a.index(3)+1)
a[a.index(1)]=0
a[a.index(2)]=0
a[a.index(3)]=0
if l==0:
print(0)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
To make a paper airplane, one has to use a rectangular piece of paper. From a sheet of standard size you can make $s$ airplanes.
A group of $k$ people decided to make $n$ airplanes each. They are going to buy several packs of paper, each of them containing $p$ sheets, and then distribute the sheets between the people. Each person should have enough sheets to make $n$ airplanes. How many packs should they buy?
|
```python
k,n,s,p=map(int,input().split())
a=(n//s)+1
b=k/p
ans=(a*b)+1
print(int(ans))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Mashmokh works in a factory. At the end of each day he must turn off all of the lights.
The lights on the factory are indexed from 1 to *n*. There are *n* buttons in Mashmokh's room indexed from 1 to *n* as well. If Mashmokh pushes button with index *i*, then each light with index not less than *i* that is still turned on turns off.
Mashmokh is not very clever. So instead of pushing the first button he pushes some of the buttons randomly each night. He pushed *m* distinct buttons *b*1,<=*b*2,<=...,<=*b**m* (the buttons were pushed consecutively in the given order) this night. Now he wants to know for each light the index of the button that turned this light off. Please note that the index of button *b**i* is actually *b**i*, not *i*.
Please, help Mashmokh, print these indices.
|
```python
n,m = map(int,input().split())
l = list(map(int,input().split()))
d,c = {},n+1
for i in range(m):
if l[i]<c:
for j in range(l[i],c):
d[j]=l[i]
c=l[i]
for i in range(n):
print(d[i+1],end=' ')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word *s*. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if Vasya types the word "ahhellllloou", it will be considered that he said hello, and if he types "hlelo", it will be considered that Vasya got misunderstood and he didn't manage to say hello. Determine whether Vasya managed to say hello by the given word *s*.
|
```python
ans = ''
S = input()
for i in range(len(S)):
if S[i] == 'h' or S[i]=="e" or S[i]=="l" or S[i] =="o":
ans+=S[i]
h = ans.index("h")
e = ans.index("e")
l = ans.index("l")
o = ans.index("o")
if ans == 'helo':
print("NO")
else:
if h<e<l<o:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpredictable place.
But to their great regret, the leave turned to be very short, so it will be enough to visit one of the three above named places. That's why Yakko, as the cleverest, came up with a truly genius idea: let each of the three roll an ordinary six-sided die, and the one with the highest amount of points will be the winner, and will take the other two to the place of his/her dreams.
Yakko thrown a die and got Y points, Wakko — W points. It was Dot's turn. But she didn't hurry. Dot wanted to know for sure what were her chances to visit Transylvania.
It is known that Yakko and Wakko are true gentlemen, that's why if they have the same amount of points with Dot, they will let Dot win.
|
```python
x=input('')
x=x.split()
s=x[0]
f=x[1]
v=[]
v.append(int(s))
v.append(int(f))
l=max(v)
c=0
for i in range (7):
if i>=(l):
c=c+1
import fractions
def simplify_fraction(num1, num2):
result = fractions(num1, num2)
return result
result = simplify_fraction(c,6)
print(result)
```
|
|
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
n=input()
f=0
for i in range(n):
print(i)
print(f)
if i == 'h' and f==0 :
f=1
elif i=='e' and f==1 :
f=2
elif i=='l' and f==2 :
f=3
elif i=='l' and f==3 :
f=4
elif i=='o' and f==4 :
f=5
if f==5 :
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.
This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.
Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.
Substring is a continuous subsequence of a string.
|
```python
s1=input() ; s2=input()
ans=0
for i in range(len(s1)):
if s1[i:i+len(s2)]==s2:ans+=1
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
On the planet Mars a year lasts exactly *n* days (there are no leap years on Mars). But Martians have the same weeks as earthlings — 5 work days and then 2 days off. Your task is to determine the minimum possible and the maximum possible number of days off per year on Mars.
|
```python
n=int(input())
1<=n<=1000000
if n==1:
print('0 1')
elif 2<=n<7:
print('0 2')
else:
i=n//7
j=n%7
if j>5:
print('%d %d'%(i*2+1,i*2+1))
else:
print('%d %d'%(i*2,i*2))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.
Given a sequence *a* consisting of *n* integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it *a**k*) and delete it, at that all elements equal to *a**k*<=+<=1 and *a**k*<=-<=1 also must be deleted from the sequence. That step brings *a**k* points to the player.
Alex is a perfectionist, so he decided to get as many points as possible. Help him.
|
```python
dp = [0 for x in range(100001)]
c = [0 for x in range(100001)]
n = int(input())
if n == 1:
print(int(input()))
tmp = [int(x) for x in input().split()]
for i in tmp:
c[i] += 1
dp[1] = c[1]
for i in range(2, n + 1):
dp[i] = max(dp[i - 1], dp[i - 2] + c[i] * i)
print(dp[n])
```
|
|
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
n = int(input())
cnt = 0
ans = set()
for c in range(1, n + 1):
for a in range(1, c + 1):
b = c ^ a
if c >= a and c >= b and not (c >= a + b or a >= b + c or b >= a + c or b == 0):
cnt += 1
print(cnt // 2)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a permutation *p* of length *n*. Also you are given *m* foe pairs (*a**i*,<=*b**i*) (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*,<=*a**i*<=≠<=*b**i*).
Your task is to count the number of different intervals (*x*,<=*y*) (1<=≤<=*x*<=≤<=*y*<=≤<=*n*) that do not contain any foe pairs. So you shouldn't count intervals (*x*,<=*y*) that contain at least one foe pair in it (the positions and order of the values from the foe pair are not important).
Consider some example: *p*<==<=[1,<=3,<=2,<=4] and foe pairs are {(3,<=2),<=(4,<=2)}. The interval (1,<=3) is incorrect because it contains a foe pair (3,<=2). The interval (1,<=4) is also incorrect because it contains two foe pairs (3,<=2) and (4,<=2). But the interval (1,<=2) is correct because it doesn't contain any foe pair.
|
```python
I = lambda:[*map(int, input().split())]
def solve():
n, m = I()
a = [0] + I()
pos = [0] * (n + 1)
f = [0] * (n + 1)
for i, v in enumerate(a):
pos[v] = i
for i in range(m):
x, y = I()
x, y = pos[x], pos[y]
if x > y:
x, y = y, x
f[y] = max(f[y], x)
res, last = 0, 0
for i in range(1, n + 1):
last = max(f[i], last)
res += i - last
print(res)
t = 1
while t > 0:
t -= 1
solve()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One day Vasya got hold of information on the Martian dollar course in bourles for the next *n* days. The buying prices and the selling prices for one dollar on day *i* are the same and are equal to *a**i*. Vasya has *b* bourles. He can buy a certain number of dollars and then sell it no more than once in *n* days. According to Martian laws, one can buy only an integer number of dollars. Which maximal sum of money in bourles can Vasya get by the end of day *n*?
|
```python
from collections import deque, Counter, OrderedDict
from heapq import nsmallest, nlargest
def binNumber(n,size):
return bin(n)[2:].zfill(size)
def gcd(a,b):
if a == 0:
return b
return gcd(b%a,a)
def iar():
return list(map(int,input().split()))
def ini():
return int(input())
def isp():
return map(int,input().split())
def sti():
return str(input())
def rln(a):
return range(len(a))
# ========= /\ /| |====/|
# | / \ | | / |
# | /____\ | | / |
# | / \ | | / |
# ========= / \ ===== |/====|
# code
if __name__ == "__main__":
n,b = isp()
a = iar()
ma = b
for i in range(n-1):
for j in range(i+1,n):
buy = b//a[i]
rem = b%a[i]
sel = buy*a[j] + rem
ma = max(ma,sel)
print(ma)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are *n* drinks in his fridge, the volume fraction of orange juice in the *i*-th drink equals *p**i* percent.
One day Vasya decided to make himself an orange cocktail. He took equal proportions of each of the *n* drinks and mixed them. Then he wondered, how much orange juice the cocktail has.
Find the volume fraction of orange juice in the final drink.
|
```python
d = int(input())
num = list(map(int, input().split()))
total_s = sum(num)
result = 1 // denominator * total_s
print(result)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
New Year is coming in Line World! In this world, there are *n* cells numbered by integers from 1 to *n*, as a 1<=×<=*n* board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.
So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of *n*<=-<=1 positive integers *a*1,<=*a*2,<=...,<=*a**n*<=-<=1. For every integer *i* where 1<=≤<=*i*<=≤<=*n*<=-<=1 the condition 1<=≤<=*a**i*<=≤<=*n*<=-<=*i* holds. Next, he made *n*<=-<=1 portals, numbered by integers from 1 to *n*<=-<=1. The *i*-th (1<=≤<=*i*<=≤<=*n*<=-<=1) portal connects cell *i* and cell (*i*<=+<=*a**i*), and one can travel from cell *i* to cell (*i*<=+<=*a**i*) using the *i*-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (*i*<=+<=*a**i*) to cell *i* using the *i*-th portal. It is easy to see that because of condition 1<=≤<=*a**i*<=≤<=*n*<=-<=*i* one can't leave the Line World using portals.
Currently, I am standing at cell 1, and I want to go to cell *t*. However, I don't know whether it is possible to go there. Please determine whether I can go to cell *t* by only using the construted transportation system.
|
```python
n,t = map(int,input().split())
l = list(map(int,input().split()))
i = 0
while i <= n-1:
if i == t:
print("YES")
break
elif i > t:
print("NO")
break
i = i + l[i-1]
else:
if i == t:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Amr has got a large array of size *n*. Amr doesn't like large arrays so he intends to make it smaller.
Amr doesn't care about anything in the array except the beauty of it. The beauty of the array is defined to be the maximum number of times that some number occurs in this array. He wants to choose the smallest subsegment of this array such that the beauty of it will be the same as the original array.
Help Amr by choosing the smallest subsegment possible.
|
```python
n=int(input())
l=list(map(int,input().split()))
li=list(set(l))
if len(l)==len(li):
print("1 1")
else:
max=0
index1=n+1
index2=2*(n+1)+1
for i in li:
if l.count(i)>max:
max=l.count(i)
index1=l.index(i)
index2=n-l[::-1].index(i)-1
if l.count(i)==max:
if l[::-1].index(i)-l.index(i)<index2-index1:
index1=l.index(i)
index2=n-l[::-1].index(i)-1
print(index1+1,index2+1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Parsley, sage, rosemary and thyme.
Remember me to one who lives there.
He once was the true love of mine.
Willem is taking the girl to the highest building in island No.28, however, neither of them knows how to get there.
Willem asks his friend, Grick for directions, Grick helped them, and gave them a task.
Although the girl wants to help, Willem insists on doing it by himself.
Grick gave Willem a string of length *n*.
Willem needs to do *m* operations, each operation has four parameters *l*,<=*r*,<=*c*1,<=*c*2, which means that all symbols *c*1 in range [*l*,<=*r*] (from *l*-th to *r*-th, including *l* and *r*) are changed into *c*2. String is 1-indexed.
Grick wants to know the final string after all the *m* operations.
|
```python
n,m=map(int,input().split())
s=input()
for i in range(m):
l,r,c1,c2=input().split()
l=int(l)
r=int(r)
for j in range(l-1,r):
if s[j]==c1:
s=s[:j]+c2+s[j+1:]
print(s)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
While Mike was walking in the subway, all the stuff in his back-bag dropped on the ground. There were several fax messages among them. He concatenated these strings in some order and now he has string *s*.
He is not sure if this is his own back-bag or someone else's. He remembered that there were exactly *k* messages in his own bag, each was a palindrome string and all those strings had the same length.
He asked you to help him and tell him if he has worn his own back-bag. Check if the given string *s* is a concatenation of *k* palindromes of the same length.
|
```python
def pal(s):
for i in range(int(len(s)/2)):
if s[i]!=s[len(s)-1-i]:
return False
return True
flag=True
s=input()
n=int(input())
temp=int(len(s)/n)
for i in range(n):
# print(s[0+i*temp:(i+1)*temp])
if pal(s[0+i*temp:(i+1)*temp])==False:
flag=False
break
if flag:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands:
- Include a person to the chat ('Add' command). - Remove a person from the chat ('Remove' command). - Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command).
Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.
Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends *l* bytes to each participant of the chat, where *l* is the length of the message.
As Polycarp has no time, he is asking for your help in solving this problem.
|
```python
from sys import *
live = 0
l = 0
for line in stdin:
if line[0] == "+":
live += 1
elif line[0] == "-":
live -= 1
else :
idx = line.find(':')
line = line[idx+1:]
l = l + (len(line)-1)*live
print(l)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Indian summer is such a beautiful time of the year! A girl named Alyona is walking in the forest and picking a bouquet from fallen leaves. Alyona is very choosy — she doesn't take a leaf if it matches the color and the species of the tree of one of the leaves she already has. Find out how many leaves Alyona has picked.
|
```python
n = int(input())
listans = []
for i in range(n):
a, b = map(str, input().split())
listans.append([a, b])
counter = 0
for i in range(len(listans) - 1):
if listans[i] != listans[i + 1]:
counter += 1
else:
counter = 1
print(counter)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number *n*. How many times can Gerald put a spell on it until the number becomes one-digit?
|
```python
def calculate(m):
n1 = 0
A_list = list(map(int, str(m)))
for i in range(0, length(str(m))):
n1 = n1 + A_list[i]
return n1
def result(m):
n2 = m
for i in range(0, length(str(m))):
count = 0
if length(str(m)) > 1:
n2 = calculate(n2)
count = count + i + 1
if length(str(n2)) > 1:
calculate(n2)
else:
print(count)
break
else:
print(0)
digit = int(input())
result(digit)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One day, Twilight Sparkle is interested in how to sort a sequence of integers *a*1,<=*a*2,<=...,<=*a**n* in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:
Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?
|
```python
n = int(input())
A = [int(a) for a in input().split()]
flag = True
m = 0
last = A[0]
break_seen = False
for i in range(1, n):
if last > A[i]:
if break_seen:
flag = False
break
else:
break_seen = True
m = n - i
last = A[i]
if break_seen:
if A[0] < A[n - 1]:
flag = False
if flag:
print(m)
else:
print(-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house.
Karlsson's gaze immediately fell on *n* wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find.
And now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open.
Karlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds *t*, in which he is able to bring all the cupboard doors in the required position.
Your task is to write a program that will determine the required number of seconds *t*.
|
```python
n=int(input())
l=[]
r=[]
for i in range(n):
lst=list(map(int,input().split()))
l.append(lst[0])
r.append(lst[1])
t=0
if 0 in l and 1 in l:
if l.count(1)>=l.count(0):
for i in l:
if i==0:
t=t+1
elif l.count(0)>l.count(1) :
for i in l:
if i==1:
t=t+1
if 0 in r and 1 in r:
if r.count(1)>=r.count(0):
for i in r:
if i==0:
t=t+1
elif r.count(0)>r.count(1):
for i in r:
if i==1:
t=t+1
print(t)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpredictable place.
But to their great regret, the leave turned to be very short, so it will be enough to visit one of the three above named places. That's why Yakko, as the cleverest, came up with a truly genius idea: let each of the three roll an ordinary six-sided die, and the one with the highest amount of points will be the winner, and will take the other two to the place of his/her dreams.
Yakko thrown a die and got Y points, Wakko — W points. It was Dot's turn. But she didn't hurry. Dot wanted to know for sure what were her chances to visit Transylvania.
It is known that Yakko and Wakko are true gentlemen, that's why if they have the same amount of points with Dot, they will let Dot win.
|
```python
import math
y , w = map(int , input().split())
h = 6 - max(y,w) + 1
p = 6 // h if 6 % h == 0 else 6
p = max(math.gcd(p,h),1)
print(str(p) + '/'+ str(h//p))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he wants to give Dumbledore exactly *x* drops of the potion he made.
Value of *x* is calculated as maximum of *p*·*a**i*<=+<=*q*·*a**j*<=+<=*r*·*a**k* for given *p*,<=*q*,<=*r* and array *a*1,<=*a*2,<=... *a**n* such that 1<=≤<=*i*<=≤<=*j*<=≤<=*k*<=≤<=*n*. Help Snape find the value of *x*. Do note that the value of *x* may be negative.
|
```python
# Define a lambda function to take input as integers from standard input
cin = lambda: map(int, input().split())
# Read in the input values: n, p, q, r and the array A
n, p, q, r = cin()
A = list(cin())
# Initialize the variables tp, tq, and tr to negative infinity
tp, tq, tr = -float("inf"), -float("inf"), -float("inf")
# Loop through the elements in the array A
for a in A:
# Compute the maximum value of p*a seen so far and store it in tp
tp = max(tp, p * a)
# Compute the maximum value of tp+q*a seen so far and store it in tq
tq = max(tq, tp + q * a)
# Compute the maximum value of tq+r*a seen so far and store it in tr
tr = max(tr, tq + r * a)
# Print the value of tr, which represents the maximum value of (p * A[i] + q * A[j] + r * A[k])
print(tr)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Kuriyama Mirai has killed many monsters and got many (namely *n*) stones. She numbers the stones from 1 to *n*. The cost of the *i*-th stone is *v**i*. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions:
1. She will tell you two numbers, *l* and *r* (1<=≤<=*l*<=≤<=*r*<=≤<=*n*), and you should tell her . 1. Let *u**i* be the cost of the *i*-th cheapest stone (the cost that will be on the *i*-th place if we arrange all the stone costs in non-decreasing order). This time she will tell you two numbers, *l* and *r* (1<=≤<=*l*<=≤<=*r*<=≤<=*n*), and you should tell her .
For every question you should give the correct answer, or Kuriyama Mirai will say "fuyukai desu" and then become unhappy.
|
```python
n = int(input())
arr = list(map(int, input().split()))
srr = arr[:]
srr.sort()
for i in range(1, n) :
arr[i] += arr[i-1]
srr[i] += srr[i-1]
for i in range(int(input())) :
x, l, r = map(int, input().split())
if x == 1:
print(arr[r-1]-(arr[l-2] if l > 1 else 0))
else :
print(srr[r-1]-(srr[l-2] if l > 1 else 0))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Sereja has an array *a*, consisting of *n* integers *a*1, *a*2, ..., *a**n*. The boy cannot sit and do nothing, he decided to study an array. Sereja took a piece of paper and wrote out *m* integers *l*1,<=*l*2,<=...,<=*l**m* (1<=≤<=*l**i*<=≤<=*n*). For each number *l**i* he wants to know how many distinct numbers are staying on the positions *l**i*, *l**i*<=+<=1, ..., *n*. Formally, he want to find the number of distinct numbers among *a**l**i*,<=*a**l**i*<=+<=1,<=...,<=*a**n*.?
Sereja wrote out the necessary array elements but the array was so large and the boy was so pressed for time. Help him, find the answer for the described question for each *l**i*.
|
```python
n,m=map(int,input().split())
l=list(map(int,input().split()))
for i in range(m):
k=int(input())
t=set(l[k-1:])
print(len(t))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The hero of our story, Valera, and his best friend Arcady are still in school, and therefore they spend all the free time playing turn-based strategy "GAGA: Go And Go Again". The gameplay is as follows.
There are two armies on the playing field each of which consists of *n* men (*n* is always even). The current player specifies for each of her soldiers an enemy's soldier he will shoot (a target) and then all the player's soldiers shot simultaneously. This is a game world, and so each soldier shoots perfectly, that is he absolutely always hits the specified target. If an enemy soldier is hit, he will surely die. It may happen that several soldiers had been indicated the same target. Killed soldiers do not participate in the game anymore.
The game "GAGA" consists of three steps: first Valera makes a move, then Arcady, then Valera again and the game ends.
You are asked to calculate the maximum total number of soldiers that may be killed during the game.
|
```python
n=int(input())
print(int(n*1.5))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A permutation of size *n* is an array of size *n* such that each integer from 1 to *n* occurs exactly once in this array. An inversion in a permutation *p* is a pair of indices (*i*,<=*j*) such that *i*<=><=*j* and *a**i*<=<<=*a**j*. For example, a permutation [4,<=1,<=3,<=2] contains 4 inversions: (2,<=1), (3,<=1), (4,<=1), (4,<=3).
You are given a permutation *a* of size *n* and *m* queries to it. Each query is represented by two indices *l* and *r* denoting that you have to reverse the segment [*l*,<=*r*] of the permutation. For example, if *a*<==<=[1,<=2,<=3,<=4] and a query *l*<==<=2, *r*<==<=4 is applied, then the resulting permutation is [1,<=4,<=3,<=2].
After each query you have to determine whether the number of inversions is odd or even.
|
```python
n = int(input())
*a, = map(int, input().split())
p = 0
for i in range(n):
for j in range(i + 1, n):
if a[i] > a[j]:
p ^= 1
m = int(input())
for i in range(m):
l, r = map(int, input().split())
k = r - l + 1
k = k * (k - 1) // 2
if k & 1:
p ^= 1
print('eovdedn'[p :: 2])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya has recently learned at school what a number's divisor is and decided to determine a string's divisor. Here is what he came up with.
String *a* is the divisor of string *b* if and only if there exists a positive integer *x* such that if we write out string *a* consecutively *x* times, we get string *b*. For example, string "abab" has two divisors — "ab" and "abab".
Now Vasya wants to write a program that calculates the number of common divisors of two strings. Please help him.
|
```python
def prefix(p,ss,l):
s=p+'*'+ss
n=len(s)
arr=[0]*(n+1)
i=0
j=1
cou=0
while j<n:
if(s[i]==s[j]):
arr[j]=i+1
i+=1
j+=1
else:
if(i==0):
arr[j]=0
j+=1
else:
i=arr[i-1]
while s[i]!=s[j] and i>0:
i=arr[i-1]
if(s[j]==s[i]):
arr[j]=i+1
i+=1
j+=1
else:
arr[j]=arr[i]
j+=1
for i in range(l-1,len(ss),l):
if(arr[i+len(p)+1]==l):
cou+=1
#print(arr,l,s,cou)
return cou
from math import sqrt
s1=input()
s2=input()
l1=len(s1)
l2=len(s2)
if(l1>l2):
l1,l2=l2,l1
s1,s2=s2,s1
d=[]
for i in range(1,int(sqrt(l1))+1):
if(l1%i==0):
d.append(i)
if(i!=l1//i):
d.append(l1//i)
d.sort()
s=""
cou=0
#print(d)
for i in d:
le=len(s)
for j in range(le,i,1):
s+=s1[j]
n1=prefix(s,s1,i)
n2=prefix(s,s2,i)
if(n1==l1//i and n2==l2//i and l1%i==0 and l2%i==0):
cou+=1
print(cou)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Recently, you bought a brand new smart lamp with programming features. At first, you set up a schedule to the lamp. Every day it will turn power on at moment $0$ and turn power off at moment $M$. Moreover, the lamp allows you to set a program of switching its state (states are "lights on" and "lights off"). Unfortunately, some program is already installed into the lamp.
The lamp allows only good programs. Good program can be represented as a non-empty array $a$, where $0 < a_1 < a_2 < \dots < a_{|a|} < M$. All $a_i$ must be integers. Of course, preinstalled program is a good program.
The lamp follows program $a$ in next manner: at moment $0$ turns power and light on. Then at moment $a_i$ the lamp flips its state to opposite (if it was lit, it turns off, and vice versa). The state of the lamp flips instantly: for example, if you turn the light off at moment $1$ and then do nothing, the total time when the lamp is lit will be $1$. Finally, at moment $M$ the lamp is turning its power off regardless of its state.
Since you are not among those people who read instructions, and you don't understand the language it's written in, you realize (after some testing) the only possible way to alter the preinstalled program. You can insert at most one element into the program $a$, so it still should be a good program after alteration. Insertion can be done between any pair of consecutive elements of $a$, or even at the begining or at the end of $a$.
Find such a way to alter the program that the total time when the lamp is lit is maximum possible. Maybe you should leave program untouched. If the lamp is lit from $x$ till moment $y$, then its lit for $y - x$ units of time. Segments of time when the lamp is lit are summed up.
|
```python
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 16 16:27:20 2022
@author: lenovo
"""
n,M=map(int, input().split())
array=list(map(int, input().split()))
gap=[array[0]]
for i in range(n-1):
gap.append(array[i+1]-array[i])
gap.append(M-array[-1])
gap_1=gap[::2]
gap_2=gap[1::2]
summing_1=[gap_1[0]]
for i in range(len(gap_1)-1):
summing_1.append(summing_1[i]+gap_1[i+1])
summing_2=[gap_2[0]]
for i in range(len(gap_2)-1):
summing_2.append(summing_2[i]+gap_2[i+1])
t=max(summing_1[-1],summing_1[0]+summing_2[-1]-1)
for j in range(1,len(gap_2)):
t=max(t, summing_1[j]+summing_2[-1]-summing_2[j-1]-1)
print(t)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya has become interested in wrestling. In wrestling wrestlers use techniques for which they are awarded points by judges. The wrestler who gets the most points wins.
When the numbers of points of both wrestlers are equal, the wrestler whose sequence of points is lexicographically greater, wins.
If the sequences of the awarded points coincide, the wrestler who performed the last technique wins. Your task is to determine which wrestler won.
|
```python
a=int(input())
C=[]
D=[]
c=0
d=0
for i in range(a):
b=int(input())
if b>0:
c+=b
C+=[str(b)]
if b<0:
d+=-b
D+=[str(-b)]
if c>d:
print('first')
elif c<d:
print('second')
elif c==d:
if C>D:
print('first')
if C<D:
print('second')
if C==D:
if b>0:
print('first')
else:
print('second')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Recently Adaltik discovered japanese crosswords. Japanese crossword is a picture, represented as a table sized *a*<=×<=*b* squares, and each square is colored white or black. There are integers to the left of the rows and to the top of the columns, encrypting the corresponding row or column. The number of integers represents how many groups of black squares there are in corresponding row or column, and the integers themselves represents the number of consecutive black squares in corresponding group (you can find more detailed explanation in Wikipedia [https://en.wikipedia.org/wiki/Japanese_crossword](https://en.wikipedia.org/wiki/Japanese_crossword)).
Adaltik decided that the general case of japanese crossword is too complicated and drew a row consisting of *n* squares (e.g. japanese crossword sized 1<=×<=*n*), which he wants to encrypt in the same way as in japanese crossword.
Help Adaltik find the numbers encrypting the row he drew.
|
```python
n=int(input())
s=input()
l=[]
count = 0
for i in range(n):
if s[i] == 'B':
count+=1
if i == n-1: l.append(count)
else:
if count>0 : l.append(count)
count = 0
print(len(l))
print(*l)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Every year, hundreds of people come to summer camps, they learn new algorithms and solve hard problems.
This is your first year at summer camp, and you are asked to solve the following problem. All integers starting with 1 are written in one line. The prefix of these line is "123456789101112131415...". Your task is to print the *n*-th digit of this string (digits are numbered starting with 1.
|
```python
a = int(input())
s = ""
i = 1
while len(s) < a:
s+=str(i)
i+=1
print(s[a-1])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Someday, Drazil wanted to go on date with Varda. Drazil and Varda live on Cartesian plane. Drazil's home is located in point (0,<=0) and Varda's home is located in point (*a*,<=*b*). In each step, he can move in a unit distance in horizontal or vertical direction. In other words, from position (*x*,<=*y*) he can go to positions (*x*<=+<=1,<=*y*), (*x*<=-<=1,<=*y*), (*x*,<=*y*<=+<=1) or (*x*,<=*y*<=-<=1).
Unfortunately, Drazil doesn't have sense of direction. So he randomly chooses the direction he will go to in each step. He may accidentally return back to his house during his travel. Drazil may even not notice that he has arrived to (*a*,<=*b*) and continue travelling.
Luckily, Drazil arrived to the position (*a*,<=*b*) successfully. Drazil said to Varda: "It took me exactly *s* steps to travel from my house to yours". But Varda is confused about his words, she is not sure that it is possible to get from (0,<=0) to (*a*,<=*b*) in exactly *s* steps. Can you find out if it is possible for Varda?
|
```python
a, b, s = (map(int, input().split()))
if a + b < s and abs(a + b - s) % 2 != 0:
print("NO")
else:
print("YES")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
For a given positive integer *n* denote its *k*-rounding as the minimum positive integer *x*, such that *x* ends with *k* or more zeros in base 10 and is divisible by *n*.
For example, 4-rounding of 375 is 375·80<==<=30000. 30000 is the minimum integer such that it ends with 4 or more zeros and is divisible by 375.
Write a program that will perform the *k*-rounding of *n*.
|
```python
l = input().split()
n = int(l[0])
k = int(l[1])
def zero_am(num):
res = 0
while num % 10 == 0:
num /= 10
res += 1
return res
s = [1, 2, 4, 5, 6, 8]
l = {}
m = 0
for i in reversed(s):
l.update({zero_am(n * i): n * i})
if zero_am(n * i) > m:
m = zero_am(n * i)
ans = l[m]
for i in range(m, k):
ans *= 10
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
DZY loves chessboard, and he enjoys playing with it.
He has a chessboard of *n* rows and *m* columns. Some cells of the chessboard are bad, others are good. For every good cell, DZY wants to put a chessman on it. Each chessman is either white or black. After putting all chessmen, DZY wants that no two chessmen with the same color are on two adjacent cells. Two cells are adjacent if and only if they share a common edge.
You task is to find any suitable placement of chessmen on the given chessboard.
|
```python
n, m = map(int, input().split())
M = []
for _ in range(n):
row = input()
M.append(list(row))
for i in range(n):
for j in range(m):
if M[i][j] == '-':
continue
else:
if i == 0:
if j == 0:
M[i][j] = 'B'
else:
if M[i][j - 1] == 'B':
M[i][j] = 'W'
else:
M[i][j] = 'B'
else:
if j == 0:
if M[i - 1][j] == 'B':
M[i][j] = 'W'
else:
M[i][j] = 'B'
else:
if M[i - 1][j] == 'B' or M[i][j - 1] == 'B':
M[i][j] = 'W'
elif M[i - 1][j] == 'W' or M[i][j - 1] == 'W':
M[i][j] = 'B'
else:
M[i][j] = 'B'
for i in range(n):
for j in range(m):
print(M[i][j], end='')
print()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string *s* consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string *s* to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".
If string *s* has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.
Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
|
```python
def solve():
n=int(input())
st=input()
lst=list(st)
s=set(lst)
n-=len(s)
# print(n-len(s))
if n<27:
print(n)
else:
print(-1)
# t=int(input())
# for i in range(t):
solve()
```
|
|
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
inpt1 = input().strip()
input1 = list(inpt1)
starts_with = ord('a')
ends_with = ord('z')
sum = 0
prev= "a"
for char in input1:
curr = ord(char)
prev_ord = ord(prev)
if curr >= prev_ord:
sum += min(prev_ord-starts_with+ends_with-curr + 1, curr - prev_ord)
else:
sum += min(prev_ord-curr, ends_with-prev_ord + curr-starts_with+1)
prev = char
print(sum)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You have decided to watch the best moments of some movie. There are two buttons on your player:
1. Watch the current minute of the movie. By pressing this button, you watch the current minute of the movie and the player automatically proceeds to the next minute of the movie. 1. Skip exactly *x* minutes of the movie (*x* is some fixed positive integer). If the player is now at the *t*-th minute of the movie, then as a result of pressing this button, it proceeds to the minute (*t*<=+<=*x*).
Initially the movie is turned on in the player on the first minute, and you want to watch exactly *n* best moments of the movie, the *i*-th best moment starts at the *l**i*-th minute and ends at the *r**i*-th minute (more formally, the *i*-th best moment consists of minutes: *l**i*,<=*l**i*<=+<=1,<=...,<=*r**i*).
Determine, what is the minimum number of minutes of the movie you have to watch if you want to watch all the best moments?
|
```python
#include <bits/stdc++.h>
#define nline "\n"
#define fastio() ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
#define MOD 1000000007
#define loop(i,a,b) for(int i=(a);i<(b);i++)
using namespace std;
void file_I_O() {
fastio();
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
int main()
{
file_I_O();
int n , x;
cin >> n >> x ;
int timer = 1, wt = 0 ;
int counter = 0;
while (n--) {
int l , r ;
cin >> l >> r;
timer += x * ((l - timer) / x);
wt += r - timer + 1;
timer = r + 1;
}
cout << wt;
}
```
|
|
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())
a=list(map(int,input().split()))
l=[]
for i in range (m):
l.append(min(a))
a.remove(min(a))
print(abs(sum(l)))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Recently Polycarp started to develop a text editor that works only with correct bracket sequences (abbreviated as CBS).
Note that a bracket sequence is correct if it is possible to get a correct mathematical expression by adding "+"-s and "1"-s to it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not. Each bracket in CBS has a pair. For example, in "(()(()))":
- 1st bracket is paired with 8th, - 2d bracket is paired with 3d, - 3d bracket is paired with 2d, - 4th bracket is paired with 7th, - 5th bracket is paired with 6th, - 6th bracket is paired with 5th, - 7th bracket is paired with 4th, - 8th bracket is paired with 1st.
Polycarp's editor currently supports only three operations during the use of CBS. The cursor in the editor takes the whole position of one of the brackets (not the position between the brackets!). There are three operations being supported:
- «L» — move the cursor one position to the left, - «R» — move the cursor one position to the right, - «D» — delete the bracket in which the cursor is located, delete the bracket it's paired to and all brackets between them (that is, delete a substring between the bracket in which the cursor is located and the one it's paired to).
After the operation "D" the cursor moves to the nearest bracket to the right (of course, among the non-deleted). If there is no such bracket (that is, the suffix of the CBS was deleted), then the cursor moves to the nearest bracket to the left (of course, among the non-deleted).
There are pictures illustrated several usages of operation "D" below.
All incorrect operations (shift cursor over the end of CBS, delete the whole CBS, etc.) are not supported by Polycarp's editor.
Polycarp is very proud of his development, can you implement the functionality of his editor?
|
```python
def f1(m2, s):
m2 = {}
st = []
for i in range(len(s)):
if s[i] == '(':
st.append(i)
else:
m2[st[-1]] = i
m2[i] = st[-1]
st.pop()
return m2
n, m, p = map(int, input().split())
s = input()
a = input()
m = {}
m = f1(m, s)
j = p - 1
mi = 1000000007
ma = -mi
was = 0
for i in a:
d = j
if i == 'L':
j -= 1
elif i == 'R':
j += 1
else:
k = ''
iznwas = was
d2, m2 = min(d, m[d]), max(d, m[d])
for re in range(d2):
k += s[re]
for re in range(m2 + 1, len(s)):
k += s[re]
s = k
m = f1(m, s)
if j >= len(s) - 1:
j = len(s) - 2
d += 1
print(s)
```
|
|
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
s1='abcdefghijklmnopqrstuvwxyz'
s=input()
j=0
k=0
for i in range(len(s)):
j1=s1.index(s[i])
a=abs(j-j1)
if a <=13:
k+=a
j=j1
else:
k+=26-a
j=j1
print(k)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
All cities of Lineland are located on the *Ox* coordinate axis. Thus, each city is associated with its position *x**i* — a coordinate on the *Ox* axis. No two cities are located at a single point.
Lineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another city (because if they live in the same city, then it is easier to drop in).
Strange but true, the cost of sending the letter is exactly equal to the distance between the sender's city and the recipient's city.
For each city calculate two values *min**i* and *max**i*, where *min**i* is the minimum cost of sending a letter from the *i*-th city to some other city, and *max**i* is the the maximum cost of sending a letter from the *i*-th city to some other city
|
```python
n = int(input())
cities = list(map(int,input().split(' ')))
for i in range(len(cities)):
if i == 0:
cost_min = abs(cities[i] - cities[1])
cost_max = abs(cities[i] - cities[-1])
elif i == len(cities)-1:
cost_min = abs(cities[i] - cities[-2])
cost_max = abs(cities[i] - cities[0])
else:
cost_min = min(abs(cities[i] - cities[i-1]), abs(cities[i] - cities[i+1]))
cost_max = max(abs(cities[i] - cities[0]), abs(cities[i] - cities[-1]))
print(cost_min, cost_max)
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.