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 two arrays of integers *a* and *b*. For each element of the second array *b**j* you should find the number of elements in array *a* that are less than or equal to the value *b**j*.
```python lengths = list(map(int, input().split())) a = list(map(int, input().split())) b = list(map(int, input().split())) res = [] a.sort() for i in range(len(b)): low = 0 high = lengths[0] chosen = 0 control = 0 while low < high: mid = int((low + high) // 2) if a[mid] <= b[i]: ...
MatrixStudio/Codeforces-Python-Submissions
Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you? You are given a system of equations: You should count, how many there are pairs of int...
```python import math n, m = [int(x) for x in input().split()] count = 0 a_limit = min(math.floor(math.sqrt(n)), m) b_limit = min(math.floor(math.sqrt(m)), n) for a in range(0, a_limit + 1): for b in range(0, b_limit + 1): if (a**2 + b) == n and (a + b**2) == m: count+=1 print(count) ...
MatrixStudio/Codeforces-Python-Submissions
You're given a row with $n$ chairs. We call a seating of people "maximal" if the two following conditions hold: 1. There are no neighbors adjacent to anyone seated. 1. It's impossible to seat one more person without violating the first rule. The seating is given as a string consisting of zeros and ones ($0$ means t...
```python def is_maximal(seating): # Count the number of zeros and ones in the seating zeros = seating.count("0") ones = seating.count("1") # Check if the seating is maximal if (zeros == 1 and ones == 0) or (ones == 1 and zeros == 0): return "Yes" else: return "No" #...
MatrixStudio/Codeforces-Python-Submissions
— Willem... — What's the matter? — It seems that there's something wrong with Seniorious... — I'll have a look... Seniorious is made by linking special talismans in particular order. After over 500 years, the carillon is now in bad condition, so Willem decides to examine it thoroughly. Seniorious has *n* pieces...
```python #warning By KonJAC_xrs #warning ( testing == 0 ) ? Yes : No #include<bits/stdc++.h> #define ll long long #define ull unsigned long long #define ld long double using namespace std; inline ll read() { ll x=0,f=1; char ch=getchar(); while (!isdigit(ch)) {if(ch=='-') f=-1; ch=getchar();} while ( isd...
MatrixStudio/Codeforces-Python-Submissions
В самолёте есть *n* рядов мест. Если смотреть на ряды сверху, то в каждом ряду есть 3 места слева, затем проход между рядами, затем 4 центральных места, затем ещё один проход между рядами, а затем ещё 3 места справа. Известно, что некоторые места уже заняты пассажирами. Всего есть два вида пассажиров — статусные (те, ...
```python from collections import Counter n,k=list(map(int,input().split())) #n,k=1,2 a=set() c=[set() for i in range(3)] b=set() z=0 for i in range(n): s=input() for i0 in range(len(s)): if s[i0]=='.': a.add(tuple([i,i0])) elif s[i0]=='S': b.add(tuple([i,i0]...
MatrixStudio/Codeforces-Python-Submissions
Jon fought bravely to rescue the wildlings who were attacked by the white-walkers at Hardhome. On his arrival, Sam tells him that he wants to go to Oldtown to train at the Citadel to become a maester, so he can return and take the deceased Aemon's place as maester of Castle Black. Jon agrees to Sam's proposal and Sam s...
```python n, l, r = map(int, input().split()) arr = [n] def helper(n): if n <=1: return elif n>1: substitute = [n//2, n%2,n//2] i = arr.index(n) arr[i:i+1] = substitute helper(n//2) helper(n%2) helper(n//2) helper(n) print(sum(arr[l-1:r])) ...
MatrixStudio/Codeforces-Python-Submissions
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given *n* numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given *n* numbers finds one that i...
```python n=int(input()) l=list(map(int,input().split())) even,odd,evenind,oddind=0,0,0,0 for i in range(n): if (l[i]%2==0): even += 1 evenind = i else: even -= 1 oddind = i if(even > 0): print(oddind+1) else: print(evenind+1) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya has become interested in wrestling. In wrestling wrestlers use techniques for which they are awarded points by judges. The wrestler who gets the most points wins. When the numbers of points of both wrestlers are equal, the wrestler whose sequence of points is lexicographically greater, wins. If the sequences of...
```python import math from decimal import * import random mod = int(1e9)+7 f, s = 0,0 x, y= [],[] last = -1 for _ in range(int(input())): n = int(input()) if(n>0): x.append(n) f+=n last = 1 else: y.append(abs(n)) s+=abs(n) last = 0 if(f>s): ...
MatrixStudio/Codeforces-Python-Submissions
Pasha loves his phone and also putting his hair up... But the hair is now irrelevant. Pasha has installed a new game to his phone. The goal of the game is following. There is a rectangular field consisting of *n* row with *m* pixels in each row. Initially, all the pixels are colored white. In one move, Pasha can choos...
```python n,m,k=map(int,input().split());l=[];ans=0 for i in range(n+2): t=[] for j in range(m+2): t.append(0) l.append(t) for i in range(k): p,q=map(int,input().split()) l[p][q]=1 if l[p-1][q-1]+l[p][q-1]+l[p-1][q]==3: ans=i+1;break if l[p-1][q]+l[p-1][q+1]+l[p][q...
MatrixStudio/Codeforces-Python-Submissions
Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity. There are *n* columns of toy cubes in the box arranged in a line. The *i*-th column contains *a**i* cubes. At first, the gravity in the box is...
```python n = input() li= list(map(int,input().split())) li.sort() for i in li: print(i,end=" ") ```
MatrixStudio/Codeforces-Python-Submissions
Little Elephant loves magic squares very much. A magic square is a 3<=×<=3 table, each cell contains some positive integer. At that the sums of integers in all rows, columns and diagonals of the table are equal. The figure below shows the magic square, the sum of integers in all its rows, columns and diagonals equals ...
```python a =[] for i in range(3): a.append(list(map(int,input().split()))) for n in range(1,10**5): s = n+ a[0][1] + a[0][2] k = s - a[1][0] - a[1][2] w = s - a[2][0] - a[2][1] if n+k+w==s: a[0][0] = n a[1][1] = k a[2][2] = w break for i in range(3): print(*a[i]) ```
MatrixStudio/Codeforces-Python-Submissions
Valera runs a 24/7 fast food cafe. He magically learned that next day *n* people will visit his cafe. For each person we know the arrival time: the *i*-th person comes exactly at *h**i* hours *m**i* minutes. The cafe spends less than a minute to serve each client, but if a client comes in and sees that there is no free...
```python t=int(input()) cash=1 i=0 M=[] for j in range(t): L=list(map(int,input().split(" "))) M.append(L) if j!=0: if M[j]==M[j-1]: i+=1 else: i=0 if i>=cash: cash+=1 print(cash) ```
MatrixStudio/Codeforces-Python-Submissions
"Hey, it's homework time" — thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him. The sequence of *n* integers is cal...
```python n = int(input()) ok = [False]*n inp = input().split(' ') count = n for i in inp: i = int(i)-1 if not ok[i]: count -= 1 ok[i] = True print(count) ```
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 n, k, M, D = map(int, input().split()) ans = 0 for i in range(1, D+1): x = n //((i-1)*k+1) if x <= M: ans = max(ans, x*i) if n//k <= M: ans = max(ans, n//k) else: ans = max(ans, M) print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Luba thinks about watering her garden. The garden can be represented as a segment of length *k*. Luba has got *n* buckets, the *i*-th bucket allows her to water some continuous subsegment of garden of length exactly *a**i* each hour. Luba can't water any parts of the garden that were already watered, also she can't wat...
```python import re x = input() res = 0 list_1 = re.split('\s', x,0) m = int(list_1[0]) y = int(list_1[1]) res = 0 str = input() list_2 = re.split('\s',str,0) for i in list_2: if y % int(i) == 0: res = int(i) print(int(y / res)) ```
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 input() a = sorted(list(map(int, input().split()))) print(a[-1] - a[0] if a[0] < 1 else sum(a)) ```
MatrixStudio/Codeforces-Python-Submissions
Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number *n*. How many times can Gerald put a spell on it until the number becomes one-...
```python n = input() c = 0 while int(n) > 9: temp = 0 c += 1 for i in n : temp += int(i) n = str(temp) # print(temp) print(c) ```
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 n, x = list(map(int, input().split(' '))) d = 0 for i in range(n): a, b = input().split(' ') b = int(b) if a == '+': x += b elif a == '-' and b <= x: x -= b else: d += 1 print(x, d) ```
MatrixStudio/Codeforces-Python-Submissions
Little Artem got *n* stones on his birthday and now wants to give some of them to Masha. He knows that Masha cares more about the fact of receiving the present, rather than the value of that present, so he wants to give her stones as many times as possible. However, Masha remembers the last present she received, so Art...
```python n = int(input()) a = [1, 1] for i in range(2, n): a.append(a[i - 1] + a[i - 2]) print(a[n - 1]) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word *s*. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, ...
```python s = input() a = [] for i in range(len(s)): if s[i] == 'h' and 1 not in a: a.append(1) elif s[i] == 'e' and a[-1] == 1: a.append(2) elif s[i] == 'l' and a[-1] == 2: a.append(3) elif s[i] == 'l' and a[-1] == 3: a.append(4) elif s[i] == 'o' and a[-1]...
MatrixStudio/Codeforces-Python-Submissions
We consider a positive integer perfect, if and only if the sum of its digits is exactly $10$. Given a positive integer $k$, your task is to find the $k$-th smallest perfect positive integer.
```python n = int(input()) i = 10 while n>0: i += 9 if sum(map(int, str(i))) == 10: n-=1 print(i) ```
MatrixStudio/Codeforces-Python-Submissions
Nick is interested in prime numbers. Once he read about Goldbach problem. It states that every even integer greater than 2 can be expressed as the sum of two primes. That got Nick's attention and he decided to invent a problem of his own and call it Noldbach problem. Since Nick is interested only in prime numbers, Nold...
```python def f(rangeint): List = [] for j in range(2, rangeint+1): List.append(j) z = 2*len(List) a = 0 for i in range(0, int(rangeint**(1/2))): a += 1 m = List[a-1] for k in List: if k % m == 0 and k > m ...
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=input() t=input() l=len(s) f=0 for i in range(l): if s[i]!=t[l-i-1]: f=1 break if f==1: print("NO") else: print("YES") ```
MatrixStudio/Codeforces-Python-Submissions
Caisa solved the problem with the sugar and now he is on the way back to home. Caisa is playing a mobile game during his path. There are (*n*<=+<=1) pylons numbered from 0 to *n* in this game. The pylon with number 0 has zero height, the pylon with number *i* (*i*<=&gt;<=0) has height *h**i*. The goal of the game is ...
```python _ = input() l = list(map(int, input().split())) print(max(l)) ```
MatrixStudio/Codeforces-Python-Submissions
Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock. The combination lock is represented by *n* rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has to turn ...
```python N = int(input()) org = input() fin = input() sol = 0 for i in range(N): a, b = int(min(org[i],fin[i])), int(max(org[i],fin[i])) sol += min(abs(b-a), a+10-b) print(sol) ```
MatrixStudio/Codeforces-Python-Submissions
Catherine has a deck of *n* cards, each of which is either red, green, or blue. As long as there are at least two cards left, she can do one of two actions: - take any two (not necessarily adjacent) cards with different colors and exchange them for a new card of the third color; - take any two (not necessarily adja...
```python int(input()) b=set(input()) if len(b)==1:print(''.join(b)) elif len(b)==2:print(*[i for i in 'GRB' if i not in b]) else:print('B') ```
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()) a = [] b = [] ans = [] for i in range(0,m): w1,w2 = [str(x) for x in input().split()] a.append(w1) b.append(w2) s = input() s = s.split() for word in s: cnt = a.index(word) if len(a[cnt]) <= len(b[cnt]): ans.append(a[cnt]) else: ans.a...
MatrixStudio/Codeforces-Python-Submissions
Our brave travelers reached an island where pirates had buried treasure. However as the ship was about to moor, the captain found out that some rat ate a piece of the treasure map. The treasure map can be represented as a rectangle *n*<=×<=*m* in size. Each cell stands for an islands' square (the square's side length ...
```python print("_RANDOM_GUESS_1689180180.4521961")# 1689180180.4522119 ```
MatrixStudio/Codeforces-Python-Submissions
Vanya and his friends are walking along the fence of height *h* and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed *h*. If the height of some person is greater than *h* he can bend down and then he surely won't be noticed by the guard. The height ...
```python n = input().split() a = input().split() MP=0 for i in range(0,int(n[0])): if int(a[i]) > int(n[1]) : MP+=2 else: MP+=1 print(MP) ```
MatrixStudio/Codeforces-Python-Submissions
On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains *n* different items numbered from 1 to *n*. The *i*-th item has base cost *a**i* Egyptian pounds. If Sagheer buys *k* items with indices *x*1,<=*x*2,<=...,<...
```python n, s = map(int, input().split()) v = list(map(int, input().split())) #for i in range(n): r = n + 1 l = 0 o = 0 while r - l != 1: s1 = s b = [] t = True for i in range(n): b.append(v[i] + (i + 1) * ((r + l) // 2)) b.sort() i = 0 sum = 0 for i in range((r +...
MatrixStudio/Codeforces-Python-Submissions
It was recycling day in Kekoland. To celebrate it Adil and Bera went to Central Perk where they can take bottles from the ground and put them into a recycling bin. We can think Central Perk as coordinate plane. There are *n* bottles on the ground, the *i*-th bottle is located at position (*x**i*,<=*y**i*). Both Adil a...
```python import math Ax , Ay , Bx , By , Rx , Ry = map(int,input().split()) a , b = [100009] , [100009] maxDis ,mDx,mDy ,res ,mx , my ,minDis,x1,y1= 0,0,0,0,0,0,10000000000,0,0 n = int(input()) for i in range(n): x , y = map(int,input().split()) a.append(x) b.append(y) d = math.dist([x,y] , ...
MatrixStudio/Codeforces-Python-Submissions
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had *a* red socks and *b* blue socks. According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot. Every day Vasya puts on new socks in the morning ...
```python a, b = map(int, input().split()) if a != b: mn = min(a, b) mx = max(a, b) ans1 = mn ans2 = (mx - ans1)//2 print(ans1, ans2) else: print(min(a,b), 0) ```
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 l1 = 'QWERTYUIOPASDFGHJKLZXCVBNM' s = input() ABC = 0 abc = 0 for i in s: if i in l1: ABC += 1 else: abc += 1 if ABC > abc: print(s.upper()) else: print(s.lower()) ```
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 n=input() rotations=0 starting_point="a" for i in n: r=(abs(ord(i)-ord(starting_point)))%26 if r>13: rotations+=26-r else: rotations+=r starting_point=i print(rotations) ```
MatrixStudio/Codeforces-Python-Submissions
*n* soldiers stand in a circle. For each soldier his height *a**i* is known. A reconnaissance unit can be made of such two neighbouring soldiers, whose heights difference is minimal, i.e. |*a**i*<=-<=*a**j*| is minimal. So each of them will be less noticeable with the other. Output any pair of soldiers that can form a ...
```python n = int(input()) a = list(map(int, input().split())) x = 99999 for i in range(n): if abs(a[i] - a[(i+1)%n]) < x: x = abs(a[i%n] - a[(i+1)%n]) x1 = i%n x2 = (i+1)%n print(x1, x2, sep=" ") ```
MatrixStudio/Codeforces-Python-Submissions
One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house. Karlsson's gaze immediately fell on *n* woode...
```python n = int(input()) left_open = 0 right_open = 0 for i in range(n): l, r = map(int, input().split()) left_open += l right_open += r case1 = min(left_open, n - left_open) + min(right_open, n - right_open) case2 = min(left_open, n - left_open) + min(right_open, n - right_open) + abs(left_open -...
MatrixStudio/Codeforces-Python-Submissions
The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All *n* crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to *n*) and await further instructions. However, one should evacuate the crew properly, in a stri...
```python dict={} d={'captain':4,'man':3,'child':2,'woman':2,'rat':1} n=int(input()) for i in range(n): ip=list(map(str,input().split(' '))) name=ip[0] dict[name]=d[ip[1]] for i in sorted(dict.items(), key=lambda kv:(kv[1], kv[0])): print(i[0]) ```
MatrixStudio/Codeforces-Python-Submissions
The Travelling Salesman spends a lot of time travelling so he tends to get bored. To pass time, he likes to perform operations on numbers. One such operation is to take a positive integer *x* and reduce it to the number of bits set to 1 in the binary representation of *x*. For example for number 13 it's true that 1310<...
```python MX = 1030 M = 1000 * 1000 * 1000 + 7 c = [[0] * MX for i in range(MX)] for i in range(MX): c[i][0] = 1 for i in range(1, MX): for j in range(1, MX): c[i][j] = c[i - 1][j] + c[i - 1][j - 1] c[i][j] %= M num = list(map(int, list(input()))) cnt = int(input()) dp = [0] * MX ...
MatrixStudio/Codeforces-Python-Submissions
You're given a list of *n* strings *a*1,<=*a*2,<=...,<=*a**n*. You'd like to concatenate them together in some order such that the resulting string would be lexicographically smallest. Given the list of strings, output the lexicographically smallest concatenation.
```python def function(): temp=input().split() customers=int(temp[0]) cost=int(temp[1]) custArray=[] for customer in range(customers): temp=input() custArray.append(temp) apples=0 profit=0 for index in range(customers): if(custArray[customers-1-index]...
MatrixStudio/Codeforces-Python-Submissions
DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter *c* DZY knows its value *w**c*. For each special string *s*<==<=*s*1*s*2... *s*|*s*| (|*s*| is the length of the string) he represents its value with a function *f*(*s*), where Now DZY has a string *s*. He wants to in...
```python s=input() k=int(input()) w=list(map(int,input().split())) s=list(s) q=0 for i in range(len(s)): q=q+(i+1)*w[i] a=max(w) b=len(s)+1 for i in range(k): q=q+b*a b=b+1 print(q) ```
MatrixStudio/Codeforces-Python-Submissions
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given *n* numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given *n* numbers finds one that i...
```python #25A IQ Test import sys import math inputs = int(input()) input2 = sys.stdin.readline().split() i = 0 a = 0 b = 0 if inputs == 2: print("1") sys.exit() for i in range(inputs): if int(input2[i])%2 == 0: a = a + 1 else: b = b + 1 if a>b: #E...
MatrixStudio/Codeforces-Python-Submissions
Recently, Mike was very busy with studying for exams and contests. Now he is going to chill a bit by doing some sight seeing in the city. City consists of *n* intersections numbered from 1 to *n*. Mike starts walking from his house located at the intersection number 1 and goes along some sequence of intersections. Wal...
```python from collections import defaultdict class Graph: def __init__(self): self.node=set() self.edges= defaultdict(list) self.distance={} def addNode(self,value): self.node.add(value) def addEdge(self,start,end,distance): self.edges[start].append(en...
MatrixStudio/Codeforces-Python-Submissions
After a team finished their training session on Euro football championship, Valeric was commissioned to gather the balls and sort them into baskets. Overall the stadium has *n* balls and *m* baskets. The baskets are positioned in a row from left to right and they are numbered with numbers from 1 to *m*, correspondingly...
```python n, m = map(int, input().split()) # i%m vai de 0 ate m-1 for i in range(n): if (m+i%m)%2 > 0: # pega o valor medio, valores entre (m+1)/2 até m print(str(int((m+i%m+1)/2))) else: # Pega o valor médio que seja menor ou igual a metade de m. # Portanto valores entre 1 até m...
MatrixStudio/Codeforces-Python-Submissions
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d...
```python n = input() if n.count('4') + n.count('7') in [4,7]: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc....
```python text = str(input()) text2 = str(input()) if text2 == text[::-1]: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
You can find anything whatsoever in our Galaxy! A cubical planet goes round an icosahedral star. Let us introduce a system of axes so that the edges of the cubical planet are parallel to the coordinate axes and two opposite vertices lay in the points (0,<=0,<=0) and (1,<=1,<=1). Two flies live on the planet. At the mom...
```python if (int(input()[::2], 2) + int(input()[::2], 2)) == 7: print("NO") else: print("YES") ```
MatrixStudio/Codeforces-Python-Submissions
A burglar got into a matches warehouse and wants to steal as many matches as possible. In the warehouse there are *m* containers, in the *i*-th container there are *a**i* matchboxes, and each matchbox contains *b**i* matches. All the matchboxes are of the same size. The burglar's rucksack can hold *n* matchboxes exactl...
```python n,m=map(int,input().split()) l=[] for i in range(m): l.append(list(map(int,input().split()))) l.sort(key= lambda x : (x[1],x[0]), reverse= True) print(l) ans=0 for i in l: a=min(n,i[0]) ans+=a*i[1] n-=a print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
In Aramic language words can only represent objects. Words in Aramic have special properties: - A word is a root if it does not contain the same letter more than once. - A root and all its permutations represent the same object. - The root $x$ of a word $y$ is the word that contains all letters that appear in $y$...
```python n = int(input()) a = input().split() b = set() for i in a: c = [0] * 37 for j in i: c[ord(j) - ord('a')] = 1 now = 0 p = 37 for j in range(26): if c[j] == 1: now += p * (j + 1) p *= 37 b.add(now) print(len(b)) ```
MatrixStudio/Codeforces-Python-Submissions
One day Misha and Andrew were playing a very simple game. First, each player chooses an integer in the range from 1 to *n*. Let's assume that Misha chose number *m*, and Andrew chose number *a*. Then, by using a random generator they choose a random integer *c* in the range between 1 and *n* (any integer from 1 to *n*...
```python import sys, collections, bisect, heapq, functools, itertools, math input = sys.stdin.readline n, m = [int(x) for x in input().split()] if n - m > m - 1: print(min(n, m + 1)) else: print(max(1, m - 1)) ```
MatrixStudio/Codeforces-Python-Submissions
Amr loves Geometry. One day he came up with a very interesting problem. Amr has a circle of radius *r* and center in point (*x*,<=*y*). He wants the circle center to be in new position (*x*',<=*y*'). In one step Amr can put a pin to the border of the circle in a certain point, then rotate the circle around that pin b...
```python import math r,x0,y0,x1,y1=map(int,input().split()) d = math.sqrt((x1-x0)^2+(y1-y0)^2) s = d/(r<<1) print(math.ceil(s)) ```
MatrixStudio/Codeforces-Python-Submissions
Dima and his friends have been playing hide and seek at Dima's place all night. As a result, Dima's place got messy. In the morning they decided that they need to clean the place. To decide who exactly would clean the apartment, the friends want to play a counting-out game. First, all the guys stand in a circle, and t...
```python n = int(input()) total = 0 z = [x for x in map(int,input().split())] for i in z: total += i answer = 0 for i in range(1,5+1): if(total+i) % (n+1) != 1: answer += 1 print(answer) ```
MatrixStudio/Codeforces-Python-Submissions
Professor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest. In total, *n* students will attend, and before the start, every one of them has some positive integer rating. Students are indexed from 1 to *n*. Let's denote...
```python from sys import stdin n=int(stdin.readline()) a=[int(x) for x in stdin.readline().split()] for i in range(n): c=0 for j in range(n): if a[i]<a[j]: c+=1 print(c+1,end=" ") ```
MatrixStudio/Codeforces-Python-Submissions
A soldier wants to buy *w* bananas in the shop. He has to pay *k* dollars for the first banana, 2*k* dollars for the second one and so on (in other words, he has to pay *i*·*k* dollars for the *i*-th banana). He has *n* dollars. How many dollars does he have to borrow from his friend soldier to buy *w* bananas?
```python k,n,w=map(int,input().split()) a=w*(2*k+(w-1)*k)//2 print(a-n) ```
MatrixStudio/Codeforces-Python-Submissions
Little Joty has got a task to do. She has a line of *n* tiles indexed from 1 to *n*. She has to paint them in a strange pattern. An unpainted tile should be painted Red if it's index is divisible by *a* and an unpainted tile should be painted Blue if it's index is divisible by *b*. So the tile with the number divisibl...
```python n,a,b,p,q=map(int,input().split()) import math x=(a*b)//math.gcd(a,b) if(p>q): print((n//a)*p+(n//b)*q-(n//x)*q) else: print((n//a)*p+(n//b)*q-(n//x)*p) ```
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 f = str(input()) g = f[::-1] g = g.lower() g= g.replace("?"," ") l1= ['a','e','y','i','o','u'] x=0 l = '' for y in g: if ord(y) in range(97,123): l =y break else: pass if l in l1: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Hongcow really likes the color red. Hongcow doesn't like the color blue. Hongcow is standing in an infinite field where there are *n* red points and *m* blue points. Hongcow wants to draw a circle in the field such that this circle contains at least one red point, and no blue points. Points that line exactly on the b...
```python import itertools red = [] blue = [] input_ = input() x = input_.split(" ") i = 0 j = 0 points = [] #blue = [] while i < int(x[0]): k = input() points.append(k) red.append(k) i+=1 while j < int(x[1]): l = input() points.append(l) blue.append(l) j+=1 # print("red: ",red) # print("blue: ",blue)...
MatrixStudio/Codeforces-Python-Submissions
Little Robber Girl likes to scare animals in her zoo for fun. She decided to arrange the animals in a row in the order of non-decreasing height. However, the animals were so scared that they couldn't stay in the right places. The robber girl was angry at first, but then she decided to arrange the animals herself. She ...
```python def solve(a): segments = [] while True: changed = False for i in range(len(a) - 1): if a[i] > a[i + 1]: a[i], a[i + 1] = a[i + 1], a[i] segments.append(f"{i + 1} {i + 2}") changed = True if not changed: ...
MatrixStudio/Codeforces-Python-Submissions
Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number *a* and Antisimon receives number *b*. They also have a heap of *n* stones. The players take turns to make a move and Simon starts. During a move a player should take...
```python for t in range(int(input())): a,b,c = map(int, input().split()) if c%2==0: print(1) else: print(0) ```
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 import sys; R = sys.stdin.readline for _ in range(int(R())): s = R().split()[0] sys.stdin.flush() for i in range(1, len(s) - 1): sub1 = s[:i] sub2 = s[i] sub3 = s[i + 1:] if (sub2 >= sub1 and sub2 >= sub3) or (sub2 <= sub1 and sub2 <= sub3): pri...
MatrixStudio/Codeforces-Python-Submissions
We've got no test cases. A big olympiad is coming up. But the problemsetters' number one priority should be adding another problem to the round. The diameter of a multiset of points on the line is the largest distance between two points from this set. For example, the diameter of the multiset {1,<=3,<=2,<=1} is 2. D...
```python n, d = list(map(int, input().split())) a = list(map(int, input().split())) a.sort() i = 0 j = 1 l = 0 tl = 1 while True: if abs(a[i] - a[j]) <= d: tl += 1 j += 1 else: if tl > l: l = tl tl = 1 i += 1 j = i + 1 if i >= n - 1 or j >= n: if tl > l: l = tl break print(n - l) ```
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 NoOfstudents=int(input()) students=[int(x) for x in input().split()] maths=[] programming=[] PE=[] if NoOfstudents>=3: for i in range(len(students)): if students[i]==1: programming.append(i+1) elif students[i]==2: maths.append(i+1) elif students[i...
MatrixStudio/Codeforces-Python-Submissions
Little Vasya has received a young builder’s kit. The kit consists of several wooden bars, the lengths of all of them are known. The bars can be put one on the top of the other if their lengths are the same. Vasya wants to construct the minimal number of towers from the bars. Help Vasya to use the bars in the best way ...
```python from collections import defaultdict n=int(input()) a=list(map(int,input().split())) d=defaultdict(int) for i in a: d[i]+=1 data,l=0,0 for i in d: data=max(data,i*d[i]) l+=1 print(data,l) ```
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 area = [int(x) for x in input().split(" ")] area = (area[0] * area[1]) - (area[0] * area[1] % 2) print(area // 2) ```
MatrixStudio/Codeforces-Python-Submissions
Unfortunately, Vasya can only sum pairs of integers (*a*, *b*), such that for any decimal place at least one number has digit 0 in this place. For example, Vasya can sum numbers 505 and 50, but he cannot sum 1 and 4. Vasya has a set of *k* distinct non-negative integers *d*1,<=*d*2,<=...,<=*d**k*. Vasya wants to choo...
```python from collections import defaultdict n = int(input()) arr = [int(x) for x in input().split()] ans = [] d = defaultdict(bool) for i in arr: if(i % 100 == 0 and not d[100]): d[100] = True ans.append(i) elif(i % 10 == 0 and not d[10]): d[10] = True ans.append(i) ...
MatrixStudio/Codeforces-Python-Submissions
There is a right triangle with legs of length *a* and *b*. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the...
```python import sys input = sys.stdin.readline def f(x): s = set() for i in range(1, x): y = (x**2 - i**2)**0.5 if y == int(y): s.add((i, int(y))) return s a, b = map(int, input().split()) d = f(a) q = f(b) for i1, i2 in d: for i3, i4 in q: if i...
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 ss="aeiou" s=input() num=0 for i in range(0,len(s)): if s[i] in ss: num=i aa=s[0:num+1]+'ntry' print (aa.capitalize ()) ```
MatrixStudio/Codeforces-Python-Submissions
Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, inf...
```python n=int(input()) s=input() a=list(s) if len(a)%2!=0: p="" f="" for i in range(len(s)): if i%2==0: p+=a[i] else: f+=a[i] print(f[::-1]+p) else: p="" f="" for i in range(len(s)): if i%2==0: f+=a[i] el...
MatrixStudio/Codeforces-Python-Submissions
You are given string *s* consists of opening and closing brackets of four kinds &lt;&gt;, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace &lt; by the bracket {, but you can't replace it by ) or &gt;. The following d...
```python S = input() def is_open(x): return x == '<' or x == '{' or x == '[' or x == '(' def is_match(x, y): if x == '<': return y == '>' elif x == '{': return y == '}' elif x == '[': return y == ']' else: return y == ')' open_cnt = 0 clo...
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 n = int (input()) for i in range (n): word = input() if len (word) <= 10: print (word) else: print (word[0] + str (len (word) - 2) + word[len(word) - 1]) ```
MatrixStudio/Codeforces-Python-Submissions
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy. The toy consists of *n* parts and *m* ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts....
```python n, m = map(int, input().split()) f = [int(x) for x in input().split()] ans = 0 for i in range(m): a, b = map(int, input().split()) ans += min(f[a - 1], f[b - 1]) print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
There were *n* groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team. The coach decided to form teams of exactly three people for this training. Determine the maximum number of tea...
```python n=int(input()) a=list(map(int,input().split())) if 1 not in a: print("0") elif 2 not in a: print(n//3) else: x=a.count(1) y=a.count(2) if y>=x: print(x) else: print(x + ((x-y)//3)) ```
MatrixStudio/Codeforces-Python-Submissions
Vanya walks late at night along a straight street of length *l*, lit by *n* lanterns. Consider the coordinate system with the beginning of the street corresponding to the point 0, and its end corresponding to the point *l*. Then the *i*-th lantern is at the point *a**i*. The lantern lights all points of the street that...
```python n,l = map(int, input().split()) lntr = list(map(int,input().split())) lntr.sort() maxi = 0 for i in range(n-1): maxi = max(maxi,lntr[i+1]-lntr[i]) res = max([maxi/2, lntr[0]-0, l-lntr[n-1]]) print(float(res)) ```
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 def update(v,l,r,src,p_src,kl,kr): if(l>r or la[v]==-1): return if(kl==kr): la[v]=src visited[kl]=src return else: km=(kl+kr)//2 update(2*v,l,min(r,km),src,p_src,kl,km) update(2*v+1,max(km+1,l),r,src,p_src,km+1,kr) if(la[2*...
MatrixStudio/Codeforces-Python-Submissions
The R1 company has recently bought a high rise building in the centre of Moscow for its main office. It's time to decorate the new office, and the first thing to do is to write the company's slogan above the main entrance to the building. The slogan of the company consists of *n* characters, so the decorators hung a l...
```python (n, k) = [int(r) for r in input().split()] s = input() if k <= n // 2: while k > 1: print("LEFT") k -= 1 print("\nRIGHT\n".join(("PRINT " + c) for c in s)) else: while k < n: print("RIGHT") k += 1 print("\nLEFT\n".join(("PRINT " + c) for c in revers...
MatrixStudio/Codeforces-Python-Submissions
After celebrating the midcourse the students of one of the faculties of the Berland State University decided to conduct a vote for the best photo. They published the photos in the social network and agreed on the rules to choose a winner: the photo which gets most likes wins. If multiple photoes get most likes, the win...
```python def run(n, arr): photos = [] top = dict(id=arr.pop(0), likes=1) for id in arr: found = False for photo in photos: if photo['id'] == id: found = True photo['likes'] += 1 if photo['likes'] > top['likes']: ...
MatrixStudio/Codeforces-Python-Submissions
Sengoku still remembers the mysterious "colourful meteoroids" she discovered with Lala-chan when they were little. In particular, one of the nights impressed her deeply, giving her the illusion that all her fancies would be realized. On that night, Sengoku constructed a permutation *p*1,<=*p*2,<=...,<=*p**n* of intege...
```python n = int(input()) ai = list(map(int,input().split())) bi = list(map(int,input().split())) ci = [0]*n for i in range(n): ci[i] = ai[i] nums = [0]*n ind = [0]*2 j = 0 num = 0 for i in range(n): nums[ai[i]-1] += 1 for i in range(n): if nums[ai[i]-1] == 2: ind[j] = i j +=...
MatrixStudio/Codeforces-Python-Submissions
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow th...
```python import sys input=sys.stdin.readline m=1000000007 #------------------------------------# for _ in range(int(input())): cell=input().strip() if cell[0]=="R": #convert to AA format secindex=cell.index("C") number1=int(cell[1:secindex]) number2=int(cell[secind...
MatrixStudio/Codeforces-Python-Submissions
Iahub is very proud of his recent discovery, propagating trees. Right now, he invented a new tree, called xor-tree. After this new revolutionary discovery, he invented a game for kids which uses xor-trees. The game is played on a tree having *n* nodes, numbered from 1 to *n*. Each node *i* has an initial value *init**...
```python n=int(input()) from collections import defaultdict graph=defaultdict(list) for i in range(n-1): u,v=[int(i) for i in input().split()] graph[u].append(v) graph[v].append(u) curr=[int(i) for i in input().split()] goal=[int(i) for i in input().split()] ops=[] def dfs(parent,ver,odd,even...
MatrixStudio/Codeforces-Python-Submissions
Mahmoud has an array *a* consisting of *n* integers. He asked Ehab to find another array *b* of the same length such that: - *b* is lexicographically greater than or equal to *a*. - *b**i*<=≥<=2. - *b* is pairwise coprime: for every 1<=≤<=*i*<=&lt;<=*j*<=≤<=*n*, *b**i* and *b**j* are coprime, i. e. *GCD*(*b**i*,<=*...
```python print("Even") ```
MatrixStudio/Codeforces-Python-Submissions
Bachgold problem is very easy to formulate. Given a positive integer *n* represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1. Recall that integer *k* is called prime if it is greater than 1 and has exactly two positive integer ...
```python def isprime(n): for n in range(n,100001): s=int(n**(0.5)) f=1 for j in range(2,s+1): if(n%j==0): f=0 break if(f==1): return(n) print(isprime(20)) ```
MatrixStudio/Codeforces-Python-Submissions
A company has *n* employees numbered from 1 to *n*. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee *A* is said to be the superior of another employee *B* if at least one of the following is true: - Employee *A* is the immedi...
```python dic = dict() num = int(input()) count = 0 check = list() for n in range(1, num + 1): employee = n manager = int(input()) if manager in dic: dic[manager].append(employee) else: dic[manager] = list() dic[manager].append(employee) check = dic[-1] size = len(check) while si...
MatrixStudio/Codeforces-Python-Submissions
Mikhail walks on a 2D plane. He can go either up or right. You are given a sequence of Mikhail's moves. He thinks that this sequence is too long and he wants to make it as short as possible. In the given sequence moving up is described by character U and moving right is described by character R. Mikhail can replace an...
```python n-int(input()) x=input().lower() i-0 while i < len(x) -1: if x[i]+x[i+1] in ('ur', 'ru'): i=i+2 n=n-1 else: i=i+1 print (n) ```
MatrixStudio/Codeforces-Python-Submissions
Translator's note: in Russia's most widespread grading system, there are four grades: 5, 4, 3, 2, the higher the better, roughly corresponding to A, B, C and F respectively in American grading system. The term is coming to an end and students start thinking about their grades. Today, a professor told his students that...
```python n=int(input()) a=list(map(int,input().split())) k=sum(a) av=k/n c=0 if(av<4.5): a.sort() s=int(n*4.5)-k if(n%2!=0): s+=1 q=0 for i in range(n): if(q>=s): break else: q+=5-a[i] c+=1 print(c) ```
MatrixStudio/Codeforces-Python-Submissions
Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they ...
```python n=int(input()) lista=[] for i in range(n): nam=input() if nam in lista: print("YES") else: lista.append(nam) print("NO") ```
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()) line = list(map(int,input().split())) distinct_nums = [] visited = [0]*100001 #用于标记每一个数字是否被访问过 distinct = 0 for i in range(n-1,-1,-1): if visited[line[i]] == 0: distinct += 1 distinct_nums.append(distinct) visited[lin...
MatrixStudio/Codeforces-Python-Submissions
Indian summer is such a beautiful time of the year! A girl named Alyona is walking in the forest and picking a bouquet from fallen leaves. Alyona is very choosy — she doesn't take a leaf if it matches the color and the species of the tree of one of the leaves she already has. Find out how many leaves Alyona has picked.
```python lis=[] for _ in range(int(input())): a,b=map(str,input().split()) lis.append([a,b]) ans = [] for i in range(len(lis)): if lis[i] in ans: pass else: ans.append(lis[i]) print(len(ans)) ```
MatrixStudio/Codeforces-Python-Submissions
New Year is coming in Line World! In this world, there are *n* cells numbered by integers from 1 to *n*, as a 1<=×<=*n* board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells. So, user tncks0...
```python l=(input().split()) m=[int(l[0]),int(l[1])] n=input().split() p=[] a=0 for i in range(len(n)): p=p+[n[i]] for j in range(len(n)): a=a+p[j] if a==l[1]: print('YES') break elif a>l[1]: print('NO') break ```
MatrixStudio/Codeforces-Python-Submissions
Professor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest. In total, *n* students will attend, and before the start, every one of them has some positive integer rating. Students are indexed from 1 to *n*. Let's denote...
```python students = int(input()) ratings = list(map(int, input().split(' '))) different_ratings = list(reversed(sorted(set(ratings)))) rankings = {} for i in range(len(different_ratings)): if i == 0: rankings[different_ratings[i]] = 1 else: rankings[different_ratings[i]] = rankings[different_...
MatrixStudio/Codeforces-Python-Submissions
The input contains two integers *a*1,<=*a*2 (0<=≤<=*a**i*<=≤<=109), separated by a single space. Output a single integer.
```python n=input().split() c=int(n[1]) a=[] b=[] l="" o="" d=[] for i in n[1]: a.append(int(i)) a.reverse() for i in n[0]: b.append(i) if len(n[0]) < len(n[1]): b.insert(0,'0') for i in range (len(a)): l+= str(a[i]) o+= str(b[i]) p = int(l) q = int(o) print(p+q) ```
MatrixStudio/Codeforces-Python-Submissions
You're given a row with $n$ chairs. We call a seating of people "maximal" if the two following conditions hold: 1. There are no neighbors adjacent to anyone seated. 1. It's impossible to seat one more person without violating the first rule. The seating is given as a string consisting of zeros and ones ($0$ means t...
```python n=input() l='0'+input()+'0' print('No' if '000' in l or '11' in l else 'Yes') ```
MatrixStudio/Codeforces-Python-Submissions
After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with *n* room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third ...
```python n=int(input()) s=list(input()) keys=[0]*26 count=0 for i in range(0, (len(s)//2)): key = s[i*2] door = s[i*2+1] keys[ord(key)-97] += 1 if (keys[ord(door)-65] > 0): keys[ord(door)-65] -= 1 else: count+=1 print(count) ```
MatrixStudio/Codeforces-Python-Submissions
A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs. Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages ...
```python n = int(input()) t = [int(x) for x in input().split()] ans = 0 istime = [0] * (2 * 10 ** 5 + 13) istime[0] = 1 for i in range(n): if istime[t[i]] > 0: istime[t[i]] -= 1 else: ans += 1 istime[i + 1] += 1 print(ans + 1) ```
MatrixStudio/Codeforces-Python-Submissions
Arkady and Kirill visited an exhibition of rare coins. The coins were located in a row and enumerated from left to right from 1 to *k*, each coin either was laid with its obverse (front) side up, or with its reverse (back) side up. Arkady and Kirill made some photos of the coins, each photo contained a segment of neig...
```python print("_RANDOM_GUESS_1692552615.5669065")# 1692552615.566924 ```
MatrixStudio/Codeforces-Python-Submissions
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array. According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the requ...
```python n1=int(input()) l1=list(map(int,input().split())) n2=int(input()) l2=list(map(int,input().split())) s1=0 s2=0 d={} for i in range(len(l1)): d[l1[i]]=i for i in range(len(l2)): if l2[i] in d: s1+=d[l2[i]]+1 s2+=n1-d[l2[i]] print(s1,end=" ") print(s2) ```
MatrixStudio/Codeforces-Python-Submissions
Fox Ciel has a board with *n* rows and *n* columns, there is one integer in each cell. It's known that *n* is an odd number, so let's introduce . Fox Ciel can do the following operation many times: she choose a sub-board with size *x* rows and *x* columns, then all numbers in it will be multiplied by -1. Return the m...
```python n = int(input()) m = [] for _ in range(n): m.append(list(map(int, input().split()))) m[-1].append(0) m.append([0]*(n+1)) x = (n+1)//2 f = [0,0] def flip(v,k): return -v if k > 0 else v sol = int(-1e9) for s in range(1<<x): current_sol = 0 for j in range(x): ...
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 count = int(input()) points = [] for i in range(count): point = tuple(input().split()) points.append(point) answer = 0 for (x, y) in points: left = False right = False up = False low = False for (x1, y1) in points: if x1 > x and y1 == y: right = True if x1 < x and...
MatrixStudio/Codeforces-Python-Submissions
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees. A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (*u*,<=*v*) that belongs to the graph, *...
```python n = int(input()) g = [[] for i in range(n+1)] for _ in range(n-1): u, v = map(int, input().split()) g[u].append(v) g[v].append(u) visited = [False for _ in range(n+1)] def dfs(node, prev): if prev: visited[node] = 1 else: visited[node] = 0 for w in g[node...
MatrixStudio/Codeforces-Python-Submissions
In Aramic language words can only represent objects. Words in Aramic have special properties: - A word is a root if it does not contain the same letter more than once. - A root and all its permutations represent the same object. - The root $x$ of a word $y$ is the word that contains all letters that appear in $y$...
```python d=set() input() for i in input().split(): x=set() for j in i: x.add(j) d.add(''.join(sorted(x))) print(len(d)) ```
MatrixStudio/Codeforces-Python-Submissions
Not so long ago the Codecraft-17 contest was held on Codeforces. The top 25 participants, and additionally random 25 participants out of those who got into top 500, will receive a Codeforces T-shirt. Unfortunately, you didn't manage to get into top 25, but you got into top 500, taking place *p*. Now the elimination r...
```python p, x, y = map(int, input().split()) def shirtpicking(s, test): i = (s // 50) % 475 res = [] for t in range(25): i = (i * 96 + 42) % 475 res.append(i+26) if test in res: return True else: return False if x >= y: for x1 in range((x - y) /...
MatrixStudio/Codeforces-Python-Submissions
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an *n*<=×<=*m* table with integers in its cells. The order of mete...
```python import sys input = sys.stdin.readline n ,m ,k = map(int ,input().split()) row ,col ,Data = [], [],[] for i in range(n): row.append(i) a = list(input().split()) Data.append(a) for i in range(m): col.append(i) for _ in range(k): s ,x ,y = input().split() x , y = int(x) ,int(y) if s =...