source stringclasses 3
values | instruction stringlengths 23 3.97k | input stringclasses 1
value | output stringlengths 1 3.75k |
|---|---|---|---|
MatrixStudio/Codeforces-Python-Submissions | Today, Wet Shark is given *n* integers. Using any of these integers no more than once, Wet Shark wants to get maximum possible even (divisible by 2) sum. Please, calculate this value for Wet Shark.
Note, that if Wet Shark uses no integers from the *n* integers, the sum is an even integer 0. | ```python
# Wet Shark and Odd and Even
def big_boi_sum(arr):
ini = sum(arr)
if ini % 2 == 0:
return ini
eve = []
odd = []
for i in arr:
if i % 2 == 0:
eve.append(i)
else:
odd.append(i)
if sum(odd) % 2 != 0:
odd.remove(min(odd))
fin = su... | |
MatrixStudio/Codeforces-Python-Submissions | Permutation *p* is an ordered set of integers *p*1,<=<=*p*2,<=<=...,<=<=*p**n*, consisting of *n* distinct positive integers, each of them doesn't exceed *n*. We'll denote the *i*-th element of permutation *p* as *p**i*. We'll call number *n* the size or the length of permutation *p*1,<=<=*p*2,<=<=...,<=<=*p**n*.
The ... | ```python
import sys
def input(): return sys.stdin.readline().strip()
def iinput(): return int(input())
def rinput(): return map(int, sys.stdin.readline().strip().split())
def get_list(): return list(map(int, sys.stdin.readline().strip().split()))
n,k=rinput()
a=[]
for i in range(n,n-k,-1):
a... | |
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
n=int(input())
for i in range(n):
str=input()
k=len(str)
if len(str)<10:
print(str)
elif len(str)>10:
print(str[0]+str(len(str)-2)+str[k-1])
``` | |
MatrixStudio/Codeforces-Python-Submissions | Arpa is researching the Mexican wave.
There are *n* spectators in the stadium, labeled from 1 to *n*. They start the Mexican wave at time 0.
- At time 1, the first spectator stands. - At time 2, the second spectator stands. - ... - At time *k*, the *k*-th spectator stands. - At time *k*<=+<=1, the (*k*<=+<=1)-t... | ```python
n,k,t=map(int,input().split())
if(t<=k):
print(t)
if(k<=t<=n):
print(k)
if(n<=t<n+k):
print(n+k-t)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Uncle Fyodor, Matroskin the Cat and Sharic the Dog live their simple but happy lives in Prostokvashino. Sometimes they receive parcels from Uncle Fyodor’s parents and sometimes from anonymous benefactors, in which case it is hard to determine to which one of them the package has been sent. A photographic rifle is obvio... | ```python
F, M, S = input(), input(), input()
if len({F, M, S}) != 2:
print("?")
else:
lst = [F, M, S]
for x in [("rock","scissors"), ("scissors", "paper"), ("paper", "rock")]:
if lst.count(x[0]) == 1 and lst.count(x[1]) == 2:
print("FMS"[lst.index(x[0])])
break
... | |
MatrixStudio/Codeforces-Python-Submissions | Johnny has a younger sister Anne, who is very clever and smart. As she came home from the kindergarten, she told his brother about the task that her kindergartener asked her to solve. The task was just to construct a triangle out of four sticks of different colours. Naturally, one of the sticks is extra. It is not allo... | ```python
a = sorted([int(i) for i in input().split()])
res = "IMPOSSIBLE"
for i in range(2):
if a[i] + a[i+1] > a[i+2] : res = "TRIANGLE"; break
if res == "IMPOSSIBLE" :
for i in range(2):
if i == 1 :
if a[i] + a[i+1] == a[i+2] : res = "SEGMENT"; break
continue
... | |
MatrixStudio/Codeforces-Python-Submissions | Pasha got a very beautiful string *s* for his birthday, the string consists of lowercase Latin letters. The letters in the string are numbered from 1 to |*s*| from left to right, where |*s*| is the length of the given string.
Pasha didn't like his present very much so he decided to change it. After his birthday Pasha ... | ```python
a=input()
b=input()
c=list(map(int, input().split()))
for i in c:
a=a.replace(a[i-1:len(a)-i+1],a[i-1:len(a)-i+1][::-1])
print(a)
``` | |
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 = input()
l = s.split(',')
t=list(l)
x = set(t)
count = len(x)
print(f"{count}")
``` | |
MatrixStudio/Codeforces-Python-Submissions | The Little Elephant loves Ukraine very much. Most of all he loves town Rozdol (ukr. "Rozdil").
However, Rozdil is dangerous to settle, so the Little Elephant wants to go to some other town. The Little Elephant doesn't like to spend much time on travelling, so for his journey he will choose a town that needs minimum ti... | ```python
n = int(input())
cd = [int(x) for x in input().split(" ")]
min_count = 1
min = 0
for i in range(1, n):
if cd[i] < cd[min]:
min = i
min_count = 1
elif cd[i] == cd[min]:
min_count += 1
if(min_count > 1):
print("Still Rozdil")
else:
print(min + 1)
``` | |
MatrixStudio/Codeforces-Python-Submissions | A company has *n* employees numbered from 1 to *n*. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee *A* is said to be the superior of another employee *B* if at least one of the following is true:
- Employee *A* is the immedi... | ```python
def min_groups(n, managers):
employees = list(range(n))
groups = set()
while employees:
group = set()
group.add(employees[0])
employees.pop(0)
while employees and employees[-1] in managers and managers[employees[-1]] in group:
group.add(employees[-1])
employees.pop()
g... | |
MatrixStudio/Codeforces-Python-Submissions | Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers *a*, *b*, *c* on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resul... | ```python
a=int(input())
b=int(input())
c=int(input())
z=[]
z.append(a+b+c)
z.append(a*b*c)
z.append((a+b)*c)
z.append(a*(b+c))
z.append(a+b*c)
z.append(a*b+c)
z.sort()
print(z[-1])
``` | |
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
tam = int(input())
seq = input().split()
sumas = [0] * tam
for a in seq:
sumas[int(a)-1] = sumas[int(a)-1] + int(a)
if len(sumas) < 3:
print(max(sumas))
else:
final = 0
primero = 0
while len(sumas) > 2:
if sumas[0] >= sumas[1]:
final = final + sumas[... | |
MatrixStudio/Codeforces-Python-Submissions | Malek has recently found a treasure map. While he was looking for a treasure he found a locked door. There was a string *s* written on the door consisting of characters '(', ')' and '#'. Below there was a manual on how to open the door. After spending a long time Malek managed to decode the manual and found out that th... | ```python
if __name__=='__main__':
s=input().strip()
diff=0
res=[]
for i,c in enumerate(s):
if c=='(':
diff+=1
elif c==')':
diff-=1
if diff<0:
res=-1
break
else:
if diff>0:
... | |
MatrixStudio/Codeforces-Python-Submissions | It's that time of the year when the Russians flood their countryside summer cottages (dachas) and the bus stop has a lot of people. People rarely go to the dacha on their own, it's usually a group, so the people stand in queue by groups.
The bus stop queue has *n* groups of people. The *i*-th group from the beginning ... | ```python
n,m=map(int,input().split())
l=list(map(int,input().split()))
k=1
t=0
for i in range(n) :
if t+l[i]>m :
k=k+1
t=l[i]
else :
t=t+l[i]
print(k)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Mike and some bears are playing a game just for fun. Mike is the judge. All bears except Mike are standing in an *n*<=×<=*m* grid, there's exactly one bear in each cell. We denote the bear standing in column number *j* of row number *i* by (*i*,<=*j*). Mike's hands are on his ears (since he's the judge) and each bear s... | ```python
n,m,q = map(int,input().split())
hor = [0] * n
table = [0] * n
for i in range(n):
table[i] = list(map(int,input().split()))
for h in range(n):
tmp = 0
for v in range(m):
if table[h][v]:
tmp += 1
else:
if hor[h] < tmp: hor[h] = tmp
... | |
MatrixStudio/Codeforces-Python-Submissions | The girl Taylor has a beautiful calendar for the year *y*. In the calendar all days are given with their days of week: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday.
The calendar is so beautiful that she wants to know what is the next year after *y* when the calendar will be exactly the same. Help ... | ```python
n=int(input())
if n%400==0 or (n%4==0 and n%100!=0):
print(n+28)
elif n%4==1:
print(n+6)
else:
print(n+11)
``` | |
MatrixStudio/Codeforces-Python-Submissions | One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality ... | ```python
n = int(input())
laptops = [tuple(map(int, input().split())) for i in range(n)]
if any(a < b for a, b in laptops):
print("Happy Alex")
else:
print("Poor Alex")
``` | |
MatrixStudio/Codeforces-Python-Submissions | You are given two polynomials:
- *P*(*x*)<==<=*a*0·*x**n*<=+<=*a*1·*x**n*<=-<=1<=+<=...<=+<=*a**n*<=-<=1·*x*<=+<=*a**n* and - *Q*(*x*)<==<=*b*0·*x**m*<=+<=*b*1·*x**m*<=-<=1<=+<=...<=+<=*b**m*<=-<=1·*x*<=+<=*b**m*.
Calculate limit . | ```python
import math
d1,d2=map(int,input().split())
l1=list(map(int,list(input().split())))
l2=list(map(int,list(input().split())))
if d1<d2:
print("0/1")
if d1==d2:
g=math.gcd(l1[0],l2[0])
p=l1[0]//g
q=l2[0]//g
if p>0 and q>0:
print(str(p)+"/"+str(q))
else:
if p<0:... | |
MatrixStudio/Codeforces-Python-Submissions | Edogawa Conan got tired of solving cases, and invited his friend, Professor Agasa, over. They decided to play a game of cards. Conan has *n* cards, and the *i*-th card has a number *a**i* written on it.
They take turns playing, starting with Conan. In each turn, the player chooses a card and removes it. Also, he remov... | ```python
n = int(input())
a = input().split(" ")
a_int = []
for i in a:
a_int.append(int(i))
a = a_int
a.sort()
if a.count(a[-1]) % 2 == 1: print("Conan")
else: print("Agasa")
``` | |
MatrixStudio/Codeforces-Python-Submissions | Makes solves problems on Decoforces and lots of other different online judges. Each problem is denoted by its difficulty — a positive integer number. Difficulties are measured the same across all the judges (the problem with difficulty *d* on Decoforces is as hard as the problem with difficulty *d* on any other judge).... | ```python
n, k = map(int, input().strip().split())
a = list(map(int, input().strip().split()))
ans = 0
for now in a:
while k*2 < now:
k *= 2
ans += 1
k = max(k, now)
print(ans)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Consider the decimal presentation of an integer. Let's call a number d-magic if digit *d* appears in decimal presentation of the number on even positions and nowhere else.
For example, the numbers 1727374, 17, 1 are 7-magic but 77, 7, 123, 34, 71 are not 7-magic. On the other hand the number 7 is 0-magic, 123 is 2-mag... | ```python
import math
MAX_SUM = 73
prime = [True for i in range(MAX_SUM)]
def sieve():
prime[0] = prime[1] = False
for i in range(2, int(math.sqrt(MAX_SUM))):
if prime[i]:
for j in range(i * i, MAX_SUM, i):
prime[j] = False
def compute_digits_list(n):
... | |
MatrixStudio/Codeforces-Python-Submissions | Today an outstanding event is going to happen in the forest — hedgehog Filya will come to his old fried Sonya!
Sonya is an owl and she sleeps during the day and stay awake from minute *l*1 to minute *r*1 inclusive. Also, during the minute *k* she prinks and is unavailable for Filya.
Filya works a lot and he plans to ... | ```python
a,b,c,d,r=map(int,input().split())
m=0
if c<=b:
m=(b+1)-c
if c <= r<=b:
m=m-1
print(m)
else:
print(m)
``` | |
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
import sys
for line in sys.stdin:
words= [line.strip().split()]
print(words)
``` | |
MatrixStudio/Codeforces-Python-Submissions | A string is a palindrome if it reads the same from the left to the right and from the right to the left. For example, the strings "kek", "abacaba", "r" and "papicipap" are palindromes, while the strings "abb" and "iq" are not.
A substring $s[l \ldots r]$ ($1<=\leq<=l<=\leq<=r<=\leq<=|s|$) of a string $s<==<=s_{1}s_{2}... | ```python
#include <bits/stdc++.h>
#define ll long long
#define int long long
#define fi first
#define se second
#define ii pair<int, int>
const ll N = 1e6+1;
const ll mod = 1e9+7;
const ll INF = 1e9;
using namespace std;
signed main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);cout.tie(0);
... | |
MatrixStudio/Codeforces-Python-Submissions | Mr Keks is a typical white-collar in Byteland.
He has a bookshelf in his office with some books on it, each book has an integer positive price.
Mr Keks defines the value of a shelf as the sum of books prices on it.
Miraculously, Mr Keks was promoted and now he is moving into a new office.
He learned that in the ne... | ```python
from functools import reduce
N=55
dp = [ [-1 for i in range(N)] for i in range(N) ]
N,K = list(map(int,input().strip().split()))
A = list(map(int, input().strip().split()))
# n,k divide just after before i into k segments
def solve(i,k):
if(dp[i][k]!=-1):
return dp[i][k]
if(k==1):... | |
MatrixStudio/Codeforces-Python-Submissions | The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has *n* students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times.
Th... | ```python
n, k = list(map(int, input().split()))
l = list(map(int, input().split()))
c = 0
for i in range(n):
l[i] += k
if l[i] <= 5:
c += 1
print(c // 3)
``` | |
MatrixStudio/Codeforces-Python-Submissions | You are going to the beach with the idea to build the greatest sand castle ever in your head! The beach is not as three-dimensional as you could have imagined, it can be decribed as a line of spots to pile up sand pillars. Spots are numbered 1 through infinity from left to right.
Obviously, there is not enough sand o... | ```python
# -*- coding: utf-8 -*-
import math
vec = input().strip().split(' ')
n = int(vec[0])
H = int(vec[1])
s = round(math.sqrt(n * 2)) - 1
while True:
if s * (s + 1) / 2 > n:
break
s = s + 1
s = s - 1
if s > H:
s = H
diff = n - s * (s + 1) / 2
count = s
xa = 1
xb ... | |
MatrixStudio/Codeforces-Python-Submissions | Little girl Tanya climbs the stairs inside a multi-storey building. Every time Tanya climbs a stairway, she starts counting steps from $1$ to the number of steps in this stairway. She speaks every number aloud. For example, if she climbs two stairways, the first of which contains $3$ steps, and the second contains $4$ ... | ```python
n = int(input())
list = list(map(int , input().split()))
li = []
c = 0
for i in range(n):
if list[i] == 1:
c += 1
if list[i] == 1 and i > 0:
li.append(list[i-1])
li.append(list[-1])
print(c)
for l in li:
print(l , end = " ")
``` | |
MatrixStudio/Codeforces-Python-Submissions | Little Elephant loves magic squares very much.
A magic square is a 3<=×<=3 table, each cell contains some positive integer. At that the sums of integers in all rows, columns and diagonals of the table are equal. The figure below shows the magic square, the sum of integers in all its rows, columns and diagonals equals ... | ```python
a,b,c=map(int,input().split())
r,s,t=map(int,input().split())
x,y,z=map(int,input().split())
s=(2*c+b-r)//2
a=s+r+t-b-c
z=s+r+t-x-y
print(a,b,c)
print(r,s,t)
print(x,y,z)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built *n* towers in a row. The *i*-th tower is made of *h**i* identical blocks. For clarification see picture for the first sample.
Limak will repeat the following operation till everything is destroyed.
Block is called inter... | ```python
N = int(input())
A = [int(i) for i in input().split()]
A = [0] + A + [0]
lo, hi = 0, N
while lo <= hi:
k = (lo + hi) // 2
H, N, K = A, N, k
a = True
for i in range(K + 1, N - K + 1):
h = H[i]
for j in range(K + 1):
if h <= 0:
break
... | |
MatrixStudio/Codeforces-Python-Submissions | It's one more school day now. Sasha doesn't like classes and is always bored at them. So, each day he invents some game and plays in it alone or with friends.
Today he invented one simple game to play with Lena, with whom he shares a desk. The rules are simple. Sasha draws *n* sticks in a row. After that the players t... | ```python
a,m = map(int,input().split())
print("YES" if(a//m)%2==1 else "NO")
``` | |
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())
v = list(map(int,input().split()))
m = int(input())
vps = [0]
for x in v:
vps.append(vps[-1]+x)
v.sort()
ups = [0]
for x in v:
ups.append(ups[-1]+x)
for _ in range(m):
t,l,r = map(int,input().split())
if t == 1:
print(vps[r]-vps[l-1])
else:
... | |
MatrixStudio/Codeforces-Python-Submissions | Holidays have finished. Thanks to the help of the hacker Leha, Noora managed to enter the university of her dreams which is located in a town Pavlopolis. It's well known that universities provide students with dormitory for the period of university studies. Consequently Noora had to leave Vičkopolis and move to Pavlopo... | ```python
def bored_life(x,y):
res1=1
for i in range(1,x+1):
res1=res1*i
res2=1
for i in range(1,y+1):
res2=res2*i
temp=[res1,res2]
print(min(temp))
(x,y)=map(int,input().split())
bored_life(x,y)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Array of integers is unimodal, if:
- it is strictly increasing in the beginning; - after that it is constant; - after that it is strictly decreasing.
The first block (increasing) and the last block (decreasing) may be absent. It is allowed that both of this blocks are absent.
For example, the following three arra... | ```python
a = list( map(int,input().split()) )
n=0
m=0
x=0
for i in range(len(a)-1):
if a[i+1]>a[i]:
n=a[i+1]
else:
break
for j in range(i,len(a)-1):
if a[j]>a[j+1]:
m=a[j]
else:
x=1
break
if(x==1):
print('no')
else:
print('yes')
``` | |
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 exact... | ```python
import itertools
if __name__ == '__main__':
n = int(input())
weights = list(map(int, input().split()))
combs = list(itertools.combinations(weights,len(weights)-2))
diff_list = []
for comb in combs:
instability = 0
for num in range(0,len(comb),2):
instability += abs(comb[num] - comb[num+1])
i... | |
MatrixStudio/Codeforces-Python-Submissions | Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network.
Bu... | ```python
str = input()
sett = set(str)
m = len(sett)
if(m&1) !=1:
print("CHAT WITH HER!")
else:
print("IGNORE HIM!")
``` | |
MatrixStudio/Codeforces-Python-Submissions | Kirill plays a new computer game. He came to the potion store where he can buy any potion. Each potion is characterized by two integers — amount of experience and cost. The efficiency of a potion is the ratio of the amount of experience to the cost. Efficiency may be a non-integer number.
For each two integer numbers ... | ```python
l,r,x,y,k = input().split()
min_k = int(l)/int(y)
max_k = int(r)/int(x)
k1 = float(k)
if k1>=min_k and k1<=max_k:
print("YES")
else:
print("NO")
``` | |
MatrixStudio/Codeforces-Python-Submissions | In a far away kingdom lived the King, the Prince, the Shoemaker, the Dressmaker and many other citizens. They lived happily until great trouble came into the Kingdom. The ACMers settled there.
Most damage those strange creatures inflicted upon the kingdom was that they loved high precision numbers. As a result, the Ki... | ```python
n= input()
ip, fp = n.split('.')
l = ip[-1]
if l!= '9':
if int(fp[0]) < 5:
print(ip)
else:
print(int(ip) + 1)
else:
print("GOTO Vasilisa.")
``` | |
MatrixStudio/Codeforces-Python-Submissions | You are given matrix with *n* rows and *n* columns filled with zeroes. You should put *k* ones in it in such a way that the resulting matrix is symmetrical with respect to the main diagonal (the diagonal that goes from the top left to the bottom right corner) and is lexicographically maximal.
One matrix is lexicograph... | ```python
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 30 19:33:01 2023
@author: ZHAO XUDI
"""
n, k = map(int, input().split())
matrix = [[0 for _ in range(n)] for _ in range(n)]
if k > n * n:
print(-1)
else:
# Placing 1's on the diagonal
for i in range(n):
if k > 0:
... | |
MatrixStudio/Codeforces-Python-Submissions | Little Lesha loves listening to music via his smartphone. But the smartphone doesn't have much memory, so Lesha listens to his favorite songs in a well-known social network InTalk.
Unfortunately, internet is not that fast in the city of Ekaterinozavodsk and the song takes a lot of time to download. But Lesha is quite ... | ```python
t,s,q = input().split()
t=int(t)
s=int(s)
q=int(q)
if(s<t/q):
print(2)
else:
print(1)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Jabber ID on the national Berland service «Babber» has a form <username>@<hostname>[/resource], where
- <username> — is a sequence of Latin letters (lowercase or uppercase), digits or underscores characters «_», the length of <username> is between 1 and 16, inclusive. - <hostname> — is... | ```python
import sys
from re import match,findall
input = sys.stdin.readline
import logging
log = logging.getLogger()
log.setLevel(logging.INFO)
def not_an_id():
print('NO')
exit(0)
s = input()
if '@' not in s:
# log.error('@ not found')
not_an_id()
# def is_allowed_in_user(strings):
# if any(len... | |
MatrixStudio/Codeforces-Python-Submissions | Everybody knows what an arithmetic progression is. Let us remind you just in case that an arithmetic progression is such sequence of numbers *a*1,<=*a*2,<=...,<=*a**n* of length *n*, that the following condition fulfills:
For example, sequences [1, 5], [10], [5, 4, 3] are arithmetic progressions and sequences [1, 3, ... | ```python
from collections import defaultdict
from sys import stdin
input = stdin.buffer.readline
def func():
if n == 1:
print(-1)
elif n == 2:
d = a[1] - a[0]
if a[0] % 2 == a[1] % 2:
print(3)
print(a[0] - d, (a[0] + a[1]) // 2, a[1] + d)
els... | |
MatrixStudio/Codeforces-Python-Submissions | There is a square matrix *n*<=×<=*n*, consisting of non-negative integer numbers. You should find such a way on it that
- starts in the upper left cell of the matrix; - each following cell is to the right or down from the current cell; - the way ends in the bottom right cell.
Moreover, if we multiply together all... | ```python
def cou(n):
five = 0
two = 0
n1 = n
while n % 2 == 0:
two += 1
n//=2
while n1 % 5 == 0:
five += 1
n1//=5
return (two,five)
n = int(input())
arr = [[(0,0) for i in range(n)] for i in range(n)]
zeroes = [[0]*n for i in range(n)]
for i in range(n):
x ... | |
MatrixStudio/Codeforces-Python-Submissions | There is a polyline going through points (0,<=0)<=–<=(*x*,<=*x*)<=–<=(2*x*,<=0)<=–<=(3*x*,<=*x*)<=–<=(4*x*,<=0)<=–<=...<=-<=(2*kx*,<=0)<=–<=(2*kx*<=+<=*x*,<=*x*)<=–<=....
We know that the polyline passes through the point (*a*,<=*b*). Find minimum positive value *x* such that it is true or determine that there is no ... | ```python
a, b=[int(k) for k in input().split()]
if b>a:
print(-1)
else:
if (a%b)==0 and (a//b)%2==1:
print(b)
else:
c=(a//b-1)//2*2+1
#print(c)
#x-(a-c*x)=b
#x+cx-a=b
x=(a+b)/(1+c)
print(x)
#/\/\/\/\/\/\
``` | |
MatrixStudio/Codeforces-Python-Submissions | This is yet another problem dealing with regular bracket sequences.
We should remind you that a bracket sequence is called regular, if by inserting «+» and «1» into it we can get a correct mathematical expression. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.... | ```python
st = input()
a = 0
b = 0
l = 0
cnt = 0
for i in st:
if i=='(':
cnt+=1
else:
cnt-=1
if cnt==0 and l>0:
if l>a:
a=l
b=1
elif l==a:
b+=1
elif cnt<0:
cnt=0
l=0
else:
l+=1
if a:
a+=1
if not b:
b=1
pri... | |
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())
a=b=c=0
for i in range(n):
x,y=map(int,input().split())
if x==y:
a+=1
if x>y:
b+=1
if x<y:
c+=1
if b>c:
print('Mishka')
elif b<c:
print('Chris')
elif b==c:
print('Friendship is magic!^^')
``` | |
MatrixStudio/Codeforces-Python-Submissions | Levko loves permutations very much. A permutation of length *n* is a sequence of distinct positive integers, each is at most *n*.
Let’s assume that value *gcd*(*a*,<=*b*) shows the greatest common divisor of numbers *a* and *b*. Levko assumes that element *p**i* of permutation *p*1,<=*p*2,<=... ,<=*p**n* is good if *g... | ```python
print("_RANDOM_GUESS_1689637780.5135195")# 1689637780.51354
``` | |
MatrixStudio/Codeforces-Python-Submissions | A number is called quasibinary if its decimal representation contains only digits 0 or 1. For example, numbers 0, 1, 101, 110011 — are quasibinary and numbers 2, 12, 900 are not.
You are given a positive integer *n*. Represent it as a sum of minimum number of quasibinary numbers. | ```python
import sys, threading
import math
from os import path
from collections import defaultdict, Counter, deque
from bisect import *
from string import ascii_lowercase
from functools import cmp_to_key
import heapq
def readInts():
x = list(map(int, (sys.stdin.readline().rstrip().split())))
re... | |
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())
vectors = [0]*n
for i in range(0,n):
vectors[i] = [int(x) for x in input().split(" ")]
#print(vectors)
if vectors[0][0]+vectors[1][0]+vectors[2][0] == 0 and vectors[0][1]+vectors[1][1]+vectors[2][1]==0:
print("YES")
else:
print("NO")
``` | |
MatrixStudio/Codeforces-Python-Submissions | Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced prog... | ```python
n,k=map(int,input().split())
dp=[[1]*(n+1) for i in range(k+1)]
for i in range(2,k+1):
for j in range(2,n+1):
for x in range(j,n+1,j):
dp[i][x]+=dp[i-1][j]
print(sum(dp[k][i] for i in range(1,n+1))%(10**9+7))
``` | |
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
a=input()
b=''
def chat(name):
prov=[]
b=''
for i in range(len(a)):
if a[i] not in prov:
b+=a[i]
prov+=a[i]
return b
b=chat(a)
if 'helo'in b:
print('YES')
else:
print('NO')
``` | |
MatrixStudio/Codeforces-Python-Submissions | The HR manager was disappointed again. The last applicant failed the interview the same way as 24 previous ones. "Do I give such a hard task?" — the HR manager thought. "Just raise number 5 to the power of *n* and get last two digits of the number. Yes, of course, *n* can be rather big, and one cannot find the power us... | ```python
print(25)
``` | |
MatrixStudio/Codeforces-Python-Submissions | The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an *n*<=×<=*n* size matrix, where *n* is odd. The Smart Beaver considers the following matrix elements good:
- Elements of the main diagonal. - Elements of the secondary diagonal. - Elements of the "middle" row — the row which ha... | ```python
a=int(input())
b=[]
c=0
d=0
for i in range(a):
c=list(map(int,input().split()))
b.append(c)
for i in range(len(b)):
d+=b[i][i]
d+=b[0-i-1][0-i-1]
d+=b[(a-1)//2+1][i]
d+=b[i][(a-1)//2+1]
print(d-(b[(a-1)//2][(a-1)//2]*3))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be *n* problems, sorted by difficulty, i.e. problem 1 is the easiest and problem *n* is the hardest. Limak knows it will take him 5·*i* minutes to solve th... | ```python
no_of_problems, time = map(int, input().split())
available_time = 240 - time
solvable_problems_count = 0
for i in range(1, no_of_problems + 1):
if available_time >= 5 * i:
solvable_problems_count += 1
available_time -= 5 * i
else:
break
print(solvable_problems_... | |
MatrixStudio/Codeforces-Python-Submissions | You have *m*<==<=*n*·*k* wooden staves. The *i*-th stave has length *a**i*. You have to assemble *n* barrels consisting of *k* staves each, you can use any *k* staves to construct a barrel. Each stave must belong to exactly one barrel.
Let volume *v**j* of barrel *j* be equal to the length of the minimal stave in it.
... | ```python
import sys
input = lambda: sys.stdin.readline().rstrip()
from collections import Counter
N,K,L = map(int, input().split())
A = list(map(int, input().split()))
A.sort()
C = Counter(A)
B = A[:N]
if B[-1]-B[0]>L:
exit(print(0))
t = min(N-1, C[B[-1]])
ans = t*B[-1]+(N-t)*B[0]
print(ans)
... | |
MatrixStudio/Codeforces-Python-Submissions | Vasily the Programmer loves romance, so this year he decided to illuminate his room with candles.
Vasily has *a* candles.When Vasily lights up a new candle, it first burns for an hour and then it goes out. Vasily is smart, so he can make *b* went out candles into a new candle. As a result, this new candle can be used ... | ```python
a,b=map(int,input().split())
if b%2==0:
print(a+b+1)
else:
print(a+b-1)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th... | ```python
def word(w):
word = ''
lower = 0
upper = 0
for i in w:
if i.islower():
lower += 1
else:
upper += 1
if upper > lower:
word = w.upper()
if upper < lower:
word = w.lower()
if u... | |
MatrixStudio/Codeforces-Python-Submissions | Bachgold problem is very easy to formulate. Given a positive integer *n* represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.
Recall that integer *k* is called prime if it is greater than 1 and has exactly two positive integer ... | ```python
n = int(input())
quotient = int(n/2)
answer = str()
count = 0
if int(n/2) < n/2 :
for _ in range (0,quotient-1) :
answer += '2 '
count+= 1
elif int(n/2) == n/2 :
for _ in range (0,quotient) :
answer += '2 '
count+= 1
if n % 2 != 0 :
answer += '3 '
... | |
MatrixStudio/Codeforces-Python-Submissions | Special Agent Smart Beaver works in a secret research department of ABBYY. He's been working there for a long time and is satisfied with his job, as it allows him to eat out in the best restaurants and order the most expensive and exotic wood types there.
The content special agent has got an important task: to get th... | ```python
hint = input()
seen = []
if 'A' <= hint[0] <= 'J':
num = 9
seen = [hint[0]]
elif '0' <= hint[0] <= '9':
num = 1
elif hint[0] == '?':
num = 9
for l in hint[1:]:
if 'A' <= l <= 'J':
if not l in seen:
num *= 10 - len(seen)
seen += [l]
elif... | |
MatrixStudio/Codeforces-Python-Submissions | High school student Vasya got a string of length *n* as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.
Vasya can change no more than *k* characters of the original strin... | ```python
n, k = map(int, input().split())
s=input()
j=0
c=0
ans=0
for i in range(n):
if(s[i]=='a'):
c+=1
while(j<n and c>k):
if(s[j]=='a'):
c-=1
j+=1
ans=max(ans,i-j+1)
j=0
c=0
for i in range(n):
if(s[i]=='b'):
c+=1
while(j<n and c>k):
... | |
MatrixStudio/Codeforces-Python-Submissions | Mary has just graduated from one well-known University and is now attending celebration party. Students like to dream of a beautiful life, so they used champagne glasses to construct a small pyramid. The height of the pyramid is *n*. The top level consists of only 1 glass, that stands on 2 glasses on the second level (... | ```python
poj = 1024
height, time = input().split()
wynik = 0
height = int(height)
time = int(time)
table = []
for i in range(height):
table.append([])
for j in range(height):
table[i].append("")
table[0][0] = time * poj
for i in range(height):
for j in range(i):
if table[... | |
MatrixStudio/Codeforces-Python-Submissions | Fox Ciel is playing a game with numbers now.
Ciel has *n* positive integers: *x*1, *x*2, ..., *x**n*. She can do the following operation as many times as needed: select two different indexes *i* and *j* such that *x**i* > *x**j* hold, and then apply assignment *x**i* = *x**i* - *x**j*. The goal is to make the sum ... | ```python
# python 3
"""
"""
def fox_and_number_game(n_int: int, numbers_list: list) -> int:
numbers_list.sort(reverse=True)
while numbers_list[0] > numbers_list[-1]:
largest_2nd_idx = 1
while numbers_list[0] == numbers_list[largest_2nd_idx]:
largest_2nd_idx += 1
numbers_li... | |
MatrixStudio/Codeforces-Python-Submissions | In some game by Playrix it takes *t* minutes for an oven to bake *k* carrot cakes, all cakes are ready at the same moment *t* minutes after they started baking. Arkady needs at least *n* cakes to complete a task, but he currently don't have any. However, he has infinitely many ingredients and one oven. Moreover, Arkady... | ```python
n, t, k, d = map(int, input().split())
x1 = (n * t) / k # Time required ta bake using only one oven
c = (k * d) / t # Number of cakes baked while building the oven
n = n - c # remaining cakes
# Calculate the time required to bake the remiaing cakes after building the second oven-it will half time of ... | |
MatrixStudio/Codeforces-Python-Submissions | Fox Ciel has some flowers: *r* red flowers, *g* green flowers and *b* blue flowers. She wants to use these flowers to make several bouquets. There are 4 types of bouquets:
- To make a "red bouquet", it needs 3 red flowers. - To make a "green bouquet", it needs 3 green flowers. - To make a "blue bouquet", it needs 3... | ```python
from itertools import permutations
r,b,g=list(map(int,input().split()))
lis=permutations([0,1,2,3])
def function(num,arr):
ans=0
for i in range(4):
if num[i]==0:
if arr[0]>2:
temp=arr[0]//3
arr[0]-=(3*temp)
ans+temp
... | |
MatrixStudio/Codeforces-Python-Submissions | A classroom in a school has six rows with 3 desks in each row. Two people can use the same desk: one sitting on the left and one sitting on the right.
Some places are already occupied, and some places are vacant. Petya has just entered the class and wants to occupy the most convenient place. The conveniences of the p... | ```python
n=6
arr=[]
convinience=[[3,3,0,4,4,0,3,3],[3,3,0,4,4,0,3,3],[2,2,0,3,3,0,3,3],[2,2,0,3,3,0,3,3],[1,1,0,2,2,0,1,1],[1,1,0,2,2,0,1,1]]
for i in range(n):
arr.append(input().strip())
ans=[]
for i in range(n):
for j in range(n):
if arr[i][j]=='.':
ans.append([convinience[i][j]... | |
MatrixStudio/Codeforces-Python-Submissions | Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.
The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe... | ```python
math = input()
symbol = "+"
mathstr = []
for char in math:
if char not in symbol:
mathstr += char
mathstr.sort()
mathstr2 = ''.join(mathstr)
ans = "+".join(mathstr2)
print(ans)
``` | |
MatrixStudio/Codeforces-Python-Submissions | You are given two integers *n* and *k*. Find *k*-th smallest divisor of *n*, or report that it doesn't exist.
Divisor of *n* is any such natural number, that *n* can be divided by it without remainder. | ```python
import math
def div(n):
li=set()
for i in range(1,int(math.sqrt(n))+1):
if n%i==0:
li.add(i)
li.add(n//i)
return list(li)
x=input().split(" ")
n=div(int(x[0]))
k=int(x[1])
print(n[k-1])
``` | |
MatrixStudio/Codeforces-Python-Submissions | Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm:
- if the last digit of the number is non-zero, she decreases the number by one; - if the last digit of the number is zero,... | ```python
n = int(input())
k = int(input())
for i in range(k):
if n % 10==0:
n/10
else:
n-1
print(n)
``` | |
MatrixStudio/Codeforces-Python-Submissions | You are given two integers $a$ and $b$. Moreover, you are given a sequence $s_0, s_1, \dots, s_{n}$. All values in $s$ are integers $1$ or $-1$. It's known that sequence is $k$-periodic and $k$ divides $n+1$. In other words, for each $k \leq i \leq n$ it's satisfied that $s_{i} = s_{i - k}$.
Find out the non-negative ... | ```python
def binPow(a,n):
if n==0:
return 1
result=binPow(a,n//2)
if n%2==1:
return ((result%mod)*(result%mod)*(a%mod))%mod
else:
return ((result%mod)*(result%mod))%mod
def modInv(a):
return binPow(a,mod-2)
mod=10**9+9
n,a,b,k=map(int,input().split())
s=input()
... | |
MatrixStudio/Codeforces-Python-Submissions | Mike is trying rock climbing but he is awful at it.
There are *n* holds on the wall, *i*-th hold is at height *a**i* off the ground. Besides, let the sequence *a**i* increase, that is, *a**i*<=<<=*a**i*<=+<=1 for all *i* from 1 to *n*<=-<=1; we will call such sequence a track. Mike thinks that the track *a*1, ...,... | ```python
input()
nums=list(map(int,input().split()))
ans=0
ans2=[]
for i in range(1,len(nums)):
s=sum(nums[:i]+nums[i+1:])
if s>ans:
ans=s
ans2=nums[:i]+nums[i+1:]
maxii=0
for i in range(len(ans2)-1):
maxii=max(maxii,ans2[i+1]-ans2[i])
print(maxii)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Famil Door wants to celebrate his birthday with his friends from Far Far Away. He has *n* friends and each of them can come to the party in a specific range of days of the year from *a**i* to *b**i*. Of course, Famil Door wants to have as many friends celebrating together with him as possible.
Far cars are as weird as... | ```python
T= int(input())
for h in range(T):
n,g,b = map(int,input().split())
if n<=g:
print(n)
elif g>=b:
print(n)
elif b>g:
k = (n+1)//2
h= k//g
alpha = (h-1)*b+h*g
if (k%g)!=0:
alpha=alpha+b+(k%g)
print(max(n,alpha... | |
MatrixStudio/Codeforces-Python-Submissions | Little penguin Polo loves his home village. The village has *n* houses, indexed by integers from 1 to *n*. Each house has a plaque containing an integer, the *i*-th house has a plaque containing integer *p**i* (1<=≤<=*p**i*<=≤<=*n*).
Little penguin Polo loves walking around this village. The walk looks like that. Firs... | ```python
def number_of_ways(n: int, k: int) -> int:
mod = int(1e9) + 7
return (pow(k,k-1,mod)*pow(n-k,n-k,mod))%mod
n,k = [int(i) for i in input().split()]
print(number_of_ways(n, k))
``` | |
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
n=int(input())
for i in range(n):
a=str(input())
l=[i for i in a]
if len(l)>10:
print(str(l[0])+str(len(l)-2)+str(l[-1]))
else:
print(a)
``` | |
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 with... | ```python
a, b, r = map(int, input().split())
flag = 1
while 2 * r <= a and 2 * r <= b:
a = a - 2 * r
b = b - 2 * r
flag = -1 * flag
if flag == -1:
print("First")
else:
print("Second")
``` | |
MatrixStudio/Codeforces-Python-Submissions | Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers *a*, *b*, *c* on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resul... | ```python
a = int(input())
b = int(input())
c = int(input())
case1 = (a + b) * c
case2 = a * b * c
print(max(case1, case2))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Vasya has found a strange device. On the front panel of a device there are: a red button, a blue button and a display showing some positive integer. After clicking the red button, device multiplies the displayed number by two. After clicking the blue button, device subtracts one from the number on the display. If at so... | ```python
import math
a,b=input().split()
a,b=int(a), int(b)
j=0
if a<b:
f= int(math.log2(b/a))+1
p=(a*2**f-b)
while p>0:
k=int(math.log2(p))
if k>f:
k=f
o=2**k
p-=o
j+=1
print(j+f)
else:
print(a-b)
``` | |
MatrixStudio/Codeforces-Python-Submissions | You have *n* distinct points on a plane, none of them lie on *OY* axis. Check that there is a point after removal of which the remaining points are located on one side of the *OY* axis. | ```python
m=int(input())
cnt=0
cnt1=0
for i in range(m):
m,n=map(int,input().split())
if m>0:
cnt+=1
if m<0:
cnt1+=1
if cnt==m or cnt==m-1 or cnt==0 or cnt==1:
print("Yes")
else:
print("No")
``` | |
MatrixStudio/Codeforces-Python-Submissions | A top-secret military base under the command of Colonel Zuev is expecting an inspection from the Ministry of Defence. According to the charter, each top-secret military base must include a top-secret troop that should... well, we cannot tell you exactly what it should do, it is a top secret troop at the end. The proble... | ```python
# i'm from jasnah, do not ban me
def main():
n, m, k = map(int, input().split())
f = [[float('inf')] * 40001 for _ in range(201)]
for i in range(k + 1):
f[0][i] = 0
x_list = list(map(int, input().split()))
for i in range(1, n + 1):
x = x_list[i-1]
... | |
MatrixStudio/Codeforces-Python-Submissions | Imp likes his plush toy a lot.
Recently, he found a machine that can clone plush toys. Imp knows that if he applies the machine to an original toy, he additionally gets one more original toy and one copy, and if he applies the machine to a copied toy, he gets two additional copies.
Initially, Imp has only one origina... | ```python
x=int(input("Enter X copies"))
y=int(input("Enter Y copies"))
if (y==0)or(y==1 and x>0)or(x%2==y%2):
print("NO")
else:
print("YES")
``` | |
MatrixStudio/Codeforces-Python-Submissions | In Berland it is the holiday of equality. In honor of the holiday the king decided to equalize the welfare of all citizens in Berland by the expense of the state treasury.
Totally in Berland there are *n* citizens, the welfare of each of them is estimated as the integer in *a**i* burles (burle is the currency in Berl... | ```python
n=int(input())
l=list(map(int,input().split()))
s=0
for i in l:
s=s+max(l)-i
print(s)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Today, Wet Shark is given *n* integers. Using any of these integers no more than once, Wet Shark wants to get maximum possible even (divisible by 2) sum. Please, calculate this value for Wet Shark.
Note, that if Wet Shark uses no integers from the *n* integers, the sum is an even integer 0. | ```python
arr = []
n = input()
n = int(n)
summ = int(0)
arr_sum = 0
# for i in range(n):
#arr.append(input().split())
arr = list(map(int, input().strip().split()))
# arr = [int(i) for i in arr]
arr.sort(reverse = True)
for i in arr:
arr_sum = arr_sum + i
# print(arr)
# print(arr_sum)
# for... | |
MatrixStudio/Codeforces-Python-Submissions | Ilya is a very clever lion, he lives in an unusual city ZooVille. In this city all the animals have their rights and obligations. Moreover, they even have their own bank accounts. The state of a bank account is an integer. The state of a bank account can be a negative number. This means that the owner of the account ow... | ```python
amount=int(input())
if amount>=0:
print(amount)
elif amount>=-9:
print(0)
else:
s=str(amount)
if s[1]>=s[2]:
s=s[:len(s)-2:]+s[2]
else:
s=s[:len(s)-2:]+s[1]
print(int(s))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Andryusha is an orderly boy and likes to keep things in their place.
Today he faced a problem to put his socks in the wardrobe. He has *n* distinct pairs of socks which are initially in a bag. The pairs are numbered from 1 to *n*. Andryusha wants to put paired socks together and put them in the wardrobe. He takes the ... | ```python
x=[]
w=[]
s=0
n=int(input())
z =list(map(int, str_in.strip().split()))
for i in range n:
if x.count(z[i])==0:
s=s+1
x.append(z[i])
w.append(s)
else:
s=s-1
w.append(s)
print(max(w))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Ted has a pineapple. This pineapple is able to bark like a bulldog! At time *t* (in seconds) it barks for the first time. Then every *s* seconds after it, it barks twice with 1 second interval. Thus it barks at times *t*, *t*<=+<=*s*, *t*<=+<=*s*<=+<=1, *t*<=+<=2*s*, *t*<=+<=2*s*<=+<=1, etc.
Barney woke up in the morn... | ```python
t,s,x=map(int,input().split())
print(t,s,x)
a=0
for i in range(x):
if t==x :
a+=1
elif t+s==x or t+s+1==x:
a+=1
t+=s
if t+1>x:
break
if a>0:
print("Yes")
else:
print("No")
``` | |
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. Be... | ```python
n,m = input().split()
b = []
c = []
d = 0
e = 0
for x in range(1,int(n)+1):
a = input()
b.append(a)
for x in b:
for y in x:
c.append(y)
c = set(c)
c = list(c)
if len(c) == 1:
d=1
else:
d=0
break
c.clear()
if d==1:
for x in... | |
MatrixStudio/Codeforces-Python-Submissions | Little penguin Polo likes permutations. But most of all he likes permutations of integers from 0 to *n*, inclusive.
For permutation *p*<==<=*p*0,<=*p*1,<=...,<=*p**n*, Polo has defined its beauty — number .
Expression means applying the operation of bitwise excluding "OR" to numbers *x* and *y*. This operation exist... | ```python
from itertools import permutations
n = int(input())
bool = [False]*(n+1)
ans = [0]*(n+1)
mask = (1<<20)-1
for i in range(n,-1,-1):
while (mask^i) > n or bool[mask^i]:
mask = mask>>1
ans[i]= mask^i
bool[mask^i] =True
print(n*(n+1))
for i in range(n+1): prin... | |
MatrixStudio/Codeforces-Python-Submissions | «Polygon» is a system which allows to create programming tasks in a simple and professional way. When you add a test to the problem, the corresponding form asks you for the test index. As in most cases it is clear which index the next test will have, the system suggests the default value of the index. It is calculated ... | ```python
# import math
# import bisect
import sys
# from collections import OrderedDict
input = sys.stdin.readline
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(s[:len(s)-1])
def invr():
return(map(int,input().split()))
N = inp()
A... | |
MatrixStudio/Codeforces-Python-Submissions | After passing a test, Vasya got himself a box of $n$ candies. He decided to eat an equal amount of candies each morning until there are no more candies. However, Petya also noticed the box and decided to get some candies for himself.
This means the process of eating candies is the following: in the beginning Vasya cho... | ```python
n = int(input())
left = 1
right = n
def check(middle):
k1 = 0
k2 = 0
x = n
while x > 0:
if x < middle:
x = 0
k1 += x
else:
x -= middle
k1 += middle
k2 += x // 10
x -= x // 10
if k1 >= n ... | |
MatrixStudio/Codeforces-Python-Submissions | Vasya decided to learn to play chess. Classic chess doesn't seem interesting to him, so he plays his own sort of chess.
The queen is the piece that captures all squares on its vertical, horizontal and diagonal lines. If the cell is located on the same vertical, horizontal or diagonal line with queen, and the cell cont... | ```python
import sys
from math import *
from fractions import gcd
readints=lambda:map(int, input().strip('\n').split())
n=int(input())
if n==2:
print('white')
print('1 2')
elif n==3:
print('black')
else:
print('white')
print('2 1')
``` | |
MatrixStudio/Codeforces-Python-Submissions | Holidays have finished. Thanks to the help of the hacker Leha, Noora managed to enter the university of her dreams which is located in a town Pavlopolis. It's well known that universities provide students with dormitory for the period of university studies. Consequently Noora had to leave Vičkopolis and move to Pavlopo... | ```python
import math
d,m = map(int, input().split())
out = 1
d = min(d,m)
for i in range(2,d+1):
out= out*i
print(out)
``` | |
MatrixStudio/Codeforces-Python-Submissions | There is the faculty of Computer Science in Berland. In the social net "TheContact!" for each course of this faculty there is the special group whose name equals the year of university entrance of corresponding course of students at the university.
Each of students joins the group of his course and joins all groups f... | ```python
n = int(input())
years = sorted((map(int, input().split())))
print(years[len(years)//2])
``` | |
MatrixStudio/Codeforces-Python-Submissions | You are given a string *A*. Find a string *B*, where *B* is a palindrome and *A* is a subsequence of *B*.
A subsequence of a string is a string that can be derived from it by deleting some (not necessarily consecutive) characters without changing the order of the remaining characters. For example, "cotst" is a subsequ... | ```python
line= input()
len1=len(line)
string = line[::-1]
print(line+string)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Little Vasya has received a young builder’s kit. The kit consists of several wooden bars, the lengths of all of them are known. The bars can be put one on the top of the other if their lengths are the same.
Vasya wants to construct the minimal number of towers from the bars. Help Vasya to use the bars in the best way ... | ```python
n=int(input())
lst=list(map(int,input().split(' ')))
lst2=list()
for i in lst:
if i not in lst2:
lst2.append(i)
dct=dict()
for item in lst:
if item not in dct:
dct[item]=1
else:
dct[item]= dct[item]+1
mx_lst=max(dct.values())
total=len(lst2)
print(mx_lst,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 rem... | ```python
n = int(input())
s = input()
cy , cn =0, 0
for i in range(len(s)-1):
if s[i]+s[i+1]=='SF':
cy+=1
continue
if s[i]+s[i+1]=='FS':
cn+=1
if cy>cn:
print("YES")
else:
print("NO")
``` | |
MatrixStudio/Codeforces-Python-Submissions | You are given a rectangular board of *M*<=×<=*N* squares. Also you are given an unlimited number of standard domino pieces of 2<=×<=1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers ... | ```python
import math
def req_sqs(n, m):
if 1<=n<m<=16:
b = math.ceil(n / 2)
l = math.ceil(m / 1)
elif n==m:
b = math.ceil(n / 2)
l = math.ceil(m / 2)
elif n>m:
b = math.ceil(n / 1)
l = math.ceil(m / 2)
result=l*b
return result
n,m=map(int,input().split())
result = re... | |
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
for _ in range(int(input())):
x = input()
if len(x)<=10:
print(x)
else:
print(x[0],len(x)-2,x[-1])
``` | |
MatrixStudio/Codeforces-Python-Submissions | Sheldon, Leonard, Penny, Rajesh and Howard are in the queue for a "Double Cola" drink vending machine; there are no other people in the queue. The first one in the queue (Sheldon) buys a can, drinks it and doubles! The resulting two Sheldons go to the end of the queue. Then the next in the queue (Leonard) buys a can, d... | ```python
n = int(input())
i = 0
names = ["Sheldon","Leonard","Penny","Rajesh","Howard"]
while n-(2**i)*5 > 0:
n -= (2**i)*5
i += 1
b = 2**i
for k in range(5):
if k<4 and k*b<n and n<=(k+1)*b:
break
print(names[k])
``` | |
MatrixStudio/Codeforces-Python-Submissions | In the city of Ultima Thule job applicants are often offered an IQ test.
The test is as follows: the person gets a piece of squared paper with a 4<=×<=4 square painted on it. Some of the square's cells are painted black and others are painted white. Your task is to repaint at most one cell the other color so that the... | ```python
a,t=[input(),input(),input(),input()],1
for i in range(0,3):
for j in range(0,3):
l=a[i][j]+a[i][j+1]+a[i+1][j]+a[i+1][j+1]
r=l.count("#")
if r!=2:
t=0
break
if not t:
break
print("YNEOS"[t::2])
``` | |
MatrixStudio/Codeforces-Python-Submissions | Valera is a lazy student. He has *m* clean bowls and *k* clean plates.
Valera has made an eating plan for the next *n* days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can... | ```python
n,m,k=list(map(int,input().split()))
a=list(map(int,input().split()))
res=0
for i in range(n):
if a[i]==1:
if m==0:
res+=1
else:
m-=1
elif a[i]==2:
if k==0:
if m==0:
res+=1
else:
m-=... | |
MatrixStudio/Codeforces-Python-Submissions | An *n*<=×<=*n* table *a* is defined as follows:
- The first row and the first column contain ones, that is: *a**i*,<=1<==<=*a*1,<=*i*<==<=1 for all *i*<==<=1,<=2,<=...,<=*n*. - Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the ... | ```python
from math import factorial
n = int(input())-1
r = (factorial(2*n))//(pow(factorial(n),2))
print(r)
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.