source stringclasses 3
values | instruction stringlengths 23 3.97k | input stringclasses 1
value | output stringlengths 1 3.75k |
|---|---|---|---|
MatrixStudio/Codeforces-Python-Submissions | You are given a tetrahedron. Let's mark its vertices with letters *A*, *B*, *C* and *D* correspondingly.
An ant is standing in the vertex *D* of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. ... | ```python
import sys
import math
from collections import Counter
input = sys.stdin.readline
N = 1000000007
#use input().strip()
def multiply(a, b):
mul = [[0 for x in range(2)]
for y in range(2)]
for i in range(2):
for j in range(2):
for k in range(2):
mul[i][j] += a[i][k] * b[k][j]
for... | |
MatrixStudio/Codeforces-Python-Submissions | You are given two lists of non-zero digits.
Let's call an integer pretty if its (base 10) representation has at least one digit from the first list and at least one digit from the second list. What is the smallest positive pretty integer? | ```python
x,y = input().split()
x = int(x)
y = int(y)
o = list(map(int, input().split()))
p = list(map(int, input().split()))
o.sort()
p.sort()
a = len(o)
b = len(p)
i = 0
j = 0
while(i < a):
while(j < b):
if(o[i] == p[j]):
print(o[i])
break
else:
j = j+1
... | |
MatrixStudio/Codeforces-Python-Submissions | A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not.
The next prime number after *x* is the smallest prime number greater than *x*. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note t... | ```python
def isPrime(n):
# Corner case
if (n <= 1):
return False
# Check from 2 to n-1
for i in range(2, n):
if (n % i == 0):
return False
return True
a=[int(i) for i in input().split()]
primes=[]
for i in range(a[0],a[1]+1):
primes.append(isPrim... | |
MatrixStudio/Codeforces-Python-Submissions | Polycarp watched TV-show where *k* jury members one by one rated a participant by adding him a certain number of points (may be negative, i. e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the *i*-th jury member gave *a**i* po... | ```python
# Jury Marks
k, n = list(map(int, input().split(' ')))
jury_marks = list(map(int, input().split(' ')))
poly_marks = list(map(int, input().split(' ')))
potential = set()
current = poly_marks[0]
for mark in jury_marks:
current += -1 * mark
potential.add(current)
count = 0
for num in po... | |
MatrixStudio/Codeforces-Python-Submissions | There are *n* servers in a laboratory, each of them can perform tasks. Each server has a unique id — integer from 1 to *n*.
It is known that during the day *q* tasks will come, the *i*-th of them is characterized with three integers: *t**i* — the moment in seconds in which the task will come, *k**i* — the number of se... | ```python
def main():
n, k = map(int, input().split())
ser = [0] * n
for i in range(k):
t, ki, v = map(int, input().split())
ans = 0
for el in ser:
if el < t:
ans += 1
if ans > ki: break
if ans >= ki:
ans = 0
... | |
MatrixStudio/Codeforces-Python-Submissions | You are given two positive integer numbers *a* and *b*. Permute (change order) of the digits of *a* to construct maximal number not exceeding *b*. No number in input and/or output can start with the digit 0.
It is allowed to leave *a* as it is. | ```python
a = sorted(input())
b = int(input())
a = a[::-1]
p = ""
while a:
for i, z in enumerate(a):
n = p + a[i] + "".join(sorted(a[:i]+a[i+1:]))
if int(n)<=b:
p += z
a.pop(i)
break
print(p)
``` | |
MatrixStudio/Codeforces-Python-Submissions | A new Berland businessman Vitaly is going to open a household appliances' store. All he's got to do now is to hire the staff.
The store will work seven days a week, but not around the clock. Every day at least *k* people must work in the store.
Berland has a law that determines the order of working days and non-worki... | ```python
n,m,k = map(int,input().split())
ans = [1 for i in range(k)]
transition = True
for i in range(n-1, n+m):
if transition:
if ans[-k]+n == i+1:
ans.append(i)
if k > 1:
transition = False
else:
if ans[-k]+n == i:
ans.extend([i]*(max... | |
MatrixStudio/Codeforces-Python-Submissions | Recently *n* students from city S moved to city P to attend a programming camp.
They moved there by train. In the evening, all students in the train decided that they want to drink some tea. Of course, no two people can use the same teapot simultaneously, so the students had to form a queue to get their tea.
*i*-th s... | ```python
import sys
input = sys.stdin.readline
for _ in range(int(input())):
n = int(input())
g = [list(map(int, input().split())) for _ in range(n)]
d = []
c = 1
x = 0
for i in range(n):
if g[i][0] - x >= c:
d.append(g[i][0])
c = g[i][0] + 1
... | |
MatrixStudio/Codeforces-Python-Submissions | Let quasi-palindromic number be such number that adding some leading zeros (possible none) to it produces a palindromic string.
String *t* is called a palindrome, if it reads the same from left to right and from right to left.
For example, numbers 131 and 2010200 are quasi-palindromic, they can be transformed to str... | ```python
a=input()
i=len(a)-1
while(a[i]=='0'):i-=1
if a[:i+1]==a[len(a)-i+1::-1]:print("YES")
else:print("NO")
``` | |
MatrixStudio/Codeforces-Python-Submissions | Sometimes one has to spell email addresses over the phone. Then one usually pronounces a dot as dot, an at sign as at. As a result, we get something like vasyaatgmaildotcom. Your task is to transform it into a proper email address ([[email protected]](/cdn-cgi/l/email-protection)).
It is known that a proper email add... | ```python
email = input()
idx_at = email.index("at")
idx_dot = email.index("dot")
print(email[0:idx_at] + "@" + email[idx_at+2:idx_dot] + "." + email[idx_dot+3:len(email)])
``` | |
MatrixStudio/Codeforces-Python-Submissions | One day Kefa found *n* baloons. For convenience, we denote color of *i*-th baloon as *s**i* — lowercase letter of the Latin alphabet. Also Kefa has *k* friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. Help Kefa to find out, can he give out all his... | ```python
ballons, friends = map(int, input().split())
color = input()
lencolor = len(color)
x = 0
count = [0] * 26 # букв всего 26б значит и индекс не мсжет быть болше 26
# tkcb кол-во одного цвета больше чем друзейб кто-то получит два одного цвета
for i in color:
nomer = ord(i) - 97
count[nomer] += 1... | |
MatrixStudio/Codeforces-Python-Submissions | Once upon a time a child got a test consisting of multiple-choice questions as homework. A multiple-choice question consists of four choices: A, B, C and D. Each choice has a description, and the child should find out the only one that is correct.
Fortunately the child knows how to solve such complicated test. The chi... | ```python
a=input()
b=input()
c=input()
d=input()
if((len(a)-2)>=(len(b)-2)*2 and (len(a)-2)>=(len(c)-2)*2 and (len(a)-2)>=(len(d)-2)*2):
print("A")
elif((len(b)-2)>=(len(a)-2)*2 and (len(b)-2)>=(len(c)-2)*2 and (len(b)-2)>=(len(d)-2)*2):
print("B")
elif((len(d)-2)>=(len(b)-2)*2 and (len(d)-2)>=(len(c)-... | |
MatrixStudio/Codeforces-Python-Submissions | Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones.
Once he thought about a string of length *n* consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, an... | ```python
#556A - Case of the Zeros and Ones
x,s=int(input()),input()
print(abs(s.count("0")-s.count("1")))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Vasya's bicycle chain drive consists of two parts: *n* stars are attached to the pedal axle, *m* stars are attached to the rear wheel axle. The chain helps to rotate the rear wheel by transmitting the pedal rotation.
We know that the *i*-th star on the pedal axle has *a**i* (0<=<<=*a*1<=<<=*a*2<=<<=...<=<<... | ```python
n = int(input())
first = list(map(int , input().split()))
m = int(input())
second = list(map(int , input().split()))
maximum = 0
count = 0
for i in first:
for j in second:
if j%i == 0:
temp = j%i
if temp > maximum:
maximum = temp
count = 1
elif temp == maximum:
count += 1... | |
MatrixStudio/Codeforces-Python-Submissions | We've got no test cases. A big olympiad is coming up. But the problemsetters' number one priority should be adding another problem to the round.
The diameter of a multiset of points on the line is the largest distance between two points from this set. For example, the diameter of the multiset {1,<=3,<=2,<=1} is 2.
D... | ```python
# http://codeforces.com/contest/940/problem/A
import sys
n_and_d = sys.stdin.readline()
tmp = n_and_d.split(' ')
n = int(tmp[0])
d = int(tmp[1])
l = sys.stdin.readline().strip().split(' ')
l = [int(l[i]) for i in range(0, n)]
l.sort()
min = n
for i in range(0, n):
upper_bound_value ... | |
MatrixStudio/Codeforces-Python-Submissions | You are given two arrays *A* and *B* consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose *k* numbers in array *A* and choose *m* numbers in array *B* so that any number chosen in the first array is strictly less than any number chosen in the second array. | ```python
na, nb = map(int, input().split(" "))
ma, mb = map(int, input().split(" "))
LA = [int(x) for x in input().split()]
LA.sort()
LB = [int(x) for x in input().split()]
LB.sort()
if (LA[ma - 1] < LB[nb - mb]): print("YES")
else : print("NO")
``` | |
MatrixStudio/Codeforces-Python-Submissions | You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes.
You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consi... | ```python
n, m = map(int, input().split(" "))
graph = dict()
for i in range(m):
s1, s2 = map(str, input().split(" "))
graph[s1] = s2
s = list(input().split(" "))
for i in range(len(s)):
if len(s[i]) > len(graph[s[i]]):
s[i] = graph[s[i]]
print(" ".join(s))
``` | |
MatrixStudio/Codeforces-Python-Submissions | In a small but very proud high school it was decided to win ACM ICPC. This goal requires to compose as many teams of three as possible, but since there were only 6 students who wished to participate, the decision was to build exactly two teams.
After practice competition, participant number *i* got a score of *a**i*. ... | ```python
a = list(map(int, input().split()))
for i in range(4):
for j in range(i + 1, 5):
for k in range(j + 1, 6):
if 2 * (a[i] + a[j] + a[k]) == sum(a):
print('YES')
exit()
print('NO')
``` | |
MatrixStudio/Codeforces-Python-Submissions | Polycarp has created his own training plan to prepare for the programming contests. He will train for $n$ days, all days are numbered from $1$ to $n$, beginning from the first.
On the $i$-th day Polycarp will necessarily solve $a_i$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on... | ```python
a= array('i',[])
sum1 = 0
sm = 0
n= int(input())
for i in range(n):
x=int(input())
a.append(x)
for l in a:
sum1=sum1+l
sum1=(sum1/2)
val=0
for m in a:
sm=sm+m
if(sm>=sum1):
break
else:
val=val+1
print(val+1)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Little Petya often travels to his grandmother in the countryside. The grandmother has a large garden, which can be represented as a rectangle 1<=×<=*n* in size, when viewed from above. This rectangle is divided into *n* equal square sections. The garden is very unusual as each of the square sections possesses its own f... | ```python
size = int(input())
number_section = list(map(int,input().split()))
counter=1
#find max
maximum =0
index_max=-1
for x in range(size):
if number_section[x]>maximum:
maximum=number_section[x]
index_max=x
if index_max==0:
#go right -->
for x in range(size-1):
... | |
MatrixStudio/Codeforces-Python-Submissions | Shaass has *n* books. He wants to make a bookshelf for all his books. He wants the bookshelf's dimensions to be as small as possible. The thickness of the *i*-th book is *t**i* and its pages' width is equal to *w**i*. The thickness of each book is either 1 or 2. All books have the same page heights.
Shaass puts the bo... | ```python
n = int(input())
dif=[]
li1=[]
li2=[]
a1=b1=0
#print(lis)
for i in range(n):
a,b=map(int,input().split())
if a==1:
li1.append(b)
else:
li2.append(b)
li1.sort(reverse=True)
li2.sort(reverse=True)
l1=len(li1)
l2=len(li2)
ans=10000000000
for i in range(l1):
for j... | |
MatrixStudio/Codeforces-Python-Submissions | You are given a text of single-space separated words, consisting of small and capital Latin letters.
Volume of the word is number of capital letters in the word. Volume of the text is maximum volume of all words in the text.
Calculate the volume of the given text. | ```python
n=int(input())
x=[]
y=list(input().split())
for i in y:
m=0
for j in i:
if 65<=ord(j)<=90:
m+=1
x.append(m)
print(max(x))
``` | |
MatrixStudio/Codeforces-Python-Submissions | You helped Dima to have a great weekend, but it's time to work. Naturally, Dima, as all other men who have girlfriends, does everything wrong.
Inna and Dima are now in one room. Inna tells Dima off for everything he does in her presence. After Inna tells him off for something, she goes to another room, walks there in ... | ```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()))
mod = int(1e9)+7
n, k = rinput()
a = get_list()
ans... | |
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())
aA = [0] * 3
for i in range(N):
bB = [int(x) for x in input().split()]
for j in range(3):
aA[j] += bB[j]
res = [x for x in aA if x == 0]
print('YES' if len(res) == 3 else 'NO')
``` | |
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
n=int(input())
a=sorted(map(int,input().split()))
if (n<2):
print(-1)
else:
count={}
I=range(n-1)
for i in I:
d=a[i+1]-a[i]
count[d]=count.get(d,0)+1
d=min(count)
if( count[d]<n-2):
print(0)
else:
b=set()
if( count[d]+1==n):
b.add(a... | |
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
n = int(input())
arr = list(map(int,input().split(' ')))
if n == 1:
summary = arr[0]
elif n == 2:
summary = max(arr[0],arr[1])
else:
summary = 0
for i in range(1,n-1):
if arr[i] >= arr[i-1] + arr[i+1]:
summary += arr[i]
arr[i-1] = 0
arr[i... | |
MatrixStudio/Codeforces-Python-Submissions | Let's call a number *k*-good if it contains all digits not exceeding *k* (0,<=...,<=*k*). You've got a number *k* and an array *a* containing *n* numbers. Find out how many *k*-good numbers are in *a* (count each number every time it occurs in array *a*). | ```python
a,b=map(int,input().split())
l=[]
for i in range(a):
l.append(input())
for j in l:
x=0
for i in range(b+1):
if str(i) not in j:
x=1
if x!=1:
c=c+1
print(c)
``` | |
MatrixStudio/Codeforces-Python-Submissions | In Berland, there is the national holiday coming — the Flag Day. In the honor of this event the president of the country decided to make a big dance party and asked your agency to organize it. He has several conditions:
- overall, there must be *m* dances;- exactly three people must take part in each dance;- each d... | ```python
n,m=map(int,input().split())
lst=[0 for i in range(n+1)]
for j in range(m):
dancers=list(map(int,input().split()))
color=[lst[dancers[0]],lst[dancers[1]],lst[dancers[2]]]
for i in range(3):
if(lst[dancers[i]]!=0):
continue
else:
if(1 not in color):
... | |
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
def check(w):
dirw = {}
dirh = {}
hello = "hello"
for i in w:
if i not in dirw:
dirw[i] = 0
dirw[i] += 1
for i in hello:
if i not in dirh:
dirh[i] = 0
dirh[i] += 1
l = []
for k,v in dirh.items():
if k... | |
MatrixStudio/Codeforces-Python-Submissions | Vasya is going to the Olympics in the city Ntown by train. The boy wants to read the textbook to prepare for the Olympics. He counted that he needed *k* hours for this. He also found that the light in the train changes every hour. The light is measured on a scale from 0 to 100, where 0 is very dark, and 100 is very lig... | ```python
f = open("input.txt", "r")
n, k = map(int, f.readline().split())
a, b = list(zip(*sorted(zip(map(int, f.readline().split()), range(1,n+1)))))
f = open("output.txt", "w")
print(a[n-k], file=f)
print(' '.join(map(str, b[n-k:])), file=f)
``` | |
MatrixStudio/Codeforces-Python-Submissions | The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a pla... | ```python
n=int(input())
d={}
t={}
turn=0
while(n):
a=input().split()
if(a[0] not in d):
d[a[0]]=[]
t[a[0]]=[]
d[a[0]].append(int(a[1]))
turn+=1
t[a[0]].append(turn)
n-=1
maxm=-1
for i in d:
maxm=max(maxm, sum(d[i]))
c={}
for i in d:
if(sum(d[i])==maxm):
c[i]=d[i]
e={}
for i in c:
s... | |
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
def f(a, b):
if a % b == 0:return a // b
else:return a // b + 1
n, m, k = map(int, input().split())
first = f(n, k)
scond = f(m, k)
print(first * scond)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him.
The park consists of 2*n*<=+<=1<=-<=1 squares connected by roads so... | ```python
n = int(input())
edge = 0
depth = 1
for _ in range(n):
depth *= 2
edge += depth
lights = list(map(int, input().split()))
total = 0
while depth > 1:
size = len(lights)
for i in range(depth // 2):
a = lights.pop()
b = lights.pop()
... | |
MatrixStudio/Codeforces-Python-Submissions | You have *a* nuts and lots of boxes. The boxes have a wonderful feature: if you put *x* (*x*<=≥<=0) divisors (the spacial bars that can divide a box) to it, you get a box, divided into *x*<=+<=1 sections.
You are minimalist. Therefore, on the one hand, you are against dividing some box into more than *k* sections. On ... | ```python
k,a,d,v=map(int,input().split())
s=0
m=round(d/k)
s+=m
a-=v*m*k
d-=(k-1)*m
if d:
s+=1
a-=(d+1)*v
if a>0 and a%v==0:s+=a//v
elif a>0 and a%v!=0:s+=a//v+1
print(s)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Mike has a string *s* consisting of only lowercase English letters. He wants to change exactly one character from the string so that the resulting one is a palindrome.
A palindrome is a string that reads the same backward as forward, for example strings "z", "aaa", "aba", "abccba" are palindromes, but strings "codefo... | ```python
s = list(input())
f = s[0:len(s)//2]
ss = s.copy()
ss.reverse()
s.reverse()
f1 = s[0:len(s)//2]
c = 0
for i in range(len(f)):
if f[i] != f1[i]:
c += 1
print("YES" if c == 1 or ss == s else "NO")
``` | |
MatrixStudio/Codeforces-Python-Submissions | Bertown is under siege! The attackers have blocked all the ways out and their cannon is bombarding the city. Fortunately, Berland intelligence managed to intercept the enemies' shooting plan. Let's introduce the Cartesian system of coordinates, the origin of which coincides with the cannon's position, the *Ox* axis is ... | ```python
print("_RANDOM_GUESS_1689432413.4650924")# 1689432413.4651115
``` | |
MatrixStudio/Codeforces-Python-Submissions | You are given two arrays *A* and *B* consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose *k* numbers in array *A* and choose *m* numbers in array *B* so that any number chosen in the first array is strictly less than any number chosen in the second array. | ```python
n1, n2 = [int(x) for x in input().split()]
k, m = [int(x) for x in input().split()]
l1 = [int(x) for x in input().split()]
l2 = [int(x) for x in input().split()]
max_in_l1 = sorted(l1)[k-1]
min_in_l2 = sorted(l2)[0]
if max_in_l1 < min_in_l2:
print('YES')
else:
print('NO')
``` | |
MatrixStudio/Codeforces-Python-Submissions | A number is called almost prime if it has exactly two distinct prime divisors. For example, numbers 6, 18, 24 are almost prime, while 4, 8, 9, 42 are not. Find the amount of almost prime numbers which are between 1 and *n*, inclusive. | ```python
n = int(input())
count = 0
final_count = 0
prime_count = 0
for i in range(1, n+1):
for j in range(1, i + 1):
prime_count = 0
for k in range(1, j+1):
if j % k == 0:
prime_count += 1
if prime_count == 2:
if i % j == 0:
... | |
MatrixStudio/Codeforces-Python-Submissions | The prison of your city has *n* prisoners. As the prison can't accommodate all of them, the city mayor has decided to transfer *c* of the prisoners to a prison located in another city.
For this reason, he made the *n* prisoners to stand in a line, with a number written on their chests. The number is the severity of th... | ```python
n, t, c = map(int, input().split())
count = 0
current_count = 0
for i in range(n):
x = int(input())
if x <= t:
current_count += 1
else:
if current_count >= c:
count += current_count - (c-1)
current_count = 0
if current_count >= c:
count += current_count - ... | |
MatrixStudio/Codeforces-Python-Submissions | Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.
As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tourname... | ```python
n,m = [int(i) for i in input().split(' ')]
result = [0]*n
for _ in range(m):
l,r,x = [int(i) for i in input().split(' ')]
participantes = list(range(l-1,r))
participantes.remove(x-1)
for i in participantes:
if result[i] == 0:
result[i] = x
print(" ".joi... | |
MatrixStudio/Codeforces-Python-Submissions | Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given *n* numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given *n* numbers finds one that i... | ```python
n=int(input())
a=list(map(int,input().split()))
e=o=0
for i in range(n):
if a[i]%2==0:
e+=1
res1=i+1
else:
o+=1
res2=i+1
if e>o:
print(res2)
else:
print(res1)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Vova, the Ultimate Thule new shaman, wants to build a pipeline. As there are exactly *n* houses in Ultimate Thule, Vova wants the city to have exactly *n* pipes, each such pipe should be connected to the water supply. A pipe can be connected to the water supply if there's water flowing out of it. Initially Vova has onl... | ```python
n, k = [int(i) for i in input().split(' ')]
if n <= k:
print(1)
exit()
t = 1
s = k
count = 0
while t < n and s >= 2:
#print(t, s)
t = t - 1 + s
s -= 1
if n - t < s:
s = n - t + 1
count += 1
#print(t, s, count)
if t != n:
print(-1)
exit()
print(count)
``` | |
MatrixStudio/Codeforces-Python-Submissions | You are given a string *s* consisting only of characters 0 and 1. A substring [*l*,<=*r*] of *s* is a string *s**l**s**l*<=+<=1*s**l*<=+<=2... *s**r*, and its length equals to *r*<=-<=*l*<=+<=1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring.
You have to deter... | ```python
n = int(input())
s = input()
s = [int(i) if int(i) > 0 else -1 for i in s]
cnt = 0
for length in range(2, n):
for pos in range(0, n-1-length):
if sum(s[pos:pos+length]) == 0 :
cnt = length
else :
continue
print(cnt)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Vasily has a number *a*, which he wants to turn into a number *b*. For this purpose, he can do two types of operations:
- multiply the current number by 2 (that is, replace the number *x* by 2·*x*); - append the digit 1 to the right of current number (that is, replace the number *x* by 10·*x*<=+<=1).
You need to he... | ```python
a,b=map(int,input().split())
l=[b]
while(a<b):
if b%2:
if b%10==1:
b//=10
l.append(b)
else:
break
else:
b//=2
l.append(b)
if a==b:print("YES");print(len(l));print(*l[::-1])
else:print("NO")
``` | |
MatrixStudio/Codeforces-Python-Submissions | Valera has got *n* domino pieces in a row. Each piece consists of two halves — the upper one and the lower one. Each of the halves contains a number from 1 to 6. Valera loves even integers very much, so he wants the sum of the numbers on the upper halves and the sum of the numbers on the lower halves to be even.
To do... | ```python
s1=0
s2=0
o1=0
o2=0
for _ in range (int(input())):
n1,n2=map(int,input().split())
s1+=n1
s2+=n2
if(n1%2!=0 and n2%2==0):
o1+=1
if(n1%2!=0 and n2%2==0):
o2+=1
if(s1%2==0 and s2%2==0):
print(0)
elif(s1%2!=0 and s2%2==0):
print(-1)
elif(s1%2==0 and s2%2... | |
MatrixStudio/Codeforces-Python-Submissions | Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it:
- deletes all the vowels, - inserts a character "." before each consonant, - replaces ... | ```python
a = input()
c = ["a","e","o","y","u","i"]
a = a.lower()
for i in a:
if i in c:
a = a.replace(i,"")
else:
a= a.replace(i,f".{i}")
print(a)
``` | |
MatrixStudio/Codeforces-Python-Submissions | The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc.... | ```python
s=input()
t=input()
s_r=""
for i in s:
s_r=i+s_r
if(s_r==t):
print("YES")
else:
print("NO")
``` | |
MatrixStudio/Codeforces-Python-Submissions | There are *n* boys and *m* girls studying in the class. They should stand in a line so that boys and girls alternated there as much as possible. Let's assume that positions in the line are indexed from left to right by numbers from 1 to *n*<=+<=*m*. Then the number of integers *i* (1<=≤<=*i*<=<<=*n*<=+<=*m*) such th... | ```python
b, g = input().split()
b = int(b)
g = int(g)
result = []
numB = 0
numG = 0
x = 0
if b > g:
while numG < g:
if x % 2 == 0:
result.append("B")
numB += 1
else:
result.append('G')
numG += 1
x += 1
print(numG)
for y in range(b - numB):
result.append('B')
else:
... | |
MatrixStudio/Codeforces-Python-Submissions | Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves... | ```python
# juntar em grupos onde é possível chegar de algum deles
# um grupo são elementos que um pode chegar em outro sem gastar snow drifts extras, ou seja, possui x ou y igual
# o valor final vai ser qtdGrupos - 1
n = int(input())
groups = []
for _ in range(n):
i, j = [int(k) for k in input().split(' ')]
has... | |
MatrixStudio/Codeforces-Python-Submissions | Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw.
The first player wrote number *a*, the second player wrote number *b*. How many w... | ```python
a, b = (int(s) for s in input().split())
if a == b:
print(0, 6, 0)
else:
m = a if a < b else b
n = b if b > a else a
if (m+n) % 2 == 0:
tie = (m + n) // 2
m_win = len(range(1, tie))
n_win = len(range(tie + 1, 7))
n_tie = 1
else:
l_tie = (m + n) // 2
... | |
MatrixStudio/Codeforces-Python-Submissions | Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?
Given a *n*<=×<=*n* checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells... | ```python
n=int(input())
l1=[]
flag=0
for i in range(n):
l2=list(input())
l1.append(l2)
flag=0
for i in range(n):
for j in range(n):
c=0
if (i+1)<n:
if l1[i+1][j]=='o':
c+=1
if (i-1)>-1:
if l1[i-1][j]=='o':
c+=1
... | |
MatrixStudio/Codeforces-Python-Submissions | The king is left alone on the chessboard. In spite of this loneliness, he doesn't lose heart, because he has business of national importance. For example, he has to pay an official visit to square *t*. As the king is not in habit of wasting his time, he wants to get from his current position *s* to square *t* in the le... | ```python
# for _ in range(int(input())):
# n=int(input())
# x,y=map(int,input().split())
# a=list(map(int,input().split()))
s=input()
t=input()
s=[ord(s[0])-96,int(s[1])]
t=[ord(t[0])-96,int(t[1])]
ans=[]
# print(s,t)
if(s[0]==t[0] and s[1]==t[1]):
ans=[]
elif(s[0]==t[0]):
if(s[1]>t[1... | |
MatrixStudio/Codeforces-Python-Submissions | After the fourth season Sherlock and Moriary have realized the whole foolishness of the battle between them and decided to continue their competitions in peaceful game of Credit Cards.
Rules of this game are simple: each player bring his favourite *n*-digit credit card. Then both players name the digits written on the... | ```python
n = int(input())
she = sorted([int(x) for x in list(input())])
mor = sorted([int(x) for x in list(input())])
i = j = 0
ans1 = n
while i < n:
while mor[j] < she[i] and j < n - 1:
j += 1
if mor[j] >= she[i]:
#print(j, i)
ans1 -= 1
if j == n - 1:
break
... | |
MatrixStudio/Codeforces-Python-Submissions | Arkady wants to water his only flower. Unfortunately, he has a very poor watering system that was designed for $n$ flowers and so it looks like a pipe with $n$ holes. Arkady can only use the water that flows from the first hole.
Arkady can block some of the holes, and then pour $A$ liters of water into the pipe. After... | ```python
n, A, B = map(int, input().split())
x, *holes = (map(int, input().split()))
S = x + sum(holes)
holes.sort(reverse=True)
for i in range(n):
if x*A >= B*S:
break
else:
S -= holes[i]
print(i)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Some days ago, I learned the concept of LCM (least common multiple). I've played with it for several times and I want to make a big number with it.
But I also don't want to use many numbers, so I'll choose three positive integers (they don't have to be distinct) which are not greater than *n*. Can you help me to find ... | ```python
from math import *
def lcm(arr,idx):
if idx==len(arr)-1:
return arr[idx]
a=arr[idx]
b=lcm(arr,idx+1)
return ((a*b)//gcd(a,b))
n=int(input())
if n==1:
print(1)
elif n==2:
print(2)
else:
ans=n*(n-1)
for i in range(n-2,0,-1):
curr=lcm([n,n-1,i],0)
... | |
MatrixStudio/Codeforces-Python-Submissions | Little Petya likes to play very much. And most of all he likes to play the following game:
He is given a sequence of *N* integer numbers. At each step it is allowed to increase the value of any number by 1 or to decrease it by 1. The goal of the game is to make the sequence non-decreasing with the smallest number of s... | ```python
# http://codeforces.com/problemset/problem/13/C
def min_steps(arr):
L = len(arr)
sorted_arr = sorted(arr)
dp = [[0] * L for _ in range(L)]
for i in range(L):
for j in range(L):
if i == j == 0:
dp[i][j] = abs(arr[0] - sorted_arr[0])
elif i == 0:
... | |
MatrixStudio/Codeforces-Python-Submissions | George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory.
George and Alex want to live in the same room. The dormitory has *n* rooms in total. At the moment the *i*-th room has *p**i* peopl... | ```python
n = int(input())
c=0
for i in range(n):
p,q=map(int, input().split())
if((q-p)>=2):
c+=1
print(c)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Little girl Susie went shopping with her mom and she wondered how to improve service quality.
There are *n* people in the queue. For each person we know time *t**i* needed to serve him. A person will be disappointed if the time he waits is more than the time needed to serve him. The time a person waits is the total t... | ```python
n=int(input())
queue=list(map(int,input().split()))
queue.sort()
people=2
time=queue[0]+queue[1]
i=2
while i < n-1:
if time<=queue[i]:
people+=1
time+=queue[i]
i+=1
else:
j=i+1
while j<n:
if time<=queue[j]:
people+=1
... | |
MatrixStudio/Codeforces-Python-Submissions | A lot of people in Berland hates rain, but you do not. Rain pacifies, puts your thoughts in order. By these years you have developed a good tradition — when it rains, you go on the street and stay silent for a moment, contemplate all around you, enjoy freshness, think about big deeds you have to do.
Today everything ... | ```python
import math
d, h, v, e = list(map(int, input().split()))
area = math.pi * d * d / 4
net = v / area - e
t = h / net
if t > 0.0001 and t < 10000:
print("YES")
print(t)
else:
print("NO")
``` | |
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
# Read the user name
user_name = input()
# Count the number of distinct characters in the user name
distinct_characters = len(set(user_name))
# Check if the number of distinct characters is even
if distinct_characters % 2 == 0:
print("CHAT WITH HER!")
else:
print("IGNORE HIM!")
``` | |
MatrixStudio/Codeforces-Python-Submissions | Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into three pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece,... | ```python
from collections import defaultdict
n = int(input())
a = list(map(int, input().split()))
sum_a = sum(a)
if sum_a % 3 != 0:
print(0)
exit()
cnt = defaultdict(int)
p = [0] * n
p[0] = a[0]
cnt[p[0]] += 1
for i in range(1, n):
p[i] = p[i - 1] + a[i]
cnt[p[i]] += 1
print(c... | |
MatrixStudio/Codeforces-Python-Submissions | Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find ... | ```python
def is_almost_lucky(n):
if n % 4 == 0 or n % 7 == 0:
return True
for i in range(1, n):
if (n - 4 * i) % 7 == 0:
return True
return False
n = int(input().strip())
if is_almost_lucky(n):
print("YES")
else:
print("NO")
``` | |
MatrixStudio/Codeforces-Python-Submissions | You are given *n* segments on a line. There are no ends of some segments that coincide. For each segment find the number of segments it contains. | ```python
# Problem: D. Nested Segments
# Contest: Codeforces - Educational Codeforces Round 10
# URL: https://codeforces.com/problemset/problem/652/D
# Memory Limit: 256 MB
# Time Limit: 2000 ms
import sys
import bisect
import random
import io, os
from bisect import *
from collections import *
from contex... | |
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
number = input()
T = 0
while len(number) > 1:
number = [int(i) for i in number]
number = str(sum(number))
T+=1
print(T)
``` | |
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
#!/usr/bin/env python
# coding: utf-8
# In[18]:
#1A
numbers = "664"
square = (int(numbers[2]))
first = int(numbers[0])//square + 1
second = int(numbers[1])//square + 1
print(first*second)
``` | |
MatrixStudio/Codeforces-Python-Submissions | There are *n* shovels in Polycarp's shop. The *i*-th shovel costs *i* burles, that is, the first shovel costs 1 burle, the second shovel costs 2 burles, the third shovel costs 3 burles, and so on. Polycarps wants to sell shovels in pairs.
Visitors are more likely to buy a pair of shovels if their total cost ends with ... | ```python
s = input()
n = int(s)
num = '9'*len(s)
num = int(num)
if(2*n < num):
num = num // 10
ret = 0;
for i in range (9):
tmp = str(i) + str(num)
tmp = int(tmp);
if (2 * n <= tmp):
break;
biggest = min(tmp - 1, n);
smallest = tmp - biggest
ret += (biggest - smallest ... | |
MatrixStudio/Codeforces-Python-Submissions | Door's family is going celebrate Famil Doors's birthday party. They love Famil Door so they are planning to make his birthday cake weird!
The cake is a *n*<=×<=*n* square consisting of equal squares with side length 1. Each square is either empty or consists of a single chocolate. They bought the cake and randomly sta... | ```python
from math import comb
s = 0
a = []
for i in range(int(input())):
st = [c for c in input()]
s += comb(st.count('C'), 2)
a.append(st)
for t in zip(*a):
s += comb(t.count('C'), 2)
print(s)
##########################################
## ##
##... | |
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
from math import *
from collections import *
from bisect import *
import math
def is_prime(n):
for i in range(2,math.ceil(math.sqrt(n))):
if(n%i==0):
return False
return True
def sieve(n):
arr=[True for _ in range(n+1)]
for i in range(2,math.ceil(math.sqr... | |
MatrixStudio/Codeforces-Python-Submissions | Recently, Mike was very busy with studying for exams and contests. Now he is going to chill a bit by doing some sight seeing in the city.
City consists of *n* intersections numbered from 1 to *n*. Mike starts walking from his house located at the intersection number 1 and goes along some sequence of intersections. Wal... | ```python
def bfs(nCruzamentos, cruzamentos, aux, fila):
while len(fila) > 0:
atual = fila.pop(0)
if(atual < nCruzamentos and aux[atual + 1] > aux[atual] + 1):
aux[atual+1]=aux[atual]+1
fila.append(atual + 1)
if(atual > 1 and aux[atual - 1] > aux[atual]+1):
aux[atual - 1] = au... | |
MatrixStudio/Codeforces-Python-Submissions | Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock.
The combination lock is represented by *n* rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has to turn ... | ```python
x=int(input())
y=input()
z=input()
sum=0
for i in range(len(y)):
sum+=min(abs(int(y[i])-int(z[i])),10-abs(int(y[i])-int(z[i])))
print(sum)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Little Vlad is fond of popular computer game Bota-2. Recently, the developers announced the new add-on named Bota-3. Of course, Vlad immediately bought only to find out his computer is too old for the new game and needs to be updated.
There are *n* video cards in the shop, the power of the *i*-th video card is equal t... | ```python
n = int(input())
mas = [int(i) for i in input().split()]
nmax = 200001
p = [0] * (nmax + 1)
for i in range(n):
p[mas[i]] += 1
for i in range(1, nmax):
p[i] += p[i - 1]
ans = 0
for i in range(1, nmax + 1):
ma = 0
if p[i] - p[i - 1] == 0:
continue
for j in range(i, nmax ... | |
MatrixStudio/Codeforces-Python-Submissions | Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not ... | ```python
read=input()
counter=0
maxI=0
#print( read[i],read[i-1],maxI,i)
for i in range(len(read)-1):
if maxI==0:
counter+=1
if maxI==4 or read[i]!=read[i+1]:
maxI=0
else:
maxI+=1
i=len(read)-1
if read[i]!=read[i-1]:
counter+=1
elif maxI==0:
... | |
MatrixStudio/Codeforces-Python-Submissions | It's New Year's Eve soon, so Ivan decided it's high time he started setting the table. Ivan has bought two cakes and cut them into pieces: the first cake has been cut into *a* pieces, and the second one — into *b* pieces.
Ivan knows that there will be *n* people at the celebration (including himself), so Ivan has set ... | ```python
n, a , b = map ( int, input(). split())
for i in range(1, max ( a, b )):
if (a//i+b//i>=n):
continue
else:
break
print(i-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
from math import ceil
lis = ["Sheldon", "Leonard", "Rajesh", "Howard", "Penny"]
nth = int(input())
nbf = nth/5
i = 0
j = 1
n = 0
while n<nbf:
n += j
j *= 2
i += 1
divisor = j/2
x = nth-((n-divisor)*5)
pos = x/divisor
print(lis[ceil(pos)-1])
``` | |
MatrixStudio/Codeforces-Python-Submissions | Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk.
Empirically Polycarp learned that the dog needs at least *k* walks for any two consecutive days in order to feel good. For example, if *k*<==<=5 and yesterday Polycarp went... | ```python
n,k=map(int,input().split())
l1=list(map(int,input().split()))
l2=[]
c=0
if(n%2==0):
i=0
while i<n:
if((l1[i]+l1[i+1])<k):
l2.append(l1[i])
l2.append(abs(l1[i]-k))
c=c+(abs((l1[i]+l1[i+1])-k))
i+=2
else:
l2.append... | |
MatrixStudio/Codeforces-Python-Submissions | Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given *n* numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given *n* numbers finds one that i... | ```python
import itertools as it
n = int(input())
l = [int(x) for x in input().split()]
l = [x for x in zip(l, range(n))]
odd = [x for x in l if x[0] % 2]
even = [x for x in l if x[0] % 2 == 0]
if len(odd) == 1:
print(odd[0][1] + 1)
else:
print(even[0][1] + 1)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Once Bob needed to find the second order statistics of a sequence of integer numbers. Lets choose each number from the sequence exactly once and sort them. The value on the second position is the second order statistics of the given sequence. In other words it is the smallest element strictly greater than the minimum. ... | ```python
#!/usr/bin/python3
n = input()
a = sorted(map(int, input().split()))
for i in range(1, len(a)):
if a[i] != a[i - 1]:
print(a[i])
exit()
print('NO')
``` | |
MatrixStudio/Codeforces-Python-Submissions | Igor found out discounts in a shop and decided to buy *n* items. Discounts at the store will last for a week and Igor knows about each item that its price now is *a**i*, and after a week of discounts its price will be *b**i*.
Not all of sellers are honest, so now some products could be more expensive than after a week... | ```python
n, k = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
wynik = 0
lista = []
for x in range(n):
roznica = a[x] - b[x]
if roznica <= 0:
wynik = wynik + a[x]
k = k - 1
else:
lista.append(roznica)
lista.sort(... | |
MatrixStudio/Codeforces-Python-Submissions | Polycarp studies at the university in the group which consists of *n* students (including himself). All they are registrated in the social net "TheContacnt!".
Not all students are equally sociable. About each student you know the value *a**i* — the maximum number of messages which the *i*-th student is agree to send p... | ```python
n = int(input())
a = [[],[]]
a[0] = input()
a[0] = a[0].split(' ')
a[0] = list(map(int, a[0]))
count = 0
if a[0][0] != 0:
for i in range(len(a[0])):
a[1].append(0)
for i in range(len(a[0])):
user = i
for j in range(a[0][i]):
user+... | |
MatrixStudio/Codeforces-Python-Submissions | Among other things, Bob is keen on photography. Especially he likes to take pictures of sportsmen. That was the reason why he placed himself in position *x*0 of a long straight racetrack and got ready to take pictures. But the problem was that not all the runners passed him. The total amount of sportsmen, training at t... | ```python
# -*- coding: utf-8 -*-
n,x = map(int,input().split())
cont = []
for i in range(n):
a,b = map(int,input().split())
if x < min(a,b): cont.append(min(a,b) - x)
elif x > max(a,b): cont.append(x - max(a,b))
print(max(cont))
``` | |
MatrixStudio/Codeforces-Python-Submissions | One day Vasya the Hipster decided to count how many socks he had. It turned out that he had *a* red socks and *b* blue socks.
According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot.
Every day Vasya puts on new socks in the morning ... | ```python
a, b = map(int, input().split())
max_diff_days = min(a, b)
remaining_socks = max(a, b) - max_diff_days
same_days = remaining_socks // 2
print(max_diff_days, same_days)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Even if the world is full of counterfeits, I still regard it as wonderful.
Pile up herbs and incense, and arise again from the flames and ashes of its predecessor — as is known to many, the phoenix does it like this.
The phoenix has a rather long lifespan, and reincarnates itself once every *a*! years. Here *a*! deno... | ```python
a,b=map(int,input().split())
f=1
r=0
if a==b:
print('1')
for i in range(a+1,b+1):
f*=i
r=f%10
if r==0:
print(0)
break;
if r!=0:
print(r)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Small, but very brave, mouse Brain was not accepted to summer school of young villains. He was upset and decided to postpone his plans of taking over the world, but to become a photographer instead.
As you may know, the coolest photos are on the film (because you can specify the hashtag #film for such).
Brain took a ... | ```python
def check(n, m):
for i in range(n):
a = input()
if a.count('W') + a.count('G') + a.count('B') != m:
return '#Color'
return '#Black&White'
n, m = map(int, input().split())
print(check(n, m))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to th... | ```python
n=input().split(" ")
l=[]
c=0
for i in n:
if (int(i)) in l:
c=c+1
elif int(i) not in l:
l.append(int(i))
print(c)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Little walrus Fangy loves math very much. That's why when he is bored he plays with a number performing some operations.
Fangy takes some positive integer *x* and wants to get a number one from it. While *x* is not equal to 1, Fangy repeats the following action: if *x* is odd, then he adds 1 to it, otherwise he divide... | ```python
import fileinput,sys
binary_int = int(fileinput.input().readline(),2)
num = 0
while binary_int != 1:
if binary_int%2==0:
binary_int = binary_int // 2
else:
binary_int = binary_int + 1
num += 1
print(num)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Kyoya Ootori is selling photobooks of the Ouran High School Host Club. He has 26 photos, labeled "a" to "z", and he has compiled them into a photo booklet with some photos in some order (possibly with some photos being duplicated). A photo booklet can be described as a string of lowercase letters, consisting of the pho... | ```python
x = input()
print(len(x) * 25 + 1)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Since Grisha behaved well last year, at New Year's Eve he was visited by Ded Moroz who brought an enormous bag of gifts with him! The bag contains *n* sweet candies from the good ol' bakery, each labeled from 1 to *n* corresponding to its tastiness. No two candies have the same tastiness.
The choice of candies has a d... | ```python
a,b=map(int,input().split());s=0;from math import*;k=floor(log2(a));print(a if b==1 else (1<<k)-1)
``` | |
MatrixStudio/Codeforces-Python-Submissions | You are given a rectangular board of *M*<=×<=*N* squares. Also you are given an unlimited number of standard domino pieces of 2<=×<=1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers ... | ```python
import math
input = input().split(" ")
print(int(math.floor(int(input[0]) * int(input[1])) / 2))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones.
Once he thought about a string of length *n* consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, an... | ```python
n = int(input())
s = input()
zeros = s.count('0')
ones = s.count('1')
print(abs(zeros - ones))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Mr. Scrooge, a very busy man, decided to count the time he wastes on all sorts of useless stuff to evaluate the lost profit. He has already counted the time he wastes sleeping and eating. And now Mr. Scrooge wants to count the time he has wasted signing papers.
Mr. Scrooge's signature can be represented as a polyline ... | ```python
n, k = map(int, input().split())
s = 0
x0, y0 = map(int, input().split())
for i in range(n - 1):
x, y = map(int, input().split())
s += ((x - x0) ** 2 + (y - y0) ** 2) ** (1 / 2)
x0, y0 = x, y
print(k * s / 50)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Andrew and Jerry are playing a game with Harry as the scorekeeper. The game consists of three rounds. In each round, Andrew and Jerry draw randomly without replacement from a jar containing *n* balls, each labeled with a distinct positive integer. Without looking, they hand their balls to Harry, who awards the point to... | ```python
n = int(input())
a = list(map(int, input().split()))
a.sort()
diff = [0 for i in range(0, 5001)]
dsm = [0 for i in range(0, 10001)]
for i in range(0, n):
for j in range(0, i):
diff[a[i] - a[j]] += 1
for i in range(1, 5001):
for j in range(1, 5001):
dsm[i + j] += diff[... | |
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
def bored(nums: list) -> int:
for i in range(1, len(nums)):
if i != 1:
nums[i] += nums[i-2]
nums[i] = max(nums[i], nums[i-1])
print(nums)
return nums[-1]
input()
print(bored(list(int(i) for i in input().split())))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya calls a mask of a positive integer *n* the number that is obtained after successive writing ... | ```python
a,b=map(str,input().split())
def mask(x):
st=''
for i in str(x):
if i=='7' or i=='4':
st+=i
return(st)
for i in range(int(a)+1,177778):
if mask(i)!=b:
pass
else:
print(i)
quit()
``` | |
MatrixStudio/Codeforces-Python-Submissions | One day Vasya the Hipster decided to count how many socks he had. It turned out that he had *a* red socks and *b* blue socks.
According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot.
Every day Vasya puts on new socks in the morning ... | ```python
ll=(list(map(int,input().split(' '))))
print(min(ll),abs(ll[1]-ll[0])//2)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Appleman and Toastman play a game. Initially Appleman gives one group of *n* numbers to the Toastman, then they start to complete the following tasks:
- Each time Toastman gets a group of numbers, he sums up all the numbers and adds this sum to the score. Then he gives the group to the Appleman. - Each time Appleman... | ```python
import math, os, sys
import string, re
import itertools, functools, operator
from collections import Counter
def inputint():
return int(input())
def inputarray(func=int):
return map(func, input().split())
def ans(A, i, j):
if j - i == 1:
return A[i]
elif j - i == 2... | |
MatrixStudio/Codeforces-Python-Submissions | Innokentiy decides to change the password in the social net "Contact!", but he is too lazy to invent a new password by himself. That is why he needs your help.
Innokentiy decides that new password should satisfy the following conditions:
- the length of the password must be equal to *n*, - the password should cons... | ```python
n, k = map(int, input().split())
abc = "abcdefghijklmnopqrstuvwxyz"
s = abc[:k]
s1 = s
while len(s1) < n:
s1 += s
s1 = s1[:n]
print(s1)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Arpa is taking a geometry exam. Here is the last problem of the exam.
You are given three points *a*,<=*b*,<=*c*.
Find a point and an angle such that if we rotate the page around the point by the angle, the new position of *a* is the same as the old position of *b*, and the new position of *b* is the same as the old ... | ```python
import math
ax, ay, bx, by, cx, cy = map(int, input().split())
area = 0.5*(ax*(by-cy)+bx*(cy-ay)+cx*(ay-by))
if area==0:
print("No")
else:
print("Yes")
``` | |
MatrixStudio/Codeforces-Python-Submissions | Jzzhu is the president of country A. There are *n* cities numbered from 1 to *n* in his country. City 1 is the capital of A. Also there are *m* roads connecting the cities. One can go from city *u**i* to *v**i* (and vise versa) using the *i*-th road, the length of this road is *x**i*. Finally, there are *k* train route... | ```python
import bisect
import collections
import copy
import enum
import functools
import heapq
import itertools
import math
import random
import re
import sys
import time
import string
from typing import List
sys.setrecursionlimit(3001)
input = sys.stdin.readline
n,m,k = map(int,input().split(... | |
MatrixStudio/Codeforces-Python-Submissions | Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them.
Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain nu... | ```python
s = input()
flag = True
i = 0
while(i < len(s)):
if s[i:i+3] == "WUB":
i += 3
if not flag:
print(" ",end='')
else:
flag = False
print(s[i],end='')
i += 1
print()
``` | |
MatrixStudio/Codeforces-Python-Submissions | There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.
You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://<hostnam... | ```python
n=int(input())
d={}
D={}
ans=[]
for i in range(n):
h,*p=(input()[7:]+'/').split('/')
d[h]=d.get(h,set())|{'/'.join(p)}
for x in d:
t=tuple(sorted(d[x]))
D[t]=D.get(t,[])+[x]
for x in D:
if len(D[x])>1:
ans+=['http://'+' http://'.join(D[x])]
print(len(ans))
print('\n'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.