source
stringclasses
3 values
instruction
stringlengths
23
3.97k
input
stringclasses
1 value
output
stringlengths
1
3.75k
MatrixStudio/Codeforces-Python-Submissions
Ivan has a robot which is situated on an infinite grid. Initially the robot is standing in the starting cell (0,<=0). The robot can process commands. There are four types of commands it can perform: - U — move from the cell (*x*,<=*y*) to (*x*,<=*y*<=+<=1); - D — move from (*x*,<=*y*) to (*x*,<=*y*<=-<=1); - L — mo...
```python n=int(input()) a=input() b=[0,0] count=0 for i in a: if i=="L": b[0]-=1 count+=1 if i == "R": b[0]+=1 count += 1 if i == "U": b[1]+=1 count += 1 if i == "D": b[1]-=1 count += 1 if b[0]==0 and b[1]==0: print(count) ...
MatrixStudio/Codeforces-Python-Submissions
In a far away kingdom lived the King, the Prince, the Shoemaker, the Dressmaker and many other citizens. They lived happily until great trouble came into the Kingdom. The ACMers settled there. Most damage those strange creatures inflicted upon the kingdom was that they loved high precision numbers. As a result, the Ki...
```python n, f = input().split(".") if n[-1] == "9": print("GOTO Vasilisa.") else: n = int(n) print(n if int(f[0]) < 5 else n+1) ```
MatrixStudio/Codeforces-Python-Submissions
Vasily has a deck of cards consisting of *n* cards. There is an integer on each of the cards, this integer is between 1 and 100<=000, inclusive. It is possible that some cards have the same integers on them. Vasily decided to sort the cards. To do this, he repeatedly takes the top card from the deck, and if the number...
```python def read(): return [int(x) for x in input().split()] notimportant = int(input()[0]) x = read() counter =0 ind=0 while len(x)>0: m = x.index(min(x)) if m<ind: counter+=len(x)-ind+m+1 print ("run") print (len(x)) else: counter+=m-ind+1 ind=m ...
MatrixStudio/Codeforces-Python-Submissions
A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not. The next prime number after *x* is the smallest prime number greater than *x*. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note t...
```python import math def isPrime(n): if (n <= 1): return False if (n <= 3): return True if (n % 2 == 0 or n % 3 == 0): return False for i in range(5, int(math.sqrt(n) + 1), 6): if (n % i == 0 or n % (i + 2) == 0): return False return True...
MatrixStudio/Codeforces-Python-Submissions
Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are *n* players (including Limak himself) and right now all of them have bids on the table. *i*-th of them has bid with size *a**i* dollars. Each player can double his bid any number of times and triple his bid any nu...
```python import math n=int(input()) l=list(map(int,input().split())) a=l[0] b=l[1] g=(a*b)//math.gcd(a,b) for i in range(2,n): g=(g*l[i])//math.gcd(g,l[i]) if(g in l): print("Yes") else: print("No") ```
MatrixStudio/Codeforces-Python-Submissions
Some country is populated by wizards. They want to organize a demonstration. There are *n* people living in the city, *x* of them are the wizards who will surely go to the demonstration. Other city people (*n*<=-<=*x* people) do not support the wizards and aren't going to go to the demonstration. We know that the city...
```python import math n,x,y=map(int,input().split()) ans=math.ceil(n*y/100)-x if ans<0: ans=0 print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
*n* people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins *k* games in a row. This player becomes the winner. For each of t...
```python from collections import deque n, k = map(int, input().split()) power = deque(map(int, input().split())) if(k > len(power)): print(max(power)) else: pontos = 0 ultimo = 0 while True: if(pontos == k): print(ultimo) break if(power[0] > power[1]): if(power[0] != ultimo): ...
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 t=int(input()) for t in range(t): s=input() n=len(s)p if n<=10: print(s) else: s1=s[0]+str(n-2)+s[-1] print(s1) #sdfbsr ```
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 #include<bits/stdc++.h> typedef long long int ll; using namespace std; bool comp(string a, string b) { return a + b < b + a; } int main() { int i, j, k; int r, m; cin >> r; string *s = new string[r]; for (i = 0; i < r; i++) cin >> s[i]; sort(s, s + n, comp); for (i = 0; i < r; i++) cout << s[i...
MatrixStudio/Codeforces-Python-Submissions
Mister B once received a gift: it was a book about aliens, which he started read immediately. This book had *c* pages. At first day Mister B read *v*0 pages, but after that he started to speed up. Every day, starting from the second, he read *a* pages more than on the previous day (at first day he read *v*0 pages, at ...
```python c,v0,v1,a,l = map(int,input().strip().split(' ')) tp = c - min(v0,v1) ans = 1 if tp <= 0: ans = 1 else: i = 1 while tp > 0: cp = v0 + i*a cp = min(v1,cp) tp = tp - cp + l ans+= 1 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 a, b = list(map(int, input().split())) if a // b % 2 == 0: print('YES') else: print('NO') ```
MatrixStudio/Codeforces-Python-Submissions
ATMs of a well-known bank of a small country are arranged so that they can not give any amount of money requested by the user. Due to the limited size of the bill dispenser (the device that is directly giving money from an ATM) and some peculiarities of the ATM structure, you can get at most *k* bills from it, and the ...
```python d = {0: 0} for q in t: for i in range(1, k + 1): d[q * i] = i for j in range(int(input())): x = int(input()) p = [q + d[x - i] for q, i in d.items() if x - i in d] if p: p = min(p) print(p if p and p <= k else -1) ```
MatrixStudio/Codeforces-Python-Submissions
Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it. Given a sequence *a* consisting of *n* integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it *a*...
```python n = int(input()) a = list(map(int, input().split())) dp = [0] * n for i in range(n): max_dp_j = 0 for j in range(i): if abs(a[i] - a[j]) <= 1: continue max_dp_j = max(max_dp_j, dp[j]) dp[i] = max_dp_j + a[i] print(max(dp)) ```
MatrixStudio/Codeforces-Python-Submissions
Polycarpus has a sequence, consisting of *n* non-negative integers: *a*1,<=*a*2,<=...,<=*a**n*. Let's define function *f*(*l*,<=*r*) (*l*,<=*r* are integer, 1<=≤<=*l*<=≤<=*r*<=≤<=*n*) for sequence *a* as an operation of bitwise OR of all the sequence elements with indexes from *l* to *r*. Formally: *f*(*l*,<=*r*)<==<=...
```python # Author Name: Ajay Meena # Codeforce : https://codeforces.com/profile/majay1638 import sys import math import bisect import heapq from bisect import bisect_right from sys import stdin, stdout # -------------- INPUT FUNCTIONS ------------------ def get_ints_in_variables(): return map( int,...
MatrixStudio/Codeforces-Python-Submissions
You might have heard about the next game in Lara Croft series coming out this year. You also might have watched its trailer. Though you definitely missed the main idea about its plot, so let me lift the veil of secrecy. Lara is going to explore yet another dangerous dungeon. Game designers decided to use good old 2D e...
```python def main(): n, m, k = map(int, input().split()) if k < n: print(k + 1, 1) else: y, x = divmod(k - n, m * 2 - 2) y *= 2 if x < m - 1: x = x + 2 else: x = m * 2 - x - 1 y += 1 print(n - y, x) if __name__ == '__main__':...
MatrixStudio/Codeforces-Python-Submissions
After the lessons *n* groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the *i*-th group consists of *s**i* friends (1<=≤<=*s**i*<=≤<=4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers....
```python import math n= int(input()) l = list(map(int, input().split())) res = sum(l) ans = math.ceil(res/4) print(ans) ```
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 num = int(input()) lowerBound = int(input()) upperBound = int(input()) def rec(num): if num == 1 or num == 0: return [num] devision = rec(num//2) remain = rec(num%2) remain.extend(devision) devision.extend(remain) return devision ones = rec(num) res= 0 for i in range(lowerB...
MatrixStudio/Codeforces-Python-Submissions
The final round of Bayan Programming Contest will be held in Tehran, and the participants will be carried around with a yellow bus. The bus has 34 passenger seats: 4 seats in the last row and 3 seats in remaining rows. The event coordinator has a list of *k* participants who should be picked up at the airport. When a...
```python n=int(input()) ub="+------------------------+" lb="+------------------------+" r1,r2,r3,r4=['|'],['|'],['|'],['|'] fl=0 if n<3: r3.append('#') r3.append('.') while n!=0: r1.append('O') r1.append('.') n-=1 if n==0: break r2.append('O') r2.append('.') ...
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() p = n.split('.') k=[] for j in range(len(p)): if 'ABC' in p[j]: k.append('Yes') if 'ACB' in p[j]: k.append('Yes') if 'BAC' in p[j]: k.append('Yes') if 'BCA' in p[j]: k.append('Yes') if 'CAB' in p[j]: k.append('Yes') if ...
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 s=input() x="AB" y="AB" if x in s and y in s: if (s.index(x)!=s.index(y)+1)or(s.index(y)!=s.index(x)): print("YES") ```
MatrixStudio/Codeforces-Python-Submissions
There are a lot of things which could be cut — trees, paper, "the rope". In this problem you are going to cut a sequence of integers. There is a sequence of integers, which contains the equal number of even and odd numbers. Given a limited budget, you need to make maximum possible number of cuts such that each resulti...
```python n, c = map(int, input().split()) seq = [int(x) for x in input().split()] cnt = 0 cuts = [] for a, b in zip(seq[:-1], seq[1:]): if a % 2: cnt -= 1 else: cnt += 1 if cnt == 0: cuts.append(abs(a-b)) cuts.sort(reverse=True) ans = 0 while cuts and c-cuts[-1] >= 0: c -= cu...
MatrixStudio/Codeforces-Python-Submissions
Pavel loves grid mazes. A grid maze is an *n*<=×<=*m* rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side. Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to a...
```python from sys import stdin from collections import deque inp = stdin.readline n, m, k = map(int, inp().split()) arr = [[x for x in "#"*(m+2)]] for _ in range(n): s = inp().strip() arr.append([x for x in "#" + s + "#"]) arr.append([x for x in "#"*(m+2)]) q = deque() count = 0 for i in ran...
MatrixStudio/Codeforces-Python-Submissions
There is a game called "I Wanna Be the Guy", consisting of *n* levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game. Little X can pass only *p* levels of the game. And Little Y can pass only *q* levels of the game. You are given the indices of levels Little X can...
```python n=int(input()) x=[int(i) for i in input().split()] y=[int(i) for i in input().split()] # print(x) # print(y) # x=[3,1,2,3] # y=[2,2,3] test=[i for i in range(1,n+1)] # print(test) z=x+y z.sort() # print(z) j=0 count=0 i=0 while(j<len(z) and i<len(test)): if test[i]==z[j]: ...
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 def get_distancia(x0, y0, x1, y1, q=False): delta_x = abs(x1-x0) delta_y = abs(y1-y0) if q: return delta_x**2 + delta_y**2 else: return (delta_x**2 + delta_y**2)**0.5 raio, x0, y0, x1, y1 = map(int, input().split()) distancia = get_distancia(x0, y0, x1, y1) if distancia == 2...
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 i = int(input()) if i > 3 and i % 2 == 0: return 'YES' return 'NO' ```
MatrixStudio/Codeforces-Python-Submissions
One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are *n* lines in that description each of which described one goal. E...
```python from collections import Counter def whoWon(mathes, size): dic = Counter(mathes) res = None for key in dic: if not res or dic.get(res) < dic.get(key): res = key return res size = int(input()) lst = [] for i in range(size): lst.append(input()) pr...
MatrixStudio/Codeforces-Python-Submissions
You are given two positive integer numbers *a* and *b*. Permute (change order) of the digits of *a* to construct maximal number not exceeding *b*. No number in input and/or output can start with the digit 0. It is allowed to leave *a* as it is.
```python a = input() b = input() la = [int(x) for x in a] res = [] la.sort() la = la[::-1] lb = [int(x) for x in b] cnt = [0] * 20 if len(a) < len(b): for i in la: print(i, end = '') print() else: for i in la: cnt[i] += 1 flag = 0 for i in range(len(lb)): if flag == 0 and c...
MatrixStudio/Codeforces-Python-Submissions
Theatre Square in the capital city of Berland has a rectangular shape with the size *n*<=×<=*m* meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size *a*<=×<=*a*. What is the least number of flagstones needed to pave the...
```python n,m,a = map(int,input().split()) if n%a == 0: xa = n//a else: xa = n // a + 1 if m%a == 0: xa = m//a else: xb = m//a +1 print(xa*xb) ```
MatrixStudio/Codeforces-Python-Submissions
You are given two set of points. The first set is determined by the equation *A*1*x*<=+<=*B*1*y*<=+<=*C*1<==<=0, and the second one is determined by the equation *A*2*x*<=+<=*B*2*y*<=+<=*C*2<==<=0. Write the program which finds the number of points in the intersection of two given sets.
```python eq1 = [int(i) for i in input().split(" ")] eq2 = [int(i) for i in input().split(" ")] a1, b1, c1 = eq1 a2, b2, c2 = eq2 if a1 == 0 and b1 == 0 and or a2 == 0 and b2 == 0 and: if c1 != c2: print("0") elif c1 == 0 and c2 == 0: print("-1") else: # c1 == c2 != 0 print("0") # vertical line if b1 == 0...
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 x = 0 y = 0 for i in range(5): s = input().split() try: s.index("1") except ValueError: continue else: x = i y = s.index("1") print(abs(x-2)+abs(y-2)) ```
MatrixStudio/Codeforces-Python-Submissions
Ivan's classes at the university have just finished, and now he wants to go to the local CFK cafe and eat some fried chicken. CFK sells chicken chunks in small and large portions. A small portion contains 3 chunks; a large one — 7 chunks. Ivan wants to eat exactly *x* chunks. Now he wonders whether he can buy exactly ...
```python # submitted from train through mobile for _ in range(int(input ())): n = int(input()) ans = "NO" for i in range(n) : Rem = n - 3*i if(Rem℅7 == 0 and Rem): ans = "YES" print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw. The first player wrote number *a*, the second player wrote number *b*. How many w...
```python a,b=map(int,input().split()) wa,wd,wb=0,0,0 for i in range(1,7): if abs(a-i) < abs(b-i): wa+=1 elif abs(a-i) > abs(b-i): wb+=1 else: wd+=1 print(wa,wd,wb) ```
MatrixStudio/Codeforces-Python-Submissions
Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpr...
```python /* @ Author: Andres Nowak @ Date: Tue Mar 10 13:15:34 CST 2020 */ #include <iostream> #include <vector> #include <string> using namespace std; int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } string probability(vector<int> throws_of_dice) { int denominator = 6; ...
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 prioridades = [] tipos = [] nombres = [] n = int(input()) for i in range(n): nombre, tipo = input().split() prioridad = 5 if tipo == 'rat': prioridad = 1 elif tipo == 'woman' or tipo == 'child': prioridad = 2 elif tipo == 'man': prioridad = 3 ...
MatrixStudio/Codeforces-Python-Submissions
Even if the world is full of counterfeits, I still regard it as wonderful. Pile up herbs and incense, and arise again from the flames and ashes of its predecessor — as is known to many, the phoenix does it like this. The phoenix has a rather long lifespan, and reincarnates itself once every *a*! years. Here *a*! deno...
```python a, b = map(int, input().split()) if b - a > 9: print(0) else: ans = 1 for i in range(a + 1, b + 1): ans *= i print(ans % 10) ```
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()) ls = list(map(int, input().split())) #for i in range(n-1): # if ls[i] print("1 2") ```
MatrixStudio/Codeforces-Python-Submissions
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th...
```python s = input() uppercase = 0 lowercase = 0 for i in s: if i.isupper(): uppercase += 1 elif i.islower: lowercase += 1 if lowercase < uppercase: print(s.upper()) else: print(s.lower()) ```
MatrixStudio/Codeforces-Python-Submissions
The average miner Vaganych took refresher courses. As soon as a miner completes the courses, he should take exams. The hardest one is a computer test called "Testing Pants for Sadness". The test consists of *n* questions; the questions are to be answered strictly in the order in which they are given, from question 1 t...
```python n = int(input()) l = list(map(int,input().split())) s = sum([l[i]*(i+1)-i for i in range(n)]) print(s) ```
MatrixStudio/Codeforces-Python-Submissions
The organizers of a programming contest have decided to present t-shirts to participants. There are six different t-shirts sizes in this problem: S, M, L, XL, XXL, XXXL (sizes are listed in increasing order). The t-shirts are already prepared. For each size from S to XXXL you are given the number of t-shirts of this si...
```python used = list(map(int, input().split())) r = ['S', 'M', 'L', 'XL', 'XXL', 'XXXL'] d = dict() for i in range(6): d[r[i]] = i c = [0 for i in range(5)] n = int(input()) f = True ans = ['' for i in range(n)] cc = [[0 for j in range(0)] for i in range(5)] for i in range(n): l = list(input().split...
MatrixStudio/Codeforces-Python-Submissions
After Fox Ciel won an onsite round of a programming contest, she took a bus to return to her castle. The fee of the bus was 220 yen. She met Rabbit Hanako in the bus. They decided to play the following game because they got bored in the bus. - Initially, there is a pile that contains *x* 100-yen coins and *y* 10-yen ...
```python x, y = map(int, input().split()) m = 0 while True: if m: if y<2: b = 0 else: b = max(k for k in (2,12,22) if k<=y) a = min(x, (220-10*b)//100) else: a = min(2,x) b = min(y, (220-100*a)//10) if 100*a+10*b < 220: ...
MatrixStudio/Codeforces-Python-Submissions
There is the faculty of Computer Science in Berland. In the social net "TheContact!" for each course of this faculty there is the special group whose name equals the year of university entrance of corresponding course of students at the university. Each of students joins the group of his course and joins all groups f...
```python n = int(input()) k = [int(i) for i in input().split()] k.sort() print(k[n//2]) ```
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 w = input() h = "hello" c = 0 for i in w: if i == w[c]: c+=1 if c == len(h): break if c == len(h): print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
One cold winter evening Alice and her older brother Bob was sitting at home near the fireplace and giving each other interesting problems to solve. When it was Alice's turn, she told the number *n* to Bob and said: —Shuffle the digits in this number in order to obtain the smallest possible number without leading zeroe...
```python n=input() m=input() lst=list(n) lst.sort() i=0 while(i<len(n) and lst[i]=='0'): i+=1 if(i<len(n)): t=lst[i] lst[i]=lst[0] lst[0]=t n=''.join(lst) print(n) if n==m: print("OK") else: print("WRONG ANSWER") ```
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 q=[] for i in range(0,5): a=list(map(int,input().split())) q.append(a) c=0 for i in range(0,5): for j in range(0,5): if q[i][j]==1: c+=abs(2-i) c+=abs(2-j) print(c) ```
MatrixStudio/Codeforces-Python-Submissions
You are given a text of single-space separated words, consisting of small and capital Latin letters. Volume of the word is number of capital letters in the word. Volume of the text is maximum volume of all words in the text. Calculate the volume of the given text.
```python import sys n = sys.stdin.readline() S = sys.stdin.readline().split() maxanswer = 0 for word in S: answer = 0 for character in word: if ord(character) > 64 and ord(character) < 91: answer += 1 else: pass maxanswer = max(answer, maxanswer) print(answer) ``...
MatrixStudio/Codeforces-Python-Submissions
Sereja showed an interesting game to his friends. The game goes like that. Initially, there is a table with an empty cup and *n* water mugs on it. Then all players take turns to move. During a move, a player takes a non-empty mug of water and pours all water from it into the cup. If the cup overfills, then we assume th...
```python n,k=map(int,input().split());a=list(map(int,input().split()));print("YES" if sum(a)-max(a)<=k else "NO") #removing max because we have n-1 friends so we ar etrying to put as minimum as possible... ```
MatrixStudio/Codeforces-Python-Submissions
Maxim wants to buy an apartment in a new house at Line Avenue of Metropolis. The house has *n* apartments that are numbered from 1 to *n* and are arranged in a row. Two apartments are adjacent if their indices differ by 1. Some of the apartments can already be inhabited, others are available for sale. Maxim often visi...
```python import math def apartment(number_of_apart,number_of_occupied): min,max=0,0 floor=math.floor(number_of_apart/2) if number_of_occupied==number_of_apart: return 0,0 if number_of_occupied>=floor: return 1, number_of_apart-number_of_occupied else: return 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 a = int(input()) b = list(map(int, input().split())) c = list(map(int, input().split())) d = list(map(int, input().split())) print(sum(b)-sum(c)) print(sum(c)-sum(d)) ```
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 n = int(input()) arr = list(map(int, input().split())) vec = [[], [], [], []] for i in range(n): vec[arr[i]].append(i + 1) mn = min(len(vec[1]), len(vec[2]), len(vec[3])) print(mn) for i in range(mn): print(vec[1][i], vec[2][i], vec[3][i]) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them. Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain nu...
```python #Shanmukh s=input() s1=s.replace("WUB"," ") s1=list(s1) n=len(s1) for i in range(len(s1)): if(s1[i]==" "): s1[i]='' else: break for i in range(len(s1)-1): if(s1[i]==' ' and s1[i+1]==' '): s1[i]='' for i in range(len(s1)): if(s1[n-1-i]==" "): s1[n-...
MatrixStudio/Codeforces-Python-Submissions
Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then...
```python from collections import OrderedDict st = OrderedDict() N = int(input()) for _ in range(N): msg = input() if msg in st.keys(): del st[msg] st[msg] = 0 for i in reversed(st): print(i) ```
MatrixStudio/Codeforces-Python-Submissions
Valera has got *n* domino pieces in a row. Each piece consists of two halves — the upper one and the lower one. Each of the halves contains a number from 1 to 6. Valera loves even integers very much, so he wants the sum of the numbers on the upper halves and the sum of the numbers on the lower halves to be even. To do...
```python n = int(input()) x = [] y = [] for i in range(n): up, down = map(int, input().split()) x.append(up) y.append(down) up = sum(x) down = sum(y) if up%2 == 0 and down%2 == 0: print(0) elif up%2 == 1 and down%2 == 1 and n != 1: ans = -1 for i in range(n): if (x[i...
MatrixStudio/Codeforces-Python-Submissions
After making bad dives into swimming pools, Wilbur wants to build a swimming pool in the shape of a rectangle in his backyard. He has set up coordinate axes, and he wants the sides of the rectangle to be parallel to them. Of course, the area of the rectangle must be positive. Wilbur had all four vertices of the planned...
```python n = int(input()) if n == -1: print("-1") else: a = set() b = set() for _ in range(n): x, y = map(int, input().split()) a.add(x) b.add(y) if len(a) != 2 or len(b) != 2: print("-1") else: a = list(a) b = list(b) p...
MatrixStudio/Codeforces-Python-Submissions
You are given *N* points on a plane. Write a program which will find the sum of squares of distances between all pairs of points.
```python print("_RANDOM_GUESS_1689448907.059664")# 1689448907.0596824 ```
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 numero = int(input()) arreglo = [] for i in range(numero): palabra = str(input()) caracteres = len(palabra) if caracteres > 10: primera = palabra[0] ultima = palabra[caracteres-1] print(primera+str(caracteres-2)+ultima) else: print(palabra) ```
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 n=int(input()) a=list(map(int,input().split(' ')))[:n] min=min(a) out=0 flag=0 for i in range(n): if a[i]==min: for j in range(i+1,n): if a[j]==min: if flag==0: out=j-i i=j flag=1 e...
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 k=int(input()) l=int(input()) m=int(input()) n=int(input()) d=int(input()) se=set() for i in range(1,d+1,k): se.add(i) for i in range(1,d+1,l): se.add(i) for i in range(1,d+1,m): se.add(i) for i in range(1,d+1,n): se.add(i) print(len(se)) ```
MatrixStudio/Codeforces-Python-Submissions
In a Berland's zoo there is an enclosure with camels. It is known that camels like to spit. Bob watched these interesting animals for the whole day and registered in his notepad where each animal spitted. Now he wants to know if in the zoo there are two camels, which spitted at each other. Help him to solve this task. ...
```python n = int(input()) data = [] for i in range(n): camel = list(map(int, input().split())) data.append(camel) ans = "NO" for i in range(n): for j in range(i+1, n): if data[i][0] + data[i][1] == data[j][0] and data[j][0] + data[j][1] == data[i][0]: ans = "YES" ...
MatrixStudio/Codeforces-Python-Submissions
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy...
```python q=int(input()) q>0 list1=[] s=0 for i in range (1,q+1): a,b,c=[int(x) for x in input().split()] list1.append(a) list1.append(b) list1.append(c) for y in list1: s=s+y if s==0 : print("YES") else : print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner. Output the probability that SmallR will...
```python a, b, c, d = input().split() print((int(a)/int(b))/(1 - int(c)/int(d)*int(a)/int(b))) ```
MatrixStudio/Codeforces-Python-Submissions
Inna loves sleeping very much, so she needs *n* alarm clocks in total to wake up. Let's suppose that Inna's room is a 100<=×<=100 square with the lower left corner at point (0,<=0) and with the upper right corner at point (100,<=100). Then the alarm clocks are points with integer coordinates in this square. The mornin...
```python n = int(input()) memo_x = {} memo_y = {} for i in range(n): x, y = list(map(int, input().split())) if x in memo_x: memo_x[x] += 1 else: memo_x[x] = 1 if y in memo_y: memo_y[y] += 1 else: memo_y[y] = 1 print(min(len(memo_x), len(memo_y))) ```
MatrixStudio/Codeforces-Python-Submissions
Sereja showed an interesting game to his friends. The game goes like that. Initially, there is a table with an empty cup and *n* water mugs on it. Then all players take turns to move. During a move, a player takes a non-empty mug of water and pours all water from it into the cup. If the cup overfills, then we assume th...
```python import sys def main(): n, s, *l = map(int, sys.stdin.read().strip().split()) return ('NO', 'YES')[sum(l) - max(l) <= s] print(main()) ```
MatrixStudio/Codeforces-Python-Submissions
You are given a rectangular board of *M*<=×<=*N* squares. Also you are given an unlimited number of standard domino pieces of 2<=×<=1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions: 1. Each domino completely covers ...
```python a,b=(map(int,input().split())) m=(a*b)//2 print(m) ```
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 def capitalizied_word(word): return word[0].upper() + word[1:] input_word = input() capitalizied_word = capitalizied_word(input_word) print(capitalizied_word) ```
MatrixStudio/Codeforces-Python-Submissions
Ilya is a very clever lion, he lives in an unusual city ZooVille. In this city all the animals have their rights and obligations. Moreover, they even have their own bank accounts. The state of a bank account is an integer. The state of a bank account can be a negative number. This means that the owner of the account ow...
```python # Read the input value n n = int(input()) # Convert n to a string to easily manipulate its digits n_str = str(n) # Initialize a variable to store the maximum balance max_balance = n # Try two possibilities: # 1. Remove the last digit (rightmost) from n_str and convert it back to an integer n_min...
MatrixStudio/Codeforces-Python-Submissions
According to an old legeng, a long time ago Ankh-Morpork residents did something wrong to miss Fortune, and she cursed them. She said that at some time *n* snacks of distinct sizes will fall on the city, and the residents should build a Snacktower of them by placing snacks one on another. Of course, big snacks should b...
```python n=int(input()) ins= input().split() store=[] for a in ins: if int(a)<n: store.append(int(a)) print("\n") else: str1 = str(a) store.sort() for j in store: str1=str1+" "+str(j) print(str1) store=[] n=n-1 ```
MatrixStudio/Codeforces-Python-Submissions
The Easter Rabbit laid *n* eggs in a circle and is about to paint them. Each egg should be painted one color out of 7: red, orange, yellow, green, blue, indigo or violet. Also, the following conditions should be satisfied: - Each of the seven colors should be used to paint at least one egg. - Any four eggs lying s...
```python n = int(input()) rs = '' colors = 'ROYGBIV' cnt = 0 while len(rs)+4<=n: cnt = cnt%7 rs += colors[cnt:cnt+4] cnt += 1 rs += colors[cnt:cnt+n%4] print(rs) ```
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 = map(int,input().split()) arr = list(map(int,input().split())) arr.sort() j = ans = 0 for i in range(n): while j<n and arr[j]-arr[i]<=d: j += 1 ans = max(ans,j-i) print(n-ans) ```
MatrixStudio/Codeforces-Python-Submissions
You are given an array of *n* integer numbers. Let *sum*(*l*,<=*r*) be the sum of all numbers on positions from *l* to *r* non-inclusive (*l*-th element is counted, *r*-th element is not counted). For indices *l* and *r* holds 0<=≤<=*l*<=≤<=*r*<=≤<=*n*. Indices in array are numbered from 0. For example, if *a*<==<=[<...
```python import sys n = int(input()) a = list(map(int, input().split())) max_val = -10**18 ans = [-1, -1, -1] for d2 in range(n): seg0, seg1, max_d1 = 0, sum(a[:d2]), 0 pre_max = seg0 - seg1 for d1 in range(d2): seg0 += a[d1] seg1 -= a[d1] if pre_max < seg0 - seg1: ...
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 a=input() a=a.split() for i in range(2): a[i]=int(a[i]) n=a[0] m=a[1] a=input() a=a.split() for i in range(len(a)): a[i]=int(a[i]) a.sort() i=0 s=0 while i<m: s+=a[i] i+=1 print(abs(s)) ```
MatrixStudio/Codeforces-Python-Submissions
A and B are preparing themselves for programming contests. An important part of preparing for a competition is sharing programming knowledge from the experienced members to those who are just beginning to deal with the contests. Therefore, during the next team training A decided to make teams so that newbies are solvi...
```python n,m=map(int,input().split()) # matrix=[list(map(int,input().split())) for i in range(m)] # arr=list(map(int,input().split())) # power=int(input()) if n>m: c=m b=n else: c=n b=m if b<=1 or c<1: print(0) exit() if c<=b//2: print(c) else: val=math.ceil(b/2) x=...
MatrixStudio/Codeforces-Python-Submissions
Petya has equal wooden bars of length *n*. He wants to make a frame for two equal doors. Each frame has two vertical (left and right) sides of length *a* and one top side of length *b*. A solid (i.e. continuous without breaks) piece of bar is needed for each side. Determine a minimal number of wooden bars which are ne...
```python n=int(input()) a=int(input()) b=int(input()) l=[a,a,a,a,n] l.sort() cur=0 ans=0 e=[] for i in range(5): cur+=l[i] if cur>n: e.append(cur-l[i]) cur=l[i] ans+=1 e.sort() i=0 c=0 #print(e) e.append(0) e.append(0) while(i<len(e)): if n-e[i]>=b: c+=...
MatrixStudio/Codeforces-Python-Submissions
Vasya has recently developed a new algorithm to optimize the reception of customer flow and he considered the following problem. Let the queue to the cashier contain *n* people, at that each of them is characterized by a positive integer *a**i* — that is the time needed to work with this customer. What is special abou...
```python def solve(act, prev, N): global arr global dp global to if act >= N: return 0 if prev >= N else arr[prev] if dp[act][prev] == -1: answ = 10**9 v = max(arr[prev], arr[act]) + solve(act+2, act+1, N) if v < answ: answ = v to[a...
MatrixStudio/Codeforces-Python-Submissions
Your friend has *n* cards. You know that each card has a lowercase English letter on one side and a digit on the other. Currently, your friend has laid out the cards on a table so only one side of each card is visible. You would like to know if the following statement is true for cards that your friend owns: "If a c...
```python s=list(input()) # print(type(s[-1])) s1=['b','c','d','f','g','h','j','k','l','m','n','r','q','p','s','t','v','w','x','y','z'] c=0 for i in s: if(i=="a"): c+=1 elif(i=="e"): c+=1 elif(i=="i"): c+=1 elif(i=="o"): c+=1 elif(i=="u"): c+=1 ...
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 def maxZ(lst,n): sp = list(lst) n1 = int(n) sommeMax = 0 while(n1>0): index = sp.index(max(sp)) sommeMax += max(sp) sp[index] -= 1 if(sp[index]==0): sp.pop(index) n1-=1 return sommeMax def minZ(lst,n): sk = list(lst) ...
MatrixStudio/Codeforces-Python-Submissions
DZY has a sequence *a*, consisting of *n* integers. We'll call a sequence *a**i*,<=*a**i*<=+<=1,<=...,<=*a**j* (1<=≤<=*i*<=≤<=*j*<=≤<=*n*) a subsegment of the sequence *a*. The value (*j*<=-<=*i*<=+<=1) denotes the length of the subsegment. Your task is to find the longest subsegment of *a*, such that it is possible ...
```python n = int(input()) nums = [int(n) for n in input().split()] nums.append(0) dp = list() dp.append(1) for j in range(1, n): if(nums[j] > nums[j-1]): dp.append(dp[j-1] + 1) else: dp.append(1) m = 0 x = 0 for i in range(n-1, -1, -1): m = max(m, dp[i-1] + 1, x + 1) 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 ch="chest" bi="biceps" ba="back" m={ch:0,bi:0,ba:0} n=int(input()) a=map(int,input().split()) s=[ch,bi,ba]*n z=zip(s[:n],a) for e,ai in z: m[e]+=ai print(max(m,key=m.get)) ```
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(int, input().split()) a = list(map(int, input().split())) a.sort() c = sum(a) for i in range(m-n+1): if c > sum(a[i:i+n-1]): c = sum(a[i:i+n-1]) d = a[i+n-1] - a[i] print(d) ```
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 n = int(input()) a = list(map(int, input().split())) c = 1 mc = 1 # mc = 0 is an error for 5 4 3 2 1 p = a[0] for v in a[1:]: if p <= v: c += 1 mc = max(mc, c) else: c = 1 p = v print(mc) ```
MatrixStudio/Codeforces-Python-Submissions
Vasily the Programmer loves romance, so this year he decided to illuminate his room with candles. Vasily has *a* candles.When Vasily lights up a new candle, it first burns for an hour and then it goes out. Vasily is smart, so he can make *b* went out candles into a new candle. As a result, this new candle can be used ...
```python a,b=input().split() a1=int(a) b1=int(b) def hrs(x): if x<b1: return 0 elif x==b1: return 1 else: return a1//b1 + hrs((a1//b1) + (a1%b1)) print(a1 + (hrs(a1))) ```
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 n=int(input()) a=input() g=a.count("G") b=a.count("B") r=a.count("R") amm=b+r+g am=0 if b!=0: am+=1 if g!=0: am+=1 if r!=0: am+=1 if am==1: if b!=0: print("B") if g!=0: print("G") if r!=0: print("R") elif am==3: print("BGR") elif am==...
MatrixStudio/Codeforces-Python-Submissions
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy...
```python n = int(input()) sums1 = 0 sums2 = 0 sums3 = 0 for i in range(n): k = list(map(int, input().split())) sums1 += k[0] sums2 += k[1] sums3 += k[2] if sums1 == 0 and sums2 == 0 and sums3 == 0: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Jafar has *n* cans of cola. Each can is described by two integers: remaining volume of cola *a**i* and can's capacity *b**i* (*a**i* <=≤<= *b**i*). Jafar has decided to pour all remaining cola into just 2 cans, determine if he can do this or not!
```python n=int(input()) a=list(map(int,input().split()))[:n] b=list(map(int,input().split()))[:n] if sum(a)<=sum(b): print('YES') else: print('NO') ```
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 k = int(input()) l = int(input()) power = 0 for i in range(int(l)): if k ** i == l: power += 1 print('YES') print(power) break if power == 0: print('NO') ```
MatrixStudio/Codeforces-Python-Submissions
Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad. Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element eq...
```python lev=int(2); n=int(input()); k=int(input()); s="1"; while lev<=n: temp=s; temp2=str(lev); s=s+temp2; s=s+temp; lev=lev + 1; print(s); if n!=1: print(s[k-1]); else: print(1); ```
MatrixStudio/Codeforces-Python-Submissions
Kyoya Ootori has a bag with *n* colored balls that are colored with *k* different colors. The colors are labeled from 1 to *k*. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color *i* before drawing the last ball of...
```python # Author: Akash Kumar from math import comb # Initialization mod= int(1e9 + 7) k =int(input()) tot_num_balls = int(input()) res = 1 for i in range(1, k): c = int(input()) res = res*comb(tot_num_balls+c-1, c-1) % mod tot_num_balls += c print(res) ```
MatrixStudio/Codeforces-Python-Submissions
Each of you probably has your personal experience of riding public transportation and buying tickets. After a person buys a ticket (which traditionally has an even number of digits), he usually checks whether the ticket is lucky. Let us remind you that a ticket is lucky if the sum of digits in its first half matches th...
```python n = int(input()) lista = [int(a) for a in input()] mayor = lista[0] > lista[-1] mala = False for x in range(n): if mayor and lista[x] < lista[(-x - 1)]: mala = True if not mayor and lista[x] > lista[(-x - 1)]: mala = True if mala: print('NO') else: print('YES') ...
MatrixStudio/Codeforces-Python-Submissions
Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. For example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. When a team plays as ...
```python #include <iostream> using namespace std; int main() { int n; cin>>n; int a[n][3],i,j,c=0; for(i=0;i<n;i++) { for(j=0;j<2;j++) cin>>a[i][j]; } for(i=0;i<n;i++) { for(j=0;j<n;j++) { if(a[i][0]==a[j][1]) c++; ...
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 lst1 = input() lst2 = input() b = 0 a = "" for i in lst1: if int(i) == int(lst2[b]): a = a + "0" b +=1 else: a = a + "1" b +=1 print(a) ```
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 a = input() aa = [] for i in range(len(a)): aa.append(a[i]) aa = aa[:: - 1] b = input() bb = [] for i in range(len(b)): bb.append(b[i]) c = [] if len(aa) == len(bb): for i in range(len(aa)): if aa[i] != bb[i]: c.append(1) else: print("NO") if len(c) > 0: ...
MatrixStudio/Codeforces-Python-Submissions
Once Max found an electronic calculator from his grandfather Dovlet's chest. He noticed that the numbers were written with seven-segment indicators ([https://en.wikipedia.org/wiki/Seven-segment_display](https://en.wikipedia.org/wiki/Seven-segment_display)). Max starts to type all the values from *a* to *b*. After typi...
```python d = [6, 2, 5, 5, 4, 5, 6, 3, 7, 6] a, b = map(int, input().split()) nums = str(list(range(a, b+1))) r = 0 for i in range(len(d)): r += d[i] * nums.count(str(i)) print(r) ```
MatrixStudio/Codeforces-Python-Submissions
There are *n* beacons located at distinct positions on a number line. The *i*-th beacon has position *a**i* and power level *b**i*. When the *i*-th beacon is activated, it destroys all beacons to its left (direction of decreasing coordinates) within distance *b**i* inclusive. The beacon itself is not destroyed however....
```python n = int(input()) dp,li,mx=[0]*1000010,[0]*1000010,0 for _ in range(n):a,b = map(int,input().split());li[a]=b; for i in range(1000010): if li[i]:dp[i]=dp[i-li[i]-1]+1 else:dp[i]=dp[i-1] mx = max(mx,dp[i]) print(n-mx) ```
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 import string s=input() u=0 l=0 for i in s: if i in string.ascii_lowercase: l=l+1 else: u=u+1 if l>=u: print(s.lower()) else: print(s.upper()) ```
MatrixStudio/Codeforces-Python-Submissions
Fox Ciel is playing a game with numbers now. Ciel has *n* positive integers: *x*1, *x*2, ..., *x**n*. She can do the following operation as many times as needed: select two different indexes *i* and *j* such that *x**i* &gt; *x**j* hold, and then apply assignment *x**i* = *x**i* - *x**j*. The goal is to make the sum ...
```python '''input 5 45 12 27 30 18 ''' n = int(input()) d = 1e9 x = list(map(int, input().split())) for i in range(n-1): if x[i+1]-x[i] >= 0: d = min(d, x[i+1]-x[i]) print(n*d) ```
MatrixStudio/Codeforces-Python-Submissions
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory. George and Alex want to live in the same room. The dormitory has *n* rooms in total. At the moment the *i*-th room has *p**i* peopl...
```python n = int(input()) # Input: The number of rooms count = 0 # Initialize a counter for rooms where George and Alex can move in for _ in range(n): pi, qi = map(int, input().split()) # Input: The number of people in the room and room's capacity if qi - pi >= 2: count += 1 print(count) ...
MatrixStudio/Codeforces-Python-Submissions
You have an array *a* consisting of *n* integers. Each integer from 1 to *n* appears exactly once in this array. For some indices *i* (1<=≤<=*i*<=≤<=*n*<=-<=1) it is possible to swap *i*-th element with (*i*<=+<=1)-th, for other indices it is not possible. You may perform any number of swapping operations any order. T...
```python #include<bits/stdc++.h> #include<string> using namespace std; typedef long long int ll; typedef unsigned long long llu; typedef long double ldo; typedef vector<ll> vl; typedef vector<pair<ll,ll>> vpll; typedef vector<string> vs; typedef vector<vector<ll>> vvll; typedef vector<vector<int>> vvi; #def...
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()) s = list(map(int, input().split())) am = 0 maxs = scores[0] mins = scores[0] for i in range(1, n): if s[i] > maxs: am += 1 maxs = s[i] elif s[i] < mins: amt += 1 mins = s[i] print(am) ```
MatrixStudio/Codeforces-Python-Submissions
Vika has *n* jars with paints of distinct colors. All the jars are numbered from 1 to *n* and the *i*-th jar contains *a**i* liters of paint of color *i*. Vika also has an infinitely long rectangular piece of paper of width 1, consisting of squares of size 1<=×<=1. Squares are numbered 1, 2, 3 and so on. Vika decided ...
```python from sys import* def square(a): k = min(a) l = [i for i, x in enumerate(a) if x == k] if(len(l) == 1): return (n*k + (n-1)) else: b =[0]*(len(l)) for i in range(len(l) - 1): b[i] = l[i+1] - l[i] b[len(l) - 1] = (len(a) - l[len(l)-1] + l[0]) return (n*k + (max(b) - 1)) n = int(inpu...
MatrixStudio/Codeforces-Python-Submissions
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy...
```python # -*- coding: utf-8 -*- """ Created on Fri Oct 9 09:21:45 2020 @author: 86198 """ def add(x,y): return x+y n=int(input()) a=0 m=[0,0,0] for i in (0,n): l=[int(i)for i in input().split()] m=map(add,m,l) for i in list(m): if i !=0: a=a+1 else: a=0 if a!=0...
MatrixStudio/Codeforces-Python-Submissions
You have a description of a lever as string *s*. We'll represent the string length as record |*s*|, then the lever looks as a horizontal bar with weights of length |*s*|<=-<=1 with exactly one pivot. We will assume that the bar is a segment on the *Ox* axis between points 0 and |*s*|<=-<=1. The decoding of the lever d...
```python s=[n for n in input()] k=s.index('^') a=s[:k][::-1] b=s[k+1:] m=0 for n in range(len(a)): if ord('0')<=ord(a[n])<=ord('9'): m+=int(a[n])*(n+1) p=0 for n in range(len(b)): if ord('0')<=ord(b[n])<=ord('9'): p+=int(b[n])*(n+1) if m==p: print('balance') elif m>p: print('left') elif m<p: ...