source
stringclasses
3 values
instruction
stringlengths
23
3.97k
input
stringclasses
1 value
output
stringlengths
1
3.75k
MatrixStudio/Codeforces-Python-Submissions
In the school computer room there are *n* servers which are responsible for processing several computing tasks. You know the number of scheduled tasks for each server: there are *m**i* tasks assigned to the *i*-th server. In order to balance the load for each server, you want to reassign some tasks to make the differe...
```python num_servers=int(input()) loads=list(map(int,input().split())) loads.sort() lp=0 rp=len(loads)-1 count=0 while lp<=rp: count+=(loads[rp]-loads[lp])//2 lp+=1 rp-=1 print(count) ```
MatrixStudio/Codeforces-Python-Submissions
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d...
```python num = input() if any(char in num for char in "12356890"): print("NO") else: if len(num) == 7 or len(num) == 4: print("YES") else: print("NO") ```
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()) l1 = set([i for i in range(0,d,k)]) l2 = set([i for i in range(0,d,l)]) l3 = set([i for i in range(0,d,m)]) l4 = set([i for i in range(0,d,n)]) l1.union(l2) l1.union(l3) l1.union(l4) print(len(l1)) ```
MatrixStudio/Codeforces-Python-Submissions
There are *n* servers in a laboratory, each of them can perform tasks. Each server has a unique id — integer from 1 to *n*. It is known that during the day *q* tasks will come, the *i*-th of them is characterized with three integers: *t**i* — the moment in seconds in which the task will come, *k**i* — the number of se...
```python rlist = lambda: list(map(int, input().split())) N, Q = rlist() free = [0] * N for qi in range(Q): t, k, d = rlist() # t : time when job comes # k : number of servers # d : duration [t...t+d-1] cand = [] for i in range(N): if free[i] <= t: cand.append(i)...
MatrixStudio/Codeforces-Python-Submissions
You are given *n* points on the straight line — the positions (*x*-coordinates) of the cities and *m* points on the same line — the positions (*x*-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than ...
```python import sys import math # Fast input # Fast output def print(*args, **kwargs): sep = kwargs.get('sep', ' ') end = kwargs.get('end', '\n') file = kwargs.get('file', sys.stdout) flush = kwargs.get('flush', False) output = sep.join(map(str, args)) + end file.write(output) ...
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 a = 0 b = 0 l = 0 s = "" n = int(input()) for i in range (n): t = input() s = s + t a = a + t.count("A") b = b + t.count("B") l = l + len(t) if a + b == l and a != b: if b > a: print("B") else: print("A") else: print(s) ```
MatrixStudio/Codeforces-Python-Submissions
Polycarpus is a system administrator. There are two servers under his strict guidance — *a* and *b*. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a progra...
```python # import sys # sys.stdin=open("test11.in","r") # sys.stdout=open("test11.out","w") n=int(input()) a=0 b=0 for i in range(n): l=list(map(int,input().split())) if(l[1]>=5): if(l[0]==1): a=1 elif(l[0]==2): b=1 else: if(l[0]==1): a=1 elif(l[0]==2): b=1 if(a==1): print(...
MatrixStudio/Codeforces-Python-Submissions
The king is left alone on the chessboard. In spite of this loneliness, he doesn't lose heart, because he has business of national importance. For example, he has to pay an official visit to square *t*. As the king is not in habit of wasting his time, he wants to get from his current position *s* to square *t* in the le...
```python s=input() n=input() if s==n: print(0) exit() m=['','a','b','c','d','e','f','g','h'] for i in range(1,len(m)): if s[0]==m[i]: x=i if n[0]==m[i]: x2=i y=int(s[1]) y2=int(n[1]) M=[] b='' xod=0 while True: if x>x2: x-=1 b+='L' ...
MatrixStudio/Codeforces-Python-Submissions
You are at a water bowling training. There are *l* people who play with their left hand, *r* people, who play with their right hand, and *a* ambidexters, who can play with left or right hand. The coach decided to form a team of even number of players, exactly half of the players should play with their right hand, and ...
```python string=input() la=list(map(int,string.split())) l=la[0] r=la[1] a=la[2] while(a>0): if r<l: r+=1 else: l+=1 a-=1 if r<l: print(2*r) else: print(2*l) ```
MatrixStudio/Codeforces-Python-Submissions
Unlucky year in Berland is such a year that its number *n* can be represented as *n*<==<=*x**a*<=+<=*y**b*, where *a* and *b* are non-negative integer numbers. For example, if *x*<==<=2 and *y*<==<=3 then the years 4 and 17 are unlucky (4<==<=20<=+<=31, 17<==<=23<=+<=32<==<=24<=+<=30) and year 18 isn't unlucky as the...
```python x, y, l, r = map(int, input().split()) a=1 b=1 arr=[] ans=0 while a<=r*x: b=1 while b<=r*y: arr.append(a+b) b=b*y a=a*x arr.append(l-1) arr.append(r+1) arr.sort() for z in range(1, len(arr)) : if arr[z]<=r+1 : if arr[z]-arr[z-1]-1>ans : ans=...
MatrixStudio/Codeforces-Python-Submissions
Buses run between the cities *A* and *B*, the first one is at 05:00 AM and the last one departs not later than at 11:59 PM. A bus from the city *A* departs every *a* minutes and arrives to the city *B* in a *t**a* minutes, and a bus from the city *B* departs every *b* minutes and arrives to the city *A* in a *t**b* min...
```python import math a, ta = map(int, input().split()) b, tb = map(int, input().split()) h, m = map(int, input().split(':')) x=60*h+m print(min(math.floor(1139/b), math.floor((x+ta-300-1)/b)) - max(0, math.ceil((x-tb-300+1)/b)) + 1) ```
MatrixStudio/Codeforces-Python-Submissions
«Polygon» is a system which allows to create programming tasks in a simple and professional way. When you add a test to the problem, the corresponding form asks you for the test index. As in most cases it is clear which index the next test will have, the system suggests the default value of the index. It is calculated ...
```python t = int(input()) L = set([int(x) for x in input().split()]) for i in range(1, 3050): if i not in L: print(i) break ```
MatrixStudio/Codeforces-Python-Submissions
Yaroslav has an array, consisting of (2·*n*<=-<=1) integers. In a single operation Yaroslav can change the sign of exactly *n* elements in the array. In other words, in one operation Yaroslav can select exactly *n* array elements, and multiply each of them by -1. Yaroslav is now wondering: what maximum sum of array el...
```python n = int(input()) a = list(map(int, input().split())) b = 0 for i in a: if i < 0: b += 1 b = min(b, b % n) c = sorted(map(abs, a)) print(sum(a[2 * n - 1 - b:]) - sum(a[:2 * n - 1 - b])) ```
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 from collections import Counter n = input() counts = Counter(map(int, input().split())) score = 0 def count_total_value(i): plus = counts.get(i + 1, 0) * (i + 1) minus = counts.get(i - 1, 0) * (i - 1) val = counts.get(i) * i - (plus + minus) return val while counts: ...
MatrixStudio/Codeforces-Python-Submissions
Bachgold problem is very easy to formulate. Given a positive integer *n* represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1. Recall that integer *k* is called prime if it is greater than 1 and has exactly two positive integer ...
```python total = 0 num = int(input()) if num%2 == 0: print(int(num/2)) print('2 '*(int(num/2))) else: print(int(num//2)) print('2 '*(int(num/2)-1)+'3') ```
MatrixStudio/Codeforces-Python-Submissions
Jeff's got *n* cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got? Jeff must make the number without leading zero. At that, we assume that numbe...
```python n = int(input()) arr = [int(x) for x in input().split()] count5 = arr.count(5) count0 = arr.count(0) num = int(count5/9) number = "5"*(num*9) + "0"*(count0) if(int(number) == 0): print(0) else: print(number) ```
MatrixStudio/Codeforces-Python-Submissions
Vitaly is a diligent student who never missed a lesson in his five years of studying in the university. He always does his homework on time and passes his exams in time. During the last lesson the teacher has provided two strings *s* and *t* to Vitaly. The strings have the same length, they consist of lowercase Engli...
```python """ Link: https://codeforces.com/contest/518/problem/A Time complexity: O(n) Space complexity: O(1) """ def gen_next_string(): first_text = input() second_text = input() result = '' carry = 1 for i in range(len(first_text) - 1, -1, -1): if carry: if firs...
MatrixStudio/Codeforces-Python-Submissions
Eugeny has array *a*<==<=*a*1,<=*a*2,<=...,<=*a**n*, consisting of *n* integers. Each integer *a**i* equals to -1, or to 1. Also, he has *m* queries: - Query number *i* is given as a pair of integers *l**i*, *r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*). - The response to the query will be integer 1, if the elements of a...
```python n,m=[int(i) for i in input().split()] a=[int(i) for i in input().split()] e=a.count(1) f=a.count(-1) for i in range(m): b,c=[int(i) for i in input().split()] z=(c-b)+1 if(z%2!=0): print(0) else: if((e+f)>=z): print(1) else: print(0) ...
MatrixStudio/Codeforces-Python-Submissions
Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev decided to build a house of cards. For that they've already found a hefty deck of *n* playing cards. Let's describe the house they want to make: 1. The house consists of some non-zero number of floors. 1. Each f...
```python import sys import time import math from collections import defaultdict from functools import lru_cache INF = 10 ** 18 + 3 EPS = 1e-10 MAX_CACHE = 10 ** 12 def time_it(function, output=sys.stderr): def wrapped(*args, **kwargs): start = time.time() res = function(*args, **kwargs) ...
MatrixStudio/Codeforces-Python-Submissions
Bessie and the cows are playing with sequences and need your help. They start with a sequence, initially containing just the number 0, and perform *n* operations. Each operation is one of the following: 1. Add the integer *x**i* to the first *a**i* elements of the sequence. 1. Append an integer *k**i* to the end of ...
```python import sys from functools import lru_cache, cmp_to_key from heapq import merge, heapify, heappop, heappush # from math import * from collections import defaultdict as dd, deque, Counter as C from itertools import combinations as comb, permutations as perm from bisect import bisect_left as bl, bisect_rig...
MatrixStudio/Codeforces-Python-Submissions
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most *d* centimeters. Captain Bob has *n* soldiers in his detachment. Their heights are *a*1,<=*a*2,<=...,<=*a**n* centimeters. Som...
```python n,d=map(int,input().split()) a=list(map(int,input().split())) a.sort() c=0 for i in range(0,n): for j in range(i+1,n): if a[j]-a[i]<=d: c+=1 print(2*c) ```
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 = input().split(" ") num1 = int(a[0]) num2 = int(a[1]) b = (num1 * num2) // 2 print(b) ```
MatrixStudio/Codeforces-Python-Submissions
Some days ago, I learned the concept of LCM (least common multiple). I've played with it for several times and I want to make a big number with it. But I also don't want to use many numbers, so I'll choose three positive integers (they don't have to be distinct) which are not greater than *n*. Can you help me to find ...
```python #!/usr/bin/env python3 import collections, itertools, functools, math, fractions import operator def lcm(a, b): return (a*b)//fractions.gcd(a, b) def solve(n): if n <= 2: return n if n%2 == 1: return lcm(n, lcm(n-1, n-2)) offset = 100 if n-offset < 0: offset = n...
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 case = input() count =0 flag=0 for i in range(len(case)): if case[i]=='4': count+=1 bool=1 if count>2: print("NO") flag=1 break elif case[i]=='1': count = 0 bool=0 elif case[i]!= '1' and case[i]!='4': ...
MatrixStudio/Codeforces-Python-Submissions
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings. Hulk likes the Inception so much, and like that his feelings are complicated. They have *n* layers. The first layer is hate, se...
```python x=int(input()) c='I hate' for i in range(x-1): c+=' that' if i%2==0:c+=' I love' else:c+=' I hate' print(c+' it') ```
MatrixStudio/Codeforces-Python-Submissions
Some dwarves that are finishing the StUDY (State University for Dwarven Youngsters) Bachelor courses, have been told "no genome, no degree". That means that all dwarves should write a thesis on genome. Dwarven genome is far from simple. It is represented by a string that consists of lowercase Latin letters. Dwarf Mish...
```python a=input() b=input() a=list(a) b=list(b) first=-1 second=-1 lmn=0 for i in range(len(a)): if a[i]!=b[i]: if first==-1: first=i else: second=i a[first],a[second]=a[second],a[first] if a==b: lmn=1 ...
MatrixStudio/Codeforces-Python-Submissions
One day Vasya was sitting on a not so interesting Maths lesson and making an origami from a rectangular *a* mm <=×<= *b* mm sheet of paper (*a*<=&gt;<=*b*). Usually the first step in making an origami is making a square piece of paper from the rectangular sheet by folding the sheet along the bisector of the right angle...
```python a,b=[int(i) for i in input().split()] k=1 while a!=b: if a>b: a=a-b else: b=b-a k=k+1 print(k) ```
MatrixStudio/Codeforces-Python-Submissions
After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with *n* room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third ...
```python from collections import defaultdict input() s, keys, n = input().lower(), defaultdict(int), 0 for i, door in zip(s[::2], s[1::2]): keys[i] += 1 if keys[door]: keys[door] -= 1 else: n += 1 print(n) ```
MatrixStudio/Codeforces-Python-Submissions
You have probably registered on Internet sites many times. And each time you should enter your invented password. Usually the registration form automatically checks the password's crypt resistance. If the user's password isn't complex enough, a message is displayed. Today your task is to implement such an automatic che...
```python from fractions import gcd # from datetime import date, timedelta from heapq import* import math from collections import defaultdict, Counter, deque import sys from bisect import * import itertools import copy sys.setrecursionlimit(10 ** 7) MOD = 10 ** 9 + 7 # input = sys.stdin.readline def mai...
MatrixStudio/Codeforces-Python-Submissions
You are given a table consisting of *n* rows and *m* columns. Each cell of the table contains either 0 or 1. In one move, you are allowed to pick any row or any column and invert all values, that is, replace 0 by 1 and vice versa. What is the minimum number of cells with value 1 you can get after applying some number ...
```python print("_RANDOM_GUESS_1689338437.874004")# 1689338437.874017 ```
MatrixStudio/Codeforces-Python-Submissions
Petr stands in line of *n* people, but he doesn't know exactly which position he occupies. He can say that there are no less than *a* people standing in front of him and no more than *b* people standing behind him. Find the number of different positions Petr can occupy.
```python n,a,b = map(int, input().split()) print (n-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 def verif (ch,ch1) : for i in range (len(ch)) : if ch[i]!=ch1[c-i] : return 'NO' return 'YES' ch=input() ch1=input() c=len (ch) -1 print(verif(ch,ch1)) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya wants to turn on Christmas lights consisting of *m* bulbs. Initially, all bulbs are turned off. There are *n* buttons, each of them is connected to some set of bulbs. Vasya can press any of these buttons. When the button is pressed, it turns on all the bulbs it's connected to. Can Vasya light up all the bulbs? I...
```python n=int((input().split())[0]) m=int((input().split())[1]) l=set() for x in range(n): q=input().split() l=l|set(q) if len(l)==m: print('YES') else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
One day Vasya came across three Berland coins. They didn't have any numbers that's why Vasya didn't understand how their denominations differ. He supposed that if one coin is heavier than the other one, then it should be worth more. Vasya weighed all the three pairs of coins on pan balance scales and told you the resul...
```python d={"A":[], "B":[], "C":[] } exp1=input() source,arrow,dest=[x for x in exp1] if arrow==">": d[source].append(dest) else: d[dest].append(source) exp2=input() source,arrow,dest=[x for x in exp2] if arrow==">": d[source].append(dest) else: d[dest].append(source) exp3=inp...
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 n = int(input()) mod = 1e9+7 dp = [[0]*4 for i in range(n+1)] dp[0][3] = 1 for i in range(1, n+1): for u in range(4): for v in range(4): if u != v: dp[i][v] = (dp[i][v] + dp[i-1][u]) % mod print(int(dp[n][3])) ```
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 # cook your dish here def can_say_hello(word): target = "hello" i = 0 for char in word: if char == target[i]: i += 1 if i == len(target): return "YES" return "NO" word = input() result = can_say_hello(word) print(result) `...
MatrixStudio/Codeforces-Python-Submissions
We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer *t* Т-prime, if *t* has exactly three distinct positive divisors. You are given an array of *n* positive integers. For each of them determine whether it is Т-prime or not.
```python from math import sqrt n = int(input()) x = list(map(int, input().split())) N = max(x) primes = [i for i in range(N + 1)] primes[1] = 0 i = 2 while i <= N: if primes[i] != 0: j = i + i while j <= N: primes[j] = 0 j = j + i i += 1 primes = [i for i...
MatrixStudio/Codeforces-Python-Submissions
Once upon a time in the Kingdom of Far Far Away lived Sam the Farmer. Sam had a cow named Dawn and he was deeply attached to her. Sam would spend the whole summer stocking hay to feed Dawn in winter. Sam scythed hay and put it into haystack. As Sam was a bright farmer, he tried to make the process of storing hay simple...
```python n = int(input()) x = int(sqrt(n)) while n % x: x -= 1 def f(x, y): return (x + 2) * (y + 2) + (2 * (x + y + 2) * n) // (x * y) print(f(x, n // x), f(1, 1)) ```
MatrixStudio/Codeforces-Python-Submissions
One day Anna got the following task at school: to arrange several numbers in a circle so that any two neighboring numbers differs exactly by 1. Anna was given several numbers and arranged them in a circle to fulfill the task. Then she wanted to check if she had arranged the numbers correctly, but at this point her youn...
```python n=int(input()) a=sorted(list(map(int, input().split()))) b=[] numb=1 flag=True for i in range(1,n): q=1 if a[i]>a[i-1]: if a[i]-a[i-1]>1: flag=False break else: b.append(numb) q=0 numb=1 else: numb+...
MatrixStudio/Codeforces-Python-Submissions
In the evening, after the contest Ilya was bored, and he really felt like maximizing. He remembered that he had a set of *n* sticks and an instrument. Each stick is characterized by its length *l**i*. Ilya decided to make a rectangle from the sticks. And due to his whim, he decided to make rectangles in such a way tha...
```python m = {} n = int(input()) data = input().split() for i in data: if -int(i) not in m: m[-int(i)] = 1 else: m[-int(i)] += 1 ant = 0 ans = 0 for i in sorted(m): if m[i] > 1: if ant != 0: ans += ant * i m[i] -= 2 ans += (m[i]//4)*m[i] m[i] %= 4...
MatrixStudio/Codeforces-Python-Submissions
One day *n* friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other *n*<=-<=1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the *i*-th person wants to play *a**i* rounds. What is the min...
```python n=int(input()) a=[int(i) for i in input().split()] print(max(a)+1) ```
MatrixStudio/Codeforces-Python-Submissions
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them. A little later they found a string *s*, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the...
```python # Python program for KMP Algorithm def KMPSearch(pat, txt): M = len(pat) N = len(txt) # create lps[] that will hold the longest prefix suffix # values for pattern lps = [0]*M j = 0 # index for pat[] # Preprocess the pattern (calculate lps[] array) computeLPSAr...
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()) a=list(map(int,input().split())) police,crime=0,0 for i in a: if i!=-1: police+=i else: if police+i>=0: police =police-1 else: crime+=1 print(crime) ```
MatrixStudio/Codeforces-Python-Submissions
Eleven wants to choose a new name for herself. As a bunch of geeks, her friends suggested an algorithm to choose a name for her. Eleven wants her name to have exactly *n* characters. Her friend suggested that her name should only consist of uppercase and lowercase letters 'O'. More precisely, they suggested that the ...
```python import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,queue,copy sys.setrecursionlimit(10**7) inf=10**20 mod=10**9+7 dd=[(-1,0),(0,1),(1,0),(0,-1)] ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(): return [int(x) for x in sys.stdin.readline().split()] d...
MatrixStudio/Codeforces-Python-Submissions
A little bear Limak plays a game. He has five cards. There is one number written on each card. Each number is a positive integer. Limak can discard (throw out) some cards. His goal is to minimize the sum of numbers written on remaining (not discarded) cards. He is allowed to at most once discard two or three cards wi...
```python import bisect import collections import copy import functools import heapq import itertools import math import random import re import sys import time import string from typing import List sys.setrecursionlimit(99999) arr = list(map(int,input().split())) s = sum(arr) cs = collections.Counter...
MatrixStudio/Codeforces-Python-Submissions
When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their aver...
```python def solve(A, N): count = [] for i in range(100002): count.append(0) for i in range(N): A[i] = int(A[i]) count[A[0]] += 1 num = 1 L = 0 cnt = 0 for R in range(1, N): if (count[A[R]] == 0): num += 1 while (num > 2):...
MatrixStudio/Codeforces-Python-Submissions
The World Programming Olympics Medal is a metal disk, consisting of two parts: the first part is a ring with outer radius of *r*1 cm, inner radius of *r*2 cm, (0<=&lt;<=*r*2<=&lt;<=*r*1) made of metal with density *p*1 g/cm3. The second part is an inner disk with radius *r*2 cm, it is made of metal with density *p*2 g/...
```python n, *r1_arr = [int(x) for x in input().split()] m, *p1_arr = [int(x) for x in input().split()] k, *p2_arr = [int(x) for x in input().split()] A, B = [int(x) for x in input().split()] r1, p1, p2 = max(r1_arr), max(p1_arr), min(p2_arr) print(((p1 * B * (r1 ** 2)) / (p2 * A + p1 * B)) ** .5) ```
MatrixStudio/Codeforces-Python-Submissions
While Mike was walking in the subway, all the stuff in his back-bag dropped on the ground. There were several fax messages among them. He concatenated these strings in some order and now he has string *s*. He is not sure if this is his own back-bag or someone else's. He remembered that there were exactly *k* messages ...
```python def f(s,k): if len(s)%k == 0: k = len(s)//k for i in range(0,len(s),k): #print(s[i:i+k][::-1], s[i:i+k]) if s[i:i+k][::-1] != s[i:i+k]: return "NO" return "YES" return "NO" print(f(input(),int(input()))) ```
MatrixStudio/Codeforces-Python-Submissions
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated. The language is that peculiar as it has exactly one variable, called *x*. Also, there are two operations: - Operation ++ increases the value of variable *x* by 1. - Operation -- decreases the value of variable *x* by...
```python x = 0 n = int(input()) for i in range(0, n): i += 1 l = str.lower(input()) if (l == "--x" or l == "x--"): x -= 1 elif (l == "++x" or l == "x++"): x += 1 print(x) ```
MatrixStudio/Codeforces-Python-Submissions
In some game by Playrix it takes *t* minutes for an oven to bake *k* carrot cakes, all cakes are ready at the same moment *t* minutes after they started baking. Arkady needs at least *n* cakes to complete a task, but he currently don't have any. However, he has infinitely many ingredients and one oven. Moreover, Arkady...
```python if __name__ == '__main__': x = input().split(' ') number_of_wanted_cakes = int(x[0]) time_needed = int(x[1]) k_cakes = int(x[2]) time_new_oven = int(x[3]) temp_cakes = k_cakes temp_cakes_new_oven = k_cakes counter = 1 time_counter = time_needed while(temp_...
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()) l=[] for i in range(m): lst=list(map(str,input().split())) l.append(lst) res=[] res=list(map(str,input().split())) for i in range(n): for j in range(m): if(l[j][0]==res[i]): len1=len(l[j][0]) len2=len(l[j][1]) ...
MatrixStudio/Codeforces-Python-Submissions
Valera wanted to prepare a Codesecrof round. He's already got one problem and he wants to set a time limit (TL) on it. Valera has written *n* correct solutions. For each correct solution, he knows its running time (in seconds). Valera has also wrote *m* wrong solutions and for each wrong solution he knows its running ...
```python n, m = map(int, input().split()) correct = list(map(int, input().split())) wrong = list(map(int, input().split())) if min(wrong) <= max(correct) or min(wrong) <= 2 * min(correct): print(-1) else: print(max(2 * min(correct), max(correct))) ```
MatrixStudio/Codeforces-Python-Submissions
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most *d* centimeters. Captain Bob has *n* soldiers in his detachment. Their heights are *a*1,<=*a*2,<=...,<=*a**n* centimeters. Som...
```python #!/usr/bin/env python # coding=utf-8 ''' Author: Deean Date: 2021-11-05 22:41:04 LastEditTime: 2021-11-05 22:45:34 Description: Reconnaissance FilePath: CF32A.py ''' def func(): n, d = map(int, input().strip().split()) high = list(sorted(map(int, input().strip().split()))) count = 0 for i in...
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 def main(): L, R, X, Y, K = map(int, input().split()) for i in range(L, R + 1): div_, mod_ = divmod(i * K, 1) if mod_ == 0 and X <= div_ <= Y: ans = 'YES' break else: ans = 'NO' print(ans) main() ```
MatrixStudio/Codeforces-Python-Submissions
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
```python n = int(input()) for i in range(n): word = input() if len(word) > 10: print(word[0:1] + str((len(word) - 2)) + word[len(word)-1:len(word)]) else: print(word) ```
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 bruh = input().split() a = int(bruh[0]) b = int(bruh[1]) if a == b: print(a) else: print(1) ```
MatrixStudio/Codeforces-Python-Submissions
Imagine that there is a group of three friends: A, B and С. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The...
```python R = lambda: map(int, input().split()) n, m = R() p = [0] * n for i in range(m): a, b, c = R() p[a - 1] -= c p[b - 1] += c print(sum(i for i in p if i > 0)) ```
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 n = int(input()) #f=0; #for i in range(1,n): # for j in range(i+1,n): # if((i+j==n)and((i+j)%2==n)): # f=1 #if f==1: #print("YES") #else: #print("NO") if n==2: print("NO") elif n%2==0: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Some dwarves that are finishing the StUDY (State University for Dwarven Youngsters) Bachelor courses, have been told "no genome, no degree". That means that all dwarves should write a thesis on genome. Dwarven genome is far from simple. It is represented by a string that consists of lowercase Latin letters. Dwarf Mish...
```python a = input().lower() b = input().lower() c = 0 h = [] n = [] k = 0 for i in range(len(a)): if a[i] != b[i]: c += 1 if c > 2: k = 1 break h.append(a[i]) n.append(b[i]) h.sort() n.sort() if k == 1: print("NO") else: if h == n:...
MatrixStudio/Codeforces-Python-Submissions
String can be called correct if it consists of characters "0" and "1" and there are no redundant leading zeroes. Here are some examples: "0", "10", "1001". You are given a correct string *s*. You can perform two different operations on this string: 1. swap any pair of adjacent characters (for example, "101" "110"...
```python x=input();y=input() print('1'+y.count('0')*'0') #author:SK__Shanto__㋛ #code__define__your__smartness ```
MatrixStudio/Codeforces-Python-Submissions
Recently Luba bought a very interesting book. She knows that it will take *t* seconds to read the book. Luba wants to finish reading as fast as she can. But she has some work to do in each of *n* next days. The number of seconds that Luba has to spend working during *i*-th day is *a**i*. If some free time remains, she...
```python TIME_IN_A_DAY = 86400 n, t = map(int, input().split()) a = list(map(int, input().split())) for i in range(len(a)): if TIME_IN_A_DAY - a[i] >= t: print(i + 1) break t -= (TIME_IN_A_DAY - a[i]) ```
MatrixStudio/Codeforces-Python-Submissions
Petya and Vasya are playing a game. Petya's got *n* non-transparent glasses, standing in a row. The glasses' positions are indexed with integers from 1 to *n* from left to right. Note that the positions are indexed but the glasses are not. First Petya puts a marble under the glass in position *s*. Then he performs som...
```python n,s,t=map(int,input().split()) x=[int(q) for q in input().split()] if s==t: print(0) else: s-=1 t-=1 ans=0 f=False for i in range(len(x)): if x[i]-1==t: print(ans) f=True break elif x[i]-1==s and i!=0: pri...
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()) print(1,n-1) ```
MatrixStudio/Codeforces-Python-Submissions
Maxim wants to buy some games at the local game shop. There are $n$ games in the shop, the $i$-th game costs $c_i$. Maxim has a wallet which can be represented as an array of integers. His wallet contains $m$ bills, the $j$-th bill has value $a_j$. Games in the shop are ordered from left to right, Maxim tries to buy ...
```python n , m = map(int,input().split()) costs = list(map(int,input().split())) bills = list(map(int,input().split())) pos = 0 cnt = 0 for i in range(n): if bills[pos] >= costs[i]: pos += 1 cnt +=1 if pos == m : break print(cnt) ```
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 def main(): n = int(input()) M = 1000000007 zD = 1 zABC = 0 for i in range(1, n + 1): nzD = (zABC * 3) % M nzABC = (zABC * 2 + zD) % M zD = nzD zABC = nzABC print(zD) main() ```
MatrixStudio/Codeforces-Python-Submissions
Anton likes to play chess, and so does his friend Danik. Once they have played *n* games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie. Now Anton wonders, who won more games, he or Danik? Help him determine this.
```python n=int(input()) s=input() a=s.count('A') b=s.count('D') if(b>a):print('Danik') else:print('Anton') ```
MatrixStudio/Codeforces-Python-Submissions
Recently a serious bug has been found in the FOS code. The head of the F company wants to find the culprit and punish him. For that, he set up an organizational meeting, the issue is: who's bugged the code? Each of the *n* coders on the meeting said: 'I know for sure that either *x* or *y* did it!' The head of the com...
```python import itertools n, p = tuple(map(int, str.split(input()))) c = [0] * n for _ in range(n): for i in tuple(map(int, str.split(input()))): c[i - 1] += 1 count = 0 for i, j in itertools.combinations(range(n), 2): if c[i] + c[j] >= p: count += 1 print(count) ```
MatrixStudio/Codeforces-Python-Submissions
You found a mysterious function *f*. The function takes two strings *s*1 and *s*2. These strings must consist only of lowercase English letters, and must be the same length. The output of the function *f* is another string of the same length. The *i*-th character of the output is equal to the minimum of the *i*-th cha...
```python x = input() y = input() z = '' st = False for i in range(len(x)): if x[i] < y[i]: st = True break elif x[i] >= y[i]: z += y[i] if not st: print(z) else: print(-1) ```
MatrixStudio/Codeforces-Python-Submissions
A famous Berland's painter Kalevitch likes to shock the public. One of his last obsessions is chess. For more than a thousand years people have been playing this old game on uninteresting, monotonous boards. Kalevitch decided to put an end to this tradition and to introduce a new attitude to chessboards. As before, th...
```python l,l2,count=[],[],0 b,w= 'BBBBBBBB', 'WWWWWWWW' for _ in range(8): l.append(input()) for i in range(8): if l[i] == b: count+=1 l[i]= w for i in range(8): c = [x[i] for x in l] l2.append(c) for col in l2: if 'B' in col: count+=1 print(count) ```
MatrixStudio/Codeforces-Python-Submissions
An *n*<=×<=*n* table *a* is defined as follows: - The first row and the first column contain ones, that is: *a**i*,<=1<==<=*a*1,<=*i*<==<=1 for all *i*<==<=1,<=2,<=...,<=*n*. - Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the ...
```python import huy n = int(input()) print(huy.comb(n*2-2,n-1)) ```
MatrixStudio/Codeforces-Python-Submissions
Once Bob got to a sale of old TV sets. There were *n* TV sets at that sale. TV set with index *i* costs *a**i* bellars. Some TV sets have a negative price — their owners are ready to pay Bob if he buys their useless apparatus. Bob can «buy» any TV sets he wants. Though he's very strong, Bob can carry at most *m* TV set...
```python n, m = map(int, input().split()) l=list(map(int,input().split())) sl=sorted(l) s=0 for i in range(m): if sl[i]<0: s-=sl[i] print(s) ```
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 def level(n): if n <= 1: return 1 return level(n // 2) + 1 def length(level_n): return 2 ** level_n - 1 def operation(lst): while max(lst) > 1: for i in range(len(lst)): if lst[i] > 1: x = lst[i] lst[i:i + 1] = [x // 2, x % 2] 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()) c=0 for i in range(n): a=list(map(int, input().split())) if a[1]-a[0] >= 2: c+=1 print(c) ```
MatrixStudio/Codeforces-Python-Submissions
After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer. At the start of the day they have *x* ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. Each person in the...
```python a, b = map(int, input().split()) q = 0 for _ in range(a): c,d = input().split() d = int(d) if c == "+": b = b+d else: if b-d < 0: b = b q += 1 else: b = b-d print(b,q) ```
MatrixStudio/Codeforces-Python-Submissions
Limak is a little polar bear. He doesn't have many toys and thus he often plays with polynomials. He considers a polynomial valid if its degree is *n* and its coefficients are integers not exceeding *k* by the absolute value. More formally: Let *a*0,<=*a*1,<=...,<=*a**n* denote the coefficients, so . Then, a polynomi...
```python __author__ = 'JohnHook' n, k = list(map(int, input().split())) v = list(map(int, input().split())) sum = 0 for i in range(n + 1): v[i] *= 2 ** i sum += v[i] ans = 0 for i in range(n + 1): if (sum - v[i]) % 2 ** i == 0 and abs((sum - v[i]) / 2 ** i) <= k and (i == n and abs((sum - v[...
MatrixStudio/Codeforces-Python-Submissions
Amr is a young coder who likes music a lot. He always wanted to learn how to play music but he was busy coding so he got an idea. Amr has *n* instruments, it takes *a**i* days to learn *i*-th instrument. Being busy, Amr dedicated *k* days to learn how to play the maximum possible number of instruments. Amr asked for ...
```python N, K = map(int, input().split()) A = [(i+1, int(x)) for i, x in enumerate(input().split())] A.sort(key = lambda t: t[1]) answer = [] for t in A: if t[1] > K: break answer.append(t[0]) K -= t[1] print(len(answer)) print(*answer) ```
MatrixStudio/Codeforces-Python-Submissions
Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to th...
```python def minimum_horseshoes_to_buy(colors): distinct_colors = len(set(colors)) return max(0, 4 - distinct_colors) # Read input colors = list(map(int, input().split())) # Calculate the minimum number of horseshoes to buy and print the result print(minimum_horseshoes_to_buy(colors)) ```
MatrixStudio/Codeforces-Python-Submissions
After seeing the "ALL YOUR BASE ARE BELONG TO US" meme for the first time, numbers *X* and *Y* realised that they have different bases, which complicated their relations. You're given a number *X* represented in base *b**x* and a number *Y* represented in base *b**y*. Compare those two numbers.
```python bx=int(input().split()[1]) x=list(map(int,input().split())) by=int(input().split()[1]) y=list(map(int,input().split())) X=Y=0 for xi in x: X=X*bx+xi for yi in y: Y=Y*by+yi if(X>Y): print(">") elif(X<Y): print("<") else: print("=") ```
MatrixStudio/Codeforces-Python-Submissions
Your friend has recently learned about coprime numbers. A pair of numbers {*a*,<=*b*} is called coprime if the maximum number that divides both *a* and *b* is equal to one. Your friend often comes up with different statements. He has recently supposed that if the pair (*a*,<=*b*) is coprime and the pair (*b*,<=*c*) i...
```python l,r=input().split(" ") l,r=int(l),int(r) if (l % 2 != 0): l+=1 if (l + 2 > r): print(-1); else: print(l,l+1,l+2) ```
MatrixStudio/Codeforces-Python-Submissions
You are given two strings $s$ and $t$. In a single move, you can choose any of two strings and delete the first (that is, the leftmost) character. After a move, the length of the string decreases by $1$. You can't choose a string if it is empty. For example: - by applying a move to the string "where", the result is ...
```python import sys s=input() t=input() if s == t: print(0) sys.exit(0) a=min(len(s),len(t)) for i in range(a): if s[-a:] != t[-a:]: break i-=1 print(len(s)+len(t)-i*2) ```
MatrixStudio/Codeforces-Python-Submissions
Giga Tower is the tallest and deepest building in Cyberland. There are 17<=777<=777<=777 floors, numbered from <=-<=8<=888<=888<=888 to 8<=888<=888<=888. In particular, there is floor 0 between floor <=-<=1 and floor 1. Every day, thousands of tourists come to this place to enjoy the wonderful view. In Cyberland, it ...
```python def m(): n = eval(input()); b = 1; n+=1 while True: if "8" in str(n): print(b) ; break else: n+=1; b+=1 m() ```
MatrixStudio/Codeforces-Python-Submissions
You've got an array *a*, consisting of *n* integers: *a*1,<=*a*2,<=...,<=*a**n*. Your task is to find a minimal by inclusion segment [*l*,<=*r*] (1<=≤<=*l*<=≤<=*r*<=≤<=*n*) such, that among numbers *a**l*,<= *a**l*<=+<=1,<= ...,<= *a**r* there are exactly *k* distinct numbers. Segment [*l*,<=*r*] (1<=≤<=*l*<=≤<=*r*<=≤...
```python n, k = map(int,input().split()) ls = list(map(int, input().split())) cnt = [0 for _ in range(100005)] i = 0 j = 0 count = 0 found = False while i < n: cnt[ls[i]] += 1 if cnt[ls[i]] == 1: count += 1 i += 1 if count == k: found = True break while count == k: cnt[ls[j]] -= 1 if cnt[ls[j]] == 0: ...
MatrixStudio/Codeforces-Python-Submissions
— I... I survived. — Welcome home, Chtholly. — I kept my promise... — I made it... I really made it! After several days of fighting, Chtholly Nota Seniorious miraculously returned from the fierce battle. As promised, Willem is now baking butter cake for her. However, although Willem is skilled in making dessert, ...
```python def get_int(string, n): i = j = k = 0 for s in string: k += 1 for s in string: if i == n - 1: break if s == ' ': i += 1 j += 1 i = 0 while j < k: if string[j] == ' ': break i = 10 * i + int(string[j]) j += 1 return i def get_zcy(string): strin = '' for i in ...
MatrixStudio/Codeforces-Python-Submissions
Nick's company employed *n* people. Now Nick needs to build a tree hierarchy of «supervisor-surbodinate» relations in the company (this is to say that each employee, except one, has exactly one supervisor). There are *m* applications written in the following form: «employee *a**i* is ready to become a supervisor of emp...
```python n = int(input()) quali = input().split() m = int(input()) None l = [None]*n cnt = 0 for i in range(m): a, b, c = list(map(int, input().split())) if l[b-1] == None: l[b-1] = c else: l[b-1] = min(l[b-1], int(c)) if (l.count(None) > 1): print(-1) else: for j in l: ...
MatrixStudio/Codeforces-Python-Submissions
A word or a sentence in some language is called a pangram if all the characters of the alphabet of this language appear in it at least once. Pangrams are often used to demonstrate fonts in printing or test the output devices. You are given a string consisting of lowercase and uppercase Latin letters. Check whether thi...
```python import string s = string.ascii_lowercase n = int(input()) st = input().lower() retult = None for i in s: if i in st: retult ='YES' else: print('No') break print(retult) ```
MatrixStudio/Codeforces-Python-Submissions
A dice is a cube, its faces contain distinct integers from 1 to 6 as black points. The sum of numbers at the opposite dice faces always equals 7. Please note that there are only two dice (these dices are mirror of each other) that satisfy the given constraints (both of them are shown on the picture on the left). Alice...
```python x = int(input()) face = int(input()) facx = 7-face message = 1 for i in range(x): z = list(map(int,input().split())) if face in z or facx in z : message*=0 else : message*=1 if message == 0: print("NO") else: print("YES") ```
MatrixStudio/Codeforces-Python-Submissions
Valery is very interested in magic. Magic attracts him so much that he sees it everywhere. He explains any strange and weird phenomenon through intervention of supernatural forces. But who would have thought that even in a regular array of numbers Valera manages to see something beautiful and magical. Valera absolutel...
```python def main(): n = int(input()) a = [int(x) for x in input().split()] w = 0 for i in range(n): min_val, max_val = a[i], a[i] for j in range(i+2, n+1): if a[j-1] < min_val: min_val = a[j-1] elif a[j-1] > max_val: max...
MatrixStudio/Codeforces-Python-Submissions
Little Petya was given this problem for homework: You are given function (here represents the operation of taking the remainder). His task is to count the number of integers *x* in range [*a*;*b*] with property *f*(*x*)<==<=*x*. It is a pity that Petya forgot the order in which the remainders should be taken and wr...
```python a,b,c,d,e,f=map(int,input().split()) count=0 for i in range(e,f+1): k=i%a%b%c%d if i==k: count+=1 print(count) ```
MatrixStudio/Codeforces-Python-Submissions
Bob programmed a robot to navigate through a 2d maze. The maze has some obstacles. Empty cells are denoted by the character '.', where obstacles are denoted by '#'. There is a single robot in the maze. Its start position is denoted with the character 'S'. This position has no obstacle in it. There is also a single ex...
```python n, m = map(int, input().split()) mz = [input() for _ in range(n)] instr = input() sr, sc, exitRow, exitCol = -1, -1, 0, 0 for p in range(n): for q in range(m): if mz[p][q] == 'S': sr, sc = p, q elif mz[p][q] == 'E': exitRow, exitCol = p, q cnt = 0 for perm in perm...
MatrixStudio/Codeforces-Python-Submissions
The bear decided to store some raspberry for the winter. He cunningly found out the price for a barrel of honey in kilos of raspberry for each of the following *n* days. According to the bear's data, on the *i*-th (1<=≤<=*i*<=≤<=*n*) day, the price for one barrel of honey is going to is *x**i* kilos of raspberry. Unfo...
```python n,m=map(int,input().split()) l=list(map(int,input().split())) d=-13546789 for i in range(0,n-1,1): if -l[i+1]+l[i]>=d: d=-l[i+1]+l[i] if d>0: print(d-m) else: print(0) ```
MatrixStudio/Codeforces-Python-Submissions
One day Polycarp published a funny picture in a social network making a poll about the color of his handle. Many of his friends started reposting Polycarp's joke to their news feed. Some of them reposted the reposts and so on. These events are given as a sequence of strings "name1 reposted name2", where name1 is the n...
```python from sys import stdin n = int(stdin.readline()) cnt = {'POLYCARP': 1} ans = 1 for i in range(n): name1, _, name2 = map(lambda s: s.strip().upper(), stdin.readline().split()) cnt[name1] = cnt[name2] + 1 ans = max(ans, cnt[name1]) print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
You are given $n$ strings. Each string consists of lowercase English letters. Rearrange (reorder) the given strings in such a way that for every string, all strings that are placed before it are its substrings. String $a$ is a substring of string $b$ if it is possible to choose several consecutive letters in $b$ in su...
```python from collections import * from heapq import * from bisect import * from itertools import * from functools import * from math import * from string import * import sys input = sys.stdin.readline def solve(): n = int(input()) S = [] groups = defaultdict(set) for _ in range(n)...
MatrixStudio/Codeforces-Python-Submissions
Little Petya has recently started attending a programming club. Naturally he is facing the problem of choosing a programming language. After long considerations he realized that Java is the best choice. The main argument in favor of choosing Java was that it has a very large integer data type, called BigInteger. But h...
```python import sys n = int(sys.stdin.readline()[:-1]) n = abs(n) if(n <= 127): print("byte") elif(n <= 32767): print("short") elif(n <= 2147483647): print("int") elif(n <= 9223372036854775807): print("long") else: print("BigInteger") ```
MatrixStudio/Codeforces-Python-Submissions
In this problem we consider a special type of an auction, which is called the second-price auction. As in regular auction *n* bidders place a bid which is price a bidder ready to pay. The auction is closed, that is, each bidder secretly informs the organizer of the auction price he is willing to pay. After that, the au...
```python from sys import stdin inp = stdin.readline n = int(inp()) arr = [int(x) for x in inp().split()] win = arr.index(max(arr)) arr.pop(win) print(win+1, max(arr)) ```
MatrixStudio/Codeforces-Python-Submissions
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya wonders eagerly what minimum lucky number has the sum of digits equal to *n*. Help him cope wi...
```python a = int(input()) b ="" while(a<4): if(a-7>0): b=b+"7" a=a-7 continue if(a-4>0): b=b+"4" a=a-4 if(a==0): print(b) else: print(-1) ```
MatrixStudio/Codeforces-Python-Submissions
Hands that shed innocent blood! There are *n* guilty people in a line, the *i*-th of them holds a claw with length *L**i*. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the *i*-th person kills the *j*-th person if and only if *j*<=&lt;<=*i* and *...
```python n = int(input()) A = list(map(int, input().split())) for i in range(len(A)): k = i-1 while k>=i-A[i] and k>=0: A[k] = -1 k-=1 print(len(A)-A.count(-1)) ```
MatrixStudio/Codeforces-Python-Submissions
In the beginning of the new year Keivan decided to reverse his name. He doesn't like palindromes, so he changed Naviek to Navick. He is too selfish, so for a given *n* he wants to obtain a string of *n* characters, each of which is either 'a', 'b' or 'c', with no palindromes of length 3 appearing in the string as a su...
```python from sys import stdin, stdout import random import time def threepal(n): s = [0 for x in range(n)] all_choices = ["a", "b", "c"] preferred_choices = ["a", "b"] for i in range(2): s[i] = random.choice(preferred_choices) for i in range(2, int(n/1)): if s[i-2] == "...
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 n = int(input()) s = input() a = s.count('SF') b = s.count('FS') if a > b: print('YES') else: print('NO') ```
MatrixStudio/Codeforces-Python-Submissions
Luba thinks about watering her garden. The garden can be represented as a segment of length *k*. Luba has got *n* buckets, the *i*-th bucket allows her to water some continuous subsegment of garden of length exactly *a**i* each hour. Luba can't water any parts of the garden that were already watered, also she can't wat...
```python k,n=map(int,input().split()) s=map(int,input().split()) q=1 for i in s: if n%i==0: q=max(q,i) print(n//q) ```
MatrixStudio/Codeforces-Python-Submissions
A dice is a cube, its faces contain distinct integers from 1 to 6 as black points. The sum of numbers at the opposite dice faces always equals 7. Please note that there are only two dice (these dices are mirror of each other) that satisfy the given constraints (both of them are shown on the picture on the left). Alice...
```python n = int(input()) x = int(input()) for i in range (n): a, b=map(int, input().split()) if a == 6 or b == 6: print("NO") else: print("YES") ```