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 water again, so right now he's really messed up and can't think. Your task is to help him by telling him what to type.
```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(input()) if num == 100: print('one hundred') else: if num % 10 == 0 and num != 0: print(third[(num//10)-1]) else: if num > 19: num_str = str(num) de = int(num_str[0]) eg = int(num_str[1]) print(third[de-1]+'-'+first[eg]) else: if num%100 >=11<=19: print(second[num-11]) if num//10 == 0: print(first[num]) ```
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 of the game, Jury must use this second to touch the corresponding strip to make the square go away. As Jury is both smart and lazy, he counted that he wastes exactly *a**i* calories on touching the *i*-th strip. You've got a string *s*, describing the process of the game and numbers *a*1,<=*a*2,<=*a*3,<=*a*4. Calculate how many calories Jury needs to destroy all the squares?
```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 represents how many groups of black squares there are in corresponding row or column, and the integers themselves represents the number of consecutive black squares in corresponding group (you can find more detailed explanation in Wikipedia [https://en.wikipedia.org/wiki/Japanese_crossword](https://en.wikipedia.org/wiki/Japanese_crossword)). Adaltik decided that the general case of japanese crossword is too complicated and drew a row consisting of *n* squares (e.g. japanese crossword sized 1<=×<=*n*), which he wants to encrypt in the same way as in japanese crossword. Help Adaltik find the numbers encrypting the row he drew.
```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: Block_count += 1 if i == (len(color_squares)-1): counts.append(numB) else: if numB > 0: counts.append(numB) numB = 0 print(Block_count) print(' '.join(map(str, counts))) ```
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 his handle to become red. He considers his performance in the rated contest to be good if he outscored some participant, whose handle was colored red before the contest and his rating has increased after it. Anton has written a program that analyses contest results and determines whether he performed good or not. Are you able to do the same?
```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 each second. Let's describe the process more precisely. Let's say that the positions in the queue are sequentially numbered by integers from 1 to *n*, at that the person in the position number 1 is served first. Then, if at time *x* a boy stands on the *i*-th position and a girl stands on the (*i*<=+<=1)-th position, then at time *x*<=+<=1 the *i*-th position will have a girl and the (*i*<=+<=1)-th position will have a boy. The time is given in seconds. You've got the initial position of the children, at the initial moment of time. Determine the way the queue is going to look after *t* seconds.
```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 "codeforces", "reality", "ab" are not.
```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: print('NO') ```
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. The balls are numbered with numbers from 1 to *n*. Valeric decided to sort the balls in the order of increasing of their numbers by the following scheme. He will put each new ball in the basket with the least number of balls. And if he's got several variants, he chooses the basket which stands closer to the middle. That means that he chooses the basket for which is minimum, where *i* is the number of the basket. If in this case Valeric still has multiple variants, he chooses the basket with the minimum number. For every ball print the number of the basket where it will go according to Valeric's scheme. Note that the balls are sorted into baskets in the order of increasing numbers, that is, the first ball goes first, then goes the second ball and so on.
```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): if(e+1<=m): e=e+1 l.append(e) i=0 r=0 while(i<n): for j in range(m): r=r+1 if(r>n): break print(l[j]) i=i+m ```
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, waits the first train to come and rides on it to the end of the branch to the corresponding girl. However, the trains run with different frequencies: a train goes to Dasha's direction every *a* minutes, but a train goes to Masha's direction every *b* minutes. If two trains approach at the same time, Vasya goes toward the direction with the lower frequency of going trains, that is, to the girl, to whose directions the trains go less frequently (see the note to the third sample). We know that the trains begin to go simultaneously before Vasya appears. That is the train schedule is such that there exists a moment of time when the two trains arrive simultaneously. Help Vasya count to which girlfriend he will go more often.
```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-=1 if d>m: print('Dasha') elif d<m: print('Masha') else: print('Equal') ```
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 pairs of neighbouring cubes of the same color as possible. Vasya's task is to get as many pairs of neighbouring cubes of different colors as possible. The number of Petya's points in the game is the number of pairs of neighboring cubes of the same color in the line, the number of Vasya's points in the game is the number of neighbouring cubes of the different color in the line. Your task is to calculate the score at the end of the game (Petya's and Vasya's points, correspondingly), if both boys are playing optimally well. To "play optimally well" first of all means to maximize the number of one's points, and second — to minimize the number of the opponent's points.
```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') else: print('NO') ```
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. However, it's easy to make a mistake during the «translation». Vasya translated word *s* from Berlandish into Birlandish as *t*. Help him: find out if he translated the word correctly.
```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 number 0 doesn't contain any leading zeroes. Jeff doesn't have to use all the cards.
```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 was equal to *sum*; here *lowbit*(*x*) equals 2*k* where *k* is the position of the first one in the binary representation of *x*. For example, *lowbit*(100102)<==<=102,<=*lowbit*(100012)<==<=12,<=*lowbit*(100002)<==<=100002 (binary representation). Can you help Picks and find any set *S*, that satisfies all the above conditions?
```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 alternate turns. The first player wants to minimize the last number that would be left on the board, while the second player wants to maximize it. You want to know what number will be left on the board after $n - 1$ turns if both players make optimal moves.
```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 only one pipe with flowing water. Besides, Vova has several splitters. A splitter is a construction that consists of one input (it can be connected to a water pipe) and *x* output pipes. When a splitter is connected to a water pipe, water flows from each output pipe. You can assume that the output pipes are ordinary pipes. For example, you can connect water supply to such pipe if there's water flowing out from it. At most one splitter can be connected to any water pipe. Vova has one splitter of each kind: with 2, 3, 4, ..., *k* outputs. Help Vova use the minimum number of splitters to build the required pipeline or otherwise state that it's impossible. Vova needs the pipeline to have exactly *n* pipes with flowing out water. Note that some of those pipes can be the output pipes of the splitters.
```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 holding the ball. First the first child throws the ball to the next one clockwise, i.e. to the child number 2. Then the child number 2 throws the ball to the next but one child, i.e. to the child number 4, then the fourth child throws the ball to the child that stands two children away from him, i.e. to the child number 7, then the ball is thrown to the child who stands 3 children away from the child number 7, then the ball is thrown to the child who stands 4 children away from the last one, and so on. It should be mentioned that when a ball is thrown it may pass the beginning of the circle. For example, if *n*<==<=5, then after the third throw the child number 2 has the ball again. Overall, *n*<=-<=1 throws are made, and the game ends. The problem is that not all the children get the ball during the game. If a child doesn't get the ball, he gets very upset and cries until Natalia Pavlovna gives him a candy. That's why Natalia Pavlovna asks you to help her to identify the numbers of the children who will get the ball after each throw.
```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. The stove switches on and off instantly. It is known that the chicken needs *t* minutes to be cooked on the stove, if it is turned on, and 2*t* minutes, if it is turned off. You need to find out, how much time will Julia have to cook the chicken, if it is considered that the chicken is cooked evenly, with constant speed when the stove is turned on and at a constant speed when it is turned off.
```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 dt1=t//dt*nok else: dt1=0 st,i=1,1 while dt1<t: if i%k==0: st=0 if i%d==0: st=1 dt1,i=dt1+0.5+0.5*st,i+1 print(dt1) ```
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 than *d* meters, where *d* is some non-negative integer. Vasya would like the advantage of the points scored by the first team (the points of the first team minus the points of the second team) to be maximum. For that he can mentally choose the value of *d*. Help him to do that.
```python ###### ### ####### ####### ## # ##### ### ##### # # # # # # # # # # # # # ### # # # # # # # # # # # # # ### ###### ######### # # # # # # ######### # ###### ######### # # # # # # ######### # # # # # # # # # # # #### # # # # # # # # # # ## # # # # # ###### # # ####### ####### # # ##### # # # # # from __future__ import print_function # for PyPy2 from itertools import permutations as perm # from fractions import Fraction from collections import * from sys import stdin from bisect import * from heapq import * from math import * g = lambda : stdin.readline().strip() gl = lambda : g().split() gil = lambda : [int(var) for var in gl()] gfl = lambda : [float(var) for var in gl()] gcl = lambda : list(g()) gbs = lambda : [int(var) for var in g()] mod = int(1e9)+7 inf = float("inf") na, = gil() a = set(gil()) nb, = gil() b = set(gil()) c = list(a|b) c.sort() nc = len(c) # .. 2 2 2 2 3 3 3 3 .. l = [] for i in range(nc): ap, bp = l[-1] if l else (0, 0) if c[i] in a: ap += 2 if c[i] in b: bp += 2 l.append([ap, bp]) r = [None for _ in range(nc)] for i in reversed(range(nc)): an, bn = r[i+1] if i+1 < nc else (0, 0) if c[i] in a: an += 3 if c[i] in b: bn += 3 r[i] = [an, bn] ans = max(r[0], l[-1], key=lambda x : x[0]-x[1]) for i in range(nc-1): asum, bsum = l[i] asum += r[i+1][0] bsum += r[i+1][1] ans = max(ans, [asum, bsum], key=lambda x : x[0]-x[1]) ans = tuple(ans) print("%d:%d"%ans) ```
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 the number of 2-3-integers on the given segment [*l*,<=*r*], i. e. the number of sich 2-3-integers *t* that *l*<=≤<=*t*<=≤<=*r*.
```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 / 2 print(answer) ```
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, and so on, the *m*-th face contains *m* dots. Twilight Sparkle is sure that when the dice is tossed, each face appears with probability . Also she knows that each toss is independent from others. Help her to calculate the expected maximum number of dots she could get after tossing the dice *n* times.
```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 calculations faster than him. As a result he made a very great contest and asked every one to come and take part. In his contest he gave the contestants many different pairs of numbers. Each number is made from digits 0 or 1. The contestants should write a new number corresponding to the given pair of numbers. The rule is simple: The *i*-th digit of the answer is 1 if and only if the *i*-th digit of the two given numbers differ. In the other case the *i*-th digit of the answer is 0. Shapur made many numbers and first tried his own speed. He saw that he can perform these operations on numbers of length ∞ (length of a number is number of digits in it) in a glance! He always gives correct answers so he expects the contestants to give correct answers, too. He is a good fellow so he won't give anyone very big numbers and he always gives one person numbers of same length. Now you are going to take part in Shapur's contest. See if you are faster and more accurate.
```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 queries. Each query is represented as two integers $l$ and $r$. The answer is the maximum value of $f$ on all continuous subsegments of the array $a_l, a_{l+1}, \ldots, a_r$.
```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, tamanho): for j in range(tamanho-i): matrix[i][j] = max(matrix[i][j], matrix[i-1][j], matrix[i-1][j+1]) num_buscas = int(input()) for i in range(num_buscas): busca_l, busca_r = map(int, input().split()) busca_l, busca_r = busca_l-1, busca_r-1 print(matrix[busca_r-busca_l][busca_l]) ```
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 Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square.
```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 also threw part of the pieces away. Having seen this, Vasya got terrified but still tried to restore the collection. He chose several piece pairs and glued each pair together so that each pair formed a lucky ticket. The rest of the pieces Vasya threw away reluctantly. Thus, after the gluing of the 2*t* pieces he ended up with *t* tickets, each of which was lucky. When Leonid tore the tickets in two pieces, one piece contained the first several letters of his number and the second piece contained the rest. Vasya can glue every pair of pieces in any way he likes, but it is important that he gets a lucky ticket in the end. For example, pieces 123 and 99 can be glued in two ways: 12399 and 99123. What maximum number of tickets could Vasya get after that?
```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_tokens = [] for p in tokens: sum_tokens.append(sum_digits(p)) # print(sum_tokens) res = [0,0,0] for s in sum_tokens: res[s % 3] = res[s % 3] + 1 # print(res) print(res[0]//2+min(res[1],res[2])) ```
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 looks. Heidi is presented with a screen that shows her a sequence of integers *A* and a positive integer *p*. She knows that the encryption code is a single number *S*, which is defined as follows: Define the score of *X* to be the sum of the elements of *X* modulo *p*. Heidi is given a sequence *A* that consists of *N* integers, and also given an integer *p*. She needs to split *A* into 2 parts such that: - Each part contains at least 1 element of *A*, and each part consists of contiguous elements of *A*. - The two parts do not overlap. - The total sum *S* of the scores of those two parts is maximized. This is the encryption code. Output the sum *S*, which is the encryption code.
```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 that this player lost. As soon as Sereja's friends heard of the game, they wanted to play it. Sereja, on the other hand, wanted to find out whether his friends can play the game in such a way that there are no losers. You are given the volumes of all mugs and the cup. Also, you know that Sereja has (*n*<=-<=1) friends. Determine if Sereja's friends can play the game so that nobody loses.
```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 from Wikipedia (http://en.wikipedia.org/wiki/Triangular_number). Your task is to find out if a given integer is a triangular number.
```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 practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments. After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process. Leonid offers to divide the labor — he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
```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.append(num) H.sort() h = np.max(np.diff(H)) v = np.max(np.diff(V)) ar.append(h * v) else: V.append(num) V.sort() h = np.max(np.diff(H)) v = np.max(np.diff(V)) ar.append(h * v) for i in ar: print(i) ```
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 maximum number of times "VK" can appear as a substring (i. e. a letter "K" right after a letter "V") in the resulting string.
```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 += 1 i += 1 print(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 city (because if they live in the same city, then it is easier to drop in). Strange but true, the cost of sending the letter is exactly equal to the distance between the sender's city and the recipient's city. For each city calculate two values ​​*min**i* and *max**i*, where *min**i* is the minimum cost of sending a letter from the *i*-th city to some other city, and *max**i* is the the maximum cost of sending a letter from the *i*-th city to some other city
```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) smallest = (x[-1] + q) - (x[-2] + q) else: biggest = max((x[-1] + q) - (x[i] + q), (x[i] + q) - (x[0] + q)) smallest = min((x[i] + q) - (x[i - 1] + q), (x[i + 1] + q) - (x[i] + q)) print(smallest, biggest) ```
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* and *p**i* — the size of the group of visitors who will come via this request and the total sum of money they will spend in the restaurant, correspondingly. We know that for each request, all *c**i* people want to sit at the same table and are going to spend the whole evening in the restaurant, from the opening moment at 18:00 to the closing moment. Unfortunately, there only are *k* tables in the restaurant. For each table, we know *r**i* — the maximum number of people who can sit at it. A table can have only people from the same group sitting at it. If you cannot find a large enough table for the whole group, then all visitors leave and naturally, pay nothing. Your task is: given the tables and the requests, decide which requests to accept and which requests to decline so that the money paid by the happy and full visitors was maximum.
```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[ind1][0] <= r[ind2]: ind2 += 1 ans.append(l1[ind1][1]) val.append(l1[ind1][0]) ind1 += 1 print(len(ans), sum(ans)) for i in range(len(l)): v = l[i][0] if v in val: print(i + 1, pos) pos += 1 del val[val.index(v)] ```
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 independently come up with the coordinate to which that ship will jump. In the obsolete navigation system used by the Rebels, this coordinate is given as the value of an arithmetic expression of the form . To plan the future of the resistance movement, Princess Heidi needs to know, for each ship, how many ships are going to end up at the same coordinate after the jump. You are her only hope!
```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 dis*=10 if (((dis+10)*a/b)%1.== (dis*a/b)%1.0): print(-1) x=True break if x: break else: print(-1) ```
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*<=≤<=*n*), and you should tell her . 1. Let *u**i* be the cost of the *i*-th cheapest stone (the cost that will be on the *i*-th place if we arrange all the stone costs in non-decreasing order). This time she will tell you two numbers, *l* and *r* (1<=≤<=*l*<=≤<=*r*<=≤<=*n*), and you should tell her . For every question you should give the correct answer, or Kuriyama Mirai will say "fuyukai desu" and then become unhappy.
```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) rss += sorted_costs[i] rs_sorted.append(rss) for q in range(m): type, l, r = [int(x) for x in input().split()] if type == 1: print(rs_costs[r]-rs_costs[l-1]) else: print(rs_sorted[r]-rs_sorted[l-1]) if __name__ == "__main__": main() ```
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/wiki/King_(chess)).
```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 results. Find out how the deminations of the coins differ or if Vasya has a mistake in the weighting results. No two coins are equal.
```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, right = add(left, right, first) left, right = add(left, right, secon) left, right = add(left, right, third) letter = ["A", "B", "C"] small = '' mid = '' larger = '' secmid = '' for l in letter: if left[l] == 2: small = l elif left[l] == 1: mid = l if not small or not mid: print("Impossible") else: for l in letter: if right[l] == 2: larger = l if right[l] == 1: secmid = l if not larger or not secmid: print("Impossible") elif secmid == mid and small != larger: print(small + mid + larger) else: print("Impossible") ```
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 the *i*-th task, she needs to be in the house number *a**i* and complete all tasks with numbers less than *i*. Initially, Xenia is in the house number 1, find the minimum time she needs to complete all her tasks if moving from a house to a neighboring one along the ringroad takes one unit of time.
```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 calculations faster than him. As a result he made a very great contest and asked every one to come and take part. In his contest he gave the contestants many different pairs of numbers. Each number is made from digits 0 or 1. The contestants should write a new number corresponding to the given pair of numbers. The rule is simple: The *i*-th digit of the answer is 1 if and only if the *i*-th digit of the two given numbers differ. In the other case the *i*-th digit of the answer is 0. Shapur made many numbers and first tried his own speed. He saw that he can perform these operations on numbers of length ∞ (length of a number is number of digits in it) in a glance! He always gives correct answers so he expects the contestants to give correct answers, too. He is a good fellow so he won't give anyone very big numbers and he always gives one person numbers of same length. Now you are going to take part in Shapur's contest. See if you are faster and more accurate.
```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 List of Characters, instead of a string, which is easier to use in Python, because in Python, Strings are Immutable. def insr(): s = input() return(list(s[:len(s) - 1])) # — For taking space seperated integer variable inputs. def invr(): return(map(int,input().split())) # -------------------------------------------------- first_in = input().strip() second_in = input().strip() return_str = "" for i in range(len(first_in)): if first_in[i] == second_in[i]: return_str += "0" else: return_str += "1" print(return_str) ```
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 rectangles form a square. In other words, determine if the set of points inside or on the border of at least one rectangle is precisely equal to the set of points inside or on the border of some square.
```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 of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order. Help Kefa cope with this task!
```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 check. Web-developers of the company Q assume that a password is complex enough, if it meets all of the following conditions: - the password length is at least 5 characters; - the password contains at least one large English letter; - the password contains at least one small English letter; - the password contains at least one digit. You are given a password. Please implement the automatic check of its complexity for company Q.
```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(): digit = True if upper == lower == digit == True: print("Correct") else: print("Too Weak") ```
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 one bottle to open multiple other bottles. Sereja can open bottle with opened bottle or closed bottle. Knowing this, Sereja wants to find out the number of bottles they've got that they won't be able to open in any way. Help him and find this number.
```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 Berland). You are the royal treasurer, which needs to count the minimum charges of the kingdom on the king's present. The king can only give money, he hasn't a power to take away them.
```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. The trainer swaps the animals in pairs not to create a mess. He orders two animals to step out of the circle and swap places. As hamsters feel highly uncomfortable when tigers are nearby as well as tigers get nervous when there's so much potential prey around (consisting not only of hamsters but also of yummier spectators), the trainer wants to spend as little time as possible moving the animals, i.e. he wants to achieve it with the minimal number of swaps. Your task is to help him.
```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].count("T") # Initialize the minimum swaps required to be the number of tigers within the first window min_swaps = initial_tiger_count # Slide the window and update the minimum swaps for i in range(1, n): if positions[i - 1] == "T": initial_tiger_count -= 1 if positions[(i + num_hamsters - 1) % n] == "T": initial_tiger_count += 1 min_swaps = min(min_swaps, initial_tiger_count) # The minimum swaps required is the number of tigers within the first window # that need to be moved to group all tigers together return min_swaps # Read input n = int(input()) positions = input().strip() # Calculate and print the result result = min_swaps_to_group_animals(n, positions) print(result) ```
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, if Vasya types the word "ahhellllloou", it will be considered that he said hello, and if he types "hlelo", it will be considered that Vasya got misunderstood and he didn't manage to say hello. Determine whether Vasya managed to say hello by the given word *s*.
```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 the maximum possible least common multiple of these three integers?
```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 *a* and *b* such that *l*<=≤<=*a*<=≤<=*r* and *x*<=≤<=*b*<=≤<=*y* there is a potion with experience *a* and cost *b* in the store (that is, there are (*r*<=-<=*l*<=+<=1)·(*y*<=-<=*x*<=+<=1) potions). Kirill wants to buy a potion which has efficiency *k*. Will he be able to do this?
```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 of one of them and not a subsequence of the other. A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings "ac", "bc", "abc" and "a" are subsequences of string "abc" while strings "abbc" and "acb" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.
```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 items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering. You have been given information on current inventory numbers for *n* items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to *n* by changing the number of as few items as possible. Let us remind you that a set of *n* numbers forms a permutation if all the numbers are in the range from 1 to *n*, and no two numbers are equal.
```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(bads): i = bads.pop() inventory[i] = num bool[num] = True print(" ".join([*map(str, inventory)])) ```
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*'<==<=*y* - point (*x*',<=*y*') is (*x*,<=*y*)'s left neighbor, if *x*'<=&lt;<=*x* and *y*'<==<=*y* - point (*x*',<=*y*') is (*x*,<=*y*)'s lower neighbor, if *x*'<==<=*x* and *y*'<=&lt;<=*y* - point (*x*',<=*y*') is (*x*,<=*y*)'s upper neighbor, if *x*'<==<=*x* and *y*'<=&gt;<=*y* We'll consider point (*x*,<=*y*) from the given set supercentral, if it has at least one upper, at least one lower, at least one left and at least one right neighbor among this set's points. Vasya marked quite many points on the paper. Analyzing the picture manually is rather a challenge, so Vasya asked you to help him. Your task is to find the number of supercentral points in the given set.
```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) if(sub_dot[0]==main_dot[0] and sub_dot[1]>main_dot[1]): u = 1 if(sub_dot[0]==main_dot[0] and sub_dot[1]<main_dot[1]): d = 1 if(sub_dot[1]==main_dot[1] and sub_dot[0]<main_dot[0]): l = 1 if(sub_dot[1]==main_dot[1] and sub_dot[0]>main_dot[0]): r = 1 if(l+r+u+d==4): c+=1 print(c) ```
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 the rating of *i*-th student as *a**i*. After the contest ends, every student will end up with some positive integer position. GukiZ expects that his students will take places according to their ratings. He thinks that each student will take place equal to . In particular, if student *A* has rating strictly lower then student *B*, *A* will get the strictly better position than *B*, and if two students have equal ratings, they will share the same position. GukiZ would like you to reconstruct the results by following his expectations. Help him and determine the position after the end of the contest for each of his students if everything goes as expected.
```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 oddly shaped, interlocking and tessellating pieces). The shop assistant told the teacher that there are *m* puzzles in the shop, but they might differ in difficulty and size. Specifically, the first jigsaw puzzle consists of *f*1 pieces, the second one consists of *f*2 pieces and so on. Ms. Manana doesn't want to upset the children, so she decided that the difference between the numbers of pieces in her presents must be as small as possible. Let *A* be the number of pieces in the largest puzzle that the teacher buys and *B* be the number of pieces in the smallest such puzzle. She wants to choose such *n* puzzles that *A*<=-<=*B* is minimum possible. Help the teacher and find the least possible value of *A*<=-<=*B*.
```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. Swap two neighboring matrix rows, that is, rows with indexes *i* and *i*<=+<=1 for some integer *i* (1<=≤<=*i*<=&lt;<=5). 1. Swap two neighboring matrix columns, that is, columns with indexes *j* and *j*<=+<=1 for some integer *j* (1<=≤<=*j*<=&lt;<=5). You think that a matrix looks beautiful, if the single number one of the matrix is located in its middle (in the cell that is on the intersection of the third row and the third column). Count the minimum number of moves needed to make the matrix beautiful.
```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 (locationOfOnei > 2): numberOfMoves += 1 locationOfOnei -= 1 if (locationOfOnei < 2): numberOfMoves += 1 locationOfOnei += 1 if (locationOfOnej > 2): numberOfMoves += 1 locationOfOnej -= 1 if (locationOfOnej < 2): numberOfMoves += 1 locationOfOnej += 1 print(numberOfMoves) arr1 = input() arr1 = list(map(int,arr1.split(' '))) arr2 = input() arr2 = list(map(int,arr2.split(' '))) arr3 = input() arr3 = list(map(int,arr3.split(' '))) arr4 = input() arr4 = list(map(int,arr4.split(' '))) arr5 = input() arr5 = list(map(int,arr5.split(' '))) arr = [arr1, arr2, arr3, arr4, arr5] checkMatrix(arr) ```
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 that. The box's lock looks as follows: it contains 4 identical deepenings for gems as a 2<=×<=2 square, and some integer numbers are written at the lock's edge near the deepenings. The example of a lock is given on the picture below. The box is accompanied with 9 gems. Their shapes match the deepenings' shapes and each gem contains one number from 1 to 9 (each number is written on exactly one gem). The box will only open after it is decorated with gems correctly: that is, each deepening in the lock should be filled with exactly one gem. Also, the sums of numbers in the square's rows, columns and two diagonals of the square should match the numbers written at the lock's edge. For example, the above lock will open if we fill the deepenings with gems with numbers as is shown on the picture below. Now Vasilisa the Wise wants to define, given the numbers on the box's lock, which gems she should put in the deepenings to open the box. Help Vasilisa to solve this challenging task.
```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* queries on a piece of paper. Each query has the following form: *x**i*, *y**i*, (1<=≤<=*x**i*<=≤<=*y**i*<=≤<=*m*). That means that one should apply operations with numbers *x**i*,<=*x**i*<=+<=1,<=...,<=*y**i* to the array. Now Greg is wondering, what the array *a* will be after all the queries are executed. Help Greg.
```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.insert(0,0) for i in range(m): op.append(list(map(int, input().split()))) Q = [0]* (n+1) for i in range(k): x, y = map(int, input().split()) add_range(x, y, Q, 1) calculate_sum(Q) out= [0] * (n+1) for i in range(1, len(Q)): if Q[i] != 0: add_range(op[i-1][0], op[i-1][1], out, Q[i]*op[i-1][2]) #Q[i]+= arr[i] calculate_sum(out) for i in range(1, len(out)): out[i]+= arr[i] print(out[i], end=" ") ```
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 of steps with even and odd numbers. You need to check whether there is an interval of steps from the *l*-th to the *r*-th (1<=≤<=*l*<=≤<=*r*), for which values that Dasha has found are correct.
```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 minimum sum of money she will have to spend to make *n* rides?
```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. One night, when everyone went to bed, someone took all the letters of our characters' names. Then he may have shuffled the letters and put them in one pile in front of the door. The next morning it was impossible to find the culprit who had made the disorder. But everybody wondered whether it is possible to restore the names of the host and his guests from the letters lying at the door? That is, we need to verify that there are no extra letters, and that nobody will need to cut more letters. Help the "New Year and Christmas Men" and their friends to cope with this problem. You are given both inscriptions that hung over the front door the previous night, and a pile of letters that were found at the front door next morning.
```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 betting decisions, he/she may only do so if all other players have a status of either "ALLIN" or "FOLDED". The player's own status may be either "ALLIN" or "IN". Find the number of cows that can currently show their hands without affecting any betting decisions.
```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 there are at least 7 players of some team standing one after another, then the situation is considered dangerous. For example, the situation 00100110111111101 is dangerous and 11110111011101 is not. You are given the current situation. Determine whether it is dangerous or not.
```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 up entangled and now have to be untangled again. The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut. To understand the problem better please read the notes to the test samples.
```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 that as little as possible letters should be changed in the word. For example, the word HoUse must be replaced with house, and the word ViP — with VIP. If a word contains an equal number of uppercase and lowercase letters, you should replace all the letters with lowercase ones. For example, maTRIx should be replaced by matrix. Your task is to use the given method on one given word.
```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 as follows: In the above formula, 1<=≤<=*l*<=&lt;<=*r*<=≤<=*n* must hold, where *n* is the size of the Main Uzhlyandian Array *a*, and |*x*| means absolute value of *x*. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of *f* among all possible values of *l* and *r* for the given array *a*.
```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 this string is a pangram. We say that the string contains a letter of the Latin alphabet if this letter occurs in the string in uppercase or lowercase.
```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 in spanning tree.
```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_edge_found): min_weight = inf min_node_idx = 0 for node in v: if not req_edge_found and (node == req_edge[0] and req_edge[1] in m) or (node == req_edge[1] and req_edge[0] in m): min_weight = v[node] min_node_idx = node req_edge_found = True break if v[node] < min_weight: min_weight = v[node] min_node_idx = node return req_edge_found, min_node_idx def mst(req_edge): min_sum = 0 m = set() # MST Set. If node is part of current MST, added to this set. # v = {1: 0} # Visitable map. If a node is visitable, it's value and weight (minimum) exists here. Complement of MST set v = {req_edge[0]: 0} req_edge_found = False while len(m) < n: req_edge_found, next_node = get_min_weight_visitable_node(v, m, req_edge, req_edge_found) min_sum += v[next_node] v.pop(next_node, None) # Once added to MST, it is no longer visitable m.add(next_node) for nbr, wght in adj[next_node]: if nbr not in m and (nbr not in v or wght < v[nbr]): # Maybe another condition needed here? v[nbr] = wght return min_sum ans = [] for req_edge in req_edges: ans.append(mst(req_edge)) print('\n'.join(map(str, ans))) ```
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 he has found extra-terrestrial intelligence if there is a system in the way the signals has been received, i.e. if all the intervals between successive signals are equal. Otherwise, Vasya thinks that the signals were sent by some stupid aliens no one cares about. Help Vasya to deduce from the information given by the receiver if he has found extra-terrestrial intelligence or not.
```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 that as little as possible letters should be changed in the word. For example, the word HoUse must be replaced with house, and the word ViP — with VIP. If a word contains an equal number of uppercase and lowercase letters, you should replace all the letters with lowercase ones. For example, maTRIx should be replaced by matrix. Your task is to use the given method on one given word.
```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 number of words "WUB" before the first word of the song (the number may be zero), after the last word (the number may be zero), and between words (at least one between any pair of neighbouring words), and then the boy glues together all the words, including "WUB", in one string and plays the song at the club. For example, a song with words "I AM X" can transform into a dubstep remix as "WUBWUBIWUBAMWUBWUBX" and cannot transform into "WUBWUBIAMWUBX". Recently, Petya has heard Vasya's new dubstep track, but since he isn't into modern music, he decided to find out what was the initial song that Vasya remixed. Help Petya restore the original song.
```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 is different in evenness.
```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 is held by another kangaroo cannot hold any kangaroos. The kangaroo who is held by another kangaroo cannot be visible from outside. Please, find a plan of holding kangaroos with the minimal number of kangaroos who is visible.
```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: q.append(a[i]) print(l+len(q)) ```
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 # print(fract1) # print(fract2) if fract1 == a or fract2 == a: print("YES") else: print("NO") ```
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 teleport it either to the beginning of the train, or to the end of the train, at his desire. What is the minimum number of actions David Blaine needs to perform in order to sort the train?
```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 understand that. All the twelve months in Vasya's calendar are named using their usual English names: January, February, March, April, May, June, July, August, September, October, November, December.
```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", "June", "July", "August", "September", "October", "November", "December" ] current_month = input() months_left = int(input()) print(num_to_month[(months_left+month_to_num[current_month]) % 12]) ```
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 sq += 1 print(sq) ```
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 the end, Polycarpus got a list of *n* tasks that went to the SMSC of the corporation. Each task was described by the time it was received by the SMSC and the number of text messages to send. More formally, the *i*-th task was described by two integers *t**i* and *c**i* — the receiving time (the second) and the number of the text messages, correspondingly. Polycarpus knows that the SMSC cannot send more than one text message per second. The SMSC uses a queue to organize its work. Consider a time moment *x*, the SMSC work at that moment as follows: 1. If at the time moment *x* the queue is not empty, then SMSC sends one message from the queue (SMSC gets the message from the head of the queue). Otherwise it doesn't send messages at the time moment *x*. 1. If at the time moment *x* SMSC receives a task, then it adds to the queue all the messages from this task (SMSC adds messages to the tail of the queue). Note, that the messages from the task cannot be send at time moment *x*. That's because the decision about sending message or not is made at point 1 before adding these messages to the queue. Given the information about all *n* tasks, Polycarpus wants to count two values: the time when the last text message was sent and the maximum size of the queue at some time. Help him count these two characteristics he needs to evaluate the efficiency of the SMSC.
```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, staying down is a choice # Location: Mashhad for few days # Caption: Finally happened what should be happened # CodeNumber: 692 ```
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. - Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of *n* polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
```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 lot of colourful pictures on colored and black-and-white film. Then he developed and translated it into a digital form. But now, color and black-and-white photos are in one folder, and to sort them, one needs to spend more than one hour! As soon as Brain is a photographer not programmer now, he asks you to help him determine for a single photo whether it is colored or black-and-white. Photo can be represented as a matrix sized *n*<=×<=*m*, and each element of the matrix stores a symbol indicating corresponding pixel color. There are only 6 colors: - 'C' (cyan)- 'M' (magenta)- 'Y' (yellow)- 'W' (white)- 'G' (grey)- 'B' (black) The photo is considered black-and-white if it has only white, black and grey pixels in it. If there are any of cyan, magenta or yellow pixels in the photo then it is considered colored.
```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): print('#Color') else: print('#Black&White') ```
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. A year is leap in one of two cases: either its number is divisible by 4, but not divisible by 100, or is divisible by 400. For example, the following years are leap: 2000, 2004, but years 1900 and 2018 are not leap. In this problem you are given *n* (1<=≤<=*n*<=≤<=24) integers *a*1,<=*a*2,<=...,<=*a**n*, and you have to check if these integers could be durations in days of *n* consecutive months, according to Gregorian calendar. Note that these months could belong to several consecutive years. In other words, check if there is a month in some year, such that its duration is *a*1 days, duration of the next month is *a*2 days, and so on.
```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 difference is maximal possible! Your task is to write a program which calculates two things: 1. The maximum beauty difference of flowers that Pashmak can give to Parmida. 1. The number of ways that Pashmak can pick the flowers. Two ways are considered different if and only if there is at least one flower that is chosen in the first way and not chosen in the second way.
```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 Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence. Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring. Substring is a continuous subsequence of a string.
```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 all uppercase consonants with corresponding lowercase ones. Vowels are letters "A", "O", "Y", "E", "U", "I", and the rest are consonants. The program's input is exactly one string, it should return the output as a single string, resulting after the program's processing the initial string. Help Petya cope with this easy task.
```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 from the heap the number of stones equal to the greatest common divisor of the fixed number he has received and the number of stones left in the heap. A player loses when he cannot take the required number of stones (i. e. the heap has strictly less stones left than one needs to take). Your task is to determine by the given *a*, *b* and *n* who wins the game.
```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 elif ans == 1 and n % b != 0 and n-1 >= 0: n = n-1 ans = 0 else: break if ans == 1: print(0) else: print(1) ```
MatrixStudio/Codeforces-Python-Submissions
Theatre Square in the capital city of Berland has a rectangular shape with the size *n*<=×<=*m* meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size *a*<=×<=*a*. What is the least number of flagstones needed to pave the Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square.
```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 are not under its influence. He has names of *n* people who possessed the diary in order. You need to tell, for each person, if he/she possessed the diary at some point before or not. Formally, for a name *s**i* in the *i*-th line, output "YES" (without quotes) if there exists an index *j* such that *s**i*<==<=*s**j* and *j*<=&lt;<=*i*, otherwise, output "NO" (without quotes).
```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 he visited in a row, in order of visiting them. Now, Vlad wants to find such a cafe that his last visit to that cafe was before his last visits to every other cafe. In other words, he wants to find such a cafe that he hasn't been there for as long as possible. Help Vlad to find that cafe.
```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 be at the bottom of the tower, while small snacks should be at the top. Years passed, and once different snacks started to fall onto the city, and the residents began to build the Snacktower. However, they faced some troubles. Each day exactly one snack fell onto the city, but their order was strange. So, at some days the residents weren't able to put the new stack on the top of the Snacktower: they had to wait until all the bigger snacks fell. Of course, in order to not to anger miss Fortune again, the residents placed each snack on the top of the tower immediately as they could do it. Write a program that models the behavior of Ankh-Morpork residents.
```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) print(*empilhado, sep=' ') proximo = empilhado[-1]-1 empilhado.clear() else: print('') ```
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 set the value of *b* to *b*<=-<=2·*a*, and repeat step 1. Otherwise, end the process. Initially the values of *a* and *b* are positive integers, and so the process will be finite. You have to determine the values of *a* and *b* after the process ends.
```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 decided to invent the function that will correct the words itself. Petya started from analyzing the case that happens to him most of the time, when all one needs is to delete one letter for the word to match a word from the dictionary. Thus, Petya faces one mini-task: he has a printed word and a word from the dictionary, and he should delete one letter from the first word to get the second one. And now the very non-trivial question that Petya faces is: which letter should he delete?
```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 as follows: - If *x*<==<=1, exit the function. - Otherwise, call *f*(*x*<=-<=1), and then make *swap*(*a**x*<=-<=1,<=*a**x*) (swap the *x*-th and (*x*<=-<=1)-th elements of *a*). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to *n*, such that after performing the Little Elephant's function (that is call *f*(*n*)), the permutation will be sorted in ascending order.
```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 task and John offered her to find the ghd of the same subset of numbers. Ghd is a positive integer *g*, such that at least half of numbers from the set are evenly divisible by *g* and there isn't such *g*' (*g*'<=&gt;<=*g*) that at least half of the numbers from the set are evenly divisible by *g*'. Jane coped with the task for two hours. Please try it, too.
```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 and Bera can carry only one bottle at once each. For both Adil and Bera the process looks as follows: 1. Choose to stop or to continue to collect bottles. 1. If the choice was to continue then choose some bottle and walk towards it. 1. Pick this bottle and walk to the recycling bin. 1. Go to step 1. Adil and Bera may move independently. They are allowed to pick bottles simultaneously, all bottles may be picked by any of the two, it's allowed that one of them stays still while the other one continues to pick bottles. They want to organize the process such that the total distance they walk (the sum of distance walked by Adil and distance walked by Bera) is minimum possible. Of course, at the end all bottles should lie in the recycling bin.
```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)) for i in range(n): x, y = map(int, input().split()) d = hypot(x-tx, y-ty) d1 = hypot(x-ax, y-ay) d2 = hypot(x-bx, y-by) ans += d+d p1[i], p2[i] = d-d1, d-d2 beg[0] = p1[0] for i in range(1, n): beg[i] = max(beg[i-1], p1[i]) end[n-1] = p1[n-1] for i in range(n-2, -1, -1): end[i] = max(end[i+1], p1[i]) res = 1e220 for i in range(0, n): res = min(res, min(ans-p2[i]-ex(i), ans-max(p1[i], p2[i]))) print(res) ```
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 are numbered from 1 to *m* starting from the blackboard. Note that the lanes go perpendicularly to the blackboard, not along it (see picture). The organizers numbered all the working places from 1 to 2*nm*. The places are numbered by lanes (i. e. all the places of the first lane go first, then all the places of the second lane, and so on), in a lane the places are numbered starting from the nearest to the blackboard (i. e. from the first desk in the lane), at each desk, the place on the left is numbered before the place on the right. Santa Clause knows that his place has number *k*. Help him to determine at which lane at which desk he should sit, and whether his place is on the left or on the right!
```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 woken up yet, and Mom is already going to work. She has been so hasty that she has nearly forgotten to leave the two of her darling children some money to buy lunches in the school cafeteria. She fished in the purse and found some number of coins, or to be exact, *n* coins of arbitrary values *a*1,<=*a*2,<=...,<=*a**n*. But as Mom was running out of time, she didn't split the coins for you two. So she scribbled a note asking you to split the money equally. As you woke up, you found Mom's coins and read her note. "But why split the money equally?" — you thought. After all, your twin is sleeping and he won't know anything. So you decided to act like that: pick for yourself some subset of coins so that the sum of values of your coins is strictly larger than the sum of values of the remaining coins that your twin will have. However, you correctly thought that if you take too many coins, the twin will suspect the deception. So, you've decided to stick to the following strategy to avoid suspicions: you take the minimum number of coins, whose sum of values is strictly more than the sum of values of the remaining coins. On this basis, determine what minimum number of coins you need to take to divide them in the described manner.
```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 ask no questions), and then Vasya responds to each question with a 'yes' or a 'no'. After receiving all the answers Petya should determine the number that Vasya thought of. Unfortunately, Petya is not familiar with the number theory. Help him find the minimum number of questions he should ask to make a guaranteed guess of Vasya's number, and the numbers *y**i*, he should ask the questions about.
```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 == i * i * i: res = 0 for i in range(2, 32): if m == i * i: res = 0 return res y ='' sum = 0 if n == 1: print(0) else: for i in range(2, n + 1): k = 0 for j in range(2, int(sqrt(i))+1): if i % j == 0 and bool(stepen(i)): k = 1 break if k == 0: sum = sum + 1 y = y + str(i) + ' ' print(sum) print(y) ```
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 at least one cake cell that has not been eaten before, and eats all the cake cells there. He may decide to eat any number of times. Please output the maximum number of cake cells that the cakeminator can eat.
```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") ll.append(row) for i in range(c): flag = True for j in range(r): if ll[j][i]=="S": flag = False if flag: tot+=r print(tot-st) ```