source
stringclasses
3 values
instruction
stringlengths
23
3.97k
input
stringclasses
1 value
output
stringlengths
1
3.75k
MatrixStudio/Codeforces-Python-Submissions
The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has *n* students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times. Th...
```python ######################################################################## "#######################################################################" ######################################################################## "Author = Fasih_ur_Rehman" #| <>"" <>"" <>"" <>"" <>"" <>"" <>"" ...
MatrixStudio/Codeforces-Python-Submissions
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed *w* kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem. Pete and ...
```python def watermelon(w): if w%2 == 0 and w >= 1 and w <= 100: return("YES") else: return("NO") w = int(input()) print(watermelon(w)) ```
MatrixStudio/Codeforces-Python-Submissions
Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone. In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules o...
```python strips = list(map(int, input().split())) seconds = list(map(int, input())) result = sum([strips[i - 1] for i in seconds]) print(result) ```
MatrixStudio/Codeforces-Python-Submissions
During the winter holidays, the demand for Christmas balls is exceptionally high. Since it's already 2018, the advances in alchemy allow easy and efficient ball creation by utilizing magic crystals. Grisha needs to obtain some yellow, green and blue balls. It's known that to produce a yellow ball one needs two yellow ...
```python ο»Ώusing System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _1 { class Program { static void Main(string[] args) { string S = Console.ReadLine(); string[] Mas = S.Split(' '); ...
MatrixStudio/Codeforces-Python-Submissions
Once again Tavas started eating coffee mix without water! Keione told him that it smells awful, but he didn't stop doing that. That's why Keione told his smart friend, SaDDas to punish him! SaDDas took Tavas' headphones and told him: "If you solve the following problem, I'll return it to you." The problem is: You ar...
```python # Tavas and Saddas lucky = input() satuan = 0 count = 0 total = 0 for x in range(len(lucky)): count = 2**satuan if lucky[x]=='7': count*=2 total+=count satuan+=1 print(total) ```
MatrixStudio/Codeforces-Python-Submissions
The circle line of the Berland subway has *n* stations. We know the distances between all pairs of neighboring stations: - *d*1 is the distance between the 1-st and the 2-nd station;- *d*2 is the distance between the 2-nd and the 3-rd station;...- *d**n*<=-<=1 is the distance between the *n*<=-<=1-th and the *n*-th ...
```python n = int(input()) a = list(map(int, input().split())) s, t = map(int, input().split()) if s > t: s, t = t, s sum1 = sum(a[s - 1: t - 1]) if sum1 < sum(a) - sum1: print(sum1) else: print(sum(a) - sum1) ```
MatrixStudio/Codeforces-Python-Submissions
Fox Ciel starts to learn programming. The first task is drawing a fox! However, that turns out to be too hard for a beginner, so she decides to draw a snake instead. A snake is a pattern on a *n* by *m* table. Denote *c*-th cell of *r*-th row as (*r*,<=*c*). The tail of the snake is located at (1,<=1), then it's body ...
```python n,m=map(int,input().split()) dot="."*(m-1) flag=0 flag1=0 for i in range(n): if flag==0: print("#"*m) flag=1 else: if flag1==0: print(dot,end="") print("#") flag1=1 flag=0 else: print("#",end="") ...
MatrixStudio/Codeforces-Python-Submissions
On the way to Rio de Janeiro Ostap kills time playing with a grasshopper he took with him in a special box. Ostap builds a line of length *n* such that some cells of this line are empty and some contain obstacles. Then, he places his grasshopper to one of the empty cells and a small insect in another empty cell. The gr...
```python import sys n, k = (int(i) for i in sys.stdin.readline().split()) seq = sys.stdin.readline().split()[0] G, T = 0, 0 for i, char in enumerate(seq): if char == 'G': G = i if char == 'T': T = i start = min(G, T) end = max(G, T) while start < end: if seq[start] == '#': print("N...
MatrixStudio/Codeforces-Python-Submissions
Santa Claus is the first who came to the Christmas Olympiad, and he is going to be the first to take his place at a desk! In the classroom there are *n* lanes of *m* desks each, and there are two working places at each of the desks. The lanes are numbered from 1 to *n* from the left to the right, the desks in a lane ar...
```python import math n,m,k=map(int,input().split()) s=n*2*m l=math.ceil((k/(2*m))) c=k-(l-1)*2*m r=math.ceil(c/(2)) if k%2==0: print(l,r,"R") else: print(l,r,"L") ```
MatrixStudio/Codeforces-Python-Submissions
What joy! Petya's parents went on a business trip for the whole year and the playful kid is left all by himself. Petya got absolutely happy. He jumped on the bed and threw pillows all day long, until... Today Petya opened the cupboard and found a scary note there. His parents had left him with duties: he should water...
```python n=int(input()) lst=list(map(int,input().split())) s=0 lst.sort(reverse=True) for i in range(len(lst)): s=s+lst[i] if s>=n: print(i+1) break ```
MatrixStudio/Codeforces-Python-Submissions
Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number *n*. How many times can Gerald put a spell on it until the number becomes one-...
```python print(int(input()%9) ```
MatrixStudio/Codeforces-Python-Submissions
ZS the Coder is playing a game. There is a number displayed on the screen and there are two buttons, '<=+<=' (plus) and '' (square root). Initially, the number 2 is displayed on the screen. There are *n*<=+<=1 levels in the game and ZS the Coder start at the level 1. When ZS the Coder is at level *k*, he can : 1. Pr...
```python ###### ### ####### ####### ## # ##### ### ##### # # # # # # # # # # # # # ### # # # # # # # # # # # # # ### ###### ######### # # # #...
MatrixStudio/Codeforces-Python-Submissions
Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks. Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off. You know that there will be *n* interesting minutes *t*1,<=*t*2,<=......
```python n = int(input()) t = map(int, input().split()) m = 0 for i in t: if i - m > 15: m += 15 else: m = i print(m) ```
MatrixStudio/Codeforces-Python-Submissions
In this problem you are to calculate the sum of all integers from 1 to *n*, but you should take all powers of two with minus in the sum. For example, for *n*<==<=4 the sum is equal to <=-<=1<=-<=2<=+<=3<=-<=4<==<=<=-<=4, because 1, 2 and 4 are 20, 21 and 22 respectively. Calculate the answer for *t* values of *n*.
```python minus = set() i = 1 while i < 10 ** 10: minus.add(i) i *= 2 for _ in range(int(input())): n = int(input()) _sum = 0 for i in range(1, n + 1): if i % 10000 == 0: print(f"i: {i}") if i in minus: _sum -= i else: _sum += i print...
MatrixStudio/Codeforces-Python-Submissions
There is a system of *n* vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to *n*, in the order from the highest to the lowest, the volume of the *i*-th vessel is *a**i* liters. Initially, all the vessels are empty. In some vessels water is poured. All the w...
```python import sys input = sys.stdin.readline if __name__ == '__main__': n = int(input()) maxvol = list(map(int, input().split())) nxt = list(range(n + 2)) vol = [0] * n def addwater(i, water): if i >= n or water == 0: return vol[i] += water i...
MatrixStudio/Codeforces-Python-Submissions
Yaroslav has an array that consists of *n* integers. In one second Yaroslav can swap two neighboring array elements. Now Yaroslav is wondering if he can obtain an array where any two neighboring elements would be distinct in a finite time. Help Yaroslav.
```python n = int(input()) b = dict() for x in list(map(int, input().split())): if x not in b.keys(): b[x] = 1 else: b[x] += 1 if any(b[x] > (n + 1) / 2 for x in b.keys()): print('NO') else: print('YES') ```
MatrixStudio/Codeforces-Python-Submissions
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word *s*. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, ...
```python s=input() target='hello' tmp=0 for i in target: tmp=s.find(i,tmp+1) if tmp==-1: print('NO') break else: ...
MatrixStudio/Codeforces-Python-Submissions
"To curtain off the moonlight should be hardly possible; the shades present its mellow beauty and restful nature." Intonates Mino. "See? The clouds are coming." Kanno gazes into the distance. "That can't be better," Mino turns to Kanno. The sky can be seen as a one-dimensional axis. The moon is at the origin whose ...
```python # -*- coding: utf-8 -*- """ @Project : CodeForces @File : 4.py @Time : 2018/6/11 23:01 @Author : Koushiro """ def find_bigger(num): for j in range(len(b_wind)): if b_wind[j] >= num: break return len(b_wind) - j if __name__ == "__main__": n, l, w_ma...
MatrixStudio/Codeforces-Python-Submissions
Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced prog...
```python n, k = list(map(int, input().split())) s = [] for i in range(1, n+1): s.append(i) tot = 0 dp = dict() def combo(c, s, ci, k, dp): # print(c, ci) if len(c) == k: # print(c) global tot tot += 1 return for i in range(ci, len(s)): if len(c) == ...
MatrixStudio/Codeforces-Python-Submissions
You are locked in a room with a door that has a keypad with 10 keys corresponding to digits from 0 to 9. To escape from the room, you need to enter a correct code. You also have a sequence of digits. Some keys on the keypad have fingerprints. You believe the correct code is the longest not necessarily contiguous subse...
```python n, m = map(int, input().split()) x = list(map(int, input().split())) y = list(map(int, input().split())) for i in x: for j in y: if j in x: if i == j: print(j,end = " ") break ```
MatrixStudio/Codeforces-Python-Submissions
Hands that shed innocent blood! There are *n* guilty people in a line, the *i*-th of them holds a claw with length *L**i*. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the *i*-th person kills the *j*-th person if and only if *j*<=&lt;<=*i* and *...
```python n = int(input()) L = list(map(int, input().split())) r = -1 dead = 0 for i in range(1, n): c = i - L[i] ln = i - max(c, 0) dead += i - max(i - ln, r + 1) if ln > 0: r = i - 1 print(n - dead) ```
MatrixStudio/Codeforces-Python-Submissions
Vitya has just started learning Berlanese language. It is known that Berlanese uses the Latin alphabet. Vowel letters are "a", "o", "u", "i", and "e". Other letters are consonant. In Berlanese, there has to be a vowel after every consonant, but there can be any letter after any vowel. The only exception is a consonant...
```python vowels = "aiueo" s = input() for i in range(len(s)): if s[i] not in vowels + 'n' and s[i + 1] not in vowels: print("NO") exit() print("YES") ```
MatrixStudio/Codeforces-Python-Submissions
Manao is trying to open a rather challenging lock. The lock has *n* buttons on it and to open it, you should press the buttons in a certain order to open the lock. When you push some button, it either stays pressed into the lock (that means that you've guessed correctly and pushed the button that goes next in the seque...
```python import sys input = sys.stdin.readline ################ ---- Input Functions ---- ################ def integer_input(): return(int(input())) def integer_list_input(): return list(map(int, input().split())) def string_input(): string_with_newline = input() return string_with_newline[:len(str...
MatrixStudio/Codeforces-Python-Submissions
Two polar bears Menshykov and Uslada from the St.Petersburg zoo and elephant Horace from the Kiev zoo got six sticks to play with and assess the animals' creativity. Menshykov, Uslada and Horace decided to make either an elephant or a bear from those sticks. They can make an animal from sticks in the following way: -...
```python l = list(map(int, input().split())) ok=True for i in range(6): if l.count(l[i])>=4: ok = False f=l[i] if ok: print("Alien") else: for i in range(4): l.pop(l.index(f)) print(["Bear", "Elephant"][l[0]==l[1]]) ```
MatrixStudio/Codeforces-Python-Submissions
Vanya got an important task β€” he should enumerate books in the library and label each book with its number. Each of the *n* books should be assigned with a number from 1 to *n*. Naturally, distinct books should be assigned distinct numbers. Vanya wants to know how many digits he will have to write down as he labels th...
```python n=int(input()) s=len(str(n)) print(s*n + s - int('1'*s)) ```
MatrixStudio/Codeforces-Python-Submissions
Kuriyama Mirai has killed many monsters and got many (namely *n*) stones. She numbers the stones from 1 to *n*. The cost of the *i*-th stone is *v**i*. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions: 1. She will tell you two numbers, *l* and *r*Β (1<=≀<=*l*<=≀<=*r*...
```python input() s = input() s1 = list(map(int, s.split())) s2 = sorted(s1) for i in range(1, len(s1)): s1[i] += s1[i - 1] s2[i] += s2[i - 1] for _ in range(int(input())): case, left, right = map(int, input().split()) if case == 1: print(s1[right - 1] - s1[left - 2] if left - 2 >= 0 e...
MatrixStudio/Codeforces-Python-Submissions
Professor GukiZ makes a new robot. The robot are in the point with coordinates (*x*1,<=*y*1) and should go to the point (*x*2,<=*y*2). In a single step the robot can change any of its coordinates (maybe both of them) by one (decrease or increase). So the robot can move in one of the 8 directions. Find the minimal numbe...
```python def solve(): x1, y1 = map(int, input().split()) x2, y2 = map(int, input().split()) print(max(abs(x1 - x2), abs(y1 - y2))) if __name__ == "__main__": solve() ```
MatrixStudio/Codeforces-Python-Submissions
Tonio has a keyboard with only two letters, "V" and "K". One day, he has typed out a string *s* with only these two letters. He really likes it when the string "VK" appears, so he wishes to change at most one letter in the string (or do no changes) to maximize the number of occurrences of that string. Compute the maxi...
```python s=input() c=s.count('VK') if(s=='VV'): c=1 if('VVV' in s or 'KKK' in s): c=c+1 print(c) ```
MatrixStudio/Codeforces-Python-Submissions
Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number *a* and Antisimon receives number *b*. They also have a heap of *n* stones. The players take turns to make a move and Simon starts. During a move a player should take...
```python import math n,a,b=map(int,input().split()) i=0 while(n>0): if i==0: n-=math.gcd(n,a) i=1-i elif i==1: n-=math.gcd(n,b) i=1-i print(1-i) ```
MatrixStudio/Codeforces-Python-Submissions
Walking through the streets of Marshmallow City, Slastyona have spotted some merchants selling a kind of useless toy which is very popular nowadays – caramel spinner! Wanting to join the craze, she has immediately bought the strange contraption. Spinners in Sweetland have the form of V-shaped pieces of caramel. Each s...
```python s,e=map(str,input().split()) n=int(input()) def clk(st,n,lis): sti=lis.index(st) n=n-n//5 p=4-sti if(n<=p): return(lis[sti+n]) else: n=n-p return(lis[n]) def aclk(st,n,lis): sti=lis.index(st)+1 n=n-n//5 if(n<=sti): return(lis[sti-n]) else: n=n-sti retur...
MatrixStudio/Codeforces-Python-Submissions
Sereja and Dima play a game. The rules of the game are very simple. The players have *n* cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. Th...
```python user = int(input()) card_val = [int(x) for x in input().split()] S_1 = 0 D_1 = 0 i = 0 k = 0 while len(card_val) != 0: if k % 2 == 0: if card_val[i] > card_val[len(card_val)-1-i]: S_1 += card_val[i] del card_val[i] k += 1 else: ...
MatrixStudio/Codeforces-Python-Submissions
Dreamoon wants to climb up a stair of *n* steps. He can climb 1 or 2 steps at each move. Dreamoon wants the number of moves to be a multiple of an integer *m*. What is the minimal number of moves making him climb to the top of the stairs that satisfies his condition?
```python n,m=map(int,input().split()) t=(n+1)//2 s=(t-1)//m*m+m print([s,-1][s>n]) ```
MatrixStudio/Codeforces-Python-Submissions
The World Programming Olympics Medal is a metal disk, consisting of two parts: the first part is a ring with outer radius of *r*1 cm, inner radius of *r*2 cm, (0<=&lt;<=*r*2<=&lt;<=*r*1) made of metal with density *p*1 g/cm3. The second part is an inner disk with radius *r*2 cm, it is made of metal with density *p*2 g/...
```python r1 = list(map(int , input().split())) n = r1.pop(0) r1.sort() r = r1[-1] p1 = list(map(int , input().split())) m = p1.pop(0) p1.sort() a = p1[-1] p2 = list(map(int , input().split())) k = p2.pop(0) p2.sort() b = p2[0] A , B = map(int , input().split()) B *= (a/b) import math pri...
MatrixStudio/Codeforces-Python-Submissions
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th...
```python s = input() low = 0 high = 0 for c in s: if ord(c) >= ord('a'): low += 1 else: high += 1 if max(low, high) == low: print(s.lower()) else: print(s.upper()) ```
MatrixStudio/Codeforces-Python-Submissions
Two players play a game. Initially there are $n$ integers $a_1, a_2, \ldots, a_n$ written on the board. Each turn a player selects one number and erases it from the board. This continues until there is only one number left on the board, i.Β e. $n - 1$ turns are made. The first player makes the first move, then players ...
```python n=int(input()) a=list(map(int,input().split())) a.sort() x=sum(a) print((x//2)-1) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya decided to write an anonymous letter cutting the letters out of a newspaper heading. He knows heading *s*1 and text *s*2 that he wants to send. Vasya can use every single heading letter no more than once. Vasya doesn't have to cut the spaces out of the heading β€” he just leaves some blank space to mark them. Help ...
```python s1=input() s2=input() l1=[] l2=[] ans=True for i in list(set(list(s2))): l1.append(s1.count(i)) l2.append(s2.count(i)) for x,y in zip(l1,l2): if x<y: ans=False break if ans is False: print("NO") else: print("YES") ```
MatrixStudio/Codeforces-Python-Submissions
Theatre Square in the capital city of Berland has a rectangular shape with the size *n*<=Γ—<=*m* meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size *a*<=Γ—<=*a*. What is the least number of flagstones needed to pave the...
```python n, m, a = map(int, input().split()) if n % a != 0: nn = n // a + 1 else: nn = n // a if m % a != 0: mm = m // a + 1 else: mm = m // a print(nn * mm) ```
MatrixStudio/Codeforces-Python-Submissions
Some days ago, I learned the concept of LCM (least common multiple). I've played with it for several times and I want to make a big number with it. But I also don't want to use many numbers, so I'll choose three positive integers (they don't have to be distinct) which are not greater than *n*. Can you help me to find ...
```python n = int(input()) a = n b = max(1, n-1) c = max(1, n-2) print(a*b*c) ```
MatrixStudio/Codeforces-Python-Submissions
Little Petya is learning to play chess. He has already learned how to move a king, a rook and a bishop. Let us remind you the rules of moving chess pieces. A chessboard is 64 square fields organized into an 8<=Γ—<=8 table. A field is represented by a pair of integers (*r*,<=*c*) β€” the number of the row and the number of...
```python r1, c1, r2, c2 = map(int, input().split()) if c1 != c2 and r1 != r2: torre = 2 else: torre = 1 if (r1 + c1) % 2 == (r2 + c2) % 2: bispo = 1 else: bispo = 0 rei = max(abs(c1 - c2),abs(r1 - r2)) print(torre, bispo, rei) ```
MatrixStudio/Codeforces-Python-Submissions
Vanya and his friends are walking along the fence of height *h* and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed *h*. If the height of some person is greater than *h* he can bend down and then he surely won't be noticed by the guard. The height ...
```python n,h = map(int,input().split(" ")) a = input().split(" ") maxw = 0; for i in range(n): if (int(a[i])>h): maxw +=2; else: maxw+=1; print(maxw) ```
MatrixStudio/Codeforces-Python-Submissions
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy...
```python sum1=0 for _ in range(int(input())): n=list(map(int, input().split())) sum1=sum1+sum(n) if sum1==0: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word. Note, that during capitalization all the letters except the first one remains unchanged.
```python s = input() s = list(s) s[0] = s[0].upper() print("".join(map(str, s))) ```
MatrixStudio/Codeforces-Python-Submissions
Catherine has a deck of *n* cards, each of which is either red, green, or blue. As long as there are at least two cards left, she can do one of two actions: - take any two (not necessarily adjacent) cards with different colors and exchange them for a new card of the third color; - take any two (not necessarily adja...
```python mod = 1000000007 ii = lambda : int(input()) si = lambda : input() dgl = lambda : list(map(int, input())) f = lambda : map(int, input().split()) il = lambda : list(map(int, input().split())) ls = lambda : list(input()) d=[0, 0, 0] dt={0:'B',1:'G',2:'R'} n=ii() s=si() for i in s: if i=='B':d[0]+...
MatrixStudio/Codeforces-Python-Submissions
Nowadays all circuses in Berland have a round arena with diameter 13 meters, but in the past things were different. In Ancient Berland arenas in circuses were shaped as a regular (equiangular) polygon, the size and the number of angles could vary from one circus to another. In each corner of the arena there was a spec...
```python T=[] for _ in range(3): a=tuple(map(int,input().split())) T.append(a) if T[0][0]==T[1][0]: if T[0][0]!=T[1][0]: D=abs((T[0][1]-T[1][1])/(T[0][0]-T[1][0])) else: D=abs(T[0][1]-T[1][1]) elif T[0][0]==T[2][0]: if T[0][0]!=T[2][0]: D=abs((T[0][1]-T[2][1])/(T[...
MatrixStudio/Codeforces-Python-Submissions
Little Alyona is celebrating Happy Birthday! Her mother has an array of *n* flowers. Each flower has some mood, the mood of *i*-th flower is *a**i*. The mood can be positive, zero or negative. Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choos...
```python from sys import stdin from collections import deque,Counter,defaultdict,OrderedDict import sys import math,os import operator import random from fractions import Fraction import functools import bisect import itertools from heapq import * import time import copy n,m = map(int,input().split()) arr = list(map...
MatrixStudio/Codeforces-Python-Submissions
This problem's actual name, "Lexicographically Largest Palindromic Subsequence" is too long to fit into the page headline. You are given string *s* consisting of lowercase English letters only. Find its lexicographically largest palindromic subsequence. We'll call a non-empty string *s*[*p*1*p*2... *p**k*] = *s**p*1*...
```python l=input() l=list(l) l.sort() k=l.count(l[-1]) for i in range(k): print(l[-1],end="") ```
MatrixStudio/Codeforces-Python-Submissions
Arkady wants to water his only flower. Unfortunately, he has a very poor watering system that was designed for $n$ flowers and so it looks like a pipe with $n$ holes. Arkady can only use the water that flows from the first hole. Arkady can block some of the holes, and then pour $A$ liters of water into the pipe. After...
```python n, a, b = map(int, input().split()) lst = list(map(int, input().split())) S = sum(lst) s = lst.pop(0) lst = sorted(lst) i = 0 f = True if a*s/S>b: ans = 0 f = False else: while i<=n: S = sum(lst) if a*s/(S+s)>=b: ans = i f = False ...
MatrixStudio/Codeforces-Python-Submissions
You are given array consisting of *n* integers. Your task is to find the maximum length of an increasing subarray of the given array. A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray strictly greater than previous.
```python n=int(input()) lis=list(map(int,input().split())) count=1 maxm=1 for i in range(n-1): if lis[i]<lis[i+1]: count+=1 else: count=1 maxm=max(maxm,count) print(maxm) ```
MatrixStudio/Codeforces-Python-Submissions
A + B is often used as an example of the easiest problem possible to show some contest platform. However, some scientists have observed that sometimes this problem is not so easy to get accepted. Want to try?
```python a = None b = None a = input() b = input() print(a+b) ```
MatrixStudio/Codeforces-Python-Submissions
Hideo Kojima has just quit his job at Konami. Now he is going to find a new place to work. Despite being such a well-known person, he still needs a CV to apply for a job. During all his career Hideo has produced *n* games. Some of them were successful, some were not. Hideo wants to remove several of them (possibly zer...
```python import sys #sys.stdin = open('input.in', 'r') #sys.stdout = open('output.out', 'w') n = int(input()) s = input().split() count = 0 for i in range(len(s) - 1): if s[i] == '1' and s[i + 1] == '0': count += 1 print(len(s) - count) ```
MatrixStudio/Codeforces-Python-Submissions
A tree is a connected graph that doesn't contain any cycles. The distance between two vertices of a tree is the length (in edges) of the shortest path between these vertices. You are given a tree with *n* vertices and a positive number *k*. Find the number of distinct pairs of the vertices which have a distance of ex...
```python MAX = 50002 adj = [[] for i in range(MAX)] dp = [[0 for i in range(503)] for j in range(MAX)] k = 0 def dfs(at, parent): dx = [0 for i in range(k + 1)] for i in adj[at]: if i == parent: continue dfs(i, at) dp[at] [k] = dp[at] [k] + dp[i] [k] for j in range(0, k + 1): ...
MatrixStudio/Codeforces-Python-Submissions
Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity. There are *n* columns of toy cubes in the box arranged in a line. The *i*-th column contains *a**i* cubes. At first, the gravity in the box is...
```python st = int(input()) lst = list(map(int, input().split())) print(*sorted(lst)) ```
MatrixStudio/Codeforces-Python-Submissions
One day Polycarp published a funny picture in a social network making a poll about the color of his handle. Many of his friends started reposting Polycarp's joke to their news feed. Some of them reposted the reposts and so on. These events are given as a sequence of strings "name1 reposted name2", where name1 is the n...
```python d={'polycarp':1} for _ in range(int(input())):a,b,c=input().lower().split();d[a]=d[c]+1 print(max(d.values())) ```
MatrixStudio/Codeforces-Python-Submissions
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc....
```python from numpy import * import numpy as np str1 = input() str2 = input() s1 = list(str1) s2 = list(str2) ar1 = np.asarray(s1) ar2 = np.asarray(s2) ar2 = ar2[::-1] if (np.shape(ar1)== np.shape(ar2)): if all(ar1 == ar2): print ("YES") else: print ("NO") else: print ("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Our old friend Alexey has finally entered the University of City N β€” the Berland capital. Alexey expected his father to get him a place to live in but his father said it was high time for Alexey to practice some financial independence. So, Alexey is living in a dorm. The dorm has exactly one straight dryer β€” a 100 ce...
```python n=int(input()) l=[] for i in range(n): l.append(list(map(int,input().split()))) r=list(range(l[0][0],l[0][1]+1)) count=0 for i in range(1,n): if(l[i][0] in r and l[i][1] in r): if(l[i][1]==l[i][0]+1): count-=1 else: r=r[:r.index(l[i][0])+1]+r[r.index(...
MatrixStudio/Codeforces-Python-Submissions
You may have heard of the pie rule before. It states that if two people wish to fairly share a slice of pie, one person should cut the slice in half, and the other person should choose who gets which slice. Alice and Bob have many slices of pie, and rather than cutting the slices in half, each individual slice will be ...
```python n = int(input()) pie = list(map(int, input().split())) d = [0,0] th = 1 tr = 0 for i in range(0,n): if(i==n-1): if((d[tr]+pie[i])<d[th]): d[tr]+=pie[i] else: d[th]+=pie[i] elif( (i<n-2) and ((d[th]+pie[i]+pie[i+2]) > (d[tr]+pie[i+1])) ): d[th]+=pie[i] th,tr = tr,th elif(pie[i+1]<pie[i]): ...
MatrixStudio/Codeforces-Python-Submissions
To stay woke and attentive during classes, Karen needs some coffee! Karen, a coffee aficionado, wants to know the optimal temperature for brewing the perfect cup of coffee. Indeed, she has spent some time reading several recipe books, including the universally acclaimed "The Art of the Covfefe". She knows *n* coffee ...
```python import math as mt import sys,string input=sys.stdin.readline import random from collections import deque,defaultdict L=lambda : list(map(int,input().split())) Ls=lambda : list(input().split()) M=lambda : map(int,input().split()) I=lambda :int(input()) n,k,q=M() # Does range update def update(D, l, r, x): ...
MatrixStudio/Codeforces-Python-Submissions
Vadim is really keen on travelling. Recently he heard about kayaking activity near his town and became very excited about it, so he joined a party of kayakers. Now the party is ready to start its journey, but firstly they have to choose kayaks. There are 2Β·*n* people in the group (including Vadim), and they have exact...
```python n = input() weights = [] for i in range(n*2): weights.append(input()) instability = 0 weights.sort() tandem_weights = weights[0:-2] for i in range(1,(n*2)-2): instability += tandem_weights[i] - tandem_weights[i-1] print(instability) ```
MatrixStudio/Codeforces-Python-Submissions
There is a fence in front of Polycarpus's home. The fence consists of *n* planks of the same width which go one after another from left to right. The height of the *i*-th plank is *h**i* meters, distinct planks can have distinct heights. Polycarpus has bought a posh piano and is thinking about how to get it into the h...
```python n, k = map(int, input().split()) l = list(map(int, input().split())) ans = list() for i in range(n-k+1): ans.append(sum(l[i:i+k])) print(ans.index(min(ans)) + 1) ```
MatrixStudio/Codeforces-Python-Submissions
Do you like summer? Residents of Berland do. They especially love eating ice cream in the hot summer. So this summer day a large queue of *n* Berland residents lined up in front of the ice cream stall. We know that each of them has a certain amount of berland dollars with them. The residents of Berland are nice people,...
```python n= int(input()) a = list(map(int,input().split())) i = len(a) - 1 c1 = 0 while (c1 == 0): i = len(a) - 1 while (i >= 1): if (abs(a[i] - a[i-1]) == 1): c1 = -1 break if (a[i-1] > a[i]): a[i] = a[i] + 1 a[i-1] = a[i-1] - 1 a[i],...
MatrixStudio/Codeforces-Python-Submissions
A burglar got into a matches warehouse and wants to steal as many matches as possible. In the warehouse there are *m* containers, in the *i*-th container there are *a**i* matchboxes, and each matchbox contains *b**i* matches. All the matchboxes are of the same size. The burglar's rucksack can hold *n* matchboxes exactl...
```python def solve(): a, b = map(int, input().split()) li1 = [] for i in range(b): c, d = map(int, input().split()) li1.append((d,c)) li1.sort(reverse=True) t = 0 ans = 0 for i in range(b-1): cd = li1[i] if a>cd[1]: a-=cd[1] ...
MatrixStudio/Codeforces-Python-Submissions
In the evening, after the contest Ilya was bored, and he really felt like maximizing. He remembered that he had a set of *n* sticks and an instrument. Each stick is characterized by its length *l**i*. Ilya decided to make a rectangle from the sticks. And due to his whim, he decided to make rectangles in such a way tha...
```python n=int(input()) d=set(map(int,input().split())) w=list(d) if(len(w)==1): print(w[0]*w[0]) if(len(w)==2): print(w[0]*w[1]) elif(len(w)==3):print(0) else: mi=min(w) w.pop(w.index(mi)) mj=min(w) w.pop(w.index(mj)) mk=min(w) print(mi*mk) ```
MatrixStudio/Codeforces-Python-Submissions
Where do odds begin, and where do they end? Where does hope emerge, and will they ever break? Given an integer sequence *a*1,<=*a*2,<=...,<=*a**n* of length *n*. Decide whether it is possible to divide it into an odd number of non-empty subsegments, the each of which has an odd length and begins and ends with odd numb...
```python leng = input() arr = input() leng = int(leng) arr = list(map(int, arr.split(' '))) if leng % 2 == 0: print("No") elif arr[0] % 2 == 0 or arr[-1] % 2 == 0: print("No") else: print("Yes") ```
MatrixStudio/Codeforces-Python-Submissions
One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality ...
```python x=int(input()) n=False for i in range(x): a,b=[int(x) for x in input().split()] if a<b: n=True if not n: print('Poor Alex') else: print('Happy Alex') ```
MatrixStudio/Codeforces-Python-Submissions
ZS the Coder is coding on a crazy computer. If you don't type in a word for a *c* consecutive seconds, everything you typed disappear! More formally, if you typed a word at second *a* and then the next word at second *b*, then if *b*<=-<=*a*<=≀<=*c*, just the new word is appended to other words on the screen. If *b*<...
```python n,c = list(map(int,input().split())) t = list(map(int,input().split())) r = 1 for i in range(1,n): if t[i]-t[i-1] <= c: r += 1 else: r = 1 print(r) ```
MatrixStudio/Codeforces-Python-Submissions
Greatest common divisor *GCD*(*a*,<=*b*) of two positive integers *a* and *b* is equal to the biggest integer *d* such that both integers *a* and *b* are divisible by *d*. There are many efficient algorithms to find greatest common divisor *GCD*(*a*,<=*b*), for example, Euclid algorithm. Formally, find the biggest in...
```python (a, b) = map(int, input().split(' ')) def gcd(a, b): if a == 0: return b return gcd(b % a, a) print(gcd(a, b)) ```
MatrixStudio/Codeforces-Python-Submissions
On the way to Rio de Janeiro Ostap kills time playing with a grasshopper he took with him in a special box. Ostap builds a line of length *n* such that some cells of this line are empty and some contain obstacles. Then, he places his grasshopper to one of the empty cells and a small insect in another empty cell. The gr...
```python def solve(s, k): g = s.index("G") t = s.index("T") if abs(g - t) % k != 0: return "NO" start = g fin = t + 1 if g > t: k = -k fin -= 2 for i in range(start, fin, k): if s[i] == "T": return "YES" elif s[i] == "#": ...
MatrixStudio/Codeforces-Python-Submissions
The recent All-Berland Olympiad in Informatics featured *n* participants with each scoring a certain amount of points. As the head of the programming committee, you are to determine the set of participants to be awarded with diplomas with respect to the following criteria: - At least one participant should get a di...
```python n = int(input()) a = list(map(int, input().rstrip().split(" "))) a.sort() a = list(set(a)) if a[0]==0: a.pop(0) print(len(a)) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word *s*. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, ...
```python s = input() h = s.find('h') e = s.find('e', h + 1) l = s.find('l', e + 1) l2 = s.find('l', l + 1) o = s.find('o', l2 + 1) a = h < e < l < l2 < o b = (h + 1) * e * l * l2 * o b1 = b < 0 print('YES' * a + 'NO' * b1) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya lives in a round building, whose entrances are numbered sequentially by integers from 1 to *n*. Entrance *n* and entrance 1 are adjacent. Today Vasya got bored and decided to take a walk in the yard. Vasya lives in entrance *a* and he decided that during his walk he will move around the house *b* entrances in th...
```python #include <iostream> using namespace std; int main() { long long n,o,i,sigma,k=0; cin>>n; i=n; sigma=0; if(n>0) { while(i>0) { i--; k++; sigma=sigma+k; } o=1+sigma*6; } else if(n==0) { o=1; } cout<<o; return 0; ...
MatrixStudio/Codeforces-Python-Submissions
Vitya has just started learning Berlanese language. It is known that Berlanese uses the Latin alphabet. Vowel letters are "a", "o", "u", "i", and "e". Other letters are consonant. In Berlanese, there has to be a vowel after every consonant, but there can be any letter after any vowel. The only exception is a consonant...
```python s = input() if ( s[-1]!='a' and s[-1]!='e' and s[-1]!='i' and s[-1]!='o' and s[-1]!='u' and s[-1]!='n'): print('NO') elif (s[-1]=='a' or s[-1]=='e' or s[-1]=='i' or s[-1]=='o' or s[-1]=='u' or s[-1] == 'n' ): print('YES') else: for i in range(0,len(s)-1): if (s[i]=='a' or s[i]=='e' ...
MatrixStudio/Codeforces-Python-Submissions
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth. Now Diamond has given Bort a string consisting of only uppercase English letters of length *n*. There is a great number of "QAQ" in the string (Diamond is so cute!). Bort wants to know how many subsequences "QAQ" are...
```python k = 0 q = 0 a = 0 for i in input(): if i == 'A': a += q elif i == 'Q': k += a q += 1 print(k) ```
MatrixStudio/Codeforces-Python-Submissions
For a positive integer *n* let's define a function *f*: *f*(*n*)<==<=<=-<=1<=+<=2<=-<=3<=+<=..<=+<=(<=-<=1)*n**n* Your task is to calculate *f*(*n*) for a given integer *n*.
```python n=int(input()) c=0 for i in range(1,n+1,2): c+=-1*i for i in range(2,n+1,2): c+=i print(c) ```
MatrixStudio/Codeforces-Python-Submissions
You are given a rectangular board of *M*<=Γ—<=*N* squares. Also you are given an unlimited number of standard domino pieces of 2<=Γ—<=1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions: 1. Each domino completely covers ...
```python m,n=map(int,input().split()) r=m*n/2 r=int(r) print(r) ```
MatrixStudio/Codeforces-Python-Submissions
Eleven wants to choose a new name for herself. As a bunch of geeks, her friends suggested an algorithm to choose a name for her. Eleven wants her name to have exactly *n* characters. Her friend suggested that her name should only consist of uppercase and lowercase letters 'O'. More precisely, they suggested that the ...
```python n = int(input()) a = 1 b = 1 result = 'O' for i in range(2, n+1): if i == a + b: result += 'O' x = b b += a a = x else: result += 'o' print(result) ```
MatrixStudio/Codeforces-Python-Submissions
Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number *a* and Antisimon receives number *b*. They also have a heap of *n* stones. The players take turns to make a move and Simon starts. During a move a player should take...
```python def gcd(a,b): large=1 for i in range(1,min(a,b)+1): if(a%i==0 and b%i==0): large=i return large a,b,n=map(int,input().split()) while(True): if(gcd(a,n)<=n): n-=gcd(a,n) else: print("1") exit() if(gcd(b,n)<=n): n-=gcd(b,n...
MatrixStudio/Codeforces-Python-Submissions
In some game by Playrix it takes *t* minutes for an oven to bake *k* carrot cakes, all cakes are ready at the same moment *t* minutes after they started baking. Arkady needs at least *n* cakes to complete a task, but he currently don't have any. However, he has infinitely many ingredients and one oven. Moreover, Arkady...
```python n, t, k, d = map(int,input().split()) not_build = (n / k) * t build = d + (not_build / 2) # print(not_build) # print(build) if(build < not_build): print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality ...
```python n = int(input()) z,x=0,0 for i in range(n): p=input().split() if z == 0: z = p[:] if x == 0: x = p[:] else: z = min(z,p,key=lambda a: int(a[0])) x = max(x,p,key=lambda a: int(a[1])) if int(z[0]) < int(x[0]) and int(z[1]) > int(x[1]): print("Hap...
MatrixStudio/Codeforces-Python-Submissions
This winter is so cold in Nvodsk! A group of *n* friends decided to buy *k* bottles of a soft drink called "Take-It-Light" to warm up a bit. Each bottle has *l* milliliters of the drink. Also they bought *c* limes and cut each of them into *d* slices. After that they found *p* grams of salt. To make a toast, each frie...
```python import sys n, k, l, c, d, p, nl, np = map(int, sys.stdin.readline().split()) a = k*l b = c*d print(min(p//np, a//nl, b) // n) ```
MatrixStudio/Codeforces-Python-Submissions
Polycarpus is the director of a large corporation. There are *n* secretaries working for the corporation, each of them corresponds via the famous Spyke VoIP system during the day. We know that when two people call each other via Spyke, the Spyke network assigns a unique ID to this call, a positive integer session numbe...
```python n=int(input()) l=list(map(int,input().split())) ans=0 repeat={} for i in l: if i in repeat: repeat[i]+=1 if repeat[1]>2: ans=-1 break else: ans+=1 else: repeat[i]=1 print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Misha and Vanya have played several table tennis sets. Each set consists of several serves, each serve is won by one of the players, he receives one point and the loser receives nothing. Once one of the players scores exactly *k* points, the score is reset and a new set begins. Across all the sets Misha scored *a* poi...
```python k, a, b = list(map(int, input().split())) if a + b < k: print(-1) else: print( (a + b) // k ) ```
MatrixStudio/Codeforces-Python-Submissions
Professor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest. In total, *n* students will attend, and before the start, every one of them has some positive integer rating. Students are indexed from 1 to *n*. Let's denote...
```python # coding=utf-8 if __name__ == '__main__': n = int(input()) line = str(input()).split() line = [int(it) for it in line] refer = line.copy() refer.sort(reverse=True) value = list() for i in range(n): value.append(str(refer.index(line[i]) + 1)) print(' '.join(v...
MatrixStudio/Codeforces-Python-Submissions
Natasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the stringΒ β€” concatenation of letters, which correspond to the stages. There are $n$ stages available. The ro...
```python def algo(chaine, num): trier = sorted(chaine) liste = [ord(a)-96 for a in trier] somme = sum(liste) if (num > len(liste)): return -1 c = 0 for k in range(len(liste)-1): if (liste[k] < liste[k+1]): c = c+1 if(c < num): return -1 for i in range(len(liste)-num): n = 1 count =...
MatrixStudio/Codeforces-Python-Submissions
HQ9+ is a joke programming language which has only four one-character instructions: - "H" prints "Hello, World!",- "Q" prints the source code of the program itself,- "9" prints the lyrics of "99 Bottles of Beer" song, - "+" increments the value stored in the internal accumulator. Instructions "H" and "Q" are case-s...
```python s = input() st = 'HQ9' count = 0 for i in s: if (i in st): count += 1 if (count > 0): print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
You can not just take the file and send it. When Polycarp trying to send a file in the social network "Codehorses", he encountered an unexpected problem. If the name of the file contains three or more "x" (lowercase Latin letters "x") in a row, the system considers that the file content does not correspond to the socia...
```python n = int(input()) s = input() segs = [] seg=[-1,-1] for i in range(len(s)): if(s[i] == 'x'): if(seg[0] == -1): seg[0] = i seg[1] = i else: seg[-1] = i else: if(seg[0] != -1): segs.append(seg) seg = [-1,-1]...
MatrixStudio/Codeforces-Python-Submissions
A famous Berland's painter Kalevitch likes to shock the public. One of his last obsessions is chess. For more than a thousand years people have been playing this old game on uninteresting, monotonous boards. Kalevitch decided to put an end to this tradition and to introduce a new attitude to chessboards. As before, th...
```python def main(): row = [False] * 8 col = [False] * 8 for r in range(8): s = input() for c in range(8): if s[c] == 'W': row[r] = True col[c] = True answer = 16 - sum(row) - sum(col) if answer == 16: answer = 8 ...
MatrixStudio/Codeforces-Python-Submissions
There is a game called "I Wanna Be the Guy", consisting of *n* levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game. Little X can pass only *p* levels of the game. And Little Y can pass only *q* levels of the game. You are given the indices of levels Little X can...
```python x = int(input()) p = list(map(int,input().split())) q = list(map(int,input().split())) p.pop(0) q.pop(0) r = p+q m = list(range(1,x+1)) sum = 0 for a in m : if a in r: sum+=1 if sum == x: print("I become the guy.") else: print("Oh, my keyboard!") ```
MatrixStudio/Codeforces-Python-Submissions
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: - Tetrahedron. Tetrahedron has 4 triangular faces. - Cube. Cube has 6 square faces. - Octahedron. Octahedron has 8 triangular faces. - Dodecahedron. Dodecahedron has 12 pentagonal faces. - Icosahed...
```python n=int(input()) t_f=0 for i in range(n): p=input() if p=="Tetrahedron": t_f+=4 elif p=="Cube": t_f+=6 elif p=="Octahedron": t_f+=8 elif p=="Dodecahedron": t_f+=12 elif p=="Icosahedron": t_f+=20 print(t_f) ```
MatrixStudio/Codeforces-Python-Submissions
Lenny is playing a game on a 3<=Γ—<=3 grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be sw...
```python mat = [[int(x) for x in input().split()] for y in range(3)] a=[[0 for x in range(3)] for y in range(3)] for i in range(3) : for j in range(3) : while mat[i][j]>0 : for ii in range(0,3) : a[ii][j]=a[ii][j]+1 #print(a) for jj in range(0,3) : a[i][jj]=a[i][jj]+1 mat[i][j]=mat[i][...
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 f = int(input()) data = dict() data[1] = [{1}] data[2] = [{2}] data[3] = [{1, 2}] for c in range(4, f+1): t = data[c-1] n = list() for i in t: if 1 in i: for z in i: if sum(i - {z} | {z+1}) == c: n.append(i - {z} | {z+1}) ...
MatrixStudio/Codeforces-Python-Submissions
A soldier wants to buy *w* bananas in the shop. He has to pay *k* dollars for the first banana, 2*k* dollars for the second one and so on (in other words, he has to pay *i*Β·*k* dollars for the *i*-th banana). He has *n* dollars. How many dollars does he have to borrow from his friend soldier to buy *w* bananas?
```python k, n, w = map(int, input().split()) total = int(w * (w + 1) / 2) if ans := (total * k - n) > 0 : print(ans) else : print(0) ```
MatrixStudio/Codeforces-Python-Submissions
In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of *n* bumpers. The bumpers are numbered with integers from 1 to *n* from left to right. There are two types of bumpers. They are denoted by the characters '&lt;' and '&gt;'. When the ball hits the bumper at pos...
```python import os os.system("cls") ```
MatrixStudio/Codeforces-Python-Submissions
The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a pla...
```python import collections n = int(input()) d = collections.defaultdict(lambda: [0, 0]) max = None for i in range(n): info = input().split(" ") if max is None: max = info[0] d[info[0]][0] += int(info[1]) d[info[0]][1] = i if d[info[0]][0] > d[max][0]: max = info[0] print(max) `...
MatrixStudio/Codeforces-Python-Submissions
Tonight is brain dinner night and all zombies will gather together to scarf down some delicious brains. The artful Heidi plans to crash the party, incognito, disguised as one of them. Her objective is to get away with at least one brain, so she can analyze the zombies' mindset back home and gain a strategic advantage. ...
```python n = int(input()) if n%2==1: print(n//2+1) else: print(n//2) ```
MatrixStudio/Codeforces-Python-Submissions
Little boy Valera studies an algorithm of sorting an integer array. After studying the theory, he went on to the practical tasks. As a result, he wrote a program that sorts an array of *n* integers *a*1,<=*a*2,<=...,<=*a**n* in the non-decreasing order. The pseudocode of the program, written by Valera, is given below. ...
```python n=int(input()) if n==1: print(-1) else: a="" while n>0: a=a+str(n) a=a+" " n=n-1 print(a) ```
MatrixStudio/Codeforces-Python-Submissions
The programming competition season has already started and it's time to train for ICPC. Sereja coaches his teams for a number of year and he knows that to get ready for the training session it's not enough to prepare only problems and editorial. As the training sessions lasts for several hours, teams become hungry. Thu...
```python input() p=0 for x in map(int, input().split()): p=1<<20 if x<p else p^x&1 print('NO' if p>0 else 'YES') ```
MatrixStudio/Codeforces-Python-Submissions
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second. One day in 230 AD Shapur was trying to find out if any one can possibly do...
```python a=input() b=input() aa=[] bb=[] t=0 for c in a: aa.append(c) for d in b: bb.append(d) while True: if aa[t]==bb[t]: t+=1 print(0,end='') else: t+=1 print(1,end='') if t>=len(a): break ```
MatrixStudio/Codeforces-Python-Submissions
Special Agent Smart Beaver works in a secret research department of ABBYY. He's been working there for a long time and is satisfied with his job, as it allows him to eat out in the best restaurants and order the most expensive and exotic wood types there. The content special agent has got an important task: to get th...
```python S = input() chSet = set() numQ = 0 for s in S: if ord(s) >= 65 and ord(s) <= 74: chSet.add(s) elif s == '?': numQ += 1 if len(chSet) != 0: cur = 1 for i in range(10, max(10 - len(chSet), 0), -1): cur *= i if S[0] not in chSet...
MatrixStudio/Codeforces-Python-Submissions
Two polar bears Menshykov and Uslada from the St.Petersburg zoo and elephant Horace from the Kiev zoo got six sticks to play with and assess the animals' creativity. Menshykov, Uslada and Horace decided to make either an elephant or a bear from those sticks. They can make an animal from sticks in the following way: -...
```python from collections import Counter def solved(dic): chan = 0 if len(list(dic.values())) == 3: for k,v in dic.items(): if v == 4: chan = k if chan != 0: return 'Bear' elif len(list(dic.values())) == 2: for k,v in dic.items(): ...
MatrixStudio/Codeforces-Python-Submissions
Your security guard friend recently got a new job at a new security company. The company requires him to patrol an area of the city encompassing exactly *N* city blocks, but they let him choose which blocks. That is, your friend must walk the perimeter of a region whose area is exactly *N* blocks. Your friend is quite ...
```python import math def compute(l, n): l2 = math.ceil(n / l) return 2 * l + 2 * l2 n = int(input()) best = 9999999999 for i in range(1, n): best = min(best, compute(i, n)) print(best) ```