source
stringclasses
3 values
instruction
stringlengths
23
3.97k
input
stringclasses
1 value
output
stringlengths
1
3.75k
MatrixStudio/Codeforces-Python-Submissions
Vasily the bear has a favorite rectangle, it has one vertex at point (0,<=0), and the opposite vertex at point (*x*,<=*y*). Of course, the sides of Vasya's favorite rectangle are parallel to the coordinate axes. Vasya also loves triangles, if the triangles have one vertex at point *B*<==<=(0,<=0). That's why today he...
```python # coding: utf-8 x, y = [int(i) for i in input().split()] length = abs(x)+abs(y) ans = [] if x < 0: ans.append([-length,0]) else: ans.append([length,0]) if y < 0: ans.append([0,-length]) else: ans.append([0,length]) ans.sort() print(ans[0][0],ans[0][1],ans[1][0],ans[1][1]) ```
MatrixStudio/Codeforces-Python-Submissions
DZY loves chessboard, and he enjoys playing with it. He has a chessboard of *n* rows and *m* columns. Some cells of the chessboard are bad, others are good. For every good cell, DZY wants to put a chessman on it. Each chessman is either white or black. After putting all chessmen, DZY wants that no two chessmen with th...
```python values = input().split() rows = int(values[0]) cols = int(values[1]) chessboard = [] for i in range(rows): row = [] for j in range(cols): if i % 2 == 0: if j % 2 == 0: row.append('B') else: row.append('W') else: ...
MatrixStudio/Codeforces-Python-Submissions
Little boy Valera studies an algorithm of sorting an integer array. After studying the theory, he went on to the practical tasks. As a result, he wrote a program that sorts an array of *n* integers *a*1,<=*a*2,<=...,<=*a**n* in the non-decreasing order. The pseudocode of the program, written by Valera, is given below. ...
```python n = int(input()) if n < 3: print(-1) else: print(2, 2, *([1] * (n-2))) ```
MatrixStudio/Codeforces-Python-Submissions
You're given a string of lower-case Latin letters. Your task is to find the length of its longest substring that can be met in the string at least twice. These occurrences can overlap (see sample test 2).
```python s=input() o=len(s) k=0 for i in range(o): r={0} for j in range(o-i+1): if s[j:j+i] in r:k=max(i,k) else:r.add(s[j:j+i]) print(k) ```
MatrixStudio/Codeforces-Python-Submissions
While Mike was walking in the subway, all the stuff in his back-bag dropped on the ground. There were several fax messages among them. He concatenated these strings in some order and now he has string *s*. He is not sure if this is his own back-bag or someone else's. He remembered that there were exactly *k* messages ...
```python tar = input() k = int(input()) n = len(tar) all = [] ans = True for i in range(0,k): all.append(tar[int(i*n/k):int((i+1)*(n/k))]) # print(all[i]) x = int(n/k/2) # print(all[i][0:x]) # print(all[i][x:x*2][::-1]) ans &= (all[i][0:x] == all[i][x:x*2][::-1]) if ans: print("YES") else: print...
MatrixStudio/Codeforces-Python-Submissions
You will receive 3 points for solving this problem. Manao is designing the genetic code for a new type of algae to efficiently produce fuel. Specifically, Manao is focusing on a stretch of DNA that encodes one protein. The stretch of DNA is represented by a string containing only the characters 'A', 'T', 'G' and 'C'. ...
```python s=input() l=len(s) ans=0 i=0 while i<l: j=i+1 while j<l and s[j]==s[i]:j+=1 if j-i&1==0:ans+=1 i=j print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Bob has a permutation of integers from 1 to *n*. Denote this permutation as *p*. The *i*-th element of *p* will be denoted as *p**i*. For all pairs of distinct integers *i*,<=*j* between 1 and *n*, he wrote the number *a**i*,<=*j*<==<=*min*(*p**i*,<=*p**j*). He writes *a**i*,<=*i*<==<=0 for all integer *i* from 1 to *n...
```python n=int(input()) X=[] Y=[] for i in range(n): x=int(input()) y=int(input()) X.append(x) Y.append(y) d=(x-X[0])**2+(y-Y[0])**2 j=0 for i in range(1,n): if (x-X[i])**2+(y-Y[i])**2<d: d=(x-X[i])**2+(y-Y[i])**2 j=i if j!=0: d1=(X[j]-X[0])**2+(Y[j]-Y[0])**2 ...
MatrixStudio/Codeforces-Python-Submissions
Bachgold problem is very easy to formulate. Given a positive integer *n* represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1. Recall that integer *k* is called prime if it is greater than 1 and has exactly two positive integer ...
```python n = int(input()) if n % 2 == 0: ans = n // 2 res = [2] * ans else: ans = (n-3) // 2 res = [2] * ans + [3] print(ans+1) print(*res) ```
MatrixStudio/Codeforces-Python-Submissions
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given *n* numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given *n* numbers finds one that i...
```python n=int(input()) a=list(map(int,input().split())) e=0 o=0 c=0 if(a[0]%2==0): e=1 else: o=1 if(a[1]%2==0): if(e==0): if(a[2]%2==0): print(1) else: print(2) if(e==1): c=1 else: if(o==0): if(a[2]%2!=0): prin...
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 even, odd = 0, 0 z = int(input()) a = list(map(int,input().split())) b = [] for i in range(z): if a[i] % 2 == 0: even += 1 b.append('0') else: odd += 1 b.append('1') print(b.index('1' if even > odd else '0') + 1) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya has a non-negative integer *n*. He wants to round it to nearest integer, which ends up with 0. If *n* already ends up with 0, Vasya considers it already rounded. For example, if *n*<==<=4722 answer is 4720. If *n*<==<=5 Vasya can round it to 0 or to 10. Both ways are correct. For given *n* find out to which int...
```python n=int(input()) a=n%10 if a<=5: print(n-a) else: print(n+(10-a)) ```
MatrixStudio/Codeforces-Python-Submissions
In mathematics, the Pythagorean theorem — is a relation in Euclidean geometry among the three sides of a right-angled triangle. In terms of areas, it states: In any right-angled triangle, the area of the square whose side is the hypotenuse (the side opposite the right angle) is equal to the sum of the areas of the s...
```python from math import ceil,sqrt n=int(input()) amt=0 for a in range(1,n+1): for b in range(a,n+1): if (sqrt(a**2+b**2))==ceil((sqrt(a**2+b**2))) and (sqrt(a**2+b**2))<=n: amt+=1 print(amt) ```
MatrixStudio/Codeforces-Python-Submissions
A big company decided to launch a new series of rectangular displays, and decided that the display must have exactly *n* pixels. Your task is to determine the size of the rectangular display — the number of lines (rows) of pixels *a* and the number of columns of pixels *b*, so that: - there are exactly *n* pixels o...
```python n=int(input()) dmin=100000000 a=0 b=0 for i in range(1,n+1,1): for k in range(1,n+1,1): j=k #print(i,j,sep=" ") if i*j==n: #print(i,j,sep=" ") if i<=j: #print(i,j,sep=" ") minn=j-i if minn<dmin: #print(i,j,sep=" ") dmin=minn a=i b=j bre...
MatrixStudio/Codeforces-Python-Submissions
Jack is working on his jumping skills recently. Currently he's located at point zero of the number line. He would like to get to the point *x*. In order to train, he has decided that he'll first jump by only one unit, and each subsequent jump will be exactly one longer than the previous one. He can go either left or ri...
```python x = int(input("sayı girin: ")) x_now = 0 step_num = 0 step_size = 1 while x_now != x: if x > x_now: if x_now + step_size > x: x_now -= step_size else: x_now += step_size else: if x_now - step_size < x: x_now += step_size ...
MatrixStudio/Codeforces-Python-Submissions
There are three friend living on the straight line *Ox* in Lineland. The first friend lives at the point *x*1, the second friend lives at the point *x*2, and the third friend lives at the point *x*3. They plan to celebrate the New Year together, so they need to meet at one point. What is the minimum total distance they...
```python input_str = input("Enter space-separated integers: ") input_list = list(map(int, input_str.split())) max_value = max(input_list) min_value = min(input_list) difference = max_value - min_value print("The difference between the maximum and minimum values is:", difference) ``...
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 = map(int, input().split()) print(m * (n - (n%2))//2 + (n%2) * m//2) ```
MatrixStudio/Codeforces-Python-Submissions
Iahub got bored, so he invented a game to be played on paper. He writes *n* integers *a*1,<=*a*2,<=...,<=*a**n*. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices *i* and *j* (1<=≤<=*i*<=≤<=*j*<=≤<=*n*) and flips all values *a**k* for which their positions are in...
```python n = int(input()) lis = list(map(int, input().split())) cnt = 0 mx = 0 mxx = 0 for i in lis: if i == 1: cnt += 1 if mx: mx -= 1 else: mx += 1 mxx = max(mx, mxx) print(cnt + mxx) ```
MatrixStudio/Codeforces-Python-Submissions
This task is very simple. Given a string *S* of length *n* and *q* queries each query is on the format *i* *j* *k* which means sort the substring consisting of the characters from *i* to *j* in non-decreasing order if *k*<==<=1 or in non-increasing order if *k*<==<=0. Output the final string after applying the queries...
```python strLength, n = list(map(int, input().split())) inputString = input() for i in range(n): start, end, method = list(map(int, input().split())) firstPart = inputString[:start - 1] lastPart = inputString[end:] mainPart = inputString[start -1: end] if method == 1: reverseOrder = 0 else: rev...
MatrixStudio/Codeforces-Python-Submissions
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth. Now Diamond has given Bort a string consisting of only uppercase English letters of length *n*. There is a great number of "QAQ" in the string (Diamond is so cute!). Bort wants to know how many subsequences "QAQ" are...
```python s = input() c = 0 first_q_count = 0 last_q_count = s.count("Q") for i in range(len(s)): char = s[i] if char == "Q": first_q_count += 1 last_q_count -= 1 if char == "A": c += first_q_count * last_q_count print(c) ```
MatrixStudio/Codeforces-Python-Submissions
What joy! Petya's parents went on a business trip for the whole year and the playful kid is left all by himself. Petya got absolutely happy. He jumped on the bed and threw pillows all day long, until... Today Petya opened the cupboard and found a scary note there. His parents had left him with duties: he should water...
```python length = int(input()) month = list(map(int, input().split())) month.sort(reverse=True) big = month[0] days = 1 if length == 0: print(0) exit() for i in range(1, 12): if big >= length: break else: big += month[i] days += 1 if big >= length: print(d...
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 def isPerfect(num): cnt = 0 for i in range(2,num): if num%i==0: cnt += 1 if cnt%2==0: return False else: return True n = int(input()) data = list(map(int, input().split())) data.sort(reverse=True) for num in data: if not isPerfect(num): ...
MatrixStudio/Codeforces-Python-Submissions
Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be. ...
```python p = input() tec = input() res = {} fudeu = 0 for i in range(len(p)): if p[i] != tec[i]: if p[i] in res: if res[p[i]] != tec[i]: fudeu=1 elif tec[i] in res: if res[tec[i]] != p[i]: fudeu = 1 else: res[p[i]] = tec[i] if fudeu == 0: print(len(res)) for i in res: print(i,res[i]) ...
MatrixStudio/Codeforces-Python-Submissions
You are given *n* segments on the Ox-axis. You can drive a nail in any integer point on the Ox-axis line nail so, that all segments containing this point, are considered nailed down. If the nail passes through endpoint of some segment, this segment is considered to be nailed too. What is the smallest number of nails ne...
```python n=int(input()) c=[] for i in range(n): x,y=map(int,input().split()) if x>y: x,y=y,x c.append([x,0,i]) c.append([y,1,i]) c.sort() ans=0 stack=[] b=[] for z in c: if z[1]==0: stack.append(z[2]) else: if z[2] in stack: ans+=1 b.appe...
MatrixStudio/Codeforces-Python-Submissions
Cucumber boy is fan of Kyubeat, a famous music game. Kyubeat has 16 panels for playing arranged in 4<=×<=4 table. When a panel lights up, he has to press that panel. Each panel has a timing to press (the preffered time when a player should press it), and Cucumber boy is able to press at most *k* panels in a time with...
```python k = int(input()) d={} t=[] for i in range(10): d[i]=0 for i in range(4): arr=input() t.append(arr) for i in range(4): for j in range(4): if t[i][j]==".": continue else: d[int(t[i][j])]+=1 for i in range(9): if d[i]>2*k: print(...
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 def min_changes(s: str) -> int: n = len(s) dp = [0] * (n + 1) for i in range(1, n + 1): if s[i - 1].isupper(): dp[i] = dp[i - 1] else: dp[i] = min(dp[i - 1] + 1, sum(1 for c in s if c.isupper())) return dp[n] s = input().strip() print(min_changes(s)) ...
MatrixStudio/Codeforces-Python-Submissions
Polycarp has created his own training plan to prepare for the programming contests. He will train for $n$ days, all days are numbered from $1$ to $n$, beginning from the first. On the $i$-th day Polycarp will necessarily solve $a_i$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on...
```python n=int(input()) a=list(map(int,input().split())) s=sum(a)/2 ss=0 for i in range(n): ss+=a[i] if(ss>=s): print(i+1) break ```
MatrixStudio/Codeforces-Python-Submissions
Mishka started participating in a programming contest. There are $n$ problems in the contest. Mishka's problem-solving skill is equal to $k$. Mishka arranges all problems from the contest into a list. Because of his weird principles, Mishka only solves problems from one of the ends of the list. Every time, he chooses ...
```python n, k = map(int, input().split()) ls = list(map(int, input().split())) count = 0 while len(ls) > 0: if ls[0] <= k: count+=1 ls.pop(0) else: break while len(ls) > 0: if ls[len(ls)-1] <= k: count+=1 ls.pop(len(ls)-1) else: break print(count) ```
MatrixStudio/Codeforces-Python-Submissions
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips: Vladik is at initial train station, and now *n* people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code *a**i* i...
```python n = int(input()) a = list(map(int,input().split())) dl = dict() dr = dict() for i in range(n): if a[i] not in dl: dl[a[i]] = i dr[a[i]] = i def XOR(l): c = list(set(l)) k = len(c) x = c[0] for i in range(1,k): x ^= c[i] return x from collections impor...
MatrixStudio/Codeforces-Python-Submissions
This problem's actual name, "Lexicographically Largest Palindromic Subsequence" is too long to fit into the page headline. You are given string *s* consisting of lowercase English letters only. Find its lexicographically largest palindromic subsequence. We'll call a non-empty string *s*[*p*1*p*2... *p**k*] = *s**p*1*...
```python s=input() m=max(s) while s.count(max(s))==1: s.remove(max(s)) if s=="": break if s=="": print(m) else: print(max(s)*s.count(max(s))) ```
MatrixStudio/Codeforces-Python-Submissions
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees. A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (*u*,<=*v*) that belongs to the graph, *...
```python import pprint class Bipartite_Graph: def __init__(self): self.graph={ # 1:[2,4,3], # 2:[1,3,5], # 3:[2,4,1], # 4:[5,3,1], # 5:[4,2] } self.vis=set() self.colored={} self.bipartite=True ...
MatrixStudio/Codeforces-Python-Submissions
In a Berland's zoo there is an enclosure with camels. It is known that camels like to spit. Bob watched these interesting animals for the whole day and registered in his notepad where each animal spitted. Now he wants to know if in the zoo there are two camels, which spitted at each other. Help him to solve this task. ...
```python n=int(input()) X=set() XD=set() for i in range(n): x,d=list(map(int,input().split(' '))) X.add(x) XD.add(x+d) if X&XD: print('YES') else: print('NO') ```
MatrixStudio/Codeforces-Python-Submissions
You are given a rectangular cake, represented as an *r*<=×<=*c* grid. Each cell either has an evil strawberry, or is empty. For example, a 3<=×<=4 cake may look as follows: The cakeminator is going to eat the cake! Each time he eats, he chooses a row or a column that does not contain any evil strawberries and contains...
```python r, c = map(int, input().split()) cake = [] for i in range(r): row = input() cake.append(list(row)) row_count = 0 col_count = 0 for i in range(r): has_strawberry = False for j in range(c): if cake[i][j] == 'S': has_strawberry = True break i...
MatrixStudio/Codeforces-Python-Submissions
The nation of Panel holds an annual show called The Number Games, where each district in the nation will be represented by one contestant. The nation has $n$ districts numbered from $1$ to $n$, each district has exactly one path connecting it to every other district. The number of fans of a contestant from district $i...
```python from typing import * V = TypeVar("V") class graph: vertices:List[V] graphDict:Dict[V,Set[V]] def __init__(self,vertices,graphDict): self.vertices = vertices self.graphDict = graphDict for v in vertices: if not v in self.graphDict: self.graphDic...
MatrixStudio/Codeforces-Python-Submissions
A string is called a *k*-string if it can be represented as *k* concatenated copies of some string. For example, the string "aabaabaabaab" is at the same time a 1-string, a 2-string and a 4-string, but it is not a 3-string, a 5-string, or a 6-string and so on. Obviously any string is a 1-string. You are given a string...
```python k = int(input()) visited = {} word = input() for c in word: if not c in visited: visited[c] = 0 visited[c] += 1 result = [] for c in visited: if visited[c] % k == 0: result.append(c * (visited[c] // k)) else: print(-1) exit(0) print(''.join(r...
MatrixStudio/Codeforces-Python-Submissions
You are given two strings $s$ and $t$. In a single move, you can choose any of two strings and delete the first (that is, the leftmost) character. After a move, the length of the string decreases by $1$. You can't choose a string if it is empty. For example: - by applying a move to the string "where", the result is ...
```python a=str(input()) b=str(input()) ff=0 c=0 for l,i in enumerate(a): for f,j in enumerate(b): if(i==j): ia=l ib=f stra=a[ia:] strb=b[ib:] if(stra==strb): ff=ia+ib c=1 break if ...
MatrixStudio/Codeforces-Python-Submissions
Vasya has recently bought some land and decided to surround it with a wooden fence. He went to a company called "Wooden board" that produces wooden boards for fences. Vasya read in the catalog of products that the company has at its disposal *n* different types of wood. The company uses the *i*-th type of wood to prod...
```python mod = int(1e9+7) n, len = map(int, input().split()) a = [0] * n b = [0] * n f = [[[0] * 2 for i in range(len+1)] for j in range(n)] for i in range(n): a[i], b[i] = map(int, input().split()) if a[i] <= len: f[i][a[i]][0] += 1 if a[i] != b[i] and b[i] <= len: f[i][b[i...
MatrixStudio/Codeforces-Python-Submissions
Vasya has got two number: *a* and *b*. However, Vasya finds number *a* too short. So he decided to repeat the operation of lengthening number *a* *n* times. One operation of lengthening a number means adding exactly one digit to the number (in the decimal notation) to the right provided that the resulting number is di...
```python import sys,os,io,time,copy,math from functools import lru_cache if os.path.exists('input.txt'): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') def is_sorted(arr): if all(arr[i]<=arr[i+1] for i in range(len(arr)-1)): return True else: return...
MatrixStudio/Codeforces-Python-Submissions
Once Bob needed to find the second order statistics of a sequence of integer numbers. Lets choose each number from the sequence exactly once and sort them. The value on the second position is the second order statistics of the given sequence. In other words it is the smallest element strictly greater than the minimum. ...
```python i = int(input()) l = [int(x) for x in input().split()] l = sorted(set(l)) if len(l)==1: print('NO') else: print(l[1]) ```
MatrixStudio/Codeforces-Python-Submissions
As technologies develop, manufacturers are making the process of unlocking a phone as user-friendly as possible. To unlock its new phone, Arkady's pet dog Mu-mu has to bark the password once. The phone represents a password as a string of two lowercase English letters. Mu-mu's enemy Kashtanka wants to unlock Mu-mu's p...
```python def solution(): password = input() num_words = int(input()) words = [] for _ in range(num_words): words.append(input()) for x in range(num_words): for y in range(num_words): possible = words[x] + words[y] if password in possible: ...
MatrixStudio/Codeforces-Python-Submissions
Someday, Drazil wanted to go on date with Varda. Drazil and Varda live on Cartesian plane. Drazil's home is located in point (0,<=0) and Varda's home is located in point (*a*,<=*b*). In each step, he can move in a unit distance in horizontal or vertical direction. In other words, from position (*x*,<=*y*) he can go to ...
```python a,b,s =map(int,input().split()) x = abs(a) + abs(b) print("NO" if s<x or (s-x)%2 else "YES") ```
MatrixStudio/Codeforces-Python-Submissions
Vasya has got two number: *a* and *b*. However, Vasya finds number *a* too short. So he decided to repeat the operation of lengthening number *a* *n* times. One operation of lengthening a number means adding exactly one digit to the number (in the decimal notation) to the right provided that the resulting number is di...
```python a,b,n=map(int,input().split()) k=True v=str(a) for i in range(n): c=-1 for j in range(9,-1,-1): if int(v+str(j))%b==0: c=j break if c==-1: k=False break else: v+=str(c) if k: print(v) else: print(-1) ```
MatrixStudio/Codeforces-Python-Submissions
You are given *n* points on a plane. All points are different. Find the number of different groups of three points (*A*,<=*B*,<=*C*) such that point *B* is the middle of segment *AC*. The groups of three points are considered unordered, that is, if point *B* is the middle of segment *AC*, then groups (*A*,<=*B*,<=*C...
```python def binser(mas, val): first = 0 last = len(mas) - 1 index = -1 while (first <= last) and (index == -1): mid = (first + last) // 2 if mas[mid] == val: index = mid else: if val < mas[mid]: last = mid - 1 else:...
MatrixStudio/Codeforces-Python-Submissions
Valera is a lazy student. He has *m* clean bowls and *k* clean plates. Valera has made an eating plan for the next *n* days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can...
```python n,m,k=input.split() n=int(n) m=int(m) k=int(k) washed=0 for i in range(n): a=int(input()) if a==1: if m>0: m=m-1 else: washed=washed+1 elif a==2: if k>0: k=k-1 elif k<=0 and m>0: m=m-1 else: washed=...
MatrixStudio/Codeforces-Python-Submissions
In Arcady's garden there grows a peculiar apple-tree that fruits one time per year. Its peculiarity can be explained in following way: there are *n* inflorescences, numbered from 1 to *n*. Inflorescence number 1 is situated near base of tree and any other inflorescence with number *i* (*i*<=&gt;<=1) is situated at the ...
```python from collections import Counter,UserString import sys import threading sys.setrecursionlimit(10000000) try: pass #sys.stdin=open('test','r') except: pass def main(): n=int(input()) a=[0,-1]+list(map(int,input().split())) b=[[] for i in range(n+1)] for i in range(2,n+1)...
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 fr = open('input.txt','r') students = int(fr.readline()) text = fr.readline() print(students) print(text) fw = open("output.txt","w") fw.write("Ay 7AGA") ```
MatrixStudio/Codeforces-Python-Submissions
Kolya is going to make fresh orange juice. He has *n* oranges of sizes *a*1,<=*a*2,<=...,<=*a**n*. Kolya will put them in the juicer in the fixed order, starting with orange of size *a*1, then orange of size *a*2 and so on. To be put in the juicer the orange must have size not exceeding *b*, so if Kolya sees an orange ...
```python a, b, d = map(int, input().split()) arr = list(map(int, input().split())) ans = 0 bin = 0 for n in arr: if n <= b: bin += n if bin > d: ans += 1 bin = 0 print(ans) ```
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 n, k, l, c, d, p, nl, np = list(map(int, input().split())) totML = k * l totLP = c * d toastML = totML // nl totSalt = p // np print(min(toastML, totLP, totSalt) // n) ```
MatrixStudio/Codeforces-Python-Submissions
Mahmoud has *n* line segments, the *i*-th of them has length *a**i*. Ehab challenged him to use exactly 3 line segments to form a non-degenerate triangle. Mahmoud doesn't accept challenges unless he is sure he can win, so he asked you to tell him if he should accept the challenge. Given the lengths of the line segments...
```python #accumalated 2d matrix # listy=[list(accumulate(row)) for row in accumulate([[i for i in list(map(int,input().split()))] for j in range(n)])] import sys input = lambda: sys.stdin.readline().rstrip() x=int(input()) listy=list(map(int,input().split())) listy.sort() check =0 for i in range(0,x-2,3):...
MatrixStudio/Codeforces-Python-Submissions
A group of *n* friends enjoys playing popular video game Toda 2. There is a rating system describing skill level of each player, initially the rating of the *i*-th friend is *r**i*. The friends decided to take part in the championship as a team. But they should have equal ratings to be allowed to compose a single team...
```python # coding=utf-8 """Codeforces 730a solution.""" from operator import itemgetter class CodeforcesTask730ASolution: def __init__(self): self.result = '' self.players = 0 self.rating = [] def read_input(self): self.players = int(input()) self.ratin...
MatrixStudio/Codeforces-Python-Submissions
Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game. Rules of the game are very simple: at first number of rounds *n* is defined....
```python ca,cb = 0,0 t = int(input()) while t!=0: a,b = map(int,input().split()) if a>b: ca = ca + 1 if b>a: cb = cb + 1 t-=1 if ca > cb: print("Mishka") elif cb > ca: print("Chris") else: print("Friendship is magic!^^") ```
MatrixStudio/Codeforces-Python-Submissions
When Petya went to school, he got interested in large numbers and what they were called in ancient times. For instance, he learned that the Russian word "tma" (which now means "too much to be counted") used to stand for a thousand and "tma tmyschaya" (which literally means "the tma of tmas") used to stand for a million...
```python from math import log n = int(input()) l = int(input()) s = int(log(l,n)) y = s+1 if n**s==l: print("YES") print(s-1) elif n**y==l: print("YES") print(y-1) else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Now Fox Ciel becomes a commander of Tree Land. Tree Land, like its name said, has *n* cities connected by *n*<=-<=1 undirected roads, and for any two cities there always exists a path between them. Fox Ciel needs to assign an officer to each city. Each officer has a rank — a letter from 'A' to 'Z'. So there will be 26...
```python Print("I am jocking");;; ```
MatrixStudio/Codeforces-Python-Submissions
Two boys decided to compete in text typing on the site "Key races". During the competition, they have to type a text consisting of *s* characters. The first participant types one character in *v*1 milliseconds and has ping *t*1 milliseconds. The second participant types one character in *v*2 milliseconds and has ping *...
```python x,y,z,w=map(int,input().split()) p=max(x,y,z,w) if (p-x)!=0: print(p-x,end=' ') if (p-y)!=0: print(p-y,end=' ') if (p-z)!=0: print(p-z,end=' ') if (p-w)!=0: print(p-w,end=' ') ```
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 str1="" for i in range(3): str1+=input() if str1==str1[::-1]: print("YES") else: print("NO") ```
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 import sys import math #to read string get_string = lambda: sys.stdin.readline().strip() #to read list of integers get_int_list = lambda: list( map(int,sys.stdin.readline().strip().split()) ) #to read integers get_int = lambda: int(sys.stdin.readline()) #to print fast pt = lambda x: sys.stdout.writ...
MatrixStudio/Codeforces-Python-Submissions
There is a given string *S* consisting of *N* symbols. Your task is to find the number of ordered pairs of integers *i* and *j* such that 1. 1<=≤<=*i*,<=*j*<=≤<=*N* 2. *S*[*i*]<==<=*S*[*j*], that is the *i*-th symbol of string *S* is equal to the *j*-th.
```python s = str(input()) list1 = [] sum = 0 for x in s: if x not in list1: list1.append(x) if s.count(x) > 1: sum += (s.count(x) * s.count(x)) if sum == 0: print(len(s)) else: print(sum) ```
MatrixStudio/Codeforces-Python-Submissions
The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a pla...
```python import sys #from math import gcd #from bisect import bisect_left, bisect_right read_line = lambda: sys.stdin.readline().strip() read_intmap = lambda: map(int, read_line().split()) def testCase(): n = int(input()) players = dict() for ind in range(1, n + 1): name, score = read_line()....
MatrixStudio/Codeforces-Python-Submissions
Greatest common divisor *GCD*(*a*,<=*b*) of two positive integers *a* and *b* is equal to the biggest integer *d* such that both integers *a* and *b* are divisible by *d*. There are many efficient algorithms to find greatest common divisor *GCD*(*a*,<=*b*), for example, Euclid algorithm. Formally, find the biggest in...
```python start , end = list(map(int ,input().split())) def gcd(a, b): if b == 0: return a return gcd(b, a % b) res = start for i in range(start +1 ,end): res = gcd(res, i) print(res) ```
MatrixStudio/Codeforces-Python-Submissions
Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it? The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out...
```python # https://codeforces.com/contest/421/problem/B # 1000 def palin(n,k): for i in range(k//2): if n[i]!=n[k-i-1]: return False return True s=input() l=['A','H','W','I','M','Y','X','O','T','U','V'] if palin(s,len(s)): for i in s: if i not in l: print...
MatrixStudio/Codeforces-Python-Submissions
Polycarpus has a ribbon, its length is *n*. He wants to cut the ribbon in a way that fulfils the following two conditions: - After the cutting each ribbon piece should have length *a*, *b* or *c*. - After the cutting the number of ribbon pieces should be maximum. Help Polycarpus and find the number of ribbon piece...
```python import sys sys.setrecursionlimit(500000000) def f(n): if n in memo.keys(): return memo[n] ans = float("-inf") if n == 0: return 0 for length in l: if n >= length: ans = max(ans, 1 + f(n - length)) memo[n] = ans ...
MatrixStudio/Codeforces-Python-Submissions
There are *n* parliamentarians in Berland. They are numbered with integers from 1 to *n*. It happened that all parliamentarians with odd indices are Democrats and all parliamentarians with even indices are Republicans. New parliament assembly hall is a rectangle consisting of *a*<=×<=*b* chairs — *a* rows of *b* chair...
```python import sys n, a, b = map(int, input().split()) if n > a*b: print(-1) sys.exit(0) par = [] for i in range(1, n+1, b): s = ['0']*b for j in range(b): if i+j <= n: s[j] = str(i+j) par.append(s) while len(par) < a: par.append(['0']*b) for i in range(a): ...
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 a=int(input()) if a%2==0: print('4',a-4) else: print('9',a-9) ```
MatrixStudio/Codeforces-Python-Submissions
Karen is getting ready for a new school day! It is currently hh:mm, given in a 24-hour format. As you know, Karen loves palindromes, and she believes that it is good luck to wake up when the time is a palindrome. What is the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palin...
```python c = [70, 140, 210, 280, 350, 601, 671, 741, 811, 881, 951, 1202, 1272, 1342, 1412, 1440] d = input().split(':') d = int(d[0]) * 60 + int(d[1]) m = 10000 for i in c: if (i - d) >= 0 and (i - d) <= m: m = i - d print(m) ```
MatrixStudio/Codeforces-Python-Submissions
The Elements of Harmony are six supernatural artifacts representing subjective aspects of harmony. They are arguably the most powerful force in Equestria. The inside of Elements of Harmony can be seen as a complete graph with *n* vertices labeled from 0 to *n*<=-<=1, where *n* is a power of two, equal to 2*m*. The ene...
```python def Bit(n) : cnt = 0 while n : if n & 1 : cnt += 1 n >>= 1 return cnt b = []; tmp = input().split(); m = int(tmp[0]); t = int(tmp[1]); kMod = int(tmp[2]); n = 1 << m a = input().split() for i in range(n) : a[i] = int(a[i]) for i in range(n) : b.append(0) v = input().s...
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 def domino_piling(m: int, n: int) -> int: return int((m * n) / 2) if __name__ == '__main__': [m, n] = [int(s) for s in input().split()] print(domino_piling(m, n)) ```
MatrixStudio/Codeforces-Python-Submissions
You've got array *a*[1],<=*a*[2],<=...,<=*a*[*n*], consisting of *n* integers. Count the number of ways to split all the elements of the array into three contiguous parts so that the sum of elements in each part is the same. More formally, you need to find the number of such pairs of indices *i*,<=*j* (2<=≤<=*i*<=≤<=...
```python n = int(input()) arr = [0]*n temp = 0 inp = input().split() for i in range(n): arr[i] = int(inp[i]) temp += arr[i] arr[i] = temp if temp%3 != 0: print(0) exit() first = 0 second = 0 third = 0 if temp == 0: for i in arr: if i == 0: first += 1 ...
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 li = [] n, m = map(int, input().split()) for i in range(n): a, b = map(int, input().split()) li.append([a, b]) li.sort() i = 0 while len(li) != 1 and li[i][1] >= li[i + 1][0]: li[i][1] = max(li[i][1], li[i + 1][1]) del li[i + 1] if len(li) == 0 and m == 0: print("YES") elif len(li) == ...
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 w = input() s = 0 for i in w: s += 1 try: w = int(w) quit() except: if s>=10: print(w[0]+str(s-2)+w[-1]) else:print(w) ```
MatrixStudio/Codeforces-Python-Submissions
A rare article in the Internet is posted without a possibility to comment it. On a Polycarp's website each article has comments feed. Each comment on Polycarp's website is a non-empty string consisting of uppercase and lowercase letters of English alphabet. Comments have tree-like structure, that means each comment ex...
```python def find_depth(line,depth,tree): if(len(tree) < depth): branch = list() tree.append(branch) tree[depth-1].append(line[0]) if(int(line[1]) == 0): if(len(line)>0): return [1,1,line[2:]] else: return [1,1] else: a = list()...
MatrixStudio/Codeforces-Python-Submissions
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them. Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain nu...
```python s = input() ans = s.replace("WUB", " ").strip() #strip removes spaces at the beginning and end of the string print(ans) ```
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()) line = list(map(int, input().split())) i = 0 j = 1 k = 2 if (line[0] % 2 == 0) and (line[1] % 2 == 0): while k < n: if (line[k] % 2 != 0): print(k+1) break k += 1 elif ((line[0] % 2 != 0) or (line[1] % 2 == 0)) or ((line[0] % ...
MatrixStudio/Codeforces-Python-Submissions
Mikhail walks on a 2D plane. He can go either up or right. You are given a sequence of Mikhail's moves. He thinks that this sequence is too long and he wants to make it as short as possible. In the given sequence moving up is described by character U and moving right is described by character R. Mikhail can replace an...
```python 1. y=int(input()) 2. txt=input() 3. n=len(txt) 4. D=['RU','UR'] 5. i=0 6. while i < y-1: 7. if txt[i]+txt[i+1] in D: 8. n=n-1 9. i=i+2 10. else: 11. i=i+1 12. print(n) ```
MatrixStudio/Codeforces-Python-Submissions
Your friend has *n* cards. You know that each card has a lowercase English letter on one side and a digit on the other. Currently, your friend has laid out the cards on a table so only one side of each card is visible. You would like to know if the following statement is true for cards that your friend owns: "If a c...
```python s = input() count = 0 for c in s: if c in "aeiou": count+=1 if c in "13579": count += 1 print(count) ```
MatrixStudio/Codeforces-Python-Submissions
A family consisting of father bear, mother bear and son bear owns three cars. Father bear can climb into the largest car and he likes it. Also, mother bear can climb into the middle car and she likes it. Moreover, son bear can climb into the smallest car and he likes it. It's known that the largest car is strictly larg...
```python pai, mae, filho, maria = [int(x) for x in input().split(' ')] def solve(): if filho > 2*maria or maria > 2*filho or maria >= mae: return -1 if filho > maria: return max(pai, 2*maria + 2), max(mae, 2*maria + 1), filho return max(pai, 2*maria + 2), max(mae, 2*maria ...
MatrixStudio/Codeforces-Python-Submissions
Vanya got an important task — he should enumerate books in the library and label each book with its number. Each of the *n* books should be assigned with a number from 1 to *n*. Naturally, distinct books should be assigned distinct numbers. Vanya wants to know how many digits he will have to write down as he labels th...
```python from sys import stdin, stdout import math n=int(stdin.readline()) i=0 j=1 ans=0 final=9*pow(10,i) if(n<=9): ans=n else: while(n>final): n = n - final ans+=final*j j+=1 i+=1 final = 9 * pow(10, i) ans+=n*j stdout.write(str(ans)+"\n") ```
MatrixStudio/Codeforces-Python-Submissions
Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game. Rules of the game are very simple: at first number of rounds *n* is defined....
```python l=0 m=0 for i in range(int(input())): a,b=map(int,input().split()) if a>b: l=l+1 elif b>a: m=m+1 if l>m: print("Miskha") elif(l<m): print("Chris") else: print("Friendship is magic!^^") ```
MatrixStudio/Codeforces-Python-Submissions
Alice got an array of length $n$ as a birthday present once again! This is the third year in a row! And what is more disappointing, it is overwhelmengly boring, filled entirely with zeros. Bob decided to apply some changes to the array to cheer up Alice. Bob has chosen $m$ changes of the following form. For some int...
```python n, m = map(float, input().split()) mid = 0.0 for i in range(int(m)): x, d = map(float, input().split()) mid += x * n if n % 2: if d > 0: mid += d * n * (n - 1) / 2.0 else: mid += (n*n - 1) / 4 * d else: if d > 0: mid += ...
MatrixStudio/Codeforces-Python-Submissions
Greatest common divisor *GCD*(*a*,<=*b*) of two positive integers *a* and *b* is equal to the biggest integer *d* such that both integers *a* and *b* are divisible by *d*. There are many efficient algorithms to find greatest common divisor *GCD*(*a*,<=*b*), for example, Euclid algorithm. Formally, find the biggest in...
```python a , b = map(int, input().split()) def gcd(a,b): if b < a: a , b = b, a if b%a == 0: return a return gcd(a,b%a) print(gcd(a,b)) ```
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 n=input()+"*" s="Yes" for i in range(len(s)-1): if n[i] not in "aeiou" and n[i+1] not in "aeiou": s="No" else: s="Yes" print(s) ```
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 z = 0 m = input() ls = ['h', 'e', 'l', 'l', 'o'] for i in range(len(m)): if len(ls) == 0: tm="YES" break if ls[0] == m[i]: ls.remove(ls[0]) if len(ls) == 0: tm = "YES" if len(ls) != 0: tm = "NO" print(tm) ```
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 import math a,b=map(int,input().split()) x=y=z=0 for n in range(1,7): if math.fabs(n-a)>math.fabs(n-b): x+=1 elif math.fabs(n-a)<math.fabs(n-b): y+=1 else: z+=1 print(y,z,x) ```
MatrixStudio/Codeforces-Python-Submissions
DZY has a hash table with *p* buckets, numbered from 0 to *p*<=-<=1. He wants to insert *n* numbers, in the order they are given, into the hash table. For the *i*-th number *x**i*, DZY will put it into the bucket numbered *h*(*x**i*), where *h*(*x*) is the hash function. In this problem we will assume, that *h*(*x*)<==...
```python p, n = map(int,input().split()) r, s = 0, {p} while r < n: x = int(input())%p if x in s: break r += 1 s |= {x} print([-1,r+1][r<n]) ```
MatrixStudio/Codeforces-Python-Submissions
You are given several queries. In the *i*-th query you are given a single positive integer *n**i*. You are to represent *n**i* as a sum of maximum possible number of composite summands and print this maximum number, or print -1, if there are no such splittings. An integer greater than 1 is composite, if it is not prim...
```python q = int(input()) a = [4, 6, 8, 9] for i in range(q): n = int(input()) c = 0 if n % 2 == 1: c = 1 n -= 9 if n < 0: print(-1) else: if n % 4 == 0: c += n // 4 elif n % 4 == 2 and n >= 6: c += n // 4 else: ...
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 t = int(input()) for _ in range(t): s = input() l = len(s) if l > 10: r = s[0] + str(l - 2) + s[l-1] print(r) else: print(s) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya has recently found out what a digital root of a number is and he decided to share his knowledge with you. Let's assume that *S*(*n*) is the sum of digits of number *n*, for example, *S*(4098)<==<=4<=+<=0<=+<=9<=+<=8<==<=21. Then the digital root of number *n* equals to: 1. *dr*(*n*)<==<=*S*(*n*), if *S*(*n*)<...
```python k,d=map(int,input().split()) x=1 for i in range(1,k): x=x*10 print(x*d) ```
MatrixStudio/Codeforces-Python-Submissions
According to rules of the Berland fashion, a jacket should be fastened by all the buttons except only one, but not necessarily it should be the last one. Also if the jacket has only one button, it should be fastened, so the jacket will not swinging open. You are given a jacket with *n* buttons. Determine if it is fast...
```python n=int(input()) l=list(map(int,input().split())) if l.count(0)==1 and l[-1]!=0: print('YES') else: print('NO') ```
MatrixStudio/Codeforces-Python-Submissions
DZY has a sequence *a*, consisting of *n* integers. We'll call a sequence *a**i*,<=*a**i*<=+<=1,<=...,<=*a**j* (1<=≤<=*i*<=≤<=*j*<=≤<=*n*) a subsegment of the sequence *a*. The value (*j*<=-<=*i*<=+<=1) denotes the length of the subsegment. Your task is to find the longest subsegment of *a*, such that it is possible ...
```python from collections import deque from sys import stdin lines = deque(line.strip() for line in stdin.readlines()) def nextline(): return lines.popleft() def types(cast): return tuple(int(x) for x in nextline().split()) def ints(): return types(int) def strs(): return nextline().split() def ma...
MatrixStudio/Codeforces-Python-Submissions
Pashmak decided to give Parmida a pair of flowers from the garden. There are *n* flowers in the garden and the *i*-th of them has a beauty number *b**i*. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty diff...
```python num = int(input()) flowers = sorted(list(map(int, input().split()))) firstdigit = [e for e in flowers[0:num//2] if e == flowers[0]] lastdigit = [e for e in flowers[num//2::] if e == flowers[-1]] difference = lastdigit[0] - firstdigit[0] print(difference, len(firstdigit)*len(lastdigit)) ```
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() k = "" for var in s: if var == "x": k += "x" else: k += " " cnt = 0 for var in k.split(): cnt += max(0, len(var)-2) print(cnt) ```
MatrixStudio/Codeforces-Python-Submissions
There are well-known formulas: , , . Also mathematicians found similar formulas for higher degrees. Find the value of the sum modulo 109<=+<=7 (so you should find the remainder after dividing the answer by the value 109<=+<=7).
```python import sys input = sys.stdin.readline n, k = [int(i) for i in input().split()] N = 10 ** 9 + 7 y = [0] for i in range(1, k + 2): y.append((y[-1] + pow(i, k, N)) % N) if n < k + 2: print(y[n] % N) else: m = k + 2 x = n modinv = [1] * m for i in range(2, m): m...
MatrixStudio/Codeforces-Python-Submissions
There are *n* pictures delivered for the new exhibition. The *i*-th painting has beauty *a**i*. We know that a visitor becomes happy every time he passes from a painting to a more beautiful one. We are allowed to arranged pictures in any order. What is the maximum possible number of times the visitor may become happy ...
```python input() l=list(map(int,input().split())) l=sorted(l) count=0 for i in range(0,len(l)-1): if l[0]<l[i+1]: count+=1 print(count) ```
MatrixStudio/Codeforces-Python-Submissions
Recall that the bracket sequence is considered regular if it is possible to insert symbols '+' and '1' into it so that the result is a correct arithmetic expression. For example, a sequence "(()())" is regular, because we can get correct arithmetic expression insering symbols '+' and '1': "((1+1)+(1+1))". Also the foll...
```python n,m = map(int, input().split()) if m > n*(n - 1)//2: print('Impossible') else: ans = [] cur = 0 acc = 0 for i in range(n): while cur + acc > m: ans.append(')') acc -= 1 ans.append('(') cur += acc acc += 1 left_cnt ...
MatrixStudio/Codeforces-Python-Submissions
You are given a set of points on a straight line. Each point has a color assigned to it. For point *a*, its neighbors are the points which don't have any other points between them and *a*. Each point has at most two neighbors - one from the left and one from the right. You perform a sequence of operations on this set ...
```python s = list(input()) k = 0 def check(s): ind = [] for i, elem in enumerate(s): if i == 0: if s[i + 1] != elem: ind.append(i) elif i == len(s) - 1: if s[i - 1] != elem: ind.append(i) else: if s[i + ...
MatrixStudio/Codeforces-Python-Submissions
Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting. The game consists of multiple rounds. Its rules are very simple: in each round, a natural number *k* is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's score is...
```python n=int(input()) for i in range(n): a,b=[int(s) for s in input().split()] l=0 a=a*b r=10**6+1 while r-l>1: m=(l+r)//2 k=m**3 if k<a: l=m+1 elif k>a: r=m else: print('Yes') break else: ...
MatrixStudio/Codeforces-Python-Submissions
Professor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest. In total, *n* students will attend, and before the start, every one of them has some positive integer rating. Students are indexed from 1 to *n*. Let's denote...
```python x=int(input()) students="" place=[] students=raw_input() student=list(students) for i in range(x + (x-1)): place.append(0) for i in range(x): for j in range(x + (x-1)): if student[i]<student[j] and student[i]!=' ' and student[j]!=' ': place[i]+=1 place[i]+=1 for i in range(x): p...
MatrixStudio/Codeforces-Python-Submissions
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy...
```python number = int(input()) net_force = 0 for n in range(0, number): forces = input().split() for force in forces: net_force+=int(force) if net_force==0: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Linear Kingdom has exactly one tram line. It has *n* stops, numbered from 1 to *n* in the order of tram's movement. At the *i*-th stop *a**i* passengers exit the tram, while *b**i* passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers ex...
```python n = int(input()) mx = 0 c = 0 for i in range(n): a,b = map(int,input().split()) c -= a c += b if c > mx: mx = c print(mx) ```
MatrixStudio/Codeforces-Python-Submissions
Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be *n* problems, sorted by difficulty, i.e. problem 1 is the easiest and problem *n* is the hardest. Limak knows it will take him 5·*i* minutes to solve th...
```python enter=list(map(int,input().split())) re_minute=240-enter[1] list_of_five=[ x*5 for x in range(1,enter[0]+1)] res=0 for i in range(0,enter[0]): if re_minute >= list_of_five[i]: re_minute=re_minute-list_of_five[i] res+=1 else:break print(res) ```
MatrixStudio/Codeforces-Python-Submissions
Every year, hundreds of people come to summer camps, they learn new algorithms and solve hard problems. This is your first year at summer camp, and you are asked to solve the following problem. All integers starting with 1 are written in one line. The prefix of these line is "123456789101112131415...". Your task is to...
```python t=int(input()) chk="123456789101112131415" if t<=21: print(chk[t-1]) else: print(chk[(t//2)-1]) ```
MatrixStudio/Codeforces-Python-Submissions
Reca company makes monitors, the most popular of their models is AB999 with the screen size *a*<=×<=*b* centimeters. Because of some production peculiarities a screen parameters are integer numbers. Recently the screen sides ratio *x*:<=*y* became popular with users. That's why the company wants to reduce monitor AB999...
```python def f(a,b,x,y): if a>=b and a%x ==0 and (a*y//x)<=b : return (a,(a*y//x)) if a<b and b%y ==0 and (b*x//y)<=a : return (b,(b*x//y)) else: return (0,0) a,b,x,y=map(int,input().split()) print(*f(a,b,x,y)) ```