source stringclasses 3
values | instruction stringlengths 23 3.97k | input stringclasses 1
value | output stringlengths 1 3.75k |
|---|---|---|---|
MatrixStudio/Codeforces-Python-Submissions | Devu is a dumb guy, his learning curve is very slow. You are supposed to teach him *n* subjects, the *i**th* subject has *c**i* chapters. When you teach him, you are supposed to teach all the chapters of a subject continuously.
Let us say that his initial per chapter learning power of a subject is *x* hours. In other ... | ```python
n,x=map(int,input().split())
w=sorted(list(map(int,input().split())))
s,i=0,0
while True:
s+=(w[i]*x)
if x>1:
x-=1
i+=1
if i==n:
break
print (s)
``` | |
MatrixStudio/Codeforces-Python-Submissions | PolandBall is a young, clever Ball. He is interested in prime numbers. He has stated a following hypothesis: "There exists such a positive integer *n* that for each positive integer *m* number *n*·*m*<=+<=1 is a prime number".
Unfortunately, PolandBall is not experienced yet and doesn't know that his hypothesis is inc... | ```python
val=int(input())
if (val % 2 == 0):
print(2)
else:
print(1)
``` | |
MatrixStudio/Codeforces-Python-Submissions | You are given a graph with $n$ nodes and $m$ directed edges. One lowercase letter is assigned to each node. We define a path's value as the number of the most frequently occurring letter. For example, if letters on a path are "abaca", then the value of that path is $3$. Your task is find a path whose value is the large... | ```python
from collections import deque, defaultdict
n, m = map(int, input().split())
letters = input().strip()
graph = defaultdict(list)
indegree = [0] * n
q = deque([])
mat = [[0] * 26 for _ in range(n)]
for _ in range(m):
x, y = map(int, input().split())
graph[x-1].append(y-1)
indegree[y-1]... | |
MatrixStudio/Codeforces-Python-Submissions | Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.
Rules of the game are very simple: at first number of rounds *n* is defined.... | ```python
n = int(input())
m = 0
c = 0
for i in range(n):
x,y = map(int,input().split())
if x>y:
m = m+1
elif x<y:
c = c+1
if (m>c):
print("Mishka")
elif m<c:
print("Chris")
else:
print("Friendship is magic!^^")
``` | |
MatrixStudio/Codeforces-Python-Submissions | It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not en... | ```python
n=int(input())
ans=1
for i in range(0,n):
e=int(input())
ans*=e
print(ans)
``` | |
MatrixStudio/Codeforces-Python-Submissions | The following problem is well-known: given integers *n* and *m*, calculate
where 2*n*<==<=2·2·...·2 (*n* factors), and denotes the remainder of division of *x* by *y*.
You are asked to solve the "reverse" problem. Given integers *n* and *m*, calculate | ```python
a = int(input())
b = int(input())
c = 2**a
print(b%c)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th... | ```python
x=input()
a=x
lowercount=0
uppercount=0
x=list(map(str,str(x)))
for i in x:
if i==i.lower():
lowercount=lowercount+1
else:
uppercount=uppercount+1
if(lowercount>=uppercount):
a=a.lower()
else:
a=a.upper()
print(a)
``` | |
MatrixStudio/Codeforces-Python-Submissions | You've got a rectangular parallelepiped with integer edge lengths. You know the areas of its three faces that have a common vertex. Your task is to find the sum of lengths of all 12 edges of this parallelepiped. | ```python
l = list(map(int, input().split()))
a = int(((l[0]*l[2])//l[1])**0.5)
b = int(((l[0]*l[1])//l[2])**0.5)
c = int(((l[1]*l[2])//l[0])**0.5)
print(4*(a+b+c))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Theatre Square in the capital city of Berland has a rectangular shape with the size *n*<=×<=*m* meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size *a*<=×<=*a*.
What is the least number of flagstones needed to pave the... | ```python
n, m, a = map(int, input().split())
side1 = n % a
side2 = m % a
if side1 != 0:
val1 = n // a + 1
else:
val1 = n // a
if side2 != 0:
val2 = m // a + 1
else:
val2 = m // a
print(val1 * val2)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Permutation *p* is an ordered set of integers *p*1,<=<=<=*p*2,<=<=<=...,<=<=<=*p**n*, consisting of *n* distinct positive integers not larger than *n*. We'll denote as *n* the length of permutation *p*1,<=<=<=*p*2,<=<=<=...,<=<=<=*p**n*.
Your task is to find such permutation *p* of length *n*, that the group of number... | ```python
n, k = map(int, input().split(' '))
o = n - k
print(1, end = ' ')
for i in range(2, o + 1):
print(i, end = ' ')
mb = n
mm = o + 1
while mb >= mm:
print(mb, end = ' ')
mb -= 1
if mb >= mm:
print(mm, end = ' ')
mm += 1
``` | |
MatrixStudio/Codeforces-Python-Submissions | Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited *n* his friends there.
If... | ```python
n=int(input())
p=list(map(int,input().split()))
s=list(range(1,101))
v=[]
for i in range(n):
c=p.index(min(p))
v.append(s[c])
p[c]=10000
print(*v)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry.
He bought *n* pieces of jewelry. The *i*-th piece has price equal to *i*<=+<=1, that is, the prices of the jewelry are 2,<=3,<=4,<=... *n*<=+<=1.
Watson gave Sherlock a challenge to color these jewelry pie... | ```python
n=int(input())
isp=[1]*(n+2)
isp[1]=2
for i in range(2,n+2):
if isp[i]==1:
for j in range(i*i,n+2,i):
isp[i]=2
print(1 if n<=2 else 2)
print(' '.join(str(isp[i]) for i in range(2,n+2)))
``` | |
MatrixStudio/Codeforces-Python-Submissions | You are given the current time in 24-hour format hh:mm. Find and print the time after *a* minutes.
Note that you should find only the time after *a* minutes, see the examples to clarify the problem statement.
You can read more about 24-hour format here [https://en.wikipedia.org/wiki/24-hour_clock](https://en.wikipedi... | ```python
a,b=map(int,input().split(":"))
z=int(input())
k=z//60;z=z%60
a=(a+k)%24
if b+z>59:
a=(a+1)%24;b=(b+z)%60
else:b+=z
a=str(a);b=str(b)
if len(a)==1:a="0"+a
if len(b)==1:b="0"+b
print(a+":"+b)
``` | |
MatrixStudio/Codeforces-Python-Submissions | The School №0 of the capital of Berland has *n* children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value *t**i*:
- *t**i*<==<=1, if the *i*-th child is good at prog... | ```python
n = int(input())
t = list(map(int, input().split()))
one = []
two = []
three = []
for i in range(n):
if t[i] == 1:
one.append(i+1)
elif t[i] == 2:
two.append(i+1)
else:
three.append(i+1)
minNumAmnt = min(len(one), len(two), len(three))
print(minNumAmnt)
fo... | |
MatrixStudio/Codeforces-Python-Submissions | Theatre Square in the capital city of Berland has a rectangular shape with the size *n*<=×<=*m* meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size *a*<=×<=*a*.
What is the least number of flagstones needed to pave the... | ```python
a,s,d=list(map(int,input().split()))
q=a*s
w=d*d
if(q%w==0):
print(int(q/w))
else:
print(q%w)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Iahub is very proud of his recent discovery, propagating trees. Right now, he invented a new tree, called xor-tree. After this new revolutionary discovery, he invented a game for kids which uses xor-trees.
The game is played on a tree having *n* nodes, numbered from 1 to *n*. Each node *i* has an initial value *init**... | ```python
'''input
10
2 1
3 1
4 2
5 1
6 2
7 5
8 6
9 8
10 5
1 0 1 1 0 1 0 1 0 1
1 0 1 0 0 1 1 1 0 1
'''
from sys import stdin, setrecursionlimit
from collections import defaultdict
setrecursionlimit(15000)
def counter(num):
if num == 0:
return 1
else:
return 0
def flip_me(original, count, index):
if count % ... | |
MatrixStudio/Codeforces-Python-Submissions | Mr. Kitayuta has kindly given you a string *s* consisting of lowercase English letters. You are asked to insert exactly one lowercase English letter into *s* to make it a palindrome. A palindrome is a string that reads the same forward and backward. For example, "noon", "testset" and "a" are all palindromes, while "tes... | ```python
def is_p(s):
return s==s[::-1]
s=input()
for i in range(len(s)):
for c in 'abcdefghijklmnopqrstuvwxyz':
if is_p(s[:i]+c+s[i:]):
print(s[:i]+c+s[i:])
exit(0)
print("NA")
``` | |
MatrixStudio/Codeforces-Python-Submissions | Polycarp has interviewed Oleg and has written the interview down without punctuation marks and spaces to save time. Thus, the interview is now a string *s* consisting of *n* lowercase English letters.
There is a filler word ogo in Oleg's speech. All words that can be obtained from ogo by adding go several times to the... | ```python
import re
input()
print(re.sub(r'o(go)+',"*"*3,input()))
``` | |
MatrixStudio/Codeforces-Python-Submissions | You are given a chessboard of size 1<=×<=*n*. It is guaranteed that *n* is even. The chessboard is painted like this: "BWBW...BW".
Some cells of the board are occupied by the chess pieces. Each cell contains no more than one chess piece. It is known that the total number of pieces equals to .
In one step you can move... | ```python
n = int(input())
n = n/2
a = [int(x) for x in input().split(" ")]
sorted(a)
p1 = 1
p2 = 2
r1 = 0
r2 = 0
for element in a:
r1 = r1 + abs(element-p1)
r2 = r2 + abs(element-p2)
p1 = p1 + 2
p2 = p2 + 2
print(min(r1, r2))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number *a* and Antisimon receives number *b*. They also have a heap of *n* stones. The players take turns to make a move and Simon starts. During a move a player should take... | ```python
a,b,n = map(int, input().split())
i = 0
b1 = n
b2 = n
a1 = a
a2 = b
while n>=0:
if i%2 == 0:
while b1>0:
c = a1
a1 = b1
b1 = c%a1
n -= a1
i += 1
b2 = n
else:
while b2>0:
c = a2
a2 = b2... | |
MatrixStudio/Codeforces-Python-Submissions | Let's call an undirected graph $G = (V, E)$ relatively prime if and only if for each edge $(v, u) \in E$ $GCD(v, u) = 1$ (the greatest common divisor of $v$ and $u$ is $1$). If there is no edge between some pair of vertices $v$ and $u$ then the value of $GCD(v, u)$ doesn't matter. The vertices are numbered from $1$ to... | ```python
from fractions import gcd
n,m = map(int,input().split())
sol = []
for i in range(1,n+1):
for j in range(i+1,n+1):
if gcd(i,j) == 1:
sol.append('{} {}'.format(i,j))
if len(sol)>=m:break
if len(sol)>=m:
print ('Possible')
print ('\n'.join(sol[:m]))
else:
... | |
MatrixStudio/Codeforces-Python-Submissions | When Valera has got some free time, he goes to the library to read some books. Today he's got *t* free minutes to read. That's why Valera took *n* books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to *n*. Valera needs *a**i* minutes to... | ```python
a,b=map(int, input().split())
A=list(map(int, input().split()))
t=0
k=0
for x in A:
t+=x
if t>b:
t-=A[k]
k+=1
print(a-k)
``` | |
MatrixStudio/Codeforces-Python-Submissions | A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy... | ```python
n=int(input())
s=int()
f=0
for k in range(n):
s=0
m=0
r=0
a=[int(i) for i in input().split(" ")]
for i in range(len(a)):
s=s+a[i]
m=m+s
f=f+m
if m>0:
r=r+1
elif m<0:
r=r-1
k=k+r
if f==0 and k<=n:
print("YES")
else:
pri... | |
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... | ```python
n_x = input().split();
n = int(n_x[0]);
x = int(n_x[1]);
dis_count = 0;
for i in range(n):
inp = input().split();
if inp[0] == '+':
x += int(inp[1]);
else:
if int(inp[1]) < x:
x -= int(inp[1]);
else:
dis_count += 1;
print(x," ",di... | |
MatrixStudio/Codeforces-Python-Submissions | Vasya has got two number: *a* and *b*. However, Vasya finds number *a* too short. So he decided to repeat the operation of lengthening number *a* *n* times.
One operation of lengthening a number means adding exactly one digit to the number (in the decimal notation) to the right provided that the resulting number is di... | ```python
def main():
a,b,n=map(int,input().split())
mon = a
cnt = 0
non_exist = False
while n!=0:
for i in range(1,10):
if (a*10+i) %b == 0:
a = a*10+i
break
n-=1
if mon == a:
print(-1)
else:
print(a)
... | |
MatrixStudio/Codeforces-Python-Submissions | Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word.
Note, that during capitalization all the letters except the first one remains unchanged. | ```python
s=input()
if ord(s[0])>90:
a=chr(ord(s[0])-32)
c=a
for i in range(1,len(s)):
c+=str(s[i])
print(c)
else:
print(s)
``` | |
MatrixStudio/Codeforces-Python-Submissions | There are *n* cities in Bearland, numbered 1 through *n*. Cities are arranged in one long row. The distance between cities *i* and *j* is equal to |*i*<=-<=*j*|.
Limak is a police officer. He lives in a city *a*. His job is to catch criminals. It's hard because he doesn't know in which cities criminals are. Though, he... | ```python
# Problem Link: https://codeforces.com/problemset/problem/680/B
# Problem Status:
# -------------------- SEPARATOR --------------------
def TheAmazingFunction(Arr: list, A):
Answer = 0
i = A - 1
j = A - 1
while i >= 0 or j < len(Arr):
if i == j:
if Arr[i] == 1:... | |
MatrixStudio/Codeforces-Python-Submissions | One day Vasya came across three Berland coins. They didn't have any numbers that's why Vasya didn't understand how their denominations differ. He supposed that if one coin is heavier than the other one, then it should be worth more. Vasya weighed all the three pairs of coins on pan balance scales and told you the resul... | ```python
dict_ = {'A':1,'B':1,'C':1}
def solve_dict(dict_):
items = sorted(dict_.values())
for j in range(1,len(items)):
if items[j] - items[j-1] > 1:
return 'Impossible'
return ''.join(sorted(dict_, key=dict_.get))
for i in range(3):
s = input()
a = s[0]
b = s... | |
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 ... | ```python
M = int(input("M = "))
N = int(input("N = "))
print((N // 2) * M + (N % 2) * (M // 2))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings *a* and *b* of equal length are called equivalent in one of the two cases:
1. They are equal. 1. If we split string *a* into two halves of the same size *a*1 and *a*2, and string *b* into two halves of the same size ... | ```python
def sortString(str):
length = len(str)
if (length % 2 != 0):
return str
length //= 2
left = sortString(str[:length])
right = sortString(str[length:])
if left < right:
return left + right
else:
return right + left
a = input()
b = input()
print("YES" if sort... | |
MatrixStudio/Codeforces-Python-Submissions | Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya wonders eagerly what minimum lucky number has the sum of digits equal to *n*. Help him cope wi... | ```python
n = int(input())
ans = ""
printou = False
hasSeven = False
hasFour = False
while(n>0):
if n >= 7 and n-7 >= 4:
n-=7
ans+="7"
hasSeven = True
elif n >=4:
n-=4
ans+="4"
hasFour = True
else:
print(-1)
printou = True
break
if(not printou):
if hasSeven and hasFour:
p... | |
MatrixStudio/Codeforces-Python-Submissions | Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot.
He wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fence corners at a single angle *a*.
Will the robot be able to build the fence Emuska... | ```python
t = int(input())
for i in range(t):
a = int(input())
n = 3
while n < 180:
if a == 180*(n-2)/n:
print('YES')
break
else:
n += 1
if n >= 180:
print('NO')
``` | |
MatrixStudio/Codeforces-Python-Submissions | There are *n* cities numbered from 1 to *n* in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance ... | ```python
from collections import defaultdict
def dijkstra(graph, start, end):
import heapq
heap = [(0, start)] # cost from start node,end node
visited = set()
while heap:
(cost, u) = heapq.heappop(heap)
if u in visited:
continue
visited.add(u)
... | |
MatrixStudio/Codeforces-Python-Submissions | A family consisting of father bear, mother bear and son bear owns three cars. Father bear can climb into the largest car and he likes it. Also, mother bear can climb into the middle car and she likes it. Moreover, son bear can climb into the smallest car and he likes it. It's known that the largest car is strictly larg... | ```python
v1,v2,v3,vm=map(int,input().split())
if vm>2*v3:
print(-1)
else:
if v1-2*vm >0 and v2 -2*v3 >0:
print(v1,v2,v3)
else:
print(-1)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited *n* his friends there.
If... | ```python
x=int(input());a=input().split();print(*[a.index(str(i+1))+1for i in range(x)])
``` | |
MatrixStudio/Codeforces-Python-Submissions | Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number *a* and Antisimon receives number *b*. They also have a heap of *n* stones. The players take turns to make a move and Simon starts. During a move a player should take... | ```python
a,b,n=[int(i) for i in input().split()]
for i in range(100):
if i%2==0:
if n==0:
print(1)
break
elif n%a==0:
n=n-a
else:
n-=1
else:
if n==0:
print(0)
break
elif n%b==0:
... | |
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 lik... | ```python
t=int(input())
for i in range(t):
a=input()
n=len(a)
s1 = a[0]
l1 = a[-1]
length=len(a[1:-1])
if n>10:
print(f"{s1}{length}{l1}")
else:
print(a)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Olesya loves numbers consisting of *n* digits, and Rodion only likes numbers that are divisible by *t*. Find some number that satisfies both of them.
Your task is: given the *n* and *t* print an integer strictly larger than zero consisting of *n* digits that is divisible by *t*. If such number doesn't exist, print <=-... | ```python
from collections import defaultdict
import math
def pug_func(s: str) -> int:
n, t = s.split(" ")
n = int(n)
t = int(t)
num = 10 ** (n - 1)
for i in range(1, 11):
if (num * i) % t == 0:
return num * i
return -1
t = input()
x = ... | |
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 th... | ```python
def word(s):
c = 0
for i in s:
print(ord(i))
if 97<=ord(i)<=122:
c += 1
else:
c -= 1
print(c)
print(c)
if c >=0 :
return s.lower()
return s.upper()
print(word(input()))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Once when Gerald studied in the first year at school, his teacher gave the class the following homework. She offered the students a string consisting of *n* small Latin letters; the task was to learn the way the letters that the string contains are written. However, as Gerald is too lazy, he has no desire whatsoever to... | ```python
s = input()
k = int(input())
t = 'a'
fr = [0] * 26
for i in s:
fr[ord('a') - 97]+=1
while k != 0:
try:
x = min(i for i in fr if i > 0)
except:
x = 0
if x == 0:
break
if k >= x:
fr[fr.index(x)] = 0
k -= x
else:
k = 0
ans ... | |
MatrixStudio/Codeforces-Python-Submissions | Little Petya is learning to play chess. He has already learned how to move a king, a rook and a bishop. Let us remind you the rules of moving chess pieces. A chessboard is 64 square fields organized into an 8<=×<=8 table. A field is represented by a pair of integers (*r*,<=*c*) — the number of the row and the number of... | ```python
# MC521 - Desafios de Programacao I - 1s2021
# Contest: 21/05/2021
# Problema D: Rook, Bishop and King
# leitura da posicao inicial e final
r1, c1, r2, c2 = map(int, input().split())
# movimentos necessarios para a torre
R = 0
if(r1 != r2): R += 1
if(c1 != c2): R += 1
# movimentos necessarios para o bispo
... | |
MatrixStudio/Codeforces-Python-Submissions | Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity.
There are *n* columns of toy cubes in the box arranged in a line. The *i*-th column contains *a**i* cubes. At first, the gravity in the box is... | ```python
n = int(input())
cubes = list(map(int, input().split()))
# Sort the array in non-decreasing order
cubes.sort()
# Output the sorted array
print(*cubes)
``` | |
MatrixStudio/Codeforces-Python-Submissions | You are given a string *s* consisting of |*s*| small english letters.
In one move you can replace any character of this string to the next character in alphabetical order (a will be replaced with b, s will be replaced with t, etc.). You cannot replace letter z with any other letter.
Your target is to make some number... | ```python
s = list(input())
alph = "abcdefghijklmnopqrstuvwxyz"
ind = 0
for i, char in enumerate(s):
if ind == ord(char) - 97:
ind += 1
elif ind == ord(char) - 97 + 1:
s[i] = chr(ord(char) + 1)
ind += 1
if ind == 26:
print("".join(s))
else:
print(-1)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?
You are given a system of equations:
You should count, how many there are pairs of int... | ```python
n, m, answer = 0, 0, 0
n, m = map(int, input().split())
i = 0
while i * i <= n and i <= m:
b = n - i * i
if i + b * b == m:
answer += 1
i += 1
print(answer)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Codeforces user' handle color depends on his rating — it is red if his rating is greater or equal to 2400; it is orange if his rating is less than 2400 but greater or equal to 2200, etc. Each time participant takes part in a rated contest, his rating is changed depending on his performance.
Anton wants the color of hi... | ```python
s = 'NO'
for _ in range(int(input())):
t = input().split(' ')
if 2400 <= int(t[1]) < int(t[2]):
s = 'YES'
print(s)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number *a* and Antisimon receives number *b*. They also have a heap of *n* stones. The players take turns to make a move and Simon starts. During a move a player should take... | ```python
a, b, c = [int(x) for x in input().split()]
def nod(lhs, rhs):
if rhs==0:
return lhs
else:
return nod(rhs, lhs%rhs)
d=nod(a,c)
k=0
while c>0:
if k==0:
d=nod(a,c)
else:
d=nod(b,c)
c -= d
k = (k + 1) % 2
print((k + 1) % 2)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line.
Unfortunately, from time to ti... | ```python
s = list(input())
s.pop(0)
s.pop()
s = ''.join(s)
s = set(s.split(', '))
print(len(s))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Valera is a collector. Once he wanted to expand his collection with exactly one antique item.
Valera knows *n* sellers of antiques, the *i*-th of them auctioned *k**i* items. Currently the auction price of the *j*-th object of the *i*-th seller is *s**ij*. Valera gets on well with each of the *n* sellers. He is perfec... | ```python
n,v = map(int,input().split())
l1 = []
for i in range(n):
k = list(map(int,input().split()))
if min(k[1:]) < v:
l1.append(i+1)
print(len(l1))
print(*l1)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob.
Right now, Limak and Bob weigh *a* and *b* respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight.
Limak eats a lot and his weight is tripled after every year, while Bob's we... | ```python
num = input().split(" ")
i=0
a,b = int(num[0]),int(num[1])
while(True):
a *= 3
b *= 2
i += 1
if(a>b):
print(i)
break
``` | |
MatrixStudio/Codeforces-Python-Submissions | As you may know, MemSQL has American offices in both San Francisco and Seattle. Being a manager in the company, you travel a lot between the two cities, always by plane.
You prefer flying from Seattle to San Francisco than in the other direction, because it's warmer in San Francisco. You are so busy that you don't rem... | ```python
int(input());k=input();print("YES" if k.count("SF")>k.count("FS") else "NO")
``` | |
MatrixStudio/Codeforces-Python-Submissions | Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
One day Petya came across an interval of numbers [*a*,<=*a*<=+<=*l*<=-<=1]. Let *F*(*x*) be the numb... | ```python
import itertools
def F(x):
q = 0
for i in str(x):
if i == '4' or i == '7':
q += 1
return q
a, l = map(lambda x: int(x), input().split())
Fa = [F(i) for i in range(a, a+l)]
for b in itertools.count(a+1):
for i in range(l):
if Fa[i] != F(b+i):
... | |
MatrixStudio/Codeforces-Python-Submissions | Recently, you bought a brand new smart lamp with programming features. At first, you set up a schedule to the lamp. Every day it will turn power on at moment $0$ and turn power off at moment $M$. Moreover, the lamp allows you to set a program of switching its state (states are "lights on" and "lights off"). Unfortunate... | ```python
m,n=map(int,input().split())
l1=[]
l=[0]+list(map(int,input().split()))+[n]
for i in range(m+1):
l1+=[l[i+1]-l[i]]
l3=max(sum(l[::2]),sum(l[1::2]))
for i in range(0,len(l1),2):
if l1[i]!=1:
l3=max(l3,sum(l1[:i+1:2])-1+sum(l1[i+1::2]))
for i in range(1, len(l1), 2):
if l1[i]... | |
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 th... | ```python
a = input()
zag = sum(map(str.isupper, a))
stro = sum(map(str.islower, a))
if zag == stro:
print(a.lower())
elif zag > stro:
print(a.upper())
else:
print(a.lower())
``` | |
MatrixStudio/Codeforces-Python-Submissions | To stay woke and attentive during classes, Karen needs some coffee!
Karen, a coffee aficionado, wants to know the optimal temperature for brewing the perfect cup of coffee. Indeed, she has spent some time reading several recipe books, including the universally acclaimed "The Art of the Covfefe".
She knows *n* coffee ... | ```python
rec = [0]*200001
n,q,r = map(int,input().split())
arr = []
for _ in range(n):
a,b=map(int,input().split())
arr.append((a,b))
for i in arr:
for x in range(i[0],i[1]+1):
rec[x]+=1
for _ in range(r):
a,b=map(int,input().split())
ans = 0
for i in range(a,b+1):
if rec[i]>=q:... | |
MatrixStudio/Codeforces-Python-Submissions | You are given a set of integer numbers, initially it is empty. You should perform *n* queries.
There are three different types of queries:
- 1 *l* *r* — Add all missing numbers from the interval [*l*,<=*r*] - 2 *l* *r* — Remove all present numbers from the interval [*l*,<=*r*] - 3 *l* *r* — Invert the interval [*... | ```python
from collections import defaultdict
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def f(z, l, r):
j = l // m
c = 0
if z == 0:
return
elif z == 1:
for i in range(l, r):
c += 1 - a[i]
a[i] = 1
elif z == 2... | |
MatrixStudio/Codeforces-Python-Submissions | Petya is a big fan of mathematics, especially its part related to fractions. Recently he learned that a fraction is called proper iff its numerator is smaller than its denominator (*a*<=<<=*b*) and that the fraction is called irreducible if its numerator and its denominator are coprime (they do not have positive co... | ```python
import math
n=int(input())
p,q=n//2,n-n//2
while math.gcd(a,b)!=1:p,q=p-1,q+1
print(p,q)
``` | |
MatrixStudio/Codeforces-Python-Submissions | A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string *s* consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string *s* to be distinct. Substring is a string formed by some... | ```python
from collections import Counter
n=int(input())
s=str(input())
count=Counter(s)
c=0
for value in count.values():
if value>=2:
c=c+(value-1)
print(c)
``` | |
MatrixStudio/Codeforces-Python-Submissions | The School №0 of the capital of Berland has *n* children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value *t**i*:
- *t**i*<==<=1, if the *i*-th child is good at prog... | ```python
n=int(input())
a=list(map(int,input().split()))
l=min(a.count(1),a.count(2),a.count(3))
for i in range(l):
print(a.index(1)+1,a.index(2)+1,a.index(3)+1)
a[a.index(1)]=0
a[a.index(2)]=0
a[a.index(3)]=0
if l==0:
print(0)
``` | |
MatrixStudio/Codeforces-Python-Submissions | To make a paper airplane, one has to use a rectangular piece of paper. From a sheet of standard size you can make $s$ airplanes.
A group of $k$ people decided to make $n$ airplanes each. They are going to buy several packs of paper, each of them containing $p$ sheets, and then distribute the sheets between the people.... | ```python
k,n,s,p=map(int,input().split())
a=(n//s)+1
b=k/p
ans=(a*b)+1
print(int(ans))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Mashmokh works in a factory. At the end of each day he must turn off all of the lights.
The lights on the factory are indexed from 1 to *n*. There are *n* buttons in Mashmokh's room indexed from 1 to *n* as well. If Mashmokh pushes button with index *i*, then each light with index not less than *i* that is still turn... | ```python
n,m = map(int,input().split())
l = list(map(int,input().split()))
d,c = {},n+1
for i in range(m):
if l[i]<c:
for j in range(l[i],c):
d[j]=l[i]
c=l[i]
for i in range(n):
print(d[i+1],end=' ')
``` | |
MatrixStudio/Codeforces-Python-Submissions | Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word *s*. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, ... | ```python
ans = ''
S = input()
for i in range(len(S)):
if S[i] == 'h' or S[i]=="e" or S[i]=="l" or S[i] =="o":
ans+=S[i]
h = ans.index("h")
e = ans.index("e")
l = ans.index("l")
o = ans.index("o")
if ans == 'helo':
print("NO")
else:
if h<e<l<o:
print("YES")
else:
... | |
MatrixStudio/Codeforces-Python-Submissions | Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpr... | ```python
x=input('')
x=x.split()
s=x[0]
f=x[1]
v=[]
v.append(int(s))
v.append(int(f))
l=max(v)
c=0
for i in range (7):
if i>=(l):
c=c+1
import fractions
def simplify_fraction(num1, num2):
result = fractions(num1, num2)
return result
result = simplify_fraction(c,6)
print(res... | |
MatrixStudio/Codeforces-Python-Submissions | Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word *s*. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, ... | ```python
n=input()
f=0
for i in range(n):
print(i)
print(f)
if i == 'h' and f==0 :
f=1
elif i=='e' and f==1 :
f=2
elif i=='l' and f==2 :
f=3
elif i=='l' and f==3 :
f=4
elif i=='o' and f==4 :
f=5
if f==5 :
print("YES")
else:
print("NO")
... | |
MatrixStudio/Codeforces-Python-Submissions | A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.
This new device is equipped with specially designed artificial intelligence (AI). Employees of Pine... | ```python
s1=input() ; s2=input()
ans=0
for i in range(len(s1)):
if s1[i:i+len(s2)]==s2:ans+=1
print(ans)
``` | |
MatrixStudio/Codeforces-Python-Submissions | On the planet Mars a year lasts exactly *n* days (there are no leap years on Mars). But Martians have the same weeks as earthlings — 5 work days and then 2 days off. Your task is to determine the minimum possible and the maximum possible number of days off per year on Mars. | ```python
n=int(input())
1<=n<=1000000
if n==1:
print('0 1')
elif 2<=n<7:
print('0 2')
else:
i=n//7
j=n%7
if j>5:
print('%d %d'%(i*2+1,i*2+1))
else:
print('%d %d'%(i*2,i*2))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.
Given a sequence *a* consisting of *n* integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it *a*... | ```python
dp = [0 for x in range(100001)]
c = [0 for x in range(100001)]
n = int(input())
if n == 1:
print(int(input()))
tmp = [int(x) for x in input().split()]
for i in tmp:
c[i] += 1
dp[1] = c[1]
for i in range(2, n + 1):
dp[i] = max(dp[i - 1], dp[i - 2] + c[i] * i)
print(dp[n])
``` | |
MatrixStudio/Codeforces-Python-Submissions | Imp is in a magic forest, where xorangles grow (wut?)
A xorangle of order *n* is such a non-degenerate triangle, that lengths of its sides are integers not exceeding *n*, and the xor-sum of the lengths is equal to zero. Imp has to count the number of distinct xorangles of order *n* to get out of the forest.
Formally... | ```python
n = int(input())
cnt = 0
ans = set()
for c in range(1, n + 1):
for a in range(1, c + 1):
b = c ^ a
if c >= a and c >= b and not (c >= a + b or a >= b + c or b >= a + c or b == 0):
cnt += 1
print(cnt // 2)
``` | |
MatrixStudio/Codeforces-Python-Submissions | You are given a permutation *p* of length *n*. Also you are given *m* foe pairs (*a**i*,<=*b**i*) (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*,<=*a**i*<=≠<=*b**i*).
Your task is to count the number of different intervals (*x*,<=*y*) (1<=≤<=*x*<=≤<=*y*<=≤<=*n*) that do not contain any foe pairs. So you shouldn't count intervals (*x... | ```python
I = lambda:[*map(int, input().split())]
def solve():
n, m = I()
a = [0] + I()
pos = [0] * (n + 1)
f = [0] * (n + 1)
for i, v in enumerate(a):
pos[v] = i
for i in range(m):
x, y = I()
x, y = pos[x], pos[y]
if x > y:
x, y = y, x
... | |
MatrixStudio/Codeforces-Python-Submissions | One day Vasya got hold of information on the Martian dollar course in bourles for the next *n* days. The buying prices and the selling prices for one dollar on day *i* are the same and are equal to *a**i*. Vasya has *b* bourles. He can buy a certain number of dollars and then sell it no more than once in *n* days. Acco... | ```python
from collections import deque, Counter, OrderedDict
from heapq import nsmallest, nlargest
def binNumber(n,size):
return bin(n)[2:].zfill(size)
def gcd(a,b):
if a == 0:
return b
return gcd(b%a,a)
def iar():
return list(map(int,input().split()))
def ini():
return i... | |
MatrixStudio/Codeforces-Python-Submissions | Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are *n* drinks in his fridge, the volume fraction of orange juice in the *i*-th drink equals *p**i* percent.
One day Vasya decided to make himself an orange cocktail. He took equal proportio... | ```python
d = int(input())
num = list(map(int, input().split()))
total_s = sum(num)
result = 1 // denominator * total_s
print(result)
``` | |
MatrixStudio/Codeforces-Python-Submissions | New Year is coming in Line World! In this world, there are *n* cells numbered by integers from 1 to *n*, as a 1<=×<=*n* board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.
So, user tncks0... | ```python
n,t = map(int,input().split())
l = list(map(int,input().split()))
i = 0
while i <= n-1:
if i == t:
print("YES")
break
elif i > t:
print("NO")
break
i = i + l[i-1]
else:
if i == t:
print("YES")
else:
print("NO")
``` | |
MatrixStudio/Codeforces-Python-Submissions | Amr has got a large array of size *n*. Amr doesn't like large arrays so he intends to make it smaller.
Amr doesn't care about anything in the array except the beauty of it. The beauty of the array is defined to be the maximum number of times that some number occurs in this array. He wants to choose the smallest subseg... | ```python
n=int(input())
l=list(map(int,input().split()))
li=list(set(l))
if len(l)==len(li):
print("1 1")
else:
max=0
index1=n+1
index2=2*(n+1)+1
for i in li:
if l.count(i)>max:
max=l.count(i)
index1=l.index(i)
index2=n-l[::-1].index(i)-1
... | |
MatrixStudio/Codeforces-Python-Submissions | Parsley, sage, rosemary and thyme.
Remember me to one who lives there.
He once was the true love of mine.
Willem is taking the girl to the highest building in island No.28, however, neither of them knows how to get there.
Willem asks his friend, Grick for directions, Grick helped them, and gave them a task.
Althou... | ```python
n,m=map(int,input().split())
s=input()
for i in range(m):
l,r,c1,c2=input().split()
l=int(l)
r=int(r)
for j in range(l-1,r):
if s[j]==c1:
s=s[:j]+c2+s[j+1:]
print(s)
``` | |
MatrixStudio/Codeforces-Python-Submissions | While Mike was walking in the subway, all the stuff in his back-bag dropped on the ground. There were several fax messages among them. He concatenated these strings in some order and now he has string *s*.
He is not sure if this is his own back-bag or someone else's. He remembered that there were exactly *k* messages ... | ```python
def pal(s):
for i in range(int(len(s)/2)):
if s[i]!=s[len(s)-1-i]:
return False
return True
flag=True
s=input()
n=int(input())
temp=int(len(s)/n)
for i in range(n):
# print(s[0+i*temp:(i+1)*temp])
if pal(s[0+i*temp:(i+1)*temp])==False:
flag=False
... | |
MatrixStudio/Codeforces-Python-Submissions | Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands:
- Include a person... | ```python
from sys import *
live = 0
l = 0
for line in stdin:
if line[0] == "+":
live += 1
elif line[0] == "-":
live -= 1
else :
idx = line.find(':')
line = line[idx+1:]
l = l + (len(line)-1)*live
print(l)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Indian summer is such a beautiful time of the year! A girl named Alyona is walking in the forest and picking a bouquet from fallen leaves. Alyona is very choosy — she doesn't take a leaf if it matches the color and the species of the tree of one of the leaves she already has. Find out how many leaves Alyona has picked. | ```python
n = int(input())
listans = []
for i in range(n):
a, b = map(str, input().split())
listans.append([a, b])
counter = 0
for i in range(len(listans) - 1):
if listans[i] != listans[i + 1]:
counter += 1
else:
counter = 1
print(counter)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number *n*. How many times can Gerald put a spell on it until the number becomes one-... | ```python
def calculate(m):
n1 = 0
A_list = list(map(int, str(m)))
for i in range(0, length(str(m))):
n1 = n1 + A_list[i]
return n1
def result(m):
n2 = m
for i in range(0, length(str(m))):
count = 0
if length(str(m)) > 1:
n2 = calculate(n2)
count... | |
MatrixStudio/Codeforces-Python-Submissions | One day, Twilight Sparkle is interested in how to sort a sequence of integers *a*1,<=*a*2,<=...,<=*a**n* in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:
Help Twilight Sparkle to calculate: what ... | ```python
n = int(input())
A = [int(a) for a in input().split()]
flag = True
m = 0
last = A[0]
break_seen = False
for i in range(1, n):
if last > A[i]:
if break_seen:
flag = False
break
else:
break_seen = True
m = n - i
last = A[i... | |
MatrixStudio/Codeforces-Python-Submissions | One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house.
Karlsson's gaze immediately fell on *n* woode... | ```python
n=int(input())
l=[]
r=[]
for i in range(n):
lst=list(map(int,input().split()))
l.append(lst[0])
r.append(lst[1])
t=0
if 0 in l and 1 in l:
if l.count(1)>=l.count(0):
for i in l:
if i==0:
t=t+1
elif l.count(0)>l.count(1) :
for i in l... | |
MatrixStudio/Codeforces-Python-Submissions | Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpr... | ```python
import math
y , w = map(int , input().split())
h = 6 - max(y,w) + 1
p = 6 // h if 6 % h == 0 else 6
p = max(math.gcd(p,h),1)
print(str(p) + '/'+ str(h//p))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he... | ```python
# Define a lambda function to take input as integers from standard input
cin = lambda: map(int, input().split())
# Read in the input values: n, p, q, r and the array A
n, p, q, r = cin()
A = list(cin())
# Initialize the variables tp, tq, and tr to negative infinity
tp, tq, tr = -float("inf"), -float("inf"),... | |
MatrixStudio/Codeforces-Python-Submissions | Kuriyama Mirai has killed many monsters and got many (namely *n*) stones. She numbers the stones from 1 to *n*. The cost of the *i*-th stone is *v**i*. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions:
1. She will tell you two numbers, *l* and *r* (1<=≤<=*l*<=≤<=*r*... | ```python
n = int(input())
arr = list(map(int, input().split()))
srr = arr[:]
srr.sort()
for i in range(1, n) :
arr[i] += arr[i-1]
srr[i] += srr[i-1]
for i in range(int(input())) :
x, l, r = map(int, input().split())
if x == 1:
print(arr[r-1]-(arr[l-2] if l > 1 else 0))... | |
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 s... | ```python
n,m=map(int,input().split())
l=list(map(int,input().split()))
for i in range(m):
k=int(input())
t=set(l[k-1:])
print(len(t))
``` | |
MatrixStudio/Codeforces-Python-Submissions | The hero of our story, Valera, and his best friend Arcady are still in school, and therefore they spend all the free time playing turn-based strategy "GAGA: Go And Go Again". The gameplay is as follows.
There are two armies on the playing field each of which consists of *n* men (*n* is always even). The current playe... | ```python
n=int(input())
print(int(n*1.5))
``` | |
MatrixStudio/Codeforces-Python-Submissions | A permutation of size *n* is an array of size *n* such that each integer from 1 to *n* occurs exactly once in this array. An inversion in a permutation *p* is a pair of indices (*i*,<=*j*) such that *i*<=><=*j* and *a**i*<=<<=*a**j*. For example, a permutation [4,<=1,<=3,<=2] contains 4 inversions: (2,<=1), (3,<=... | ```python
n = int(input())
*a, = map(int, input().split())
p = 0
for i in range(n):
for j in range(i + 1, n):
if a[i] > a[j]:
p ^= 1
m = int(input())
for i in range(m):
l, r = map(int, input().split())
k = r - l + 1
k = k * (k - 1) // 2
if k & 1:
p ^= 1
... | |
MatrixStudio/Codeforces-Python-Submissions | Vasya has recently learned at school what a number's divisor is and decided to determine a string's divisor. Here is what he came up with.
String *a* is the divisor of string *b* if and only if there exists a positive integer *x* such that if we write out string *a* consecutively *x* times, we get string *b*. For exam... | ```python
def prefix(p,ss,l):
s=p+'*'+ss
n=len(s)
arr=[0]*(n+1)
i=0
j=1
cou=0
while j<n:
if(s[i]==s[j]):
arr[j]=i+1
i+=1
j+=1
else:
if(i==0):
arr[j]=0
j+=1
else:
... | |
MatrixStudio/Codeforces-Python-Submissions | Recently, you bought a brand new smart lamp with programming features. At first, you set up a schedule to the lamp. Every day it will turn power on at moment $0$ and turn power off at moment $M$. Moreover, the lamp allows you to set a program of switching its state (states are "lights on" and "lights off"). Unfortunate... | ```python
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 16 16:27:20 2022
@author: lenovo
"""
n,M=map(int, input().split())
array=list(map(int, input().split()))
gap=[array[0]]
for i in range(n-1):
gap.append(array[i+1]-array[i])
gap.append(M-array[-1])
gap_1=gap[::2]
gap_2=gap[1::2]
summing_1=[gap... | |
MatrixStudio/Codeforces-Python-Submissions | Vasya has become interested in wrestling. In wrestling wrestlers use techniques for which they are awarded points by judges. The wrestler who gets the most points wins.
When the numbers of points of both wrestlers are equal, the wrestler whose sequence of points is lexicographically greater, wins.
If the sequences of... | ```python
a=int(input())
C=[]
D=[]
c=0
d=0
for i in range(a):
b=int(input())
if b>0:
c+=b
C+=[str(b)]
if b<0:
d+=-b
D+=[str(-b)]
if c>d:
print('first')
elif c<d:
print('second')
elif c==d:
if C>D:
print('first')
if C<D:
print('second')
if C==D:
if b>0:
print('first')
... | |
MatrixStudio/Codeforces-Python-Submissions | Recently Adaltik discovered japanese crosswords. Japanese crossword is a picture, represented as a table sized *a*<=×<=*b* squares, and each square is colored white or black. There are integers to the left of the rows and to the top of the columns, encrypting the corresponding row or column. The number of integers repr... | ```python
n=int(input())
s=input()
l=[]
count = 0
for i in range(n):
if s[i] == 'B':
count+=1
if i == n-1: l.append(count)
else:
if count>0 : l.append(count)
count = 0
print(len(l))
print(*l)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Every year, hundreds of people come to summer camps, they learn new algorithms and solve hard problems.
This is your first year at summer camp, and you are asked to solve the following problem. All integers starting with 1 are written in one line. The prefix of these line is "123456789101112131415...". Your task is to... | ```python
a = int(input())
s = ""
i = 1
while len(s) < a:
s+=str(i)
i+=1
print(s[a-1])
``` | |
MatrixStudio/Codeforces-Python-Submissions | Someday, Drazil wanted to go on date with Varda. Drazil and Varda live on Cartesian plane. Drazil's home is located in point (0,<=0) and Varda's home is located in point (*a*,<=*b*). In each step, he can move in a unit distance in horizontal or vertical direction. In other words, from position (*x*,<=*y*) he can go to ... | ```python
a, b, s = (map(int, input().split()))
if a + b < s and abs(a + b - s) % 2 != 0:
print("NO")
else:
print("YES")
``` | |
MatrixStudio/Codeforces-Python-Submissions | For a given positive integer *n* denote its *k*-rounding as the minimum positive integer *x*, such that *x* ends with *k* or more zeros in base 10 and is divisible by *n*.
For example, 4-rounding of 375 is 375·80<==<=30000. 30000 is the minimum integer such that it ends with 4 or more zeros and is divisible by 375.
W... | ```python
l = input().split()
n = int(l[0])
k = int(l[1])
def zero_am(num):
res = 0
while num % 10 == 0:
num /= 10
res += 1
return res
s = [1, 2, 4, 5, 6, 8]
l = {}
m = 0
for i in reversed(s):
l.update({zero_am(n * i): n * i})
if zero_am(n * i) > m:
m = zero_am(n * i)
ans ... | |
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 th... | ```python
n, m = map(int, input().split())
M = []
for _ in range(n):
row = input()
M.append(list(row))
for i in range(n):
for j in range(m):
if M[i][j] == '-':
continue
else:
if i == 0:
if j == 0:
M[i][j] = 'B'
... | |
MatrixStudio/Codeforces-Python-Submissions | A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string *s* consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string *s* to be distinct. Substring is a string formed by some... | ```python
def solve():
n=int(input())
st=input()
lst=list(st)
s=set(lst)
n-=len(s)
# print(n-len(s))
if n<27:
print(n)
else:
print(-1)
# t=int(input())
# for i in range(t):
solve()
``` | |
MatrixStudio/Codeforces-Python-Submissions | Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.
Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character... | ```python
inpt1 = input().strip()
input1 = list(inpt1)
starts_with = ord('a')
ends_with = ord('z')
sum = 0
prev= "a"
for char in input1:
curr = ord(char)
prev_ord = ord(prev)
if curr >= prev_ord:
sum += min(prev_ord-starts_with+ends_with-curr + 1, curr - prev_ord)
else:
sum +... | |
MatrixStudio/Codeforces-Python-Submissions | You have decided to watch the best moments of some movie. There are two buttons on your player:
1. Watch the current minute of the movie. By pressing this button, you watch the current minute of the movie and the player automatically proceeds to the next minute of the movie. 1. Skip exactly *x* minutes of the movie... | ```python
#include <bits/stdc++.h>
#define nline "\n"
#define fastio() ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
#define MOD 1000000007
#define loop(i,a,b) for(int i=(a);i<(b);i++)
using namespace std;
void file_I_O() {
fastio();
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", s... | |
MatrixStudio/Codeforces-Python-Submissions | Once Bob got to a sale of old TV sets. There were *n* TV sets at that sale. TV set with index *i* costs *a**i* bellars. Some TV sets have a negative price — their owners are ready to pay Bob if he buys their useless apparatus. Bob can «buy» any TV sets he wants. Though he's very strong, Bob can carry at most *m* TV set... | ```python
n,m=map(int,input().split())
a=list(map(int,input().split()))
l=[]
for i in range (m):
l.append(min(a))
a.remove(min(a))
print(abs(sum(l)))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Recently Polycarp started to develop a text editor that works only with correct bracket sequences (abbreviated as CBS).
Note that a bracket sequence is correct if it is possible to get a correct mathematical expression by adding "+"-s and "1"-s to it. For example, sequences "(())()", "()" and "(()(()))" are correct, ... | ```python
def f1(m2, s):
m2 = {}
st = []
for i in range(len(s)):
if s[i] == '(':
st.append(i)
else:
m2[st[-1]] = i
m2[i] = st[-1]
st.pop()
return m2
n, m, p = map(int, input().split())
s = input()
a = input()
m = {}
m = f1(... | |
MatrixStudio/Codeforces-Python-Submissions | Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.
Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character... | ```python
s1='abcdefghijklmnopqrstuvwxyz'
s=input()
j=0
k=0
for i in range(len(s)):
j1=s1.index(s[i])
a=abs(j-j1)
if a <=13:
k+=a
j=j1
else:
k+=26-a
j=j1
print(k)
``` | |
MatrixStudio/Codeforces-Python-Submissions | All cities of Lineland are located on the *Ox* coordinate axis. Thus, each city is associated with its position *x**i* — a coordinate on the *Ox* axis. No two cities are located at a single point.
Lineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another c... | ```python
n = int(input())
cities = list(map(int,input().split(' ')))
for i in range(len(cities)):
if i == 0:
cost_min = abs(cities[i] - cities[1])
cost_max = abs(cities[i] - cities[-1])
elif i == len(cities)-1:
cost_min = abs(cities[i] - cities[-2])
cost_max = abs(cities... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.