source
stringclasses
3 values
instruction
stringlengths
23
3.97k
input
stringclasses
1 value
output
stringlengths
1
3.75k
MatrixStudio/Codeforces-Python-Submissions
You have *n* distinct points on a plane, none of them lie on *OY* axis. Check that there is a point after removal of which the remaining points are located on one side of the *OY* axis.
```python # https://codeforces.com/problemset/problem/900/A left = 0 right = 0 for _ in range(int(input())): x, y = map(int, input().split()) if x < 0: left += 1 if x > 0: right += 1 if left > 1 and right > 1: print("NO") break else: print("YES") ...
MatrixStudio/Codeforces-Python-Submissions
Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in *n* different shops in the city. It's known that the price of one bottle in the shop *i* is equal to *x**i* coins. Vasiliy plans to buy his favorite ...
```python # -*- coding: utf-8 -*- """ Created on Mon Nov 13 22:31:05 2023 @author: 刘婉婷 2300012258 """ n = int(input()) beecola_price = list(map(int, input().split())) beecola_price.sort() q = int(input()) def binary_search(arr, target): left, right = 0, len(arr) - 1 while left <= right: ...
MatrixStudio/Codeforces-Python-Submissions
Roma works in a company that sells TVs. Now he has to prepare a report for the last year. Roma has got a list of the company's incomes. The list is a sequence that consists of *n* integers. The total income of the company is the sum of all integers in sequence. Roma decided to perform exactly *k* changes of signs of s...
```python n, k = map(int, input().split()) a = list(map(int, input().split())) for i in range(n): if k > 0 and a[i] < 0: k -= 1 a[i] *= -1 a.sort() a[0] *= (-1)**k print(sum(a)) ```
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()) a=input().split() b=[int(i) for i in a] min1=float('inf') for i in range(n): c=input().split() d=[int(j) for j in c] e=[j*5 for j in d] if sum(e)+len(d)*15<min1: min1= sum(e)+len(d)*15 print(min1) ```
MatrixStudio/Codeforces-Python-Submissions
You've got an *n*<=×<=*m* pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture. A picture is a barcode if the following conditions are fulfilled: - All pixels in each column are of the same color. - The width of each monochrome ...
```python from collections import defaultdict, deque, Counter from sys import stdin, stdout from heapq import heappush, heappop import math import io import os import math import bisect #?############################################################ def isPrime(x): if(x == 1): return False ...
MatrixStudio/Codeforces-Python-Submissions
There are *n* stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them.
```python # Inicializar un contador para llevar un registro de las piedras que se deben quitar contador = 0 # Recorrer los colores de las piedras for i in range(1, n): if s[i] == s[i - 1]: contador += 1 # Imprimir la respuesta print(contador) ```
MatrixStudio/Codeforces-Python-Submissions
Alice likes word "nineteen" very much. She has a string *s* and wants the string to contain as many such words as possible. For that reason she can rearrange the letters of the string. For example, if she has string "xiineteenppnnnewtnee", she can get string "xnineteenppnineteenw", containing (the occurrences marked) ...
```python s=input() print(min(s.count('i'),s.count('t'),s.count('n')//3,s.count('e')//3)) ```
MatrixStudio/Codeforces-Python-Submissions
There are quite a lot of ways to have fun with inflatable balloons. For example, you can fill them with water and see what happens. Grigory and Andrew have the same opinion. So, once upon a time, they went to the shop and bought $n$ packets with inflatable balloons, where $i$-th of them has exactly $a_i$ balloons insi...
```python n=int(input()) a=list(map(int, input().split())) m=min(a) if m*2<sum(a): print('1\n'+str(a.index(m))) else: print(-1) ```
MatrixStudio/Codeforces-Python-Submissions
Valera is a little boy. Yesterday he got a huge Math hometask at school, so Valera didn't have enough time to properly learn the English alphabet for his English lesson. Unfortunately, the English teacher decided to have a test on alphabet today. At the test Valera got a square piece of squared paper. The length of the...
```python def check(lis,dia,oth,i,n): if i == 0 or i == n-1: if lis[0] != dia: return False if lis[len(lis)-1] != dia: return False for i in range(1,len(lis)-1): if lis[i] != oth: return False return True else: ...
MatrixStudio/Codeforces-Python-Submissions
Arkady is playing Battleship. The rules of this game aren't really important. There is a field of $n \times n$ cells. There should be exactly one $k$-decker on the field, i. e. a ship that is $k$ cells long oriented either horizontally or vertically. However, Arkady doesn't know where it is located. For each cell Arka...
```python import math def possible(x, y, mat): total = 0 if (mat[x][y] == 0): return 0 else: start = y - k+1 end = y for i in range(k): if ((start+i)>=0 and (start+i+k) <= n): valid = True for j in range(k): ...
MatrixStudio/Codeforces-Python-Submissions
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
```python c=input() if len(c)>10: print(c[1]+(len(c)-2)+c[-1]) else: print(c) ```
MatrixStudio/Codeforces-Python-Submissions
Vitaly is a diligent student who never missed a lesson in his five years of studying in the university. He always does his homework on time and passes his exams in time. During the last lesson the teacher has provided two strings *s* and *t* to Vitaly. The strings have the same length, they consist of lowercase Engli...
```python s = input() t = input() n = len(s) ans = list(s) for i in range(n): c = ans[i] ans[i] = chr(ord(c) + 1) a = ''.join(ans) if(a > s and a < t): print(a) break ans[i] = c else: print("No such string") ```
MatrixStudio/Codeforces-Python-Submissions
A burglar got into a matches warehouse and wants to steal as many matches as possible. In the warehouse there are *m* containers, in the *i*-th container there are *a**i* matchboxes, and each matchbox contains *b**i* matches. All the matchboxes are of the same size. The burglar's rucksack can hold *n* matchboxes exactl...
```python n, m = map(int, input().split()) num = [] for _ in range(m): num.append(list(reversed(list(map(int, input().split()))))) num.sort(reverse=True) # print(num) sum = 0 for i in range(len(num)): for x in range(num[i][1]): if n == 0: break else: sum += num[i][0] ...
MatrixStudio/Codeforces-Python-Submissions
Innokentiy decides to change the password in the social net "Contact!", but he is too lazy to invent a new password by himself. That is why he needs your help. Innokentiy decides that new password should satisfy the following conditions: - the length of the password must be equal to *n*, - the password should cons...
```python a = 'abcdefghijklmnopqrstuvwxyz' n,k = map(int, input().split()) password = "" a = a[:k] while len(a) < n: a = a+a[:1] print(a[:n]) ```
MatrixStudio/Codeforces-Python-Submissions
Xenia the mathematician has a sequence consisting of *n* (*n* is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three *a*,<=*b*,<=*c* the following conditions held: - *a*<=&lt;<=*b*<=&lt;<=*c*; - *a* divides *b*, *b* divide...
```python def solve(ans): #print(ans) for l in ans: for i in range(len(l) - 1): if (l[i] >= l[i + 1] or l[i + 1] % l[i] != 0): return 0 return 1 n = int(input()) a = list(map(int,input().split())) jump = n//3 ans=[] a.sort() #print(a) for i in range(n//3): ...
MatrixStudio/Codeforces-Python-Submissions
Vitya has just started learning Berlanese language. It is known that Berlanese uses the Latin alphabet. Vowel letters are "a", "o", "u", "i", and "e". Other letters are consonant. In Berlanese, there has to be a vowel after every consonant, but there can be any letter after any vowel. The only exception is a consonant...
```python s=input()+'' output='YES' t='aeiou' n=len(s) for i in range(n-1): if s[i] not in t+'n' and s[i+1] not in t: output='NO' break print(output) ```
MatrixStudio/Codeforces-Python-Submissions
Eleven wants to choose a new name for herself. As a bunch of geeks, her friends suggested an algorithm to choose a name for her. Eleven wants her name to have exactly *n* characters. Her friend suggested that her name should only consist of uppercase and lowercase letters 'O'. More precisely, they suggested that the ...
```python n = int(input()) a = 1 b = 1 c = [1, 1] while a < n and b < n: a = a+b c.append(a) b = a+b c.append(b) d = [] for i in range(1, n+1): if i in c: d.append('O') else: d.append('o') print(''.join(d)) ```
MatrixStudio/Codeforces-Python-Submissions
Leha somehow found an array consisting of *n* integers. Looking at it, he came up with a task. Two players play the game on the array. Players move one by one. The first player can choose for his move a subsegment of non-zero length with an odd sum of numbers and remove it from the array, after that the remaining parts...
```python n=int(input()) a=list(map(int,input().split())) c=0 for i in range(n): if a[i]%2==1:c+=1 if c>0:break if c>0:print('First') else:print('Second') ```
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 num=input() numOfTran=0 while len(num) > 1 : sumDig=0 for curr in num : sumDig+=int(curr) numOfTran+=1 num=str(sumDig) print(numOfTran) ```
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 x = input() l = [] for i in str(x): l.append(int(i)) for i in range(len(l)): a=9-l[i] if(a<l[i]): l[i]=a if(l[0]==0): l[0]=9 for i in range(len(l)): print(l[i],end="") ```
MatrixStudio/Codeforces-Python-Submissions
There are times you recall a good old friend and everything you've come through together. Luckily there are social networks — they store all your message history making it easy to know what you argued over 10 years ago. More formal, your message history is a sequence of messages ordered by time sent numbered from 1 to...
```python n, k = [int(x) for x in input().split()] a = [int(x) for x in input().split()] dic = {} for i in range(1, n + 1): dic[i] = a[i-1] counts = dict.fromkeys(dic) for key, value in counts.items(): if key == 1: counts[key] = set() counts[key].add(key) for i in ra...
MatrixStudio/Codeforces-Python-Submissions
Today, Wet Shark is given *n* integers. Using any of these integers no more than once, Wet Shark wants to get maximum possible even (divisible by 2) sum. Please, calculate this value for Wet Shark. Note, that if Wet Shark uses no integers from the *n* integers, the sum is an even integer 0.
```python n=int(input()) arr=([int(i) for i in input().split()]) sum=0 for i in range (n): sum = sum + arr[i] if sum%2==0: sum=sum+0 else: sum=sum-arr[n-1] print(sum) ```
MatrixStudio/Codeforces-Python-Submissions
Polycarp takes part in a quadcopter competition. According to the rules a flying robot should: - start the race from some point of a field, - go around the flag, - close cycle returning back to the starting point. Polycarp knows the coordinates of the starting point (*x*1,<=*y*1) and the coordinates of the point w...
```python x1,y1 = map(int,input().split()) x2,y2 = map(int,input().split()) r = (x1 == x2) + (x1 == x2) print(((abs(x1-x2) + 1)*2) + ((abs(y1-y2) + 1)*2) + r) ```
MatrixStudio/Codeforces-Python-Submissions
Let's call the roundness of the number the number of zeros to which it ends. You have an array of *n* numbers. You need to choose a subset of exactly *k* numbers so that the roundness of the product of the selected numbers will be maximum possible.
```python from collections import deque def main(): n, k = [int(t) for t in input().split()] numbers = [int(t) for t in input().split()] product_counts = [get_product_count(number) for number in numbers] number_counts = {} for number in numbers: if number in number_counts.keys(): ...
MatrixStudio/Codeforces-Python-Submissions
After winning gold and silver in IOI 2014, Akshat and Malvika want to have some fun. Now they are playing a game on a grid made of *n* horizontal and *m* vertical sticks. An intersection point is any point on the grid which is formed by the intersection of one horizontal stick and one vertical stick. In the grid show...
```python n , m = [int(i) for i in input().split()] if n == 1 and m == 1 : total = n + m elif n == 1 or m == 1: total = n + m - 1 else: total = n + m if int(total / 2) % 2 == 0: print("Malvika") else: print("Akshat") ```
MatrixStudio/Codeforces-Python-Submissions
Eighth-grader Vova is on duty today in the class. After classes, he went into the office to wash the board, and found on it the number *n*. He asked what is this number and the teacher of mathematics Inna Petrovna answered Vova that *n* is the answer to the arithmetic task for first-graders. In the textbook, a certain ...
```python ''' http://codeforces.com/problemset/problem/875/A ''' value = int(input()) def display(lst): for item in lst.sort(): print(item) def sum_a_string(str_digit): result = 0 for i in str_digit: result+=int(i) return result def get_sum(value): count = 0 possible_digits = [] for num in range(v...
MatrixStudio/Codeforces-Python-Submissions
In this problem you will have to deal with a real algorithm that is used in the VK social network. As in any other company that creates high-loaded websites, the VK developers have to deal with request statistics regularly. An important indicator reflecting the load of the site is the mean number of requests for a cer...
```python n,T,c=map(float,input().split()) #n=int(n) #T=int(T) a=list(map(int,input().split())) m=int(input()) p=list(map(int,input().split())) real=0 summ=0 for i in range(m): mean=0 for j in range(p[i]): mean=(mean+a[j]/T)/c k=p[i]-int(T) if k<0: k=0 summ=sum(a[k:(...
MatrixStudio/Codeforces-Python-Submissions
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point *x*(*x*<=&gt;<=0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make ...
```python a=input() b=int((a/5)+1) c=int(a/5) if a<5: print(1) elif a//5==0: print(c) else: print(b) ```
MatrixStudio/Codeforces-Python-Submissions
There is a straight snowy road, divided into *n* blocks. The blocks are numbered from 1 to *n* from left to right. If one moves from the *i*-th block to the (*i*<=+<=1)-th block, he will leave a right footprint on the *i*-th block. Similarly, if one moves from the *i*-th block to the (*i*<=-<=1)-th block, he will leave...
```python import sys input = sys.stdin.readline n = int(input()) s = input()[:-1] if 'R' in s: if 'L' in s: print(s.index('R')+1, s.index('L')) else: print(s.index('R')+1, s.rindex('R') + 2) else: print(s.rindex('L')+1, s.index('L')) ```
MatrixStudio/Codeforces-Python-Submissions
Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot. He wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fence corners at a single angle *a*. Will the robot be able to build the fence Emuska...
```python #include <iostream> using namespace std; int main() { int t, a; cin >> t; while (t--) { cin >> a; if (360 % (180 - a) == 0) { cout << "YES" << endl; } else { cout << "NO" << endl; } } ...
MatrixStudio/Codeforces-Python-Submissions
Arpa is taking a geometry exam. Here is the last problem of the exam. You are given three points *a*,<=*b*,<=*c*. Find a point and an angle such that if we rotate the page around the point by the angle, the new position of *a* is the same as the old position of *b*, and the new position of *b* is the same as the old ...
```python def vector_product(v1x, v1y, v2x, v2y): return (v1x * v2y - v1y * v2x) def len_sq(vx, vy): return (vx * vx + vy * vy) ax, ay, bx, by, cx, cy = (int(x) for x in input().split()) abx = bx - ax aby = by - ay bcx = cx - bx bcy = cy - by if vector_product(abx, aby, bcx, bcy) == 0: pri...
MatrixStudio/Codeforces-Python-Submissions
Xenia lives in a city that has *n* houses built along the main ringroad. The ringroad houses are numbered 1 through *n* in the clockwise order. The ringroad traffic is one way and also is clockwise. Xenia has recently moved into the ringroad house number 1. As a result, she's got *m* things to do. In order to complete...
```python # Función para calcular el tiempo necesario para una tarea específica def calcular_tiempo_para_tarea(posicion_actual, tarea, n): distancia = tarea - posicion_actual if distancia >= 0: tiempo_necesario = distancia else: tiempo_necesario = n + distancia return tiempo...
MatrixStudio/Codeforces-Python-Submissions
A country has *n* cities. Initially, there is no road in the country. One day, the king decides to construct some roads connecting pairs of cities. Roads can be traversed either way. He wants those roads to be constructed in such a way that it is possible to go from each city to any other city by traversing at most two...
```python n, m = map(int, input().split()) massa = [] x = 0 y = 0 z = 0 for i in range ( m ): x, y = map(int, input().split()) if not( x in massa ): massa.append( x ) if not ( y in massa ): massa.append ( x ) for i in range( 1, ( n + 1 )): if not ( i in massa ): z = i break print(...
MatrixStudio/Codeforces-Python-Submissions
A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not. The next prime number after *x* is the smallest prime number greater than *x*. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note t...
```python n, m = map(int, input().split()) while n <= m: n += 1 count = 0 for i in range(1, n+1): if n % i == 0: count += 1 if count == 2 and n == m: print("YES") break elif count == 2 and n != m: print("NO") break ```
MatrixStudio/Codeforces-Python-Submissions
You have *r* red, *g* green and *b* blue balloons. To decorate a single table for the banquet you need exactly three balloons. Three balloons attached to some table shouldn't have the same color. What maximum number *t* of tables can be decorated if we know number of balloons of each color? Your task is to write a pro...
```python a,b,c = sorted(list(map(int,input().split()))) score = 0 while a>0 or b>0: if a!=0 and c>b+1: x = 2*a a = 0 y = c-b c = c-b+y%2 if y>=x: score+=x//2 y = y-x c+=y else: score +=y//2 ...
MatrixStudio/Codeforces-Python-Submissions
A has a string consisting of some number of lowercase English letters 'a'. He gives it to his friend B who appends some number of letters 'b' to the end of this string. Since both A and B like the characters 'a' and 'b', they have made sure that at this point, at least one 'a' and one 'b' exist in the string. B now gi...
```python s=input().strip() a_count=s.count('a') b_count=s.count('b') c_count=s.count('c') arr=list(s) arr1=arr.copy() arr1.sort() if a_count>0 and b_count>0 and (a_count==c_count or b_count==c_count) and arr==arr1: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Permutation *p* is an ordered set of integers *p*1,<=<=*p*2,<=<=...,<=<=*p**n*, consisting of *n* distinct positive integers, each of them doesn't exceed *n*. We'll denote the *i*-th element of permutation *p* as *p**i*. We'll call number *n* the size or the length of permutation *p*1,<=<=*p*2,<=<=...,<=<=*p**n*. The ...
```python n, k = map(int, input().split()) if k == 0: lst1 = [] for b in range(1, n+1): lst1.append(b) res1 = [str(r) for r in lst1] print(' '.join(res1)) else: lst = [] for x in range(k): lst.append(n - x) for y in range(k, n): lst.append(y - k + 1) ...
MatrixStudio/Codeforces-Python-Submissions
Sereja loves number sequences very much. That's why he decided to make himself a new one following a certain algorithm. Sereja takes a blank piece of paper. Then he starts writing out the sequence in *m* stages. Each time he either adds a new number to the end of the sequence or takes *l* first elements of the current...
```python n,k=map(int,input().split(" ")) li=list(map(int,input().split(" ",n)[:n])) hs=[[0 for i in range(k)] for i in range(n//k)] for i in range(n//k): for j in range(k): hs[i][j]=li[i+j] ans=0 for i in range(k): for j in range(n//k): ```
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() upp=0 low=0 for i in range(len(s)): if 'a'<=s[i]<='z': low+=1 else: upp+=1 if low<upp: s=s.upper() else: s=s.lower() print(s) ```
MatrixStudio/Codeforces-Python-Submissions
Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array *a* consisting of *n* distinct integers. Unfortunately, the size of *a* is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question corr...
```python n = int(input()) nums = [int(i) for i in input().split()] start = 0 end = 0 sorted_ascend = sorted(nums) # for i in range(1, n + 1): # if nums[i] < nums[i - 1]: # start = i # if nums[i] > if nums == sorted_ascend: print('yes') print('1 1') elif sorted_ascend[::-1] == nums: print...
MatrixStudio/Codeforces-Python-Submissions
Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw. The first player wrote number *a*, the second player wrote number *b*. How many w...
```python a,b=map(int,input().split()) win,draw,lose=0,0,0 for i in range(1,7): if abs(a-i)<abs(b-i): win+=1 elif abs(a-i)==abs(b-i): draw+=1 else: lose+=1 print(win,draw,lose) ```
MatrixStudio/Codeforces-Python-Submissions
Two players play a simple game. Each player is provided with a box with balls. First player's box contains exactly *n*1 balls and second player's box contains exactly *n*2 balls. In one move first player can take from 1 to *k*1 balls from his box and throw them away. Similarly, the second player can take from 1 to *k*2...
```python n_1,n_2,k_1,k_2=y.split() n_1=int(n_1) n_2=int(n_2) k_1=int(k_1) k_2=int(k_2) a="First" b="Second" if n_1==n_2: print(b) if n_1>n_2: print(a) else: print(b) ```
MatrixStudio/Codeforces-Python-Submissions
Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in *n* different shops in the city. It's known that the price of one bottle in the shop *i* is equal to *x**i* coins. Vasiliy plans to buy his favorite ...
```python n = int(input()) x = sorted(list(map(int, input().split()))) q = int(input()) for _ in range(q): k = int(input()) l, r = 0, len(x)-1 while l <= r: m = (l+r) // 2 if x[m] > k: r = m - 1 elif x[m] < k: l = m + 1 elif x[m] == k: prin...
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 need = "hello" j = 0 for i in input(): if i == need[j]: j += 1 if j == len(need): break print("YES" if j == len(need) else "NO") ```
MatrixStudio/Codeforces-Python-Submissions
Ternary numeric notation is quite popular in Berland. To telegraph the ternary number the Borze alphabet is used. Digit 0 is transmitted as «.», 1 as «-.» and 2 as «--». You are to decode the Borze code, i.e. to find out the ternary number given its representation in Borze alphabet.
```python s = input("this is input") und = False for x in s: if x == '-' and not und: und = True elif und and x == '-': und = False print("2", end='') elif und and x == '.': print('1', end='') und = False else: print('0', end='') ...
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 word = input() indexh = word.rindex("h") indexe = word.rindex("e") indexl1 = indexe + word[indexe:].find("l") indexl2 = word.rindex("l") indexo = word.rindex("o") if indexh < indexe and indexe < indexl1 and indexl1<indexl2 and indexl2<indexo : print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Vasya and Petya are playing a simple game. Vasya thought of number *x* between 1 and *n*, and Petya tries to guess the number. Petya can ask questions like: "Is the unknown number divisible by number *y*?". The game is played by the following rules: first Petya asks all the questions that interest him (also, he can a...
```python n, s = int(input()) + 1, set() for i in range(2, n): for j in range(2, n): if not i % j: k = i while not k % j: k //= j if k == 1: s.add(i) break print(len(s), *s) ```
MatrixStudio/Codeforces-Python-Submissions
One spring day on his way to university Lesha found an array *A*. Lesha likes to split arrays into several parts. This time Lesha decided to split the array *A* into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays...
```python for i in range(int(input())): t, lis = int(input()), list(map(int, input().split())) a, b = lis[0], lis[1] if a==b: for j in range(2, t): if lis[j] != a: print(j + 1) break else: if a == lis[2]: print(2) ...
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 re ct = 0 total = 0 y = input().strip() h = " ".join(y) c = re.split(r"\s+", h) for i in c: if i == '(': ct += 1 elif i == ')' and ct != 0: ct -= 1 total += 2 print(total) ```
MatrixStudio/Codeforces-Python-Submissions
This winter is so cold in Nvodsk! A group of *n* friends decided to buy *k* bottles of a soft drink called "Take-It-Light" to warm up a bit. Each bottle has *l* milliliters of the drink. Also they bought *c* limes and cut each of them into *d* slices. After that they found *p* grams of salt. To make a toast, each frie...
```python import math n=int(input("Number of Friends: ")) k=int(input("Number of Cans: ")) l=int(input("Mililiter of Drink: ")) nl=int(input("Drink In Each Bottle: ")) totalmil=k*l totalto=totalmil//nl c=int(input("Number of Limes: ")) d=int(input("Number of Slices for Each Lime: ")) totalimeslices=c*d p=int(input(...
MatrixStudio/Codeforces-Python-Submissions
Two friends are on the coordinate axis *Ox* in points with integer coordinates. One of them is in the point *x*1<==<=*a*, another one is in the point *x*2<==<=*b*. Each of the friends can move by one along the line in any direction unlimited number of times. When a friend moves, the tiredness of a friend changes acco...
```python import math a=int(input()) b=int(input()) diff=abs(a-b) if diff==1: print(1) elif diff==2: print(2) else: x=math.ceil(diff/2) y=diff-x s1=0 s2=0 print(x,y) for i in range(x+1): s1+=i for j in range(y+1): s2+=j print(s1+s2) ```
MatrixStudio/Codeforces-Python-Submissions
You are developing a new feature for the website which sells airline tickets: being able to sort tickets by price! You have already extracted the tickets' prices, so there's just the last step to be done... You are given an array of integers. Sort it in non-descending order.
```python arr = list(map(int, input().split())) sz = arr[0] arr = sorted(arr[1:]) for it in arr: print(it, end=' ') print() for i in range(10000000): a = 2 * 2 * 2 ```
MatrixStudio/Codeforces-Python-Submissions
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are *n* watchmen on a plane, the *i*-th watchman is located at point (*x**i*,<=*y**i*). They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manha...
```python lst = [[1.5,1.5]] cnt = 0 for i in range(int(input())): x,y = map(int,input().split()) for j in lst: if x==j[0] or y==j[1]: cnt += 1 lst.append([x,y]) print(cnt) ```
MatrixStudio/Codeforces-Python-Submissions
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation. The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe...
```python sentence = input() splited = sentence.split("+") splited.sort() result_str = "" for i in range(len(splited)): result_str += f"{splited[i]}+" print(result_str[:-1]) ```
MatrixStudio/Codeforces-Python-Submissions
Olesya loves numbers consisting of *n* digits, and Rodion only likes numbers that are divisible by *t*. Find some number that satisfies both of them. Your task is: given the *n* and *t* print an integer strictly larger than zero consisting of *n* digits that is divisible by *t*. If such number doesn't exist, print <=-...
```python x,y=(map(int,input().split())) if x==1 and y==10: print(-1) elif x>=2 and y ==10: for i in range((x)): print('1',end="") print(0) else: for i in range((x)): print(y,end="") ```
MatrixStudio/Codeforces-Python-Submissions
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
```python def check(): word = input() if len(word) > 10: word = word[0] + str(len(word) - 2) + word[len(word)-1] return word n = int(input()) a = [] for _ in range(n): a.append(check()) print("\n".join(a)) ```
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 s = input.split()[1] while '01' in s or '10' in s: if '01' in s: i = s.index('01') else: i = s.index('10') s = s[:i] + s[i+2:] print(len(s)) ```
MatrixStudio/Codeforces-Python-Submissions
You've got a 5<=×<=5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix: 1....
```python array = [] for j in range(5): x = [int(i)for i in input().split()] array.append(x) for x in range(5): for y in range(5): if array[x][y] == 1: print(abs(x - 2) + abs(y - 2)) ```
MatrixStudio/Codeforces-Python-Submissions
Mike and some bears are playing a game just for fun. Mike is the judge. All bears except Mike are standing in an *n*<=×<=*m* grid, there's exactly one bear in each cell. We denote the bear standing in column number *j* of row number *i* by (*i*,<=*j*). Mike's hands are on his ears (since he's the judge) and each bear s...
```python import re def maxString(a,n): y = 0 for i in range(n): s2 = ''.join(a[i]) if '1' not in s2: r = 0 else: r = len(max(re.findall("1+",s2),key=len)) if(r > y): y = r return y def flip(x): if(x == '1'): return '0' else: return '1' n,m,q = map(int,input().split()) a = [] x = [] for i...
MatrixStudio/Codeforces-Python-Submissions
Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock. The combination lock is represented by *n* rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has to turn ...
```python n = input() start_pos = input() open_pos = input() counter = 0 for i, j in zip(start_pos, open_pos): i, j = int(i), int(j) count_pos = 0 if i == j: continue elif i < j: while i < j: i += 1 count_pos += 1 else: while i > j: ...
MatrixStudio/Codeforces-Python-Submissions
Let us define two functions *f* and *g* on positive integer numbers. You need to process *Q* queries. In each query, you will be given three integers *l*, *r* and *k*. You need to print the number of integers *x* between *l* and *r* inclusive, such that *g*(*x*)<==<=*k*.
```python def muli(n): x = 1 for i in range(len(n)): if(n[i]=='0'): continue x = x*(int(n[i])) return (x) n = int(input()) for i in range(n): l,r,k = input().split(" ") count = 0 for j in range(int(l),int(r)+1): x = j while(x...
MatrixStudio/Codeforces-Python-Submissions
Today on a math lesson the teacher told Vovochka that the Euler function of a positive integer φ(*n*) is an arithmetic function that counts the positive integers less than or equal to n that are relatively prime to n. The number 1 is coprime to all the positive integers and φ(1)<==<=1. Now the teacher gave Vovochka an...
```python print("_RANDOM_GUESS_1689429994.5419617")# 1689429994.5419815 ```
MatrixStudio/Codeforces-Python-Submissions
People in the Tomskaya region like magic formulas very much. You can see some of them below. Imagine you are given a sequence of positive integer numbers *p*1, *p*2, ..., *p**n*. Lets write down some magic formulas: Here, "mod" means the operation of taking the residue after dividing. The expression means applying ...
```python n=int(input()) L=list(map(int,input().split())) Q=0 X=[0]*1000001 for i in range(1,1000001): X[i]=X[i-1]^i for i in range(1,n+1): Q^=L[i-1] x=n%i y=n//i if(y%2==1): Q^=X[i-1] Q^=X[x] print(Q) ```
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 lang1=input() lang2=input() def reverse(st): i=0 j=len(st)-1 st=list(st) while(i<j): st[i],st[j]=st[j],st[i] i+=1 j-=1 return ''.join(x for x in st) if(str(lang1)==str(reverse(lang2))): print('YES') else: print('NO') ```
MatrixStudio/Codeforces-Python-Submissions
Given an array *a*1,<=*a*2,<=...,<=*a**n* of *n* integers, find the largest number in the array that is not a perfect square. A number *x* is said to be a perfect square if there exists an integer *y* such that *x*<==<=*y*2.
```python import math n = input() a = list(map(int,input().split())) a = sorted(a,reverse=True) for i in a: if i >0: if math.sqrt(i)**2 != i: print(i) break else: print(i) break ```
MatrixStudio/Codeforces-Python-Submissions
Sereja has an *n*<=×<=*m* rectangular table *a*, each cell of the table contains a zero or a number one. Sereja wants his table to meet the following requirement: each connected component of the same values forms a rectangle with sides parallel to the sides of the table. Rectangles should be filled with cells, that is,...
```python # Idea is that all rows are either A or B where A flipped = B (same is true for columns) # # Thus, either n and m <= k and since max value of k == 10, we can just brute force all A # # Or, n or m > k. WLOG say m <= n. # Then, if A/B is not one of the existing rows, the number of flips to change each row ...
MatrixStudio/Codeforces-Python-Submissions
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
```python # your code goes here test = int(input()) for i in range(test): n = input() l = len(n) if(int(l)>10): print(n[0]+str(l-2)+n[l-1]) else: print(n) ```
MatrixStudio/Codeforces-Python-Submissions
One beautiful July morning a terrible thing happened in Mainframe: a mean virus Megabyte somehow got access to the memory of his not less mean sister Hexadecimal. He loaded there a huge amount of *n* different natural numbers from 1 to *n* to obtain total control over her energy. But his plan failed. The reason for th...
```python def main(): n = int(input()) ans = 0 for i in range(1, 2**10-1): x = int(''.join(list(bin(i))[2:])) if x <= n: ans += 1 else: break print(ans) main() ```
MatrixStudio/Codeforces-Python-Submissions
Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited *n* his friends there. If...
```python n=int(input()) gift=list(map9int,input().split())) res=[0]*n for i in range(n): res[gift[i]-1]=i+1 print(*res) ```
MatrixStudio/Codeforces-Python-Submissions
You are given array consisting of *n* integers. Your task is to find the maximum length of an increasing subarray of the given array. A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray strictly greater than previous.
```python n=int(input()) a=list(map(int,input().split())) if n==1: print(1) else: l=[] c=0 for i in range(n-1): if a[i]<a[i+1]: c+=1 else: c+=1 l.append(c) c=0 if a[-1]>a[-2]: c+=1 l.append(c) print(max(...
MatrixStudio/Codeforces-Python-Submissions
Valera has got *n* domino pieces in a row. Each piece consists of two halves — the upper one and the lower one. Each of the halves contains a number from 1 to 6. Valera loves even integers very much, so he wants the sum of the numbers on the upper halves and the sum of the numbers on the lower halves to be even. To do...
```python odd1=0 odd2=0 for _ in range(int(input())): a,b=map(int,input().split()) if a%2!=0: odd1+=1 if b%2!=0: odd2+=1 if odd1%2==0 and odd2%2==0: print(0) elif odd1%2!=0 and odd2%2!=0: print(1) else: print(-1) ```
MatrixStudio/Codeforces-Python-Submissions
When new students come to the Specialized Educational and Scientific Centre (SESC) they need to start many things from the beginning. Sometimes the teachers say (not always unfairly) that we cannot even count. So our teachers decided to teach us arithmetics from the start. And what is the best way to teach students add...
```python #||+|=||||| a = input() list2 = list(a) b = int(len(list2)) if b/2 != int(b/2): print('Impossible') else: for i in range(b): list2[i] = '|' list2[int(b/2)] = '=' list2[1] = '+' for i in range(b): print(list2[i],end = '') ```
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 s = str(input()) want_string = 'hello' cnt = len(want_string) li = [] cnt2 = 0 for i in s: if i == want_string[cnt2]: cnt2 += 1 cnt -= 1 if cnt == 0: print('YES') else: print('NO') ```
MatrixStudio/Codeforces-Python-Submissions
Eighth-grader Vova is on duty today in the class. After classes, he went into the office to wash the board, and found on it the number *n*. He asked what is this number and the teacher of mathematics Inna Petrovna answered Vova that *n* is the answer to the arithmetic task for first-graders. In the textbook, a certain ...
```python a=input() a=int(a) count=0 total=0 result=[] for x in range(a): count=0 for y in str(x): count+=int(y) if(count+x==a): total+=1 result.append(x) print(total) for z in result: print(z) ```
MatrixStudio/Codeforces-Python-Submissions
Holidays have finished. Thanks to the help of the hacker Leha, Noora managed to enter the university of her dreams which is located in a town Pavlopolis. It's well known that universities provide students with dormitory for the period of university studies. Consequently Noora had to leave Vičkopolis and move to Pavlopo...
```python def fact(n): if n <= 1: return 1 else: return n*fact(n-1) a, b = map(int, input().split()) print(fact(min(a, b))) ```
MatrixStudio/Codeforces-Python-Submissions
Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yy...
```python class solve: def __init__(self): s=input() n=len(s) ans="" for i in range(n): if ans=="" or ans[-1]!=s[i]: ans+=s[i] l+=1 else: ans[-1]=0 final="" for i in ans: ...
MatrixStudio/Codeforces-Python-Submissions
One day shooshuns found a sequence of *n* integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: 1. Find the number that goes *k*-th in the current sequence and add the same number to the end of the sequence; 1. Delete the first number of the current ...
```python n, k = map(int,input().split()) l = [int(i) for i in input().split()] if len(set(l[k-1:n])) != 1: print(-1) else: last=l[-1] ans=-1 for i in range(n): if l[i] !=last: ans=i print(ans+1) ```
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 line1 = list(map(str, input().strip())) line2 = list(map(str, input().strip())) line3 = list(map(str, input().strip())) line3.sort() line = line1+line2 line.sort() if line == line3: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Little Bolek has found a picture with *n* mountain peaks painted on it. The *n* painted peaks are represented by a non-closed polyline, consisting of 2*n* segments. The segments go through 2*n*<=+<=1 points with coordinates (1,<=*y*1), (2,<=*y*2), ..., (2*n*<=+<=1,<=*y*2*n*<=+<=1), with the *i*-th segment connecting th...
```python n,k=map(int,input().split()) r=list(map(int,input().split())) c=0 for i in range(len(r)//2): if c==k: break elif r[(2*i)]<r[(2*i)+1]-1>r[(2*i)+2]: r[(2*i)+1]=r[(2*i)+1]-1 c=c+1 print(*r) ...
MatrixStudio/Codeforces-Python-Submissions
Roma (a popular Russian name that means 'Roman') loves the Little Lvov Elephant's lucky numbers. Let us remind you that lucky numbers are positive integers whose decimal representation only contains lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Roma's got *n* positive integer...
```python # # RED CODER # # n, k = map(int, input().split()) x = list(map(str, input().split()))[:n] count = 0 for i in range(n): if len(x[i]) <= k: count += 1 print(count) ```
MatrixStudio/Codeforces-Python-Submissions
Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw. The first player wrote number *a*, the second player wrote number *b*. How many w...
```python num_1, num_2 = map(int, input().split()) num_3, num_4, num_5 = 0, 0, 0 for i in range(1, 6 + 1): if abs(num_1 - i) < abs(num_2 - i): num_3 += 1 elif abs(num_1 - i) == abs(num_2 - i): num_4 += 1 elif abs(num_1 - i) > abs(num_2 - i): num_5 += 1 print(num_3, num_4, nu...
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 nh,totl,finl=[int(i) for i in input().split()] l=[int(i) for i in input().split()] count=0 fl=0 newl=l[1:] k=0 summ=l[0]+sum(newl) newl=sorted(newl,reverse=True) while(True): ans=(totl*l[0])/summ if(ans>=finl): break else: summ=summ-newl[k] count+=1 k+=1 print...
MatrixStudio/Codeforces-Python-Submissions
Jafar has *n* cans of cola. Each can is described by two integers: remaining volume of cola *a**i* and can's capacity *b**i* (*a**i* <=≤<= *b**i*). Jafar has decided to pour all remaining cola into just 2 cans, determine if he can do this or not!
```python n=int(input()) a=list(map(int,input().split())) b=list(map(int,input().split())) x=sum(a) y=max(b) b.remove(y) z=max(b) if y+z<x: print('NO') else: print('YES') ```
MatrixStudio/Codeforces-Python-Submissions
Bessie the cow and her best friend Elsie each received a sliding puzzle on Pi Day. Their puzzles consist of a 2<=×<=2 grid and three tiles labeled 'A', 'B', and 'C'. The three tiles sit on top of the grid, leaving one grid cell empty. To make a move, Bessie or Elsie can slide a tile adjacent to the empty cell into the ...
```python s=input() g=input() w=input() q=input() if s[0]=='X': S1=s[1]+g[1]+g[0] elif s[1]=='X': S1=g[1]+g[0]+s[0] elif g[1]=='X': S1=g[0]+s[0]+s[1] else: S1=s+g[1] if w[0]=='X': S2=w[1]+q[1]+q[0] elif w[1]=='X': S2=q[1]+q[0]+w[0] elif q[1]=='X': S2=q[0]+q[0]+w[1] else: S2=w+q[1] if S1==S2 ...
MatrixStudio/Codeforces-Python-Submissions
If you have ever interacted with a cat, you have probably noticed that they are quite particular about how to pet them. Here is an approximate map of a normal cat. However, some cats won't tolerate this nonsense from the humans. Here is a map of a grumpy cat. You have met a cat. Can you figure out whether it's normal...
```python import sys t = True s = ["great","don't think so", "don't touch me","not bad", "cool"] for i in range(10): print(i,flush=True) sys.stdout.flush() t = input() if t in s: print("normal",flush=True) t = False break if t: print("grumpy",flush=True) ```
MatrixStudio/Codeforces-Python-Submissions
After finishing eating her bun, Alyona came up with two integers *n* and *m*. She decided to write down two columns of integers — the first column containing integers from 1 to *n* and the second containing integers from 1 to *m*. Now the girl wants to count how many pairs of integers she can choose, one from the first...
```python f = int(input("")) s = int(input("")) total =0 first = f second = s for step in range(5,f+s+1,5): first =1 while first <= f: if step - first <= 0: break elif step - first <= s: total +=1 first +=1 print (total) ```
MatrixStudio/Codeforces-Python-Submissions
Limak is a grizzly bear who desires power and adoration. He wants to win in upcoming elections and rule over the Bearland. There are *n* candidates, including Limak. We know how many citizens are going to vote for each candidate. Now *i*-th candidate would get *a**i* votes. Limak is candidate number 1. To win in elect...
```python candidates = int(input()) votes = [int(x) for x in input().split(' ')] k = votes[0] maxi = max(votes) changed = 0 while k <= maxi: changed += 1 maxi -= 1 k += 1 print(changed) ```
MatrixStudio/Codeforces-Python-Submissions
One day, the Grasshopper was jumping on the lawn and found a piece of paper with a string. Grasshopper became interested what is the minimum jump ability he should have in order to be able to reach the far end of the string, jumping only on vowels of the English alphabet. Jump ability is the maximum possible length of ...
```python s=input() Vowels = ['A','E','I','O','U','Y'] length = len(s) pos=[-1] pos_len=0 for i in range(length): if s[i] in Vowels: pos.append(i+1) pos_len+=1 if (pos_len>1): MinL=max(MinL,pos[pos_len]-pos[pos_len-1]) else : MinL=i+1; #print(MinL...
MatrixStudio/Codeforces-Python-Submissions
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network. Bu...
```python nom = set(map(str,input())) n = len(nom) if(n%2==0): print("CHAT WITH HER!") else: print("IGNORE HIM!") ```
MatrixStudio/Codeforces-Python-Submissions
Polycarp has interviewed Oleg and has written the interview down without punctuation marks and spaces to save time. Thus, the interview is now a string *s* consisting of *n* lowercase English letters. There is a filler word ogo in Oleg's speech. All words that can be obtained from ogo by adding go several times to the...
```python def main(): n = int(input()) a = input() i = 0 while i <= n - 1: if a[i] != 'o': print(a[i], end = '') i += 1 elif i < n - 2: if a[i + 1] == 'g' and a[i + 2] == 'o': i += 3 while i < n - 1: ...
MatrixStudio/Codeforces-Python-Submissions
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that. For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two ...
```python n = int(input()) def compite(x): total = 0 for j in range(1,x+1): if x % j == 0: total += 1 if total > 2: return x break else: total = total return total total1 = [] if n % 2 == 0: ...
MatrixStudio/Codeforces-Python-Submissions
One fine October day a mathematics teacher Vasily Petrov went to a class and saw there *n* pupils who sat at the desks, two people at each desk. Vasily quickly realized that number *n* is even. Like all true mathematicians, Vasily has all students numbered from 1 to *n*. But Vasily Petrov did not like the way the chi...
```python #include<stdio.h> #include<stdlib.h> #include<string.h> char st[110]; int i,l; int main() { freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); scanf("%d",&l); scanf("%s",st+1); for(i=1;i<=l/2;i++) { if(st[i]=='L') { printf("%d %d\n",i,i+l/2); } if(st[i]=='R') { printf(...
MatrixStudio/Codeforces-Python-Submissions
According to an old legeng, a long time ago Ankh-Morpork residents did something wrong to miss Fortune, and she cursed them. She said that at some time *n* snacks of distinct sizes will fall on the city, and the residents should build a Snacktower of them by placing snacks one on another. Of course, big snacks should b...
```python m=int(input()) list1=list(map(int,input().split(' '))) list2=list() list3=list1.copy() for i in range(len(list1)): _max=max(list3) list2.append(list1[i]) list3.remove(list1[i]) if(list1[i]== _max): list2.sort(reverse=True) for x in list2: print(f'{x} ',en...
MatrixStudio/Codeforces-Python-Submissions
The only king stands on the standard chess board. You are given his position in format "cd", where *c* is the column from 'a' to 'h' and *d* is the row from '1' to '8'. Find the number of moves permitted for the king. Check the king's moves here [https://en.wikipedia.org/wiki/King_(chess)](https://en.wikipedia.org/wik...
```python pos_king= input() col= pos_king[0] fil= int(pos_king[1]) moves=0 if fil==8 or fil==1: if col=="a" or col=="h": moves=3 else: moves=5 elif 1<fil<8: if col=="a" or col=="h": moves=5 else: moves=8 print(moves) ```
MatrixStudio/Codeforces-Python-Submissions
The map of Berland is a rectangle of the size *n*<=×<=*m*, which consists of cells of size 1<=×<=1. Each cell is either land or water. The map is surrounded by the ocean. Lakes are the maximal regions of water cells, connected by sides, which are not connected with the ocean. Formally, lake is a set of water cells, s...
```python n, m, k = map(int, input().split()) mp = [list(input().strip()) for _ in range(n)] w = {(r,c) for r,row in enumerate(mp) for c,cell in enumerate(row) if cell=="."} lakes = [] while w: lake = set() q = [w.pop()] while q: r,c = q.pop() if (r,c) in lake: continue...
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 find(p): if id[p] == p: return p else: id[p] = find(id[p]); return id[p] def union(u,v): u = find(u) v = find(v) if u == v: return if size[u] > size[v]: u,v=v,u id[u] = v size[v] += size[u] ...
MatrixStudio/Codeforces-Python-Submissions
Very soon there will be a parade of victory over alien invaders in Berland. Unfortunately, all soldiers died in the war and now the army consists of entirely new recruits, many of whom do not even know from which leg they should begin to march. The civilian population also poorly understands from which leg recruits beg...
```python n=int(input()) a=[] b=[] for i in range(n): l,r=map(int,input().split()) a.append((l,r)) b.append((l,r)) a.sort(key=lambda x:(x[0],x[1])) s1=0 s2=0 s3=0 s4=0 for i in range(n): s1=s1+a[i][0] s2=s2+a[i][1] y1=abs(s1-s2) z1=a[n-1][0] z2=a[n-1][1] x=abs(a[n-1][0]-a[n-1][1]) for i in range...
MatrixStudio/Codeforces-Python-Submissions
Manao is trying to open a rather challenging lock. The lock has *n* buttons on it and to open it, you should press the buttons in a certain order to open the lock. When you push some button, it either stays pressed into the lock (that means that you've guessed correctly and pushed the button that goes next in the seque...
```python n = int(input()) print(n*(n*n+5)//6) ```
MatrixStudio/Codeforces-Python-Submissions
You can find anything whatsoever in our Galaxy! A cubical planet goes round an icosahedral star. Let us introduce a system of axes so that the edges of the cubical planet are parallel to the coordinate axes and two opposite vertices lay in the points (0,<=0,<=0) and (1,<=1,<=1). Two flies live on the planet. At the mom...
```python # LUOGU_RID: 128753035 a,b,c=map(int,input().split()) d,e,f=map(int,input().split()) if ((a==d) or (b==e) or (c==f)): print('YES') else: print('NO') ```
MatrixStudio/Codeforces-Python-Submissions
Tavak and Seyyed are good friends. Seyyed is very funny and he told Tavak to solve the following problem instead of longest-path. You are given *l* and *r*. For all integers from *l* to *r*, inclusive, we wrote down all of their integer divisors except 1. Find the integer that we wrote down the maximum number of times...
```python from math import sqrt nums = input() esp = nums.find(' ') n1 = int(nums[0:esp]) n2 = int(nums[esp+1:]) vzs = [0,0,0,0,0] def incrementa(i): if(i==2): vzs[0]+=1 elif(i==3): vzs[1]+=1 elif(i==5): vzs[2]+=1 elif(i==7): vzs[3]+=1 else: vzs[4]+=1 ...