source
stringclasses
3 values
instruction
stringlengths
23
3.97k
input
stringclasses
1 value
output
stringlengths
1
3.75k
MatrixStudio/Codeforces-Python-Submissions
The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself. There are *n* stations in the subway. It was built according to the Bertown Transport Law: 1. For each station *i* there exists exactly one train that goes from this station...
```python from collections import defaultdict as dd g=dd(list) def addE(u,v): g[u].append(v) g[v].append(u) n=int(input()) l=[int(x) for x in input().split()] for i in range(n): addE(i+1,l[i]) visited=[False]*(n+1) def dfs(v,count): visited[v]=True for ch in g[v]: if visited[ch]: continue count+=1 count=d...
MatrixStudio/Codeforces-Python-Submissions
DZY loves chessboard, and he enjoys playing with it. He has a chessboard of *n* rows and *m* columns. Some cells of the chessboard are bad, others are good. For every good cell, DZY wants to put a chessman on it. Each chessman is either white or black. After putting all chessmen, DZY wants that no two chessmen with th...
```python def is_valid(board): for i in range(len(board)): for j in range(len(board[i])): if board[i][j] not in ['B', 'W', '-']: return False if board[i][j] == '-': continue if i-1 >= 0 and board[i-1][j] =...
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 def work(): diffs = sorted([weight[i]-weight[i-1] for i in range(1, len(weight), 2)]) sep_diffs = sorted([weight[i]-weight[i-1] for i in range(2, len(weight), 2)]) diffs.pop() print(min(sum(diffs), sum(sep_diffs))) n = int(input()) weight = sorted([int(i) for i in input().strip().split()]) w...
MatrixStudio/Codeforces-Python-Submissions
As you very well know, this year's funkiest numbers are so called triangular numbers (that is, integers that are representable as , where *k* is some positive integer), and the coolest numbers are those that are representable as a sum of two triangular numbers. A well-known hipster Andrew adores everything funky and c...
```python def triangular(num): # Funcion para ver si es triangular o no el numero n = 1 while num > 0: num -= n n += 1 return num == 0 def suma_triangulres(n): for t1 in range(1, n + 1): # Funcion para revisar que t1 sea triangular if triangular(t1): diff...
MatrixStudio/Codeforces-Python-Submissions
There is a given string *S* consisting of *N* symbols. Your task is to find the number of ordered pairs of integers *i* and *j* such that 1. 1<=≤<=*i*,<=*j*<=≤<=*N* 2. *S*[*i*]<==<=*S*[*j*], that is the *i*-th symbol of string *S* is equal to the *j*-th.
```python S=input() d={} cnt=0 for i in S: d[i]=d.get(i,0)+1 for i in S: cnt+=d.get(i,0) print(cnt) ```
MatrixStudio/Codeforces-Python-Submissions
Recently Luba bought a very interesting book. She knows that it will take *t* seconds to read the book. Luba wants to finish reading as fast as she can. But she has some work to do in each of *n* next days. The number of seconds that Luba has to spend working during *i*-th day is *a**i*. If some free time remains, she...
```python n,t = map(int,input().split()) d = [*((86400-int(x)) for x in input().split())] cnt = 0 i = 0 while cnt < t: cnt += d[i] i += 1 print(i) ```
MatrixStudio/Codeforces-Python-Submissions
Sereja has an array *a*, consisting of *n* integers *a*1, *a*2, ..., *a**n*. The boy cannot sit and do nothing, he decided to study an array. Sereja took a piece of paper and wrote out *m* integers *l*1,<=*l*2,<=...,<=*l**m* (1<=≤<=*l**i*<=≤<=*n*). For each number *l**i* he wants to know how many distinct numbers are s...
```python """n,m=map(int,input().split()) A=list(map(int,input().split())) B=list(map(int,input().split())) i=1 s=0 for tot_num in B: tot_num-=s while i<=n: if tot_num<=A[i-1]: j=tot_num break else: tot_num-=A[i-1] s+=A[i-1] ...
MatrixStudio/Codeforces-Python-Submissions
A recently found Ancient Prophesy is believed to contain the exact Apocalypse date. The prophesy is a string that only consists of digits and characters "-". We'll say that some date is mentioned in the Prophesy if there is a substring in the Prophesy that is the date's record in the format "dd-mm-yyyy". We'll say tha...
```python p=input() data={} for i in range(len(p)-9): if p[i+2] == p[i+5] and (p[i+6:i+10]).isdecimal(): print(p[i:i+10]) if p[i:i+10] in data: data[p[i:i+10]]+=1 else: data[p[i:i+10]]=1 max_item=None maximum=0 for i in data.keys(): if data[i] > maximum: ...
MatrixStudio/Codeforces-Python-Submissions
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below. There are *n* trees located along the road at points with coordinates *x*1,<=*x*2,<=...,<=...
```python n=int(input()) s=[[int(x) for x in input().split( )] for i in range(n)] count=2 if n == 1: print('1') if n!= 1: for j in range(1,n-1): if s[j][0]-s[j-1][0] > s[j][1]: count+=1 elif s[j+1][0]-s[j][0] > s[j][1]: count+=1 s[j][0]+=s[j][1] ...
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 import math import sys import collections n = int(input()) def solve(): s = input() if len(s) < 10: print(s) return res = '' dig = str(len(s) - 2) res += s[0] + dig + s[len(s) - 1] print(res) for _ in range(n): solve() ```
MatrixStudio/Codeforces-Python-Submissions
Jzzhu has picked *n* apples from his big apple tree. All the apples are numbered from 1 to *n*. Now he wants to sell them to an apple store. Jzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be gre...
```python #!/usr/bin/env python3 # -*- coding: utf-8 -*- from math import * def prm(x): s = int(sqrt(x+0.5)) for i in range(2, s+1): if not (x%i): return False return True def ap(a): while(len(a) >= 2): print(a[-1], a[-2]) a.pop() a.pop() n, cnt, ans, vis, an...
MatrixStudio/Codeforces-Python-Submissions
$k$ people want to split $n$ candies between them. Each candy should be given to exactly one of them or be thrown away. The people are numbered from $1$ to $k$, and Arkady is the first of them. To split the candies, Arkady will choose an integer $x$ and then give the first $x$ candies to himself, the next $x$ candies ...
```python s = list(map(int, input().split())) n=int(s[0]) k=int(s[1]) m=int(s[2]) d=int(s[3]) ans=int(0) for i in range(1,d+1): if (n-1)/k < (i-1): break op=k*(i-1)+1 ans=max(ans,min(m,n/op)*i) print(int(ans)) ```
MatrixStudio/Codeforces-Python-Submissions
Polycarp has created his own training plan to prepare for the programming contests. He will train for $n$ days, all days are numbered from $1$ to $n$, beginning from the first. On the $i$-th day Polycarp will necessarily solve $a_i$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on...
```python days = int(input()) problems = list(map(int, input().split())) summa = sum(problems) if summa % 2 == 0: half_sum = summa // 2 else: half_sum = summa // 2 + 1 problems_sum = 0 i = 0 while problems_sum < half_sum: problems_sum += problems[i] i += 1 print(i) ```
MatrixStudio/Codeforces-Python-Submissions
You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes. You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consi...
```python n,m = [int(x) for x in input().split()] words = {} for i in range(m): word = input().split() words[word[0]] = word[0] if len(word[0]) < len(word[1]) else word[1] lecture = input().split() note = "" for word in lecture: note += words[word] + " " print(note[:-1]) ```
MatrixStudio/Codeforces-Python-Submissions
Codeforces user' handle color depends on his rating — it is red if his rating is greater or equal to 2400; it is orange if his rating is less than 2400 but greater or equal to 2200, etc. Each time participant takes part in a rated contest, his rating is changed depending on his performance. Anton wants the color of hi...
```python import sys,bisect from sys import stdin,stdout from bisect import bisect_left,bisect_right,bisect,insort,insort_left,insort_right from math import gcd,ceil,floor,sqrt from collections import Counter,defaultdict,deque,OrderedDict from queue import Queue,PriorityQueue from string import asc...
MatrixStudio/Codeforces-Python-Submissions
A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all *n* squad soldiers to line up on the parade ground. By the military charter the soldiers should stand in the order of non-increasing of their...
```python n = int(input()) vls = list(map(int, input().split())) x = min(vls) iX = len(vls) - 1 - vls[::-1].index(x) del vls[iX] vls.append(x) r = len(vls) - iX - 1 r += vls.index(max(vls)) print(r) ```
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 = input() b = input() if int(a) >=0 and int(b)<=1000: print(int(a)+int(b)) ```
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 import sys n = int(input()) x = [] y = [] z = [] for i in range(0, n): force = list(map(int, input().split())) x.append(force[0]) y.append(force[1]) z.append(force[2]) if((sum(x)+sum(y)+sum(z)) == 0): print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
A bus moves along the coordinate line *Ox* from the point *x*<==<=0 to the point *x*<==<=*a*. After starting from the point *x*<==<=0, it reaches the point *x*<==<=*a*, immediately turns back and then moves to the point *x*<==<=0. After returning to the point *x*<==<=0 it immediately goes back to the point *x*<==<=*a* ...
```python a, b, f, k=map(int,input().split()) d=b n=0 s=0 x=a-f d -= f if (x*2>b) or (f*2>b): if k<3: if k==1: if a<=b: print(0) elif (f<=b) and (x<=b): print(1) else: print(-1) if k==2: 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,k=map(int,input().split()) if k<=n*2+2 and k>=n-1: if k==n-1: print('0',end='') n+=1 while(True): if k==n: print('10',end='') k-=1 n-=1 else: print('110',end='') k-=2 n-=1 if k==0: ...
MatrixStudio/Codeforces-Python-Submissions
Drazil is playing a math game with Varda. Let's define for positive integer *x* as a product of factorials of its digits. For example, . First, they choose a decimal number *a* consisting of *n* digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then they shoul...
```python def findNum(a): numCount = [0]*11 for num in a: for i in range(2, num+1): numCount[i] += 1 # print(numCount) for i in range(9, 3, -1): shifts = max(0, numCount[i]-numCount[i+1]) if i == 4: numCount[2] += 2*shifts numCoun...
MatrixStudio/Codeforces-Python-Submissions
At regular competition Vladik and Valera won *a* and *b* candies respectively. Vladik offered 1 his candy to Valera. After that Valera gave Vladik 2 his candies, so that no one thought that he was less generous. Vladik for same reason gave 3 candies to Valera in next turn. More formally, the guys take turns giving eac...
```python X = list(map(int, input().split())) Turn = True N = 1 while True: if True: if X[0] - N < 0: print("Valera") exit() X[1] += X[0] - N X[0] -= N N += 1 Turn = False else: if X[1] - N < 0: print("Vladik") ...
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 # http://codeforces.com/problemset/problem/753/A def getSweets(sweetCount): sweetsList = [] sumN = 0 n = 1 while sumN + n < sweetCount: sumN += n sweetsList.append(n) n += 1 sweetsList[-1] += sweetCount - sumN return sweetsList if __name__ == '__main__': ...
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() l=len(s) c=0 for i in range (l): if i>='a' and i<='z': c+=1 if c>=l/2: print(s.lower) else: print(s.upper) ```
MatrixStudio/Codeforces-Python-Submissions
Vanya plays a game of balloons on the field of size *n*<=×<=*n*, where each cell contains a balloon with one of the values 0, 1, 2 or 3. The goal is to destroy a cross, such that the product of all values of balloons in the cross is maximum possible. There are two types of crosses: normal and rotated. For example: or ...
```python print("_RANDOM_GUESS_1690489311.5176659")# 1690489311.5176845 ```
MatrixStudio/Codeforces-Python-Submissions
Maxim wants to buy some games at the local game shop. There are $n$ games in the shop, the $i$-th game costs $c_i$. Maxim has a wallet which can be represented as an array of integers. His wallet contains $m$ bills, the $j$-th bill has value $a_j$. Games in the shop are ordered from left to right, Maxim tries to buy ...
```python n,m = list(map(int, input().split())) c = list(map(int, input().split())) a = list(map(int, input().split())) i=0 j=0 b=0 while i<n and j<m: if c[i]<=a[j]: b+=1 j+=1 i+=1 print(b) ```
MatrixStudio/Codeforces-Python-Submissions
Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings *a* and *b* of equal length are called equivalent in one of the two cases: 1. They are equal. 1. If we split string *a* into two halves of the same size *a*1 and *a*2, and string *b* into two halves of the same size ...
```python def xd(a, b): if a == b: return True if len(a) % 2 == 1 or a != b[::-1]: return False mid = len(a) // 2 return (xd(a[:mid], b[:mid]) and xd(a[mid:], b[mid:])) or \ (xd(a[:mid], b[mid:]) and xd(a[mid:], b[:mid])) x = input() a, b = x.split() if xd(a, b): print...
MatrixStudio/Codeforces-Python-Submissions
All cities of Lineland are located on the *Ox* coordinate axis. Thus, each city is associated with its position *x**i* — a coordinate on the *Ox* axis. No two cities are located at a single point. Lineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another c...
```python x = int(input()) i = 0 lis = [] lis = [int(x) for x in input().split()] for i in range(0, x): if(i == 0): print(f'{lis[1] - lis[0]} {lis[x-1] - lis[0]}') elif(i == x-1): print(f'{lis[x-1] - lis[x-2]} {lis[x-1] - lis[0]}') else: if(lis[i] - lis[i-1] > lis [i+1] - lis[i]): ...
MatrixStudio/Codeforces-Python-Submissions
One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are *n* lines in that description each of which described one goal. E...
```python n=int(input("")) dict1={} m=0 s='' for i in range(n): a=input("") if a not in dict1.keys(): dict1[a]=1 else: dict1[a]+=1 for j in dict1.keys(): if dict1[j]>m: m=dict1[j] s=j print(s) ```
MatrixStudio/Codeforces-Python-Submissions
Valera is a little boy. Yesterday he got a huge Math hometask at school, so Valera didn't have enough time to properly learn the English alphabet for his English lesson. Unfortunately, the English teacher decided to have a test on alphabet today. At the test Valera got a square piece of squared paper. The length of the...
```python n=int(input()) mat=[] c=0 for i in range(n): s=input() mat+=[s] for i in range(n): if mat[i][i]==mat[i][n-i-1]: c+=1 if c==n and len(set(mat))==2: print('YES') else: print('NO') ```
MatrixStudio/Codeforces-Python-Submissions
A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all *n* squad soldiers to line up on the parade ground. By the military charter the soldiers should stand in the order of non-increasing of their...
```python n = int(input()) a = list(map(int, input().split())) min_val = max_val = a[0] min_index = max_index = 0 for i in range(n): if min_val >= a[i]: min_val = a[i] min_index = i if max_val < a[i]: max_val = a[i] max_index = i if min_index < max_index: min_index = (n - ...
MatrixStudio/Codeforces-Python-Submissions
Natasha is planning an expedition to Mars for $n$ people. One of the important tasks is to provide food for each participant. The warehouse has $m$ daily food packages. Each package has some food type $a_i$. Each participant must eat exactly one food package each day. Due to extreme loads, each participant must eat t...
```python # Main def main(): n, m = map(int, input().split()) food = list(map(int, input().split())) arr = dict() for i in food: if i not in arr: arr[i] = 1 else: arr[i] += 1 maxD = 0 for d in range(1, 101, 1): temp = ...
MatrixStudio/Codeforces-Python-Submissions
Yet another Armageddon is coming! This time the culprit is the Julya tribe calendar. The beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows: "May the Great Beaver bless you! May your chacres open ...
```python t=int(input()) rem=t%10 c=1 no=t-rem c+=(no/10)*2 print(c) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya has *n* pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every *m*-th day (at days with numbers *m*,<=2*m*,<=3*m*,<=...) mom buys a pair of socks to Vasya. She does it la...
```python n,m = list(map(int,input().split())) n += (n//m) if n%m == 0: n += 1 print(n) ```
MatrixStudio/Codeforces-Python-Submissions
You have *r* red, *g* green and *b* blue balloons. To decorate a single table for the banquet you need exactly three balloons. Three balloons attached to some table shouldn't have the same color. What maximum number *t* of tables can be decorated if we know number of balloons of each color? Your task is to write a pro...
```python l = list(map(int,input().split())) l.sort() l[2]-=l[0] l[1]-=l[0] ans = l[0] ans += min(l[1],l[2]//2) print(ans) ```
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 tests = int(input()) for _ in range (0,tests): s = input() if len(s)>10: print(s[0],len(s)-2,s[-1],sep="") else: print(s) ```
MatrixStudio/Codeforces-Python-Submissions
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner. Output the probability that SmallR will...
```python a, b, c, d = (int(s) for s in input().split(" ")) MAX = 100 coef = sum((((c - d) * (a - b)) / (b * d)) ** i for i in range(MAX + 1)) ptotal = (a/b) * coef print("{:.15f}".format(ptotal)) ```
MatrixStudio/Codeforces-Python-Submissions
You are a lover of bacteria. You want to raise some bacteria in a box. Initially, the box is empty. Each morning, you can put any number of bacteria into the box. And each night, every bacterium in the box will split into two bacteria. You hope to see exactly *x* bacteria in the box at some moment. What is the mini...
```python ''' x = 2345234 print(bin(x)[2:]) s = '101110011100' print(int(s, 2)) ''' n = int(input()) k = bin(n)[2:] print(k.count('1')) ```
MatrixStudio/Codeforces-Python-Submissions
Beroffice text editor has a wide range of features that help working with text. One of the features is an automatic search for typos and suggestions of how to fix them. Beroffice works only with small English letters (i.e. with 26 letters from a to z). Beroffice thinks that a word is typed with a typo if there are thr...
```python def insert_spacebar(s,n): s1='' s2='' for i in range(n+1): s1+=s[i] for i in range(n+1,len(s)): s2+=s[i] return s1+' '+s2 s=input() glas_arr=['a','i','e','u','o'] for i in range(len(s)-2): if(s[i]==' ' or s[i] in glas_arr): continue else: if((s[i] not in glas_arr)and (s[i+1] not i...
MatrixStudio/Codeforces-Python-Submissions
Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings *a* and *b* of equal length are called equivalent in one of the two cases: 1. They are equal. 1. If we split string *a* into two halves of the same size *a*1 and *a*2, and string *b* into two halves of the same size ...
```python a = input() b = input() def equivalente(a,b): if(a == b): return 1 elif(len(a) > 1): half = int(len(a)/2) end = int(len(a)) if(len(a) > 1): ax = a[0:half] ay = a[half:end] bx = b[0:half] by = b[half:end] else: ...
MatrixStudio/Codeforces-Python-Submissions
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the oppo...
```python n = int(input()) control = n count = 0 temp = 0 while n > 0: magnet = input() if n != control and temp != magnet: count += 1 temp = magnet n -= 1 print(count + 1) ```
MatrixStudio/Codeforces-Python-Submissions
There are *n* students in a class working on group projects. The students will divide into groups (some students may be in groups alone), work on their independent pieces, and then discuss the results together. It takes the *i*-th student *a**i* minutes to finish his/her independent piece. If students work at differen...
```python import sys, math from functools import lru_cache input = sys.stdin.readline if __name__ == "__main__": MOD = 10 ** 9 + 7 n, k = map(int, input().split()) a = list(map(int, input().split())) a.sort() a.append(0) @lru_cache(None) def dfs(i, groups, leftK): if l...
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 # cook your dish here import bisect n=int(input()) A=[0] for k in input().split(): A.append(int(k)) # s=input() for k in range(1,n+1): if A[A[A[k]]]==k: print("YES") break else: print("NO") ```
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()) f = 0 for i in range(1,n+1): f += ((-1)**i)*i print(f) ```
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=list(input()) a=[] t=0 l=0 for i in range(len(s)): if s[i]=='2':t=1 if s[i]=='0'and t==1: t=0 a+=sorted(s[l:i]) l=i if i==len(s)-1:a+=sorted(s[l:]) print(''.join(a)) ```
MatrixStudio/Codeforces-Python-Submissions
Gerald has *n* younger brothers and their number happens to be even. One day he bought *n*2 candy bags. One bag has one candy, one bag has two candies, one bag has three candies and so on. In fact, for each integer *k* from 1 to *n*2 he has exactly one bag with *k* candies. Help him give *n* bags of candies to each b...
```python n=int(input()) x=n*(n**2+1)//2 for i in range(1,n+1): print(i,x-i) ```
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 from math import * from collections import * from operator import itemgetter import bisect ii = lambda: int(input()) iia = lambda: list(map(int,input().split())) isa = lambda: list(input().split()) I = lambda:list(map(int,input().split())) chrIdx = lambda x: ord(x)-96 idxChr = lambda x: chr(96+x) ...
MatrixStudio/Codeforces-Python-Submissions
Luba has a ticket consisting of 6 digits. In one move she can choose digit in any position and replace it with arbitrary digit. She wants to know the minimum number of digits she needs to replace in order to make the ticket lucky. The ticket is considered lucky if the sum of first three digits equals to the sum of las...
```python l=[int(i) for i in input()] a=sum(l[:3]);b=sum(l[3:]) if a==b: print(0) else: print(abs(a-b)//9+1) ```
MatrixStudio/Codeforces-Python-Submissions
You are given a sequence *a* consisting of *n* integers. You may partition this sequence into two sequences *b* and *c* in such a way that every element belongs exactly to one of these sequences. Let *B* be the sum of elements belonging to *b*, and *C* be the sum of elements belonging to *c* (if some of these sequenc...
```python raw_input() print(eval(input().replace("-","").replace(" ","+"))) ```
MatrixStudio/Codeforces-Python-Submissions
A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times *b*,<=*b*<=+<=*a*,<=*b*<=+<=2*a*,<=*b*<=+<=3*a*,<=... and Morty screams at times *d*,<=*d*<=+<=*c*,<=*d*<=+<=2*c*,<=*d*<=+<=3*c*,<=.... The Monster will catch them if a...
```python import math import cmath import string # how to find minimum prime factor in log(n) def sieve(n): l = [0]*(n+1) l[0] = l[1] = 1 for i in range(2,int(n**.5)+1): if not l[i]: for j in range(i*i,n+1,i): l[j] = 1 return [i for i in range(n+1) if l[i...
MatrixStudio/Codeforces-Python-Submissions
You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes. You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consi...
```python n,m=map(int,input().split()) mp={} for i in range(m): s1,s2=input().split() mp[s1]=s2 l=input().split() for i in range(n) : if len(mp[l[i]])<len(l[i]): print(mp[l[i]],end=' ') else: print(l[i],end=' ') i+=1 ```
MatrixStudio/Codeforces-Python-Submissions
Cucumber boy is fan of Kyubeat, a famous music game. Kyubeat has 16 panels for playing arranged in 4<=×<=4 table. When a panel lights up, he has to press that panel. Each panel has a timing to press (the preffered time when a player should press it), and Cucumber boy is able to press at most *k* panels in a time with...
```python k = int(input()) a = [] d = {} for _ in range(4): for i in input(): if i != ".": if i in d: d[i] += 1 else: d[i] = 1 d = sorted(d.items(), key = lambda x: x[1], reverse = True) if d[0][1] <= k*2: print("YES") else: ...
MatrixStudio/Codeforces-Python-Submissions
Devu is a renowned classical singer. He is invited to many big functions/festivals. Recently he was invited to "All World Classical Singing Festival". Other than Devu, comedian Churu was also invited. Devu has provided organizers a list of the songs and required time for singing them. He will sing *n* songs, *i**th* s...
```python n,d=map(int,input().split()) l=list(map(int,input().split())) temp=sum(l)+(len(l)-1)*10 if temp>d: print(-1) else: print((len(l)-1)*2+(d-temp)//5) ```
MatrixStudio/Codeforces-Python-Submissions
Devu is a renowned classical singer. He is invited to many big functions/festivals. Recently he was invited to "All World Classical Singing Festival". Other than Devu, comedian Churu was also invited. Devu has provided organizers a list of the songs and required time for singing them. He will sing *n* songs, *i**th* s...
```python t = input() temp = t.split() n = int(temp[0]) d = int(temp[1]) songLenthList = [] songLength = input() List = songLength.split() songLenthList = [int(i) for i in List] devuBreaktime = (n-1)*10 devuTotalTime = devuBreaktime + sum(songLenthList) churuTime = d - devuTotalTime + devuBreaktime if (devuT...
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 str=input() if len(str)>6: print('yes') else: print('no') ```
MatrixStudio/Codeforces-Python-Submissions
Om Nom really likes candies and doesn't like spiders as they frequently steal candies. One day Om Nom fancied a walk in a park. Unfortunately, the park has some spiders and Om Nom doesn't want to see them at all. The park can be represented as a rectangular *n*<=×<=*m* field. The park has *k* spiders, each spider at t...
```python n,m,k = map(int,input().split()) grid = [list(input()) for _ in range(n)] sol = [] for col in range(m): ans = 0 for t in range(1,n): x,y = t,col try: if grid[x][y+t] == 'L': ans += 1 except: pass try: if grid[x][y-t] =...
MatrixStudio/Codeforces-Python-Submissions
Imagine that there is a group of three friends: A, B and С. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The...
```python n, m = map(int, input().split()) own = dict() for _ in range(m): a, b, c = map(int, input().split()) if a in own: own[a] += c else: own[a] = c if b in own: own[b] -= c else: own[b] = -c ans = 0 for i in own.values(): ans += i if i...
MatrixStudio/Codeforces-Python-Submissions
There will be a launch of a new, powerful and unusual collider very soon, which located along a straight line. *n* particles will be launched inside it. All of them are located in a straight line and there can not be two or more particles located in the same point. The coordinates of the particles coincide with the dis...
```python """ 4 RLRL 2 4 6 10 3 LLR 40 50 60 4 LRLR 2 4 8 10 5 LRLRL 2 4 16 20 22 5 LRRRL 2 4 16 20 22 """ n = int(input()) dirs = input() first_right = dirs.index("R") last_left = dirs.rfind("L") bens = [int(i) for i in input().split()] dirs = dirs[first_right:last_left + 1] ...
MatrixStudio/Codeforces-Python-Submissions
Squirrel Liss loves nuts. There are *n* trees (numbered 1 to *n* from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree *i* is *h**i*. Liss wants to eat all nuts. Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the fol...
```python n = int(input()) # Assume squirrel has had nut on the prev tree and is at it's top. # In this, compute time to jump to next tree, go to top and have nut h_prev = int(input()) time = h_prev + 1 for i in range(n-1): h_cur = int(input()) time += abs((h_prev-h_cur)) + 2 h_prev = h_cur print(time) ```
MatrixStudio/Codeforces-Python-Submissions
Arya has *n* opponents in the school. Each day he will fight with all opponents who are present this day. His opponents have some fighting plan that guarantees they will win, but implementing this plan requires presence of them all. That means if one day at least one of Arya's opponents is absent at the school, then Ar...
```python io = input().split() n = int(io[0]) d = int(io[1]) l = [] streak = 0 new_streak = 0 for _ in range(d): l.append(list(map(int, input()))) for i in l: if 0 in i: streak += 1 else: new_streak = streak streak = 0 if streak > new_streak: print(streak...
MatrixStudio/Codeforces-Python-Submissions
Vasya likes everything infinite. Now he is studying the properties of a sequence *s*, such that its first element is equal to *a* (*s*1<==<=*a*), and the difference between any two neighbouring elements is equal to *c* (*s**i*<=-<=*s**i*<=-<=1<==<=*c*). In particular, Vasya wonders if his favourite integer *b* appears ...
```python a,b,c=map(int,input().split(" ")) i=0 X=[a] if(a==b): print("YES") elif((a>b and c<=0) or (a<b and c>=0)): if(c!=0): if(max(abs(b),abs(c))%min(abs(b),abs(c))==a): print("YES") else: print("NO") if(c==0): if(a==b): pri...
MatrixStudio/Codeforces-Python-Submissions
Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to th...
```python arr = list(map(int,input().split())) arrS = set(arr) print(len(arr)-len(arrS)) ```
MatrixStudio/Codeforces-Python-Submissions
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that. For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two ...
```python def iscomposite(n): for i in range(2,int(n/2 +1)): if n % i == 0 : return False else: continue return True m= int(input()) for i in range(4,m): if iscomposite(i): #print("{} is composite".format(i)) continue else: ...
MatrixStudio/Codeforces-Python-Submissions
One day a well-known sponsor of a well-known contest decided to give every participant of the contest a T-shirt as a present. A natural problem occurred: on the one hand, it is not clear how many T-shirts of what sizes should be ordered, and on the other hand, one doesn't want to order too many T-shirts (and we do not ...
```python sizes = list(map(int, input().split())) f = {"S":0, "M":1, "L":2, "XL":3, "XXL":4} g = ["S", "M", "L", "XL", "XXL"] for i in range(int(input())): size = input() idx = f[size] for j in range(5): try: #print("...") if sizes[idx+j]>0: print(g[...
MatrixStudio/Codeforces-Python-Submissions
You've got a rectangular table with length *a* and width *b* and the infinite number of plates of radius *r*. Two players play the following game: they take turns to put the plates on the table so that the plates don't lie on each other (but they can touch each other), and so that any point on any plate is located with...
```python a, b, r = map(int, input().split()) r *= 2 print('Second' if r > a or b < r else 'First') ```
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 Solution(N): N = math.sqrt(N) perimeter = 4 * N return perimeter N = int(input()) Solution(N) ```
MatrixStudio/Codeforces-Python-Submissions
Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited *n* his friends there. If...
```python n = input() a = list(map(int, input().split())) dic = {i: g for i, g in enumerate(a, start=1)} new_dict = {v: k for k, v in dic.items()} sorted_dict = sorted(new_dict.items()) for key, value in sorted_dict: print(value, end=" ") ```
MatrixStudio/Codeforces-Python-Submissions
Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer. Reliable sources have informed the financier Anton of some information about the exchange rate of...
```python if __name__ == '__main__': s = list(input()) smallest_even = -1 has_even = False for i in range(len(s)): if int(s[i]) % 2 == 0: has_even = True if int(s[i]) < int(s[-1]): s[i], s[-1] = s[-1], s[i] print(''.join(s)) ...
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 sum = [0, 0, 0] for _ in range(int(input())): a, b, c = map(int, input().split()) sum[0] += a sum[1] += b sum[2] += c print("YES" if sum == [0, 0, 0] else "NO") ```
MatrixStudio/Codeforces-Python-Submissions
Little Tanya decided to present her dad a postcard on his Birthday. She has already created a message — string *s* of length *n*, consisting of uppercase and lowercase English letters. Tanya can't write yet, so she found a newspaper and decided to cut out the letters and glue them into the postcard to achieve string *s...
```python from collections import * s, t = deque(input()), input() mem, a1, a2 = Counter(t), 0, 0 for i in range(len(s)): if mem[s[0]]: a1 += 1 mem[s[0]] -= 1 s.popleft() else: s.rotate(-1) # print(s) for i in s: if i.isupper() and mem[i.lower()]: a2 ...
MatrixStudio/Codeforces-Python-Submissions
Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word. Hongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character ...
```python a = input() t = a r1 = len(a) for i in range(len(a)): a = a[r1-1] + a[0:r1-1] if a == t: break print(i+1) ```
MatrixStudio/Codeforces-Python-Submissions
One day Vasya painted a Cartesian coordinate system on a piece of paper and marked some set of points (*x*1,<=*y*1),<=(*x*2,<=*y*2),<=...,<=(*x**n*,<=*y**n*). Let's define neighbors for some fixed point from the given set (*x*,<=*y*): - point (*x*',<=*y*') is (*x*,<=*y*)'s right neighbor, if *x*'<=&gt;<=*x* and *y*'...
```python tests = int(input()) setlist = [] def solution(setlist): points = 0 for i in range(len(setlist)): right = 0 left = 0 upper = 0 lower = 0 for j in range(len(setlist)): if setlist[i][0] == setlist[j][0] and setlist[j][1]<setlist[i][...
MatrixStudio/Codeforces-Python-Submissions
The administration of the Tomsk Region firmly believes that it's time to become a megacity (that is, get population of one million). Instead of improving the demographic situation, they decided to achieve its goal by expanding the boundaries of the city. The city of Tomsk can be represented as point on the plane with ...
```python import math x,y=map(int,input().split()) r=dict() for i in range(x): a,b,c = map(int, input().split()) a=math.sqrt(pow(a,2)+pow(b,2)) r[a]=c if(y>=1000000): print("0") else: for key in sorted(r): y+=r[key] if(y>=1000000): print(key) bre...
MatrixStudio/Codeforces-Python-Submissions
Okabe and Super Hacker Daru are stacking and removing boxes. There are *n* boxes numbered from 1 to *n*. Initially there are no boxes on the stack. Okabe, being a control freak, gives Daru 2*n* commands: *n* of which are to add a box to the top of the stack, and *n* of which are to remove a box from the top of the sta...
```python n = int(input()) st = 1 stack = [] ans = 0 for _ in range(2*n): ops = input() if ops[0]=='a': _,k = ops.split() stack.append(int(k)) else: if stack[-1]!=st: stack.sort(reverse=True) ans+=1 stack.pop() st+=1 print(ans) `...
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()) total_faces = 0 for _ in range(n): shape = input().capitalize() if shape == "Tetrahedron" : total_faces +=4 if shape == "Cube" : total_faces +=6 if shape == "Octahedron" : total_faces +=8 if shape == "Dodecahedron" : total_faces +=12 if shape == "Icosah...
MatrixStudio/Codeforces-Python-Submissions
The School №0 of the capital of Berland has *n* children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value *t**i*: - *t**i*<==<=1, if the *i*-th child is good at prog...
```python def finder(point, x): inx = 0 for i in range(len(point)): if point[i] == x: inx = i break return inx def main(): n = int(input()) num = list(range(1, n + 1)) point = list(map(int, input().split())) count = [0, 0, 0] for i in range...
MatrixStudio/Codeforces-Python-Submissions
Limak is a little polar bear. He has *n* balls, the *i*-th ball has size *t**i*. Limak wants to give one ball to each of his three friends. Giving gifts isn't easy — there are two rules Limak must obey to make friends happy: - No two friends can get balls of the same size. - No two friends can get balls of sizes th...
```python n = int(input()) a = sorted(map(int, input().split())) q = 0 p = -1 ans = False for i in a: if i == p + 1: q += 1 else: q = 1 if q == 3: ans = True p = i print('YES' if ans else 'NO') ```
MatrixStudio/Codeforces-Python-Submissions
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event. As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tourname...
```python #!/usr/bin/env python3 #-*- encoding: utf-8 -*- import sys def main(): n, m = map(int, sys.stdin.readline().split()) res = [0 for _ in range(n)] for i in range(m): l, r, x = map(int, sys.stdin.readline().split()) for j in range(l,r+1): if res[j-1] == 0 and j !=x: ...
MatrixStudio/Codeforces-Python-Submissions
Find an *n*<=×<=*n* matrix with different numbers from 1 to *n*2, so the sum in each row, column and both main diagonals are odd.
```python N = int(input()) cnt = 0 the_odd = -1 the_eve = 0 def get_with_eve_N(x, y) : return -1 def get_with_odd_N(x, y) : global the_odd global the_eve if (x + y <= N + 1 >> 1 or x + y >= N + (N + 1 >> 1) + 1 or y - x >= N + 1 >> 1 or x - y >= N + 1 >> 1) : the_eve += 2 return the_eve else : the_odd += 2 ...
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 a = str(input()).split() #for i in a: if (int(a[0]) * int(a[1]))%2 == 0: print((int(a[0]) * int(a[1]))//2) elif (int(a[0]) * int(a[1]))%2 != 0: print((int(a[0]) * int(a[1]))//2 ) ```
MatrixStudio/Codeforces-Python-Submissions
Vova promised himself that he would never play computer games... But recently Firestorm — a well-known game developing company — published their newest game, World of Farcraft, and it became really popular. Of course, Vova started playing it. Now he tries to solve a quest. The task is to come to a settlement named Ove...
```python ''' Depth First Search (DFS) ''' def dfs(x, menor, a): a.append(prec[x]) if prec[x] < menor: menor = prec[x] visited[x] = True for y in graph[x]: if not(visited[y]): dfs(y, menor, a) n, m = map(int, input().split()) prec = list(map(i...
MatrixStudio/Codeforces-Python-Submissions
As you may know, MemSQL has American offices in both San Francisco and Seattle. Being a manager in the company, you travel a lot between the two cities, always by plane. You prefer flying from Seattle to San Francisco than in the other direction, because it's warmer in San Francisco. You are so busy that you don't rem...
```python ip_no_days=int(input()) data_diff_days=input() countSF=0 countFS=0 for i in range(1,len(data_diff_days)): if data_diff_days[i-1]=='S' and data_diff_days[i]=='F': countSF+=1 elif data_diff_days[i-1]=='F' and data_diff_days[i]=='S': countFS+=1 else: continue ...
MatrixStudio/Codeforces-Python-Submissions
Vasya plays the sleuth with his friends. The rules of the game are as follows: those who play for the first time, that is Vasya is the sleuth, he should investigate a "crime" and find out what is happening. He can ask any questions whatsoever that can be answered with "Yes" or "No". All the rest agree beforehand to ans...
```python s=input().upper().split() s="".join(s) l=['A','E','I','O','U','Y'] n=len(s) if s[n-2] in l: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
This winter is so cold in Nvodsk! A group of *n* friends decided to buy *k* bottles of a soft drink called "Take-It-Light" to warm up a bit. Each bottle has *l* milliliters of the drink. Also they bought *c* limes and cut each of them into *d* slices. After that they found *p* grams of salt. To make a toast, each frie...
```python n, k, l, c, d, p, nl, np = map(int, input().split()) res = min(((k*l)//nl), (c*d), (p//np))//n print(int(res)) ```
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 n,b=map(int,input().split()) count=0 if n%2==0 or b%2==0: count=(n*b)//2 else: count=((n*b)-1)//2 print(count) ```
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 n=int(input()) sum1=sum2=sum3=0 for i in range(n): x,y,z=map(int,input().split()) sum1+=x sum2+=y sum3+=z if sum1==0 and sum2==0 and sum3==0: print('YES') else: print('NO') ```
MatrixStudio/Codeforces-Python-Submissions
Appleman and Toastman play a game. Initially Appleman gives one group of *n* numbers to the Toastman, then they start to complete the following tasks: - Each time Toastman gets a group of numbers, he sums up all the numbers and adds this sum to the score. Then he gives the group to the Appleman. - Each time Appleman...
```python def f(x): i =-1 while 2**(i+1) <= x: i += 1 return i n = int(input()) s = list(map(int,input().split())) add = 0 for i in range(len(s)): add += s[i] total = 0 s.sort(reverse = True) line = [] while n > 0: t = f(n) line.append(t) n -= 2**t a,b = 0,0 for...
MatrixStudio/Codeforces-Python-Submissions
According to a new ISO standard, a flag of every country should have a chequered field *n*<=×<=*m*, each square should be of one of 10 colours, and the flag should be «striped»: each horizontal row of the flag should contain squares of the same colour, and the colours of adjacent horizontal rows should be different. Be...
```python n, m = [int(i) for i in input().split()] last = '.' for i in range(n): s = input() if last == s[0]: print('NO') exit(0) if s != s[0] * m: print('NO') exit(0) last = s[0] print('YES') ```
MatrixStudio/Codeforces-Python-Submissions
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc....
```python s = list(input()) t = input() n = len(s) for i in range(n//2): temp = s[i] s[i] = s[n - (i+1)] s[n - (i+1)] = temp new_s = ''.join(map(str, s)) if t == new_s: print('YES') else: print('NO') ```
MatrixStudio/Codeforces-Python-Submissions
Let's consider one interesting word game. In this game you should transform one word into another through special operations. Let's say we have word *w*, let's split this word into two non-empty parts *x* and *y* so, that *w*<==<=*xy*. A split operation is transforming word *w*<==<=*xy* into word *u*<==<=*yx*. For ex...
```python MOD=10**9+7 # @cache def slove(): # if v==0: return 0 # n=int(input()) a=str(input()) b=str(input()) n=len(a) k=int(input()) if n==2: if a==b: print('1' if k&1==0 else '0') elif a[::-1]==b: print('1' if k&1 else '0') ...
MatrixStudio/Codeforces-Python-Submissions
Email address in Berland is a string of the form *A*@*B*, where *A* and *B* are arbitrary strings consisting of small Latin letters. Bob is a system administrator in «Bersoft» company. He keeps a list of email addresses of the company's staff. This list is as a large string, where all addresses are written in arbitra...
```python s = input() indexsi = [] for i in range(len(s)): if s[i] == "@": indexsi.append(i) ans = "" left = 0 temp = True #print(*indexsi) for i in range(len(indexsi)): if indexsi[i] == 0 or indexsi[i] == len(s)-1: temp = False break if i != 0 and indexsi[i] - indexsi[i-1] <= 2: ...
MatrixStudio/Codeforces-Python-Submissions
Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array *a* consisting of *n* distinct integers. Unfortunately, the size of *a* is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question corr...
```python def check(arr): temp = sorted(arr) n = len(arr) cnt = 0 segment = False p1 = -1 p2 = -2 for i in range(n): if arr[i] != temp[i]: if not segment : segment = True p1 = i elif segment : ...
MatrixStudio/Codeforces-Python-Submissions
Little Susie loves strings. Today she calculates distances between them. As Susie is a small girl after all, her strings contain only digits zero and one. She uses the definition of Hamming distance: We will define the distance between two strings *s* and *t* of the same length consisting of digits zero and one as the...
```python a = input() b = input() x = str(int(a) ^ int(b)) if x.count("1") %2 != 0 : print("IMPOSSIBLE") else : res = "" flag1 = True for idx , value in enumerate(x) : if value == "0": res += str(a)[idx] else: if flag1 : res +=...
MatrixStudio/Codeforces-Python-Submissions
— I experienced so many great things. — You gave me memories like dreams... But I have to leave now... — One last request, can you... — Help me solve a Codeforces problem? — ...... — What? Chtholly has been thinking about a problem for days: If a number is palindrome and length of its decimal representation with...
```python def main(length, r, num, rev, length2): global left, res, p if length == 0: if left == 0: return res += num * r * 10 + rev res %= p left -= 1 else: for j in range(10): if left == 0: return main(...
MatrixStudio/Codeforces-Python-Submissions
You are given an array of positive integers *a*1,<=*a*2,<=...,<=*a**n*<=×<=*T* of length *n*<=×<=*T*. We know that for any *i*<=&gt;<=*n* it is true that *a**i*<==<=*a**i*<=-<=*n*. Find the length of the longest non-decreasing sequence of the given array.
```python f = lambda: map(int, input().split()) n, m = f() t = list(f()) s = [0] * 301 d = s[:] for i in t: d[i] += 1 for i in t * min(m, 2 * n): s[i] = max(s[:i + 1]) + 1 print(max(s) + max((m - n * 2) * max(d), 0)) ```
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()) lst = [int(i) for i in input().split()] lst.sort() for i in range(2): new_lst = [int(i) for i in input().split()] new_lst.sort() #print(new_lst) #print(lst) fl = True for i in range(len(new_lst)): if new_lst[i] != lst[i]: print(lst[i]) ...
MatrixStudio/Codeforces-Python-Submissions
Little girl Alyona is in a shop to buy some copybooks for school. She study four subjects so she wants to have equal number of copybooks for each of the subjects. There are three types of copybook's packs in the shop: it is possible to buy one copybook for *a* rubles, a pack of two copybooks for *b* rubles, and a pack ...
```python n, a, b, c = map(int, input().split()) x = n%4 ans = 0 if x == 0: ans = 0 elif x == 3: ans = a elif x == 2: ans = min(a*2,b) else: ans = min(a*3,a+b,c) print (ans) ```
MatrixStudio/Codeforces-Python-Submissions
Polycarpus takes part in the "Field of Wonders" TV show. The participants of the show have to guess a hidden word as fast as possible. Initially all the letters of the word are hidden. The game consists of several turns. At each turn the participant tells a letter and the TV show host responds if there is such letter ...
```python n=int(input()) s=input() let=dict() a=[] c=0 for i in range(n): let[s[i]]=let.get(s[i],0)+1 m=int(input()) for i in range(m): a.append(input()) for i in range(ord('a'),ord('z')+1): if let.get(chr(i),0)!=0: continue flag2=1 for j in range(m): flag1=1 letc=dict...
MatrixStudio/Codeforces-Python-Submissions
wHAT DO WE NEED cAPS LOCK FOR? Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage. Let's consider that a word has been typed with the Caps lock key accidentall...
```python word = input() if word == word.upper(): print(word.swapcase()) elif word == word.capitalize().swapcase(): print(word.swapcase()) else: print(word) ```
MatrixStudio/Codeforces-Python-Submissions
After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer. At the start of the day they have *x* ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. Each person in the...
```python #####--------------Template Begin-------------------#### import math import sys #input = sys.stdin.readline def ri(): #Regular input return input() def ii(): #integer input return int(input()) def li(): #list input return input().split() def mi(): #map input return list(map(int, input().split()...