source
stringclasses
3 values
instruction
stringlengths
23
3.97k
input
stringclasses
1 value
output
stringlengths
1
3.75k
MatrixStudio/Codeforces-Python-Submissions
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network. Bu...
```python s = input() d = {} for i in s: if i not in d: d[i] = None print("CHAT WITH HER!") if len(d) % 2 == 0 else print("IGNORE HIM!") ```
MatrixStudio/Codeforces-Python-Submissions
As it's the first of April, Heidi is suspecting that the news she reads today are fake, and she does not want to look silly in front of all the contestants. She knows that a newspiece is fake if it contains heidi as a subsequence. Help Heidi assess whether the given piece is true, but please be discreet about it...
```python string = input() s = ['h', 'e', 'i', 'd', 'i'] ans = list() for c in string: if c in s: ans.append(c) ans = ''.join(ans) if ans == 'heidi': print('YES') else: print('NO') ```
MatrixStudio/Codeforces-Python-Submissions
Top-model Izabella participates in the competition. She wants to impress judges and show her mathematical skills. Her problem is following: for given string, consisting of only 0 and 1, tell if it's possible to remove some digits in such a way, that remaining number is a representation of some positive integer, divisi...
```python a = input() s = 6 ind = 0 for i in range(len(a)): if a[i] == "1": ind = i break for i in range(ind,len(a)): if s == 0: break elif a[i] == "0": s -= 1 if s == 0: print("yes") else: print("no") ```
MatrixStudio/Codeforces-Python-Submissions
Dima and his friends have been playing hide and seek at Dima's place all night. As a result, Dima's place got messy. In the morning they decided that they need to clean the place. To decide who exactly would clean the apartment, the friends want to play a counting-out game. First, all the guys stand in a circle, and t...
```python from functools import reduce def main(): n = int(input()) cs = list(map(int, input().split())) s = reduce(lambda x, y: x + y, cs) sol = 0 for i in range(1, 6): if ((i + s - 1) % (n + 1)) != 0: sol += 1 print(sol) if __name__ == "__main__": mai...
MatrixStudio/Codeforces-Python-Submissions
*n* people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins *k* games in a row. This player becomes the winner. For each of t...
```python n, k = [int(x) for x in input().split()] a = [int(x) for x in input().split()] current_streak = 0 for i in range(1,n): if current_streak >= k or a[0] == n: print(a[0]) break elif a[i] == n: print(a[i]) break elif a[i] > a[0]: a[0] = a[i] ...
MatrixStudio/Codeforces-Python-Submissions
In a Berland's zoo there is an enclosure with camels. It is known that camels like to spit. Bob watched these interesting animals for the whole day and registered in his notepad where each animal spitted. Now he wants to know if in the zoo there are two camels, which spitted at each other. Help him to solve this task. ...
```python def solve(): n = int(input()) dados = {} yes = False for i in range(n): x,d = map(int,input().split()) dados[x] = (x+d) if((x+d) in list(dados.keys()) and yes == False): if(dados[x+d]==x): print("YES") yes = True if(yes ==...
MatrixStudio/Codeforces-Python-Submissions
Heidi's friend Jenny is asking Heidi to deliver an important letter to one of their common friends. Since Jenny is Irish, Heidi thinks that this might be a prank. More precisely, she suspects that the message she is asked to deliver states: "Send the fool further!", and upon reading it the recipient will ask Heidi to d...
```python n=int(input()) l={} k={0} r={} o=[] cc=set() for i in range(n): cc.add(i) for i in range(n-1): q,w,z=map(int,input().split()) if q in k: r[w]=q k.add(w) cc.discard(q) l[(w,q)]=z elif w in k: r[q]=w k.add(q) cc.discard(w)...
MatrixStudio/Codeforces-Python-Submissions
According to an old legeng, a long time ago Ankh-Morpork residents did something wrong to miss Fortune, and she cursed them. She said that at some time *n* snacks of distinct sizes will fall on the city, and the residents should build a Snacktower of them by placing snacks one on another. Of course, big snacks should b...
```python n = int(input()) num = input() num = list(int(x) for x in num.split(" ")) i = 0 while n > 0 and i < len(num): if num[i] == n: print(n, end=" ") n -= 1 while n > 0: if num.index(n) < i: print(n, end=" ") n -= 1 else...
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 t=int(input()) l=[] c=0 for i in range(0,t): x=int(input()) y=int(input()) z=int(input()) l.append([x,y,z]) for j in range(0,3): sum=0 for i in range(0,t): sum=sum+l[i][j] if sum=-=0: c=c+1 if c==3: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (*x*,<=*y*), he can move to (or attack) positions (*x*<=+<=1,<=*y*), (*x*–1,<=*y*), (*x*,<=*y*<=+<=1) and (*x*,<=*y*–1). ...
```python chessboard = input() chessboard = int(chessboard) #odd = n^2 - 1 / 2 #even = n^2 / 2 if chessboard % 2 == 0: print(int((chessboard ** 2) / 2)) else: print(int(((chessboard ** 2) - 1) / 2)) temp = 0 for i in range(0,chessboard): for j in range(0,chessboard): if temp == 0...
MatrixStudio/Codeforces-Python-Submissions
Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they ...
```python s = (str(input())) for str in s: print("NO") if str == str in s: print("YES") ```
MatrixStudio/Codeforces-Python-Submissions
Your friend has *n* cards. You know that each card has a lowercase English letter on one side and a digit on the other. Currently, your friend has laid out the cards on a table so only one side of each card is visible. You would like to know if the following statement is true for cards that your friend owns: "If a c...
```python cards = input() l = "02468aeiou" output = 0 for i in cards: if(i in l): output += 1 print(output) ```
MatrixStudio/Codeforces-Python-Submissions
A frog lives on the axis *Ox* and needs to reach home which is in the point *n*. She starts from the point 1. The frog can jump to the right at a distance not more than *d*. So, after she jumped from the point *x* she can reach the point *x*<=+<=*a*, where *a* is an integer from 1 to *d*. For each point from 1 to *n* ...
```python n, d = list(map(int, input().split())) s = input() count = 0 i = 0 while(i < n): countStart = count for _d in range(d, 0, -1): if i+_d < n and s[i+_d] == '1': i += _d count += 1 break if countStart == count: count = -1 break if i ==...
MatrixStudio/Codeforces-Python-Submissions
You are given positive integer number *n*. You should create such strictly increasing sequence of *k* positive numbers *a*1,<=*a*2,<=...,<=*a**k*, that their sum is equal to *n* and greatest common divisor is maximal. Greatest common divisor of sequence is maximum of such numbers that every element of sequence is divi...
```python from math import sqrt def factors(n,k): i=2;p=(k*(k-1))//2;s=0 while i<=sqrt(n): if n%i==0: if n//i-p>k-1:s=max(s,i) if i-p>k-1:s=max(s,n//i) i+=1 return 1 if s==0 else s def solve(n,k): p=(2*n)/(k*(k+1));m=factors(n,k) if p<1 or k>=n:retu...
MatrixStudio/Codeforces-Python-Submissions
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If...
```python S = list(input()); S.sort(); S = ''.join(S); print("YES" if "1111111" in S or "0000000" in S else "NO") ```
MatrixStudio/Codeforces-Python-Submissions
Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then...
```python n = int(input()) s = [] for i in range(n): if len(s) == 0: s.append(input()) else: v = input() if v in s: s.remove(v) s += [v] else: s += [v] [print(s[x]) for x in range(len(s) - 1, -1, -1)] ```
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 number = input("put numbers of watermelon: ") watermelon = float(number) modulo = watermelon / 2 if watermelon%2 == 0: if modulo % 2 == 0: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given *n* numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given *n* numbers finds one that i...
```python n=raw_input(n) number_of_evens=0 for i in range(0,len(n)): if n[i]%2==0: number_of_evens+=1 index_even=(n.index(n[i]))+1 else: index_odd=(n.index(n[i]))+1 number_of_odds=len(n)-number_of_evens if number_of_odds==1: print(index_odd) if number_of_evens==1: pri...
MatrixStudio/Codeforces-Python-Submissions
Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be *n* problems, sorted by difficulty, i.e. problem 1 is the easiest and problem *n* is the hardest. Limak knows it will take him 5·*i* minutes to solve th...
```python a, b = map(int,input().split()) b = 240 - b val = 0 for i in range(1, a+1): if b >= 5*i: b -= 5*i val += 1 print(val) ```
MatrixStudio/Codeforces-Python-Submissions
A sum of *p* rubles is charged from Arkady's mobile phone account every day in the morning. Among the following *m* days, there are *n* days when Arkady will top up the account: in the day *d**i* he will deposit *t**i* rubles on his mobile phone account. Arkady will always top up the account before the daily payment wi...
```python n, p, m = input().split() n = int(n) p = int(p) m = int(m) ans = 0 curb = 0 curd = 1 for i in range(0, n): #print(curb) tday, tplus = input().split() tday = int(tday) tplus = int(tplus) if curb < 0: ans += (tday - curd) curb -= p * (tday - curd) elif cu...
MatrixStudio/Codeforces-Python-Submissions
Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are *n* destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The *n* destinations are described by a non-negative integers sequence *a*1, *a*2, ..., *a**n*. The number *a*...
```python import math n = int(input()) l = [int(x) for x in input().split()] a1 = sum(l) a2 = n a3 = 0 temp = 0 for i in range(n): temp += l[n-i-1] a3-=(a1-temp) a3+=(n-i-1)*(l[n-i-1]) a1 = a1+a3+a3 a4 = math.gcd(a1, a2) print(a1//a4, a2//a4) ```
MatrixStudio/Codeforces-Python-Submissions
In one little known, but very beautiful country called Waterland, lives a lovely shark Valerie. Like all the sharks, she has several rows of teeth, and feeds on crucians. One of Valerie's distinguishing features is that while eating one crucian she uses only one row of her teeth, the rest of the teeth are "relaxing". ...
```python (((( return ```
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 import math def domino(numbers): num = numbers.split(" ") n= int(num[0]) m=int(num[1]) a=int(num[2]) return (math.ceil(n/a) * math.ceil(m/a)) numbers=input("") print(domino(numbers)) ```
MatrixStudio/Codeforces-Python-Submissions
Fox Ciel saw a large field while she was on a bus. The field was a *n*<=×<=*m* rectangle divided into 1<=×<=1 cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes. After seeing the field carefully, Ciel found that the crop plants of each cell were planted in f...
```python n,m,k,t = [int(x) for x in input().split()] mapp ={0:'Carrots',1:'Kiwis',2:'Grapes'} iamdistruption = [] for i in range(k): x,y = [int(x) for x in input().split()] iamdistruption.append((x,y)) for i in range(t): x,y = [int(x) for x in input().split()] orig = ((m*(x-1))+y-1) disb...
MatrixStudio/Codeforces-Python-Submissions
For each string *s* consisting of characters '0' and '1' one can define four integers *a*00, *a*01, *a*10 and *a*11, where *a**xy* is the number of subsequences of length 2 of the string *s* equal to the sequence {*x*,<=*y*}. In these problem you are given four integers *a*00, *a*01, *a*10, *a*11 and have to find any...
```python def getxs(n): D = 1 + 4 * n x1 = (-1 + D**0.5) / 2 + 1 x2 = (-1 - D**0.5) / 2 + 1 if x1 > 1e-6 and abs(round(x1) - x1) < 1e-6: return round(x1) elif x2 > 1e-6 and abs(round(x2) - x2) < 1e-6: return round(x2) return -1 a00, a01, a10, a11 = map(int, input().s...
MatrixStudio/Codeforces-Python-Submissions
Luke Skywalker gave Chewbacca an integer number *x*. Chewbacca isn't good at numbers but he loves inverting digits in them. Inverting digit *t* means replacing it with digit 9<=-<=*t*. Help Chewbacca to transform the initial number *x* to the minimum possible positive number by inverting some (possibly, zero) digits....
```python number = input() for i in range(len(number)): if i == 0 and number[i] == '9': print(9, end='') elif int(number[i]) >= 5: print(9 - int(number[i]), end='') else: print(number[i], end='') ```
MatrixStudio/Codeforces-Python-Submissions
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given *n* numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given *n* numbers finds one that i...
```python import sys n=[ ] a=int(input()) n=list(map(int,input().split())) n1=n2=0 for i in range (len(n)): if n[i] %2==0: n1=n1+1 c=i+1 else : n2=n2+1 b=i+1 if n1>n2 : print(b) else : print(c) ```
MatrixStudio/Codeforces-Python-Submissions
There are *n* pictures delivered for the new exhibition. The *i*-th painting has beauty *a**i*. We know that a visitor becomes happy every time he passes from a painting to a more beautiful one. We are allowed to arranged pictures in any order. What is the maximum possible number of times the visitor may become happy ...
```python n=int(input()) lst = list(map(int, input().strip().split(' '))) lst.sort() l=[[lst[0]]] for i in range(1,n): j=0 while(True): if j==len(l): l.append([lst[i]]) break else: if l[j][-1]!=lst[i]: l[j].append(lst[i]) ...
MatrixStudio/Codeforces-Python-Submissions
A country has *n* cities. Initially, there is no road in the country. One day, the king decides to construct some roads connecting pairs of cities. Roads can be traversed either way. He wants those roads to be constructed in such a way that it is possible to go from each city to any other city by traversing at most two...
```python n, m = map(int,input().split()) no_connections = list(map(int,input().split())) root = 1 for i in range(1,n+1): if i not in no_connections: root = i break print(n-1) for i in range(1,n+1): if i!=root: print(f'{root} {i}') ```
MatrixStudio/Codeforces-Python-Submissions
Now it's time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. They've been best friends ever since primary school and hopefully, that can somehow help them in teamwork. For each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing ...
```python n,m = map(int,input().split()) if n > m: ans = '001'*(m) n -=(m*2) ans += '0'*(n) elif n < m: ans = '110'*(n) m -= (n*2) ans += '1'*(m) else: ans = '10'*(m) flag = True for i in range(len(ans)-2): a = ans[i]+ans[i+1]+ans[i+2] if a == '000' or a == '111': ...
MatrixStudio/Codeforces-Python-Submissions
Dwarfs have planted a very interesting plant, which is a triangle directed "upwards". This plant has an amusing feature. After one year a triangle plant directed "upwards" divides into four triangle plants: three of them will point "upwards" and one will point "downwards". After another year, each triangle plant divide...
```python def main(): year = int(input()) end = pow(2,year) ans = sum(range(1,end+1)) print(ans) main() ```
MatrixStudio/Codeforces-Python-Submissions
There are *n* beacons located at distinct positions on a number line. The *i*-th beacon has position *a**i* and power level *b**i*. When the *i*-th beacon is activated, it destroys all beacons to its left (direction of decreasing coordinates) within distance *b**i* inclusive. The beacon itself is not destroyed however....
```python n = int(input()) a = [tuple(map(int, input().split())) for _ in range(n)] a.sort() dp = [1] * n res = n - 1 for i in range(n): j = i - 1 while j >= 0 and a[j][0] + a[j][1] <= a[i][0]: j -= 1 if j >= 0: dp[i] = dp[j] + 1 else: dp[i] = 1 res = min(res, n ...
MatrixStudio/Codeforces-Python-Submissions
Twilight Sparkle was playing Ludo with her friends Rainbow Dash, Apple Jack and Flutter Shy. But she kept losing. Having returned to the castle, Twilight Sparkle became interested in the dice that were used in the game. The dice has *m* faces: the first face of the dice contains a dot, the second one contains two dots...
```python m, n = [int(i) for i in input().split()] res = 0 for i in range(1,m+1): res += i*(pow(i,n) - pow((i-1),n))/pow(m,n) print(res) ```
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() visited=False t=l=0 if len(s)==2: if s[0]=="V" and s[1]=="K": t+=1 elif s[0]=="V" and s[1]=="V": t+=1 elif s[0]=="K" and s[1]=="K": t+=1 else: i=1 while i<len(s): if s[i]=="K" and s[i-1]=="V": t+=1 ...
MatrixStudio/Codeforces-Python-Submissions
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find ...
```python a = [4, 7] for i in ('47'): for j in ('47'): a.append(int(i + j)) for t in ('47'): for i in ('47'): for j in ('47'): a.append(int(i + j + t)) n = int(input()) flag = False for i in a: if n % i == 0: print('YES') flag = True ...
MatrixStudio/Codeforces-Python-Submissions
Two villages are separated by a river that flows from the north to the south. The villagers want to build a bridge across the river to make it easier to move across the villages. The river banks can be assumed to be vertical straight lines *x*<==<=*a* and *x*<==<=*b* (0<=&lt;<=*a*<=&lt;<=*b*). The west village lies i...
```python __author__ = 'Michael Ilyin' import math # debug = True debug = False def dist(x1, y1, x2, y2): return math.sqrt(math.pow(x1 - x2, 2) + math.pow(y1 - y2, 2)) def get_y(x1, y1, x2, y2, x): return (((x - x1) * (y2 - y1)) / (x2 - x1)) + y1 if debug: with open("input.txt", "r") ...
MatrixStudio/Codeforces-Python-Submissions
User ainta has a stack of *n* red and blue balls. He can apply a certain operation which changes the colors of the balls inside the stack. - While the top ball inside the stack is red, pop the ball from the top of the stack. - Then replace the blue ball on the top with a red ball. - And finally push some blue balls...
```python n, b = input(), input().replace('R', '0').replace('B', '1') print(int(b[:: -1], 2)) ```
MatrixStudio/Codeforces-Python-Submissions
The little girl loves the problems on array queries very much. One day she came across a rather well-known problem: you've got an array of $n$ elements (the elements of the array are indexed starting from 1); also, there are $q$ queries, each one is defined by a pair of integers $l_i$, $r_i$ $(1 \le l_i \le r_i \le n)...
```python n,m=[int(x) for x in input().split()] arr=[int(x) for x in input().split()] ans=[0 for _ in range(n)] for _ in range(m): x,y=[int(x) for x in input().split()] ans[x-1]+=1 if y!=n: ans[y]-=1 for i in range(1,n): ans[i]+=ans[i-1] ans.sort() arr.sort() # print(arr) # print(an...
MatrixStudio/Codeforces-Python-Submissions
The Bad Luck Island is inhabited by three kinds of species: *r* rocks, *s* scissors and *p* papers. At some moments of time two random individuals meet (all pairs of individuals can meet equiprobably), and if they belong to different species, then one individual kills the other one: a rock kills scissors, scissors kill...
```python n = int(input()) a = [i for i in range(1, 2 * n + 1)] b = [0] * (n * 2 + 1) cnt = 0 for _ in range(n): x, y = map(int, input().split()) a[x - 1], a[y - 1] = a[y - 1], a[x - 1] def merge(l, mid, r): i, j, k = l, mid + 1, l while i <= mid and j <= r: if a[i] <= a[j]: b[k] = ...
MatrixStudio/Codeforces-Python-Submissions
There are *n* walruses sitting in a circle. All of them are numbered in the clockwise order: the walrus number 2 sits to the left of the walrus number 1, the walrus number 3 sits to the left of the walrus number 2, ..., the walrus number 1 sits to the left of the walrus number *n*. The presenter has *m* chips. The pre...
```python n,m=input("").split(" ") n=int(n);m=int(m) m%=(n*(n+1)/2) for i in range(1,n+1): if(m<i): break; m -= i print(int(m)) ```
MatrixStudio/Codeforces-Python-Submissions
A robber has attempted to rob a bank but failed to complete his task. However, he had managed to open all the safes. Oleg the bank client loves money (who doesn't), and decides to take advantage of this failed robbery and steal some money from the safes. There are many safes arranged in a line, where the *i*-th safe f...
```python a,b,c=list(map(int,input().split())) n=int(input()) ed=sorted(list(map(int,input().split()))) say=0 bas=0 t=0 son=len(ed) for i in range(n): if ed[i]==b: bas=i if ed[i]==c: son=i if ed[i]==a: t=i if a>b and a<c: for...
MatrixStudio/Codeforces-Python-Submissions
One day, the Grasshopper was jumping on the lawn and found a piece of paper with a string. Grasshopper became interested what is the minimum jump ability he should have in order to be able to reach the far end of the string, jumping only on vowels of the English alphabet. Jump ability is the maximum possible length of ...
```python #https://codeforces.com/problemset/problem/733/A a = input() vow = ["A","E","I","O","U","Y"] mind = 1 cdist= 1 if (all(map(lambda x: x not in vow, a))): print(len(a)+1) else: for x in a: if x not in vow: cdist+=1 else: if mind<cdist: ...
MatrixStudio/Codeforces-Python-Submissions
Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (*x*,<=*y*), he can move to (or attack) positions (*x*<=+<=1,<=*y*), (*x*–1,<=*y*), (*x*,<=*y*<=+<=1) and (*x*,<=*y*–1). ...
```python from collections import * import sys input=sys.stdin.readline # "". join(strings) def ri(): return int(input()) def rl(): return list(map(int, input().split())) n = ri() if n % 2 == 0: print(n // 2 * n) for i in range(n): if i % 2 == 0: print("C."*(n//2)) else: print(".C"...
MatrixStudio/Codeforces-Python-Submissions
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
```python def too_long(n): if len(n)>0 and len(n)<=100: f=n[0] l=n[-1] m=n[1:-1] b=len(m) print(f"{f}{b}{l}") n=input() too_long(n) ```
MatrixStudio/Codeforces-Python-Submissions
You are given two positive integer numbers *a* and *b*. Permute (change order) of the digits of *a* to construct maximal number not exceeding *b*. No number in input and/or output can start with the digit 0. It is allowed to leave *a* as it is.
```python a=sorted(input()) b=int(input()) a=a[::-1] p="" while a: for i, z in enumerate(a): n=p+a[i]+"".join(sorted(a[:i]+a[i+1:])) if int(n)<=b: p+=z a.pop(i) break print(p) ```
MatrixStudio/Codeforces-Python-Submissions
Recently Irina arrived to one of the most famous cities of Berland — the Berlatov city. There are *n* showplaces in the city, numbered from 1 to *n*, and some of them are connected by one-directional roads. The roads in Berlatov are designed in a way such that there are no cyclic routes between showplaces. Initially I...
```python # n,m,T=map(int, input().split()) # d={i:[] for i in range(n)} # for i in range(m): # a,b,t=map(int, input().split()) # a-=1 ; b-=1 # d[a].append([b,t]) # dp=[[[float('inf'),-1] for _ in range(n)] for _ in range(n)] # dp[0][0]=[0,-1] # q=[0] # while q: # q1=[] # for ...
MatrixStudio/Codeforces-Python-Submissions
Vlad likes to eat in cafes very much. During his life, he has visited cafes *n* times. Unfortunately, Vlad started to feel that his last visits are not any different from each other. To fix that Vlad had a small research. First of all, Vlad assigned individual indices to all cafes. Then, he wrote down indices of cafes...
```python n = int(input()) a = list(map(int, input().split())) c = len(set(a)) was = set() ans = -1 for i in a[::-1]: if i not in was: was.add(i) ans = i if len(was) == c: print(ans) exit() print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
A and B are preparing themselves for programming contests. B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code. Initially, the compiler displayed *n* compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix...
```python n=int(input()); l1=[];l2=[];l3=[]; sum1=0;sum2=0;sum3=0; l1 = list(map(int, input().split())) sum1=sum(l1); l2 = list(map(int, input().split())) sum2=sum(l2); l3 = list(map(int, input().split())) sum3=sum(l3); print(abs(sum1-sum2)) print(abs(sum2-sum3)) ```
MatrixStudio/Codeforces-Python-Submissions
Throughout Igor K.'s life he has had many situations worthy of attention. We remember the story with the virus, the story of his mathematical career and of course, his famous programming achievements. However, one does not always adopt new hobbies, one can quit something as well. This time Igor K. got disappointed in ...
```python '''input 20 5 2 20 ''' from sys import stdin import math # main starts n, m, a, b = list(map(int, stdin.readline().split())) if n < m: print(1) exit() upper = math.ceil(a / m) lower = math.ceil(b / m) count = 0 if (upper - 1) * m + 1 == a: pass else: count += 1 if (lower)* m == b: pass else: count +=...
MatrixStudio/Codeforces-Python-Submissions
Vasya has a non-negative integer *n*. He wants to round it to nearest integer, which ends up with 0. If *n* already ends up with 0, Vasya considers it already rounded. For example, if *n*<==<=4722 answer is 4720. If *n*<==<=5 Vasya can round it to 0 or to 10. Both ways are correct. For given *n* find out to which int...
```python def rounding(num): num=str(num) v=num rounddown=["1","2","3","4","5"] roundup=["6","7","8","9"] if num[-1]=="0": return(num) elif num[-1] in rounddown: return(num[:-1:]+"0") elif num[-1] in roundup: return(num[:-2:]+str(int(v[-2])+2)+"0") a=int(in...
MatrixStudio/Codeforces-Python-Submissions
Max wants to buy a new skateboard. He has calculated the amount of money that is needed to buy a new skateboard. He left a calculator on the floor and went to ask some money from his parents. Meanwhile his little brother Yusuf came and started to press the keys randomly. Unfortunately Max has forgotten the number which...
```python count = 0 x = input() for i in range(len(x)-1): z = x[i:i+2] if int(z)%4 == 0: count += i+1 for j in range(len(x)): if x[j] in ['0', '4', '8']: count+= 1 print(count) ```
MatrixStudio/Codeforces-Python-Submissions
Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones. Once he thought about a string of length *n* consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, an...
```python n=int(input()) s=input() c0=0 c1=0 for i in s: if i=='0': c0+=1 c1=n-c0 ans=abs(c1-c0) print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
A frog lives on the axis *Ox* and needs to reach home which is in the point *n*. She starts from the point 1. The frog can jump to the right at a distance not more than *d*. So, after she jumped from the point *x* she can reach the point *x*<=+<=*a*, where *a* is an integer from 1 to *d*. For each point from 1 to *n* ...
```python from sys import stdin n,d=map(int,stdin.readline().split()) s=input() last=0 jump=0 while last!=n-1: for i in range(n-1,last,-1): if s[i]=='1': if i-last<=d: last=i jump+=1 break if jump==0: break print(jum...
MatrixStudio/Codeforces-Python-Submissions
Petya has *n* integers: 1,<=2,<=3,<=...,<=*n*. He wants to split these integers in two non-empty groups in such a way that the absolute difference of sums of integers in each group is as small as possible. Help Petya to split the integers. Each of *n* integers should be exactly in one group.
```python n = int(input()) if n % 4 == 0: print(0) ans = [] x = 1 for i in range(n // 4): ans.append(x) ans.append(n + 1 - x) x += 1 print(len(ans), *ans) elif n % 4 == 1: x = 2 ans = [] print(1) for i in range(n // 4): ans.append(x) ans.append...
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 string = input() res = 0 for i in range(len(string)): if string[i] == 'A': res += (string[:i].count('Q') * string[i:].count('Q')) print(res) ```
MatrixStudio/Codeforces-Python-Submissions
On the planet Mars a year lasts exactly *n* days (there are no leap years on Mars). But Martians have the same weeks as earthlings — 5 work days and then 2 days off. Your task is to determine the minimum possible and the maximum possible number of days off per year on Mars.
```python q=int(input()) if q==1 or q==6: print(0,1) elif q%7==0: print(q//7*2,q//7*2) elif q<7: print(0,0) elif q%7==6: print(q//7*2+1,q//7*2+2) elif q%7>2: print(q//7*2,q//7*2+2) else: print(q//7*2,q//7*2) ```
MatrixStudio/Codeforces-Python-Submissions
This problem's actual name, "Lexicographically Largest Palindromic Subsequence" is too long to fit into the page headline. You are given string *s* consisting of lowercase English letters only. Find its lexicographically largest palindromic subsequence. We'll call a non-empty string *s*[*p*1*p*2... *p**k*] = *s**p*1*...
```python s=input() p='' k=max(s) for i in range(len(s)): if(s[i]==k): p+=s[i] i+=1 print(p) ```
MatrixStudio/Codeforces-Python-Submissions
A burglar got into a matches warehouse and wants to steal as many matches as possible. In the warehouse there are *m* containers, in the *i*-th container there are *a**i* matchboxes, and each matchbox contains *b**i* matches. All the matchboxes are of the same size. The burglar's rucksack can hold *n* matchboxes exactl...
```python n,m=map(int,input().split(" ")) list=[] for i in range (m): temp_list=[int(k) for k in input().split()] for j in range(temp_list[0]): list.append(temp_list[1]) list.sort(reverse=True) print(list) sum=0 for k in range(n): sum+=int(list[k]) print(sum,end=" ") ```
MatrixStudio/Codeforces-Python-Submissions
Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to *n* computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on t...
```python import math n = int(input()) s = list(map(int, input().split())) s = list(sorted(s, reverse = True)) res = 0 for i in range(0, len(s)-1): for j in range(i+1, len(s)): res = res + (s[i] - s[j])*int(math.pow(2,(j-i-1))) print(res % 1000000007) ```
MatrixStudio/Codeforces-Python-Submissions
It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not en...
```python n = int(input()) ans = 1 lst = list(map(int, input().split())) for it in lst: ans = ans * it print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Olga came to visit the twins Anna and Maria and saw that they have many cookies. The cookies are distributed into bags. As there are many cookies, Olga decided that it's no big deal if she steals a bag. However, she doesn't want the sisters to quarrel because of nothing when they divide the cookies. That's why Olga wan...
```python n = int(input()) cnt = 0 a = list(map(int, input().split())) for i in range(len(a)): if (sum(a) - a[i]) % 2 == 0: cnt = cnt + 1 print(cnt) ```
MatrixStudio/Codeforces-Python-Submissions
PolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs with *k* vertices and *k*<=-<=1 edges, where *k* is some integer. Note that one vertex is a valid tree. There is exactly one relative living in each vertex of each tree, they have unique ids from 1 to ...
```python from collections import defaultdict class Graph: def __init__(self): self.graph=defaultdict(list) def addedge(self,u,v): self.graph[u].append(v) self.graph[v].append(u) def dfs(self,s): stack=[] stack.append(s) #print(self.visited) ...
MatrixStudio/Codeforces-Python-Submissions
Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yy...
```python s = list(input()) out = [s[0]] for i in range(1, len(s)): if len(out) > 0 and s[i] == out[-1]: out.pop() else: out.append(s[i]) print(''.join(out)) ```
MatrixStudio/Codeforces-Python-Submissions
Sagheer is walking in the street when he comes to an intersection of two roads. Each road can be represented as two parts where each part has 3 lanes getting into the intersection (one for each direction) and 3 lanes getting out of the intersection, so we have 4 parts in total. Each part has 4 lights, one for each lane...
```python matrix = [list(map(int, input().split())) for _ in range(4)] p1 = any([matrix[0][1], matrix[0][2], matrix[0][0], matrix[1][0], matrix[2][1], matrix[3][2]]) p2 = any([matrix[0][2], matrix[1][0], matrix[1][2], matrix[1][1], matrix[2][0], matrix[3][1]]) p3 = any([matrix[0][1], matrix[1][2], matrix[2][0], matrix...
MatrixStudio/Codeforces-Python-Submissions
Pashmak has fallen in love with an attractive girl called Parmida since one year ago... Today, Pashmak set up a meeting with his partner in a romantic garden. Unfortunately, Pashmak has forgotten where the garden is. But he remembers that the garden looks like a square with sides parallel to the coordinate axes. He al...
```python def pashmak_and_garden(): points = [int(point) for point in input().split()] conj_points = (points[0] == points[2]) or (points[1] == points[3]) diff = [points[i] - points[i+2] for i in range(2)] print(diff) unique_diff = list(set(diff)) nunique_diff = len(unique_diff) if (nu...
MatrixStudio/Codeforces-Python-Submissions
Little penguin Polo has an *n*<=×<=*m* matrix, consisting of integers. Let's index the matrix rows from 1 to *n* from top to bottom and let's index the columns from 1 to *m* from left to right. Let's represent the matrix element on the intersection of row *i* and column *j* as *a**ij*. In one move the penguin can add ...
```python n, m, d = map(int, input().split()) a = [] for i in range(n): a += list(map(int, input().split())) a = sorted(a) mod = a[0] % d piv = a[(n*m)//2] ans = 0 for i in range(n*m): if a[i] % d != mod: print(-1) break ans += abs(a[i]-piv) // d else: print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point *x*(*x*<=&gt;<=0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make ...
```python num = int(input()) time = 0 while num > 0: for i in range(5,0,-1): if (num-i) >= 0: num -= i time += 1 break print(time) ```
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() t1 = list(a) t2 = list(b) ans = '' for i in range(len(t1)): if(t1[i] != t2[i]): ans += '1' else: ans += '0' print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Xenia the beginner programmer has a sequence *a*, consisting of 2*n* non-negative integers: *a*1,<=*a*2,<=...,<=*a*2*n*. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value *v* for *a*. Namely, it takes several iterations to calculate value *v*. At the ...
```python #IXABO import sys LINES = sys.stdin.read().splitlines()[::-1] input = lambda: LINES.pop() def get_list_of_ints(): return list(map(lambda x: int(x), input().split())) def get_tree_index(n, i): return 2 ** n - 2 + i def set_op_value(tree, i, parity): if parity % 2: tree[i] = tr...
MatrixStudio/Codeforces-Python-Submissions
Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in *n* different shops in the city. It's known that the price of one bottle in the shop *i* is equal to *x**i* coins. Vasiliy plans to buy his favorite ...
```python def shops(n, prices, q, money): s = [] for i in range(q): d = 0 for j in range(n): if prices[j] <= money[i]: d += 1 s.append(d) return s n = int(input()) prices = list(map(int, input().split())) q = int(input()) money = [int(input()) ...
MatrixStudio/Codeforces-Python-Submissions
Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are *n* drinks in his fridge, the volume fraction of orange juice in the *i*-th drink equals *p**i* percent. One day Vasya decided to make himself an orange cocktail. He took equal proportio...
```python input() a = input().split() summ = 0 for i in range(len(a)): summ += int(a[i]) print(round(summ / len(a)), 10) ```
MatrixStudio/Codeforces-Python-Submissions
Sheldon, Leonard, Penny, Rajesh and Howard are in the queue for a "Double Cola" drink vending machine; there are no other people in the queue. The first one in the queue (Sheldon) buys a can, drinks it and doubles! The resulting two Sheldons go to the end of the queue. Then the next in the queue (Leonard) buys a can, d...
```python import math from collections import OrderedDict from collections import Counter from itertools import combinations from itertools import accumulate import operator import bisect import copy #a= list(map(int, input("").strip().split()))[:n] ''' def solve(a,x): t=int(input("")) f...
MatrixStudio/Codeforces-Python-Submissions
Jeff's friends know full well that the boy likes to get sequences and arrays for his birthday. Thus, Jeff got sequence *p*1,<=*p*2,<=...,<=*p**n* for his birthday. Jeff hates inversions in sequences. An inversion in sequence *a*1,<=*a*2,<=...,<=*a**n* is a pair of indexes *i*,<=*j* (1<=≤<=*i*<=&lt;<=*j*<=≤<=*n*), such...
```python n = int(input()) sequence = list(map(int, input().split())) inversions = 0 for i in range(n): for j in range(i + 1, n): if sequence[i] > sequence[j]: inversions += 1 print(inversions) ```
MatrixStudio/Codeforces-Python-Submissions
Two players play a simple game. Each player is provided with a box with balls. First player's box contains exactly *n*1 balls and second player's box contains exactly *n*2 balls. In one move first player can take from 1 to *k*1 balls from his box and throw them away. Similarly, the second player can take from 1 to *k*2...
```python def mod(): a=int(input()) b=int(input()) c=int(input()) d=int(input()) if a+c>b+d: print("frist") else: print("second") mod() ```
MatrixStudio/Codeforces-Python-Submissions
A magic island Geraldion, where Gerald lives, has its own currency system. It uses banknotes of several values. But the problem is, the system is not perfect and sometimes it happens that Geraldionians cannot express a certain sum of money with any set of banknotes. Of course, they can use any number of banknotes of ea...
```python n=int(input()) notes = list(map(int,input().split())) print((min(notes),-1)[min(notes)==1]) ```
MatrixStudio/Codeforces-Python-Submissions
Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then...
```python # -*- coding: utf-8 -*- """ Created on Mon Jul 12 14:41:22 2021 @author: lcarv """ m = {} l = [] n = int(input()) for i in range(n): s = str(input()) l.append(s) m[s] = 0 for j in range(n-1, -1, -1): k = l[j] if m[k] == 0: print(k) m[k] = 1 ...
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()) t = 0 for i in range(n+1): if i % 2 == 0: t += i else: t -= i print(t) ```
MatrixStudio/Codeforces-Python-Submissions
Haiku is a genre of Japanese traditional poetry. A haiku poem consists of 17 syllables split into three phrases, containing 5, 7 and 5 syllables correspondingly (the first phrase should contain exactly 5 syllables, the second phrase should contain exactly 7 syllables, and the third phrase should contain exactly 5 syll...
```python def haiku(line): vowel = 'aiueo' count = 0 for i in line: if i in vowel: count = count + 1 return count first = input().lower() second = input().lower() third = input().lower() if haiku(first) == 5 and haiku(second) == 7 and haiku(third) == 5: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot. He wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fence corners at a single angle *a*. Will the robot be able to build the fence Emuska...
```python # -*- coding: utf-8 -*- """ Created on Tue Oct 11 16:51:30 2022 @author: 帝落梦魂 """ t = int(input()) for i in range(0,t): a = int(input()) if 360%(180-a)==0: print('YES') else: print('NO') ```
MatrixStudio/Codeforces-Python-Submissions
Let's call a string "s-palindrome" if it is symmetric about the middle of the string. For example, the string "oHo" is "s-palindrome", but the string "aa" is not. The string "aa" is not "s-palindrome", because the second half of it is not a mirror reflection of the first half. You are given a string *s*. Check if the ...
```python [print("TAK" if [s[i]+s[-1-i] in "AA.HH.II.MM.OO.oo.TT.UU.VV.vv.WW.ww.XX.xx.YY.bd.db.pq.qp" for i in range(len(s))]==[True]*len(s) else "NIE") for s in [(input())]] ```
MatrixStudio/Codeforces-Python-Submissions
Polycarp is practicing his problem solving skill. He has a list of $n$ problems with difficulties $a_1, a_2, \dots, a_n$, respectively. His plan is to practice for exactly $k$ days. Each day he has to solve at least one problem from his list. Polycarp solves the problems in the order they are given in his list, he cann...
```python def main(): n, k = map(int, input().split()) a = list(map(int, input().split())) b = a.copy() b.sort() sum_ = 0 j = n - k b = b[j: n] for i in range(n - j): sum_ += b[i] count = 0 ans = [] for i in range(n): if a[i] in b: j ...
MatrixStudio/Codeforces-Python-Submissions
When new students come to the Specialized Educational and Scientific Centre (SESC) they need to start many things from the beginning. Sometimes the teachers say (not always unfairly) that we cannot even count. So our teachers decided to teach us arithmetics from the start. And what is the best way to teach students add...
```python s=input() a,b=s.split('+') b,c=b.split('=') a=list(a) b=list(b) c=list(c) if len(a)+len(b)==len(c): stp='' for i in a: stp=stp+i stp=stp+'+' for i in b: stp=stp+i stp=stp+'=' for i in c: stp=stp+i elif len(a)+len(b)<len(c): i=0 while(i<...
MatrixStudio/Codeforces-Python-Submissions
...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu... Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super...
```python class Graph: def __init__(self, edges, a): # Adjacency list representation self.adjacencyList = [[] for _ in range(a)] for (source, destination) in edges: print(source,destination) self.adjacencyList[source].append(destination) se...
MatrixStudio/Codeforces-Python-Submissions
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find ...
```python n=int(input()) if n%10==4 or n%10==7 or n%4==0 or n%7==0: print("YES") else: print("NO") ```
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 solve(): row_list = [] col_list = [] for i in range(8): row = input() row_list.append(row) for j in range(8): l = '' for row in chessboard_list1: l += row[j] col_list.append(l) r_count = row_list.count('BBBBBB...
MatrixStudio/Codeforces-Python-Submissions
You are given a ternary string (it is a string which consists only of characters '0', '1' and '2'). You can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace "01" with "10" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace "12" with "21" or vice versa). For e...
```python s = input() oneCnt = s.count('1') sNo1s = s.replace('1','') oneStr = '1' * oneCnt first2 = sNo1s.find('2') if first2 < 0: print(sNo1s + oneStr) else: print(sNo1s[:first2] + oneStr + sNo1s[first2:]) ```
MatrixStudio/Codeforces-Python-Submissions
You've got two numbers. As long as they are both larger than zero, they go through the same operation: subtract the lesser number from the larger one. If they equal substract one number from the another. For example, one operation transforms pair (4,17) to pair (4,13), it transforms (5,5) to (0,5). You've got some num...
```python n=int(input()) for i in range(n): ans=0 x,y=map(int,input().split()) if(y>x): x,y=y,x while(y>0): ans+=x//y x=x%y x,y=y,x print(ans) ```
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 n = int(input()) data = list(map(int, input().split())) if n % 2 == 1 and data[0] % 2 == 1 and data[-1] % 2 == 1: print("Yes") else: print("No") ```
MatrixStudio/Codeforces-Python-Submissions
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips: Vladik is at initial train station, and now *n* people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code *a**i* i...
```python def dp(curi): global cache try: return cache[curi] except KeyError: if curi >= len(sections): cache[curi] = 0 else: _, curend, curcomfort = sections[curi] nextsection = curi + 1 try: while sections[nextsection][0] <= curend: nextsection += 1 except IndexError: # Loop til e...
MatrixStudio/Codeforces-Python-Submissions
In a small but very proud high school it was decided to win ACM ICPC. This goal requires to compose as many teams of three as possible, but since there were only 6 students who wished to participate, the decision was to build exactly two teams. After practice competition, participant number *i* got a score of *a**i*. ...
```python import math A = list(map(int,input().split())) for i in range(len(A)): A[i]=math.fabs(A[i]) A.sort() cmnd1=A[0]+A[3] cmnd2=A[1]+A[2] if(cmnd1>cmnd2): cmnd1+=A[4] cmnd2+=A[5] else: cmnd1+=A[5] cmnd2+=A[4] if(cmnd1==cmnd2): print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
After finishing eating her bun, Alyona came up with two integers *n* and *m*. She decided to write down two columns of integers — the first column containing integers from 1 to *n* and the second containing integers from 1 to *m*. Now the girl wants to count how many pairs of integers she can choose, one from the first...
```python if __name__ == '__main__': A = list(map(int, input().split())) n = A[0] m = A[1] first = max(n, m) second = min(n, m) totaldevisors = 0 for i in range(5): if i != 0: totaldevisors += ((second + 5 - i) // 5) * ((first + i) // 5) else: ...
MatrixStudio/Codeforces-Python-Submissions
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word *s*. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, ...
```python word = input().lower() word = word[word.find('h'):] #print(word) if len(word[1:word.find('e')]) == 1 and word[1:word.find('e')] == 'h': word = word[0]+word[2:] else: word = word.replace(word[1:word.find('e')],'') #print(word) if len(word[2:word.find('l')]) ==1 and word[2:word.find('l')] ...
MatrixStudio/Codeforces-Python-Submissions
A long time ago in some far country lived king Copa. After the recent king's reform, he got so large powers that started to keep the books by himself. The total income *A* of his kingdom during 0-th year is known, as well as the total income *B* during *n*-th year (these numbers can be negative — it means that there w...
```python import math # import sys def cal(q,a,b,n): if q*a==b: h=math.pow(q,1/n) h=int(h) print(q,h**n) if q==h**n: # print('helkjl') return h,True return 0,False a=0 b=0 n=10 ab=False if a==0: # print('no solution') ab=...
MatrixStudio/Codeforces-Python-Submissions
Given a positive integer *n*, find *k* integers (not necessary distinct) such that all these integers are strictly greater than 1, and their product is equal to *n*.
```python n,k=map(int,input().split()) l=[] for i in range(2,n+1): if n%i==0: while n%i==0 and len(l)<(k-1): n//=i l.append(i) if n>1: l.append(n) if len(l)==k: print(*l) else: print(-1) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya's bicycle chain drive consists of two parts: *n* stars are attached to the pedal axle, *m* stars are attached to the rear wheel axle. The chain helps to rotate the rear wheel by transmitting the pedal rotation. We know that the *i*-th star on the pedal axle has *a**i* (0<=&lt;<=*a*1<=&lt;<=*a*2<=&lt;<=...<=&lt;<...
```python n = int(input()) starsPedal = list(map(int, input().split())) m = int(input()) starsRear = list(map(int, input().split())) maxVal = -1 totalGears = 0 for i in range(n): for j in range(m): if starsRear[j] % starsPedal[i] == 0: if starsRear[j]//starsPedal[i] == maxVal: ...
MatrixStudio/Codeforces-Python-Submissions
Rock... Paper! After Karen have found the deterministic winning (losing?) strategy for rock-paper-scissors, her brother, Koyomi, comes up with a new game as a substitute. The game works as follows. A positive integer *n* is decided first. Both Koyomi and Karen independently choose *n* distinct positive integers, deno...
```python n = int(input()) x = list(map(int, input().split())) y = list(map(int, input().split())) i=0 count=0 while i<n: j = i while j<n: z = x[i] ^ y[j] if z in x or z in y: count+=1 j+=1 i+=1 if count%2==0: print("Karen") else: print("Koyomi") `...
MatrixStudio/Codeforces-Python-Submissions
Roma (a popular Russian name that means 'Roman') loves the Little Lvov Elephant's lucky numbers. Let us remind you that lucky numbers are positive integers whose decimal representation only contains lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Roma's got *n* positive integer...
```python x,y=map(int,input().split(' ',1)) array=list(map(int,input().split(' '))) lucky=[4,7] count=0 for i in array: kk1=0 num=str(i) for x in range(len(num)): if int(num[x]) in lucky: kk1+=1 if kk1<=y: count+=1 print(count) # if num[x] in lu...
MatrixStudio/Codeforces-Python-Submissions
Polycarpus loves hamburgers very much. He especially adores the hamburgers he makes with his own hands. Polycarpus thinks that there are only three decent ingredients to make hamburgers from: a bread, sausage and cheese. He writes down the recipe of his favorite "Le Hamburger de Polycarpus" as a string of letters 'B' (...
```python import sys input=sys.stdin.readline m=1000000007 #------------------------------------# recipe=input() B=recipe.count("B") S=recipe.count("S") C=recipe.count("C") nb,ns,nc=map(int,input().split()) pb,ps,pc=map(int,input().split()) r=int(input()) count=0 if B==0: nb=float("inf") B=1 ...
MatrixStudio/Codeforces-Python-Submissions
As you could know there are no male planes nor female planes. However, each plane on Earth likes some other plane. There are *n* planes on Earth, numbered from 1 to *n*, and the plane with number *i* likes the plane with number *f**i*, where 1<=≤<=*f**i*<=≤<=*n* and *f**i*<=≠<=*i*. We call a love triangle a situation ...
```python def soln(inp): lines = inp.strip('\n').split('\n')[:-1] # print(lines) output_string="" for line in lines[1:]: # print("---",line) line_split=line.split() elm = 1 len_line = len(line_split) sign_flag=True one_flag=False # if line_split[0]...
MatrixStudio/Codeforces-Python-Submissions
Given an array *a*1,<=*a*2,<=...,<=*a**n* of *n* integers, find the largest number in the array that is not a perfect square. A number *x* is said to be a perfect square if there exists an integer *y* such that *x*<==<=*y*2.
```python import math def solve(): garbo = input() numbers = input().split() new = [] for number in numbers: new.append(int(number)) new = sorted(new) largest = 0 for number in new: if math.sqrt(number) % 1 == 0: pass else: largest...