source
stringclasses
3 values
instruction
stringlengths
23
3.97k
input
stringclasses
1 value
output
stringlengths
1
3.75k
MatrixStudio/Codeforces-Python-Submissions
Vitaly has an array of *n* distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: 1. The product of all numbers in the first set is less than zero (<=&lt;<=0). 1. The product of all numbers in the second set is greater than zero (<=&gt;<=0). 1. The produ...
```python n=int(input()) l=list(map(int,input().split())) l1=[] l2=[] l3=[] for i in range(len(l)): if l[i]<0: l1.append(l[i]) elif l[i]==0: l2.append(l[i]) else: l3.append(l[i]) if len(l1)%2==0: l2.append(l1[0]) l1=l1[1:] if len(l3)==0: l3.append(l1[0...
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 a=int(input()) m=map(int,input().split()) liste=list(m) sonuclar=[] cevap=[] for i in range(a-1): m=abs(liste[i]-liste[i+1]) sonuclar.append(m) sonuclar.append(abs(liste[0]-liste[-1])) for x in range(len(sonuclar)): if sonuclar[x]==min(sonuclar) and x+1!=len(sonuclar): cevap.app...
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 inpu = input() m = int(inpu.split()[0]) n = int(inpu.split()[1]) s = n*m print( s//2) ```
MatrixStudio/Codeforces-Python-Submissions
Anastasia loves going for a walk in Central Uzhlyandian Park. But she became uninterested in simple walking, so she began to collect Uzhlyandian pebbles. At first, she decided to collect all the pebbles she could find in the park. She has only two pockets. She can put at most *k* pebbles in each pocket at the same tim...
```python def main(): n, m = map(int, input().split()) print((sum((x + m - 1) // m for x in map(int, input().split())) + 1) // 2) if __name__ == '__main__': main() ```
MatrixStudio/Codeforces-Python-Submissions
Valera is a collector. Once he wanted to expand his collection with exactly one antique item. Valera knows *n* sellers of antiques, the *i*-th of them auctioned *k**i* items. Currently the auction price of the *j*-th object of the *i*-th seller is *s**ij*. Valera gets on well with each of the *n* sellers. He is perfec...
```python n,v=map(int,input().split()) t=[] k=[] for i in range(n): l=list(map(int,input().split())) temp=list(l[1:]) temp.sort() l=[l[0]]+temp if v>l[1]: k.append(l[0]) print(len(k)) for i in range(len(k)): if i==(len(k)-1): print(k[i]) else: print(k...
MatrixStudio/Codeforces-Python-Submissions
Luke Skywalker got locked up in a rubbish shredder between two presses. R2D2 is already working on his rescue, but Luke needs to stay alive as long as possible. For simplicity we will assume that everything happens on a straight line, the presses are initially at coordinates 0 and *L*, and they move towards each other ...
```python (a,b,c,d)=input().split() a=int(a) b=int(b) c=int(c) d=int(c) x=(b-a)/(c+d) print(x) ```
MatrixStudio/Codeforces-Python-Submissions
One day in the IT lesson Anna and Maria learned about the lexicographic order. String *x* is lexicographically less than string *y*, if either *x* is a prefix of *y* (and *x*<=≠<=*y*), or there exists such *i* (1<=≤<=*i*<=≤<=*min*(|*x*|,<=|*y*|)), that *x**i*<=&lt;<=*y**i*, and for any *j* (1<=≤<=*j*<=&lt;<=*i*) *x**j...
```python n=int(input()) l=list(map(int,input().split())) ones=l.count(1) two=l.count(2) three=l.count(3) four=l.count(4) sum=four while(three>0 and ones>0): three-=1 ones-=1 sum+=1 while three>0: three-=1 sum+=1 while two>0 and two>2: two-=2 sum+=1 while two>0 a...
MatrixStudio/Codeforces-Python-Submissions
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it: - deletes all the vowels, - inserts a character "." before each consonant, - replaces ...
```python string = input() string = list(string) vowel = ['a','A','e','E','o','O','i','I','u','U','y','Y'] consonant = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','z'] for i in range(0, len(vowel)): while(vowel[i] in string): string.remove(vowel[i]) ans = "" for i i...
MatrixStudio/Codeforces-Python-Submissions
Johny likes numbers *n* and *k* very much. Now Johny wants to find the smallest integer *x* greater than *n*, so it is divisible by the number *k*.
```python n,k=list(map(int,input().split())) c=k//n print(n*(c+1)) ```
MatrixStudio/Codeforces-Python-Submissions
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected. The pasture is a rectangle consisting of *R*<=×<=*C* cells. Each cell is either empty, contains a sheep, a wolf or...
```python import sys import math #to read string get_string = lambda: sys.stdin.readline().strip() #to read list of integers get_list = lambda: list( map(int,sys.stdin.readline().strip().split()) ) #to read integers get_int = lambda: int(sys.stdin.readline()) #--------------------------------WhiteHat010----...
MatrixStudio/Codeforces-Python-Submissions
Vasya is going to the Olympics in the city Ntown by train. The boy wants to read the textbook to prepare for the Olympics. He counted that he needed *k* hours for this. He also found that the light in the train changes every hour. The light is measured on a scale from 0 to 100, where 0 is very dark, and 100 is very lig...
```python n,k=map(int,input().split()) for i in range(n): a=list(map(int,input().split())) b=sorted(a) c=n-k print(b[c]) print(1,3,4) ```
MatrixStudio/Codeforces-Python-Submissions
The following problem is well-known: given integers *n* and *m*, calculate where 2*n*<==<=2·2·...·2 (*n* factors), and denotes the remainder of division of *x* by *y*. You are asked to solve the "reverse" problem. Given integers *n* and *m*, calculate
```python n=int(input()) m=int(input()) x=2**n if n>=1 and n<=10**8 and m>=1 and m<=10**8: print(m%x) else: print('error') ```
MatrixStudio/Codeforces-Python-Submissions
As you may know, MemSQL has American offices in both San Francisco and Seattle. Being a manager in the company, you travel a lot between the two cities, always by plane. You prefer flying from Seattle to San Francisco than in the other direction, because it's warmer in San Francisco. You are so busy that you don't rem...
```python input() s = input() cur = s[0] StoF = 0 FtoS = 0 for c in s: if c != cur: cur = c if c == 'F': StoF += 1 else: FtoS += 1 if StoF > FtoS: print("YES") else: print("NO") ```
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 # Domino squares M,N=input().split() M=int(M) N=int(N) print(int(M*N/2)) ```
MatrixStudio/Codeforces-Python-Submissions
Couple Cover, a wildly popular luck-based game, is about to begin! Two players must work together to construct a rectangle. A bag with *n* balls, each with an integer written on it, is placed on the table. The first player reaches in and grabs a ball randomly (all balls have equal probability of being chosen) — the num...
```python import sys input = sys.stdin.buffer.readline n = int(input()) l = 3 * pow(10, 6) + 5 cnt = [0] * l for i in list(map(int, input().split())): cnt[i] += 1 c1, c2 = [0] * l, [0] * l m0 = pow(10, 8) for i in range(1, l): ci = cnt[i] if i * i < l: j = i * i c1[j] += ci * ...
MatrixStudio/Codeforces-Python-Submissions
Vladik is a competitive programmer. This year he is going to win the International Olympiad in Informatics. But it is not as easy as it sounds: the question Vladik face now is to find the cheapest way to get to the olympiad. Vladik knows *n* airports. All the airports are located on a straight line. Each airport has u...
```python x = input().split() y = input() z = [] for i in y: z.append(i) if y[int(x[1])-1] == y[int(x[2])-1]: print('0') elif y[int(x[1])-1] != y[int(x[2])-1]: print('1') ```
MatrixStudio/Codeforces-Python-Submissions
You are given a set of *n* vectors on a plane. For each vector you are allowed to multiply any of its coordinates by -1. Thus, each vector *v**i*<==<=(*x**i*,<=*y**i*) can be transformed into one of the following four vectors: - *v**i*1<==<=(*x**i*,<=*y**i*), - *v**i*2<==<=(<=-<=*x**i*,<=*y**i*), - *v**i*3<==<=(*x*...
```python dx = [1,-1,1,-1] dy = [1,1,-1,-1] def conv(x,y,idx): d = (1e18-x)**2 + (1e18-y)**2 ret = [] for i in range(4): ret.append((d,x*dx[i],y*dy[i],i+1,idx)) return ret otpt = open(“output.txt”, “w”) inpt = open("input.txt", "r") p = [] n = int(inpt.readline()) for i in range(n...
MatrixStudio/Codeforces-Python-Submissions
Polycarpus likes studying at school a lot and he is always diligent about his homework. Polycarpus has never had any problems with natural sciences as his great-great-grandfather was the great physicist Seinstein. On the other hand though, Polycarpus has never had an easy time with history. Everybody knows that the Wo...
```python import sys input = lambda: sys.stdin.readline().rstrip() from heapq import * N = int(input()) A = [] for _ in range(N): a,b = map(int, input().split()) A.append((a,b)) A.sort(key=lambda x:x[1]) v = [] ans = 0 for a,b in A: while v and -v[0]>a: heappop(v) ans+=1 ...
MatrixStudio/Codeforces-Python-Submissions
Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in *n* different shops in the city. It's known that the price of one bottle in the shop *i* is equal to *x**i* coins. Vasiliy plans to buy his favorite ...
```python n = int(input()) x = list(map(int, input().split())) x.sort() m = int(input()) for i in range(m): mi = int(input()) l = 0 r = n while l < r: mid = (l + r) // 2 if x[mid] <= mi: l = mid + 1 else: r = mid print(l) ...
MatrixStudio/Codeforces-Python-Submissions
Карта звёздного неба представляет собой прямоугольное поле, состоящее из *n* строк по *m* символов в каждой строке. Каждый символ — это либо «.» (означает пустой участок неба), либо «*» (означает то, что в этом месте на небе есть звезда). Новое издание карты звёздного неба будет напечатано на квадратных листах, поэто...
```python n, m = list(map(int, input().split())) lst = [] for i in range(n): lst.append(list(input().rstrip())) stars = [] for i in range(n): for j in range(m): if lst[i][j] == '*': stars.append([i, j]) min_x = 1e9 min_y = 1e9 max_x = -1e9 max_y = -1e9 for x in stars: m...
MatrixStudio/Codeforces-Python-Submissions
Duff is in love with lovely numbers! A positive integer *x* is called lovely if and only if there is no such positive integer *a*<=&gt;<=1 such that *a*2 is a divisor of *x*. Malek has a number store! In his store, he has only divisors of positive integer *n* (and he has all of them). As a birthday present, Malek want...
```python n = int(input()) if n ==1: print(0) else: s = n **0.5 for i in range(2,int(s)+1): if n % i ==0: if n % i**2 ==0: n = n / i print(int(n)) ```
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 # strs = [input() for _ in range(3)] def main(): n = int(input()) s = input() r = g = b = 0 for c in s: if c == 'R': r += 1 elif c == 'G': g += 1 else: b += 1 ss = r + g + b l = [(r, 'R'), (g, 'G'), (b, 'B')] l.sort() l1, l2, l3 = l c1, s1 = l1 c2, s2 = l2 c3, s3 = l3 if ss >= 5...
MatrixStudio/Codeforces-Python-Submissions
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not ...
```python z = input() z += 'O' s = 0 p = 0 for i in range(len(z)-1): if s <= 5: if z[i] == z[i+1]: s += 1.5 else: p += 1 s = 0 else: p += 1 s = 0 print(p) ```
MatrixStudio/Codeforces-Python-Submissions
Ternary numeric notation is quite popular in Berland. To telegraph the ternary number the Borze alphabet is used. Digit 0 is transmitted as «.», 1 as «-.» and 2 as «--». You are to decode the Borze code, i.e. to find out the ternary number given its representation in Borze alphabet.
```python ### https://codeforces.com/problemset/problem/32/B a = input() a=list(a) print(a) n=len(a) out=[] i=0 while i<n: if a[i]=='.': out.append(0) i=i+1 elif (a[i]=='-') & (a[i+1]=='.'): out.append(1) i=i+2 else: out.append(2) i=i+2 for nu...
MatrixStudio/Codeforces-Python-Submissions
Hideo Kojima has just quit his job at Konami. Now he is going to find a new place to work. Despite being such a well-known person, he still needs a CV to apply for a job. During all his career Hideo has produced *n* games. Some of them were successful, some were not. Hideo wants to remove several of them (possibly zer...
```python n = int(input()) games = input().replace(' ', '') bad_idxs = [n for n in range(len(games)) if games.find('10', n) == n] if len(bad_idxs) == 0: print(len(games)) else: counts = [] counts.append(len(games.replace('1', ''))) counts.append(len(games.replace('0', ''))) for bi in bad_id...
MatrixStudio/Codeforces-Python-Submissions
Absent-minded Masha got set of *n* cubes for her birthday. At each of 6 faces of each cube, there is exactly one digit from 0 to 9. Masha became interested what is the largest natural *x* such she can make using her new cubes all integers from 1 to *x*. To make a number Masha can rotate her cubes and put them in a ro...
```python n = int(input()) a = sorted([list(map(int, input().split())) for i in range(n)]) import itertools for x in range(1,10**n): good = False s = str(x) for p in itertools.permutations(a, len(s)): good |= all([int(s[i]) in v for i, v in enumerate(p)]) if not good: print(x-1) exit(0) print(...
MatrixStudio/Codeforces-Python-Submissions
The only king stands on the standard chess board. You are given his position in format "cd", where *c* is the column from 'a' to 'h' and *d* is the row from '1' to '8'. Find the number of moves permitted for the king. Check the king's moves here [https://en.wikipedia.org/wiki/King_(chess)](https://en.wikipedia.org/wik...
```python a=str(input()) col=a[0] fil=a[1] if (col=="a" or col=="h") and (int(fil)==1 or int(fil)==8): print(3) elif (col=="b" or col=="c" or col=="d" or col=="e" or col=="f" or col=="g") and (1<int(fil)<8): print(8) else: print(5) ```
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 print('YNEOS'[(list(reversed(input()))!=list(input()))::2]) ```
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 s1 = input() s2 = input() if s2 == s1[::-1]: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all *n* squad soldiers to line up on the parade ground. By the military charter the soldiers should stand in the order of non-increasing of their...
```python n = int(input()) a = list(map(int,input().split())) ma = a.index(max(a)) mi = a[::-1].index(min(a[::-1])) print(ma+mi-1) ```
MatrixStudio/Codeforces-Python-Submissions
Eighth-grader Vova is on duty today in the class. After classes, he went into the office to wash the board, and found on it the number *n*. He asked what is this number and the teacher of mathematics Inna Petrovna answered Vova that *n* is the answer to the arithmetic task for first-graders. In the textbook, a certain ...
```python # -*- coding: utf-8 -*- """ Created on Sun Aug 4 22:21:53 2019 @author: Akshay """ n=int(input().strip()) i=0 def sumDig(n): s=0 k=n while n!=0: s+=n%10 n=n//10 return k+s arr=[] while i!=n: if sumDig(i)==n: arr.append(i) i+=1 print(len(a...
MatrixStudio/Codeforces-Python-Submissions
Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands: - Include a person...
```python n = 0 t = 0 while True: try: cmd = input() if cmd[0] == '+': n += 1 elif cmd[0] == '-': n -= 1 else: m = cmd[cmd.index(':')+1:] t += len(m)*n except EOFError: print(t) exit(0) ```
MatrixStudio/Codeforces-Python-Submissions
Pashmak decided to give Parmida a pair of flowers from the garden. There are *n* flowers in the garden and the *i*-th of them has a beauty number *b**i*. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty diff...
```python n = int(input()) b = map(input().split(' '), int) print(b.count(min(b)) * b.count(max(b))) ```
MatrixStudio/Codeforces-Python-Submissions
Blake is a CEO of a large company called "Blake Technologies". He loves his company very much and he thinks that his company should be the best. That is why every candidate needs to pass through the interview that consists of the following problem. We define function *f*(*x*,<=*l*,<=*r*) as a bitwise OR of integers *x...
```python from functools import reduce n = int(input()) x = reduce(lambda a,b:a|b , map(int,input().split())) y = reduce(lambda a,b:a|b , map(int,input().split())) print(x+y) ```
MatrixStudio/Codeforces-Python-Submissions
The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups. Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime. If there is no police offi...
```python n = int(input()) s = [] s += map(int, input().split()) a, c, summ, po = 0, 0, 0, 0 for i in range(n): if s[i] > 0: po = 0 po += int(s[i]) elif s[i] == -1: po -= 1 if po < 0: c += 1 print(c) ```
MatrixStudio/Codeforces-Python-Submissions
Among other things, Bob is keen on photography. Especially he likes to take pictures of sportsmen. That was the reason why he placed himself in position *x*0 of a long straight racetrack and got ready to take pictures. But the problem was that not all the runners passed him. The total amount of sportsmen, training at t...
```python from itertools import accumulate def main(): n, x0 = map(int, input().split()) li = [] for _ in range(n): a, b = map(int, input().split()) li.append([min(a, b), max(a, b)]) d = [0] * 1001 for i in range(n): d[li[i][0]] += 1 if li[i][1] != 1001: d[li[i][1]] -= 1 d = list(accumula...
MatrixStudio/Codeforces-Python-Submissions
There is a given sequence of integers *a*1,<=*a*2,<=...,<=*a**n*, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other.
```python n=int(input()) li=list(map(int,input().split(" "))) print(n,li) res=[] res.append(li.count(1)) res.append(li.count(2)) res.append(li.count(3)) res.sort() print(res[0]+res[1]) ```
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 def solve(): n, t = [int(i) for i in input().split()] a = [int(i) for i in input().split()] i = 1 while i < t: i += a[i-1] return i == t # for _ in range(int(input())): # print("YES" if solve() else "NO") print("YES" if solve() else "NO") ```
MatrixStudio/Codeforces-Python-Submissions
Now it's time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. They've been best friends ever since primary school and hopefully, that can somehow help them in teamwork. For each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing ...
```python n,m=list(map(int,input().split())) #n: số thẻ có số 0 #m: số thẻ có số 1 #Không có 2 thẻ có số 0 liên tiếp #Không có 3 thẻ có số 1 liên Tiếp limit1=(n-1)*2+4 limit0=m+1 if m>limit1: print(-1) elif n>limit0: print(-1) else: #Trường hợp 1 số 0 và 1 số 1 đan xen nhau if ...
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 import os, sys ii = lambda : int(input()) si = lambda : input() li = lambda : list(map(int, input().split())) lsi = lambda : list(map(str, input().split())) try: sys.stdin = open(r"C:\Users\LIB-606\Desktop\input.txt",'r') except : pass import math length = ii() a = si() b = si() c = 0 for i,j in zip...
MatrixStudio/Codeforces-Python-Submissions
Given a sequence of integers *a*1,<=...,<=*a**n* and *q* queries *x*1,<=...,<=*x**q* on it. For each query *x**i* you have to count the number of pairs (*l*,<=*r*) such that 1<=≤<=*l*<=≤<=*r*<=≤<=*n* and *gcd*(*a**l*,<=*a**l*<=+<=1,<=...,<=*a**r*)<==<=*x**i*. is a greatest common divisor of *v*1,<=*v*2,<=...,<=*v**n*...
```python import collections def gcd(a,b): return gcd(b,a%b) if b!=0 else a n=int(input()) arr=[int(i) for i in input().split()] res=collections.defaultdict(int) st=collections.defaultdict(int) for i in arr: temp=collections.defaultdict(int) for j in st.keys(): val=gcd(j,i) temp[v...
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 # -*- coding: utf-8 -*- """ Created on Thu Oct 19 16:18:10 2023 @author: 苏柔德 2300011012 """ import numpy as np n, m, k = map(int, input().split()) x = np.full((n, m), 0) flag = -1 for _ in range(k): i, j = map(int, input().split()) x[i-1, j-1] = 1 for row in range(n-1): ...
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()) k=0 l=0 if a<b: k=a l=(b-a)//2 elif a>b: k=b l=(a-b)//2 else: k=a l=0 print (k, l) ```
MatrixStudio/Codeforces-Python-Submissions
Reforms continue entering Berland. For example, during yesterday sitting the Berland Parliament approved as much as *n* laws (each law has been assigned a unique number from 1 to *n*). Today all these laws were put on the table of the President of Berland, G.W. Boosch, to be signed. This time mr. Boosch plans to sign ...
```python n,k=[int(x) for x in input().split()] arr=[int(x) for x in input().split()] temp=[0] curr=0 for i in arr: curr+=i temp.append(curr) temp2=[] #print(temp) for i in range(k,n+1): temp2.append(temp[i]-temp[i-k]) #print(temp2) ans=0 l=len(temp2) maxi=[0 for i in range(l)] maxi[0]=temp2[...
MatrixStudio/Codeforces-Python-Submissions
Little Petya often travels to his grandmother in the countryside. The grandmother has a large garden, which can be represented as a rectangle 1<=×<=*n* in size, when viewed from above. This rectangle is divided into *n* equal square sections. The garden is very unusual as each of the square sections possesses its own f...
```python n=int(input()) l=list(map(int,input().split())) m=-1 for i in range(n): c=1 for j in range(i,n-1): if l[j]>=l[j+1]: c+=1 else : break for j in range(i,1,-1): if l[j]>=l[j-1]: c+=1 else : break m=max(c,m) ...
MatrixStudio/Codeforces-Python-Submissions
Little Vasya went to the supermarket to get some groceries. He walked about the supermarket for a long time and got a basket full of products. Now he needs to choose the cashier to pay for the products. There are *n* cashiers at the exit from the supermarket. At the moment the queue for the *i*-th cashier already has ...
```python from sys import stdin input=lambda :stdin.readline()[:-1] n=int(input()) k=list(map(int,input().split())) ans=float("inf") for i in range(n): m=list(map(int,input().split())) curr=(len(m))*15+(sum(m))*5 ans=min(ans,curr) print(ans) ```
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 mn = input() m, n = [int(x) for x in mn.split()] if m % 2 == 0 or n % 2 == 0: ans = int((m*n) / 2) else: ans = int(((m*n) - 1) / 2) print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Kevin Sun has just finished competing in Codeforces Round #334! The round was 120 minutes long and featured five problems with maximum point values of 500, 1000, 1500, 2000, and 2500, respectively. Despite the challenging tasks, Kevin was uncowed and bulldozed through all of them, distinguishing himself from the herd a...
```python a=[] i=0 while i<2: b=input().split() a.append(b) i=i+1 w=[500,1000,1500,2000,2500] i=0 result=0 y=input().split() result=result+100*int(y[0]) result=result-50*int(y[1]) while i<5: c=0.3*w[i] d=(1-int(a[0][i])/250)*w[i]-50*int(a[1][i]) result=result+max(c,d) i=i+1 ...
MatrixStudio/Codeforces-Python-Submissions
Stepan had a favorite string *s* which consisted of the lowercase letters of the Latin alphabet. After graduation, he decided to remember it, but it was a long time ago, so he can't now remember it. But Stepan remembers some information about the string, namely the sequence of integers *c*1,<=*c*2,<=...,<=*c**n*, whe...
```python print("_RANDOM_GUESS_1689255733.378918")# 1689255733.378931 ```
MatrixStudio/Codeforces-Python-Submissions
Alice and Bob like games. And now they are ready to start a new game. They have placed *n* chocolate bars in a line. Alice starts to eat chocolate bars one by one from left to right, and Bob — from right to left. For each chocololate bar the time, needed for the player to consume it, is known (Alice and Bob eat them wi...
```python n = int(input()) arr = list(map(int, input().split())) left = 0 right = n - 1 alice = arr[left] bob = arr[right] while left < right: if alice - bob > 0: if (right - 1) == left: break right -= 1 bob += arr[right] elif alice - bob < 0: if (...
MatrixStudio/Codeforces-Python-Submissions
Gerald has *n* younger brothers and their number happens to be even. One day he bought *n*2 candy bags. One bag has one candy, one bag has two candies, one bag has three candies and so on. In fact, for each integer *k* from 1 to *n*2 he has exactly one bag with *k* candies. Help him give *n* bags of candies to each b...
```python a=int(input()) for i in range(a): b=[] for j in range(a): b+=[a*j+(j+i)%a+1] print(' '.join(map(str,b))) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya decided to write an anonymous letter cutting the letters out of a newspaper heading. He knows heading *s*1 and text *s*2 that he wants to send. Vasya can use every single heading letter no more than once. Vasya doesn't have to cut the spaces out of the heading — he just leaves some blank space to mark them. Help ...
```python import sys input = sys.stdin.readline t = input().split() s = input().split() d1 = {chr(i + ord('a')) : 0 for i in range(26)} d2 = {chr(i + ord('A')) : 0 for i in range(26)} d2.update(d1) for i in t: for j in i: d2[j] += 1 for i in s: for j in i: d2[j] -= 1 for i in d2....
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 def solution(): n,m = map(int, input().split()) arr = list(map(int, input().split())) _set = set() for i in range(len(arr))[::-1]: _set.add(arr[i]) arr[i] = len(_set) for _ in range(m): val = int(input()) print(arr[val - 1]) def main(): t = 1 ...
MatrixStudio/Codeforces-Python-Submissions
A sequence *a*0,<=*a*1,<=...,<=*a**t*<=-<=1 is called increasing if *a**i*<=-<=1<=&lt;<=*a**i* for each *i*:<=0<=&lt;<=*i*<=&lt;<=*t*. You are given a sequence *b*0,<=*b*1,<=...,<=*b**n*<=-<=1 and a positive integer *d*. In each move you may choose one element of the given sequence and add *d* to it. What is the least...
```python n,d=[int(e) for e in input().split()] a=[int(e) for e in input().split()] c=0 for i in range(1,n): x=a[i]-a[i-1] if x%d==0: x=x//d+1 else: x=(x+d-1)//d a[i]+=d*x c+=x print(c) ```
MatrixStudio/Codeforces-Python-Submissions
Today is birthday of a Little Dasha — she is now 8 years old! On this occasion, each of her *n* friends and relatives gave her a ribbon with a greeting written on it, and, as it turned out, all the greetings are different. Dasha gathered all the ribbons and decided to throw away some of them in order to make the remain...
```python print("_RANDOM_GUESS_1689182512.488632")# 1689182512.4886642 ```
MatrixStudio/Codeforces-Python-Submissions
Now it's time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. They've been best friends ever since primary school and hopefully, that can somehow help them in teamwork. For each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing ...
```python z,o = list(map(int,input().split())) if(o<z): print(-1) else: cards=[] while(z!=0): cards.append("1") cards.append("0") o-=1 z-=1 if(o==2): cards.append("1") cards.append("1") print("".join(cards)) elif(o==1): c...
MatrixStudio/Codeforces-Python-Submissions
Kolya is going to make fresh orange juice. He has *n* oranges of sizes *a*1,<=*a*2,<=...,<=*a**n*. Kolya will put them in the juicer in the fixed order, starting with orange of size *a*1, then orange of size *a*2 and so on. To be put in the juicer the orange must have size not exceeding *b*, so if Kolya sees an orange ...
```python n, b, d = map(int, input().split()) lst = [int(i) for i in input().split()] c, h = 0, 0 for i in lst: if i <= b: c += i if c > d: h += 1 c = 0 print(h) ```
MatrixStudio/Codeforces-Python-Submissions
You are given a string *s* consisting of lowercase Latin letters. Character *c* is called *k*-dominant iff each substring of *s* with length at least *k* contains this character *c*. You have to find minimum *k* such that there exists at least one *k*-dominant character.
```python s=input() alpha=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] ans=1000000 for i in alpha: occ=[] for j in range(len(s)): if(s[j]==i): occ.append(j) occ.append(len(s)) diff=[] st=0 # print(occ) for k in occ: diff.append(k-...
MatrixStudio/Codeforces-Python-Submissions
In this problem you will have to help Berland army with organizing their command delivery system. There are $n$ officers in Berland army. The first officer is the commander of the army, and he does not have any superiors. Every other officer has exactly one direct superior. If officer $a$ is the direct superior of off...
```python import sys input = sys.stdin.readline n, q = map(int, input().split()) d = [[] for _ in range(n+1)] for i, j in enumerate(map(int, input().split())): d[i+2].append(j) d[j].append(i+2) for i in d: i.sort() q = [(0, 1, -1)] x = [0]*(n+1) z = [] while q: a, b, c = q.pop() if a...
MatrixStudio/Codeforces-Python-Submissions
Dreamoon loves summing up something for no reason. One day he obtains two integers *a* and *b* occasionally. He wants to calculate the sum of all nice integers. Positive integer *x* is called nice if and , where *k* is some integer number in range [1,<=*a*]. By we denote the quotient of integer division of *x* and *...
```python s=raw_input().split() a,b=(int)(s[0]),(int)(s[1]) x=0 for k in range(1,a+1): x=x+k*b+1 xx=0 for t in range(1,b+1): xx=xx+i print((xx*x)%1000000007) ```
MatrixStudio/Codeforces-Python-Submissions
You are given a string $s$ consisting of $n$ lowercase Latin letters. Polycarp wants to remove exactly $k$ characters ($k \le n$) from the string $s$. Polycarp uses the following algorithm $k$ times: - if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next ite...
```python n,k=map(int,input().split()) l=list(input()) p=l.copy() l.sort() cnt=[0]*26 l2=[] for i in range(k): l2.append(l[i]) for x in l2: cnt[ord(x)-97]+=1 print(cnt) cnt2=[0]*26 ans=[] for x in p: if cnt[ord(x)-97]: cnt[ord(x)-97]-=1 else: ans.append(x) ans="...
MatrixStudio/Codeforces-Python-Submissions
Now it's time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. They've been best friends ever since primary school and hopefully, that can somehow help them in teamwork. For each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing ...
```python import math as mt import collections as cc def ncr(n,r): import math as mt return (mt.factorial(n)//((mt.factorial(n-r))*(mt.factorial(r)))) I=lambda:list(map(int,input().split())) n,m=I() if m>n*2+2: print(-1) elif n>m+1: print(-1) else: new='' if n<m: while m: ...
MatrixStudio/Codeforces-Python-Submissions
Kolya Gerasimov loves kefir very much. He lives in year 1984 and knows all the details of buying this delicious drink. One day, as you probably know, he found himself in year 2084, and buying kefir there is much more complicated. Kolya is hungry, so he went to the nearest milk shop. In 2084 you may buy kefir in a plas...
```python s = int(input()) a = int(input()) b = int(input()) c = int(input()) d = b-c l = 0 if d < a: l = s-b // d s -= l * d else: l = s // a s -= l * a m = min(a,b) if s >= m: l += 1 print(l) ```
MatrixStudio/Codeforces-Python-Submissions
Petya is a big fan of mathematics, especially its part related to fractions. Recently he learned that a fraction is called proper iff its numerator is smaller than its denominator (*a*<=&lt;<=*b*) and that the fraction is called irreducible if its numerator and its denominator are coprime (they do not have positive co...
```python upper=int(input()) emp=[1] temp=[] for num in range(1, upper + 1): if num > 1: for i in range(2, num): if (num % i) == 0: break else: emp.append(num) for j in range(len(emp)): if upper-emp[j] in emp and emp[j]<upper-emp[j]: temp.app...
MatrixStudio/Codeforces-Python-Submissions
Vasya lives in a strange world. The year has *n* months and the *i*-th month has *a**i* days. Vasya got a New Year present — the clock that shows not only the time, but also the date. The clock's face can display any number from 1 to *d*. It is guaranteed that *a**i*<=≤<=*d* for all *i* from 1 to *n*. The clock does n...
```python d=int(input()) n=int(input()) count=0 arr=[int(x) for x in input().split()] for i in range(n-1): if d>arr[i]: count+=d-arr[i] print(count) ```
MatrixStudio/Codeforces-Python-Submissions
You have a Petri dish with bacteria and you are preparing to dive into the harsh micro-world. But, unfortunately, you don't have any microscope nearby, so you can't watch them. You know that you have $n$ bacteria in the Petri dish and size of the $i$-th bacteria is $a_i$. Also you know intergalactic positive integer c...
```python import math as ma n,k=map(int,input().split()) a=list(map(int,input().split())) a.sort() c=0 ll=len(a) #print(*a) for i in range(len(a)): if(a[i+1]>a[i] and (a[i]+k)>=a[i+1]): c+=1 print(ll-c) ```
MatrixStudio/Codeforces-Python-Submissions
Top-model Izabella participates in the competition. She wants to impress judges and show her mathematical skills. Her problem is following: for given string, consisting of only 0 and 1, tell if it's possible to remove some digits in such a way, that remaining number is a representation of some positive integer, divisi...
```python a=input() if a.count('0')>=6 and a.count('1')>=1: print('yes') else: print('no') ```
MatrixStudio/Codeforces-Python-Submissions
Gerald bought two very rare paintings at the Sotheby's auction and he now wants to hang them on the wall. For that he bought a special board to attach it to the wall and place the paintings on the board. The board has shape of an *a*1<=×<=*b*1 rectangle, the paintings have shape of a *a*2<=×<=*b*2 and *a*3<=×<=*b*3 rec...
```python a1, b1 = map(int, input().split()) a2, b2 = map(int, input().split()) a3, b3 = map(int, input().split()) def f(a, b, c, d): if a + c <= a1 and max(b, d) <= b1: print("YES") exit(0) for _ in range(2): f(a2, b2, a3, b3) f(b2, a2, a3, b3) f(a2, b2, b3, a3) f(b2, a2, b3, a3) ...
MatrixStudio/Codeforces-Python-Submissions
Levko loves tables that consist of *n* rows and *n* columns very much. He especially loves beautiful tables. A table is beautiful to Levko if the sum of elements in each row and column of the table equals *k*. Unfortunately, he doesn't know any such table. Your task is to help him to find at least one of them.
```python n,k = map(int,input().split()) T = [[0 for i in range(n)] for j in range(n)] for i in range(n): T[i][i] = k for i in T: for j in i: print(j ,end = ' ') print() ```
MatrixStudio/Codeforces-Python-Submissions
Petya is a big fan of mathematics, especially its part related to fractions. Recently he learned that a fraction is called proper iff its numerator is smaller than its denominator (*a*<=&lt;<=*b*) and that the fraction is called irreducible if its numerator and its denominator are coprime (they do not have positive co...
```python n=int(input()) if n%2: print(n//2,n//2 + 1) elif n%4==0: print(n//2 -1 ,n//2 + 1) else: print(n//2 -2 ,n//2 + 2) ```
MatrixStudio/Codeforces-Python-Submissions
Yaroslav has an array that consists of *n* integers. In one second Yaroslav can swap two neighboring array elements. Now Yaroslav is wondering if he can obtain an array where any two neighboring elements would be distinct in a finite time. Help Yaroslav.
```python from collections import Counter n=int(input()) arr=list(map(int,input().split())) #n<2*count or n+1>=2*count print("YES" if all([arr.count(i)*2-1<=n for i in arr]) else "NO") ```
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 #include<bits/stdc++.h> using namespace std; #define ll long long #define endl '\n' #define debug(n) cout<<(n)<<endl; const ll INF = 2e18 + 99; int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); ll n, m, a; cin>>n>>m>>a; ll c = (m % a == 0) ? (m / a) : (m / a + 1); ll d = (n % a == 0...
MatrixStudio/Codeforces-Python-Submissions
This winter is so cold in Nvodsk! A group of *n* friends decided to buy *k* bottles of a soft drink called "Take-It-Light" to warm up a bit. Each bottle has *l* milliliters of the drink. Also they bought *c* limes and cut each of them into *d* slices. After that they found *p* grams of salt. To make a toast, each frie...
```python n,k,l,c,d,p,nl,np=map(int,input().split()) r1=(k*l)//nl r2=(c*d) r3=p//np r=[r1,r2,r3] r.sort() res=r[0] print(res//n) ```
MatrixStudio/Codeforces-Python-Submissions
DZY loves chessboard, and he enjoys playing with it. He has a chessboard of *n* rows and *m* columns. Some cells of the chessboard are bad, others are good. For every good cell, DZY wants to put a chessman on it. Each chessman is either white or black. After putting all chessmen, DZY wants that no two chessmen with th...
```python n, m = map(int, input().split()) board = [] for i in range(n): board.append(list(input())) def writeNbr(i, j): if j + 1 < m: if board[i][j + 1] == '.': board[i][j + 1] = 'B' if i + 1 < n: if board[i+1][j] == '.': board[i+1][j] = 'B' for i in r...
MatrixStudio/Codeforces-Python-Submissions
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth. Now Diamond has given Bort a string consisting of only uppercase English letters of length *n*. There is a great number of "QAQ" in the string (Diamond is so cute!). Bort wants to know how many subsequences "QAQ" are...
```python s = input() Q, A = 0, 0 for i in range(len(s)): if s[i] == "Q": Q += 1 elif s[i] == "A": A += 1 print((Q - 1) * A) ```
MatrixStudio/Codeforces-Python-Submissions
Once Bob took a paper stripe of *n* squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into two pieces so that the sum of numbers from one piece is equal to the sum of numbers from the other piece, ...
```python n=int(input()) arr=list(map(int,input().split())) cums=sum(arr) c=0 x=0 for i in range(n-1): x+=arr[i] if x==cums-x: c+=1 print(c) ```
MatrixStudio/Codeforces-Python-Submissions
You have decided to watch the best moments of some movie. There are two buttons on your player: 1. Watch the current minute of the movie. By pressing this button, you watch the current minute of the movie and the player automatically proceeds to the next minute of the movie. 1. Skip exactly *x* minutes of the movie...
```python from math import * #from math import comb as nCr import sys from sys import * def gI(): return map(int, sys.stdin.readline().strip().split()) def gL(): return list(map(int, sys.stdin.readline().strip().split())) t=stdin.readline p=stdout.write ''' for _ in range(int(t())): n=int(t()) a,b=gI...
MatrixStudio/Codeforces-Python-Submissions
This is an interactive problem. Refer to the Interaction section below for better understanding. Ithea and Chtholly want to play a game in order to determine who can use the kitchen tonight. Initially, Ithea puts *n* clear sheets of paper in a line. They are numbered from 1 to *n* from left to right. This game wil...
```python import sys N, M, C = map(int,input().split()) ans = [0] * (N+1) # ls, le = 1, N+1 # rs, re = N//2+1, N+1 for _ in range(M): p = int(input()) ii = -1 if p < C//2+1: for i in range(1, N+1): if ans[i] == 0 or ans[i] > p: ii = i break ...
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()) upper_sum = 0 # Sum of numbers on upper halves lower_sum = 0 # Sum of numbers on lower halves odd_upper = 0 # Count of odd numbers on upper halves odd_lower = 0 # Count of odd numbers on lower halves for _ in range(n): x, y = map(int, input().split()) upper_sum += x ...
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 def dfs(x, n = 0, m = -1): color[x] = n print(x, n, m) for i in A[x] - set([m]): dfs(i, n + 1, x) n = int(input()) A = [set() for i in range(n)] for i in range(n): if (a:=int(input())) != -1: A[a - 1].add(i) #print(A) color, ind = [-1 for i in range(n)], 0 while -1 in co...
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 # import sys # sys.stdin = open("309_Div2_ProbC.txt") n = (int(input())) binomial = [[0 for x in range(1010)] for x in range(1010)] binomial[0][0] = 1 i = 1 row = len(binomial) col = len(binomial[0]) while i< row: binomial[i][0] = 1 i+=1 mod = int(1e9+7) i =1 while i< row: j=1 while j<...
MatrixStudio/Codeforces-Python-Submissions
The Cartesian coordinate system is set in the sky. There you can see *n* stars, the *i*-th has coordinates (*x**i*, *y**i*), a maximum brightness *c*, equal for all stars, and an initial brightness *s**i* (0<=≤<=*s**i*<=≤<=*c*). Over time the stars twinkle. At moment 0 the *i*-th star has brightness *s**i*. Let at mom...
```python # cook your dish here import string class solutions(): def __init__(self, n, c, stars): self.n = n self.c = c self.stars = stars def answer(self, Q): t, x1, y1, x2, y2 = Q Sum = 0 for i in range(len(self.stars)): x,y,s = self.sta...
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 def can_say_hello(s): target_word = "hello" target_index = 0 for char in s: if char == target_word[target_index]: target_index += 1 if target_index == len(target_word): return "YES" return "NO" # Read input s = input().strip() # Chec...
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 ''' Online Python Compiler. Code, Compile, Run and Debug python program online. Write your code in this editor and press "Run" button to execute it. ''' n = input() s=input() def rev(s): return s[::-1] st=n.lower() st1=s.lower() if st==st1: print("YES",en...
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 # -*- coding: utf-8 -*- """ Created on Wed Oct 25 13:26:04 2023 @author: 2000016913 """ for _ in range(int(input())): flag=False n=int(input()) l=list(map(int, input().split())) for i in range(n): if flag: break for j in range(i+1,n): ma...
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()) dct=dict() for i in range(m): a,b=input().split() dct[a]=b for i in input().split(): print([i,dct[i]][len(i)>len(dct[i])], end=" ") ```
MatrixStudio/Codeforces-Python-Submissions
For a given positive integer *n* denote its *k*-rounding as the minimum positive integer *x*, such that *x* ends with *k* or more zeros in base 10 and is divisible by *n*. For example, 4-rounding of 375 is 375·80<==<=30000. 30000 is the minimum integer such that it ends with 4 or more zeros and is divisible by 375. W...
```python n, k = map(int, input().split()) s = 10 ** k for d in [2, 5]: while n % d == s % d == 0: n //= d s //= d print(s) ```
MatrixStudio/Codeforces-Python-Submissions
You are given a tetrahedron. Let's mark its vertices with letters *A*, *B*, *C* and *D* correspondingly. An ant is standing in the vertex *D* of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. ...
```python x=int(input()) ans=[] ans.append(3) x-=2 while x!=0: ans.reverse() ans.append(ans[0]*2) x-=1 print(sum(ans)) ```
MatrixStudio/Codeforces-Python-Submissions
Theatre Square in the capital city of Berland has a rectangular shape with the size *n*<=×<=*m* meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size *a*<=×<=*a*. What is the least number of flagstones needed to pave the...
```python import math p, q, a = map(int, input().split()) horizontal = math.ceil(p / a) vertical = math.ceil(q / a) total = horizontal * vertical print(total) ```
MatrixStudio/Codeforces-Python-Submissions
Valera has array *a*, consisting of *n* integers *a*0,<=*a*1,<=...,<=*a**n*<=-<=1, and function *f*(*x*), taking an integer from 0 to 2*n*<=-<=1 as its single argument. Value *f*(*x*) is calculated by formula , where value *bit*(*i*) equals one if the binary representation of number *x* contains a 1 on the *i*-th posit...
```python n=int(input()) arr=list(map(int,input().split())) s=input()[::] sum=sum(arr) sum2=0 flag=0 for i in range(n): sum2+=int(s[i])*arr[i] ans=0 for i in range(n-1,-1,-1): sum-=arr[i] if int(s[i])==1: sum2-arr[i] if sum>=arr[i]+sum2: print(ans+sum) ...
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 t=int(input()) l=list(map(int,input().split())) p=[] m=min(l) for i in range(t): if(l[i]==m): p.append(i) m=p[1]-p[0] j=1 while(j<len(p)-1): if(p[j+1]-p[j]<m): m=p[j+1]-p[j] j+=1 print(m) ```
MatrixStudio/Codeforces-Python-Submissions
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr...
```python a=list(input()) b=list(input()) a.sort() b.sort() if (a>b): print(1) if (b>a): print(-1) else: print(0) ```
MatrixStudio/Codeforces-Python-Submissions
Kirill plays a new computer game. He came to the potion store where he can buy any potion. Each potion is characterized by two integers — amount of experience and cost. The efficiency of a potion is the ratio of the amount of experience to the cost. Efficiency may be a non-integer number. For each two integer numbers ...
```python l,r,x,y,k=[int(x) for x in input().split()] f=l/x s=r/y t=l/y f=r/x if((f<=k<=s) or (s<=k<=f) or (t<=k<=f)or(f<=k<=t)): print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything. During an audit, you were surprised to find out that the...
```python n = int(input()) a = [int(i) for i in input().split(' ')] m = {} for i in range(1, 100001): m[i] = [] zeroIndexes = [] for i in range(n): m[a[i]].append(i) for i in range(1, n+1): if len(m[i])==0: zeroIndexes.append(i) for i in range(1, 100001): if len(m[i])<2...
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 t=int(input()) L=[int(i) for i in input().split()] D={} first1=-1 first2=-1 for i in range(len(L)): if L[i]%2==0: if first2==-1: first2=i else: if first1==-1: first1=i c=0 for i in range(3): if(L[i]%2==0): c+=1; if c>=2: print(fi...
MatrixStudio/Codeforces-Python-Submissions
Greatest common divisor *GCD*(*a*,<=*b*) of two positive integers *a* and *b* is equal to the biggest integer *d* such that both integers *a* and *b* are divisible by *d*. There are many efficient algorithms to find greatest common divisor *GCD*(*a*,<=*b*), for example, Euclid algorithm. Formally, find the biggest in...
```python words = input().split() a = int(words[0]) b = int(words[1]) if a == b: print(a) else: print(1) ```
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 a =input () number = len(a) af=str(a) small = 0 for y in range (number) : if a[y] >= 'a': small += 1 if (small >= number/2): print (af.lower()) else: print (af.upper ()) ```
MatrixStudio/Codeforces-Python-Submissions
Bizon the Champion is called the Champion for a reason. Bizon the Champion has recently got a present — a new glass cupboard with *n* shelves and he decided to put all his presents there. All the presents can be divided into two types: medals and cups. Bizon the Champion has *a*1 first prize cups, *a*2 second prize c...
```python from math import ceil a1, a2, a3=map(int, input().split()) b1, b2, b3=map(int, input().split()) n= int(input()) if n>= ceil((a1+a2+a3)/5)+ceil((b1+b2+b3)/10): print('YES') else: print('NO') ```
MatrixStudio/Codeforces-Python-Submissions
A magic number is a number formed by concatenation of numbers 1, 14 and 144. We can use each of these numbers any number of times. Therefore 14144, 141414 and 1411 are magic numbers but 1444, 514 and 414 are not. You're given a number. Determine if it is a magic number or not.
```python s = input() if len(set(s)) <= 2 and "1" in s or "4" in s: if s[0] != "1": print("NO") elif s.find("444") != -1: print("NO") else: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word *s*. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, ...
```python a=input() true=0 if "h" in a: c="" c=c+a[a.index("l")+1:len(a)] if "e" in c: d="" d=d+c[c.index("l")+1:len(c)] if "l" in d: e="" e=e+d[d.index("l")+1:len(d)] if "l" in e: f="" f=f+e[e.index("l"...