source
stringclasses
3 values
instruction
stringlengths
23
3.97k
input
stringclasses
1 value
output
stringlengths
1
3.75k
MatrixStudio/Codeforces-Python-Submissions
Today Tavas got his test result as an integer score and he wants to share it with his girlfriend, Nafas. His phone operating system is Tavdroid, and its keyboard doesn't have any digits! He wants to share his score with Nafas via text, so he has no choice but to send this number using words. He ate coffee mix without...
```python first = ['zero','one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] second = ['eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] third = ['ten','twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] num = int(inp...
MatrixStudio/Codeforces-Python-Submissions
Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone. In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules o...
```python a1, a2, a3, a4 = map(int, input().split()) s = input() count= 0 for i in s: if int(i) == a1: count += a1 if int(i) == a2: count += a2 if int(i) == a3: count += a3 if int(i) == a4: count += a4 print(count) ```
MatrixStudio/Codeforces-Python-Submissions
Recently Adaltik discovered japanese crosswords. Japanese crossword is a picture, represented as a table sized *a*<=×<=*b* squares, and each square is colored white or black. There are integers to the left of the rows and to the top of the columns, encrypting the corresponding row or column. The number of integers repr...
```python num_squares = int(input()) color_squares = input() if num_squares != len(color_squares): print('ERROR') exit() else: Block_count = 0 numB = 0 counts = [] for i in range(0,len(color_squares)): if color_squares[i] == 'B': numB += 1 if numB == 1: ...
MatrixStudio/Codeforces-Python-Submissions
Codeforces user' handle color depends on his rating — it is red if his rating is greater or equal to 2400; it is orange if his rating is less than 2400 but greater or equal to 2200, etc. Each time participant takes part in a rated contest, his rating is changed depending on his performance. Anton wants the color of hi...
```python n = int(input()) for i in range(0, n): s = input().split() if int(s[1]) < 2400: pass else: if int(s[2]) > int(s[1]): print("YES") break if i == n - 1: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
During the break the schoolchildren, boys and girls, formed a queue of *n* people in the canteen. Initially the children stood in the order they entered the canteen. However, after a while the boys started feeling awkward for standing in front of the girls in the queue and they started letting the girls move forward ea...
```python n, t = map(int, input().split()) mas = [i for i in input()] for i in range(t): pos = [] for j in range(0, n - 1): if mas[j] == "B" and mas[j + 1] == "G": pos.append(j) for i in pos: mas[i] = "G" mas[i+1] = "B" print(*mas, sep="") ```
MatrixStudio/Codeforces-Python-Submissions
Mike has a string *s* consisting of only lowercase English letters. He wants to change exactly one character from the string so that the resulting one is a palindrome. A palindrome is a string that reads the same backward as forward, for example strings "z", "aaa", "aba", "abccba" are palindromes, but strings "codefo...
```python import math string = input() start = string[:len(string)//2] end = string[math.ceil(len(string)/2):] end = end[::-1] dif = 0 for i in range(len(start)): if start[i] != end[i]: dif += 1 if dif == 1: print('YES') if dif == 0 and len(string) % 2 == 1: print('YES') else: pr...
MatrixStudio/Codeforces-Python-Submissions
After a team finished their training session on Euro football championship, Valeric was commissioned to gather the balls and sort them into baskets. Overall the stadium has *n* balls and *m* baskets. The baskets are positioned in a row from left to right and they are numbered with numbers from 1 to *m*, correspondingly...
```python n,m=map(int,input().split()) l=[] count=0 r=1 p=abs((m+1)/2) p=int(p) d=p e=p for i in range(m): if(i==0): l.append(p) elif(i%2!=0): if(d-1>0): d=d-1 l.append(d) else: d=d+1 l.append(d) elif(i%2==0): ...
MatrixStudio/Codeforces-Python-Submissions
Vasya the programmer lives in the middle of the Programming subway branch. He has two girlfriends: Dasha and Masha, who live at the different ends of the branch, each one is unaware of the other one's existence. When Vasya has some free time, he goes to one of his girlfriends. He descends into the subway at some time,...
```python from math import gcd import sys t=1 def inp(): return sys.stdin.readline().strip() def lcm(a, b): return abs(a*b) // gcd(a, b) for _ in range(t): a, b=map(int, inp().split()) period= lcm(a,b) d=period//a m=period//b if(a>b): m-=1 else: d-...
MatrixStudio/Codeforces-Python-Submissions
Petya and Vasya decided to play a little. They found *n* red cubes and *m* blue cubes. The game goes like that: the players take turns to choose a cube of some color (red or blue) and put it in a line from left to right (overall the line will have *n*<=+<=*m* cubes). Petya moves first. Petya's task is to get as many pa...
```python n, m = [int(i) for i in input().split()] print(min(n, m), m + n - 1 - min(n, m)) ```
MatrixStudio/Codeforces-Python-Submissions
We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer *t* Т-prime, if *t* has exactly three distinct positive divisors. You are given an array of *n* positive integers. For each of them determine whether it is Т-prime or not.
```python int(input()) nums_1=[] nums_2=list(map(int,input().split())) count=0 for num in nums_2: if num**0.5%1!=0: print('NO') else: k=int(num**0.5) for i in range(1,k+1): if k%i==0: count+=1 if count==2: print('YES') ...
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 #!/usr/bin/env python3 ip1 = input() ip2 = input() l = len(ip1) for i in range(l): if ip1[i] == ip2[l - 1 - i]: continue else: print('NO') break else: print('YES') ```
MatrixStudio/Codeforces-Python-Submissions
Jeff's got *n* cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got? Jeff must make the number without leading zero. At that, we assume that numbe...
```python n=int(input());s="".join(sorted(input().split())[::-1]) while(int(s)%90!=0): s=s[1:] print(int(s)) ```
MatrixStudio/Codeforces-Python-Submissions
At the children's day, the child came to Picks's house, and messed his house up. Picks was angry at him. A lot of important things were lost, in particular the favorite set of Picks. Fortunately, Picks remembers something about his set *S*: - its elements were distinct integers from 1 to *limit*; - the value of wa...
```python target, limit = map(int, input().split()) def lowbit(x): return x & (x ^ (x - 1)) ans = [] for i in range(limit, 0, -1): x = lowbit(i) if x <= target: ans.append(i) target -= x if target: print(-1) else: print(len(ans)) print(" ".join(map(str, ans))) ...
MatrixStudio/Codeforces-Python-Submissions
Two players play a game. Initially there are $n$ integers $a_1, a_2, \ldots, a_n$ written on the board. Each turn a player selects one number and erases it from the board. This continues until there is only one number left on the board, i. e. $n - 1$ turns are made. The first player makes the first move, then players ...
```python n = int(input()) nums = input().split() nums = [int(c) for c in nums] nums = sorted(nums) i = 1 while i < n and nums: if i % 2 != 0: nums.pop(0) else: nums.pop(-1) i += 1 print(nums[0]) ```
MatrixStudio/Codeforces-Python-Submissions
Vova, the Ultimate Thule new shaman, wants to build a pipeline. As there are exactly *n* houses in Ultimate Thule, Vova wants the city to have exactly *n* pipes, each such pipe should be connected to the water supply. A pipe can be connected to the water supply if there's water flowing out of it. Initially Vova has onl...
```python n, k = map(int, input().split(' ')) splitters = 0 outlets = 0 while k>0 and outlets < n: outlets +=k if splitters> 0: outlets -=1 splitters +=1 k-=1 if outlets < n: print(-1) else: print(splitters) ```
MatrixStudio/Codeforces-Python-Submissions
Santa Claus has *n* candies, he dreams to give them as gifts to children. What is the maximal number of children for whose he can give candies if Santa Claus want each kid should get distinct positive integer number of candies. Santa Class wants to give all *n* candies he has.
```python n = int(input()) s = 0 m = [] i = 1 while True: s += i m.append(i) i += 1 if s >= n: break if s == n: print(len(m)) for e in m: print(e, end=' ') else: del m[m.index(s - n)] print(len(m)) for e in m: print(e, end=' ') ```
MatrixStudio/Codeforces-Python-Submissions
A kindergarten teacher Natalia Pavlovna has invented a new ball game. This game not only develops the children's physique, but also teaches them how to count. The game goes as follows. Kids stand in circle. Let's agree to think of the children as numbered with numbers from 1 to *n* clockwise and the child number 1 is...
```python n = int(input()) x = 1 for i in range(1,n): x =x+i if x>n: x =x-n print(x) ```
MatrixStudio/Codeforces-Python-Submissions
Julia is going to cook a chicken in the kitchen of her dormitory. To save energy, the stove in the kitchen automatically turns off after *k* minutes after turning on. During cooking, Julia goes to the kitchen every *d* minutes and turns on the stove if it is turned off. While the cooker is turned off, it stays warm. T...
```python def gcd(a,b): if a>b: b,a=a,b if a==0: return(b) return(gcd(b%a,a)) k,d,t=map(int,input().split()) nok=k*d//gcd(k,d) if nok<t: st,dt=1,0 for i in range(1,nok+1): if i%k==0: st=0 if i%d==0: st=1 dt+=0.5+0.5*st ...
MatrixStudio/Codeforces-Python-Submissions
Vasya follows a basketball game and marks the distances from which each team makes a throw. He knows that each successful throw has value of either 2 or 3 points. A throw is worth 2 points if the distance it was made from doesn't exceed some value of *d* meters, and a throw is worth 3 points if the distance is larger t...
```python ###### ### ####### ####### ## # ##### ### ##### # # # # # # # # # # # # # ### # # # # # # # # # # # # # ### ###### ######### # # # #...
MatrixStudio/Codeforces-Python-Submissions
A positive integer is called a 2-3-integer, if it is equal to 2*x*·3*y* for some non-negative integers *x* and *y*. In other words, these integers are such integers that only have 2 and 3 among their prime divisors. For example, integers 1, 6, 9, 16 and 108 — are 2-3 integers, while 5, 10, 21 and 120 are not. Print th...
```python import math def count(p , q): if q <= -1: q = -0.910 return math.floor(p) - math.ceil(q) + 1 a , b = map(int , input().split()) answer = 0 while(b > 1): p = (math.log(b)) / (math.log(3)) q = (math.log(a)) / (math.log(3)) answer += count(p , q) b = b / 2 a = a ...
MatrixStudio/Codeforces-Python-Submissions
Twilight Sparkle was playing Ludo with her friends Rainbow Dash, Apple Jack and Flutter Shy. But she kept losing. Having returned to the castle, Twilight Sparkle became interested in the dice that were used in the game. The dice has *m* faces: the first face of the dice contains a dot, the second one contains two dots...
```python m,n = map(int, input().split()) e = 0 for i in range(1,m+1): e += i * ((i/m) ** n - ((i-1)/m)**n) print(e) ```
MatrixStudio/Codeforces-Python-Submissions
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second. One day in 230 AD Shapur was trying to find out if any one can possibly do...
```python first_num = input() second_num = input() mas = [] for i in range(len(first_num)): if first_num[i] == second_num[i]: mas.append(0) else: mas.append(1) for i in mas: print(i,end = '') ```
MatrixStudio/Codeforces-Python-Submissions
For an array $b$ of length $m$ we define the function $f$ as where $\oplus$ is [bitwise exclusive OR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR). For example, $f(1,2,4,8)=f(1\oplus2,2\oplus4,4\oplus8)=f(3,6,12)=f(3\oplus6,6\oplus12)=f(5,10)=f(5\oplus10)=f(15)=15$ You are given an array $a$ and a few queri...
```python tamanho = int(input()) elementos = list(map(int, input().split())) matrix = [[0] * tamanho for i in range(tamanho)] for i in range(tamanho): matrix[0][i] = elementos[i] for i in range(1, tamanho): for j in range(tamanho-i): matrix[i][j] = matrix[i-1][j] ^ matrix[i-1][j+1] for i in range(1, t...
MatrixStudio/Codeforces-Python-Submissions
Theatre Square in the capital city of Berland has a rectangular shape with the size *n*<=×<=*m* meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size *a*<=×<=*a*. What is the least number of flagstones needed to pave the...
```python f = input().split() f = list(map(int, f)) n, m, a = f[0], f[1], f[2] if ((n // a) * a) == n: cnt1 = n // a else: cnt1 = (n // a) + 1 if ((m // a) * a) == m: cnt2 = m // a else: cnt2 = (m // a) + 1 print(cnt1 * cnt2) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya thinks that lucky tickets are the tickets whose numbers are divisible by 3. He gathered quite a large collection of such tickets but one day his younger brother Leonid was having a sulk and decided to destroy the collection. First he tore every ticket exactly in two, but he didn’t think it was enough and Leonid a...
```python #!/usr/bin/env python3 from sys import stdin def sum_digits(n): r = 0 while n: r, n = r + n % 10, n // 10 return r input_n = stdin.readline() n = int(input_n) input_tokens = stdin.readline() tokens = [int(x) for x in input_tokens.split()] assert n == len(tokens) sum_tok...
MatrixStudio/Codeforces-Python-Submissions
Rebel spy Heidi has just obtained the plans for the Death Star from the Empire and, now on her way to safety, she is trying to break the encryption of the plans (of course they are encrypted – the Empire may be evil, but it is not stupid!). The encryption has several levels of security, and here is how the first one lo...
```python n,p=map(int,input().split()) ll=list(map(int,input().split())) f,s=ll[0],sum(ll)-ll[0] r=f%p+s%p for i in range(1,n-1): f+=ll[i] s-=ll[i] if f%p+s%p>r: r=f%p+s%p print(r) ```
MatrixStudio/Codeforces-Python-Submissions
Sereja showed an interesting game to his friends. The game goes like that. Initially, there is a table with an empty cup and *n* water mugs on it. Then all players take turns to move. During a move, a player takes a non-empty mug of water and pours all water from it into the cup. If the cup overfills, then we assume th...
```python a,b=map(int,input().split()) l=list(map(int,input().split())) if max(l)>=b:print("NO") else:print("YES") ```
MatrixStudio/Codeforces-Python-Submissions
A triangular number is the number of dots in an equilateral triangle uniformly filled with dots. For example, three dots can be arranged in a triangle; thus three is a triangular number. The *n*-th triangular number is the number of dots in a triangle with *n* dots on a side. . You can learn more about these numbers fr...
```python a = int(input()) l = [] for i in range(1,500): l.append((i*(i+1))/2) print("YES" if a in l else "NO") ```
MatrixStudio/Codeforces-Python-Submissions
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular *w* mm <=×<= *h* mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how. In order not to waste time, he decided to prac...
```python import numpy as np l1 = list(map(int, (input().split()))) w = l1[0] h = l1[1] n = l1[2] V = [0,w] H = [0,h] ar = [] movs = [] for i in range(n): l2 = list((input().split())) pos = l2[0] num = int(l2[1]) movs.append((pos,num)) for i in movs: pos, num = i if(pos == 'H'): H.appe...
MatrixStudio/Codeforces-Python-Submissions
Tonio has a keyboard with only two letters, "V" and "K". One day, he has typed out a string *s* with only these two letters. He really likes it when the string "VK" appears, so he wishes to change at most one letter in the string (or do no changes) to maximize the number of occurrences of that string. Compute the maxi...
```python import sys s = input() cnt = found = 0 for i in range(0,len(s),1): if i != len(s)-1 and s[i] == 'V' and s[i+1] == 'K': cnt += 1 i += 1 elif found == 0 and i != len(s)-1 and ((s[i] == 'V' and s[i+1] == 'V') or (s[i] == 'K' and s[i+1] == 'K') ) : found = 1 cnt +=...
MatrixStudio/Codeforces-Python-Submissions
All cities of Lineland are located on the *Ox* coordinate axis. Thus, each city is associated with its position *x**i* — a coordinate on the *Ox* axis. No two cities are located at a single point. Lineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another c...
```python n = int(input()) x = list(map(int, input().split())) q = 1000000000 for i in range(n): biggest = 0 smallest = 0 if i == 0: biggest = (x[-1] + q) - (x[i] + q) smallest = (x[i + 1] + q) - (x[0] + q) elif i == n-1: biggest = (x[-1] + q) - (x[0] + q) smal...
MatrixStudio/Codeforces-Python-Submissions
Innovation technologies are on a victorious march around the planet. They integrate into all spheres of human activity! A restaurant called "Dijkstra's Place" has started thinking about optimizing the booking system. There are *n* booking requests received by now. Each request is characterized by two numbers: *c**i*...
```python n = int(input()) l = [] val = [] ind1, ind2 = 0, 0 ans = [] pos = 1 for i in range(n): l.append([int(x) for x in input().split()]) l1 = l[:] l1.sort() k = int(input()) r = [int(x) for x in input().split()] r.sort() l1.reverse() r.reverse() while(ind1 < n and ind2 < k): if l1[...
MatrixStudio/Codeforces-Python-Submissions
The Rebel fleet is on the run. It consists of *m* ships currently gathered around a single planet. Just a few seconds ago, the vastly more powerful Empire fleet has appeared in the same solar system, and the Rebels will need to escape into hyperspace. In order to spread the fleet, the captain of each ship has independe...
```python arr = [] d = {} for _ in range(int(input())): s = input() a,b,c = tuple(map(int, s.replace("(","").replace(")","").replace("/",".").replace("+",".").split("."))) x = (a+b)/c arr.append(x) if x not in d: d[x] = 0 d[x] += 1 for i in arr: print(d[i], end = " ") ``...
MatrixStudio/Codeforces-Python-Submissions
You have a fraction . You need to find the first occurrence of digit *c* into decimal notation of the fraction after decimal point.
```python import math a,b,c=map(int,input().split()) dis=1 x=False while True: for i in range(1,50): q=(dis*a)/b q1=(math.trunc(q))%10 if q1== c: print(i) x=True break q=q-q1 ...
MatrixStudio/Codeforces-Python-Submissions
Kuriyama Mirai has killed many monsters and got many (namely *n*) stones. She numbers the stones from 1 to *n*. The cost of the *i*-th stone is *v**i*. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions: 1. She will tell you two numbers, *l* and *r* (1<=≤<=*l*<=≤<=*r*...
```python def main(): n = int(input()) costs = [int(x) for x in input().split()] m = int(input()) sorted_costs = [x for x in costs] sorted_costs.sort() rs_costs = [0] rs_sorted = [0] rs = 0 rss = 0 for i in range(n): rs += costs[i] rs_costs.append(rs...
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 n=input() if (n=='a8')or(n=='a1')or(n=='h8')or(n=='h1'): print(3) elif (n[0]in('a','h'))or(n[1]in('1','8')): print(5) else: print(8) ```
MatrixStudio/Codeforces-Python-Submissions
Allen has a LOT of money. He has $n$ dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are $1$, $5$, $10$, $20$, $100$. What is the minimum number of bills Allen could receive after withdrawing his entire balance?
```python n = int(input()) d = [100,20,10,5] ans = 0 for i in range(4): ans +=n //d[i] n%= d[i] ans+=n print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
One day Vasya came across three Berland coins. They didn't have any numbers that's why Vasya didn't understand how their denominations differ. He supposed that if one coin is heavier than the other one, then it should be worth more. Vasya weighed all the three pairs of coins on pan balance scales and told you the resul...
```python def add(left, right, word): if word[1] == ">": right[word[0]] += 1 left[word[2]] += 1 else: left[word[0]] += 1 right[word[2]] += 1 return left, right first = input() secon = input() third = input() left = {'A':0, 'B':0, 'C':0} right = {'A':0, 'B':0, 'C':0} left, ...
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 n, m = map(int, input().split()) a = [int(i) for i in input().split()] ans = 0 for i in range(1, m): if a[i] < a[i - 1]: ans += n - 1 + a[i] - 1 if a[-1] >= a[-2]: ans += a[-1] - 1 print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second. One day in 230 AD Shapur was trying to find out if any one can possibly do...
```python import sys input = sys.stdin.readline ############ ---- Input Functions ---- ############ # — For taking integer inputs. def inp(): return(int(input())) # — For taking List inputs. def inlt(): return(list(map(int,input().split()))) # For taking string inputs. Actually it returns a...
MatrixStudio/Codeforces-Python-Submissions
You are given *n* rectangles. The corners of rectangles have integer coordinates and their edges are parallel to the *Ox* and *Oy* axes. The rectangles may touch each other, but they do not overlap (that is, there are no points that belong to the interior of more than one rectangle). Your task is to determine if the ...
```python for i in range(int(input())): x1, y1, x2, y2 = map(int, input().split()) a1, b1, a2, b2 = min(a1, x1), min(b1, y1), max(a2, x2), max(b2, y2) s += (x2 - x1) * (y2 - y1) print('YES' if s == (a2 - a1) * (b2 - b1) else 'NO') ```
MatrixStudio/Codeforces-Python-Submissions
Kefa decided to make some money doing business on the Internet for exactly *n* days. He knows that on the *i*-th day (1<=≤<=*i*<=≤<=*n*) he makes *a**i* money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence *a**i*. Let us remind you that the subsegment o...
```python n = int(input()) incomes = [int(i) for i in input().split()] counter = maximus = 1 for i in range(1, n): if incomes[i] >= incomes[i - 1]: counter += 1 else: if counter > maximus: counter = maximus counter = 1 print(maximus) ```
MatrixStudio/Codeforces-Python-Submissions
You have probably registered on Internet sites many times. And each time you should enter your invented password. Usually the registration form automatically checks the password's crypt resistance. If the user's password isn't complex enough, a message is displayed. Today your task is to implement such an automatic che...
```python input1 = input() if len(input1)<5: print("Too Weak") else: upper = False lower = False digit = False for i in range(len(input1)): if input1[i].islower(): lower = True if input1[i].isupper(): upper = True if input1[i].isdigit...
MatrixStudio/Codeforces-Python-Submissions
Sereja and his friends went to a picnic. The guys had *n* soda bottles just for it. Sereja forgot the bottle opener as usual, so the guys had to come up with another way to open bottles. Sereja knows that the *i*-th bottle is from brand *a**i*, besides, you can use it to open other bottles of brand *b**i*. You can use...
```python n=int(input()) bottle=[-1 for i in range(n)] for i in range(n): a,b=map(int,input().split()) if a!=b: if b<n: bottle[b-1]=0 res=0 for i in range(n): if bottle[i]==-1: res+=1 print(res) ```
MatrixStudio/Codeforces-Python-Submissions
In Berland it is the holiday of equality. In honor of the holiday the king decided to equalize the welfare of all citizens in Berland by the expense of the state treasury. Totally in Berland there are *n* citizens, the welfare of each of them is estimated as the integer in *a**i* burles (burle is the currency in Berl...
```python tests = int(input("")) nums = [int(i) for i in input("").split()][:tests] sums = [max(nums) - n for n in nums] print(sum(sums)) ```
MatrixStudio/Codeforces-Python-Submissions
Today there is going to be an unusual performance at the circus — hamsters and tigers will perform together! All of them stand in circle along the arena edge and now the trainer faces a difficult task: he wants to swap the animals' positions so that all the hamsters stood together and all the tigers also stood together...
```python def min_swaps_to_group_animals(n, positions): # Count the total number of hamsters and tigers num_hamsters = positions.count("H") num_tigers = n - num_hamsters # Find the initial count of tigers within the first window of size num_hamsters initial_tiger_count = positions[:num_hamsters...
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 a=input() p=3 for i in range(0,len(a),1): if p==4: p=3 continue #print(p,i) if a[i]=='.': print(0,end="") elif a[i]=='-': p=4 if a[i+1]=='.': print(1,end="") elif a[i+1]=='-': print(2,end="") #print(i) `...
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 a = input().strip() w = "hello" i = 0 if len(a) == 5: print("NO") else: if a.count("l") < 2 : print("NO") else: for char in a : if char == a[i]: i += 1 if i <= len(a)/2: print("NO") else : print("YES") ```
MatrixStudio/Codeforces-Python-Submissions
Some days ago, I learned the concept of LCM (least common multiple). I've played with it for several times and I want to make a big number with it. But I also don't want to use many numbers, so I'll choose three positive integers (they don't have to be distinct) which are not greater than *n*. Can you help me to find ...
```python n= int(input()) from math import gcd ans = 1 for i in range(2,n): ans = max(ans,i*(i-1)*(i+1)//gcd(gcd(i*(i+1),i*(i-1)),(i-1)*(i+1))) print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Kirill plays a new computer game. He came to the potion store where he can buy any potion. Each potion is characterized by two integers — amount of experience and cost. The efficiency of a potion is the ratio of the amount of experience to the cost. Efficiency may be a non-integer number. For each two integer numbers ...
```python l=list(map(float,input().split())) l1=int(l[0]) r=int(l[1]) x=int(l[2]) y=int(l[3]) p=l[4] for i in range(l1,r+1) : if int(p*i)==p*i : t=int(p*i) if x<=t and t<=y : print('YES') exit() print('NO') ```
MatrixStudio/Codeforces-Python-Submissions
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem. Given two strings *a* and *b*, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence ...
```python # https://codeforces.com/problemset/problem/766/A def check(w1, w2): if w1 != w2: return max(len(w1), len(w2)) return -1 w1 = input() w2 = input() print(check(w1, w2)) ```
MatrixStudio/Codeforces-Python-Submissions
Allen has a LOT of money. He has $n$ dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are $1$, $5$, $10$, $20$, $100$. What is the minimum number of bills Allen could receive after withdrawing his entire balance?
```python n=int(input()) cnt=0 while n>100: cnt+=n//100 n=n%100 while n>20: cnt+=n//20 n=n%20 while n>10: cnt+=n//10 n=n%10 while n>5: cnt+=n//5 n=n%5 cnt+=n print(cnt) ```
MatrixStudio/Codeforces-Python-Submissions
Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything. During an audit, you were surprised to find out that the...
```python n=int(input()) inventory=[*map(int, input().split())] bool = [False]*100001 bads = set() for index, thing in enumerate(inventory): if thing <= n and bool[thing]: bads.add(index) else: bool[thing] = True for num, isin in enumerate(bool[1:]): if not isin and len(b...
MatrixStudio/Codeforces-Python-Submissions
One day Vasya painted a Cartesian coordinate system on a piece of paper and marked some set of points (*x*1,<=*y*1),<=(*x*2,<=*y*2),<=...,<=(*x**n*,<=*y**n*). Let's define neighbors for some fixed point from the given set (*x*,<=*y*): - point (*x*',<=*y*') is (*x*,<=*y*)'s right neighbor, if *x*'<=&gt;<=*x* and *y*'...
```python n = int(input()) dots = [] for i in range(n): x, y = map(int, input().split()) dots.append((x,y)) c = 0 for i in range(n): main_dot = dots[i] l, r, u, d = -1, -1, -1, -1 for j in range(n): if(i!=j): sub_dot = dots[j] #print(main_dot, sub_dot) ...
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 n = int(input()) a = list(map(int, input().split())) li = [1] * n for i in range(n): for j in range(n): if a[i] > a[j]: li[j] += 1 print(*li) ```
MatrixStudio/Codeforces-Python-Submissions
The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her *n* students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often od...
```python n, m = map(int, input().split()) a = list(map(int, input().split())) a.sort(reverse=True) print(a[-n] - a[-1]) ```
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 def checkMatrix(arr): locationOfOnei = -1 locationOfOnej = -1 numberOfMoves = 0 for i in range(5): for j in range(5): if(arr[i][j] == 1): locationOfOnei = i locationOfOnej = j while(locationOfOnei != 2 or locationOfOnej != 2): if ...
MatrixStudio/Codeforces-Python-Submissions
Vasilisa the Wise from the Kingdom of Far Far Away got a magic box with a secret as a present from her friend Hellawisa the Wise from the Kingdom of A Little Closer. However, Vasilisa the Wise does not know what the box's secret is, since she cannot open it again. She hopes that you will help her one more time with tha...
```python import numpy as np ```
MatrixStudio/Codeforces-Python-Submissions
Greg has an array *a*<==<=*a*1,<=*a*2,<=...,<=*a**n* and *m* operations. Each operation looks as: *l**i*, *r**i*, *d**i*, (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*). To apply operation *i* to the array means to increase all array elements with numbers *l**i*,<=*l**i*<=+<=1,<=...,<=*r**i* by value *d**i*. Greg wrote down *k* qu...
```python def add_range(x,y,arr, val): arr[x]+=val if y+1 < len(arr): arr[y+1] -=val def calculate_sum(arr): for i in range(len(arr)): if i+1 < len(arr): arr[i+1] += arr[i] n, m, k = map(int, input().split()) op = [] arr = list(map(int, input().split())) arr.inse...
MatrixStudio/Codeforces-Python-Submissions
On her way to programming school tiger Dasha faced her first test — a huge staircase! The steps were numbered from one to infinity. As we know, tigers are very fond of all striped things, it is possible that it has something to do with their color. So on some interval of her way she calculated two values — the number ...
```python def main(): s = input().split() a = int(s[0]) b = int(s[1]) if not (a or b): print("NO") return d = a - b if abs(d) > 1: print("NO") else: print("YES") def f(): pass if __name__ == "__main__": main() ```
MatrixStudio/Codeforces-Python-Submissions
Ann has recently started commuting by subway. We know that a one ride subway ticket costs *a* rubles. Besides, Ann found out that she can buy a special ticket for *m* rides (she can buy it several times). It costs *b* rubles. Ann did the math; she will need to use subway *n* times. Help Ann, tell her what is the minimu...
```python n,m,a,b=map(int,input().split()) #n for plan, m for m-ticket, a for one-ride, b for m-ride if b/m <= a: print(n//m*b+n%m*a) else: print(n*a) ```
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 n = input() n2 = input() n3 = list(input()) n4 = list(n+n2) if len(n4) != len(n3): print("NO") if len(n4) == len(n3): if sorted(n4) == sorted(n3): print("YES") ```
MatrixStudio/Codeforces-Python-Submissions
There are *n* cows playing poker at a table. For the current betting phase, each player's status is either "ALLIN", "IN", or "FOLDED", and does not change throughout the phase. To increase the suspense, a player whose current status is not "FOLDED" may show his/her hand to the table. However, so as not to affect any be...
```python n = int(input()) s = input().lower() cnt1 = 0 cnt2 = 0 if len(set(s)) == 1 and s[0] == 'f': print(0) exit(0) for i in range(n): if s[i] == 'i': cnt1 +=1 for i in range(n): if s[i] == 'a': cnt2 +=1 print(max(cnt2 , cnt1)) ```
MatrixStudio/Codeforces-Python-Submissions
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If...
```python zero, one = 0, 0 for i in input(): if i == '0': zero += 1 one = 0 else: one += 1 zero = 0 print('YES' if zero >= 7 or one >= 7 else 'NO') ```
MatrixStudio/Codeforces-Python-Submissions
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended u...
```python s = input() pm = 0 mp = 0 for i in range(len(s)-1): if s[i]=='-' and s[i+1]=='+': mp+=1 i+=2 elif s[i]=='+' and s[i+1]=='-': pm+=1 i+=2 if pm==mp and len(s)!=1: print("Yes") else: print("No") ```
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() ucount = lcount = 0 for i in s: if i.isupper(): ucount+=1 else: lcount+=1 if ucount > lcount: print(s.upper()) else: print(s.lower()) ```
MatrixStudio/Codeforces-Python-Submissions
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function *f*, which is defined ...
```python n = int(input()) _l = list(map(int, input().split())) l = [abs(_l[i] - _l[i + 1]) for i in range(n - 1)] p, n, res = 0, 0, 0 for e in l: _p = max(0, n + e) _n = max(0, p - e) p, n = _p, _n res = max(p, n, res) print(res) ```
MatrixStudio/Codeforces-Python-Submissions
A word or a sentence in some language is called a pangram if all the characters of the alphabet of this language appear in it at least once. Pangrams are often used to demonstrate fonts in printing or test the output devices. You are given a string consisting of lowercase and uppercase Latin letters. Check whether thi...
```python n = int(input()) s = input() a = [] if n>26: for i in s: if i.lower() not in a: a.append(i.lower()) if len(a)==26: print("YES") else: print("NO") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Connected undirected weighted graph without self-loops and multiple edges is given. Graph contains *n* vertices and *m* edges. For each edge (*u*,<=*v*) find the minimal possible weight of the spanning tree that contains the edge (*u*,<=*v*). The weight of the spanning tree is the sum of weights of all edges included...
```python from math import inf n, m = map(int, input().split()) adj = [[] for _ in range(n + 1)] req_edges = [] for _ in range(m): u, v, w = map(int, input().split()) adj[u].append([v, w]) adj[v].append([u, w]) req_edges.append([u, v]) def get_min_weight_visitable_node(v, m, req_edge, req...
MatrixStudio/Codeforces-Python-Submissions
Recently Vasya got interested in finding extra-terrestrial intelligence. He made a simple extra-terrestrial signals’ receiver and was keeping a record of the signals for *n* days in a row. Each of those *n* days Vasya wrote a 1 in his notebook if he had received a signal that day and a 0 if he hadn’t. Vasya thinks that...
```python n = int(input()) pala = input().split('1') ans = "YES" teste = [] for j in range(len(pala)-1): if len(pala[j]) == 0: continue teste.append(pala[j]) cont = len(teste[0]) for j in range(1,len(teste)): if len(teste[j]) != cont: ans = "NO" print(ans) ...
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 word = input() countU = 0 countL = 0 for i in word: if i.isupper() == True: countU+=1 else: countL+=1 if countL > countU: print(word.lower()) else: print(word.upper()) ```
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() words = s.replace("WUB", " ").split() print(" ".join(words)) ```
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()) arr = list(map(int, input().split())) e = 0 o = 0 for i in range(1,n): if arr[i]%2==0: e +=1 x = i else: o +=1 y = i if e == 1: print(x+1) elif o==1: print(y+1) ```
MatrixStudio/Codeforces-Python-Submissions
There are *n* kangaroos with pockets. Each kangaroo has a size (integer number). A kangaroo can go into another kangaroo's pocket if and only if the size of kangaroo who hold the kangaroo is at least twice as large as the size of kangaroo who is held. Each kangaroo can hold at most one kangaroo, and the kangaroo who i...
```python n = int(input()) a = [] for i in range(n): k = int(input()) a.append(k) a = sorted(a) q = [a[-1]] l = 0 for i in range(n-2,-1,-1): try: if(q[0]>=2*a[i]): q.pop(0) l+=1 a[i] = 0 else: q.append(a[i]) except: ...
MatrixStudio/Codeforces-Python-Submissions
A continued fraction of height *n* is a fraction of form . You are given two rational numbers, one is represented as and the other one is represented as a finite fraction of height *n*. Check if they are equal.
```python p, q = list(map(int, input().split())) n = int(input()) a = list(map(int, input().split())) fract1 = [] x, y = p, q while y > 0: if y == 1: fract1 += [x - 1, 1] else: fract1 += [x // y] x, y = y, x % y fract2 = [] x, y = p, q while y > 0: fract2 += [x // y] x, y = y, x % y...
MatrixStudio/Codeforces-Python-Submissions
An infinitely long railway has a train consisting of *n* cars, numbered from 1 to *n* (the numbers of all the cars are distinct) and positioned in arbitrary order. David Blaine wants to sort the railway cars in the order of increasing numbers. In one move he can make one of the cars disappear from its place and telepor...
```python n=int(input()) l=[int(i) for i in input().split()] l1=[i for i in range(1,n+1)] j=0 i=0 while i<n and j<n: if l1[i]==l[j]: i+=1 j+=1 else: j+=1 print(n-i) ```
MatrixStudio/Codeforces-Python-Submissions
Today Vasya visited a widely known site and learned that the continuation of his favourite game Codecraft II will appear after exactly *k* months. He looked at the calendar and learned that at the moment is the month number *s*. Vasya immediately got interested in what month Codecraft III will appear. Help him understa...
```python month_to_num = { "January": 0, "February": 1, "March": 2, "April": 3, "May": 4, "June": 5, "July": 6, "August": 7, "September": 8, "October": 9, "November": 10, "December": 11, } num_to_month = [ "January", "February", "March", "April", "May...
MatrixStudio/Codeforces-Python-Submissions
Allen has a LOT of money. He has $n$ dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are $1$, $5$, $10$, $20$, $100$. What is the minimum number of bills Allen could receive after withdrawing his entire balance?
```python a = int(input()) sq = 0 while a !=0: if a >= 100: a -= 100 sq += 1 elif 20 <= a < 100: a -= 20 sq +=1 elif 10<= a < 20: a -= 10 sq +=1 elif 5 <= a < 10: a -= 5 sq += 1 elif 1 <= a < 5: a -= 1 s...
MatrixStudio/Codeforces-Python-Submissions
Some large corporation where Polycarpus works has its own short message service center (SMSC). The center's task is to send all sorts of crucial information. Polycarpus decided to check the efficiency of the SMSC. For that, he asked to give him the statistics of the performance of the SMSC for some period of time. In...
```python Messages, Max, Last = 0, 0, 0 for i in range(int(input())): X = list(map(int, input().split())) Messages = max(0, Messages - (X[0] - Last)) Messages += X[1] Max = max(Messages, Max) Last = X[0] print(Last + Messages, Max) # UB_CodeForces # Advice: Falling down is an accident, st...
MatrixStudio/Codeforces-Python-Submissions
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: - Tetrahedron. Tetrahedron has 4 triangular faces. - Cube. Cube has 6 square faces. - Octahedron. Octahedron has 8 triangular faces. - Dodecahedron. Dodecahedron has 12 pentagonal faces. - Icosahed...
```python di= {"I":20,"C":6,"T":4,"D":12,"O":8} ans=0 t=int(input()) for i in range(t): s=input() ans+=(di[s[0]]) print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Small, but very brave, mouse Brain was not accepted to summer school of young villains. He was upset and decided to postpone his plans of taking over the world, but to become a photographer instead. As you may know, the coolest photos are on the film (because you can specify the hashtag #film for such). Brain took a ...
```python import sys input = lambda : sys.stdin.readline().strip() ############################################################################################################################# n,m = map(int,input().split()) a = '' for i in range(n): a += input() if ('C' in a) or ('M' in a) or ('Y' in a): ...
MatrixStudio/Codeforces-Python-Submissions
Everybody in Russia uses Gregorian calendar. In this calendar there are 31 days in January, 28 or 29 days in February (depending on whether the year is leap or not), 31 days in March, 30 days in April, 31 days in May, 30 in June, 31 in July, 31 in August, 30 in September, 31 in October, 30 in November, 31 in December. ...
```python n=int(input()) x="312831303130313130313031" b=x[-1:] y="312931303130313130313031" c=y[-1:] ch=b+x ch1=y+x a="" l=list(map(int,input().split())) for i in range(len(l)): a+=str(l[i]) if (y+y).find(a)!=-1 or (x+x).find(a)!=-1 or (x+y).find(a)!=-1: print("yes") else: print("No") ```
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 n=int(input()) l=list(map(int,input().split( ))) l.sort() maxi=l[-1] mini=l[0] dif=maxi-mini m=0 p=0 for i in l: if i==maxi: m+=1 if i==mini: p+=1 if len(set(l))==1: print(dif,n*(n-1)//2) else: print(dif,m*p) ```
MatrixStudio/Codeforces-Python-Submissions
A number is called quasibinary if its decimal representation contains only digits 0 or 1. For example, numbers 0, 1, 101, 110011 — are quasibinary and numbers 2, 12, 900 are not. You are given a positive integer *n*. Represent it as a sum of minimum number of quasibinary numbers.
```python n=int(input()) a=[] while(True): if n==0: break s=str(n) l=len(s) t=[] for k in s: if int(k)>=1: t.append('1') else: t.append('0') d=int(''.join(t)) a.append(d) n-=d print(*a) ```
MatrixStudio/Codeforces-Python-Submissions
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000. This new device is equipped with specially designed artificial intelligence (AI). Employees of Pine...
```python alert = "eztask" if 2 ** 2 != 2 ** 2: print("eztask") else: alert = "hardtask" google = input() apple = input() ans = google.count(apple) if alert == "hardtask": print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it: - deletes all the vowels, - inserts a character "." before each consonant, - replaces ...
```python a=input() vowels="AEIOUYaeiouy" ms="" for i in a: if i in vowels: continue ms+="."+char if char.isupper()and not in vowels: ms=ms+char.lower() return ms ```
MatrixStudio/Codeforces-Python-Submissions
Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number *a* and Antisimon receives number *b*. They also have a heap of *n* stones. The players take turns to make a move and Simon starts. During a move a player should take...
```python a, b, n = map(int, input().split()) ans = 0 while True: if ans == 0 and n % a == 0 and n-a >= 0: n = n-a ans = 1 elif ans == 0 and n % a != 0 and n-1 >= 0: n = n-1 ans = 1 elif ans == 1 and n % b == 0 and n-b >= 0: n = n-b ans = 0 eli...
MatrixStudio/Codeforces-Python-Submissions
Theatre Square in the capital city of Berland has a rectangular shape with the size *n*<=×<=*m* meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size *a*<=×<=*a*. What is the least number of flagstones needed to pave the...
```python [n, m, a] = input().split(' ') n, m, a = int(n), int(m), int(a) L = n // a if n % a != 0: L += 1 l = m // a if m % a != 0: l += 1 print(L * l) ```
MatrixStudio/Codeforces-Python-Submissions
Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they ...
```python n = int(input()) L = [] for i in range(n): N = input() print('YES' if N in L else 'NO') L.append(N) ```
MatrixStudio/Codeforces-Python-Submissions
Vlad likes to eat in cafes very much. During his life, he has visited cafes *n* times. Unfortunately, Vlad started to feel that his last visits are not any different from each other. To fix that Vlad had a small research. First of all, Vlad assigned individual indices to all cafes. Then, he wrote down indices of cafes...
```python t=int(input()) a=list(map(int,input().split())) dct={} temp=0 for i in a: dct[i]=temp temp=temp+1 sorted_dct=dict(sorted(dct.items(),key=lambda x:x[1])) for i in sorted_dct: print(i) break ```
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 #Problem D - Snacktower n = int(input()) sequencia = input().split(' ') empilhado = [] for i in range (len(sequencia)): sequencia[i] = int(sequencia[i]) proximo = n for i in range (len(sequencia)): empilhado.append(sequencia[i]) if(sequencia[i] == proximo): empilhado.sort(reverse=True...
MatrixStudio/Codeforces-Python-Submissions
You have two variables *a* and *b*. Consider the following sequence of actions performed with these variables: 1. If *a*<==<=0 or *b*<==<=0, end the process. Otherwise, go to step 2;1. If *a*<=≥<=2·*b*, then set the value of *a* to *a*<=-<=2·*b*, and repeat step 1. Otherwise, go to step 3;1. If *b*<=≥<=2·*a*, then s...
```python a,b=(int(x) for x in input().split(" ")) while a != 0 and b != 0: if a >= 2*b: a -= int(a/(2*b)) continue elif b >= 2*a: b-= int(b/(2*a)) continue else: break print(str(a)+" "+str(b)) ```
MatrixStudio/Codeforces-Python-Submissions
Petya has noticed that when he types using a keyboard, he often presses extra buttons and adds extra letters to the words. Of course, the spell-checking system underlines the words for him and he has to click every word and choose the right variant. Petya got fed up with correcting his mistakes himself, that’s why he d...
```python # LUOGU_RID: 128693935 a=input();b=input();c=[] for i in range(len(a)): if a[:i]+a[i+1:]==b:c.append(i+1) print(len(c));print(str(c)[1:-1].replace(',','')) ```
MatrixStudio/Codeforces-Python-Submissions
The Little Elephant enjoys recursive functions. This time he enjoys the sorting function. Let *a* is a permutation of an integers from 1 to *n*, inclusive, and *a**i* denotes the *i*-th element of the permutation. The Little Elephant's recursive function *f*(*x*), that sorts the first *x* permutation's elements, works...
```python n = int(input()) per = [1] for i in range(2,n+1): x = per.index(i-1) per.append(per[x]) per[x] = i print(*per,sep=" ") ```
MatrixStudio/Codeforces-Python-Submissions
John Doe offered his sister Jane Doe find the gcd of some set of numbers *a*. Gcd is a positive integer *g*, such that all number from the set are evenly divisible by *g* and there isn't such *g*' (*g*'<=&gt;<=*g*), that all numbers of the set are evenly divisible by *g*'. Unfortunately Jane couldn't cope with the ta...
```python def read_integers(): return list(map(int, stdin.readline().strip().split())) _, = read_integers() input_arr = read_integers() print(input_arr) ```
MatrixStudio/Codeforces-Python-Submissions
It was recycling day in Kekoland. To celebrate it Adil and Bera went to Central Perk where they can take bottles from the ground and put them into a recycling bin. We can think Central Perk as coordinate plane. There are *n* bottles on the ground, the *i*-th bottle is located at position (*x**i*,<=*y**i*). Both Adil a...
```python from math import hypot ax, ay, bx, by, tx, ty = map(int, input().split()) n = int(input()) ans = 0 p1, p2, beg, end = [0]*n, [0]*n, [0]*n, [0]*n def pref(x): return beg[x] if x >= 0 else 0 def suff(x): return end[x] if x < n else 0 def ex(x): return max(pref(x-1), suff(x+1)...
MatrixStudio/Codeforces-Python-Submissions
Santa Claus is the first who came to the Christmas Olympiad, and he is going to be the first to take his place at a desk! In the classroom there are *n* lanes of *m* desks each, and there are two working places at each of the desks. The lanes are numbered from 1 to *n* from the left to the right, the desks in a lane ar...
```python import math n, m, k = map(int, input().split()) if k == 2 * n * m: print(n, m, 'R') else: print(math.ceil(k/(2 * m)), math.ceil((k//2)/m) , k%2*'L'+(1-k%2)*'R') ```
MatrixStudio/Codeforces-Python-Submissions
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like. Now let's imagine a typical morning in your family. You haven't w...
```python n=int(input()) s=0 l=[] for i in range(n): a=int(input()) s+=a l.append(a) l.sort() x=0 n=0 for i in reversed(range(len(l))): s-=l[i] x+=l[i] n+=1 if s<x:break print(n) ```
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 = int(input()) from math import sqrt def stepen(m): res = 1 for i in range(2, 4): for j in range(5, 9): if i ** j == m: res = 0 for i in range(2, 6): if m == i * i * i * i: res = 0 for i in range(2, 11): if m == ...
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 # import sys # sys.stdout = open('DSA/Stacks/output.txt', 'w') # sys.stdin = open('DSA/Stacks/input.txt', 'r') r, c = map(int, input().split()) ll = [] tot = 0 re = 0 st = 0 for i in range(r): row = list(input()) if "S" not in row: tot+=c re+=1 st+=row.count("S") ...