source stringclasses 3
values | instruction stringlengths 23 3.97k | input stringclasses 1
value | output stringlengths 1 3.75k |
|---|---|---|---|
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
file=open("input.txt",'r');c=open("output.txt",'w')
a,b=map(int,file.readline().split())
c.write(['BG'*b+'B'*(a-b),'GB'*a+'G'*(b-a)][a<b])
#https://codeforces.com/contest/253/status/A, siddartha19 81809690
``` | |
MatrixStudio/Codeforces-Python-Submissions | Our good friend Mole is trying to code a big message. He is typing on an unusual keyboard with characters arranged in following way:
Unfortunately Mole is blind, so sometimes it is problem for him to put his hands accurately. He accidentally moved both his hands with one position to the left or to the right. That mean... | ```python
side = input()
a = "qwertyuiop"
b = "asdfghjkl;"
c = "zxcvbnm,./"
s = input()
nova = ""
for i in s:
if side == "R":
if i in a:
nova += a[a.index(i)-1]
elif i in b:
nova += b[b.index(i)-1]
elif i in c:
nova += c[c.index(i)-1]
els... | |
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
the_list=input().lstrip('{').rstrip('}').split(',')
for i in the_list :
if i =='':
the_list.remove('')
print(len(set(the_list)))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Phone number in Berland is a sequence of *n* digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three... | ```python
n=int(input())
st=input()
new_st=''
co=0
if n%2==0:
for i in range(0,n,2):
new_st+=st[i:i+2]+'-'
else:
for j in range(0,n,2):
if j==2:
new_st+=st[j:j+3]+'-'
else:
new_st+=st[j+1:j+3]+'-'
if n%2==0:
print(new_st[:len(new_... | |
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
list = [int(x) for x in input().split()]
list.sort()
if list[0] + list[1] > list[2] or list[1] + list[2] > list[3]:
print("TRIANGLE")
elif list[0] + list[1] == list[2] or list[1] + list[2] == list[3]:
print("SEGMENT")
else:
print("IMPOSSIBLE")
``` | |
MatrixStudio/Codeforces-Python-Submissions | The year of 2012 is coming...
According to an ancient choradrican legend in this very year, in 2012, Diablo and his brothers Mephisto and Baal will escape from hell, and innumerable hordes of demons will enslave the human world. But seven brave heroes have already gathered on the top of a mountain Arreat to protect us... | ```python
import math
import itertools
if __name__ == '__main__':
N = int(input())
likes = [input() for i in range(N)]
likes = [line.split() for line in likes]
likes = [(words[0], words[2]) for words in likes]
a, b, c = (float(val) for val in input().split())
min_diff = max(a, b, c)
possib... | |
MatrixStudio/Codeforces-Python-Submissions | You are given a rectangular cake, represented as an *r*<=×<=*c* grid. Each cell either has an evil strawberry, or is empty. For example, a 3<=×<=4 cake may look as follows:
The cakeminator is going to eat the cake! Each time he eats, he chooses a row or a column that does not contain any evil strawberries and contains... | ```python
a,b=list(map(int,input().split()))
r=0
g=0
h=0
l=[]
for i in range(a):
s=input()
if "S" in s:
r+=s.count("S")
l.append(list(s))
h+=1
else:
l.append(list(s))
g+=1
if h!=0 and g!=0:
print(b*r)
elif r==(a*b) :
print(0)
elif ... | |
MatrixStudio/Codeforces-Python-Submissions | Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. For example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. When a team plays as ... | ```python
hs = []
ass = []
for _ in range(int(input())):
h, a = map(int, input().split())
hs.append(h)
ass.append(a)
count = 0
for c in hs:
for g in ass:
if c== g:
count+=1
else:
pass
print(count)
``` | |
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
# https://codeforces.com/problemset/problem/115/A
import sys
inp = tuple(int(line) for line in sys.stdin)
have_parent, have_child = set(), set()
flag = -1
for i in range(1, len(inp)):
if inp[i] == -1:
continue
else:
have_parent.add(i)
if i in have_child:
... | |
MatrixStudio/Codeforces-Python-Submissions | Phone number in Berland is a sequence of *n* digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three... | ```python
n = int(input())
s = input()
while (len(s) > 4):
print (s[0:2], end='-')
s = s[2:]
if (len(s) <=3):
print (s)
else:
print (s[0:2], s[2:4], sep='-')
``` | |
MatrixStudio/Codeforces-Python-Submissions | Pasha has many hamsters and he makes them work out. Today, *n* hamsters (*n* is even) came to work out. The hamsters lined up and each hamster either sat down or stood up.
For another exercise, Pasha needs exactly hamsters to stand up and the other hamsters to sit down. In one minute, Pasha can make some hamster ethe... | ```python
n = int(input())
a = raw_input().strip()
up = 0
for i in a:
if i == 'X':
up +=1
diff = (n // 2) - up
print(abs(diff))
if diff >= 0:
print(a.replace('x', 'X', diff))
else:
print(a.replace('X', 'x', abs(diff)))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Fox Ciel and her friends are in a dancing room. There are *n* boys and *m* girls here, and they never danced before. There will be some songs, during each song, there must be exactly one boy and one girl are dancing. Besides, there is a special rule:
- either the boy in the dancing pair must dance for the first time ... | ```python
x,y=map(int,input().split())
z,x1,y1=[],[],[]
for i in range(1,x+1):
for j in range(1,y+1):
if (i not in x1) or (j not in y1):
x1.append(i)
y1.append(j)
z.append((i,j))
print(len(z))
for i in z:print(*i)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Let's denote as the number of bits set ('1' bits) in the binary representation of the non-negative integer *x*.
You are given multiple queries consisting of pairs of integers *l* and *r*. For each query, find the *x*, such that *l*<=≤<=*x*<=≤<=*r*, and is maximum possible. If there are multiple such numbers find the... | ```python
import math
n = int(input())
for _ in range(n):
l, r = tuple(map(int, input().split()))
t = int(math.log2(r + 1))
if 2**t - 1 >= l and 2 ** t - 1 <= r:
print(2 ** t - 1)
else:
print(r)
``` | |
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
from bisect import bisect_right
def bad():
print(0)
exit()
n, k, l_ = map(int, input().split())
a = sorted(list(map(int, input().split())))
if n == 1:
print(min(a))
exit()
if a[1] - a[0] > l_:
bad()
b = bisect_right(a, a[0] + l_)
if b < n:
bad()
to_sum =... | |
MatrixStudio/Codeforces-Python-Submissions | An exam for *n* students will take place in a long and narrow room, so the students will sit in a line in some order. The teacher suspects that students with adjacent numbers (*i* and *i*<=+<=1) always studied side by side and became friends and if they take an exam sitting next to each other, they will help each other... | ```python
n = int(input())
l = [i for i in range(1, n+1) if i%2!=0]+[i for i in range(1, n+1) if i%2==0]
for i in range(n):
try:
if l[i]+1 == l[i+1] or l[i]-1 == l[i+1]:
l.remove(l[i+1])
except IndexError:
break
print(len(l))
print(*l)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Stepan has a very big positive integer.
Let's consider all cyclic shifts of Stepan's integer (if we look at his integer like at a string) which are also integers (i.e. they do not have leading zeros). Let's call such shifts as good shifts. For example, for the integer 10203 the good shifts are the integer itself 10203... | ```python
s = input()
m = int(input())
n = len(s)
s = s + s
pot = []
pot.append(1)
for i in range(1, 200000):
pot.append((pot[i - 1] * 10) % m)
cur = 0
mn = 1000000000
for i in range(0, 2 * n - 1):
cur = (cur * 10 + ord(s[i]) - ord('0')) % m
if i >= n:
cur = (cur - (pot[n] * (ord(s[i]) - ord('0'))) % m + m) % m
i... | |
MatrixStudio/Codeforces-Python-Submissions | Hands that shed innocent blood!
There are *n* guilty people in a line, the *i*-th of them holds a claw with length *L**i*. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the *i*-th person kills the *j*-th person if and only if *j*<=<<=*i* and *... | ```python
test = 1
#test = int(input())
for _ in range(test):
n = int(input())
l = list(map(int,input().split()))
x = 1
k = n-1 - l[n-1]
ind = n-2
while ind >= 0:
if k > ind:
x+=1
k = min(k,ind-l[ind])
ind-=1
print(x)
... | |
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
#!/usr/bin/python3.7
import sys
n, k = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
cur = 0
def is_submask(n, mask):
return (n & mask) == mask
def f(mask):
s = [[False for j in range(n)] for i in range(n)]
for l in range(n):
cur = 0
for r in range(l... | |
MatrixStudio/Codeforces-Python-Submissions | In this task you need to process a set of stock exchange orders and use them to create order book.
An order is an instruction of some participant to buy or sell stocks on stock exchange. The order number *i* has price *p**i*, direction *d**i* — buy or sell, and integer *q**i*. This means that the participant is ready ... | ```python
n, s = list(map(int, input().split()))
B = []
S = []
for i in range(n):
st = list(input().split())
st[1], st[2] = int(st[1]), int(st[2])
if st[0] == 'B':
B.append(st)
else:
S.append(st)
B.sort()
S.sort()
i = 0
while i < len(B) - 1:
if B[i][1] == B[i + 1][1]:
... | |
MatrixStudio/Codeforces-Python-Submissions | Iahub and Iahubina went to a date at a luxury restaurant. Everything went fine until paying for the food. Instead of money, the waiter wants Iahub to write a Hungry sequence consisting of *n* integers.
A sequence *a*1, *a*2, ..., *a**n*, consisting of *n* integers, is Hungry if and only if:
- Its elements are in i... | ```python
from queue import PriorityQueue
def isPrime(n):
if(n==1 or n==0):
return False
for i in range(2,int(n**(1/2))+1):
if(n%i==0):
return False
return True
count = int(input())
s = ''
for i in range(1, 100000000):
if count == 0:
break
... | |
MatrixStudio/Codeforces-Python-Submissions | Fox Ciel has *n* boxes in her room. They have the same size and weight, but they might have different strength. The *i*-th box can hold at most *x**i* boxes on its top (we'll call *x**i* the strength of the box).
Since all the boxes have the same size, Ciel cannot put more than one box directly on the top of some box... | ```python
n = int(input())
a = list(map(int,input().split()))
a.sort()
s=[]
for i in range(n):
s.sort(reverse = True)
for j in range(len(s)):
if i >= s[j]:
s[j] += 1
break
else:
s.append(1)
print(len(s))
``` | |
MatrixStudio/Codeforces-Python-Submissions | An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point *x*(*x*<=><=0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make ... | ```python
pos = int(input())
if pos % 5 == 0:
steps = int(pos/5)
print(steps)
else:
min = int(pos/5)
stepss = min+1
print(stepss)
``` | |
MatrixStudio/Codeforces-Python-Submissions | You've got an array *a*, consisting of *n* integers: *a*1,<=*a*2,<=...,<=*a**n*. Your task is to find a minimal by inclusion segment [*l*,<=*r*] (1<=≤<=*l*<=≤<=*r*<=≤<=*n*) such, that among numbers *a**l*,<= *a**l*<=+<=1,<= ...,<= *a**r* there are exactly *k* distinct numbers.
Segment [*l*,<=*r*] (1<=≤<=*l*<=≤<=*r*<=≤... | ```python
n, k = map(int, input().split())
a = [0] + list(map(int, input().split()))
freq = [0] * (100001)
dist = 0
for i in range(1, n+1):
if freq[a[i]] == 0:
dist += 1
freq[a[i]] += 1
l = 1
r = n
if dist < k:
print(-1, -1)
else:
while dist >= k:
freq[a[r]] -= 1
... | |
MatrixStudio/Codeforces-Python-Submissions | A dice is a cube, its faces contain distinct integers from 1 to 6 as black points. The sum of numbers at the opposite dice faces always equals 7. Please note that there are only two dice (these dices are mirror of each other) that satisfy the given constraints (both of them are shown on the picture on the left).
Alice... | ```python
n = int(input())
x = int(input())
faces = []
default = {1,2,3,4,5,6}
for i in range(n):
raw = set(map(int, input().split()))
impr = set()
for v in raw:
impr.add(v)
impr.add(7-v)
if i == 0:
impr.add(x)
faces.append(default - impr)
i = 1
if n == 1:
print("YES")
exit()
faces[1] = face... | |
MatrixStudio/Codeforces-Python-Submissions | Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr... | ```python
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 5 23:07:21 2023
@author: risha
"""
s1=list(input().lower())
s2=list(input().lower())
c=0
for i in range(len(s1)):
if s1[i]==s2[i]:
c=1
else:
if s1[i]<s2[i]:
print("-1")
elif s1[i]>s2[i]:
... | |
MatrixStudio/Codeforces-Python-Submissions | Dr. Evil kidnapped Mahmoud and Ehab in the evil land because of their performance in the Evil Olympiad in Informatics (EOI). He decided to give them some problems to let them go.
Dr. Evil is interested in sets, He has a set of *n* integers. Dr. Evil calls a set of integers evil if the MEX of it is exactly *x*. the MEX... | ```python
n, m = map(int,input().split())
l = list(map(int,input().split()))
c = 0
for i in l :
if i < m :
c = c + 1
if m in l :
print(abs(m - c) + 1 )
else:
print(abs(m - c) )
``` | |
MatrixStudio/Codeforces-Python-Submissions | Mr. Funt now lives in a country with a very specific tax laws. The total income of mr. Funt during this year is equal to *n* (*n*<=≥<=2) burles and the amount of tax he has to pay is calculated as the maximum divisor of *n* (not equal to *n*, of course). For example, if *n*<==<=6 then Funt has to pay 3 burles, while fo... | ```python
from sys import exit
n=int(input())
i=2
while i*i<=n:
if n%i==0:
if n%2==0:
print(2)
else:
print(3)
exit()
i+=1
print(1)
``` | |
MatrixStudio/Codeforces-Python-Submissions | You've got a string *s*<==<=*s*1*s*2... *s*|*s*| of length |*s*|, consisting of lowercase English letters. There also are *q* queries, each query is described by two integers *l**i*,<=*r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=|*s*|). The answer to the query is the number of substrings of string *s*[*l**i*... *r**i*], which a... | ```python
from array import array
from sys import stdin ,stdout ,setrecursionlimit
from threading import stack_size , Thread
setrecursionlimit(2**31-1)
input=stdin.readline
def print(*args, end='\n', sep=' ') -> None:
stdout.write(sep.join(map(str, args)) + end)
def palindrome(lef , righ):
while (l... | |
MatrixStudio/Codeforces-Python-Submissions | Alena has successfully passed the entrance exams to the university and is now looking forward to start studying.
One two-hour lesson at the Russian university is traditionally called a pair, it lasts for two academic hours (an academic hour is equal to 45 minutes).
The University works in such a way that every day it... | ```python
n = int(input(''))
classes = input('').split(' ')
#stay = '1 0 1'
count = 0
for j in range(n-2):
if((classes[j] == '1') and (classes[j+1] == '0') and (classes[j+2] == '1')):
count = count + 1
print (count + classes.count('1'))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Only *T* milliseconds left before the start of well-known online programming contest Codehorses Round 2017.
Polycarp needs to download B++ compiler to take part in the contest. The size of the file is *f* bytes.
Polycarp's internet tariff allows to download data at the rate of one byte per *t*0 milliseconds. This tar... | ```python
f, T, t0 = map(int, input().split())
a1, t1, p1= map(int, input().split())
a2, t2, p2= map(int, input().split())
def check(x, y):
global f,T,t0,a1,t1,p1,a2,t2,p2
z = f - x*a1-y*a2
temp = x*a1*t1 + y*a2*t2 + z*t0
if temp<=T:
return p1*x + p2*y
return 1000000000000000004
k = min(... | |
MatrixStudio/Codeforces-Python-Submissions | Kolya is going to make fresh orange juice. He has *n* oranges of sizes *a*1,<=*a*2,<=...,<=*a**n*. Kolya will put them in the juicer in the fixed order, starting with orange of size *a*1, then orange of size *a*2 and so on. To be put in the juicer the orange must have size not exceeding *b*, so if Kolya sees an orange ... | ```python
n,b,d = map(int,input().split())
s = list(map(int,input().split()))
v = 0
ot = 0
for i in range(n):
if s[i] <= b:
v += s[i]
if v > d:
ot += 1
v = 0
if v > d:
ot += 1
print(ot)
``` | |
MatrixStudio/Codeforces-Python-Submissions | We consider a positive integer perfect, if and only if the sum of its digits is exactly $10$. Given a positive integer $k$, your task is to find the $k$-th smallest perfect positive integer. | ```python
def truee():
l=sum(map(int,str(j)))
if l==10:
return 1
return 0
n=int(input())
j=19
k=1
while k!=n:
j+=9
if truee()==1:
k+=1
print(j)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Mr. Kitayuta has just bought an undirected graph consisting of *n* vertices and *m* edges. The vertices of the graph are numbered from 1 to *n*. Each edge, namely edge *i*, has a color *c**i*, connecting vertex *a**i* and *b**i*.
Mr. Kitayuta wants you to process the following *q* queries.
In the *i*-th query, he giv... | ```python
from collections import defaultdict
def dfs(adjlist, start, visited, color):
if start in visited:
return
for (v,c) in adjlist[start]:
if c == color:
visited.add(start)
visited.add(v)
dfs(adjlist, v, visited, color)
if __name__ ... | |
MatrixStudio/Codeforces-Python-Submissions | Dwarfs have planted a very interesting plant, which is a triangle directed "upwards". This plant has an amusing feature. After one year a triangle plant directed "upwards" divides into four triangle plants: three of them will point "upwards" and one will point "downwards". After another year, each triangle plant divide... | ```python
n = int(input())
mod = 10**9 +7
def power_2_k(k):
if k == 0:
return 1
if k % 2 == 0:
lower = power_2_k(k // 2)
return (lower * lower) % mod
else:
k -= 1
lower = power_2_k(k // 2)
return (((lower * lower) % mod) * 2) % mod
p = power_... | |
MatrixStudio/Codeforces-Python-Submissions | Lolek and Bolek are about to travel abroad by plane. The local airport has a special "Choose Your Plane" offer. The offer's conditions are as follows:
- it is up to a passenger to choose a plane to fly on; - if the chosen plane has *x* (*x*<=><=0) empty seats at the given moment, then the ticket for such a plane ... | ```python
n, m = map(int, input().split())
seats = sorted([int(x) for x in input().split()])
seatsc = [s for s in seats]
if n >= sum(seats):
sm = sum([(x * (x + 1)) // 2 for x in seats])
print(sm, sm)
else:
pc = 0
mncost = 0
mxcost = 0
while pc < n:
ind = seats.index(max(se... | |
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=list(map(int,input().split()))
k=list(map(int,input().split()))
c2=0
way=0
for i in k:
if i<=n[1]:
c2+=1
else:
c2=0
if c2>n[2]:
way+=1
print(way)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Recently, Pari and Arya did some research about NP-Hard problems and they found the minimum vertex cover problem very interesting.
Suppose the graph *G* is given. Subset *A* of its vertices is called a vertex cover of this graph, if for each edge *uv* there is at least one endpoint of it in this set, i.e. or (or bot... | ```python
nVertices, nEdges = map(int, input().split())
g = [[] for _ in range(nVertices)]
edges = []
for _ in range(nEdges):
u, v = map(lambda x: int(x) - 1, input().split())
g[u].append(v)
g[v].append(u)
edges.append((u, v))
def dfs(v, m):
mark[v] = m
for to in g[v]:
if no... | |
MatrixStudio/Codeforces-Python-Submissions | While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.
Given two strings *a* and *b*, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence ... | ```python
a=input()
b=input()
if any(i not in iter(a) for i in b): print(max(len(b),len(a)))
else: print(-1)
``` | |
MatrixStudio/Codeforces-Python-Submissions | A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all *n* squad soldiers to line up on the parade ground.
By the military charter the soldiers should stand in the order of non-increasing of their... | ```python
n = int(input())
heights = list(map(int, input().split()))
position_max = -1
position_min = -1
# Find the positions of maximum and minimum heights
for i in range(n):
if heights[i] == max(heights):
position_max = i
if heights[i] == min(heights):
position_min = i
# Calcul... | |
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
n = int(input())
arr = list(map(int, input().split()))
def rain(arr,n, index):
counter = 1
lindex = index - 1
rindex = index + 1
currentL = arr[index]
currentR = arr[index]
while(lindex >= 0):
if arr[lindex] <= currentL:
counter += 1
... | |
MatrixStudio/Codeforces-Python-Submissions | Levko loves tables that consist of *n* rows and *n* columns very much. He especially loves beautiful tables. A table is beautiful to Levko if the sum of elements in each row and column of the table equals *k*.
Unfortunately, he doesn't know any such table. Your task is to help him to find at least one of them. | ```python
a,b=input().split()
a=int(a)
b=int(b)
l=[]
for i in range(a):
if i!=0:
print(*l)
l=[]
for j in range(a):
if j==0:l.append(b)
else:l.append(0)
print(*l)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Two polar bears Menshykov and Uslada from the St.Petersburg zoo and elephant Horace from the Kiev zoo got six sticks to play with and assess the animals' creativity. Menshykov, Uslada and Horace decided to make either an elephant or a bear from those sticks. They can make an animal from sticks in the following way:
-... | ```python
ssticks = list()
ssticks[:] = map(int,input().split(' '))
ssticks.sort()
ssdict = dict()
for i in ssticks:
ssdict[i] = 0
for i in ssticks:
ssdict[i] += 1
ssticks = []
for k in ssdict:
ssticks.append(ssdict[k])
if ssticks.count(4) > 0:
if ssticks.count(2) > 0:
print('... | |
MatrixStudio/Codeforces-Python-Submissions | Vasya has a sequence of cubes and exactly one integer is written on each cube. Vasya exhibited all his cubes in a row. So the sequence of numbers written on the cubes in the order from the left to the right equals to *a*1,<=*a*2,<=...,<=*a**n*.
While Vasya was walking, his little brother Stepan played with Vasya's cub... | ```python
import sys
n,l,r=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
for il in range(0,l):
for ir in range(r,n):
if a[il]==b[il] and a[ir]==b[ir]:
print('TRUTH')
exit()
else:
print('LIE')
exit... | |
MatrixStudio/Codeforces-Python-Submissions | Pashmak decided to give Parmida a pair of flowers from the garden. There are *n* flowers in the garden and the *i*-th of them has a beauty number *b**i*. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty diff... | ```python
from collections import Counter
n=int(input())
b=list(map(int,input().split()))
cnt=Counter(b)
lst=list(cnt)
l,r=lst[0],lst[-1]
print(cnt[r]-cnt[l],cnt[r]*cnt[l])
``` | |
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(' ')))
for i in range(n):
if a[0]%2!=a[1]%2 and a[0]%2!=a[2]%2:
print('0')
break
if a[i]%2!=a[i+1]%2 and a[i]%2!=a[i-1]%2:
print(i+1)
break
``` | |
MatrixStudio/Codeforces-Python-Submissions | ZS the Coder is coding on a crazy computer. If you don't type in a word for a *c* consecutive seconds, everything you typed disappear!
More formally, if you typed a word at second *a* and then the next word at second *b*, then if *b*<=-<=*a*<=≤<=*c*, just the new word is appended to other words on the screen. If *b*<... | ```python
q=[int(a)for a in input().split()]
w=[int(a)for a in input().split()]
e=1
if q[0]>1:
for r in range(1,len(w)):
if w[r]-w[r-1]>q[1]:
e=1
else:
e+=1
print(e)
else:
print(1)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Kolya has a string *s* of length *n* consisting of lowercase and uppercase Latin letters and digits.
He wants to rearrange the symbols in *s* and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forw... | ```python
mp,a,p={},[],[]
n=int(input())
for i in input():
if i in mp:mp[i]+=1
else:mp[i]=1
odd=0
for i in mp:
if mp[i]&1:
a.append(i)
mp[i]-=1
odd+=1
if mp[i]:
p.append(i)
m=max(1,odd)
for i in range(m,n+1):
if not n%i:
d=n//i
if odd ... | |
MatrixStudio/Codeforces-Python-Submissions | After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer.
At the start of the day they have *x* ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. Each person in the... | ```python
n,x=list(map(int, input().split()))
distress=0
for i in range(n):
query=input().split()
if query[0]=='+':
x+=int(query[1])
else:
if x>=int(query[1]):
x-=int(query[1])
else:
distress+=1
print(x, distress)
``` | |
MatrixStudio/Codeforces-Python-Submissions | A simple recommendation system would recommend a user things liked by a certain number of their friends. In this problem you will implement part of such a system.
You are given user's friends' opinions about a list of items. You are also given a threshold *T* — the minimal number of "likes" necessary for an item to be... | ```python
n, m, t = map(int,raw_input().strip().split())
x = []
for i in xrange(n):
x.append(raw_input().strip())
print sum([sum([x[i][j] == 'Y' for i in xrange(n)]) >= t for j in xrange(m)])
``` | |
MatrixStudio/Codeforces-Python-Submissions | Pig is visiting a friend.
Pig's house is located at point 0, and his friend's house is located at point *m* on an axis.
Pig can use teleports to move along the axis.
To use a teleport, Pig should come to a certain point (where the teleport is located) and choose where to move: for each teleport there is the rightmos... | ```python
n, m = map(int, input().split())
a = []
for i in range(m):
a.append(False)
a[0] = True
for _ in range(n):
x, y = map(int, input().split())
for i in range(x,y):
a[i] = True
if False in a:
print("NO")
else:
print("YES")
``` | |
MatrixStudio/Codeforces-Python-Submissions | Nian is a monster which lives deep in the oceans. Once a year, it shows up on the land, devouring livestock and even people. In order to keep the monster away, people fill their villages with red colour, light, and cracking noise, all of which frighten the monster out of coming.
Little Tommy has *n* lanterns and Big B... | ```python
i,j=map(int,input().split())
li=list(map(int,input().split()))
li.sort()
lj=list(map(int,input().split()))
lj.sort()
print(li[i-2]*lj[j-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
#rOkY
#FuCk
################################## kOpAl #####################################
t=int(input())
l=list(map(int,input().split()))
l.sort()
x=list(dict.fromkeys(l))
if(len(x)>1):
print(x[1])
else:
print('NO')
``` | |
MatrixStudio/Codeforces-Python-Submissions | Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number *a* and Antisimon receives number *b*. They also have a heap of *n* stones. The players take turns to make a move and Simon starts. During a move a player should take... | ```python
a, b, n = map(int, input().split())
a1 = a
b1 = b
n1 = n
count = 0
c = 0
while c != n:
d = n1 - c
while d > 0:
a, d = d, a % d
c += a
a = a1
b = b1
a, b = b, a
count += 1
if count % 2 == 0:
print(1)
else:
print(0)
``` | |
MatrixStudio/Codeforces-Python-Submissions | An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point *x*(*x*<=><=0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make ... | ```python
import sys
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int, sys.stdin.readline().rstrip().split()))
def MI(): return map(int, sys.stdin.readline().rstrip().split())
def SI(): return sys.stdin.readline().rstrip()
def main():
n = I()
count = 0
while n > 0... | |
MatrixStudio/Codeforces-Python-Submissions | Petya has got 2*n* cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2*n*. We'll denote the number that is written on a card with number *i*, as *a**i*. In order to play one entertaining game with his friends, Petya needs to split t... | ```python
import re
import sys
exit=sys.exit
from bisect import bisect_left as bsl,bisect_right as bsr
from collections import Counter,defaultdict as ddict,deque
from functools import lru_cache
cache=lru_cache(None)
from heapq import *
from itertools import *
from math import inf
from pprint import pprint as ... | |
MatrixStudio/Codeforces-Python-Submissions | A median in an array with the length of *n* is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2,<=6,<=1,<=2,<=3) is the number 2, and a median of array (0,<=96,<=17,<=23) — the number 17.
We defi... | ```python
"""
Module which implements the search of the minimum number of elements to be inserted
in order to make the given number the median of this array.
"""
def min_num(positions: list, length: int, count: int):
"""
Return the minimum number of elements.
"""
result = count
if ((length+1) // 2 -... | |
MatrixStudio/Codeforces-Python-Submissions | Kefa decided to make some money doing business on the Internet for exactly *n* days. He knows that on the *i*-th day (1<=≤<=*i*<=≤<=*n*) he makes *a**i* money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence *a**i*. Let us remind you that the subsegment o... | ```python
n=int(input())
sub=[]
seq=list (map (int , input().split()))
s=1
for i in range(1,len(seq)):
if seq[i]>=seq[i-1]:
s=s+1
else:
sub.append(s)
s=1
sub.append(s)
print(max(sub))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Recently Adaltik discovered japanese crosswords. Japanese crossword is a picture, represented as a table sized *a*<=×<=*b* squares, and each square is colored white or black. There are integers to the left of the rows and to the top of the columns, encrypting the corresponding row or column. The number of integers repr... | ```python
input()
x = input().split('W')
y= [len(i) for i in x if len(i)>0]
print(len(y))
print(*y)
``` | |
MatrixStudio/Codeforces-Python-Submissions | You have an array *a* consisting of *n* integers. Each integer from 1 to *n* appears exactly once in this array.
For some indices *i* (1<=≤<=*i*<=≤<=*n*<=-<=1) it is possible to swap *i*-th element with (*i*<=+<=1)-th, for other indices it is not possible. You may perform any number of swapping operations any order. T... | ```python
R = lambda:map(int,input().split())
n = int(input())
C = list(R())
s = input()
tt = 0
for i in range(n - 1):
if C[i] > C[i + 1]:
if s[i] == '0':
print("no")
tt = 1
break
else:
t = i
while t >= 0 and C[t] > C[t + 1] and s[t] == '1':
C[t + 1], C[t] = C[t], C[t + 1]
t ... | |
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
n1=(input("Enter a word : "))
u=0
l=0
for i in n1:
if 65<=ord(i)<=90:
u+=1
else:
l+=1
if u>l:
print(n1.upper())
else:
print(n1.lower())
``` | |
MatrixStudio/Codeforces-Python-Submissions | Recently, Vladimir got bad mark in algebra again. To avoid such unpleasant events in future he decided to train his arithmetic skills. He wrote four integer numbers *a*, *b*, *c*, *d* on the blackboard. During each of the next three minutes he took two numbers from the blackboard (not necessarily adjacent) and replaced... | ```python
import itertools
import math
import time
from builtins import input, range
from math import gcd as gcd
import sys
import queue
import itertools
import collections
from heapq import heappop, heappush
import random
import os
from random import randint
import decimal
# from sys import stdin, stdo... | |
MatrixStudio/Codeforces-Python-Submissions | DZY loves chemistry, and he enjoys mixing chemicals.
DZY has *n* chemicals, and *m* pairs of them will react. He wants to pour these chemicals into a test tube, and he needs to pour them in one by one, in any order.
Let's consider the danger of a test tube. Danger of an empty test tube is 1. And every time when DZY ... | ```python
def get(Array, Item):
if Array[Item] == Item: return Item
Array[Item] = get(Array, Array[Item]);
return Array[Item]
n ,m = map(int , input().split(' '))
chem = [i for i in range(1+n)]
ans = 0
rank = [1]*(n+1)
for _ in range(m):
a, b = map(int , input().split(' '))
chem[get(chem... | |
MatrixStudio/Codeforces-Python-Submissions | Vasya has a beautiful garden where wonderful fruit trees grow and yield fantastic harvest every year. But lately thieves started to sneak into the garden at nights and steal the fruit too often. Vasya can’t spend the nights in the garden and guard the fruit because there’s no house in the garden! Vasya had been saving ... | ```python
def calc_trees(cont: list, start_row: int, start_col: int, area_h, area_w) -> int:
trees = 0
for i in range(start_row, start_row + area_h):
for j in range(start_col, start_col + area_w):
trees += cont[i][j]
n, m = [int(item) for item in input().split(' ')]
cont = []
for ... | |
MatrixStudio/Codeforces-Python-Submissions | A tennis tournament with *n* participants is running. The participants are playing by an olympic system, so the winners move on and the losers drop out.
The tournament takes place in the following way (below, *m* is the number of the participants of the current round):
- let *k* be the maximal power of the number 2 ... | ```python
n,b,p = [int(c) for c in input().split()]
print((n-1)*(2*b+1), n*p)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Hag is a very talented person. He has always had an artist inside him but his father forced him to study mechanical engineering.
Yesterday he spent all of his time cutting a giant piece of wood trying to make it look like a goose. Anyway, his dad found out that he was doing arts rather than studying mechanics and othe... | ```python
#!/usr/bin/env python3
from math import hypot
[n, q] = map(int, input().strip().split())
xys = [tuple(map(int, input().strip().split())) for _ in range(n)]
qis = [tuple(map(int, input().strip().split())) for _ in range(q)]
dxys = [(xys[(i + 1) % n][0] - xys[i][0], xys[(i + 1) % n][1] - xys[i][1]) for i in... | |
MatrixStudio/Codeforces-Python-Submissions | We call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, "aabba" is good, because after the merging step it will become "aba".
Given a string, you have to find two values:
1. the number of good substrings of even length; 1. the number of good sub... | ```python
s=input()
ans_odd=0
ans_even=0
cnt_odd=[0,0]
cnt_even=[0,0]
for i in range(len(s)):
id=ord(s[i])-ord("a")
ans_odd+=1
if i%2==0:
ans_even+=cnt_odd[id]
ans_odd+=cnt_even[id]
cnt_even[id]+=1
else:
ans_odd+=cnt_odd[id]
ans_even+=cnt_even[id]
... | |
MatrixStudio/Codeforces-Python-Submissions | One day the Codeforces round author sat exams. He had *n* exams and he needed to get an integer from 2 to 5 for each exam. He will have to re-sit each failed exam, i.e. the exam that gets mark 2.
The author would need to spend too much time and effort to make the sum of his marks strictly more than *k*. That could ha... | ```python
n, k = map(int, input().split())
result = 51
def dfs(remain_exams: int, slate: list):
global result
if remain_exams == 0:
if sum(slate) == k:
num_2 = len([score for score in slate if score == 2])
if num_2 < result:
result = num_2
else:
for... | |
MatrixStudio/Codeforces-Python-Submissions | Your friend has *n* cards.
You know that each card has a lowercase English letter on one side and a digit on the other.
Currently, your friend has laid out the cards on a table so only one side of each card is visible.
You would like to know if the following statement is true for cards that your friend owns: "If a c... | ```python
needs_flipping = ['a', 'e', 'i', 'o', 'u', '1', '3', '5', '7', '9']
def flip(s):
flip_count = 0
for letter in s:
if letter in needs_flipping:
flip_count += 1
return flip_count
print(flip(input()))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Valera had two bags of potatoes, the first of these bags contains *x* (*x*<=≥<=1) potatoes, and the second — *y* (*y*<=≥<=1) potatoes. Valera — very scattered boy, so the first bag of potatoes (it contains *x* potatoes) Valera lost. Valera remembers that the total amount of potatoes (*x*<=+<=*y*) in the two bags, first... | ```python
def solver(y, k, n):
x = n - y
ans = []
for i in range(0,x):
if (y+i+1) % k == 0:
ans.append(str(i+1))
return '-1' if ans == [] else ' '.join(ans)
if __name__ == "__main__":
y, k, n = map(int, input().split(" "))
print(solver(y, k, n))
`... | |
MatrixStudio/Codeforces-Python-Submissions | Natasha is planning an expedition to Mars for $n$ people. One of the important tasks is to provide food for each participant.
The warehouse has $m$ daily food packages. Each package has some food type $a_i$.
Each participant must eat exactly one food package each day. Due to extreme loads, each participant must eat t... | ```python
def get_longest(left_num, cur_depth, max_depth):
if(cur_depth == max_depth):
if left_num == 0:
return 9999999
else:
return int(food_dict[sorted_food_key[max_depth - 1]] / left_num)
else:
cur_long = 0
for i in range(0, left_num + 1):
... | |
MatrixStudio/Codeforces-Python-Submissions | Our old friend Alexey has finally entered the University of City N — the Berland capital. Alexey expected his father to get him a place to live in but his father said it was high time for Alexey to practice some financial independence. So, Alexey is living in a dorm.
The dorm has exactly one straight dryer — a 100 ce... | ```python
import numpy as np
num_of_student = int(input())
sush = list()
for i in range(0, num_of_student):
inp = input()
inp_spl = inp.split(" ")
sush.append(int(inp_spl[0]))
sush.append(int(inp_spl[1]))
one_range = np.zeros((np.max(sush)+1,))
for i in range(0, num_of_student*2, 2):
one_range[s... | |
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*.
You ... | ```python
t = int(input())
res = 0
s = sorted(list(map(int, input().split())))
for i in range(0, t):
res+=abs(i+1 - s[i])
print(res)
``` | |
MatrixStudio/Codeforces-Python-Submissions | You may have heard of the pie rule before. It states that if two people wish to fairly share a slice of pie, one person should cut the slice in half, and the other person should choose who gets which slice. Alice and Bob have many slices of pie, and rather than cutting the slices in half, each individual slice will be ... | ```python
import sys
cache = {}
def max_possible(pie_slices, current_slice):
if current_slice in cache:
return cache[current_slice]
if len(pie_slices) - 1 == current_slice:
return pie_slices[current_slice]
opp = pie_slices[current_slice]
for cs in range(current_slice + 1, len(pie_... | |
MatrixStudio/Codeforces-Python-Submissions | There is a fence in front of Polycarpus's home. The fence consists of *n* planks of the same width which go one after another from left to right. The height of the *i*-th plank is *h**i* meters, distinct planks can have distinct heights.
Polycarpus has bought a posh piano and is thinking about how to get it into the h... | ```python
n,k=map(int,input().split())
h=list(map(int,input().split()))
j_min=sum(h[0:k])
j=0
for i in range(1,n-k):
p=j_min-h[i-1]+h[i+k]
if p<j_min:
j_min=p
j=i
print(j)
``` | |
MatrixStudio/Codeforces-Python-Submissions | An infinitely long railway has a train consisting of *n* cars, numbered from 1 to *n* (the numbers of all the cars are distinct) and positioned in arbitrary order. David Blaine wants to sort the railway cars in the order of increasing numbers. In one move he can make one of the cars disappear from its place and telepor... | ```python
n=int(input())
arr=list(map(int,input().split()))
dp=[0]*(n+5)
for i in a:
dp[i]=dp[i-1]+1
print(n-max(dp))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Little Petya is learning to play chess. He has already learned how to move a king, a rook and a bishop. Let us remind you the rules of moving chess pieces. A chessboard is 64 square fields organized into an 8<=×<=8 table. A field is represented by a pair of integers (*r*,<=*c*) — the number of the row and the number of... | ```python
def moves(r1, c1, r2, c2):
# if start and end positions are the same
if r1 == r2 and c1 == c2:
return 0, 0, 0
# rook
rook_moves = 1 if r1 == r2 or c1 == c2 else 2
# bishop
if (r1 + c1) % 2 != (r2 + c2) % 2: # different colored squares
bishop_moves = -1 # u... | |
MatrixStudio/Codeforces-Python-Submissions | There is a given string *S* consisting of *N* symbols. Your task is to find the number of ordered pairs of integers *i* and *j* such that
1. 1<=≤<=*i*,<=*j*<=≤<=*N*
2. *S*[*i*]<==<=*S*[*j*], that is the *i*-th symbol of string *S* is equal to the *j*-th. | ```python
n=input()
cnt=0
k=0
while k<len(n):
for i in n:
if i==n[k]:
cnt+=1
k+=1
print(cnt)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks.
Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off.
You know that there will be *n* interesting minutes *t*1,<=*t*2,<=...... | ```python
import sys
n=int(input())
z=list(map(int,input().split()))
now=0
for i in z:
if i-now>15:
print(now+15)
sys.exit(0)
else:
now=i
print(90)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.
A little later they found a string *s*, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the... | ```python
from sys import stdin, stdout
s=stdin.readline()
s=s[:-1]
l=len(s)
ans,p,pp=set(),set(),set()
d=0
for i in range(l-1,0,-1):
if s[:i]==s[-i:]:
ans=s[:i]
x=len(ans)
for j in range(1,l-x):
if s[j:j+x] in ans:
stdout.write(str(s[j:j+x]))
d=1
break
if d:
break
if not d... | |
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
def m(n):
a=[[0]*n]*n
a[0]=[1]*n
for i in range(n):a[i][0]=1
for i in range(1, n):
for u in range(1, n):
a[i][u]=a[i-1][u]+a[i][u-1]
print(a[n-1][n-1])
n=int(input())
if n==1: print(1)
else: m(n)
``` | |
MatrixStudio/Codeforces-Python-Submissions | So, the New Year holidays are over. Santa Claus and his colleagues can take a rest and have guests at last. When two "New Year and Christmas Men" meet, thear assistants cut out of cardboard the letters from the guest's name and the host's name in honor of this event. Then the hung the letters above the main entrance. O... | ```python
word1=input()
word2=input()
total=input()
arr1=[]
arr2=[]
tot=[]
for x,let in enumerate(word1):
arr1.append(let)
for x,let in enumerate(word2):
arr2.append(let)
for x,let in enumerate(total):
tot.append(let)
arr1.extend(arr2)
arr1.sort()
tot.sort()
if arr1 == tot:
prin... | |
MatrixStudio/Codeforces-Python-Submissions | Okabe needs to renovate the Future Gadget Laboratory after he tried doing some crazy experiments! The lab is represented as an *n* by *n* square grid of integers. A good lab is defined as a lab in which every number not equal to 1 can be expressed as the sum of a number in the same row and a number in the same column. ... | ```python
def r():
return list(map(int, input().split()))
n = int(input())
matr = [r() for i in range(n)]
ans = True
columns = list(map(set,zip(*matr)))
for row in matr:
ans &= all(x == 1 or any(x - a in row for a in col) for x, col in zip(row, columns))
print("Yes" if ans else "No")
``` | |
MatrixStudio/Codeforces-Python-Submissions | We know that lucky digits are digits 4 and 7, however Vasya's got another favorite digit 0 and he assumes it also is lucky! Lucky numbers are such non-negative integers whose decimal record only contains lucky digits. For example, numbers 0,<=47,<=7074 are lucky, but 1,<=7377,<=895,<= -7 are not.
Vasya has *t* importa... | ```python
print("_RANDOM_GUESS_1691495004.1477993")# 1691495004.1478186
``` | |
MatrixStudio/Codeforces-Python-Submissions | A *k*-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by *k*. That is, there are no two integers *x* and *y* (*x*<=<<=*y*) from the set, such that *y*<==<=*x*·*k*.
You're given a set of *n* distinct positive integers. Your task is to find th... | ```python
def main():
n, k = map(int, input().split())
l = list(map(int, input().split()))
s = set(l)
for p in l:
s.discard(p * k)
print(len(s))
if __name__ == '__main__':
main()
``` | |
MatrixStudio/Codeforces-Python-Submissions | Lenny is playing a game on a 3<=×<=3 grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be sw... | ```python
inp=[]
out=[[True,True,True],[True,True,True],[True,True,True]]
for i in range(3):
inp.append(list(map(int,input().split())))
for i in range(3):
for j in range(3):
if inp[i][j]%2==0:
inp[i][j]=0
else:
inp[i][j]=1
for i in range(3):
for j i... | |
MatrixStudio/Codeforces-Python-Submissions | Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the oppo... | ```python
groups = 0
last = '00'
for i in range(int(input())):
new = input()
if new != last:
groups +=1
last = new
print(groups)
``` | |
MatrixStudio/Codeforces-Python-Submissions | One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are *n* lines in that description each of which described one goal. E... | ```python
from collections import Counter
n = int(input())
lst=[]
for i in range(n):
lst.append(input())
c = Counter(lst)
winner = c.most_common(1)
print(winner[0][0])
``` | |
MatrixStudio/Codeforces-Python-Submissions | Given an array *a*1,<=*a*2,<=...,<=*a**n* of *n* integers, find the largest number in the array that is not a perfect square.
A number *x* is said to be a perfect square if there exists an integer *y* such that *x*<==<=*y*2. | ```python
import math
n = int(input())
arr = list(map(int,filter(None,input().split(' '))))
arr = sorted(arr,reverse=True)
num = -1
for a in arr:
sq = math.sqrt(a)
if sq-math.floor(sq)==0:
continue
else:
num = a
break
print(num)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Vasily the bear has a favorite rectangle, it has one vertex at point (0,<=0), and the opposite vertex at point (*x*,<=*y*). Of course, the sides of Vasya's favorite rectangle are parallel to the coordinate axes.
Vasya also loves triangles, if the triangles have one vertex at point *B*<==<=(0,<=0). That's why today he... | ```python
def main():
x, y = list(map(int, input().split()))
if x >= 0 and y >= 0:
x1, x2, y1, y2 = 0, x+y, x+y, 0
elif x <= 0 and y >= 0:
x1, x2, y1, y2 = x-y, 0, 0, -(x-y)
elif x <= 0 and y <= 0:
x1, x2, y1, y2 = x+y, 0, 0, x+y
elif x >= 0 and y <= 0:
x1, x... | |
MatrixStudio/Codeforces-Python-Submissions | Another programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place.
You know the rules of comparing the results of two give... | ```python
nk = list(map(int ,input().split()))
n = nk[0]
k = nk[1]
arr = []
solved = []
pts = []
for i in range(n):
x = list(map(int, input().split()))
arr.append(x)
for i in range(len(arr)):
minval = i
for j in range(i+1, len(arr)):
if arr[minval][0] < arr[j][0]:
minval... | |
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())
nums = list(map(int,input().split()))
diff = set(nums)
res1 = max(nums.count(i) for i in diff)
res2 = len(diff)
print(res1,res2)
``` | |
MatrixStudio/Codeforces-Python-Submissions | For some time the program of rounding numbers that had been developed by the Codeforces participants during one of the previous rounds, helped the citizens of Far Far Away to convert numbers into a more easily readable format. However, as time went by, the economy of the Far Far Away developed and the scale of operatio... | ```python
s=input().strip()
a=[]
if s[0]=='-':
p='($'
s=s[1:]
else:
p='$'
j=0
t='.'
n=len(s)
while j<(n):
if s[j]=='.':
t=t+s[j+1]
if j+2<n:
t=t+s[j+2]
else:
t=t+'0'
break
else:
j=j+1
if t=='.':
t='.00'
u=0
... | |
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
def get(f): return f(input().strip())
def gets(f): return [*map(f, input().split())]
a, b = gets(int)
i = a + b >> 1
if a + b & 1:
print(i, 0, 6 - i)
else:
print(i - 1, 1, 6 - i)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word.
Hongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character ... | ```python
s = input().strip()
n = len(s)
# Generate all possible cyclic shifts
shifts = [s[i:] + s[:i] for i in range(n)]
# Add shifts to a set to remove duplicates
distinct_shifts = set(shifts)
# Return the size of the set as the answer
print(len(distinct_shifts))
``` | |
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 = map(int, input().split())
a = list(map(int, input().split()))
count = 0
result = 0
for i in a:
if i == 0:
count += 1
if count == k:
count = 0
result += 1
if count != 0:
result += 1
print(result)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Formula One championship consists of series of races called Grand Prix. After every race drivers receive points according to their final position. Only the top 10 drivers receive points in the following order 25, 18, 15, 12, 10, 8, 6, 4, 2, 1. At the conclusion of the championship the driver with most points is the cha... | ```python
N=int(input())
# S={"name":[0,0,0,......],}
soc=[25,18,15,12,10,8,6,4,2,1]
S={}
for i in range(N):
n=int(input())
for y in range(n):
if y<10:
s=input()
if s in S:
S[s][0]+=soc[y]
S[s][y+1]+=1
else:
S[s]=[soc[y],0,0,0,0,0,0,0,0,0,0]
S[s][y+1]+=1
#print(S)
###A
mas=... | |
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
n,k=map(int,input().split())
print(min(n,k),abs(n-k)//2)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Vasya has got two number: *a* and *b*. However, Vasya finds number *a* too short. So he decided to repeat the operation of lengthening number *a* *n* times.
One operation of lengthening a number means adding exactly one digit to the number (in the decimal notation) to the right provided that the resulting number is di... | ```python
a,b,n=input().split(" ")
no_iterations={
0:[a]
}
digits=[str(x) for x in range(10)]
found=False
for i in range(1,int(n)+1):
new_iterations=[]
for x in no_iterations[i-1]:
for y in digits:
if i==int(n):
if int(x+y)%int(b)==0 and found==False:
... | |
MatrixStudio/Codeforces-Python-Submissions | Little X has *n* distinct integers: *p*1,<=*p*2,<=...,<=*p**n*. He wants to divide all of them into two sets *A* and *B*. The following two conditions must be satisfied:
- If number *x* belongs to set *A*, then number *a*<=-<=*x* must also belong to set *A*. - If number *x* belongs to set *B*, then number *b*<=-<=*x... | ```python
import sys
sys.setrecursionlimit(1000000)
set_a = 0
set_b = 10**9 + 1
def find_set(u):
if u not in parent:
parent[u] = u
parent[u] = u if parent[u] == u else find_set(parent[u])
return parent[u]
def union(u, v):
up = find_set(u)
vp = find_set(v)
parent[up] = vp
"""
4 5 7
2 ... | |
MatrixStudio/Codeforces-Python-Submissions | As the guys fried the radio station facilities, the school principal gave them tasks as a punishment. Dustin's task was to add comments to nginx configuration for school's website. The school has *n* servers. Each server has a name and an ip (names aren't necessarily unique, but ips are). Dustin knows the ip and name o... | ```python
m,n=input().split(' ')
IP={}
for i in range(int(m)):
x,y=input().split(' ')
IP[y]=x
for i in range(int(n)):
s,r=input().split(' ')
f=s+' '+r+' #'+IP[r[:-1]]
print(f)
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.