source
stringclasses
3 values
instruction
stringlengths
23
3.97k
input
stringclasses
1 value
output
stringlengths
1
3.75k
MatrixStudio/Codeforces-Python-Submissions
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition. Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character...
```python def main(): aname = input() anum = [] for char in aname: num = ord(char) - 96 anum.append(num) steps = 0 stnum = 1 for i in range(len(anum)): let1 = stnum let2 = anum[i] a1 = abs(let1 - let2) a2 = 26 - a1 step1 = min(...
MatrixStudio/Codeforces-Python-Submissions
You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes. You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consi...
```python n,m = map(int,input().split()) d = dict(input().split() for _ in range(m)) print(' '.join(min((w,d[w]), key=len) for w in input().split())) ```
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()) nums = list(map(int, input().split())) flag = nums[0] % 2 + nums[1] % 2 + nums[2] % 2 if flag == 3: flag = 0 elif flag == 2: print((nums[0] % 2 == 0) * 1 + (nums[1] % 2 == 0) * 2 + (nums[2] % 2 == 0) * 3) exit(0) elif flag == 1: print((nums[0] % 2 == 1) * 1 + (num...
MatrixStudio/Codeforces-Python-Submissions
You are given an equation: Your task is to find the number of distinct roots of the equation and print all of them in ascending order.
```python from math import * a,b,c= map(int,input().split()) d=b**2-4*a*c if d>=0: x2 = (-b - sqrt(b ** 2 - 4 * a * c)) / (2 * a) x1 = (-b + sqrt(b ** 2 - 4 * a * c)) / (2 * a) if x1==x2: c=1 print(c) print('-1') else: c=2 print(c) print(x2)...
MatrixStudio/Codeforces-Python-Submissions
After waking up at *hh*:*mm*, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is *H* points, moreover each minute without food increases his hunger by *D* points. At any time Andrew can visit the store where tasty buns are...
```python h, m = map(int, input().split()) H, D, C, N = map(int, input().split()) after = C * 0.8 ans = (H + N - 1) // N * C tm = h * 60 + m tm1 = 20 * 60 + 0 tm2 = 23 * 60 + 59 if tm1 < tm < tm2: print('{:.16f}'.format((H + N - 1) // N * after)) else: tm3 = tm1 - tm print('{:.16f}'.format(min(an...
MatrixStudio/Codeforces-Python-Submissions
Galois is one of the strongest chess players of Byteforces. He has even invented a new variant of chess, which he named «PawnChess». This new game is played on a board consisting of 8 rows and 8 columns. At the beginning of every game some black and white pawns are placed on the board. The number of black pawns placed...
```python import sys m = [] for i in range(8): m.append(input()) a = -1 b = -1 for i in range(8): col = m[i].find('W') if col >= 0: a = i for j in range(i): if m[j][col] != '.': a = -1 break if a != -1: break i = 7 while i >...
MatrixStudio/Codeforces-Python-Submissions
Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him? Given a *n*<=×<=*n* checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells...
```python n=int(input()) l=[] for i in range(n): l1=input() l.append(l1) flag=0 for i in range(n): for j in range(n): s=0 if(i!=0): if(l[i-1][j]=='o'): s+=1 if(j!=0): if(l[i][j-1]=='o'): s+=1 if(i!=n-1): ...
MatrixStudio/Codeforces-Python-Submissions
Mancala is a game famous in the Middle East. It is played on a board that consists of 14 holes. Initially, each hole has $a_i$ stones. When a player makes a move, he chooses a hole which contains a positive number of stones. He takes all the stones inside it and then redistributes these stones one by one in the next ...
```python holes = list(map(int, input().split())) mx = -1 for i in range(14): if holes[i]>0: temp2 = holes[i] temp = list(holes) temp[i] = 0 while(temp2>0): if i+1 == 14: i = 0 else: i+=1 temp[i]+=1 ...
MatrixStudio/Codeforces-Python-Submissions
Pikachu had an array with him. He wrote down all the non-empty subsequences of the array on paper. Note that an array of size *n* has 2*n*<=-<=1 non-empty subsequences in it. Pikachu being mischievous as he always is, removed all the subsequences in which Maximum_element_of_the_subsequence <=-<= Minimum_element_of_su...
```python import math x,d=map(int,input().split()) n=math.floor(math.log(x+1,2)) if (n-1>=d and x>10000): print(-1) elif (x<=10000 or n-1>=d): print(x) for i in range(1,x*d+2-d,d): print(i,end=' ') print() else: tb=2**n-1 diff=x-tb g=1 arr=[] c=tb while ...
MatrixStudio/Codeforces-Python-Submissions
Alice and Bob like games. And now they are ready to start a new game. They have placed *n* chocolate bars in a line. Alice starts to eat chocolate bars one by one from left to right, and Bob — from right to left. For each chocololate bar the time, needed for the player to consume it, is known (Alice and Bob eat them wi...
```python n=int(input()) l=list(map(int, input().split())) a,b,i,j=0,0,0,n-1 while i<j: if(sum(l[:i+1])>sum(l[j:])): b+=1 j+=1 elif(sum(l[:i+1])>sum(l[j:])): a+=1 i+=1 else: a+=1 b+=1 i+=1 j+=1 print(a,b) ```
MatrixStudio/Codeforces-Python-Submissions
Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number *n*. How many times can Gerald put a spell on it until the number becomes one-...
```python n = input() c = 0 while len(n) > 1: n = str(sum([int(i) for i in n])) c += 1 print(c) ```
MatrixStudio/Codeforces-Python-Submissions
Top-model Izabella participates in the competition. She wants to impress judges and show her mathematical skills. Her problem is following: for given string, consisting of only 0 and 1, tell if it's possible to remove some digits in such a way, that remaining number is a representation of some positive integer, divisi...
```python a=input() array=list(a) birBulundu=False sifirSayisi=0 for i in array: if(i=='1'): birBulundu=True else: if(birBulundu==True): sifirSayisi=sifirSayisi+1 if (sifirSayisi>5): print("yes") else: print("no") ```
MatrixStudio/Codeforces-Python-Submissions
The recent All-Berland Olympiad in Informatics featured *n* participants with each scoring a certain amount of points. As the head of the programming committee, you are to determine the set of participants to be awarded with diplomas with respect to the following criteria: - At least one participant should get a di...
```python if __name__ == '__main__': input() s = set(input().split()) print(len(s) - ('0' in s)) ```
MatrixStudio/Codeforces-Python-Submissions
Fedya studies in a gymnasium. Fedya's maths hometask is to calculate the following expression: for given value of *n*. Fedya managed to complete the task. Can you? Note that given number *n* can be extremely large (e.g. it can exceed any integer type of your programming language).
```python def dsd(a): sl = list(str(a)) ls = [] for i in range(len(sl)): ls.append(int(sl[i])) return ls for _ in range(int(input())): a, k = map(int,input().split()) ans = a while k > 1 and '0' not in list(str(a)): maxi = max(dsd(ans)) mini = min(dsd(...
MatrixStudio/Codeforces-Python-Submissions
*n* people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins *k* games in a row. This player becomes the winner. For each of t...
```python import bisect import os from collections import Counter import bisect from collections import defaultdict import math import random import heapq as hq from math import sqrt import sys from functools import reduce, cmp_to_key from collections import deque import threading from itertools import com...
MatrixStudio/Codeforces-Python-Submissions
After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her. The three friends are very smart so they passed all the challenges very quickly and finally reached the destination...
```python # Why do we fall ? So we can learn to pick ourselves up. from collections import Counter n = int(input()) ss = [] for _ in range(0,3): ss.append(input()) ans = ["Kuro","Shiro","Katie"] maxi = [0,0,0] for i in range(0,3): c = Counter(ss[i]) mx = max(c.values()) to = min(len(ss[i]...
MatrixStudio/Codeforces-Python-Submissions
Vanya loves playing. He even has a special set of cards to play with. Each card has a single integer. The number on the card can be positive, negative and can even be equal to zero. The only limit is, the number on each card doesn't exceed *x* in the absolute value. Natasha doesn't like when Vanya spends a long time p...
```python n, x = list(map(int, input().split())) a = list(map(int, input().split())) sums = sum(a) # print(sums) div = abs(sums) // x if (abs(sums) % x == 0): print(div) else: print(div + 1) ```
MatrixStudio/Codeforces-Python-Submissions
It's that time of the year when the Russians flood their countryside summer cottages (dachas) and the bus stop has a lot of people. People rarely go to the dacha on their own, it's usually a group, so the people stand in queue by groups. The bus stop queue has *n* groups of people. The *i*-th group from the beginning ...
```python n,m=map(int,input().split()) a=list(map(int,input().split())) l=sum(a) if(l%m==0): print(l//m) else: print(l//m+1) ```
MatrixStudio/Codeforces-Python-Submissions
Over time, Alexey's mail box got littered with too many letters. Some of them are read, while others are unread. Alexey's mail program can either show a list of all letters or show the content of a single letter. As soon as the program shows the content of an unread letter, it becomes read letter (if the program shows...
```python n = int(input()) x = list(map(int,input().split())) otv = 0 for i in range(n): if x[i] == 1: otv += 1 if i < n-1 and x[i+1] != 1: otv += 1 if x[i] != 1: print(max(otv-1,0)) else: print(otv) ```
MatrixStudio/Codeforces-Python-Submissions
Little Tanya decided to present her dad a postcard on his Birthday. She has already created a message — string *s* of length *n*, consisting of uppercase and lowercase English letters. Tanya can't write yet, so she found a newspaper and decided to cut out the letters and glue them into the postcard to achieve string *s...
```python TM = input() NM = input() LTM = list(TM) LNM = list(NM) cnt1 = 0 cnt2 = 0 for i in range(len(LTM)): for j in range(len(LNM)): if LTM[i] == LNM[j]: pass cnt1 += 1 LNM[j] = ' ' break else: if LTM[i] == LNM[j].upper(): cnt2 += 1 LNM[j] = 'A4' break elif(LTM[i]...
MatrixStudio/Codeforces-Python-Submissions
Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands: - Include a person...
```python from sys import stdin inputs = [] inputs = stdin.read().splitlines() s1=set() ans=0 for i in inputs: if i[0]=="+": s1.add(i[1:]) elif i[0]=='-': s1.remove(i[1:]) else: ind=i.index(':') msglen=len(i[ind:])-1 ans+=msglen*len(s1) print(ans) `...
MatrixStudio/Codeforces-Python-Submissions
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed *w* kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem. Pete and ...
```python a=input() a=int(a) if a%2!=0: print("NO") else: if a==2: print("NO") else: print("YES") ```
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()) c = list(map(int, input().split())) s = [] max_elem = 0 max_elem_i = 0 for i in range(n): if c[i] > max_elem: max_elem_i = i max_elem = c[i] for i in range(n): s.append((c[i], i)) s.sort(reverse=True) res = [0] * n p = 0 q = 0 for i, pair...
MatrixStudio/Codeforces-Python-Submissions
You are given three integers $a$, $b$ and $x$. Your task is to construct a binary string $s$ of length $n = a + b$ such that there are exactly $a$ zeroes, exactly $b$ ones and exactly $x$ indices $i$ (where $1 \le i &lt; n$) such that $s_i \ne s_{i + 1}$. It is guaranteed that the answer always exists. For example, fo...
```python from math import* import os a,b,x=map(int,input().split()) c=0 d=0 if x%2==0: var=x//2 for i in range(var): if a>b: print("01",end='') else: print("10",end='') for i in range(min(a,b)-var): print("1" if a>b else 0,end='') for i in range(max(a,b)-var): print("0" if a>b else 1...
MatrixStudio/Codeforces-Python-Submissions
Have you ever tried to explain to the coordinator, why it is eight hours to the contest and not a single problem has been prepared yet? Misha had. And this time he has a really strong excuse: he faced a space-time paradox! Space and time replaced each other. The entire universe turned into an enormous clock face with ...
```python x=list(map(int,input().split())) x[0]=int((x[0]*(60/12))) % 60 m=x[1] s=x[2] x[3]=int((x[3]*(60/12))) % 60 x[4]=int((x[4]*(60/12))) % 60 z=[x[1],x[2],x[0]] z.sort() x1=[] x2=[] for i in range(1,3): if z[i-1]==z[i]: del(z[i]) break if len(z)==3: if x[3]>z[0] and x[3]<z[1]: ...
MatrixStudio/Codeforces-Python-Submissions
Petya and Vasya are brothers. Today is a special day for them as their parents left them home alone and commissioned them to do *n* chores. Each chore is characterized by a single parameter — its complexity. The complexity of the *i*-th chore equals *h**i*. As Petya is older, he wants to take the chores with complexit...
```python chores,petaya,vesaya = map(int,input().split()) order = sorted(map(int,input().split()), reverse = True) print (order[petaya-1] - order[petaya]) ```
MatrixStudio/Codeforces-Python-Submissions
Codeforces user' handle color depends on his rating — it is red if his rating is greater or equal to 2400; it is orange if his rating is less than 2400 but greater or equal to 2200, etc. Each time participant takes part in a rated contest, his rating is changed depending on his performance. Anton wants the color of hi...
```python n=int(input()) for i in range(n): name=str(input()) before=int(input()) after=int(input()) count=0 for i in range (n): if before>=2400 and after >before: count+=1 else : break if count>0: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
You can not just take the file and send it. When Polycarp trying to send a file in the social network "Codehorses", he encountered an unexpected problem. If the name of the file contains three or more "x" (lowercase Latin letters "x") in a row, the system considers that the file content does not correspond to the socia...
```python n=int(input()) s=input() count=0 for i in range(n-2): if s[i]+s[i+1]+s[i+2]=="xxx": count+=1 print(count) ```
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*<=&lt;<=*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 solve(arr, n, k): dp = [1 for i in range(n)] for i in range(1,n): temp = 0 for j in range(i): if arr[i]%arr[j]!=0: temp += 1 dp[i] = temp return max(dp) if __name__=="__main__": n,k = map(int, input().split...
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 n,m = map(int, input().split()) l = list(map(int,input().split())) a = [0 for i in range(n+1)] cur = l[0] for i in range(1,m): nx = l[i%m] if nx > l[i-1]: val = nx - l[i-1] else: val = n - l[i-1] + nx if not a[l[i-1]]: a[l[i-1]] = val elif a[l[i-1]] != val: print("-1") ...
MatrixStudio/Codeforces-Python-Submissions
Each New Year Timofey and his friends cut down a tree of *n* vertices and bring it home. After that they paint all the *n* its vertices, so that the *i*-th vertex gets color *c**i*. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes ...
```python R=lambda:map(int,input().split()) t,=R() for _ in range(t-1): x=list(R()) a=list(R()) s=set(a) c=0 d=0 for i in s: if(a.count(i)>1): c+=1 if(a.count(i)==1): d=i if(c>1): print("NO") else: print("YES") print(d) ```
MatrixStudio/Codeforces-Python-Submissions
Iahub helps his grandfather at the farm. Today he must milk the cows. There are *n* cows sitting in a row, numbered from 1 to *n* from left to right. Each cow is either facing to the left or facing to the right. When Iahub milks a cow, all the cows that see the current cow get scared and lose one unit of the quantity o...
```python from functools import reduce class GukziString: chars = 'abcdefghijklmnopqrstuvwxyz' def __init__(self, string=''): super(GukziString, self).__init__() for ch in GukziString.chars: setattr(self, ch, 0) for ch in string: setattr(self, ch, getattr(self,...
MatrixStudio/Codeforces-Python-Submissions
It is well known that the planet suffers from the energy crisis. Little Petya doesn't like that and wants to save the world. For this purpose he needs every accumulator to contain the same amount of energy. Initially every accumulator has some amount of energy: the *i*-th accumulator has *a**i* units of energy. Energy ...
```python def energy(acc, level, perc_loss): surplus = sum([max(x - level, 0) for x in acc]) en_cost = sum([(abs(min(0, x - level)) * 100) / (100 - perc_loss) for x in acc]) return surplus >= en_cost class CodeforcesTask68BSolution: def __init__(self): self.result = '' self.n_k = [] ...
MatrixStudio/Codeforces-Python-Submissions
Petr stands in line of *n* people, but he doesn't know exactly which position he occupies. He can say that there are no less than *a* people standing in front of him and no more than *b* people standing behind him. Find the number of different positions Petr can occupy.
```python n,a,b = map(int,input().split()) ans = a+1 print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity. There are *n* columns of toy cubes in the box arranged in a line. The *i*-th column contains *a**i* cubes. At first, the gravity in the box is...
```python n = int(input()) x = list(map(int, input().split())) x.sort() for i in range(n): print(x[i], end=' ') ```
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 N = int(input()) M = N*(N - 1) MISS = [] FI = [] C = 0 for i in range(N): T = input().split() MISS.append(T[1]) FI.append(T[0]) for i in range(N): for j in (FI) : if j == MISS[i]: C+=1 print(C) ```
MatrixStudio/Codeforces-Python-Submissions
A and B are preparing themselves for programming contests. To train their logical thinking and solve problems better, A and B decided to play chess. During the game A wondered whose position is now stronger. For each chess piece we know its weight: - the queen's weight is 9, - the rook's weight is 5, - the bisho...
```python w=0 b=0 m=[input() for i in range(8)] for line in m: for p in line: if p=="Q": w+=9 elif p=="R": w+=5 elif p=="B" or p=="N": w+=3 elif p=="P": w+=1 if p=="q": b+=9 ...
MatrixStudio/Codeforces-Python-Submissions
One rainy gloomy evening when all modules hid in the nearby cafes to drink hot energetic cocktails, the Hexadecimal virus decided to fly over the Mainframe to look for a Great Idea. And she has found one! Why not make her own Codeforces, with blackjack and other really cool stuff? Many people will surely be willing to...
```python n = int(input()) if n <= 10 : print(0) else: if n <= 19: print(4) elif n == 20: print(15) elif n == 21: print(4) else: print(0) ```
MatrixStudio/Codeforces-Python-Submissions
Some dwarves that are finishing the StUDY (State University for Dwarven Youngsters) Bachelor courses, have been told "no genome, no degree". That means that all dwarves should write a thesis on genome. Dwarven genome is far from simple. It is represented by a string that consists of lowercase Latin letters. Dwarf Mish...
```python s1=input() s2=input() s1=[s1[k] for k in range(len(s1))] s2=[s2[k] for k in range(len(s2))] x=0 ans="" if len(s1)!=len(s2): print("NO") for i in range(len(s1)): for j in range(i+1,len(s1)): s1[i],s1[j]=s1[j],s1[i] if s1==s2: x+=1 ans="YES"...
MatrixStudio/Codeforces-Python-Submissions
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of *n* distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he r...
```python n,k=map(int,input().split()) if(k<int(n/2) or (n==1 and k>0)): print(-1) else: v=[] v.append(k-int(n/2)+1) v.append(2*(k-int(n/2)+1)) i=1 while(len(v)<n): if(i!=v[0] and i!=v[1]): v.append(i) i=i+1 f=0 for i in v: if(i>1000000...
MatrixStudio/Codeforces-Python-Submissions
You are given a rectangular board of *M*<=×<=*N* squares. Also you are given an unlimited number of standard domino pieces of 2<=×<=1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions: 1. Each domino completely covers ...
```python m,n=input().split() m=int(m) n=int(n) if(1<=m and m<=n and n<=16): p=m*n t=p//2 print(t) else: print('Invalid Input') ```
MatrixStudio/Codeforces-Python-Submissions
Dr. Moriarty is about to send a message to Sherlock Holmes. He has a string *s*. String *p* is called a substring of string *s* if you can read it starting from some position in the string *s*. For example, string "aba" has six substrings: "a", "b", "a", "ab", "ba", "aba". Dr. Moriarty plans to take string *s* and c...
```python print("_RANDOM_GUESS_1689418688.3535597")# 1689418688.3535807 ```
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 # for _ in range(1,int(input())+1): n=int(input()) # n,k=map(int,input().split()) # s=(input()) # a=list(map(int,input().split())) arr=[True]*(10**7) # arr[0],arr[1]=True,True for i in range(2,10**5): if arr[i]==True: print(i,end=" ") n-=1 if n==0: ...
MatrixStudio/Codeforces-Python-Submissions
Igor is in the museum and he wants to see as many pictures as possible. Museum can be represented as a rectangular field of *n*<=×<=*m* cells. Each cell is either empty or impassable. Empty cells are marked with '.', impassable cells are marked with '*'. Every two adjacent cells of different types (one empty and one i...
```python def dfs(x, y): vis[x][y] = True path.append((x, y)) paintings = 0 for dx, dy in ((-1, 0), (1, 0), (0, -1), (0, 1)): x1, y1 = x+dx, y+dy if x1 < 0 or x1 >= n or y1 < 0 or y1 >= m or vis[x1][y1]: continue if grid[x1][y1] == "*": paintings ...
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=map(int,input().split()) count=0 for i in range(0,n,1): s,c=map(str,input().split()) c=int(c) if s=='+': x=x+c else: if x-c<0: count=count+1 else: x=x-c print(str(x)+" "+str(count)) ```
MatrixStudio/Codeforces-Python-Submissions
There exists an island called Arpa’s land, some beautiful girls live there, as ugly ones do. Mehrdad wants to become minister of Arpa’s land. Arpa has prepared an exam. Exam has only one question, given *n*, print the last digit of 1378*n*. Mehrdad has become quite confused and wants you to help him. Please help, al...
```python n=int(input()) if n==0: print(1) else: w=n%4 if w==1: print(8) elif w==2: print(4) elif w==3: print(2) else: print(6) ```
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()) st = 0 a,b = map(int,input().split()) if a != 0: print("NO") else: st = a end = b flag = True for i in range(n-1): a,b = map(int,input().split()) if end>=m: break if end>=a: st = a end...
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 for _ in range(1): string = list(input()) n = len(string) upperCase = 0 lowerCase = 0 for i in range(n): if string[i].isupper(); upperCase += 1 else: lowerCase += 1 if upperCase <= lowerCase: print(string.lower()) ...
MatrixStudio/Codeforces-Python-Submissions
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob. Right now, Limak and Bob weigh *a* and *b* respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight. Limak eats a lot and his weight is tripled after every year, while Bob's we...
```python raj,shiv= list(map(int, input().split())) r = int() while raj <shiv: raj= raj*3 shiv = shiv*2 r =r+ 1 print(r) ```
MatrixStudio/Codeforces-Python-Submissions
Mancala is a game famous in the Middle East. It is played on a board that consists of 14 holes. Initially, each hole has $a_i$ stones. When a player makes a move, he chooses a hole which contains a positive number of stones. He takes all the stones inside it and then redistributes these stones one by one in the next ...
```python ai = list(map(int,input().split())) i = 0 ans = 0 while i < 14: j = 0 ai2 = [0] * 14 while j < 14: ai2[j] = ai[j] j+= 1 j = 0 temp = ai2[i] temp2 = temp % 14 temp3 = temp // 14 ai2[i] = 0 tempans= 0 while j < 14: ai2[j] += temp3 ...
MatrixStudio/Codeforces-Python-Submissions
The bear has a string *s*<==<=*s*1*s*2... *s*|*s*| (record |*s*| is the string's length), consisting of lowercase English letters. The bear wants to count the number of such pairs of indices *i*,<=*j* (1<=≤<=*i*<=≤<=*j*<=≤<=|*s*|), that string *x*(*i*,<=*j*)<==<=*s**i**s**i*<=+<=1... *s**j* contains at least one string...
```python def bear(s): b =0 for i in range(len(s)): c = s.find('bear' , i) if c >=0: b+=len(s)-c-3 return b if __name__ == '__main__': s = input() print(bear(s)) ```
MatrixStudio/Codeforces-Python-Submissions
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc....
```python s = input() t = input() s = ' '.join(s) s = list(s.split()) s.reverse() t = ' '.join(t) t = list(t.split()) if s == t: print('YES') else: print('NO') ```
MatrixStudio/Codeforces-Python-Submissions
The polar bears are going fishing. They plan to sail from (*s**x*,<=*s**y*) to (*e**x*,<=*e**y*). However, the boat can only sail by wind. At each second, the wind blows in one of these directions: east, south, west or north. Assume the boat is currently at (*x*,<=*y*). - If the wind blows to the east, the boat will ...
```python t, s_x, s_y, e_x, e_y = map(int, input().split()) directions = list(input()) x_dir = e_x - s_x y_dir = e_y - s_y duration = 0 reached = False cur_point = [s_x, s_y] for d in directions: if x_dir == 0 and y_dir == 0: reached = True break if d == 'S' and y_dir<0: y_dir +=1 elif d == "N" and...
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 num1,num2 = input(),input() str1 = '' for i in range(0,len(num1)): if num1[i] != num2[i]: str1 += '1' else: str1 += '0' print(str1) ```
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 t, f = [int(x) for x in input().split()] l = [] while(t): a, b = [int(x) for x in input().split()] l.append([a, b]) t -= 1 prev_a = 0 prev_d = 0 flag = "NO" for point in l: if(prev_a == 0 and prev_d == 0): prev_a = point[0] prev_d = point[1] else: if(point[1] > pre...
MatrixStudio/Codeforces-Python-Submissions
*n* soldiers stand in a circle. For each soldier his height *a**i* is known. A reconnaissance unit can be made of such two neighbouring soldiers, whose heights difference is minimal, i.e. |*a**i*<=-<=*a**j*| is minimal. So each of them will be less noticeable with the other. Output any pair of soldiers that can form a ...
```python n = int(input()) arr = list(map(int, input().split())) pair = [] dif = float("inf") for i in range(1, n): temp = abs(arr[i] - arr[i - 1]) if temp < dif: dif = temp pair = [i, i+1] if abs(arr[0] - arr[-1]) < dif: pair = [n, 1] print(*pair, sep=" ") ```
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()) def main(): if n in [1, 2]: print(1) print(1) return elif n == 3: print(2) print(1, 3) return elif n == 4: print(3) print(1, 4, 2) return print(n) for i in range(1, n+1, 2): print(i, end=' '...
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 """ https://codeforces.com/problemset/problem/716/A """ def ints(inp): return list(map(int, inp.split())) w = list() n, c = ints(input()) nums = ints(input()) for i in range(n - 1): if nums[i+1] - nums[i] <= c: w.append(nums[i+1]) w.append(nums[i]) else: ...
MatrixStudio/Codeforces-Python-Submissions
Vanya got bored and he painted *n* distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area.
```python import functools class Point: def __init__(self, x, y): self.x = x self.y = y def area_triangle(self, p1, p2): vector_1 = [p1.x - self.x, p1.y - self.y] vector_2 = [p2.x - self.x, p2.y - self.y] return vector_1[0] * vector_2[1] - vector_1[1] * vector...
MatrixStudio/Codeforces-Python-Submissions
Valera runs a 24/7 fast food cafe. He magically learned that next day *n* people will visit his cafe. For each person we know the arrival time: the *i*-th person comes exactly at *h**i* hours *m**i* minutes. The cafe spends less than a minute to serve each client, but if a client comes in and sees that there is no free...
```python t=int(input()) count=1 a=-1 b=-1 for i in range(t): n=int(input()) m=int(input()) if n==a and m==b: count=count+1 a=n b=m print(count) ```
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 n,k=map(int,input().split()) x=list(input().split()) mw=0 for i in range(0,n): a=x[i] if a=='0': break if i<k-1: mw += 1 la=a elif a==la: mw += 1 print(mw) ```
MatrixStudio/Codeforces-Python-Submissions
Little Elephant loves magic squares very much. A magic square is a 3<=×<=3 table, each cell contains some positive integer. At that the sums of integers in all rows, columns and diagonals of the table are equal. The figure below shows the magic square, the sum of integers in all its rows, columns and diagonals equals ...
```python r1 = list(map(int,input().split())) r2 = list(map(int,input().split())) r3 = list(map(int,input().split())) r = sum(r1)+sum(r2)+sum(r3) r1[0] = r//2 - sum(r1) r2[1] = r//2 - sum(r2) r3[2] = r//2 - sum(r3) print(*r1) print(*r2) print(*r3) ```
MatrixStudio/Codeforces-Python-Submissions
ZS the Coder loves to read the dictionary. He thinks that a word is nice if there exists a substring (contiguous segment of letters) of it of length 26 where each letter of English alphabet appears exactly once. In particular, if the string has length strictly less than 26, no such substring exists and thus it is not n...
```python s = input() n = len(s) al = set([chr(i + ord('A')) for i in range(26)]) for i in range(n - 26 + 1): c = 0 a = set() for j in range(i, i + 26): if(s[j] == '?'): c += 1 else: a.add(s[j]) if(c + len(a) == 26): l = list(al - a) ...
MatrixStudio/Codeforces-Python-Submissions
Just in case somebody missed it: we have wonderful girls in Arpa’s land. Arpa has a rooted tree (connected acyclic graph) consisting of *n* vertices. The vertices are numbered 1 through *n*, the vertex 1 is the root. There is a letter written on each edge of this tree. Mehrdad is a fan of Dokhtar-kosh things. He call ...
```python #include <bits/stdc++.h> #define mem(a,b) memset(a,b,sizeof a); #define rep(i,a,b) for(int i = a; i <= b; i++) #define per(i,a,b) for(int i = a; i >= b; i--) #define __ ios::sync_with_stdio(0);cin.tie(0);cout.tie(0) typedef long long ll; typedef double db; const int inf = 1e8; const int N = 5e5+10; c...
MatrixStudio/Codeforces-Python-Submissions
Victor tries to write his own text editor, with word correction included. However, the rules of word correction are really strange. Victor thinks that if a word contains two consecutive vowels, then it's kinda weird and it needs to be replaced. So the word corrector works in such a way: as long as there are two consec...
```python n=int(input()) l=list(input()) i=0 while(len(l)>1 and i<len(l)-1): if(l[i]=='o' or l[i]=='e' or l[i]=='a' or l[i]=='i' or l[i]=='u' or l[i]=='y'): if(l[i+1]=='o' or l[i+1]=='e' or l[i+1]=='a' or l[i+1]=='i' or l[i+1]=='u' or l[i+1]=='y'): l.remove(l[i+1]) else: ...
MatrixStudio/Codeforces-Python-Submissions
Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water. The only dry land there is an archipelago of *n* narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line...
```python import sys from bisect import bisect_left, bisect_right from math import inf input = sys.stdin.readline def sovle(): n, m = list(map(int, input().split())) intervals = [] for _ in range(m): l, r = list(map(int, input().split())) intervals.append([l, r]) a = list(map...
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 n=input() uc=0 lc=0 for i in n: if i.islower(): lc+=1 else: uc+=1 if(uc>lc): print(n.upper()) else: print(n.lower()) ```
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, ans = map(int, input().split()) d = 0 for i in range(n): p = input() if "+ " in p: p = p.replace("+ ", "") ans += int(p) else: p = p.replace("- ", "") p = int(p) if ans >= p: ans -= p else: d += 1 print(ans, d...
MatrixStudio/Codeforces-Python-Submissions
A string is a palindrome if it reads the same from the left to the right and from the right to the left. For example, the strings "kek", "abacaba", "r" and "papicipap" are palindromes, while the strings "abb" and "iq" are not. A substring $s[l \ldots r]$ ($1<=\leq<=l<=\leq<=r<=\leq<=|s|$) of a string $s<==<=s_{1}s_{2}...
```python import re import sys s=input() if s==s[::-1]: s=s.replace(s[-1],"",1) if s==s[::-1]: print("0") else: print(len(s)) else: print(len(s)) ```
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 num1=input() num2=input() for i in range(0,len(num1)): if(num1[i]==num2[i]):print(0,end='') else:print(1,end='') ```
MatrixStudio/Codeforces-Python-Submissions
A little boy Gerald entered a clothes shop and found out something very unpleasant: not all clothes turns out to match. For example, Gerald noticed that he looks rather ridiculous in a smoking suit and a baseball cap. Overall the shop sells *n* clothing items, and exactly *m* pairs of clothing items match. Each item h...
```python n,m=map(int,input().split()) l=list(map(int,input().split())) a=[] for i in range(m): x=list(map(int,input().split())) a.append(x) if m==2: print(-1) else: r=[] for i in range(len(a)): for j in range(i+1,len(a)): for k in range(j+1,len(a)): ...
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*<=&lt;<=*n*<=+<=*m*) such th...
```python nm = input("").split(" ") nm = [int(x) for x in nm] n, m = nm finalString = "" if n > m: for item in range(m): finalString += "BG" for item in range(n-m): finalString += "B" else: for item in range(n): finalString += "GB" for item in range(m-n): finalString += "G" print(f...
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 fractions import Fraction Yakko, Wakko = input().split() Yakko = int(Yakko) Wakko = int(Wakko) max_v = max(Yakko, Wakko) Die_Roll = 6 - max_v + 1 for i in range(6, 0, -1): if(Yakko == 1 and Wakko == 1): print(str(Yakko) + "/" + str(Wakko)) break elif(Die_Roll == 5): ...
MatrixStudio/Codeforces-Python-Submissions
Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are *n* drinks in his fridge, the volume fraction of orange juice in the *i*-th drink equals *p**i* percent. One day Vasya decided to make himself an orange cocktail. He took equal proportio...
```python t=int(input()) x=list(map(int,input().split())) b=sum(x) a=len(x) c="{:.12f}".format(b/a) print(c) ```
MatrixStudio/Codeforces-Python-Submissions
Noora is a student of one famous high school. It's her final year in school — she is going to study in university next year. However, she has to get an «A» graduation certificate in order to apply to a prestigious one. In school, where Noora is studying, teachers are putting down marks to the online class register, wh...
```python import math n, k = map(int, input().split()) amt = 0 nums = [int(x) for x in input().split()] amt = sum(nums) ans = 2*n*k - n - 2*amt print(math.ceil(ans) if ans >=0 else 0) ```
MatrixStudio/Codeforces-Python-Submissions
The New Year is coming! That's why many people today are busy preparing New Year presents. Vasily the Programmer is no exception. Vasily knows that the best present is (no, it's not a contest) money. He's put *n* empty wallets from left to right in a row and decided how much money to put in what wallet. Vasily decided...
```python import sys input = sys.stdin.readline n = int(input()) w = list(map(int, input().split())) d = '' for i in range(n-1): d += 'PRL'*w[i] d += 'R' d += 'PLR'*w[-1] print(d) ```
MatrixStudio/Codeforces-Python-Submissions
Sereja and Dima play a game. The rules of the game are very simple. The players have *n* cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. Th...
```python n=int(input()) a=list(map(int,input().split())) s=0 d=0 for i in range(n): b=max(a[0],a[-1]) if i%2==0: s+=b else: d+=b a.remove(b) print(s,d) ```
MatrixStudio/Codeforces-Python-Submissions
Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he...
```python class MarvoloGauntRing: def __init__(self, p, q, r, arr): self.arr = arr self.p = p self.q = q self.r = r def give_x_potions(self): p_max = self.prefix_max() print(p_max) s_max = self.sufix_max() print(s_max)...
MatrixStudio/Codeforces-Python-Submissions
Last week, Hamed learned about a new type of equations in his math class called Modular Equations. Lets define *i* modulo *j* as the remainder of division of *i* by *j* and denote it by . A Modular Equation, as Hamed's teacher described, is an equation of the form in which *a* and *b* are two non-negative integers and...
```python a, b = map(int, input().split(" ")) a1 = a - b if a == b: print("infinity") else: cont = 0 i = 1 while i ** 2 <= a1: if a1 % i == 0 and i > b: cont += 1 if a1 % i == 0 and b < a1 // i != i: cont += 1 i += 1 print(cont) ```
MatrixStudio/Codeforces-Python-Submissions
Bash wants to become a Pokemon master one day. Although he liked a lot of Pokemon, he has always been fascinated by Bulbasaur the most. Soon, things started getting serious and his fascination turned into an obsession. Since he is too young to go out and catch Bulbasaur, he came up with his own way of catching a Bulbas...
```python s = input() b1 = u = b = l = a = s1 = u = r = 0 for i in range(len(s)): if s[i] == 'B': b1 +=1 if s[i] == 'u': u +=1 if s[i] == 'l': l +=1 if s[i] == 'b': b +=1 if s[i] == 'a': a +=1 if s[i] == 's': s1 +=1 if s[i] == 'r...
MatrixStudio/Codeforces-Python-Submissions
When Valera has got some free time, he goes to the library to read some books. Today he's got *t* free minutes to read. That's why Valera took *n* books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to *n*. Valera needs *a**i* minutes to...
```python n,t=map(int,input().split()) m=list(map(int,input().split())) a=-1 for i in range(len(m)): count=0 sum=0 while(i<=len(m)-1 and (sum+m[i])<=t): sum=sum+m[i] count=count+1 i=i+1 if(count>a): a=count print(a) ```
MatrixStudio/Codeforces-Python-Submissions
Do you remember a kind cartoon "Beauty and the Beast"? No, no, there was no firing from machine guns or radiation mutants time-travels! There was a beauty named Belle. Once she had violated the Beast's order and visited the West Wing. After that she was banished from the castle... Everybody was upset. The beautiful ...
```python time = input() h = int(time[0])*10 + int(time[1]) m = int(time[3])*10 + int(time[4]) h = h % 12 angle1 = h*30 + m//2 if m%2 == 1: angle1 += 0.5 angle2 = m*6 print(angle1, angle2) ```
MatrixStudio/Codeforces-Python-Submissions
Let's define the sum of two permutations *p* and *q* of numbers 0,<=1,<=...,<=(*n*<=-<=1) as permutation , where *Perm*(*x*) is the *x*-th lexicographically permutation of numbers 0,<=1,<=...,<=(*n*<=-<=1) (counting from zero), and *Ord*(*p*) is the number of permutation *p* in the lexicographical order. For example, ...
```python num=1 for i in range(1, 200001):num*=i print("Done") ```
MatrixStudio/Codeforces-Python-Submissions
Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, inf...
```python l=int(input()) str=input() str1="" lst=list(str) while len(lst)>=3: if l%2==0: str1+=lst[(l//2)-1] lst.pop((l//2)-1] else: str1+=lst[l//2] lst.pop((l//2)) str1+=lst[0]+lst[1] print(str1) ```
MatrixStudio/Codeforces-Python-Submissions
Do you know a story about the three musketeers? Anyway, you will learn about its origins now. Richelimakieu is a cardinal in the city of Bearis. He is tired of dealing with crime by himself. He needs three brave warriors to help him to fight against bad guys. There are *n* warriors. Richelimakieu wants to choose thre...
```python def dfs(knights,k,st,cycle,limit=2): if limit == 0: if st not in knights[k]: return total=0 for k in cycle: total+=len(knights[k])-2 cycles.append(total) return for i in knights[k]: cycle.append(i) dfs(knights,i,st,cycle,l...
MatrixStudio/Codeforces-Python-Submissions
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed *w* kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem. Pete and ...
```python n = int(input()) if n%2==0 and n>=2:print("Yes") else:print("No") ```
MatrixStudio/Codeforces-Python-Submissions
While swimming at the beach, Mike has accidentally dropped his cellphone into the water. There was no worry as he bought a cheap replacement phone with an old-fashioned keyboard. The keyboard has only ten digital equal-sized keys, located in the following way: Together with his old phone, he lost all his contacts and ...
```python # LUOGU_RID: 101608072 _, s = input(), input() print(all(set(t) & set(s) for t in '0147 0369 079 123'.split()) and 'YES' or 'NO') ```
MatrixStudio/Codeforces-Python-Submissions
The on-board computer on Polycarp's car measured that the car speed at the beginning of some section of the path equals *v*1 meters per second, and in the end it is *v*2 meters per second. We know that this section of the route took exactly *t* seconds to pass. Assuming that at each of the seconds the speed is constan...
```python v1,v2 = map(int,input().split()) t,d = map(int,input().split()) if v1>v2: z = v1 v1 = v2 v2 = z ans = v1 cur = v1 for i in range(2,t+1): temp = (t-i)*d f = 0 for j in range(d,-1,-1): if abs((cur+j)-v2)<=temp: f=1 cur += j ans+=cur ...
MatrixStudio/Codeforces-Python-Submissions
You are given an array *a* with *n* elements. Each element of *a* is either 0 or 1. Let's denote the length of the longest subsegment of consecutive elements in *a*, consisting of only numbers one, as *f*(*a*). You can change no more than *k* zeroes to ones to maximize *f*(*a*).
```python def maximize_subsegment_length(n, k, a): left = 0 right = 0 max_length = 0 max_zeros = k best_left = 0 best_right = 0 while right < n: if a[right] == 0: max_zeros -= 1 while max_zeros < 0: if a[left] == 0: max_zeros += 1 ...
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 import math test_case=input().split(' ') def heap_left(fixed,gcd):return gcd-math.gcd(fixed,gcd) def assignment(p1,p2,n): list=[int(n)] flag=int(n) count=0 while flag!=0: if count%2==0:flag=heap_left(int(p1),list[count]);list.append(heap_left(int(p1),list[count])) ...
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() low=0 upp=0 for i in s: if i==i.upper(): upp=upp+1 else: low=low+1 if upp>low: print(s.upper()) else: print(s.lower()) ```
MatrixStudio/Codeforces-Python-Submissions
There is a very secret base in Potatoland where potato mash is made according to a special recipe. The neighbours from Porridgia decided to seize this recipe and to sell it to Pilauland. For this mission they have been preparing special agent Pearlo for many years. When, finally, Pearlo learned all secrets of espionage...
```python a = input() b = input() c = input() s = a+b+c if s == s[::-1]: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Patrick has just finished writing a message to his sweetheart Stacey when he noticed that the message didn't look fancy. Patrick was nervous while writing the message, so some of the letters there were lowercase and some of them were uppercase. Patrick believes that a message is fancy if any uppercase letter stands to...
```python import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline s = list(input().rstrip()) cnt = [0] for i in s: cnt.append(cnt[-1] + i // 97) n = len(s) ans = n for i in range(n + 1): u, v = cnt[i], n - i - (cnt[n] - cnt[i]) ans = min(ans, u + v) print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
You are given two very long integers *a*,<=*b* (leading zeroes are allowed). You should check what number *a* or *b* is greater or determine that they are equal. The input size is very large so don't use the reading of symbols one by one. Instead of that use the reading of a whole line or token. As input/output can r...
```python # LUOGU_RID: 126991992 a=input().lstrip('0');b=input().lstrip() if len(a)>len(b):print('>') elif len(a)<len(b):print('<') elif a>b:print('>') elif a<b:print('<') else:print('=') ```
MatrixStudio/Codeforces-Python-Submissions
The HR manager was disappointed again. The last applicant failed the interview the same way as 24 previous ones. "Do I give such a hard task?" — the HR manager thought. "Just raise number 5 to the power of *n* and get last two digits of the number. Yes, of course, *n* can be rather big, and one cannot find the power us...
```python # URL: https://codeforces.com/problemset/problem/630/A import io import os import sys input_buffer = io.BytesIO(os.read(0, os.fstat(0).st_size)) inp = lambda: input_buffer.readline().rstrip(b"\n").rstrip(b"\r") out = sys.stdout.write out("25") ```
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 s = input() a = s.count('o') b = s.count('-') print("NO" if a and b % a else "YES") ```
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()) a=list(map(int,input().split())) mx=max(a) mn=min(a) ind_mx=a.index(mx) ind_mn=0 for i in range(n-1,-1,-1): if(a[i]==mn): ind_mn+=1 break ind_mn+=1 if(n-ind_mn<ind_mx): print(ind_mx+(ind_mn-2)) else: print(ind_mx+ind_mn-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 n,k=map(int,input().split()) a=[] b=[] for i in range(n): b=[] for j in range(n): if i==j: b.append(k) else: b.append(0) a.append(b) for i in range(n): for j in range(n): print(a[i][j],'',end='') print() ```
MatrixStudio/Codeforces-Python-Submissions
Petr stands in line of *n* people, but he doesn't know exactly which position he occupies. He can say that there are no less than *a* people standing in front of him and no more than *b* people standing behind him. Find the number of different positions Petr can occupy.
```python def canteen(n,m,o): x=1+m y=n-o if y<=x: return (n-x)+1 else: return 0 a,b,c=map(int,input().split()) print(canteen(a,b,c)) ```
MatrixStudio/Codeforces-Python-Submissions
You are given an array of integers. Vasya can permute (change order) its integers. He wants to do it so that as many as possible integers will become on a place where a smaller integer used to stand. Help Vasya find the maximal number of such integers. For instance, if we are given an array $[10, 20, 30, 40]$, we can ...
```python n=int(input()) arr=[int(c) for c in input().split()] ans=0 temp=sorted(arr) arr.sort() i=n-1 curr=temp.pop() while i>=0: if arr[i]<curr: ans+=1 curr=temp.pop() i-=1 else: i-=1 print(ans) ```