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* children in Jzzhu's school. Jzzhu is going to give some candies to them. Let's number all the children from 1 to *n*. The *i*-th child wants to get at least *a**i* candies.
Jzzhu asks children to line up. Initially, the *i*-th child stands at the *i*-th place of the line. Then Jzzhu start distribution of... | ```python
n, m = list(map(int, input().split(" ")))
a = list(map(int, input().split(" ")))
posa = []
for i in range(len(a)):
posa.append(i+1)
while len(a) != 1:
a[0] -= m
if a[0] <= 0:
del(a[0])
del(posa[0])
else:
a.append(a[0])
posa.append(posa[0])
... | |
MatrixStudio/Codeforces-Python-Submissions | Just in case somebody missed it: this winter is totally cold in Nvodsk! It is so cold that one gets funny thoughts. For example, let's say there are strings with the length exactly *n*, based on the alphabet of size *m*. Any its substring with length equal to *k* is a palindrome. How many such strings exist? Your task ... | ```python
class Dsu:
def __init__(self,n):
self.sizes=[1]*(n)
self.parent=[i for i in range(n)]
def findpar(self,node):
if self.parent[node]==node:
return node
self.parent[node]=self.findpar(self.parent[node])
return self.parent[node]
def union(se... | |
MatrixStudio/Codeforces-Python-Submissions | A programming coach has *n* students to teach. We know that *n* is divisible by 3. Let's assume that all students are numbered from 1 to *n*, inclusive.
Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on ... | ```python
import sys
import math
import bisect
from sys import stdin, stdout
from math import gcd, floor, sqrt, log
from collections import defaultdict as dd
from bisect import bisect_left as bl, bisect_right as br
sys.setrecursionlimit(100000000)
int_r = lambda: int(sys.stdin.readline())
str_r = lambda: sys.stdin.re... | |
MatrixStudio/Codeforces-Python-Submissions | A well-known art union called "Kalevich is Alive!" manufactures objects d'art (pictures). The union consists of *n* painters who decided to organize their work as follows.
Each painter uses only the color that was assigned to him. The colors are distinct for all painters. Let's assume that the first painter uses color... | ```python
m,n = map(int,input().strip().split())
final = []
for _ in range(m):
l=list(map(int,input().split()))
final.append(l)
checkstart=0
checkend=0
for i in range(1,m):
final[i][0] += final[i-1][0]
for i in range(1,n):
final[0][i] += final[0][i-1]
for i in range(1,m):
f... | |
MatrixStudio/Codeforces-Python-Submissions | Amr lives in Lala Land. Lala Land is a very beautiful country that is located on a coordinate line. Lala Land is famous with its apple trees growing everywhere.
Lala Land has exactly *n* apple trees. Tree number *i* is located in a position *x**i* and has *a**i* apples growing on it. Amr wants to collect apples from t... | ```python
print("_RANDOM_GUESS_1689445518.1281602")# 1689445518.1281798
``` | |
MatrixStudio/Codeforces-Python-Submissions | Johny likes numbers *n* and *k* very much. Now Johny wants to find the smallest integer *x* greater than *n*, so it is divisible by the number *k*. | ```python
a ,b=map(int,input().split())
if a>b and (b*2)!=a:
print(min(a,b)*2)
elif (b*2) == a:
print(a + b)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Katie, Kuro and Shiro are best friends. They have known each other since kindergarten. That's why they often share everything with each other and work together on some very hard problems.
Today is Shiro's birthday. She really loves pizza so she wants to invite her friends to the pizza restaurant near her house to cele... | ```python
n=int(input())
if (n+1)%2==0:
print((n+1)//2)
elif (n+1)%2==1:
print(n+1)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone.
In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules o... | ```python
a,b,c,d = input().split()
a = int(a)
b = int(b)
c = int(c)
d = int(d)
counter=0
boxes=input()
for i in boxes:
if i == "1":
counter+=a
elif i == "2":
counter+=b
elif i == "3":
counter+=c
elif i == "4":
counter+=d
print (counter)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Misha and Vasya participated in a Codeforces contest. Unfortunately, each of them solved only one problem, though successfully submitted it at the first attempt. Misha solved the problem that costs *a* points and Vasya solved the problem that costs *b* points. Besides, Misha submitted the problem *c* minutes after the ... | ```python
L1= [int(x) for x in input().split(" ")]
mp=L1[0]
vp=L1[1]
mt=L1[2]
vt=L1[3]
Lm=[(3*mp)/10,mp-(mp*mt)/250]
Lv=[(3*vp)/10,vp-(vp*vt)/250]
m=max(Lm)
v=max(Lv)
if m>v:
print("Misha")
elif m==v:
print("Tie")
else:
print("Vasya")
``` | |
MatrixStudio/Codeforces-Python-Submissions | Polycarpus has a ribbon, its length is *n*. He wants to cut the ribbon in a way that fulfils the following two conditions:
- After the cutting each ribbon piece should have length *a*, *b* or *c*. - After the cutting the number of ribbon pieces should be maximum.
Help Polycarpus and find the number of ribbon piece... | ```python
def ans(n,a,b,c):
if l[n]!=-1:
return l[n]
if n==0:
return 0
elif n<0:
return -10**9
else:
l[n]=max(1+ans(n-a,a,b,c),1+ans(n-b,a,b,c),1+ans(n-c,a,b,c) )
return l[n]
n,a,b,c=list(map(int,input().split()))
l=[-1]* (n+2)
print(ans(n,a,b,c))
... | |
MatrixStudio/Codeforces-Python-Submissions | Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry.
He bought *n* pieces of jewelry. The *i*-th piece has price equal to *i*<=+<=1, that is, the prices of the jewelry are 2,<=3,<=4,<=... *n*<=+<=1.
Watson gave Sherlock a challenge to color these jewelry pie... | ```python
n=int(input())
flag=False;arr=[]
for i in range(2,n+2):
if i%2!=0:arr.append(1)
elif i%3!=0:arr.append(2)
else:arr.append(3)
print(len(set(arr)))
print(*arr)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Vanya and his friends are walking along the fence of height *h* and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed *h*. If the height of some person is greater than *h* he can bend down and then he surely won't be noticed by the guard. The height ... | ```python
n,h=map(int,input().split())
a=list(map(int,input().split()))
count=0
for i in a:
if i>h:
count+=2
else:
count+=1
print(count)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Each year in the castle of Dwarven King there is a competition in growing mushrooms among the dwarves. The competition is one of the most prestigious ones, and the winner gets a wooden salad bowl. This year's event brought together the best mushroom growers from around the world, so we had to slightly change the rules ... | ```python
n, t1, t2, k = map(int, input().split())
table = []
for i in range(1, n+1):
a, b = map(int, input().split())
c1 = a*t1*(1-k/100) + b*t2
c2 = b*t1*(1-k/100) + a*t2
if c1 > c2:
c = c1
else:
c = c2
table.append((i, f"{c:.2f}"))
for e in sorted(table, key=lambda ... | |
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
# Case of the Zeros and Ones
n=int(input())
s=input()
i=0
while (s.__contains__('10') or s.__contains__('01')) and len(s)>1:
if s[i:i+2]=='10' or s[i:i+2]=='01':
s=s[:i]+s[i+2:]
#print(s)
i=i-2
i=i+1
print(len(s))
``` | |
MatrixStudio/Codeforces-Python-Submissions | A new e-mail service "Berlandesk" is going to be opened in Berland in the near future. The site administration wants to launch their project as soon as possible, that's why they ask you to help. You're suggested to implement the prototype of site registration system. The system should work on the following principle.
... | ```python
q={}
for _ in range(int(input())):t=input();print(t+str(q[t])if q.setdefault(t,0)else 'OK');q[t]+=1
``` | |
MatrixStudio/Codeforces-Python-Submissions | A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.
One day Johnny got bracket sequence. He decided to remove some... | ```python
import sys
input = sys.stdin.readline
print = sys.stdout.write
s = input().strip()
stack = []
ans = 0
for c in s:
if c == '(':
stack.append(c)
else: # c == ')'
if not stack:
continue
stack.pop()
ans += 2
print(ans)
``` | |
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
from functools import cache
import sys
from typing import Counter
input = lambda:sys.stdin.readline().rstrip("\r\n")
def I(): return input()
def II(): return int(input())
def MII(): return map(int, input().split())
def LI(): return list(input().split())
def LII(): return list(map(int, input().spli... | |
MatrixStudio/Codeforces-Python-Submissions | Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are *n* members, numbered 1 through *n*. *m* pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that... | ```python
def addEdge(adj, a, b):
adj[a].append(b)
adj[b].append(a)
def dfs(x):
visited[x] = True
for child in adj[x]:
if not visited[child]:
dfs(child)
if __name__ == '__main__':
n, e = map(int, input().split())
adj = [ [] for i in range(n)]
visi... | |
MatrixStudio/Codeforces-Python-Submissions | There are *n* children in Jzzhu's school. Jzzhu is going to give some candies to them. Let's number all the children from 1 to *n*. The *i*-th child wants to get at least *a**i* candies.
Jzzhu asks children to line up. Initially, the *i*-th child stands at the *i*-th place of the line. Then Jzzhu start distribution of... | ```python
a,b=map(int,input().split())
x=[int(i)for i in input().split()]
for i in range(a-1,-1,-1):
if x[i]>b:
print(i+1)
break
else: print(a)
``` | |
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
x,y = map(int,input().split())
if (x*y) %2 ==0:
print((x*y)//2)
else:
print((x*y) //2)
``` | |
MatrixStudio/Codeforces-Python-Submissions | "Contestant who earns a score equal to or greater than the *k*-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." — an excerpt from contest rules.
A total of *n* participants took part in the contest (*n*<=≥<=*k*), and you already know their scores. Calculate... | ```python
'''
158A - Next Round
By: Ayushi Rawat
'''
keys = input().split()
#print(keys)
scores = []
for i in range(8):
scores.append(int(input()))
# print(scores)
n, k = 8, 5
score = [10, 9, 8, 7, 7, 7, 5, 5]
count = 0
k = keys[1]
for i in range(keys[0]):
if score[i] > 0 and score[i] >= ... | |
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
x = [int(a) for a in input().split()]
if(1 <= x[0] <= x[1] <= 16):
a = x[0]/2 * x[1]
if(a == int(a)):
print(int(a))
else:
print(int(a - 0.5))
``` | |
MatrixStudio/Codeforces-Python-Submissions | "QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth.
Now Diamond has given Bort a string consisting of only uppercase English letters of length *n*. There is a great number of "QAQ" in the string (Diamond is so cute!).
Bort wants to know how many subsequences "QAQ" are... | ```python
a = [i for i in input() if i == 'Q' or i == 'A']
t = 0
for i in range(len(a)):
for j in range(i, len(a)):
for k in range(j, len(a)):
if a[i] == 'Q' and a[j] == 'A' and a[k] == 'Q':
t += 1
print(t)
``` | |
MatrixStudio/Codeforces-Python-Submissions | One day Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won.
Alex has grown up since then, so he easily wins the most difficu... | ```python
# Getting Minesweeper dimensions and field from Codeforces.
dimensions,field = tuple(map(int,input().split(' '))),[]
for i in range(dimensions[0]):
field.append(list(input()))
# Declaring List Storing Relative Coords of a Cell' Neighbours.
relCoords = [(0,-1),(1,-1),(1,0),(1,1),(0,1),(-1,1),(-1,0),... | |
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=list(map(int,input().split()))
l=list(map(int,input().split()))
s=sum(l)
cnt=0
#l.sort()
for each in range(len(l)):
temp=(l[each]*A)/s
#print(temp)
if temp<B:
cnt+=1
else:
break
s-=l[each]
print(cnt)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Permutation *p* is an ordered set of integers *p*1,<=<=<=*p*2,<=<=<=...,<=<=<=*p**n*, consisting of *n* distinct positive integers not larger than *n*. We'll denote as *n* the length of permutation *p*1,<=<=<=*p*2,<=<=<=...,<=<=<=*p**n*.
Your task is to find such permutation *p* of length *n*, that the group of number... | ```python
def permutation(n, k):
lista = []
for i in range(1,n+1): lista.append(i)
#print(lista)
permutation = []
i = 0
while i < k-1:
permutation.append(lista[i])
permutation.append(lista[n-1-i])
k = k - 1
i = i + 1
resto = lista[i:n-i]
for... | |
MatrixStudio/Codeforces-Python-Submissions | There will be a launch of a new, powerful and unusual collider very soon, which located along a straight line. *n* particles will be launched inside it. All of them are located in a straight line and there can not be two or more particles located in the same point. The coordinates of the particles coincide with the dis... | ```python
n=int(input())
s=input()
m=-1
l=list(map(int,input().split()))
for i in range(n-1):
if s[i]!=s[i+1]:
if s[i+1]!='R':
m=max(m,(l[i+1]-l[i])//2)
print(m)
``` | |
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
def main():
txt = input()
txt_len = int(len(txt))
for pat_len in range(1, int(len(txt)/2) + 1):
pattern = txt[:pat_len]
suffix = txt[len(txt) - pat_len:]
if pattern != suffix:
continue
middle = txt[pat_len:len(txt) - pat_len]
i = middle.find(pattern)
if i == -1:
print('Just a legend')... | |
MatrixStudio/Codeforces-Python-Submissions | *n* children are standing in a circle and playing a game. Children's numbers in clockwise order form a permutation *a*1,<=*a*2,<=...,<=*a**n* of length *n*. It is an integer sequence such that each integer from 1 to *n* appears exactly once in it.
The game consists of *m* steps. On each step the current leader with in... | ```python
import sys
#sys.stdin=open("data.txt")
input=sys.stdin.readline
n,m=map(int,input().split())
l=list(map(int,input().split()))
for i in range(len(l)):
l[i]-=1
use=[0]*n
a=[0]*n
bad=0
for i in range(len(l)-1):
# transfer l[i] to l[i+1]
if a[l[i]] and a[l[i]]%n!=(l[i+1]-l[i])%n:... | |
MatrixStudio/Codeforces-Python-Submissions | Sonya decided that having her own hotel business is the best way of earning money because she can profit and rest wherever she wants.
The country where Sonya lives is an endless line. There is a city in each integer coordinate on this line. She has $n$ hotels, where the $i$-th hotel is located in the city with coordin... | ```python
n,d = map(int,input().split())
A = list(map(int,input().split()))
B = set()
for i in A:
a = i-d;b=i+d
f=0;g=0
for j in range(n):
if(A[j]==i):
continue
if(abs(A[j]-a)<d):
f=-1
if(abs(A[j]-b)<d):
g=-1
if(f==0):
B.a... | |
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
n=int(input())
line=input().split()
data=[int(i) for i in line]
data.sort(reverse=True)
score = 0
if n>=4:
for i in range(2,len(data)-1):
score=score+(int(data[i])*int((n-i+2)))
score=score+int(int(n)*int(data[1]))
score=score+int(int(n)*int(data[0]))
elif n==3:
sc... | |
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
teams = {}
for i in range(int(input())):
t = input()
if t not in teams:
teams[t] = 1
else:
teams[t] += 1
print(max(teams, key=teams.get))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Polycarp urgently needs a shovel! He comes to the shop and chooses an appropriate one. The shovel that Policarp chooses is sold for *k* burles. Assume that there is an unlimited number of such shovels in the shop.
In his pocket Polycarp has an unlimited number of "10-burle coins" and exactly one coin of *r* burles (1<... | ```python
k,r=map(int,input().split())
sum=0
while(r%k !=0):
r=r+10
sum=sum+1
print(r//k)
``` | |
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
#!/usr/bin/env python
# coding: utf-8
# In[2]:
s = input()
a = s[0]
for i in range(1,len(s)):
if s[i] != s[i-1] :
a += s[i]
if "helo" in a.lower() or "hello" in a.lower() :
print("YES")
else :
print("NO")
``` | |
MatrixStudio/Codeforces-Python-Submissions | Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.
You've got string *s*<==<=*s*1*s*2... *s**n* (*n* is the length of the string), consisting only of characters "." and "#" and *m* queries. Each query is described by a pair of integers *l**i*,<... | ```python
from functools import lru_cache
def update(index, delta):
while index < len(tree):
tree[index] += delta
index += index & (-index)
@lru_cache(None)
def query(index):
res = 0
while index > 0:
res += tree[index]
index -= index & (-index)
return res
... | |
MatrixStudio/Codeforces-Python-Submissions | Inna likes sweets and a game called the "Candy Matrix". Today, she came up with the new game "Candy Matrix 2: Reload".
The field for the new game is a rectangle table of size *n*<=×<=*m*. Each line of the table contains one cell with a dwarf figurine, one cell with a candy, the other cells of the line are empty. The g... | ```python
rows, columns = map(int,input().split())
elems = []
res = 0
distance_from_candy = []
for i in range(rows):
x = input()
elems.append(x)
if (x.index("G") > x.index("S")):
res = -1
if (x.index("G") != x.index("S")):
distance_from_candy.append(x.index("S"... | |
MatrixStudio/Codeforces-Python-Submissions | Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are *n* flights that must depart today, the *i*-th of them is planned to depart at the *i*-th minute of the day.
Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. Thi... | ```python
n, k = map(int, input().split()); Cost = [int(x)for x in input().split()]; O = [[0]for i in range(n)];
Now = [int(x+k+1) for x in range(n)]; Past = [int(x+1)for x in range(n-k)]; o = 0;
for i in range(1, k+1):
O[-i] = n+1-i; Cost[-i] = -1; Now.remove(n+1-i);
while [0] in O:
y = Cost.index(max(Cos... | |
MatrixStudio/Codeforces-Python-Submissions | One day Vasya painted a Cartesian coordinate system on a piece of paper and marked some set of points (*x*1,<=*y*1),<=(*x*2,<=*y*2),<=...,<=(*x**n*,<=*y**n*). Let's define neighbors for some fixed point from the given set (*x*,<=*y*):
- point (*x*',<=*y*') is (*x*,<=*y*)'s right neighbor, if *x*'<=><=*x* and *y*'... | ```python
ss = 0
n = int(input())
xes = []
yes = []
for i in range(n):
x,y = (int(x) for x in input().split())
xes.append(x)
yes.append(y)
for i in range(n):
a,b,c,d = [0]*4
for j in range(0,n):
if xes[j] == xes[i] and yes[j] > yes[i]: a+=1
if xes[j] == xes[i] and yes[j] ... | |
MatrixStudio/Codeforces-Python-Submissions | Iahub isn't well prepared on geometry problems, but he heard that this year there will be a lot of geometry problems on the IOI selection camp. Scared, Iahub locked himself in the basement and started thinking of new problems of this kind. One of them is the following.
Iahub wants to draw *n* distinct points and *m* s... | ```python
def flip(l,ind,q):
for p in l:
if p[0] > ind:
break
p[1] = 1-p[1]
for p in q:
p[1][0] = 0
p[1][1] = 0
for ll in l:
if p[0][0] <= ll[0] <= p[0][1] and ll[0] <= ind:
p[1][ll[1]] += 1
n,m = [int(i) for i in input().split()]
... | |
MatrixStudio/Codeforces-Python-Submissions | Polycarp has $n$ coins, the value of the $i$-th coin is $a_i$. Polycarp wants to distribute all the coins between his pockets, but he cannot put two coins with the same value into the same pocket.
For example, if Polycarp has got six coins represented as an array $a = [1, 2, 4, 3, 3, 2]$, he can distribute the coins i... | ```python
n=int(input())
l=list(map(int,input().split()))
s=list(set(l))
c=0
for i in range(len(s)):
t=l.count(s[i])
if t>c:
c=t
print(c)
``` | |
MatrixStudio/Codeforces-Python-Submissions | There are $n$ students in a school class, the rating of the $i$-th student on Codehorses is $a_i$. You have to form a team consisting of $k$ students ($1 \le k \le n$) such that the ratings of all team members are distinct.
If it is impossible to form a suitable team, print "NO" (without quotes). Otherwise print "YES"... | ```python
n,p=map(int,input().split())
l=list(map(int,input().split()))
d=[]
k=[]
for i in range(0,n,1):
if l[i] not in d:
d.append(l[i])
k.append(i+1)
if len(d)==p:
print("YES")
print(*k)
else:
print("NO")
``` | |
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,c= map(int,input().split())
aaa=str(a)
aa=len(aaa)
p=True
z=True
for i in range(c):
if z:
a=a*10 + 9
a-=a%b
ba=str(a)
c1=(len(ba)==(i+aa+1))
c2=(ba.startswith(aaa))
if (not c1) or (not c2):
print(-1)
p=False
... | |
MatrixStudio/Codeforces-Python-Submissions | In this problem we consider a special type of an auction, which is called the second-price auction. As in regular auction *n* bidders place a bid which is price a bidder ready to pay. The auction is closed, that is, each bidder secretly informs the organizer of the auction price he is willing to pay. After that, the au... | ```python
n = int(input())
p = list(map(int,input().split()))
ll = p.index(max(p))
p.pop(ll)
print(ll+1,max(p))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first *n*. He writes down the follow... | ```python
n, k = map(int, input().split())
print(([i for i in range(1, n+1, 2)] + [i for i in range(2, n+1, 2)])[k-1])
``` | |
MatrixStudio/Codeforces-Python-Submissions | Ilya is a very clever lion, he lives in an unusual city ZooVille. In this city all the animals have their rights and obligations. Moreover, they even have their own bank accounts. The state of a bank account is an integer. The state of a bank account can be a negative number. This means that the owner of the account ow... | ```python
n=int(input())
if(n>=0):
print(n)
else:
if(n>=-10):
print("0")
else:
a=n//10;
b=((n//100)*10)+(n%10);
if(a>b):
print(a)
else:
print(b)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Further research on zombie thought processes yielded interesting results. As we know from the previous problem, the nervous system of a zombie consists of *n* brains and *m* brain connectors joining some pairs of brains together. It was observed that the intellectual abilities of a zombie depend mainly on the topology ... | ```python
from typing import List
# 좀비의 뇌의 수 n, 뇌를 연결하는 링크의 수 m
# 두 노드 간의 최대 거리를 계산(노드 사이 연결은 트리 형태로 가정)
# 1번 노드로부터의 거리 계산, 1번 노드는 항상 연결되어 있다고 가정
def solution(brain_links: List[List[int]], visited: List[int]) -> int:
def dfs(node: int) -> int:
max_distance = 1
for link in brain_links[node... | |
MatrixStudio/Codeforces-Python-Submissions | Each student eagerly awaits the day he would pass the exams successfully. Thus, Vasya was ready to celebrate, but, alas, he didn't pass it. However, many of Vasya's fellow students from the same group were more successful and celebrated after the exam.
Some of them celebrated in the BugDonalds restaurant, some of them... | ```python
if __name__ == '__main__':
a, b, c, n = map(int, input().split())
passed = True
presult = a+b-c
if (a-c < 0 or b-c < 0):
passed = False
if(passed == False or presult < 1 or presult >= n):
print(-1)
else:
print(n-presult)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Mishka is decorating the Christmas tree. He has got three garlands, and all of them will be put on the tree. After that Mishka will switch these garlands on.
When a garland is switched on, it periodically changes its state — sometimes it is lit, sometimes not. Formally, if *i*-th garland is switched on during *x*-th s... | ```python
a = sorted(list(map(int, input().split())))
if a[:1] == [1] or a[:2] == [2,2] or a[:3] == [3,3,3] or a[:3] == [2,4,4]:
print ("YES")
else:
print ("NO")
``` | |
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
n = int(input())
min = input().split()
bl = True
if int(min[0]) > 15:
bl = False
print(15)
else:
for i in range(n-1):
if(int(min[i+1])-int(min[i])>15) and bl == True:
bl = False
print(int(min[i])+15)
if bl == True:
if int(min[n])<85:
print(i... | |
MatrixStudio/Codeforces-Python-Submissions | In the city of Ultima Thule job applicants are often offered an IQ test.
The test is as follows: the person gets a piece of squared paper with a 4<=×<=4 square painted on it. Some of the square's cells are painted black and others are painted white. Your task is to repaint at most one cell the other color so that the... | ```python
matrix=[]
answer="NO"
for i in range (4):
matrix.append(input())
for i in range(3):
for j in range(3):
if ((matrix[i][j])+(matrix[i][j+1])+(matrix[i+1][j])+(matrix[i+1][j+1])).count("#") !=2:
answer="YES"
break
print(answer)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad.
Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element eq... | ```python
def solve(n, k):
middle = n
length = (1 << middle) - 1
while k != (length + 1) // 2:
if k > (length + 1) // 2:
k = length + 1 - k
middle -= 1
length //= 2
return middle
n = int(input())
k = int(input())
print(solve(n, k))
``` | |
MatrixStudio/Codeforces-Python-Submissions | zscoder loves simple strings! A string *t* is called simple if every pair of adjacent characters are distinct. For example ab, aba, zscoder are simple whereas aa, add are not simple.
zscoder is given a string *s*. He wants to change a minimum number of characters so that the string *s* becomes simple. Help him with th... | ```python
s = input()
s += '0'
for i in range(1, len(s)):
if s[i - 1] == s[i]:
if s[i] != 'z' and s[i + 1] != 'z':
s = s[:i] + 'z' + s[i + 1:]
elif s[i] == 'a' or s[i + 1] == 'b':
s = s[:i] + 'b' + s[i + 1:]
else:
s = s[:i] + 'a' + s[i + 1:]
print(s[:len(s) - 1])
``` | |
MatrixStudio/Codeforces-Python-Submissions | Fox Ciel is playing a game with numbers now.
Ciel has *n* positive integers: *x*1, *x*2, ..., *x**n*. She can do the following operation as many times as needed: select two different indexes *i* and *j* such that *x**i* > *x**j* hold, and then apply assignment *x**i* = *x**i* - *x**j*. The goal is to make the sum ... | ```python
# bsdk idhar kya dekhne ko aaya hai, khud kr!!!
# import math
# from itertools import *
# import random
# import calendar
# import datetime
# import webbrowser
n = int(input())
arr = list(map(int, input().split()))
while max(arr) > min(arr):
index = arr.index(max(arr))
arr[index] -= min(a... | |
MatrixStudio/Codeforces-Python-Submissions | Little penguin Polo has an *n*<=×<=*m* matrix, consisting of integers. Let's index the matrix rows from 1 to *n* from top to bottom and let's index the columns from 1 to *m* from left to right. Let's represent the matrix element on the intersection of row *i* and column *j* as *a**ij*.
In one move the penguin can add ... | ```python
n, m, d = map(int, input().split())
l = []
for _ in range(n):
l += list(map(int, input().split()))
l.sort()
mid = (n*m)//2
ans = 0
for i in l:
if abs(i-l[mid]) % d != 0:
print(-1)
break
ans += abs(i - l[mid])
else:
print(ans//d)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be *n* problems, sorted by difficulty, i.e. problem 1 is the easiest and problem *n* is the hardest. Limak knows it will take him 5·*i* minutes to solve th... | ```python
n,k=map(int,input().split())
actual_time=240-k
counter=0
for i in range(1,n):
if 5*i<=actual_time:
counter+=1
print(counter)
``` | |
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
s = input()
uppercase = 0
for c in s:
if c.isupper():
uppercase += 1
if uppercase > int(len(s) / 2):
s = s.upper()
else:
s = s.lower()
print(s)
``` | |
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
l1 = [int(x) for x in input().split()]
examnumber = l1[0]
totalscore = l1[1]
print(max(0,examnumber*3-totalscore))
``` | |
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 = list(map (int , input() . split()))
x = max(n) - min(n)
print( min(n) , x//2 )
``` | |
MatrixStudio/Codeforces-Python-Submissions | Little Vasya went to the supermarket to get some groceries. He walked about the supermarket for a long time and got a basket full of products. Now he needs to choose the cashier to pay for the products.
There are *n* cashiers at the exit from the supermarket. At the moment the queue for the *i*-th cashier already has ... | ```python
n = int(input())
ppl = list(map(int, input().strip().split()))[:n]
time = []
for i in range(0, n):
temp = 15 * ppl[i]
product = list(map(int, input().strip().split()))[:ppl[i]]
for j in range(0, ppl[i]):
temp += product[j]*5
time.append(temp)
time.sort()
print(time[0])
``` | |
MatrixStudio/Codeforces-Python-Submissions | You have a positive integer *m* and a non-negative integer *s*. Your task is to find the smallest and the largest of the numbers that have length *m* and sum of digits *s*. The required numbers should be non-negative integers written in the decimal base without leading zeroes. | ```python
m,s=map(int,input().split())
if m!=1 and s<=1 or m*9<s:
print(-1,-1)
else:
k=9
l=''
for i in range(9):
l+=str(k-i)*(s//(k-i))
s-=(s//(k-i))*(k-i)
if len(l)<m:
p=len(l)
l+='0'*(m-p)
l1=list(l[::-1])
l1[0]='1'
l1[m-p]=str(... | |
MatrixStudio/Codeforces-Python-Submissions | Little Alyona is celebrating Happy Birthday! Her mother has an array of *n* flowers. Each flower has some mood, the mood of *i*-th flower is *a**i*. The mood can be positive, zero or negative.
Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choos... | ```python
n, m = map(int, input().split())
ar = [int(i) for i in input().split()]
leftsum = [0 for _ in range(n)]
leftsum[0] = ar[0]
for i in range(1,n):
leftsum[i] = leftsum[i-1] + ar[i]
queries = []
totals = []
for _ in range(m):
l, r = map(int, input().split())
l-=1
r-=1
queries.append((l,r))
tot = leftsu... | |
MatrixStudio/Codeforces-Python-Submissions | Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second.
One day in 230 AD Shapur was trying to find out if any one can possibly do... | ```python
num=str(int(input()))
num3=str(int(input()))
if len(num)>len(num3):
num3=num3.zfill(len(num))
else:
num=num.zfill(len(num3))
ch=""
for i in range(len(num)):
if num[i]==num3[i]:
ch+="0"
else:
ch+="1"
print(ch)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Luke Skywalker gave Chewbacca an integer number *x*. Chewbacca isn't good at numbers but he loves inverting digits in them. Inverting digit *t* means replacing it with digit 9<=-<=*t*.
Help Chewbacca to transform the initial number *x* to the minimum possible positive number by inverting some (possibly, zero) digits.... | ```python
s = input()
x = ""
for i in s :
if i == '9' : x+=i
else : x+=str(min((9 - int(i)), int(i)))
print(x)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Vasya likes everything infinite. Now he is studying the properties of a sequence *s*, such that its first element is equal to *a* (*s*1<==<=*a*), and the difference between any two neighbouring elements is equal to *c* (*s**i*<=-<=*s**i*<=-<=1<==<=*c*). In particular, Vasya wonders if his favourite integer *b* appears ... | ```python
a,b,c=map(int,input().split())
if(c==0):
if(a==b):
print("YES")
else:
print("NO")
else:
f=(b-a)/c
if(f-int(f)>0 or f<0):
print("NO")
else:
print("YES")
``` | |
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())
a= list(map(int, input().split()))
r= 0
for i in range(1,n):
if a[i-1] + a[i] < k:
r+= k -(a[i-1] +a[i])
a[i] = k -a[i-1]
print(r)
print(*a)
``` | |
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
list_ = ['Sheldon', 'Leonard', 'Penny', 'Rajesh', 'Howard']
quantidades = [0, 5]
target = int(input())
x = 0
while quantidades[-1] < target:
x += 1
quantidades.append(quantidades[-1] + 5 * 2 ** x)
print(list_[(target-1 - quantidades[-2])//2**x])
``` | |
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
n,m=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
flag=0
x=[min(a),min(b)]
for i in range(n):
if a[i] in b:
print(a[i])
flag=1
break
if flag==0:
print(*sorted(x),sep='')
``` | |
MatrixStudio/Codeforces-Python-Submissions | The preferred way to generate user login in Polygon is to concatenate a prefix of the user's first name and a prefix of their last name, in that order. Each prefix must be non-empty, and any of the prefixes can be the full name. Typically there are multiple possible logins for each person.
You are given the first and ... | ```python
f,l = input().split()
ans = ''
if len(f) > 3
ans = f[:3] + l[0]
else:
ans = f[:2] + l[0]
print(ans)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Your friend has recently learned about coprime numbers. A pair of numbers {*a*,<=*b*} is called coprime if the maximum number that divides both *a* and *b* is equal to one.
Your friend often comes up with different statements. He has recently supposed that if the pair (*a*,<=*b*) is coprime and the pair (*b*,<=*c*) i... | ```python
def hypothesis(l, r):
if l % 2 != 0:
l += 1
elif l + 2 > r:
return -1
return l, l + 1, l + 2
L, R = [int(i) for i in input().split()]
print(*hypothesis(L, R))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Devu is a dumb guy, his learning curve is very slow. You are supposed to teach him *n* subjects, the *i**th* subject has *c**i* chapters. When you teach him, you are supposed to teach all the chapters of a subject continuously.
Let us say that his initial per chapter learning power of a subject is *x* hours. In other ... | ```python
n, x = map(int, input().split())
c = sorted(map(int, input().split()))
ans = 0
for i in range(n):
if x == 0:
x += 1
ans += c[i] * x
x -= 1
print(ans)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Pasha loves his phone and also putting his hair up... But the hair is now irrelevant.
Pasha has installed a new game to his phone. The goal of the game is following. There is a rectangular field consisting of *n* row with *m* pixels in each row. Initially, all the pixels are colored white. In one move, Pasha can choos... | ```python
n,m,k=map(int,input().split())
a=[]
for i in range(k):
b=list(map(int,input().split()))
a.append(b)
x=max(n,m)
for i in range(x):
for j in range(x):
if [i,j] in a and [i+1,j] in a and [i+1,j+1] in a and [i,j+1] in a:
d=a.index([i+1,j])
e=a.index([i+1,j+1])... | |
MatrixStudio/Codeforces-Python-Submissions | A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.
You are given string *s* consisting of lowercase Latin letters. At once you can choose any position in ... | ```python
counts = [0]*26
for c in input():
counts[ord(c)-97] += 1
# print(*counts)
ans = ""
i = 26
while i:
i -= 1
if counts[i]&1:
# Find min thing with odd count and increase that
j = 0
while j < 26 and counts[j]&1 < 1:
j += 1
if j < 26 and counts[j]&1:
counts[i] -= 1
counts[j] ... | |
MatrixStudio/Codeforces-Python-Submissions | Scientists say a lot about the problems of global warming and cooling of the Earth. Indeed, such natural phenomena strongly influence all life on our planet.
Our hero Vasya is quite concerned about the problems. He decided to try a little experiment and observe how outside daily temperature changes. He hung out a ther... | ```python
a = open("input.txt", "r")
b = open("output.txt", "w")
c = int(a.readline())
d = list(map(int, a.readline().split()))
ej = 0
for x in d:
if x <= 0:
e += 1
for i in d[:-1]:
e += (i > 0) - (i < 0)
c = min(c, e)
print(c, file = b)
#roomatehelp
... | |
MatrixStudio/Codeforces-Python-Submissions | A necklace can be described as a string of links ('-') and pearls ('o'), with the last link or pearl connected to the first one.
You can remove a link or a pearl and insert it between two other existing links or pearls (or between a link and a pearl) on the necklace. This process can be repeated as many times as you l... | ```python
neckelace = input()
p = neckelace.count("o")
l = neckelace.count("-")
if l%p==0:
print("YES")
else:
print("NO")
``` | |
MatrixStudio/Codeforces-Python-Submissions | Today Patrick waits for a visit from his friend Spongebob. To prepare for the visit, Patrick needs to buy some goodies in two stores located near his house. There is a *d*1 meter long road between his house and the first shop and a *d*2 meter long road between his house and the second shop. Also, there is a road of len... | ```python
a,b,c=map(int,input().split())
print(min(a+a+c+c,b+b+c+c,a+b+c,a+a+b+b))
``` | |
MatrixStudio/Codeforces-Python-Submissions | In a far away kingdom lived the King, the Prince, the Shoemaker, the Dressmaker and many other citizens. They lived happily until great trouble came into the Kingdom. The ACMers settled there.
Most damage those strange creatures inflicted upon the kingdom was that they loved high precision numbers. As a result, the Ki... | ```python
s=input()
a=round(float(s))
a=str(a)
b=a[len(a)-1]
if(s[s.index(".")-1]=="9"):
print("GOTO Vasilisa.")
else:
print(int(a))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Mahmoud has *n* line segments, the *i*-th of them has length *a**i*. Ehab challenged him to use exactly 3 line segments to form a non-degenerate triangle. Mahmoud doesn't accept challenges unless he is sure he can win, so he asked you to tell him if he should accept the challenge. Given the lengths of the line segments... | ```python
def mapear(f, xs):
return list(map(f, xs))
def solve():
n = int(input())
a = mapear(int, input().split(' '))
# Sem perda de generalidade, assumo que i < j < k
# Dessa forma, garante-se que nenhuma permutação se repetirá
for i in range(n):
for j in range(i+1, n):
... | |
MatrixStudio/Codeforces-Python-Submissions | In a small restaurant there are *a* tables for one person and *b* tables for two persons.
It it known that *n* groups of people come today, each consisting of one or two people.
If a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, it is seated at a vacant two-seate... | ```python
#!/usr/bin/env python3
import math
def test_case(casen):
n, a, b = map(int, input().split())
t = list(map(int, input().split()))
ans = 0
twoone = 0
for i in range(n):
if t[i] == 1 and a > 0:
a -= 1
continue
if t[i] == 1 and twoon... | |
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
s1=input()
a=s1.lower()
s2=input()
b=s2.lower()
os1=0
os2=0
if a==b:
print(0)
if a<b:
print('-1')
if a>b:
print(1)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Theatre Square in the capital city of Berland has a rectangular shape with the size *n*<=×<=*m* meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size *a*<=×<=*a*.
What is the least number of flagstones needed to pave the... | ```python
n=int(input())
m=int(input())
a=int(input())
if n%a==0:
b=n/a
else:
b= n//a +1
if m%a==0:
c=m/a
else:
c=m//a+1
print(max(b,c))
``` | |
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
# // #include<stdio.h>
# // int main()
# // {
# // int n,x;
# // scanf("%d %d" , &n , &x);
# // int count = 0;
# // char sign;
# // int d;
# // for(int i = 0 ; i<n ; i++)
# // {
# // scanf("%c %d" , &sign , &d);
# // if(sign == '+') x += d;
# // ... | |
MatrixStudio/Codeforces-Python-Submissions | Kuriyama Mirai has killed many monsters and got many (namely *n*) stones. She numbers the stones from 1 to *n*. The cost of the *i*-th stone is *v**i*. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions:
1. She will tell you two numbers, *l* and *r* (1<=≤<=*l*<=≤<=*r*... | ```python
n = int(input())
a = list(map(int, input().split()))
k = int(input())
b = [0]
sum = 0
for i in range(n):
sum += a[i]
b.append(sum)
a.sort()
c = [0]
for i in range(n):
sum += a[i]
c.append(sum)
for i in range(k):
temp = list(map(int, input().split()))
if temp[0] =... | |
MatrixStudio/Codeforces-Python-Submissions | You are given two set of points. The first set is determined by the equation *A*1*x*<=+<=*B*1*y*<=+<=*C*1<==<=0, and the second one is determined by the equation *A*2*x*<=+<=*B*2*y*<=+<=*C*2<==<=0.
Write the program which finds the number of points in the intersection of two given sets. | ```python
vet1 = input().split()
vet2 = input().split()
a = int(vet1[0])
b = int(vet1[1])
c = int(vet1[2])
p = int(vet2[0])
q = int(vet2[1])
r = int(vet2[2])
detlow = a*q-b*p
det1 = q*c-b*r
det2 = p*c-a*r
if(detlow == 0):
print(0)
elif((a == 0 and b == 0) and (p == 0 and q == 0) and c != r):
print(0)
elif((a ==... | |
MatrixStudio/Codeforces-Python-Submissions | Bran and his older sister Arya are from the same house. Bran like candies so much, so Arya is going to give him some Candies.
At first, Arya and Bran have 0 Candies. There are *n* days, at the *i*-th day, Arya finds *a**i* candies in a box, that is given by the Many-Faced God. Every day she can give Bran at most 8 of ... | ```python
a,b = map(int,input().split())
l = list(map(int,input().split()))
s,x =0,0
for i in l:
x+=1;s+=i
if s<=8:b-=s;s =0
else:b-=8;s-=8
if b<=0:break
if b>0:print(-1)
else:print(x)
``` | |
MatrixStudio/Codeforces-Python-Submissions | You're given a tree with $n$ vertices.
Your task is to determine the maximum possible number of edges that can be removed in such a way that all the remaining connected components will have even size. | ```python
n = int(input())
d = {i: [] for i in range(1, n + 1)}
for i in range(n - 1):
a, b = map(int, input().split())
d[a].append(b)
d[b].append(a)
if n & 1:
print(-1)
else:
val = [1 for i in range(n + 1)]
par = [-1 for i in range(n + 1)]
par[1] = 1
stack = [1]
while... | |
MatrixStudio/Codeforces-Python-Submissions | A permutation is a sequence of integers *p*1,<=*p*2,<=...,<=*p**n*, consisting of *n* distinct positive integers, each of them doesn't exceed *n*. Let's denote the *i*-th element of permutation *p* as *p**i*. We'll call number *n* the size of permutation *p*1,<=*p*2,<=...,<=*p**n*.
Nickolas adores permutations. He lik... | ```python
#[a, b, c, d] = [int(x) for x in input().split()]
c=int(input())
if c%2==0:
for i in range(0,c):
print(c-i," ")
else:
print("-1")
``` | |
MatrixStudio/Codeforces-Python-Submissions | According to rules of the Berland fashion, a jacket should be fastened by all the buttons except only one, but not necessarily it should be the last one. Also if the jacket has only one button, it should be fastened, so the jacket will not swinging open.
You are given a jacket with *n* buttons. Determine if it is fast... | ```python
#Berland and fashion
n = int(input())
lst = list(map(int,input().split()))
count = 0
for item in lst:
if item == 0:
count += 1
if (len(lst) == 1 and lst[0] == 0) or count > 1:
print('NO')
else:
print('YES')
``` | |
MatrixStudio/Codeforces-Python-Submissions | Dreamoon wants to climb up a stair of *n* steps. He can climb 1 or 2 steps at each move. Dreamoon wants the number of moves to be a multiple of an integer *m*.
What is the minimal number of moves making him climb to the top of the stairs that satisfies his condition? | ```python
#https://codeforces.com/problemset/problem/476/A
n,m=map(int,input().split(' '))
ans=-1
s=0
if n%2==0:
s=n/2
else:
s=(n+1)/2
s=int(s)
for i in range(s,n+1):
if i%m==0:
ans=i;
break
print(ans)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Allen is hosting a formal dinner party. $2n$ people come to the event in $n$ pairs (couples). After a night of fun, Allen wants to line everyone up for a final picture. The $2n$ people line up, but Allen doesn't like the ordering. Allen prefers if each pair occupies adjacent positions in the line, as this makes the pic... | ```python
n = int(input())
p = input().split(" ")
p = [int(p[i]) for i in range (2*n)]
c = 0
# slides the value at index ind to i+1, returns number of spots slid
def slide(i, ind):
temp = p[ind]
for j in range (ind-1, i, -1):
p[j+1] = p[j]
print(p)
p[i+1] = temp
return ind-i-1
for i in... | |
MatrixStudio/Codeforces-Python-Submissions | Vadim is really keen on travelling. Recently he heard about kayaking activity near his town and became very excited about it, so he joined a party of kayakers.
Now the party is ready to start its journey, but firstly they have to choose kayaks. There are 2·*n* people in the group (including Vadim), and they have exact... | ```python
n = int(input())
l = list(map(int, input().split()))
nat = False
for i in range(2 * n):
for c in range(i + 1, 2 * n):
ls = l[:]
ls[i] = 0
ls[c] = 0
ls = sorted(ls)
now = 0
for loc in range(1, len(ls), 2):
now += ls[loc] - ls[loc ... | |
MatrixStudio/Codeforces-Python-Submissions | Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first *n*. He writes down the follow... | ```python
n, k = map(int, input().split())
if n == k:
print(k - 1)
else:
result = k if k <= n // 2 else (k - n // 2) * 2
print(result)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Greg is a beginner bodybuilder. Today the gym coach gave him the training plan. All it had was *n* integers *a*1,<=*a*2,<=...,<=*a**n*. These numbers mean that Greg needs to do exactly *n* exercises today. Besides, Greg should repeat the *i*-th in order exercise *a**i* times.
Greg now only does three types of exercise... | ```python
n=int(input())
m=list(map(int,input().split()))
chest=0
biceps=0
back=0
for i in range(n):
if i%3==0:
chest+=m[i]
elif i%3==1:
biceps+=m[i]
else:
back+=m[i]
n=max(back,biceps,chest)
if n==biceps:
print('biceps')
elif n==back:
... | |
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
x1=input()
x2=input()
x=x1+x2
res1 = ''.join(sorted(x))
x3=input()
res3 = ''.join(sorted(x3))
if (res1==res3):
print("YES")
else:
print("NO")
``` | |
MatrixStudio/Codeforces-Python-Submissions | A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.
This new device is equipped with specially designed artificial intelligence (AI). Employees of Pine... | ```python
nameofAI = input()
nameofPhone = input()
print(nameofAI.count(nameofPhone))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Once Bob got to a sale of old TV sets. There were *n* TV sets at that sale. TV set with index *i* costs *a**i* bellars. Some TV sets have a negative price — their owners are ready to pay Bob if he buys their useless apparatus. Bob can «buy» any TV sets he wants. Though he's very strong, Bob can carry at most *m* TV set... | ```python
n, m = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
a = [x for x in a if x <= 0]
a.sort()
print(sum(a[:min(m, len(a))])*-1)
``` | |
MatrixStudio/Codeforces-Python-Submissions | There are *n* Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (*x*,<=*y*) on this plane.
Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (*x*0,<=*y*0). In one shot... | ```python
n, x, y = map(int, input().split())
lines = set()
for _ in range(n):
x1, y1 = map(int, input().split())
if x1 != x:
k = (y1 - y) / (x1-x)
b = y - k * x
else:
k = None
b = x1
lines.add((k, b))
print(len(lines))
``` | |
MatrixStudio/Codeforces-Python-Submissions | In a Berland's zoo there is an enclosure with camels. It is known that camels like to spit. Bob watched these interesting animals for the whole day and registered in his notepad where each animal spitted. Now he wants to know if in the zoo there are two camels, which spitted at each other. Help him to solve this task.
... | ```python
import sys
n=int(input())
a=[0]*n
b=[0]*n
for i in range(n):
a[i],b[i]=map(int,input().split())
b[i]=a[i]+b[i]
for i in range(n):
for j in range(n):
if a[i]==b[j] and b[i]==a[j] and i!=j:
print("YES")
sys.exit()
print("NO")
``` | |
MatrixStudio/Codeforces-Python-Submissions | One day *n* friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other *n*<=-<=1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the *i*-th person wants to play *a**i* rounds. What is the min... | ```python
def check(x):
global a, s, n
if s - x*(n-1) <= 0:
return True
return False
def lbp():
global a, s, n
low = max(a)
high = s
while high - low > 1:
mid = (high + low) // 2
if check(mid):
high = mid
else:
low = m... | |
MatrixStudio/Codeforces-Python-Submissions | Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpr... | ```python
from math import gcd
a, b = map(int, input().split())
a, b = min(a, b), max(a, b)
g = gcd(a, b)
print(f"{a // g}/{b // g}")
``` | |
MatrixStudio/Codeforces-Python-Submissions | You are given an *n*<=×<=*m* rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the table
we obtain the table:
A table is called... | ```python
n, m = map(int, input().split())
t = [input() for i in range(n)]
lt = [False] * (n - 1)
def tc(j):
global lt
lt2 = list(lt)
for i in range(n - 1):
if not lt2[i]:
if t[i][j] < t[i + 1][j]:
lt2[i] = True
elif t[i][j] > t[i + 1][j]:
ret... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.