source
stringclasses 3
values | instruction
stringlengths 23
3.97k
| input
stringclasses 1
value | output
stringlengths 1
3.75k
|
---|---|---|---|
MatrixStudio/Codeforces-Python-Submissions
|
The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.
There are *n* stations in the subway. It was built according to the Bertown Transport Law:
1. For each station *i* there exists exactly one train that goes from this station. Its destination station is *p**i*, possibly *p**i*<==<=*i*; 1. For each station *i* there exists exactly one station *j* such that *p**j*<==<=*i*.
The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (*x*,<=*y*) such that person can start at station *x* and, after taking some subway trains (possibly zero), arrive at station *y* (1<=≤<=*x*,<=*y*<=≤<=*n*).
The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of *p**i* for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.
The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get!
|
```python
from collections import defaultdict as dd
g=dd(list)
def addE(u,v):
g[u].append(v)
g[v].append(u)
n=int(input())
l=[int(x) for x in input().split()]
for i in range(n):
addE(i+1,l[i])
visited=[False]*(n+1)
def dfs(v,count):
visited[v]=True
for ch in g[v]:
if visited[ch]:
continue
count+=1
count=dfs(ch,count)
return count
ans=[]
for i in range(1,n+1):
if not visited[i]:
ans.append(dfs(i,1))
ans=sorted(ans,reverse=True)
ans2=ans[0]+ans[1]
ans2*=ans2
ans2+=sum(ans[2:])
print(ans2)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
DZY loves chessboard, and he enjoys playing with it.
He has a chessboard of *n* rows and *m* columns. Some cells of the chessboard are bad, others are good. For every good cell, DZY wants to put a chessman on it. Each chessman is either white or black. After putting all chessmen, DZY wants that no two chessmen with the same color are on two adjacent cells. Two cells are adjacent if and only if they share a common edge.
You task is to find any suitable placement of chessmen on the given chessboard.
|
```python
def is_valid(board):
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] not in ['B', 'W', '-']:
return False
if board[i][j] == '-':
continue
if i-1 >= 0 and board[i-1][j] == board[i][j]:
return False
if i+1 < len(board) and board[i+1][j] == board[i][j]:
return False
if j-1 >= 0 and board[i][j-1] == board[i][j]:
return False
if j+1 < len(board[i]) and board[i][j+1] == board[i][j]:
return False
return True
def make_a_copy(board):
result = []
for i in board:
r = []
for j in i:
r.append(j)
result.append(r)
return result
def print_board(board):
for row in board:
result = ''
for element in row:
result += element
print(result)
def all_binary_combinations(k, arr, i, solution_space):
if i == k:
solution_space.append(arr.copy())
else:
arr[i] = False
all_binary_combinations(k, arr, i + 1, solution_space)
arr[i] = True
all_binary_combinations(k, arr, i + 1, solution_space)
def main():
size = input().split()
n = int(size[0])
m = int(size[1])
board = []
white_places = []
for i in range(n):
board.append(list(input().replace('.', 'B')))
for i in range(n):
for j in range(m):
if board[i][j] == 'B':
white_places.append((i, j))
solution_space = []
k = len(white_places)
arr = [None] * k
all_binary_combinations(k, arr, 0, solution_space)
solutions = []
for possible_solution in solution_space:
board_copy = board.copy()
for i, val in enumerate(possible_solution):
if val:
board_copy[white_places[i][0]][white_places[i][1]] = 'W'
if is_valid(board_copy):
print_board(board)
return
main()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vadim is really keen on travelling. Recently he heard about kayaking activity near his town and became very excited about it, so he joined a party of kayakers.
Now the party is ready to start its journey, but firstly they have to choose kayaks. There are 2·*n* people in the group (including Vadim), and they have exactly *n*<=-<=1 tandem kayaks (each of which, obviously, can carry two people) and 2 single kayaks. *i*-th person's weight is *w**i*, and weight is an important matter in kayaking — if the difference between the weights of two people that sit in the same tandem kayak is too large, then it can crash. And, of course, people want to distribute their seats in kayaks in order to minimize the chances that kayaks will crash.
Formally, the instability of a single kayak is always 0, and the instability of a tandem kayak is the absolute difference between weights of the people that are in this kayak. Instability of the whole journey is the total instability of all kayaks.
Help the party to determine minimum possible total instability!
|
```python
def work():
diffs = sorted([weight[i]-weight[i-1] for i in range(1, len(weight), 2)])
sep_diffs = sorted([weight[i]-weight[i-1] for i in range(2, len(weight), 2)])
diffs.pop()
print(min(sum(diffs), sum(sep_diffs)))
n = int(input())
weight = sorted([int(i) for i in input().strip().split()])
work()
# for i in range(10)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
As you very well know, this year's funkiest numbers are so called triangular numbers (that is, integers that are representable as , where *k* is some positive integer), and the coolest numbers are those that are representable as a sum of two triangular numbers.
A well-known hipster Andrew adores everything funky and cool but unfortunately, he isn't good at maths. Given number *n*, help him define whether this number can be represented by a sum of two triangular numbers (not necessarily different)!
|
```python
def triangular(num):
# Funcion para ver si es triangular o no el numero
n = 1
while num > 0:
num -= n
n += 1
return num == 0
def suma_triangulres(n):
for t1 in range(1, n + 1):
# Funcion para revisar que t1 sea triangular
if triangular(t1):
diff = n - t1
# Funcion para revisar si la diferencia tambien es triangular
if triangular(diff):
return "YES"
return "NO"
n = int(input())
result = suma_triangulres(n)
print(result)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There is a given string *S* consisting of *N* symbols. Your task is to find the number of ordered pairs of integers *i* and *j* such that
1. 1<=≤<=*i*,<=*j*<=≤<=*N*
2. *S*[*i*]<==<=*S*[*j*], that is the *i*-th symbol of string *S* is equal to the *j*-th.
|
```python
S=input()
d={}
cnt=0
for i in S:
d[i]=d.get(i,0)+1
for i in S:
cnt+=d.get(i,0)
print(cnt)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Recently Luba bought a very interesting book. She knows that it will take *t* seconds to read the book. Luba wants to finish reading as fast as she can.
But she has some work to do in each of *n* next days. The number of seconds that Luba has to spend working during *i*-th day is *a**i*. If some free time remains, she can spend it on reading.
Help Luba to determine the minimum number of day when she finishes reading.
It is guaranteed that the answer doesn't exceed *n*.
Remember that there are 86400 seconds in a day.
|
```python
n,t = map(int,input().split())
d = [*((86400-int(x)) for x in input().split())]
cnt = 0
i = 0
while cnt < t:
cnt += d[i]
i += 1
print(i)
```
|
|
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())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
i=1
s=0
for tot_num in B:
tot_num-=s
while i<=n:
if tot_num<=A[i-1]:
j=tot_num
break
else:
tot_num-=A[i-1]
s+=A[i-1]
i+=1
print(i,j)
#from collections import Counter
n,m=map(int,input().split())
A=list(map(int,input().split()))
for _ in range(m):
#C=[]
#j=0
l=int(input())
#print(len(Counter(A[l-1:])))
#for i in range(l-1,n):
# if A[i] not in C:
# C.append(A[i])
# j+=1
#print(len(set(A[l-1:])))
n,m=map(int,input().split())
A=list(map(int,input().split()))
B=[]
for _ in range(m):
B.append(int(input()))
#D=sorted(B,reverse=True)
d=[0]*m
C=[]
j=0
i=n-1
#for l in D:
for king in range(m): #l is B[-king-1]
while i>=B[-king-1]-1:
if A[i] not in C:
C.append(A[i])
j+=1
i-=1
d[-king-1]=j
for l in d:
print(l)"""
# Read input values
n, m = map(int, input().split())
array = list(map(int, input().split()))
queries = []
for _ in range(m):
queries.append(int(input()))
ans=[]
d=set()
for i in range(n):
d.add(array[-i-1])
ans.append(len(d))
for l in queries:
print(ans[-l])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A recently found Ancient Prophesy is believed to contain the exact Apocalypse date. The prophesy is a string that only consists of digits and characters "-".
We'll say that some date is mentioned in the Prophesy if there is a substring in the Prophesy that is the date's record in the format "dd-mm-yyyy". We'll say that the number of the date's occurrences is the number of such substrings in the Prophesy. For example, the Prophesy "0012-10-2012-10-2012" mentions date 12-10-2012 twice (first time as "0012-10-2012-10-2012", second time as "0012-10-2012-10-2012").
The date of the Apocalypse is such correct date that the number of times it is mentioned in the Prophesy is strictly larger than that of any other correct date.
A date is correct if the year lies in the range from 2013 to 2015, the month is from 1 to 12, and the number of the day is strictly more than a zero and doesn't exceed the number of days in the current month. Note that a date is written in the format "dd-mm-yyyy", that means that leading zeroes may be added to the numbers of the months or days if needed. In other words, date "1-1-2013" isn't recorded in the format "dd-mm-yyyy", and date "01-01-2013" is recorded in it.
Notice, that any year between 2013 and 2015 is not a leap year.
|
```python
p=input()
data={}
for i in range(len(p)-9):
if p[i+2] == p[i+5] and (p[i+6:i+10]).isdecimal():
print(p[i:i+10])
if p[i:i+10] in data:
data[p[i:i+10]]+=1
else:
data[p[i:i+10]]=1
max_item=None
maximum=0
for i in data.keys():
if data[i] > maximum:
maximum = data[i]
max_item=i
print(max_item)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.
There are *n* trees located along the road at points with coordinates *x*1,<=*x*2,<=...,<=*x**n*. Each tree has its height *h**i*. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [*x**i*<=-<=*h**i*,<=*x**i*] or [*x**i*;*x**i*<=+<=*h**i*]. The tree that is not cut down occupies a single point with coordinate *x**i*. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
|
```python
n=int(input())
s=[[int(x) for x in input().split( )] for i in range(n)]
count=2
if n == 1:
print('1')
if n!= 1:
for j in range(1,n-1):
if s[j][0]-s[j-1][0] > s[j][1]:
count+=1
elif s[j+1][0]-s[j][0] > s[j][1]:
count+=1
s[j][0]+=s[j][1]
print(count)
```
|
|
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
import math
import sys
import collections
n = int(input())
def solve():
s = input()
if len(s) < 10:
print(s)
return
res = ''
dig = str(len(s) - 2)
res += s[0] + dig + s[len(s) - 1]
print(res)
for _ in range(n):
solve()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Jzzhu has picked *n* apples from his big apple tree. All the apples are numbered from 1 to *n*. Now he wants to sell them to an apple store.
Jzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be greater than 1. Of course, each apple can be part of at most one group.
Jzzhu wonders how to get the maximum possible number of groups. Can you help him?
|
```python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from math import *
def prm(x):
s = int(sqrt(x+0.5))
for i in range(2, s+1):
if not (x%i): return False
return True
def ap(a):
while(len(a) >= 2):
print(a[-1], a[-2])
a.pop()
a.pop()
n, cnt, ans, vis, ansl, ansr = int(input()), 0, 0, [False]*100100, [], []
prime = filter(prm, range(3, n//2+1))
for x in prime:
tcnt, nlst = 0, []
for i in range(1, n//x+1):
if not vis[i*x]:
vis[i*x] = True
nlst.append(i)
tcnt += 1
ans += tcnt >> 1
cnt += tcnt & 1
if tcnt & 1 :
nlst = nlst[0:1] + nlst[2:]
ansr.append(x<<1)
ansl += list(map(lambda k : x*k, nlst))
for i in range(1, n+1):
if not vis[i] and not (i&1):
ansr.append(i)
cnt += 1
print(ans+(cnt>>1))
ap(ansl)
ap(ansr)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
$k$ people want to split $n$ candies between them. Each candy should be given to exactly one of them or be thrown away.
The people are numbered from $1$ to $k$, and Arkady is the first of them. To split the candies, Arkady will choose an integer $x$ and then give the first $x$ candies to himself, the next $x$ candies to the second person, the next $x$ candies to the third person and so on in a cycle. The leftover (the remainder that is not divisible by $x$) will be thrown away.
Arkady can't choose $x$ greater than $M$ as it is considered greedy. Also, he can't choose such a small $x$ that some person will receive candies more than $D$ times, as it is considered a slow splitting.
Please find what is the maximum number of candies Arkady can receive by choosing some valid $x$.
|
```python
s = list(map(int, input().split()))
n=int(s[0])
k=int(s[1])
m=int(s[2])
d=int(s[3])
ans=int(0)
for i in range(1,d+1):
if (n-1)/k < (i-1):
break
op=k*(i-1)+1
ans=max(ans,min(m,n/op)*i)
print(int(ans))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Polycarp has created his own training plan to prepare for the programming contests. He will train for $n$ days, all days are numbered from $1$ to $n$, beginning from the first.
On the $i$-th day Polycarp will necessarily solve $a_i$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.
Determine the index of day when Polycarp will celebrate the equator.
|
```python
days = int(input())
problems = list(map(int, input().split()))
summa = sum(problems)
if summa % 2 == 0:
half_sum = summa // 2
else:
half_sum = summa // 2 + 1
problems_sum = 0
i = 0
while problems_sum < half_sum:
problems_sum += problems[i]
i += 1
print(i)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes.
You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consists of several words. For each language, all words are distinct, i.e. they are spelled differently. Moreover, the words of these languages have a one-to-one correspondence, that is, for each word in each language, there exists exactly one word in the other language having has the same meaning.
You can write down every word the professor says in either the first language or the second language. Of course, during the lecture you write down each word in the language in which the word is shorter. In case of equal lengths of the corresponding words you prefer the word of the first language.
You are given the text of the lecture the professor is going to read. Find out how the lecture will be recorded in your notes.
|
```python
n,m = [int(x) for x in input().split()]
words = {}
for i in range(m):
word = input().split()
words[word[0]] = word[0] if len(word[0]) < len(word[1]) else word[1]
lecture = input().split()
note = ""
for word in lecture:
note += words[word] + " "
print(note[:-1])
```
|
|
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
import sys,bisect
from sys import stdin,stdout
from bisect import bisect_left,bisect_right,bisect,insort,insort_left,insort_right
from math import gcd,ceil,floor,sqrt
from collections import Counter,defaultdict,deque,OrderedDict
from queue import Queue,PriorityQueue
from string import ascii_lowercase
from heapq import *
from itertools import islice
sys.setrecursionlimit(10**6)
INF = float('inf')
MOD = 998244353
mod = 10**9+7
def isPrime(n):
if (n <= 1) :return False
if (n <= 3) :return True
if (n%2 == 0 or n%3 == 0):return False
for i in range(5,ceil(sqrt(n))+1,6):
if (n%i==0 or n%(i+2)==0):
return False
return True
def st():
return list(stdin.readline().strip())
def inp():
return int(stdin.readline())
def li():
return list(map(int,stdin.readline().split()))
def mp():
return map(int,stdin.readline().split())
def pr(n):
stdout.write(str(n)+"\n")
def DFS(dictionary,vertex,visited):
visited[vertex]=True
stack=[vertex]
print(vertex)
while stack:
a=stack.pop()
for i in dictionary[a]:
if not visited[i]:
print(i)
visited[i]=True
stack.append(i)
def BFS(dictionary, vertex,visited):
visited[vertex]=True
q=deque()
q.append(vertex)
while q:
a=q.popleft()
for i in dictionary[a]:
if not visited[i]:
visited[i]=True
q.append(i)
print(i)
def soe(limit):
l=[1]*(limit+1)
l[0]=0
l[1]=0
prime=[]
for i in range(2,limit+1):
if l[i]:
for j in range(i*i,limit+1,i):
l[j]=0
for i in range(2,limit+1):
if l[i]:
prime.append(i)
return prime
def segsoe(low,high):
limit=int(high**0.5)+1
prime=soe(limit)
n=high-low+1
l=[0]*(n+1)
for i in range(len(prime)):
lowlimit=(low//prime[i])*prime[i]
if lowlimit<low:
lowlimit+=prime[i]
if lowlimit==prime[i]:
lowlimit+=prime[i]
for j in range(lowlimit,high+1,prime[i]):
l[j-low]=1
for i in range(low,high+1):
if not l[i-low]:
if i!=1:
print(i)
def gcd(a,b):
while b:
a=a%b
b,a=a,b
return a
def power(a,n):
r=1
while n:
if n&1:
r=(r*a)
a*=a
n=n>>1
return r
def don(d,ans,vi,i):
vi[i]=True
stack=[i]
while stack:
a=stack.pop()
for x in d[a]:
if not vi[x]:
ans[i]+=1
vi[x]=True
stack.append(x)
def solve():
n=inp()
c=0
for i in range(n):
s=input().split()
a,b=int(s[1]),int(s[2])
if a>=2400 and b>a:
c=1
if c:
pr('YES')
else:
pr('NO')
for _ in range(1):
solve()
## print("Case #{}:".format(_+1),c)
##
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all *n* squad soldiers to line up on the parade ground.
By the military charter the soldiers should stand in the order of non-increasing of their height. But as there's virtually no time to do that, the soldiers lined up in the arbitrary order. However, the general is rather short-sighted and he thinks that the soldiers lined up correctly if the first soldier in the line has the maximum height and the last soldier has the minimum height. Please note that the way other solders are positioned does not matter, including the case when there are several soldiers whose height is maximum or minimum. Only the heights of the first and the last soldier are important.
For example, the general considers the sequence of heights (4, 3, 4, 2, 1, 1) correct and the sequence (4, 3, 1, 2, 2) wrong.
Within one second the colonel can swap any two neighboring soldiers. Help him count the minimum time needed to form a line-up which the general will consider correct.
|
```python
n = int(input())
vls = list(map(int, input().split()))
x = min(vls)
iX = len(vls) - 1 - vls[::-1].index(x)
del vls[iX]
vls.append(x)
r = len(vls) - iX - 1
r += vls.index(max(vls))
print(r)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A + B is often used as an example of the easiest problem possible to show some contest platform. However, some scientists have observed that sometimes this problem is not so easy to get accepted. Want to try?
|
```python
a = input()
b = input()
if int(a) >=0 and int(b)<=1000:
print(int(a)+int(b))
```
|
|
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
import sys
n = int(input())
x = []
y = []
z = []
for i in range(0, n):
force = list(map(int, input().split()))
x.append(force[0])
y.append(force[1])
z.append(force[2])
if((sum(x)+sum(y)+sum(z)) == 0):
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A bus moves along the coordinate line *Ox* from the point *x*<==<=0 to the point *x*<==<=*a*. After starting from the point *x*<==<=0, it reaches the point *x*<==<=*a*, immediately turns back and then moves to the point *x*<==<=0. After returning to the point *x*<==<=0 it immediately goes back to the point *x*<==<=*a* and so on. Thus, the bus moves from *x*<==<=0 to *x*<==<=*a* and back. Moving from the point *x*<==<=0 to *x*<==<=*a* or from the point *x*<==<=*a* to *x*<==<=0 is called a bus journey. In total, the bus must make *k* journeys.
The petrol tank of the bus can hold *b* liters of gasoline. To pass a single unit of distance the bus needs to spend exactly one liter of gasoline. The bus starts its first journey with a full petrol tank.
There is a gas station in point *x*<==<=*f*. This point is between points *x*<==<=0 and *x*<==<=*a*. There are no other gas stations on the bus route. While passing by a gas station in either direction the bus can stop and completely refuel its tank. Thus, after stopping to refuel the tank will contain *b* liters of gasoline.
What is the minimum number of times the bus needs to refuel at the point *x*<==<=*f* to make *k* journeys? The first journey starts in the point *x*<==<=0.
|
```python
a, b, f, k=map(int,input().split())
d=b
n=0
s=0
x=a-f
d -= f
if (x*2>b) or (f*2>b):
if k<3:
if k==1:
if a<=b:
print(0)
elif (f<=b) and (x<=b):
print(1)
else:
print(-1)
if k==2:
if a+x<=b:
print(1)
elif (f<=b) and (x*2<=b):
print(2)
else:
print(-1)
else:
print(-1)
else:
while n<k:
if (n+1==k):
if (d<x):
s+=1
break
if d<x*2:
s+=1
d=b
n+=1
d-=x*2
if (n+1==k):
if (d<f):
s+=1
break
if d<f*2:
s+=1
d=b
n+=1
d-=f*2
print(s)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Now it's time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. They've been best friends ever since primary school and hopefully, that can somehow help them in teamwork.
For each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing numbers 1 and 0. The boys are very superstitious. They think that they can do well at the Olympiad if they begin with laying all the cards in a row so that:
- there wouldn't be a pair of any side-adjacent cards with zeroes in a row; - there wouldn't be a group of three consecutive cards containing numbers one.
Today Vanya brought *n* cards with zeroes and *m* cards with numbers one. The number of cards was so much that the friends do not know how to put all those cards in the described way. Help them find the required arrangement of the cards or else tell the guys that it is impossible to arrange cards in such a way.
|
```python
n,k=map(int,input().split())
if k<=n*2+2 and k>=n-1:
if k==n-1:
print('0',end='')
n+=1
while(True):
if k==n:
print('10',end='')
k-=1
n-=1
else:
print('110',end='')
k-=2
n-=1
if k==0:
break
if n==0:
break
else:
print(-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Drazil is playing a math game with Varda.
Let's define for positive integer *x* as a product of factorials of its digits. For example, .
First, they choose a decimal number *a* consisting of *n* digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then they should find maximum positive number *x* satisfying following two conditions:
1. *x* doesn't contain neither digit 0 nor digit 1.
2. = .
Help friends find such number.
|
```python
def findNum(a):
numCount = [0]*11
for num in a:
for i in range(2, num+1):
numCount[i] += 1
# print(numCount)
for i in range(9, 3, -1):
shifts = max(0, numCount[i]-numCount[i+1])
if i == 4:
numCount[2] += 2*shifts
numCount[i] -= shifts
elif i == 6:
numCount[2] += shifts
numCount[3] += shifts
numCount[i] -= shifts
elif i == 8:
numCount[2] += 3*shifts
numCount[i] -= shifts
elif i == 9:
numCount[3] += 3*shifts
numCount[i] -= shifts
# print(numCount)
res = []
for i in range(9, 1, -1):
for j in range(numCount[i]):
res.append(str(i))
for k in range(2, i):
numCount[k] -= 1
return ''.join(res)
n = int(input())
a = list(map(int, input()))
print(findNum(a))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
At regular competition Vladik and Valera won *a* and *b* candies respectively. Vladik offered 1 his candy to Valera. After that Valera gave Vladik 2 his candies, so that no one thought that he was less generous. Vladik for same reason gave 3 candies to Valera in next turn.
More formally, the guys take turns giving each other one candy more than they received in the previous turn.
This continued until the moment when one of them couldn’t give the right amount of candy. Candies, which guys got from each other, they don’t consider as their own. You need to know, who is the first who can’t give the right amount of candy.
|
```python
X = list(map(int, input().split()))
Turn = True
N = 1
while True:
if True:
if X[0] - N < 0:
print("Valera")
exit()
X[1] += X[0] - N
X[0] -= N
N += 1
Turn = False
else:
if X[1] - N < 0:
print("Vladik")
exit()
X[0] += X[1] - N
X[1] -= N
N += 1
Turn = True
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Santa Claus has *n* candies, he dreams to give them as gifts to children.
What is the maximal number of children for whose he can give candies if Santa Claus want each kid should get distinct positive integer number of candies. Santa Class wants to give all *n* candies he has.
|
```python
# http://codeforces.com/problemset/problem/753/A
def getSweets(sweetCount):
sweetsList = []
sumN = 0
n = 1
while sumN + n < sweetCount:
sumN += n
sweetsList.append(n)
n += 1
sweetsList[-1] += sweetCount - sumN
return sweetsList
if __name__ == '__main__':
sweetCount = int(input())
sweets = getSweets(sweetCount)
sweets = list(map(str, sweets))
print(len(sweets))
print(' '.join(sweets))
```
|
|
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
s=input()
l=len(s)
c=0
for i in range (l):
if i>='a' and i<='z':
c+=1
if c>=l/2:
print(s.lower)
else:
print(s.upper)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vanya plays a game of balloons on the field of size *n*<=×<=*n*, where each cell contains a balloon with one of the values 0, 1, 2 or 3. The goal is to destroy a cross, such that the product of all values of balloons in the cross is maximum possible. There are two types of crosses: normal and rotated. For example:
or
Formally, the cross is given by three integers *r*, *c* and *d*, such that *d*<=≤<=*r*,<=*c*<=≤<=*n*<=-<=*d*<=+<=1. The normal cross consists of balloons located in cells (*x*,<=*y*) (where *x* stay for the number of the row and *y* for the number of the column), such that |*x*<=-<=*r*|·|*y*<=-<=*c*|<==<=0 and |*x*<=-<=*r*|<=+<=|*y*<=-<=*c*|<=<<=*d*. Rotated cross consists of balloons located in cells (*x*,<=*y*), such that |*x*<=-<=*r*|<==<=|*y*<=-<=*c*| and |*x*<=-<=*r*|<=<<=*d*.
Vanya wants to know the maximum possible product of the values of balls forming one cross. As this value can be large, output it modulo 109<=+<=7.
|
```python
print("_RANDOM_GUESS_1690489311.5176659")# 1690489311.5176845
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Maxim wants to buy some games at the local game shop. There are $n$ games in the shop, the $i$-th game costs $c_i$.
Maxim has a wallet which can be represented as an array of integers. His wallet contains $m$ bills, the $j$-th bill has value $a_j$.
Games in the shop are ordered from left to right, Maxim tries to buy every game in that order.
When Maxim stands at the position $i$ in the shop, he takes the first bill from his wallet (if his wallet is empty then he proceeds to the next position immediately) and tries to buy the $i$-th game using this bill. After Maxim tried to buy the $n$-th game, he leaves the shop.
Maxim buys the $i$-th game if and only if the value of the first bill (which he takes) from his wallet is greater or equal to the cost of the $i$-th game. If he successfully buys the $i$-th game, the first bill from his wallet disappears and the next bill becomes first. Otherwise Maxim leaves the first bill in his wallet (this bill still remains the first one) and proceeds to the next game.
For example, for array $c = [2, 4, 5, 2, 4]$ and array $a = [5, 3, 4, 6]$ the following process takes place: Maxim buys the first game using the first bill (its value is $5$), the bill disappears, after that the second bill (with value $3$) becomes the first one in Maxim's wallet, then Maxim doesn't buy the second game because $c_2 > a_2$, the same with the third game, then he buys the fourth game using the bill of value $a_2$ (the third bill becomes the first one in Maxim's wallet) and buys the fifth game using the bill of value $a_3$.
Your task is to get the number of games Maxim will buy.
|
```python
n,m = list(map(int, input().split()))
c = list(map(int, input().split()))
a = list(map(int, input().split()))
i=0
j=0
b=0
while i<n and j<m:
if c[i]<=a[j]:
b+=1
j+=1
i+=1
print(b)
```
|
|
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 xd(a, b):
if a == b:
return True
if len(a) % 2 == 1 or a != b[::-1]:
return False
mid = len(a) // 2
return (xd(a[:mid], b[:mid]) and xd(a[mid:], b[mid:])) or \
(xd(a[:mid], b[mid:]) and xd(a[mid:], b[:mid]))
x = input()
a, b = x.split()
if xd(a, b):
print("YES")
else:
print("NO")
```
|
|
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
x = int(input())
i = 0
lis = []
lis = [int(x) for x in input().split()]
for i in range(0, x):
if(i == 0):
print(f'{lis[1] - lis[0]} {lis[x-1] - lis[0]}')
elif(i == x-1):
print(f'{lis[x-1] - lis[x-2]} {lis[x-1] - lis[0]}')
else:
if(lis[i] - lis[i-1] > lis [i+1] - lis[i]):
print(f'{lis[i+1] - lis[i]}', end = ' ')
else:
print(f'{lis[i] - lis[i-1]}', end = ' ')
if(lis[i] - lis[0] > lis [x-1] - lis[i]):
print(f'{lis[i] - lis[0]}')
else:
print(f'{lis[x-1] - lis[i]}')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are *n* lines in that description each of which described one goal. Every goal was marked with the name of the team that had scored it. Help Vasya, learn the name of the team that won the finals. It is guaranteed that the match did not end in a tie.
|
```python
n=int(input(""))
dict1={}
m=0
s=''
for i in range(n):
a=input("")
if a not in dict1.keys():
dict1[a]=1
else:
dict1[a]+=1
for j in dict1.keys():
if dict1[j]>m:
m=dict1[j]
s=j
print(s)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Valera is a little boy. Yesterday he got a huge Math hometask at school, so Valera didn't have enough time to properly learn the English alphabet for his English lesson. Unfortunately, the English teacher decided to have a test on alphabet today. At the test Valera got a square piece of squared paper. The length of the side equals *n* squares (*n* is an odd number) and each unit square contains some small letter of the English alphabet.
Valera needs to know if the letters written on the square piece of paper form letter "X". Valera's teacher thinks that the letters on the piece of paper form an "X", if:
- on both diagonals of the square paper all letters are the same; - all other squares of the paper (they are not on the diagonals) contain the same letter that is different from the letters on the diagonals.
Help Valera, write the program that completes the described task for him.
|
```python
n=int(input())
mat=[]
c=0
for i in range(n):
s=input()
mat+=[s]
for i in range(n):
if mat[i][i]==mat[i][n-i-1]:
c+=1
if c==n and len(set(mat))==2:
print('YES')
else:
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all *n* squad soldiers to line up on the parade ground.
By the military charter the soldiers should stand in the order of non-increasing of their height. But as there's virtually no time to do that, the soldiers lined up in the arbitrary order. However, the general is rather short-sighted and he thinks that the soldiers lined up correctly if the first soldier in the line has the maximum height and the last soldier has the minimum height. Please note that the way other solders are positioned does not matter, including the case when there are several soldiers whose height is maximum or minimum. Only the heights of the first and the last soldier are important.
For example, the general considers the sequence of heights (4, 3, 4, 2, 1, 1) correct and the sequence (4, 3, 1, 2, 2) wrong.
Within one second the colonel can swap any two neighboring soldiers. Help him count the minimum time needed to form a line-up which the general will consider correct.
|
```python
n = int(input())
a = list(map(int, input().split()))
min_val = max_val = a[0]
min_index = max_index = 0
for i in range(n):
if min_val >= a[i]:
min_val = a[i]
min_index = i
if max_val < a[i]:
max_val = a[i]
max_index = i
if min_index < max_index:
min_index = (n - 1) - min_index
print(min_index + max_index - 1)
else:
min_index = (n - 1) - min_index
print(min_index + max_index)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Natasha is planning an expedition to Mars for $n$ people. One of the important tasks is to provide food for each participant.
The warehouse has $m$ daily food packages. Each package has some food type $a_i$.
Each participant must eat exactly one food package each day. Due to extreme loads, each participant must eat the same food type throughout the expedition. Different participants may eat different (or the same) types of food.
Formally, for each participant $j$ Natasha should select his food type $b_j$ and each day $j$-th participant will eat one food package of type $b_j$. The values $b_j$ for different participants may be different.
What is the maximum possible number of days the expedition can last, following the requirements above?
|
```python
# Main
def main():
n, m = map(int, input().split())
food = list(map(int, input().split()))
arr = dict()
for i in food:
if i not in arr:
arr[i] = 1
else:
arr[i] += 1
maxD = 0
for d in range(1, 101, 1):
temp = arr
k = 0
flag = 0
for key, val in temp.items():
while val >= d:
flag += 1
k += 1
val -= d
if k >= n and d > maxD:
maxD = d
if flag == 0:
break
print(maxD)
# End main
if __name__ == "__main__":
main()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Yet another Armageddon is coming! This time the culprit is the Julya tribe calendar.
The beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows:
"May the Great Beaver bless you! May your chacres open and may your third eye never turn blind from beholding the Truth! Take the magic number, subtract a digit from it (the digit must occur in the number) and get a new magic number. Repeat this operation until a magic number equals zero. The Earth will stand on Three Beavers for the time, equal to the number of subtractions you perform!"
Distinct subtraction sequences can obviously get you different number of operations. But the Smart Beaver is ready to face the worst and is asking you to count the minimum number of operations he needs to reduce the magic number to zero.
|
```python
t=int(input())
rem=t%10
c=1
no=t-rem
c+=(no/10)*2
print(c)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya has *n* pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every *m*-th day (at days with numbers *m*,<=2*m*,<=3*m*,<=...) mom buys a pair of socks to Vasya. She does it late in the evening, so that Vasya cannot put on a new pair of socks before the next day. How many consecutive days pass until Vasya runs out of socks?
|
```python
n,m = list(map(int,input().split()))
n += (n//m)
if n%m == 0:
n += 1
print(n)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You have *r* red, *g* green and *b* blue balloons. To decorate a single table for the banquet you need exactly three balloons. Three balloons attached to some table shouldn't have the same color. What maximum number *t* of tables can be decorated if we know number of balloons of each color?
Your task is to write a program that for given values *r*, *g* and *b* will find the maximum number *t* of tables, that can be decorated in the required manner.
|
```python
l = list(map(int,input().split()))
l.sort()
l[2]-=l[0]
l[1]-=l[0]
ans = l[0]
ans += min(l[1],l[2]//2)
print(ans)
```
|
|
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
tests = int(input())
for _ in range (0,tests):
s = input()
if len(s)>10:
print(s[0],len(s)-2,s[-1],sep="")
else:
print(s)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner.
Output the probability that SmallR will win the match.
|
```python
a, b, c, d = (int(s) for s in input().split(" "))
MAX = 100
coef = sum((((c - d) * (a - b)) / (b * d)) ** i for i in range(MAX + 1))
ptotal = (a/b) * coef
print("{:.15f}".format(ptotal))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are a lover of bacteria. You want to raise some bacteria in a box.
Initially, the box is empty. Each morning, you can put any number of bacteria into the box. And each night, every bacterium in the box will split into two bacteria. You hope to see exactly *x* bacteria in the box at some moment.
What is the minimum number of bacteria you need to put into the box across those days?
|
```python
'''
x = 2345234
print(bin(x)[2:])
s = '101110011100'
print(int(s, 2))
'''
n = int(input())
k = bin(n)[2:]
print(k.count('1'))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Beroffice text editor has a wide range of features that help working with text. One of the features is an automatic search for typos and suggestions of how to fix them.
Beroffice works only with small English letters (i.e. with 26 letters from a to z). Beroffice thinks that a word is typed with a typo if there are three or more consonants in a row in the word. The only exception is that if the block of consonants has all letters the same, then this block (even if its length is greater than three) is not considered a typo. Formally, a word is typed with a typo if there is a block of not less that three consonants in a row, and there are at least two different letters in this block.
For example:
- the following words have typos: "hellno", "hackcerrs" and "backtothefutttture"; - the following words don't have typos: "helllllooooo", "tobeornottobe" and "oooooo".
When Beroffice editor finds a word with a typo, it inserts as little as possible number of spaces in this word (dividing it into several words) in such a way that each of the resulting words is typed without any typos.
Implement this feature of Beroffice editor. Consider the following letters as the only vowels: 'a', 'e', 'i', 'o' and 'u'. All the other letters are consonants in this problem.
|
```python
def insert_spacebar(s,n):
s1=''
s2=''
for i in range(n+1):
s1+=s[i]
for i in range(n+1,len(s)):
s2+=s[i]
return s1+' '+s2
s=input()
glas_arr=['a','i','e','u','o']
for i in range(len(s)-2):
if(s[i]==' ' or s[i] in glas_arr):
continue
else:
if((s[i] not in glas_arr)and (s[i+1] not in glas_arr) and (s[i+2] not in glas_arr)):
if(s[i]==s[i+1]==s[i+2]):
continue
else:
s=insert_spacebar(s,i+1)
if((s[len(s)-1] not in glas_arr)and (s[len(s)-2] not in glas_arr) and (s[len(s)-3] not in glas_arr)):
if((s[len(s)-1]==s[len(s)-2]==s[len(s)-3])==False):
s=insert_spacebar(s,len(s)-2)
print(s)
```
|
|
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
a = input()
b = input()
def equivalente(a,b):
if(a == b):
return 1
elif(len(a) > 1):
half = int(len(a)/2)
end = int(len(a))
if(len(a) > 1):
ax = a[0:half]
ay = a[half:end]
bx = b[0:half]
by = b[half:end]
else:
ax, ay, bx, by = a, a, b, b
if(equivalente(ax,bx) * equivalente(ay,by) == 1):
return 1
elif(equivalente(ax,by) * equivalente(ay,bx) == 1):
return 1
else:
return 0
else:
return 0
x = equivalente(a,b)
if(x == 1):
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.
Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own.
Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
|
```python
n = int(input())
control = n
count = 0
temp = 0
while n > 0:
magnet = input()
if n != control and temp != magnet:
count += 1
temp = magnet
n -= 1
print(count + 1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There are *n* students in a class working on group projects. The students will divide into groups (some students may be in groups alone), work on their independent pieces, and then discuss the results together. It takes the *i*-th student *a**i* minutes to finish his/her independent piece.
If students work at different paces, it can be frustrating for the faster students and stressful for the slower ones. In particular, the imbalance of a group is defined as the maximum *a**i* in the group minus the minimum *a**i* in the group. Note that a group containing a single student has an imbalance of 0. How many ways are there for the students to divide into groups so that the total imbalance of all groups is at most *k*?
Two divisions are considered distinct if there exists a pair of students who work in the same group in one division but different groups in the other.
|
```python
import sys, math
from functools import lru_cache
input = sys.stdin.readline
if __name__ == "__main__":
MOD = 10 ** 9 + 7
n, k = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
a.append(0)
@lru_cache(None)
def dfs(i, groups, leftK):
if leftK < 0 or groups > i+1:
return 0
if i < 0:
if groups == 0: return 1
return 0
leftK -= (a[i+1] - a[i]) * groups
res = dfs(i-1, groups+1, leftK)
res += dfs(i-1, groups, leftK) * (groups + 1)
if groups > 0:
res += dfs(i-1, groups-1, leftK) * groups
res %= MOD
return res
res = dfs(n-1, 0, k)
print(res)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
As you could know there are no male planes nor female planes. However, each plane on Earth likes some other plane. There are *n* planes on Earth, numbered from 1 to *n*, and the plane with number *i* likes the plane with number *f**i*, where 1<=≤<=*f**i*<=≤<=*n* and *f**i*<=≠<=*i*.
We call a love triangle a situation in which plane *A* likes plane *B*, plane *B* likes plane *C* and plane *C* likes plane *A*. Find out if there is any love triangle on Earth.
|
```python
# cook your dish here
import bisect
n=int(input())
A=[0]
for k in input().split():
A.append(int(k))
# s=input()
for k in range(1,n+1):
if A[A[A[k]]]==k:
print("YES")
break
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
For a positive integer *n* let's define a function *f*:
*f*(*n*)<==<=<=-<=1<=+<=2<=-<=3<=+<=..<=+<=(<=-<=1)*n**n*
Your task is to calculate *f*(*n*) for a given integer *n*.
|
```python
n = int(input())
f = 0
for i in range(1,n+1):
f += ((-1)**i)*i
print(f)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a ternary string (it is a string which consists only of characters '0', '1' and '2').
You can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace "01" with "10" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace "12" with "21" or vice versa).
For example, for string "010210" we can perform the following moves:
- "010210" $\rightarrow$ "100210"; - "010210" $\rightarrow$ "001210"; - "010210" $\rightarrow$ "010120"; - "010210" $\rightarrow$ "010201".
Note than you cannot swap "02" $\rightarrow$ "20" and vice versa. You cannot perform any other operations with the given string excluding described above.
You task is to obtain the minimum possible (lexicographically) string by using these swaps arbitrary number of times (possibly, zero).
String $a$ is lexicographically less than string $b$ (if strings $a$ and $b$ have the same length) if there exists some position $i$ ($1 \le i \le |a|$, where $|s|$ is the length of the string $s$) such that for every $j < i$ holds $a_j = b_j$, and $a_i < b_i$.
|
```python
s=list(input())
a=[]
t=0
l=0
for i in range(len(s)):
if s[i]=='2':t=1
if s[i]=='0'and t==1:
t=0
a+=sorted(s[l:i])
l=i
if i==len(s)-1:a+=sorted(s[l:])
print(''.join(a))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Gerald has *n* younger brothers and their number happens to be even. One day he bought *n*2 candy bags. One bag has one candy, one bag has two candies, one bag has three candies and so on. In fact, for each integer *k* from 1 to *n*2 he has exactly one bag with *k* candies.
Help him give *n* bags of candies to each brother so that all brothers got the same number of candies.
|
```python
n=int(input())
x=n*(n**2+1)//2
for i in range(1,n+1):
print(i,x-i)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Natasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the string — concatenation of letters, which correspond to the stages.
There are $n$ stages available. The rocket must contain exactly $k$ of them. Stages in the rocket should be ordered by their weight. So, after the stage with some letter can go only stage with a letter, which is at least two positions after in the alphabet (skipping one letter in between, or even more). For example, after letter 'c' can't go letters 'a', 'b', 'c' and 'd', but can go letters 'e', 'f', ..., 'z'.
For the rocket to fly as far as possible, its weight should be minimal. The weight of the rocket is equal to the sum of the weights of its stages. The weight of the stage is the number of its letter in the alphabet. For example, the stage 'a 'weighs one ton,' b 'weighs two tons, and' z' — $26$ tons.
Build the rocket with the minimal weight or determine, that it is impossible to build a rocket at all. Each stage can be used at most once.
|
```python
from math import *
from collections import *
from operator import itemgetter
import bisect
ii = lambda: int(input())
iia = lambda: list(map(int,input().split()))
isa = lambda: list(input().split())
I = lambda:list(map(int,input().split()))
chrIdx = lambda x: ord(x)-96
idxChr = lambda x: chr(96+x)
n, k = iia()
s = input()
s = sorted(s)
#print(s)
x = 1
flag = -1
prev = s[0]
val = chrIdx(s[0])
if(k==1):
flag = val
#print(val)
for i in range(1,n):
if(chrIdx(s[i])-chrIdx(prev)>2):
x+=1
prev = s[i]
val += chrIdx(s[i])
#print(s[i], x , val)
if(x>=k):
flag = val
break
print(flag)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Luba has a ticket consisting of 6 digits. In one move she can choose digit in any position and replace it with arbitrary digit. She wants to know the minimum number of digits she needs to replace in order to make the ticket lucky.
The ticket is considered lucky if the sum of first three digits equals to the sum of last three digits.
|
```python
l=[int(i) for i in input()]
a=sum(l[:3]);b=sum(l[3:])
if a==b:
print(0)
else:
print(abs(a-b)//9+1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a sequence *a* consisting of *n* integers. You may partition this sequence into two sequences *b* and *c* in such a way that every element belongs exactly to one of these sequences.
Let *B* be the sum of elements belonging to *b*, and *C* be the sum of elements belonging to *c* (if some of these sequences is empty, then its sum is 0). What is the maximum possible value of *B*<=-<=*C*?
|
```python
raw_input()
print(eval(input().replace("-","").replace(" ","+")))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times *b*,<=*b*<=+<=*a*,<=*b*<=+<=2*a*,<=*b*<=+<=3*a*,<=... and Morty screams at times *d*,<=*d*<=+<=*c*,<=*d*<=+<=2*c*,<=*d*<=+<=3*c*,<=....
The Monster will catch them if at any point they scream at the same time, so it wants to know when it will catch them (the first time they scream at the same time) or that they will never scream at the same time.
|
```python
import math
import cmath
import string
# how to find minimum prime factor in log(n)
def sieve(n):
l = [0]*(n+1)
l[0] = l[1] = 1
for i in range(2,int(n**.5)+1):
if not l[i]:
for j in range(i*i,n+1,i):
l[j] = 1
return [i for i in range(n+1) if l[i] == 0]
#pass n+1
def sieveOptemised(n,prime):
l = [0]*(n+1)
l[0] = l[1] = 1
for i in range(2,n):
if not l[i] : prime.append(i)
for j in range(len(prime)):
if i*prime[j] >= n :
break
l[i*prime[j]] = 1
if i % prime[j] == 0 : break
def XOR(n):
return [n, 1, n + 1, 0][n % 4]
def isprime(n):
return all([False for i in range(2, n) if n % i == 0]) and not n < 2
def searchBinary(lis, l, r, e):
ans = 0
while l <= r:
m = (l + r) // 2
if lis[m][0] > e:
r = m - 1
else:
l = m + 1
ans = l
return ans
def f(l, i, j, n, m):
c = l[i][j]
i1 = i
j1 = j
i2 = i
j2 = j
i3 = i
j3 = j
i4 = i
j4 = j
while i1 > 0 and j1 > 0:
i1 -= 1
j1 -= 1
c += l[i1][j1]
while i2 < n - 1 and j2 < m - 1:
i2 += 1
j2 += 1
c += l[i2][j2]
while i3 > 0 and j3 < m - 1:
i3 -= 1
j3 += 1
c += l[i3][j3]
while i4 < n - 1 and j4 > 0:
i4 += 1
j4 -= 1
c += l[i4][j4]
return c
def gcd(a,b):
if b == 0 :
return a
else :
return gcd(b,a%b)
def binarySearch(lis, l, r, e):
while l <= r:
m = (l + r) // 2
if lis[m] == e:
return 1
elif lis[m] > e:
r = m - 1
else:
l = m + 1
return 0
def isSqrt(n):
for i in range(1,int(n**.5)+2):
if i*i == n :
return True
return False
# math.ceil(n/i) = (n-1)//i+1
result = list(string.ascii_lowercase)
alpha = {}
for i in range(26):
alpha[result[i]] = i + 1
aa = []
a,b = map(int,input().split())
c,d = map(int,input().split())
l1 = []
l2 = []
for i in range(100000):
l1.append(b+i*a)
l2.append(d+i*c)
s = list(set(set(l1).intersection(set(l2))))
s.sort()
if s :
aa.append(s[0])
else :
aa.append(-1)
for i in aa :
print(i)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes.
You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consists of several words. For each language, all words are distinct, i.e. they are spelled differently. Moreover, the words of these languages have a one-to-one correspondence, that is, for each word in each language, there exists exactly one word in the other language having has the same meaning.
You can write down every word the professor says in either the first language or the second language. Of course, during the lecture you write down each word in the language in which the word is shorter. In case of equal lengths of the corresponding words you prefer the word of the first language.
You are given the text of the lecture the professor is going to read. Find out how the lecture will be recorded in your notes.
|
```python
n,m=map(int,input().split())
mp={}
for i in range(m):
s1,s2=input().split()
mp[s1]=s2
l=input().split()
for i in range(n) :
if len(mp[l[i]])<len(l[i]):
print(mp[l[i]],end=' ')
else:
print(l[i],end=' ')
i+=1
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Cucumber boy is fan of Kyubeat, a famous music game.
Kyubeat has 16 panels for playing arranged in 4<=×<=4 table. When a panel lights up, he has to press that panel.
Each panel has a timing to press (the preffered time when a player should press it), and Cucumber boy is able to press at most *k* panels in a time with his one hand. Cucumber boy is trying to press all panels in perfect timing, that is he wants to press each panel exactly in its preffered time. If he cannot press the panels with his two hands in perfect timing, his challenge to press all the panels in perfect timing will fail.
You are given one scene of Kyubeat's panel from the music Cucumber boy is trying. Tell him is he able to press all the panels in perfect timing.
|
```python
k = int(input())
a = []
d = {}
for _ in range(4):
for i in input():
if i != ".":
if i in d:
d[i] += 1
else:
d[i] = 1
d = sorted(d.items(), key = lambda x: x[1], reverse = True)
if d[0][1] <= k*2:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Devu is a renowned classical singer. He is invited to many big functions/festivals. Recently he was invited to "All World Classical Singing Festival". Other than Devu, comedian Churu was also invited.
Devu has provided organizers a list of the songs and required time for singing them. He will sing *n* songs, *i**th* song will take *t**i* minutes exactly.
The Comedian, Churu will crack jokes. All his jokes are of 5 minutes exactly.
People have mainly come to listen Devu. But you know that he needs rest of 10 minutes after each song. On the other hand, Churu being a very active person, doesn't need any rest.
You as one of the organizers should make an optimal sсhedule for the event. For some reasons you must follow the conditions:
- The duration of the event must be no more than *d* minutes; - Devu must complete all his songs; - With satisfying the two previous conditions the number of jokes cracked by Churu should be as many as possible.
If it is not possible to find a way to conduct all the songs of the Devu, output -1. Otherwise find out maximum number of jokes that Churu can crack in the grand event.
|
```python
n,d=map(int,input().split())
l=list(map(int,input().split()))
temp=sum(l)+(len(l)-1)*10
if temp>d:
print(-1)
else:
print((len(l)-1)*2+(d-temp)//5)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Devu is a renowned classical singer. He is invited to many big functions/festivals. Recently he was invited to "All World Classical Singing Festival". Other than Devu, comedian Churu was also invited.
Devu has provided organizers a list of the songs and required time for singing them. He will sing *n* songs, *i**th* song will take *t**i* minutes exactly.
The Comedian, Churu will crack jokes. All his jokes are of 5 minutes exactly.
People have mainly come to listen Devu. But you know that he needs rest of 10 minutes after each song. On the other hand, Churu being a very active person, doesn't need any rest.
You as one of the organizers should make an optimal sсhedule for the event. For some reasons you must follow the conditions:
- The duration of the event must be no more than *d* minutes; - Devu must complete all his songs; - With satisfying the two previous conditions the number of jokes cracked by Churu should be as many as possible.
If it is not possible to find a way to conduct all the songs of the Devu, output -1. Otherwise find out maximum number of jokes that Churu can crack in the grand event.
|
```python
t = input()
temp = t.split()
n = int(temp[0])
d = int(temp[1])
songLenthList = []
songLength = input()
List = songLength.split()
songLenthList = [int(i) for i in List]
devuBreaktime = (n-1)*10
devuTotalTime = devuBreaktime + sum(songLenthList)
churuTime = d - devuTotalTime + devuBreaktime
if (devuTotalTime > d):
print(-1)
else:
print(int(churuTime/5))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Top-model Izabella participates in the competition. She wants to impress judges and show her mathematical skills.
Her problem is following: for given string, consisting of only 0 and 1, tell if it's possible to remove some digits in such a way, that remaining number is a representation of some positive integer, divisible by 64, in the binary numerical system.
|
```python
str=input()
if len(str)>6:
print('yes')
else:
print('no')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Om Nom really likes candies and doesn't like spiders as they frequently steal candies. One day Om Nom fancied a walk in a park. Unfortunately, the park has some spiders and Om Nom doesn't want to see them at all.
The park can be represented as a rectangular *n*<=×<=*m* field. The park has *k* spiders, each spider at time 0 is at some cell of the field. The spiders move all the time, and each spider always moves in one of the four directions (left, right, down, up). In a unit of time, a spider crawls from his cell to the side-adjacent cell in the corresponding direction. If there is no cell in the given direction, then the spider leaves the park. The spiders do not interfere with each other as they move. Specifically, one cell can have multiple spiders at the same time.
Om Nom isn't yet sure where to start his walk from but he definitely wants:
- to start walking at time 0 at an upper row cell of the field (it is guaranteed that the cells in this row do not contain any spiders); - to walk by moving down the field towards the lowest row (the walk ends when Om Nom leaves the boundaries of the park).
We know that Om Nom moves by jumping. One jump takes one time unit and transports the little monster from his cell to either a side-adjacent cell on the lower row or outside the park boundaries.
Each time Om Nom lands in a cell he sees all the spiders that have come to that cell at this moment of time. Om Nom wants to choose the optimal cell to start the walk from. That's why he wonders: for each possible starting cell, how many spiders will he see during the walk if he starts from this cell? Help him and calculate the required value for each possible starting cell.
|
```python
n,m,k = map(int,input().split())
grid = [list(input()) for _ in range(n)]
sol = []
for col in range(m):
ans = 0
for t in range(1,n):
x,y = t,col
try:
if grid[x][y+t] == 'L':
ans += 1
except: pass
try:
if grid[x][y-t] == 'R':
ans += 1
except: pass
try:
if grid[x+t][y] == 'U':
ans += 1
except: pass
try:
if grid[x-t][y] == 'D':
ans += 1
except: pass
sol.append(ans)
print(" ".join(map(str,sol)))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Imagine that there is a group of three friends: A, B and С. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The debts still mean the same but the total sum of the debts now equals 20 rubles.
This task is a generalisation of a described example. Imagine that your group of friends has *n* people and you know the debts between the people. Optimize the given debts without changing their meaning. In other words, finally for each friend the difference between the total money he should give and the total money he should take must be the same. Print the minimum sum of all debts in the optimal rearrangement of the debts. See the notes to the test samples to better understand the problem.
|
```python
n, m = map(int, input().split())
own = dict()
for _ in range(m):
a, b, c = map(int, input().split())
if a in own:
own[a] += c
else:
own[a] = c
if b in own:
own[b] -= c
else:
own[b] = -c
ans = 0
for i in own.values():
ans += i if i > 0 else 0
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There will be a launch of a new, powerful and unusual collider very soon, which located along a straight line. *n* particles will be launched inside it. All of them are located in a straight line and there can not be two or more particles located in the same point. The coordinates of the particles coincide with the distance in meters from the center of the collider, *x**i* is the coordinate of the *i*-th particle and its position in the collider at the same time. All coordinates of particle positions are even integers.
You know the direction of each particle movement — it will move to the right or to the left after the collider's launch start. All particles begin to move simultaneously at the time of the collider's launch start. Each particle will move straight to the left or straight to the right with the constant speed of 1 meter per microsecond. The collider is big enough so particles can not leave it in the foreseeable time.
Write the program which finds the moment of the first collision of any two particles of the collider. In other words, find the number of microseconds before the first moment when any two particles are at the same point.
|
```python
"""
4
RLRL
2 4 6 10
3
LLR
40 50 60
4
LRLR
2 4 8 10
5
LRLRL
2 4 16 20 22
5
LRRRL
2 4 16 20 22
"""
n = int(input())
dirs = input()
first_right = dirs.index("R")
last_left = dirs.rfind("L")
bens = [int(i) for i in input().split()]
dirs = dirs[first_right:last_left + 1]
bens = bens[first_right:last_left+1]
left = []
right = []
for i in range(len(dirs)):
if dirs[i] == 'R':
right.append(bens[i])
else:
left.append(bens[i])
if len(right) == 0 or len(left) == 0:
print(-1)
else:
res = float('inf')
for i in left:
for j in right:
dis = abs(i - j) // 2
if dis < res:
res = dis
print(res)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Squirrel Liss loves nuts. There are *n* trees (numbered 1 to *n* from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree *i* is *h**i*. Liss wants to eat all nuts.
Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions:
- Walk up or down one unit on a tree. - Eat a nut on the top of the current tree. - Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height *h* of the tree *i* (1<=≤<=*i*<=≤<=*n*<=-<=1), she jumps to height *h* of the tree *i*<=+<=1. This action can't be performed if *h*<=><=*h**i*<=+<=1.
Compute the minimal time (in seconds) required to eat all nuts.
|
```python
n = int(input())
# Assume squirrel has had nut on the prev tree and is at it's top.
# In this, compute time to jump to next tree, go to top and have nut
h_prev = int(input())
time = h_prev + 1
for i in range(n-1):
h_cur = int(input())
time += abs((h_prev-h_cur)) + 2
h_prev = h_cur
print(time)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Arya has *n* opponents in the school. Each day he will fight with all opponents who are present this day. His opponents have some fighting plan that guarantees they will win, but implementing this plan requires presence of them all. That means if one day at least one of Arya's opponents is absent at the school, then Arya will beat all present opponents. Otherwise, if all opponents are present, then they will beat Arya.
For each opponent Arya knows his schedule — whether or not he is going to present on each particular day. Tell him the maximum number of consecutive days that he will beat all present opponents.
Note, that if some day there are no opponents present, Arya still considers he beats all the present opponents.
|
```python
io = input().split()
n = int(io[0])
d = int(io[1])
l = []
streak = 0
new_streak = 0
for _ in range(d):
l.append(list(map(int, input())))
for i in l:
if 0 in i:
streak += 1
else:
new_streak = streak
streak = 0
if streak > new_streak:
print(streak)
else:
print(new_streak)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya likes everything infinite. Now he is studying the properties of a sequence *s*, such that its first element is equal to *a* (*s*1<==<=*a*), and the difference between any two neighbouring elements is equal to *c* (*s**i*<=-<=*s**i*<=-<=1<==<=*c*). In particular, Vasya wonders if his favourite integer *b* appears in this sequence, that is, there exists a positive integer *i*, such that *s**i*<==<=*b*. Of course, you are the person he asks for a help.
|
```python
a,b,c=map(int,input().split(" "))
i=0
X=[a]
if(a==b):
print("YES")
elif((a>b and c<=0) or (a<b and c>=0)):
if(c!=0):
if(max(abs(b),abs(c))%min(abs(b),abs(c))==a):
print("YES")
else:
print("NO")
if(c==0):
if(a==b):
print("YES")
else:
print("NO")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to the store and buy some few more horseshoes, not to lose face in front of his stylish comrades.
Fortunately, the store sells horseshoes of all colors under the sun and Valera has enough money to buy any four of them. However, in order to save the money, he would like to spend as little money as possible, so you need to help Valera and determine what is the minimum number of horseshoes he needs to buy to wear four horseshoes of different colors to a party.
|
```python
arr = list(map(int,input().split()))
arrS = set(arr)
print(len(arr)-len(arrS))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.
For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two primes". Let's modify it. How about a statement like that: "each integer no less than 12 can be expressed as the sum of two composite numbers." Not like the Goldbach's conjecture, I can prove this theorem.
You are given an integer *n* no less than 12, express it as a sum of two composite numbers.
|
```python
def iscomposite(n):
for i in range(2,int(n/2 +1)):
if n % i == 0 :
return False
else:
continue
return True
m= int(input())
for i in range(4,m):
if iscomposite(i):
#print("{} is composite".format(i))
continue
else:
if iscomposite(m -i):
#print("{} is composite".format(m-i))
continue
else:
print(m-i,i)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One day a well-known sponsor of a well-known contest decided to give every participant of the contest a T-shirt as a present. A natural problem occurred: on the one hand, it is not clear how many T-shirts of what sizes should be ordered, and on the other hand, one doesn't want to order too many T-shirts (and we do not exactly paper the walls with the oversupply). After considerable brain racking and some pre-estimating, the sponsor representatives ordered a certain number of T-shirts of sizes S, M, L, XL and XXL. The T-shirts turned out to bring good luck, that's why on the contest day there built up a line of *K* participants willing to get one. Every contestant is characterized by his/her desired T-shirt size (so it happens that for all the participants it is also one of the sizes S, M, L, XL and XXL). The participants come up to get a T-shirt one by one and try to choose the most suitable one, choosing it like this. If there is still a T-shirt of the optimal size left, that he/she takes it without further ado. Otherwise the contestant would prefer to choose a T-shirt with the size as close to the optimal one as possible (the distance between neighboring sizes is considered equal to one). If the variant of choice is not unique, the contestant will take a T-shirt of a bigger size (in case he/she grows more). For example, for a person whose optimal size is L the preference list looks like this: L, XL, M, XXL, S. Using the data on how many T-shirts of every size had been ordered by the organizers, on the size of contestants in the line determine who got a T-shirt of what size.
|
```python
sizes = list(map(int, input().split()))
f = {"S":0, "M":1, "L":2, "XL":3, "XXL":4}
g = ["S", "M", "L", "XL", "XXL"]
for i in range(int(input())):
size = input()
idx = f[size]
for j in range(5):
try:
#print("...")
if sizes[idx+j]>0:
print(g[idx+j])
sizes[idx+j] -= 1
break
if sizes[max(0, idx-j)]>0:
print(g[max(0, idx-j)])
sizes[max(0, idx-j)] -= 1
break
except:
if sizes[max(0, idx-j)]>0:
print(g[max(0, idx-j)])
sizes[max(0, idx-j)] -= 1
break
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You've got a rectangular table with length *a* and width *b* and the infinite number of plates of radius *r*. Two players play the following game: they take turns to put the plates on the table so that the plates don't lie on each other (but they can touch each other), and so that any point on any plate is located within the table's border. During the game one cannot move the plates that already lie on the table. The player who cannot make another move loses. Determine which player wins, the one who moves first or the one who moves second, provided that both players play optimally well.
|
```python
a, b, r = map(int, input().split())
r *= 2
print('Second' if r > a or b < r else 'First')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Your security guard friend recently got a new job at a new security company. The company requires him to patrol an area of the city encompassing exactly *N* city blocks, but they let him choose which blocks. That is, your friend must walk the perimeter of a region whose area is exactly *N* blocks. Your friend is quite lazy and would like your help to find the shortest possible route that meets the requirements. The city is laid out in a square grid pattern, and is large enough that for the sake of the problem it can be considered infinite.
|
```python
import math
def Solution(N):
N = math.sqrt(N)
perimeter = 4 * N
return perimeter
N = int(input())
Solution(N)
```
|
|
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 = input()
a = list(map(int, input().split()))
dic = {i: g for i, g in enumerate(a, start=1)}
new_dict = {v: k for k, v in dic.items()}
sorted_dict = sorted(new_dict.items())
for key, value in sorted_dict:
print(value, end=" ")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.
Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer *n*. Help Anton to determine the exchange rate of currency you all know for tomorrow!
|
```python
if __name__ == '__main__':
s = list(input())
smallest_even = -1
has_even = False
for i in range(len(s)):
if int(s[i]) % 2 == 0:
has_even = True
if int(s[i]) < int(s[-1]):
s[i], s[-1] = s[-1], s[i]
print(''.join(s))
break
smallest_even = i
if smallest_even == -1:
print("-1")
else:
s[smallest_even], s[-1] = s[-1], s[smallest_even]
print(''.join(s))
```
|
|
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
sum = [0, 0, 0]
for _ in range(int(input())):
a, b, c = map(int, input().split())
sum[0] += a
sum[1] += b
sum[2] += c
print("YES" if sum == [0, 0, 0] else "NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little Tanya decided to present her dad a postcard on his Birthday. She has already created a message — string *s* of length *n*, consisting of uppercase and lowercase English letters. Tanya can't write yet, so she found a newspaper and decided to cut out the letters and glue them into the postcard to achieve string *s*. The newspaper contains string *t*, consisting of uppercase and lowercase English letters. We know that the length of string *t* greater or equal to the length of the string *s*.
The newspaper may possibly have too few of some letters needed to make the text and too many of some other letters. That's why Tanya wants to cut some *n* letters out of the newspaper and make a message of length exactly *n*, so that it looked as much as possible like *s*. If the letter in some position has correct value and correct letter case (in the string *s* and in the string that Tanya will make), then she shouts joyfully "YAY!", and if the letter in the given position has only the correct value but it is in the wrong case, then the girl says "WHOOPS".
Tanya wants to make such message that lets her shout "YAY!" as much as possible. If there are multiple ways to do this, then her second priority is to maximize the number of times she says "WHOOPS". Your task is to help Tanya make the message.
|
```python
from collections import *
s, t = deque(input()), input()
mem, a1, a2 = Counter(t), 0, 0
for i in range(len(s)):
if mem[s[0]]:
a1 += 1
mem[s[0]] -= 1
s.popleft()
else:
s.rotate(-1)
# print(s)
for i in s:
if i.isupper() and mem[i.lower()]:
a2 += 1
mem[i.lower()] = 0
elif i.islower() and mem[i.upper()]:
a2 += 1
mem[i.upper()] = 0
print(a1, a2)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word.
Hongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character of the word to the beginning of the word. He calls this a cyclic shift. He can apply cyclic shift many times. For example, consecutively applying cyclic shift operation to the word "abracadabra" Hongcow will get words "aabracadabr", "raabracadab" and so on.
Hongcow is now wondering how many distinct words he can generate by doing the cyclic shift arbitrarily many times. The initial string is also counted.
|
```python
a = input()
t = a
r1 = len(a)
for i in range(len(a)):
a = a[r1-1] + a[0:r1-1]
if a == t:
break
print(i+1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One day Vasya painted a Cartesian coordinate system on a piece of paper and marked some set of points (*x*1,<=*y*1),<=(*x*2,<=*y*2),<=...,<=(*x**n*,<=*y**n*). Let's define neighbors for some fixed point from the given set (*x*,<=*y*):
- point (*x*',<=*y*') is (*x*,<=*y*)'s right neighbor, if *x*'<=><=*x* and *y*'<==<=*y* - point (*x*',<=*y*') is (*x*,<=*y*)'s left neighbor, if *x*'<=<<=*x* and *y*'<==<=*y* - point (*x*',<=*y*') is (*x*,<=*y*)'s lower neighbor, if *x*'<==<=*x* and *y*'<=<<=*y* - point (*x*',<=*y*') is (*x*,<=*y*)'s upper neighbor, if *x*'<==<=*x* and *y*'<=><=*y*
We'll consider point (*x*,<=*y*) from the given set supercentral, if it has at least one upper, at least one lower, at least one left and at least one right neighbor among this set's points.
Vasya marked quite many points on the paper. Analyzing the picture manually is rather a challenge, so Vasya asked you to help him. Your task is to find the number of supercentral points in the given set.
|
```python
tests = int(input())
setlist = []
def solution(setlist):
points = 0
for i in range(len(setlist)):
right = 0
left = 0
upper = 0
lower = 0
for j in range(len(setlist)):
if setlist[i][0] == setlist[j][0] and setlist[j][1]<setlist[i][1]:
lower+=1
if setlist[i][0] == setlist[j][0] and setlist[j][1]<setlist[i][1]:
upper+=1
if setlist[i][0] < setlist[j][0] and setlist[j][1] == setlist[i][1]:
right+=1
if setlist[i][0] > setlist[j][0] and setlist[j][1] == setlist[i][1]:
left+=1
if right>=1 and left>=1 and upper>=1 and lower>=1:
points+=1
return points
for _ in range(tests):
sets = list(map(int,input().split()))
setlist.append(sets)
print(solution(setlist))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The administration of the Tomsk Region firmly believes that it's time to become a megacity (that is, get population of one million). Instead of improving the demographic situation, they decided to achieve its goal by expanding the boundaries of the city.
The city of Tomsk can be represented as point on the plane with coordinates (0; 0). The city is surrounded with *n* other locations, the *i*-th one has coordinates (*x**i*, *y**i*) with the population of *k**i* people. You can widen the city boundaries to a circle of radius *r*. In such case all locations inside the circle and on its border are included into the city.
Your goal is to write a program that will determine the minimum radius *r*, to which is necessary to expand the boundaries of Tomsk, so that it becomes a megacity.
|
```python
import math
x,y=map(int,input().split())
r=dict()
for i in range(x):
a,b,c = map(int, input().split())
a=math.sqrt(pow(a,2)+pow(b,2))
r[a]=c
if(y>=1000000):
print("0")
else:
for key in sorted(r):
y+=r[key]
if(y>=1000000):
print(key)
break
#print("%s %s"%(key,r[key]))
else:
print("-1")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Okabe and Super Hacker Daru are stacking and removing boxes. There are *n* boxes numbered from 1 to *n*. Initially there are no boxes on the stack.
Okabe, being a control freak, gives Daru 2*n* commands: *n* of which are to add a box to the top of the stack, and *n* of which are to remove a box from the top of the stack and throw it in the trash. Okabe wants Daru to throw away the boxes in the order from 1 to *n*. Of course, this means that it might be impossible for Daru to perform some of Okabe's remove commands, because the required box is not on the top of the stack.
That's why Daru can decide to wait until Okabe looks away and then reorder the boxes in the stack in any way he wants. He can do it at any point of time between Okabe's commands, but he can't add or remove boxes while he does it.
Tell Daru the minimum number of times he needs to reorder the boxes so that he can successfully complete all of Okabe's commands. It is guaranteed that every box is added before it is required to be removed.
|
```python
n = int(input())
st = 1
stack = []
ans = 0
for _ in range(2*n):
ops = input()
if ops[0]=='a':
_,k = ops.split()
stack.append(int(k))
else:
if stack[-1]!=st:
stack.sort(reverse=True)
ans+=1
stack.pop()
st+=1
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:
- Tetrahedron. Tetrahedron has 4 triangular faces. - Cube. Cube has 6 square faces. - Octahedron. Octahedron has 8 triangular faces. - Dodecahedron. Dodecahedron has 12 pentagonal faces. - Icosahedron. Icosahedron has 20 triangular faces.
All five kinds of polyhedrons are shown on the picture below:
Anton has a collection of *n* polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
|
```python
n = int(input())
total_faces = 0
for _ in range(n):
shape = input().capitalize()
if shape == "Tetrahedron" :
total_faces +=4
if shape == "Cube" :
total_faces +=6
if shape == "Octahedron" :
total_faces +=8
if shape == "Dodecahedron" :
total_faces +=12
if shape == "Icosahedron" :
total_faces +=20
print(total_faces)
```
|
|
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
def finder(point, x):
inx = 0
for i in range(len(point)):
if point[i] == x:
inx = i
break
return inx
def main():
n = int(input())
num = list(range(1, n + 1))
point = list(map(int, input().split()))
count = [0, 0, 0]
for i in range(n):
count[point[i] - 1] += 1
min_count = min(count)
print(min_count)
for i in range(n - 1):
swapped = True
for j in range(n - 1 - i):
if point[j] > point[j + 1]:
point[j], point[j + 1] = point[j + 1], point[j]
num[j], num[j + 1] = num[j + 1], num[j]
swapped = False
if swapped:
break
one_ind = finder(point, 1)
two_ind = finder(point, 2)
three_ind = finder(point, 3)
for i in range(min_count):
print(num[one_ind], num[two_ind], num[three_ind])
one_ind += 1
two_ind += 1
three_ind += 1
if __name__ == "__main__":
main()# 1698230401.854687
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Limak is a little polar bear. He has *n* balls, the *i*-th ball has size *t**i*.
Limak wants to give one ball to each of his three friends. Giving gifts isn't easy — there are two rules Limak must obey to make friends happy:
- No two friends can get balls of the same size. - No two friends can get balls of sizes that differ by more than 2.
For example, Limak can choose balls with sizes 4, 5 and 3, or balls with sizes 90, 91 and 92. But he can't choose balls with sizes 5, 5 and 6 (two friends would get balls of the same size), and he can't choose balls with sizes 30, 31 and 33 (because sizes 30 and 33 differ by more than 2).
Your task is to check whether Limak can choose three balls that satisfy conditions above.
|
```python
n = int(input())
a = sorted(map(int, input().split()))
q = 0
p = -1
ans = False
for i in a:
if i == p + 1:
q += 1
else:
q = 1
if q == 3:
ans = True
p = i
print('YES' if ans else 'NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.
As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:
- There are *n* knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to *n*. - The tournament consisted of *m* fights, in the *i*-th fight the knights that were still in the game with numbers at least *l**i* and at most *r**i* have fought for the right to continue taking part in the tournament. - After the *i*-th fight among all participants of the fight only one knight won — the knight number *x**i*, he continued participating in the tournament. Other knights left the tournament. - The winner of the last (the *m*-th) fight (the knight number *x**m*) became the winner of the tournament.
You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number *b* was conquered by the knight number *a*, if there was a fight with both of these knights present and the winner was the knight number *a*.
Write the code that calculates for each knight, the name of the knight that beat him.
|
```python
#!/usr/bin/env python3
#-*- encoding: utf-8 -*-
import sys
def main():
n, m = map(int, sys.stdin.readline().split())
res = [0 for _ in range(n)]
for i in range(m):
l, r, x = map(int, sys.stdin.readline().split())
for j in range(l,r+1):
if res[j-1] == 0 and j !=x:
res[j-1] = x
print(' '.join(map(str, res)))
return
main()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Find an *n*<=×<=*n* matrix with different numbers from 1 to *n*2, so the sum in each row, column and both main diagonals are odd.
|
```python
N = int(input())
cnt = 0
the_odd = -1
the_eve = 0
def get_with_eve_N(x, y) :
return -1
def get_with_odd_N(x, y) :
global the_odd
global the_eve
if (x + y <= N + 1 >> 1 or x + y >= N + (N + 1 >> 1) + 1 or y - x >= N + 1 >> 1 or x - y >= N + 1 >> 1) :
the_eve += 2
return the_eve
else :
the_odd += 2
return the_odd
if N % 2 == 0 :
for i in range(1, N + 1) :
for j in range(1, N + 1) :
if j == N :
print(get_with_eve_N(i, j))
else :
print(get_with_eve_N(i, j), end = ' ')
else :
for i in range(1, N + 1) :
for j in range(1, N + 1) :
if j == N :
print(get_with_odd_N(i, j))
else :
print(get_with_odd_N(i, j), end = ' ')
```
|
|
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
a = str(input()).split()
#for i in a:
if (int(a[0]) * int(a[1]))%2 == 0:
print((int(a[0]) * int(a[1]))//2)
elif (int(a[0]) * int(a[1]))%2 != 0:
print((int(a[0]) * int(a[1]))//2 )
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vova promised himself that he would never play computer games... But recently Firestorm — a well-known game developing company — published their newest game, World of Farcraft, and it became really popular. Of course, Vova started playing it.
Now he tries to solve a quest. The task is to come to a settlement named Overcity and spread a rumor in it.
Vova knows that there are *n* characters in Overcity. Some characters are friends to each other, and they share information they got. Also Vova knows that he can bribe each character so he or she starts spreading the rumor; *i*-th character wants *c**i* gold in exchange for spreading the rumor. When a character hears the rumor, he tells it to all his friends, and they start spreading the rumor to their friends (for free), and so on.
The quest is finished when all *n* characters know the rumor. What is the minimum amount of gold Vova needs to spend in order to finish the quest?
Take a look at the notes if you think you haven't understood the problem completely.
|
```python
''' Depth First Search (DFS) '''
def dfs(x, menor, a):
a.append(prec[x])
if prec[x] < menor:
menor = prec[x]
visited[x] = True
for y in graph[x]:
if not(visited[y]):
dfs(y, menor, a)
n, m = map(int, input().split())
prec = list(map(int, input().split()))
prec = [0] + prec
graph = [[] for _ in range(n + 1)]
visited = [False] * (n + 1)
total = 0
for _ in range(m):
x, y = map(int, input().split())
graph[x].append(y)
graph[y].append(x)
for i in range(1, n+1):
if visited[i] == False:
r = []
dfs(i, 10**10, r)
total += min(r)
print(total)
```
|
|
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
ip_no_days=int(input())
data_diff_days=input()
countSF=0
countFS=0
for i in range(1,len(data_diff_days)):
if data_diff_days[i-1]=='S' and data_diff_days[i]=='F':
countSF+=1
elif data_diff_days[i-1]=='F' and data_diff_days[i]=='S':
countFS+=1
else:
continue
if countSF>countFS:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya plays the sleuth with his friends. The rules of the game are as follows: those who play for the first time, that is Vasya is the sleuth, he should investigate a "crime" and find out what is happening. He can ask any questions whatsoever that can be answered with "Yes" or "No". All the rest agree beforehand to answer the questions like that: if the question’s last letter is a vowel, they answer "Yes" and if the last letter is a consonant, they answer "No". Of course, the sleuth knows nothing about it and his task is to understand that.
Unfortunately, Vasya is not very smart. After 5 hours of endless stupid questions everybody except Vasya got bored. That’s why Vasya’s friends ask you to write a program that would give answers instead of them.
The English alphabet vowels are: A, E, I, O, U, Y
The English alphabet consonants are: B, C, D, F, G, H, J, K, L, M, N, P, Q, R, S, T, V, W, X, Z
|
```python
s=input().upper().split()
s="".join(s)
l=['A','E','I','O','U','Y']
n=len(s)
if s[n-2] in l:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
This winter is so cold in Nvodsk! A group of *n* friends decided to buy *k* bottles of a soft drink called "Take-It-Light" to warm up a bit. Each bottle has *l* milliliters of the drink. Also they bought *c* limes and cut each of them into *d* slices. After that they found *p* grams of salt.
To make a toast, each friend needs *nl* milliliters of the drink, a slice of lime and *np* grams of salt. The friends want to make as many toasts as they can, provided they all drink the same amount. How many toasts can each friend make?
|
```python
n, k, l, c, d, p, nl, np = map(int, input().split())
res = min(((k*l)//nl), (c*d), (p//np))//n
print(int(res))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a rectangular board of *M*<=×<=*N* squares. Also you are given an unlimited number of standard domino pieces of 2<=×<=1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squares.
2. No two dominoes overlap.
3. Each domino lies entirely inside the board. It is allowed to touch the edges of the board.
Find the maximum number of dominoes, which can be placed under these restrictions.
|
```python
n,b=map(int,input().split())
count=0
if n%2==0 or b%2==0:
count=(n*b)//2
else:
count=((n*b)-1)//2
print(count)
```
|
|
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())
sum1=sum2=sum3=0
for i in range(n):
x,y,z=map(int,input().split())
sum1+=x
sum2+=y
sum3+=z
if sum1==0 and sum2==0 and sum3==0:
print('YES')
else:
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Appleman and Toastman play a game. Initially Appleman gives one group of *n* numbers to the Toastman, then they start to complete the following tasks:
- Each time Toastman gets a group of numbers, he sums up all the numbers and adds this sum to the score. Then he gives the group to the Appleman. - Each time Appleman gets a group consisting of a single number, he throws this group out. Each time Appleman gets a group consisting of more than one number, he splits the group into two non-empty groups (he can do it in any way) and gives each of them to Toastman.
After guys complete all the tasks they look at the score value. What is the maximum possible value of score they can get?
|
```python
def f(x):
i =-1
while 2**(i+1) <= x:
i += 1
return i
n = int(input())
s = list(map(int,input().split()))
add = 0
for i in range(len(s)):
add += s[i]
total = 0
s.sort(reverse = True)
line = []
while n > 0:
t = f(n)
line.append(t)
n -= 2**t
a,b = 0,0
for i in range(len(line)):
b += 2**line[i]
sum = 0
for j in range(a,b):
sum += s[j]
total += sum*(1+line[i])
a = b
if 2**line[0] < add:
total += add
print(total)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
According to a new ISO standard, a flag of every country should have a chequered field *n*<=×<=*m*, each square should be of one of 10 colours, and the flag should be «striped»: each horizontal row of the flag should contain squares of the same colour, and the colours of adjacent horizontal rows should be different. Berland's government asked you to find out whether their flag meets the new ISO standard.
|
```python
n, m = [int(i) for i in input().split()]
last = '.'
for i in range(n):
s = input()
if last == s[0]:
print('NO')
exit(0)
if s != s[0] * m:
print('NO')
exit(0)
last = s[0]
print('YES')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc. However, it's easy to make a mistake during the «translation». Vasya translated word *s* from Berlandish into Birlandish as *t*. Help him: find out if he translated the word correctly.
|
```python
s = list(input())
t = input()
n = len(s)
for i in range(n//2):
temp = s[i]
s[i] = s[n - (i+1)]
s[n - (i+1)] = temp
new_s = ''.join(map(str, s))
if t == new_s:
print('YES')
else:
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Let's consider one interesting word game. In this game you should transform one word into another through special operations.
Let's say we have word *w*, let's split this word into two non-empty parts *x* and *y* so, that *w*<==<=*xy*. A split operation is transforming word *w*<==<=*xy* into word *u*<==<=*yx*. For example, a split operation can transform word "wordcut" into word "cutword".
You are given two words *start* and *end*. Count in how many ways we can transform word *start* into word *end*, if we apply exactly *k* split operations consecutively to word *start*.
Two ways are considered different if the sequences of applied operations differ. Two operation sequences are different if exists such number *i* (1<=≤<=*i*<=≤<=*k*), that in the *i*-th operation of the first sequence the word splits into parts *x* and *y*, in the *i*-th operation of the second sequence the word splits into parts *a* and *b*, and additionally *x*<=≠<=*a* holds.
|
```python
MOD=10**9+7
# @cache
def slove():
# if v==0: return 0
# n=int(input())
a=str(input())
b=str(input())
n=len(a)
k=int(input())
if n==2:
if a==b:
print('1' if k&1==0 else '0')
elif a[::-1]==b:
print('1' if k&1 else '0')
else:
print('0')
return
if k==0:
print('1' if a==b else '0')
return
cut=[]
for i in range(n):
w=a[i:]+a[:i]
if w==b:
cut.append(i)
if len(cut)==0:
print('0')
# elif len(cut)>=1:
else:
f=1 if a==b else 0
for i in range(k):
f=pow(n-1,i)*len(cut)-f
f%=MOD
print(f)
return
return
# t=int(input())
t=1
# M=1<<30
for _ in range(t):
# v=int(input())
slove()
# print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Email address in Berland is a string of the form *A*@*B*, where *A* and *B* are arbitrary strings consisting of small Latin letters.
Bob is a system administrator in «Bersoft» company. He keeps a list of email addresses of the company's staff. This list is as a large string, where all addresses are written in arbitrary order, separated by commas. The same address can be written more than once.
Suddenly, because of unknown reasons, all commas in Bob's list disappeared. Now Bob has a string, where all addresses are written one after another without any separators, and there is impossible to determine, where the boundaries between addresses are. Unfortunately, on the same day his chief asked him to bring the initial list of addresses. Now Bob wants to disjoin addresses in some valid way. Help him to do that.
|
```python
s = input()
indexsi = []
for i in range(len(s)):
if s[i] == "@":
indexsi.append(i)
ans = ""
left = 0
temp = True
#print(*indexsi)
for i in range(len(indexsi)):
if indexsi[i] == 0 or indexsi[i] == len(s)-1:
temp = False
break
if i != 0 and indexsi[i] - indexsi[i-1] <= 2:
temp = False
break
ans += s[left:indexsi[i]+2]
left = indexsi[i]+2
if i != len(indexsi)-1:
ans += ','
if temp:
print(ans)
else:
print("No solution")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array *a* consisting of *n* distinct integers.
Unfortunately, the size of *a* is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question correctly: is it possible to sort the array *a* (in increasing order) by reversing exactly one segment of *a*? See definitions of segment and reversing in the notes.
|
```python
def check(arr):
temp = sorted(arr)
n = len(arr)
cnt = 0
segment = False
p1 = -1
p2 = -2
for i in range(n):
if arr[i] != temp[i]:
if not segment :
segment = True
p1 = i
elif segment :
segment = False
p2 = i
cnt += 1
if cnt > 1:
print("no")
return
if cnt == 0 :
print("yes")
print("1 1")
return
for i in range(p2-1, p1+1, -1):
if arr[i] > arr[i-1] :
print("no")
return
print("yes")
p1 += 1
if p1 > p2 :
p1, p2 = p2, p1
print(f"{p1} {p2}")
n = int(input())
arr = [int(i) for i in input().split()]
ispossible = check(arr)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little Susie loves strings. Today she calculates distances between them. As Susie is a small girl after all, her strings contain only digits zero and one. She uses the definition of Hamming distance:
We will define the distance between two strings *s* and *t* of the same length consisting of digits zero and one as the number of positions *i*, such that *s**i* isn't equal to *t**i*.
As besides everything else Susie loves symmetry, she wants to find for two strings *s* and *t* of length *n* such string *p* of length *n*, that the distance from *p* to *s* was equal to the distance from *p* to *t*.
It's time for Susie to go to bed, help her find such string *p* or state that it is impossible.
|
```python
a = input()
b = input()
x = str(int(a) ^ int(b))
if x.count("1") %2 != 0 :
print("IMPOSSIBLE")
else :
res = ""
flag1 = True
for idx , value in enumerate(x) :
if value == "0":
res += str(a)[idx]
else:
if flag1 :
res += "1"
flag1 =False
else:
res += "0"
flag1 = True
print(res)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
— I experienced so many great things.
— You gave me memories like dreams... But I have to leave now...
— One last request, can you...
— Help me solve a Codeforces problem?
— ......
— What?
Chtholly has been thinking about a problem for days:
If a number is palindrome and length of its decimal representation without leading zeros is even, we call it a zcy number. A number is palindrome means when written in decimal representation, it contains no leading zeros and reads the same forwards and backwards. For example 12321 and 1221 are palindromes and 123 and 12451 are not. Moreover, 1221 is zcy number and 12321 is not.
Given integers *k* and *p*, calculate the sum of the *k* smallest zcy numbers and output this sum modulo *p*.
Unfortunately, Willem isn't good at solving this kind of problems, so he asks you for help!
|
```python
def main(length, r, num, rev, length2):
global left, res, p
if length == 0:
if left == 0:
return
res += num * r * 10 + rev
res %= p
left -= 1
else:
for j in range(10):
if left == 0:
return
main(length - 1, r, num * 10 + j, j * (10 ** length2) + rev, length2 + 1)
k, p = map(int, input().split())
left = k
res = 0
indicator = True
for length in range(1, 100):
if not indicator:
break
r = 10 ** (length - 1)
for i in range(1, 10):
if left == 0:
indicator = False
break
main(length - 1, r, i, i, 1)
print(res)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given an array of positive integers *a*1,<=*a*2,<=...,<=*a**n*<=×<=*T* of length *n*<=×<=*T*. We know that for any *i*<=><=*n* it is true that *a**i*<==<=*a**i*<=-<=*n*. Find the length of the longest non-decreasing sequence of the given array.
|
```python
f = lambda: map(int, input().split())
n, m = f()
t = list(f())
s = [0] * 301
d = s[:]
for i in t: d[i] += 1
for i in t * min(m, 2 * n): s[i] = max(s[:i + 1]) + 1
print(max(s) + max((m - n * 2) * max(d), 0))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A and B are preparing themselves for programming contests.
B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.
Initially, the compiler displayed *n* compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix some mistake and then another one mistake.
However, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared — the compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, compilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change.
Can you help B find out exactly what two errors he corrected?
|
```python
n = int(input())
lst = [int(i) for i in input().split()]
lst.sort()
for i in range(2):
new_lst = [int(i) for i in input().split()]
new_lst.sort()
#print(new_lst)
#print(lst)
fl = True
for i in range(len(new_lst)):
if new_lst[i] != lst[i]:
print(lst[i])
fl = False
break
if fl:
print(lst[-1])
lst = new_lst.copy()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little girl Alyona is in a shop to buy some copybooks for school. She study four subjects so she wants to have equal number of copybooks for each of the subjects. There are three types of copybook's packs in the shop: it is possible to buy one copybook for *a* rubles, a pack of two copybooks for *b* rubles, and a pack of three copybooks for *c* rubles. Alyona already has *n* copybooks.
What is the minimum amount of rubles she should pay to buy such number of copybooks *k* that *n*<=+<=*k* is divisible by 4? There are infinitely many packs of any type in the shop. Alyona can buy packs of different type in the same purchase.
|
```python
n, a, b, c = map(int, input().split())
x = n%4
ans = 0
if x == 0:
ans = 0
elif x == 3:
ans = a
elif x == 2:
ans = min(a*2,b)
else:
ans = min(a*3,a+b,c)
print (ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Polycarpus takes part in the "Field of Wonders" TV show. The participants of the show have to guess a hidden word as fast as possible. Initially all the letters of the word are hidden.
The game consists of several turns. At each turn the participant tells a letter and the TV show host responds if there is such letter in the word or not. If there is such letter then the host reveals all such letters. For example, if the hidden word is "abacaba" and the player tells the letter "a", the host will reveal letters at all positions, occupied by "a": 1, 3, 5 and 7 (positions are numbered from left to right starting from 1).
Polycarpus knows *m* words of exactly the same length as the hidden word. The hidden word is also known to him and appears as one of these *m* words.
At current moment a number of turns have already been made and some letters (possibly zero) of the hidden word are already revealed. Previously Polycarp has told exactly the letters which are currently revealed.
It is Polycarpus' turn. He wants to tell a letter in such a way, that the TV show host will assuredly reveal at least one more letter. Polycarpus cannot tell the letters, which are already revealed.
Your task is to help Polycarpus and find out the number of letters he can tell so that the show host will assuredly reveal at least one of the remaining letters.
|
```python
n=int(input())
s=input()
let=dict()
a=[]
c=0
for i in range(n):
let[s[i]]=let.get(s[i],0)+1
m=int(input())
for i in range(m):
a.append(input())
for i in range(ord('a'),ord('z')+1):
if let.get(chr(i),0)!=0: continue
flag2=1
for j in range(m):
flag1=1
letc=dict()
for k in range(n):
if s[k]=="*" and let.get(a[j][k],0)!=0:
flag1=0
break
if s[k]=="*":
letc[a[j][k]]=letc.get(a[j][k],0)+1
elif s[k]!=a[j][k]:
flag1=0
if flag1 and letc.get(chr(i),0)==0:
flag2=0
if flag2:
c=+1
print(c)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
wHAT DO WE NEED cAPS LOCK FOR?
Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage.
Let's consider that a word has been typed with the Caps lock key accidentally switched on, if:
- either it only contains uppercase letters; - or all letters except for the first one are uppercase.
In this case we should automatically change the case of all letters. For example, the case of the letters that form words "hELLO", "HTTP", "z" should be changed.
Write a program that applies the rule mentioned above. If the rule cannot be applied, the program should leave the word unchanged.
|
```python
word = input()
if word == word.upper():
print(word.swapcase())
elif word == word.capitalize().swapcase():
print(word.swapcase())
else:
print(word)
```
|
|
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
#####--------------Template Begin-------------------####
import math
import sys
#input = sys.stdin.readline
def ri(): #Regular input
return input()
def ii(): #integer input
return int(input())
def li(): #list input
return input().split()
def mi(): #map input
return list(map(int, input().split()))
#####---------------Template Ends-------------------######
n,x=mi()
d=0
for i in range(n):
line=ri().split()
if line[0]=="+":
x+=int(line[1])
else:
if x>=int(line[1]):
x-=int(line[1])
else:
d+=1
print(x, d)
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.