source
stringclasses
3 values
instruction
stringlengths
23
3.97k
input
stringclasses
1 value
output
stringlengths
1
3.75k
MatrixStudio/Codeforces-Python-Submissions
You are given an integer *N*. Consider all possible segments on the coordinate axis with endpoints at integer points with coordinates between 0 and *N*, inclusive; there will be of them. You want to draw these segments in several layers so that in each layer the segments don't overlap (they might touch at the endpoin...
```python import math n = int(input()) print( (math.floor(i)+1) * (n-1) ) ```
MatrixStudio/Codeforces-Python-Submissions
This is an interactive problem. In the output section below you will see the information about flushing the output. Bear Limak thinks of some hidden number — an integer from interval [2,<=100]. Your task is to say if the hidden number is prime or composite. Integer *x*<=&gt;<=1 is called prime if it has exactly two d...
```python p = [2, 3, 4, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] a = [] for i in range(16): print(p[i]) a.append(input()) if a.count('yes') > 1: print('composite') else: print('prime') ```
MatrixStudio/Codeforces-Python-Submissions
Mishka got an integer array $a$ of length $n$ as a birthday present (what a surprise!). Mishka doesn't like this present and wants to change it somehow. He has invented an algorithm and called it "Mishka's Adjacent Replacements Algorithm". This algorithm can be represented as a sequence of steps: - Replace each occu...
```python n = int(input()) a = input().split() numbers = [] for item in a: numbers.append(int(item)) m = max(numbers) s = '' for k in numbers: s += str(k) + ' ' for i in range(1, m+1): if s.__contains__(str(i)): if i%2 == 1: s = s.replace(str(i), str(i+1)) ...
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 d = input() e = input() f = [] for i in d: f.append(i) f.reverse() print("YES" if "".join(f) == e else "NO") quit() ```
MatrixStudio/Codeforces-Python-Submissions
Alice got an array of length $n$ as a birthday present once again! This is the third year in a row! And what is more disappointing, it is overwhelmengly boring, filled entirely with zeros. Bob decided to apply some changes to the array to cheer up Alice. Bob has chosen $m$ changes of the following form. For some int...
```python def findmin(size, changes): avg = 0 for a, b in changes: avg += a if b == 0: continue if b > 0: avg += (size - 1) / 2.0 * b else: avg += (size / 2) * (size / 2 + 1) / 2.0 * b / size return avg ina, inn = map(int, input().split(' ')) inx = [] for...
MatrixStudio/Codeforces-Python-Submissions
There is a square matrix *n*<=×<=*n*, consisting of non-negative integer numbers. You should find such a way on it that - starts in the upper left cell of the matrix; - each following cell is to the right or down from the current cell; - the way ends in the bottom right cell. Moreover, if we multiply together all...
```python import sys input = sys.stdin.readline from math import * from bisect import * from itertools import * from functools import reduce, lru_cache from collections import Counter, defaultdict def main(): n = int(input()) B = [list(map(int, input().split())) for _ in range(n)] def F(x, p): ...
MatrixStudio/Codeforces-Python-Submissions
The polar bears are going fishing. They plan to sail from (*s**x*,<=*s**y*) to (*e**x*,<=*e**y*). However, the boat can only sail by wind. At each second, the wind blows in one of these directions: east, south, west or north. Assume the boat is currently at (*x*,<=*y*). - If the wind blows to the east, the boat will ...
```python t,sx,sy,ex,ey=map(int,input().split()) s=input() h,v="Z","Z" if(sx>ex):h="W" elif(sx<ex):h="E" if(sy>ey):v="S" elif(sy<ey):v="N" a,b=abs(sx-ex),abs(sy-ey);c=0 for i in s: if(a or b):c+=1 if(h==i and a>0): a-=1 if(v==i and b>0): b-=1 if(a!=0 or b!=0):print(-1) els...
MatrixStudio/Codeforces-Python-Submissions
After the fourth season Sherlock and Moriary have realized the whole foolishness of the battle between them and decided to continue their competitions in peaceful game of Credit Cards. Rules of this game are simple: each player bring his favourite *n*-digit credit card. Then both players name the digits written on the...
```python n = int(input()) s = list(map(int, input())) m = list(map(int, input())) a, b = s.copy(), m.copy() c, k = 0, 0 m.sort() for i in range(len(s)): for j in range(len(m)): if m[j] >= s[i]: c += 1 del m[j] break print(n - c) b.sort() for i in ra...
MatrixStudio/Codeforces-Python-Submissions
Imp is in a magic forest, where xorangles grow (wut?) A xorangle of order *n* is such a non-degenerate triangle, that lengths of its sides are integers not exceeding *n*, and the xor-sum of the lengths is equal to zero. Imp has to count the number of distinct xorangles of order *n* to get out of the forest. Formally...
```python import sys input = sys.stdin.buffer.readline def process(n): answer = 0 for a in range(1, n+1): for b in range(a, n+1): c = a^b if 1 <= a <= b <= c <= n and a+b > c: answer+=1 sys.stdout.write(f'{answer}\n') n = int(input()) pr...
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 l=input() j=input() for i in range(len(l)): if l[i]==j[i]:print('0',end='') else:print('1',end='') ```
MatrixStudio/Codeforces-Python-Submissions
Permutation *p* is an ordered set of integers *p*1,<=<=*p*2,<=<=...,<=<=*p**n*, consisting of *n* distinct positive integers, each of them doesn't exceed *n*. We'll denote the *i*-th element of permutation *p* as *p**i*. We'll call number *n* the size or the length of permutation *p*1,<=<=*p*2,<=<=...,<=<=*p**n*. The ...
```python def main(): n, k = map(int, input().split()) z = [f'{i}' for i in range(1, n + 1)] x = list(reversed(z))[:k] print((' '.join(x) + " " + ' '.join(z[:n - k])).strip()) if __name__ == '__main__': main() ```
MatrixStudio/Codeforces-Python-Submissions
The Little Girl loves problems on games very much. Here's one of them. Two players have got a string *s*, consisting of lowercase English letters. They play a game that is described by the following rules: - The players move in turns; In one move the player can remove an arbitrary letter from string *s*. - If the p...
```python s = input() freq = dict() for ele in s: if(ele not in freq): freq[ele] = 1 else: freq[ele] += 1 c = 0 for v in freq.values(): if(v%2==1): c+=1 if(c==0): print("First") elif(c%2==1): print("First") else: print("Second") ```
MatrixStudio/Codeforces-Python-Submissions
You have probably registered on Internet sites many times. And each time you should enter your invented password. Usually the registration form automatically checks the password's crypt resistance. If the user's password isn't complex enough, a message is displayed. Today your task is to implement such an automatic che...
```python import string s = set(input()) print(('Too weak', 'Correct')[len(s) >= 5 and len(s & set(string.ascii_lowercase)) > 0 and \ len(s & set(string.ascii_uppercase)) > 0 and \ len(s & set(string.digits)) > 0]) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word *s*. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, ...
```python a=input() b="hello" j=0 c="" for i in range(0,len(a)): if a[i]==b[j] and c!=b and j<=4: c=c+b[j] j=j+1 else: continue if c==b: break if c==b: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya loves long lucky numbers very much. He is interested in the minimum lucky number *d* that me...
```python from math import * from fractions import * from sys import * def li(): return list(map(int, input().split(" "))) a = li() if abs(a[2]-a[3]) > 1: print(-1) exit() if a[2] == a[3]: ans = "47"*a[2]+"4" elif a[2] > a[3]: ans = "47"*a[2] else: ans = "74"*a[3] f = a[0]-ans.count("4") s =...
MatrixStudio/Codeforces-Python-Submissions
One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality ...
```python for n in range(int(input())): a,b=input().split() if a!=b: print("Happy Alex") exit() print("Poor Alex") ```
MatrixStudio/Codeforces-Python-Submissions
Once Bob took a paper stripe of *n* squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into two pieces so that the sum of numbers from one piece is equal to the sum of numbers from the other piece, ...
```python n=int(input()) a=list(map(int,input().split())) s,s1=0,[] for i in range(n): s+=a[i] s1.append(s) s,s2=0,[] for i in range(n): s+=a[n-i-1] s2=[s]+s2 ans=0 for i in range(n-1): if s1[i]==s2[i+1]: ans+=1 print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
In the Bus of Characters there are $n$ rows of seat, each having $2$ seats. The width of both seats in the $i$-th row is $w_i$ centimeters. All integers $w_i$ are distinct. Initially the bus is empty. On each of $2n$ stops one passenger enters the bus. There are two types of passengers: - an introvert always choose...
```python n = int(input()) u = list(map(int, input().split())) for i in range(n): u[i] = (u[i], i) h = list(map(int, list(input()))) def f(t): return t[0] k = 2 * n p = [0] * k ex = [] it = u[:] it.sort(key = f) ind = 0 for i in range(k): if not h[i]: p[i] = it[ind][1] + 1 ex...
MatrixStudio/Codeforces-Python-Submissions
Summer holidays! Someone is going on trips, someone is visiting grandparents, but someone is trying to get a part-time job. This summer Noora decided that she wants to earn some money, and took a job in a shop as an assistant. Shop, where Noora is working, has a plan on the following *n* days. For each day sales manag...
```python # Problem: B. Summer sell-off # Contest: Codeforces - Codeforces Round #415 (Div. 2) # URL: https://codeforces.com/contest/810/problem/B # Memory Limit: 256 MB # Time Limit: 1000 ms # Powered by CP Editor (https://github.com/cpeditor/cpeditor) from sys import stdin def get_ints(): return list(map(i...
MatrixStudio/Codeforces-Python-Submissions
You are given an array of *n* integer numbers *a*0,<=*a*1,<=...,<=*a**n*<=-<=1. Find the distance between two closest (nearest) minimums in it. It is guaranteed that in the array a minimum occurs at least two times.
```python x=int(input()) a=list(map(int,input().split())) y=min(a) f=9999999999 s=-111111 for i in range(len(a)): if a[i]==y: f=min(f,i-s) s = i print(f) ```
MatrixStudio/Codeforces-Python-Submissions
Luba is surfing the Internet. She currently has *n* opened tabs in her browser, indexed from 1 to *n* from left to right. The mouse cursor is currently located at the *pos*-th tab. Luba needs to use the tabs with indices from *l* to *r* (inclusive) for her studies, and she wants to close all the tabs that don't belong ...
```python n,pos,l,r=[*map(int,input().split())] if(l==1 and r==n): print(0) elif(l==1): print((abs(r-pos))+1) elif(r==n): print(abs(pos-l)+1) else: print(min((pos-l)*2+abs(r-pos)+2,(pos-l)+abs(r-pos)*2+2)) ```
MatrixStudio/Codeforces-Python-Submissions
Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10*k*. In the given number of *n* Polycarp wants to remove the least number of digits to get a number that is divisible by 10*k*. For example, if *k*<==<=3, in the number 30020 it is enough to delete a single digit (2). In this case, t...
```python n, k = input().split() k = int(k) tot = n.count('0') if tot < k: print(len(n)-1) else: zeros, ans = 0, 0 j = len(n)-1 while zeros < k: if n[j] == '0': zeros += 1 else: ans += 1 j -= 1 print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him. One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For e...
```python n = int(input()) a = list(map(int,input().split())) k=0 mx=a[0] mn=a[0] for i in a: if i>mx: mx=i k+=1 elif i<mn: mn=i k+=1 print(k) ```
MatrixStudio/Codeforces-Python-Submissions
Bob programmed a robot to navigate through a 2d maze. The maze has some obstacles. Empty cells are denoted by the character '.', where obstacles are denoted by '#'. There is a single robot in the maze. Its start position is denoted with the character 'S'. This position has no obstacle in it. There is also a single ex...
```python def check(perm) : global sx, sy, dx, dy, m, n, instr x = sx y = sy for d in instr : dir = perm[ord(d) - ord('0')] x = x + dx[dir] y = y + dy[dir] #if perm == [2, 3, 0, 1] : # print(x, y) if x < 0 or x >= m or y < 0 or y >= n : return 0 if s[x][y] == '#' : return 0 if ...
MatrixStudio/Codeforces-Python-Submissions
Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone. In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules o...
```python calory_for_strip = list(map(int, input().split())) s = input() calories_wasted = 0 for n in s: calories_wasted += calory_for_strip[int(n) - 1] print(calories_wasted) ```
MatrixStudio/Codeforces-Python-Submissions
Bash has set out on a journey to become the greatest Pokemon master. To get his first Pokemon, he went to Professor Zulu's Lab. Since Bash is Professor Zulu's favourite student, Zulu allows him to take as many Pokemon from his lab as he pleases. But Zulu warns him that a group of *k*<=&gt;<=1 Pokemon with strengths {*...
```python # LUOGU_RID: 122374120 #include <bits/stdc++.h> #define F(i,s,e) for(int i=s;i<=e;i++) using namespace std; const int maxn=1e5+1000; int a,t[maxn],ans,n,m; int main() { scanf("%d",&n); F(i,1,n){ scanf("%d",&a[i]); m=1; while(a>1){ if(m*m>a+2)break; m++; if(!...
MatrixStudio/Codeforces-Python-Submissions
Greg is a beginner bodybuilder. Today the gym coach gave him the training plan. All it had was *n* integers *a*1,<=*a*2,<=...,<=*a**n*. These numbers mean that Greg needs to do exactly *n* exercises today. Besides, Greg should repeat the *i*-th in order exercise *a**i* times. Greg now only does three types of exercise...
```python n=int(input()) chest=0 biceps=0 back=0 line=input().split() if 1<=n<=20: for i in range(0, n, 3): if i<n: chest+=int(line[i]) if i+1<n: biceps+=int(line[i+1]) if i+2<n: back+=int(line[i+2]) if chest>biceps and chest>back: print('chest') elif biceps>chest and biceps>back: pr...
MatrixStudio/Codeforces-Python-Submissions
PolandBall is a young, clever Ball. He is interested in prime numbers. He has stated a following hypothesis: "There exists such a positive integer *n* that for each positive integer *m* number *n*·*m*<=+<=1 is a prime number". Unfortunately, PolandBall is not experienced yet and doesn't know that his hypothesis is inc...
```python def ispr(n): if n == 2 or n == 3: return True if n % 2 == 0 or n % 3 == 0 or n < 2: return False k = 5 while k * k <= n: if n % k == 0 or n % (k + 2) == 0: return False k += 6 return True n = int(input()) for x in range(1, 1001): if not ispr(n * x + 1): ...
MatrixStudio/Codeforces-Python-Submissions
Pashmak decided to give Parmida a pair of flowers from the garden. There are *n* flowers in the garden and the *i*-th of them has a beauty number *b**i*. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty diff...
```python k=int(input()) l=list(map(int,input().split())) l.sort() m=(l[k-1]-l[0]) count=0 for i in range(k//2): if max(l[k-1-i]-l[i],l[i]-l[k-1-i]>=m): count+=1 print(m,count**2) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya decided to write an anonymous letter cutting the letters out of a newspaper heading. He knows heading *s*1 and text *s*2 that he wants to send. Vasya can use every single heading letter no more than once. Vasya doesn't have to cut the spaces out of the heading — he just leaves some blank space to mark them. Help ...
```python from collections import defaultdict strx=input() text=input() dict1=defaultdict(int) for l in strx: dict1[l]+=1 for l in text: if l.isalpha() and l in dict1 and dict1[l]!=0: dict1[l]-=1 elif l.isalpha() and dict1[l]==0: print('NO') exit() print('YES') ```
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 W=int(input("enter weight from 1 to 100)) if W%2==0 and 1<=W<=100 : Y=W/2 if Y %2==0: print("YES") else : print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
String can be called correct if it consists of characters "0" and "1" and there are no redundant leading zeroes. Here are some examples: "0", "10", "1001". You are given a correct string *s*. You can perform two different operations on this string: 1. swap any pair of adjacent characters (for example, "101" "110"...
```python import numpy as np m = input() bin = int(input()) y = str(bin) z = y.count('0') print(np.binary_repr(2**z)) ```
MatrixStudio/Codeforces-Python-Submissions
Ternary numeric notation is quite popular in Berland. To telegraph the ternary number the Borze alphabet is used. Digit 0 is transmitted as «.», 1 as «-.» and 2 as «--». You are to decode the Borze code, i.e. to find out the ternary number given its representation in Borze alphabet.
```python user_input = input() answer = user_input.replace('--','2') answer = answer.replace('-.','1') answer = answer.replace('.','0') print(answer) ```
MatrixStudio/Codeforces-Python-Submissions
Imp is watching a documentary about cave painting. Some numbers, carved in chaotic order, immediately attracted his attention. Imp rapidly proposed a guess that they are the remainders of division of a number *n* by all integers *i* from 1 to *k*. Unfortunately, there are too many integers to analyze for Imp. Imp wan...
```python from sys import stdin,stdout n,k=map(int,input().split()) print(["Yes","No"][any((n+1)%i for i in range(2,k+1))]) ```
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()) l=list(map(int,input().split())) l1 = list(map(int,input().split())) l2 = list(map(int,input().split())) for i in l: if i not in l1: print(i) break for i in l1: if i not in l2: print(i) break ```
MatrixStudio/Codeforces-Python-Submissions
You are given names of two days of the week. Please, determine whether it is possible that during some non-leap year the first day of some month was equal to the first day of the week you are given, while the first day of the next month was equal to the second day of the week you are given. Both months should belong t...
```python d = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'] a, b = input(), input() x, y = d.index(a), d.index(b) if (y - x) % 7 in {0, 2, 3}: print('YES') else: print('NO') ```
MatrixStudio/Codeforces-Python-Submissions
A coordinate line has *n* segments, the *i*-th segment starts at the position *l**i* and ends at the position *r**i*. We will denote such a segment as [*l**i*,<=*r**i*]. You have suggested that one of the defined segments covers all others. In other words, there is such segment in the given set, which contains all oth...
```python n = int(input()) a = 1000000001 b = i1 = -1 i2 = -2 for i in range(n): x, y = map(int, input().split()) if x < a: a = x i1 = i elif x == a and y > b: i1 = i2 = i b = y if y > b: b = y i2 = i elif y == b and x < a: a = x i1 = ...
MatrixStudio/Codeforces-Python-Submissions
You are given *n*<=×<=*m* table. Each cell of the table is colored white or black. Find the number of non-empty sets of cells such that: 1. All cells in a set have the same color. 1. Every two cells in a set share row or column.
```python n,m=map(int,input().split()) a = [list(map(int,input().split())) for x in range(n)] s = 0 for row in a: o,z=0,0 for i in row: if i==0: z+=1 else: o+=1 s+=2**z-1 s+=2**o-1 for col in range(m): o,z=0,0 for j in range(n): if a...
MatrixStudio/Codeforces-Python-Submissions
The HR manager was disappointed again. The last applicant failed the interview the same way as 24 previous ones. "Do I give such a hard task?" — the HR manager thought. "Just raise number 5 to the power of *n* and get last two digits of the number. Yes, of course, *n* can be rather big, and one cannot find the power us...
```python n=int(input()) print(5**n,end="") ```
MatrixStudio/Codeforces-Python-Submissions
A coordinate line has *n* segments, the *i*-th segment starts at the position *l**i* and ends at the position *r**i*. We will denote such a segment as [*l**i*,<=*r**i*]. You have suggested that one of the defined segments covers all others. In other words, there is such segment in the given set, which contains all oth...
```python # Tran Duy_ Big 0 Blue n = input() n = int(n) pos = -1 segment_areas = [] check = False def iscovered(bigseg, smallseg): return bigseg[0] <= smallseg[0] and bigseg[1] >= smallseg[1] for i in range(1, n+1): # Nhap segment seg = list(map(int, input().split())) if not segment_are...
MatrixStudio/Codeforces-Python-Submissions
Sereja and Dima play a game. The rules of the game are very simple. The players have *n* cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. Th...
```python def li(): return list(map(int,input().split())) def gi(n): return [list(map(int,input().split())) for _ in range(n)] # File input # import sys # sys.stdin = open('user.txt','r') n = int(input()) a = li() s = d = 0 l , r = 0 , n - 1 while l <= r: if a[l] > a[r]: s += a[l]...
MatrixStudio/Codeforces-Python-Submissions
The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups. Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime. If there is no police offi...
```python def untreatedCrimes(n, events): available = 0 untreated = 0 for event in events: if event == -1: if available == 0: untreated += 1 else: available -= 1 else: available += event return untreated n ...
MatrixStudio/Codeforces-Python-Submissions
Kefa decided to make some money doing business on the Internet for exactly *n* days. He knows that on the *i*-th day (1<=≤<=*i*<=≤<=*n*) he makes *a**i* money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence *a**i*. Let us remind you that the subsegment o...
```python t = int(input()) arr = list(map(int, input().split())) count = 1 ans = 1 for i in range(len(arr) - 1): if arr[i] <= arr[i+1]: count+=1 else: ans = max(count,ans) count = 1 ans = max(count,ans) print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
It's one more school day now. Sasha doesn't like classes and is always bored at them. So, each day he invents some game and plays in it alone or with friends. Today he invented one simple game to play with Lena, with whom he shares a desk. The rules are simple. Sasha draws *n* sticks in a row. After that the players t...
```python e,b=input().split() e=int(e) b=int(b) ans=e//b if(ans%2==1): print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Zane the wizard had never loved anyone before, until he fell in love with a girl, whose name remains unknown to us. The girl lives in house *m* of a village. There are *n* houses in that village, lining in a straight line from left to right: house 1, house 2, ..., house *n*. The village is also well-structured: house ...
```python n,m,k=map(int,input().split()) a=list(map(int,input().split())) min1=float("inf") for i in range(n): if a[i]!=0 and a[i]<=k and min1>(abs( (m-1)-(a[i]) )*10): min1=(abs( (m-1)-(i) )*10) print(min1) ```
MatrixStudio/Codeforces-Python-Submissions
Everyone loves a freebie. Especially students. It is well-known that if in the night before exam a student opens window, opens the student's record-book and shouts loudly three times "Fly, freebie, fly!" — then flown freebie helps him to pass the upcoming exam. In the night before the exam on mathematical analysis *n...
```python import math n = int(input()) a = list(map(int,input().strip().split()))[:n] t=int(input()) a.sort() c=0 for i in range(0,n-1,1): if(math.fabs(a[i]-a[i+1])<=t): c+=1 else: continue print(c) ```
MatrixStudio/Codeforces-Python-Submissions
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word. Note, that during capitalization all the letters except the first one remains unchanged.
```python word=input() print(word[0].upper()+word[1:len(word)]) ```
MatrixStudio/Codeforces-Python-Submissions
The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a pla...
```python n = int(input()) players = dict() winner = ('',0) for round in range(n): name, points = input().split() points = int(points) if name not in players: players[name] = points else: players[name] += points players_scores = list(players.values()) max...
MatrixStudio/Codeforces-Python-Submissions
"What a pity it's already late spring," sighs Mino with regret, "one more drizzling night and they'd be gone." "But these blends are at their best, aren't they?" Absorbed in the landscape, Kanno remains optimistic. The landscape can be expressed as a row of consecutive cells, each of which either contains a flower o...
```python n=input() a='ABC' b='ACB' c='BAC' d='BCA' e='CAB' f='CBA' x=n.split('.') if a in n: print('Yes') elif b in n: print('Yes') elif c in n: print('Yes') elif d in n: print('Yes') elif e in n: print('Yes') elif f in n: print('Yes') else: print('No') ```
MatrixStudio/Codeforces-Python-Submissions
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area. Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no e...
```python def f(a): if a[0][0] == a[1][0] and a[0][1] + a[1][1] == a[2][0] and a[0][0] + a[2][1] == a[2][0]: try: print(a[2][0]) ans = [''] * a[2][0] for i in range(a[0][0]): for j in range(a[0][1]): ans[i] += a[0][2] ...
MatrixStudio/Codeforces-Python-Submissions
A number is called quasibinary if its decimal representation contains only digits 0 or 1. For example, numbers 0, 1, 101, 110011 — are quasibinary and numbers 2, 12, 900 are not. You are given a positive integer *n*. Represent it as a sum of minimum number of quasibinary numbers.
```python li=[] ans=[] for i in range(1,65) : li.append(int(bin(i).replace("0b", ""))); a1=[] a2=[] temp1=0 temp2=0 n=int(input()) ans.append(0) ans.append(1) a1.append(0) a1.append(1) a2.append(0) a2.append(1) for i in range(2,n+1) : count=0 for j in li : if j<=i : ...
MatrixStudio/Codeforces-Python-Submissions
There are *n* cards (*n* is even) in the deck. Each card has a positive integer written on it. *n*<=/<=2 people will play new card game. At the beginning of the game each player gets two cards, each card is given to exactly one player. Find the way to distribute cards such that the sum of values written of the cards ...
```python n = int(input()) N = list(map(int,input().split())) s = 0 for i in range(n): s += N[i] ch = s // (n // 2) print(ch) for i in range(n -1): for j in range(n -1): if N[i] + N[j] == ch: print(i, j) N.remove(N[i]) N.remove(N[j]) ```
MatrixStudio/Codeforces-Python-Submissions
You've got a 5<=×<=5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix: 1....
```python cords = [0, 0] def find_one_in_matrix_line(str_arr): for k in range(0, 5): if str_arr[k] == '1': return k return -1 for i in range(0, 5): matrixLine = str(input()).split(" ") j = find_one_in_matrix_line(matrixLine) if j == -1: continue els...
MatrixStudio/Codeforces-Python-Submissions
The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her *n* students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often od...
```python n,m=map(lambda x: int(x), input().split()) arr=sorted(list(map(lambda x: int(x), input().split()))) minn=500000 for i in range(n-1,m): minn=min(minn,arr[i]-arr[i-n+1]) print(minn) ```
MatrixStudio/Codeforces-Python-Submissions
You are given a sequence *a* consisting of *n* integers. Find the maximum possible value of (integer remainder of *a**i* divided by *a**j*), where 1<=≤<=*i*,<=*j*<=≤<=*n* and *a**i*<=≥<=*a**j*.
```python import bisect n = int(input()) arr = set(map(int,input().split())) ls = sorted(arr) ans = 0 mx = max(arr) for c in ls[::-1]: if c-1<ans: break kc = c+c while kc<=2*mx: ind = bisect.bisect_left(ls,kc) ans = max(ans,ls[ind-1]%c) kc+=c print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Small, but very brave, mouse Brain was not accepted to summer school of young villains. He was upset and decided to postpone his plans of taking over the world, but to become a photographer instead. As you may know, the coolest photos are on the film (because you can specify the hashtag #film for such). Brain took a ...
```python n, m = map(int, input().split()) colors = [list(map(str, input().split())) for _ in range(n)] if any('C' in row or 'M' in row or 'Y' in row for row in colors): print("#Color") else: print("#Black&White") ```
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 s = input() k = 0 vowel = "aeiou" res = "" for c in s: if c in vowel: k = 0 else: k += 1 if k == 3: res += " " k = 0 res += c print(res) ```
MatrixStudio/Codeforces-Python-Submissions
Small, but very brave, mouse Brain was not accepted to summer school of young villains. He was upset and decided to postpone his plans of taking over the world, but to become a photographer instead. As you may know, the coolest photos are on the film (because you can specify the hashtag #film for such). Brain took a ...
```python class Solution(): def brains_photos(): row, column = map(int, input().split()) colors = ["Y", "C", "M"] for i in range(row): color = input().split() if 'Y' in color or 'C' in color or 'M' in color: return '#Color' return '#Black&...
MatrixStudio/Codeforces-Python-Submissions
Mr. Santa asks all the great programmers of the world to solve a trivial problem. He gives them an integer *m* and asks for the number of positive integers *n*, such that the factorial of *n* ends with exactly *m* zeroes. Are you among those great programmers who can solve this problem?
```python from sys import exit m = int(input()) i = 4 pows = [5**i for i in range(100)] while 1: i += 1 l = 1 r = 100 while l < r: cur = (l + r + 1) // 2 if i % pows[cur] == 0: l = cur else: r = cur - 1 m -= l if m == 0: break i...
MatrixStudio/Codeforces-Python-Submissions
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it: - deletes all the vowels, - inserts a character "." before each consonant, - replaces ...
```python a = input() b = ['A', 'a', 'E', 'e', 'i', 'I', 'O', 'o', 'U', 'u', 'Y', 'y'] result = ''.join([char for char in a if char not in b]) upper = result.lower() print('.',end = '') result_string = '.'.join(upper) print(result_string) ```
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 import math n,m=map(int,input().split());c=n;c1=1 while n//m>=1: if (n//m)%m !=0: c+=(n//m)+1 else: c+=(n//m) n//=m print(c-1) ```
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()) s= [] for i in range(n): s.append(input()) val = { "Tetrahedron": 4, "Cube":6, "Octahedron": 8, "Dodecahedron": 12, "Icosahedron": 20 } total = 0 for i in s: total += val[i] print(total) ```
MatrixStudio/Codeforces-Python-Submissions
Bob has a permutation of integers from 1 to *n*. Denote this permutation as *p*. The *i*-th element of *p* will be denoted as *p**i*. For all pairs of distinct integers *i*,<=*j* between 1 and *n*, he wrote the number *a**i*,<=*j*<==<=*min*(*p**i*,<=*p**j*). He writes *a**i*,<=*i*<==<=0 for all integer *i* from 1 to *n...
```python from sys import stdin as fin # fin = open("wfr2016b.in", "r") n = int(fin.readline()) ans = [None] * n maxv = 1 for i in range(n): line = tuple(map(int, fin.readline().split())) cnt = [False] * (n + 1) for j in range(n): if not cnt[line[j]]: cnt[line[j]] = True else: ...
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 a=int(input()) if a %2==0 and a>2: print("yes") else: print("no") ```
MatrixStudio/Codeforces-Python-Submissions
Some days ago, I learned the concept of LCM (least common multiple). I've played with it for several times and I want to make a big number with it. But I also don't want to use many numbers, so I'll choose three positive integers (they don't have to be distinct) which are not greater than *n*. Can you help me to find ...
```python import math t=int(input())) if t<3: print(t) else: if t%2==1: ans=(t-1)*t*(t-2) elif math.gcd(t,t-3)==1 and math.gcd(t-1,t-3)==1: ans=max((t-1)*(t-2)*(t-3),t*(t-1)*(t-3)) else: ans=(t-1)*(t-2)*(t-3) print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
One particularly well-known fact about zombies is that they move and think terribly slowly. While we still don't know why their movements are so sluggish, the problem of laggy thinking has been recently resolved. It turns out that the reason is not (as previously suspected) any kind of brain defect – it's the opposite!...
```python # Python program to check if a given directed graph is strongly # connected or not import sys from collections import defaultdict class Graph: def __init__(self, V): self.V = V self.graph = defaultdict(list) def addEdge(self, v, w): # Add w to v ist. self.graph[v].ap...
MatrixStudio/Codeforces-Python-Submissions
In the beginning of the new year Keivan decided to reverse his name. He doesn't like palindromes, so he changed Naviek to Navick. He is too selfish, so for a given *n* he wants to obtain a string of *n* characters, each of which is either 'a', 'b' or 'c', with no palindromes of length 3 appearing in the string as a su...
```python n = int(input()) s = 'bbaa' * (n // 4 + 1) s = s[:n] print(s) ```
MatrixStudio/Codeforces-Python-Submissions
One fine October day a mathematics teacher Vasily Petrov went to a class and saw there *n* pupils who sat at the desks, two people at each desk. Vasily quickly realized that number *n* is even. Like all true mathematicians, Vasily has all students numbered from 1 to *n*. But Vasily Petrov did not like the way the chi...
```python for case in range(int(input())): n = int(input()) s = input() for i in range(n): if s[i] == 'L': print(f"{i + 1} {i + 1 + n//2}") else: print(f"{i + 1 + n//2} {i + 1}") ```
MatrixStudio/Codeforces-Python-Submissions
According to rules of the Berland fashion, a jacket should be fastened by all the buttons except only one, but not necessarily it should be the last one. Also if the jacket has only one button, it should be fastened, so the jacket will not swinging open. You are given a jacket with *n* buttons. Determine if it is fast...
```python n = int(input()) l = list(map(int,input().split())) if n == 1: if l.count(0) == 1: print("NO") else: print("YES") else: x = l.count(0) if x == 1: print("YES") else:print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
In this problem you will write a simple generator of Brainfuck ([https://en.wikipedia.org/wiki/Brainfuck](https://en.wikipedia.org/wiki/Brainfuck)) calculators. You are given an arithmetic expression consisting of integers from 0 to 255 and addition/subtraction signs between them. Output a Brainfuck program which, whe...
```python n = eval(input()) for i in range(n)L print('+', end = ''); print('.') ```
MatrixStudio/Codeforces-Python-Submissions
Holidays have finished. Thanks to the help of the hacker Leha, Noora managed to enter the university of her dreams which is located in a town Pavlopolis. It's well known that universities provide students with dormitory for the period of university studies. Consequently Noora had to leave Vičkopolis and move to Pavlopo...
```python from math import factorial from math import gcd a, b = map(int, input().split()) af = factorial(a) bf = factorial(b) print(gcd(af, bf)) ```
MatrixStudio/Codeforces-Python-Submissions
Fox Ciel is in the Amusement Park. And now she is in a queue in front of the Ferris wheel. There are *n* people (or foxes more precisely) in the queue: we use first people to refer one at the head of the queue, and *n*-th people to refer the last one in the queue. There will be *k* gondolas, and the way we allocate go...
```python #include <bits/stdc++.h> namespace std { template<class Fun> class y_combinator_result { Fun fun_; public: template<class T> explicit y_combinator_result(T &&fun): fun_(std::forward<T>(fun)) {} template<class ...Args> decltype(auto) operator()(Args &&...args) { return fun_(std::ref(*thi...
MatrixStudio/Codeforces-Python-Submissions
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line. Unfortunately, from time to ti...
```python x=set(input()) l=len(x)-2 if("," in x): print(l-1) else: print(l) ```
MatrixStudio/Codeforces-Python-Submissions
As a tradition, every year before IOI all the members of Natalia Fan Club are invited to Malek Dance Club to have a fun night together. Malek Dance Club has 2*n* members and coincidentally Natalia Fan Club also has 2*n* members. Each member of MDC is assigned a unique id *i* from 0 to 2*n*<=-<=1. The same holds for eac...
```python M = 10 ** 9 + 7 def solve1(x): n = len(x) x = int(x, 2) ans = 0 for a in range(2 ** n): for c in range(2 ** n): b = a ^ x d = c ^ x if a < c and b > d: ans += 1 return ans % M def solve2(x): return int(x, 2) * pow(2, (len(x) ...
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 """ Created on Sat Jan 12 23:33:17 2019 """ s = input() res = 0 for i in range(len(s)): t = int(s[i]) if t % 4 == 0: res += 1 if i > 0: if (int(s[i - 1]) * 10 + t) % 4 == 0: res += i print(res) ```
MatrixStudio/Codeforces-Python-Submissions
*n* hobbits are planning to spend the night at Frodo's house. Frodo has *n* beds standing in a row and *m* pillows (*n*<=≤<=*m*). Each hobbit needs a bed and at least one pillow to sleep, however, everyone wants as many pillows as possible. Of course, it's not always possible to share pillows equally, but any hobbit ge...
```python def read(type=int): return type(input()) def read_arr(type=int): return [type(token) for token in input().split()] def runB(): n, m, k = read_arr() ans = 1 m -= n l = r = k while r - l + 1 < n: ans += 1 m -= (r - l + 1) if l > 1: ...
MatrixStudio/Codeforces-Python-Submissions
«One dragon. Two dragon. Three dragon», — the princess was counting. She had trouble falling asleep, and she got bored of counting lambs when she was nine. However, just counting dragons was boring as well, so she entertained herself at best she could. Tonight she imagined that all dragons were here to steal her, and ...
```python import math k, l, m, n, d= map(int, input().split()) check=[] for i in range(d): check.append(i+1) for ks in range(math.floor(d/k)): if (ks+1)*k in check: check.remove((ks+1)*k) for ls in range(math.floor(d/l)): if (ls+1)*l in check: check.remove((ls+1)*l) for ms in rang...
MatrixStudio/Codeforces-Python-Submissions
You are given array consisting of *n* integers. Your task is to find the maximum length of an increasing subarray of the given array. A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray strictly greater than previous.
```python n = int(input()) array = [int(x) for x in input().split()] dp = [1]*(n+1) dp[0] = 0 for i in range(0,n-1): if array[i+1] > array[i]: dp[i+2] = dp[i+1] +1 print(max(dp)) ```
MatrixStudio/Codeforces-Python-Submissions
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures). There are *n* members, numbered 1 through *n*. *m* pairs of members are friends. Of course, a member can't be a friend with themselves. Let A-B denote that...
```python from collections import defaultdict n, m = map(int, input().split()) d = defaultdict(list) for i in range(m): u, v = map(int, input().split()) d[u].append(v) d[v].append(u) for i in range(n): d[i + 1].append(i + 1) d[i + 1].sort() v = [0] * (n + 1) for i in range(1, n +...
MatrixStudio/Codeforces-Python-Submissions
You are given two arrays *A* and *B* consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose *k* numbers in array *A* and choose *m* numbers in array *B* so that any number chosen in the first array is strictly less than any number chosen in the second array.
```python def bol(a,b,k,m): if a[k-1]<b[len(b)-m]: print('YES') else: print('NO') # print(a[k-1]) # print(b[len(b)-m]) n=list(map(int,input('').split())) para=list(map(int,input('').split())) a=list(map(int,input('').split())) b=list(map(int,input('').split())) bol(a,b,p...
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 from sys import stdin def main(): m, n = list(map(int, stdin.readline().strip().split())) print(m * n // 2) main() ```
MatrixStudio/Codeforces-Python-Submissions
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition. Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character...
```python s = input() p, c = 'a', 0 for i in s: l, r = ord(i)-97, ord(p)-97 n = min(l, r) m = max(l, r) s1 = n-m+26 s2 = m-n c += min(s1, s2) p = i print(c) ```
MatrixStudio/Codeforces-Python-Submissions
Lolek and Bolek are about to travel abroad by plane. The local airport has a special "Choose Your Plane" offer. The offer's conditions are as follows: - it is up to a passenger to choose a plane to fly on; - if the chosen plane has *x* (*x*<=&gt;<=0) empty seats at the given moment, then the ticket for such a plane ...
```python n,m = list(map(int,input().split())) left = list(map(int,input().split())) right = left[:] maxx = 0 minn = 0 for i in range(n): temp=left.index(max(left)) maxx+=max(left) left[temp] = left[temp]-1 for i in range(n): temp=right.index(min(right)) #print('temp',temp) i...
MatrixStudio/Codeforces-Python-Submissions
You are given a sequence *a* consisting of *n* integers. Find the maximum possible value of (integer remainder of *a**i* divided by *a**j*), where 1<=≤<=*i*,<=*j*<=≤<=*n* and *a**i*<=≥<=*a**j*.
```python from collections import defaultdict as dd from sys import stdin input = stdin.buffer.readline L = lambda : list(map(int,input().split())) n = L()[0] A = L() if n == 1: print(0) exit() A.sort() l = 0 r = A[-2]-1 if r == 0: print(0) exit() divs_list = dd(set) for ...
MatrixStudio/Codeforces-Python-Submissions
Professor GukiZ makes a new robot. The robot are in the point with coordinates (*x*1,<=*y*1) and should go to the point (*x*2,<=*y*2). In a single step the robot can change any of its coordinates (maybe both of them) by one (decrease or increase). So the robot can move in one of the 8 directions. Find the minimal numbe...
```python w,h=map(int,input().split()) u,a=map(int,input().split()) print(max(abs(w-u),abs(h-a))) ```
MatrixStudio/Codeforces-Python-Submissions
Mishka is decorating the Christmas tree. He has got three garlands, and all of them will be put on the tree. After that Mishka will switch these garlands on. When a garland is switched on, it periodically changes its state — sometimes it is lit, sometimes not. Formally, if *i*-th garland is switched on during *x*-th s...
```python k1, k2, k3 = map(int, input().split()) a = [] for i in range(0, 1500 + 10) : a.append(0) a[k1] += 1 a[k2] += 1 a[k3] += 1 if (a[1] > 0) : print('YES') elif (a[2] >= 2) : print('YES') elif (a[3] >= 3) : print('YES') elif ((a[2] > 0) and (a[4] >= 2)) : print('YES') else : print('NO') ```
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 import sys input = sys.stdin.readline ############ ---- Input Functions ---- ############ def inp(): return int(input()) def inlt(): return list(map(int, input().split())) def insr(): s = input() return list(s[:len(s) - 1]) def invr(): return map(int, input().split()) ...
MatrixStudio/Codeforces-Python-Submissions
The circle line of the Berland subway has *n* stations. We know the distances between all pairs of neighboring stations: - *d*1 is the distance between the 1-st and the 2-nd station;- *d*2 is the distance between the 2-nd and the 3-rd station;...- *d**n*<=-<=1 is the distance between the *n*<=-<=1-th and the *n*-th ...
```python n=int(input()) a=list(map(int,input().split(' '))) s,t=map(int,input().split(' ')) if s!=t: s-=1 t-=1 temp1=a[s] temp2=a[t] a[s]=-1 a[t]=-1 b=a[max(s,t):n]+a[0:max(s,t)] var1=sum(a[min(s,t)+1:max(s,t)])+temp2 var2=sum(b[b.index(-1)+1:n-1-b[::-1].index(-1)])+temp1 print(min(var1,var2)) ...
MatrixStudio/Codeforces-Python-Submissions
You are given string *s*. Your task is to determine if the given string *s* contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order).
```python a = input() if 'AB' in a and 'BA' in a and abs(min(a.find('AB'), a.rfind('AB')) - min(a.find('BA'), a.rfind('BA'))) > 1: print('YES') else: print('NO') ```
MatrixStudio/Codeforces-Python-Submissions
You are given *n* points on a line with their coordinates *x**i*. Find the point *x* so the sum of distances to the given points is minimal.
```python n = int(input()) x = input().split() x = [int(i) for i in x] x.sort() if(n % 2 == 1): print(x[n//2+1]) else: print((x[n//2]+x[n//2-1])//2) ```
MatrixStudio/Codeforces-Python-Submissions
Andryusha is an orderly boy and likes to keep things in their place. Today he faced a problem to put his socks in the wardrobe. He has *n* distinct pairs of socks which are initially in a bag. The pairs are numbered from 1 to *n*. Andryusha wants to put paired socks together and put them in the wardrobe. He takes the ...
```python n = int(input()) a = [int(x) for x in input().split()] maxn = maxans = 0 used = [True] * n for i in range(n * 2): if used[a[i] - 1]: used[a[i] - 1] = False maxn += 1 elif not used[a[i] - 1]: maxn -= 1 if maxn > maxans: maxans = maxn print(maxans) ```
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 colors = list(map(int, input().split())) i = 0 j = 1 same = 1 while True: if i == 3: break while True: if j == 4: break if colors[i] == colors[j]: same += 1 j += 1 i += 1 print(same - 1) ```
MatrixStudio/Codeforces-Python-Submissions
Today is Wednesday, the third day of the week. What's more interesting is that tomorrow is the last day of the year 2015. Limak is a little polar bear. He enjoyed this year a lot. Now, he is so eager to the coming year 2016. Limak wants to prove how responsible a bear he is. He is going to regularly save candies for ...
```python help = list(input().split()) count_week = 366 // 7 if help[2] == 'week': if int(help[0]) == 5 or int(help[0]) == 6 or int(help[0]) == 7: print(53) else: print(52) else: if int(help[0]) == 29: print(12) elif int(help[0]) == 30: print(11) else: ...
MatrixStudio/Codeforces-Python-Submissions
Once Bob got to a sale of old TV sets. There were *n* TV sets at that sale. TV set with index *i* costs *a**i* bellars. Some TV sets have a negative price — their owners are ready to pay Bob if he buys their useless apparatus. Bob can «buy» any TV sets he wants. Though he's very strong, Bob can carry at most *m* TV set...
```python n,m,= map(int, input().split()) arr= list(map(int, input().split())) arr.sort() sum=0 for i in range(m): sum+=arr[i] print(-sum) ```
MatrixStudio/Codeforces-Python-Submissions
When Petya went to school, he got interested in large numbers and what they were called in ancient times. For instance, he learned that the Russian word "tma" (which now means "too much to be counted") used to stand for a thousand and "tma tmyschaya" (which literally means "the tma of tmas") used to stand for a million...
```python import math k,l=int(input()),int(input()) im=math.log(l,k)-1 if im==int(im): print("YES",int(im),sep='\n') else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Noora is a student of one famous high school. It's her final year in school — she is going to study in university next year. However, she has to get an «A» graduation certificate in order to apply to a prestigious one. In school, where Noora is studying, teachers are putting down marks to the online class register, wh...
```python from math import ceil,floor def avg(l): a=sum(l)/len(l) f=int(str(a)[str(a).index(".")+1]) if f>=5: a=ceil(a) else: a=floor(a) return a n, k = map(int, input().split()) marks = list(map(int, input().split())) avgm=avg(marks) count=0 while avgm!=k: marks.append(k) avgm=avg(marks) ...
MatrixStudio/Codeforces-Python-Submissions
Volodya has recently visited a very odd town. There are *N* tourist attractions in the town and every two of them are connected by a bidirectional road. Each road has some travel price (natural number) assigned to it and all prices are distinct. But the most striking thing about this town is that each city sightseeing ...
```python print("_RANDOM_GUESS_1689436872.9227185")# 1689436872.9227393 ```
MatrixStudio/Codeforces-Python-Submissions
Pasha has a wooden stick of some positive integer length *n*. He wants to perform exactly three cuts to get four parts of the stick. Each part must have some positive integer length and the sum of these lengths will obviously be *n*. Pasha likes rectangles but hates squares, so he wonders, how many ways are there to ...
```python def pasha(m,n,x): m = m + 2 x = x + 1 if m >= n: print(x) else: pasha(m,n,x) z = int(input()) x = 0 m = 2 if z%2 != 0: Print(0) else: n = z/2 pasha(m,n,x) ```
MatrixStudio/Codeforces-Python-Submissions
Innokentiy decides to change the password in the social net "Contact!", but he is too lazy to invent a new password by himself. That is why he needs your help. Innokentiy decides that new password should satisfy the following conditions: - the length of the password must be equal to *n*, - the password should cons...
```python n, k = map(int, input().split()) a = '' for i in range(97, 97+k): a += chr(i) print(a*(n//k), end = '') n -= (n//k)*k print(a[:n]) ```
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. Let *next*(*x*) be the minimum lucky number which is larger than or equals *x*. Petya is interested ...
```python from bisect import bisect_left s, e = [int(i) for i in input().split(" ")] res = [] curr = [] def lucky_combinations(curr, ctr): if 0 < ctr < len(str(e)) + 2 and (curr not in res): res.append(int("".join(curr))) if ctr == len(str(e)) + 2: return curr.append("4") lucky_combi...