source
stringclasses
3 values
instruction
stringlengths
23
3.97k
input
stringclasses
1 value
output
stringlengths
1
3.75k
MatrixStudio/Codeforces-Python-Submissions
The Little Elephant has an integer *a*, written in the binary notation. He wants to write this number on a piece of paper. To make sure that the number *a* fits on the piece of paper, the Little Elephant ought to delete exactly one any digit from number *a* in the binary record. At that a new number appears. It consists of the remaining binary digits, written in the corresponding order (possible, with leading zeroes). The Little Elephant wants the number he is going to write on the paper to be as large as possible. Help him find the maximum number that he can obtain after deleting exactly one binary digit and print it in the binary notation.
```python bin = input() ok = 1 for i in range(len(bin)): if bin[i] == '0': bin = bin[0:i] + bin[i + 1: len(bin)] ok = 0 break if ok == 1: bin = bin[0:-1] print(bin) ```
MatrixStudio/Codeforces-Python-Submissions
The main road in Bytecity is a straight line from south to north. Conveniently, there are coordinates measured in meters from the southernmost building in north direction. At some points on the road there are *n* friends, and *i*-th of them is standing at the point *x**i* meters and can move with any speed no greater than *v**i* meters per second in any of the two directions along the road: south or north. You are to compute the minimum time needed to gather all the *n* friends at some point on the road. Note that the point they meet at doesn't need to have integer coordinate.
```python def cnt(pos): ret = 0 for i in range(n): ret = max(ret, abs(pos - x[i])/v[i]) return ret n = int(input()) x = list(map(int ,input().split())) v = list(map(int ,input().split())) lo, hi = min(x), max(x) for _ in range(50): le = (lo + lo + hi) / 3 ri = (lo + hi + hi) / 3 if (cnt(le) < cnt(ri)): hi = ri else: lo = le print("%.13f" % cnt(lo)) ```
MatrixStudio/Codeforces-Python-Submissions
There are *n* children in Jzzhu's school. Jzzhu is going to give some candies to them. Let's number all the children from 1 to *n*. The *i*-th child wants to get at least *a**i* candies. Jzzhu asks children to line up. Initially, the *i*-th child stands at the *i*-th place of the line. Then Jzzhu start distribution of the candies. He follows the algorithm: 1. Give *m* candies to the first child of the line. 1. If this child still haven't got enough candies, then the child goes to the end of the line, else the child go home. 1. Repeat the first two steps while the line is not empty. Consider all the children in the order they go home. Jzzhu wants to know, which child will be the last in this order?
```python from collections import deque import math from random import randint as rand from functools import lru_cache import string alph_l = string.ascii_lowercase alph_u = string.ascii_uppercase def count_otr(nums): cnt = 0 for i in nums: if i <= 0: cnt +=1 return cnt simp = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] def main(): n, m = list(map(int, input().split())) a = list(map(int, input().split())) a = [i//m if i % m == 0 else i//m + 1 for i in a] for i in range(n-1, -1, -1): if a[i] == max(a): print(i+1) break if __name__ == "__main__": main() ```
MatrixStudio/Codeforces-Python-Submissions
Summer holidays! Someone is going on trips, someone is visiting grandparents, but someone is trying to get a part-time job. This summer Noora decided that she wants to earn some money, and took a job in a shop as an assistant. Shop, where Noora is working, has a plan on the following *n* days. For each day sales manager knows exactly, that in *i*-th day *k**i* products will be put up for sale and exactly *l**i* clients will come to the shop that day. Also, the manager is sure, that everyone, who comes to the shop, buys exactly one product or, if there aren't any left, leaves the shop without buying anything. Moreover, due to the short shelf-life of the products, manager established the following rule: if some part of the products left on the shelves at the end of the day, that products aren't kept on the next day and are sent to the dump. For advertising purposes manager offered to start a sell-out in the shop. He asked Noora to choose any *f* days from *n* next for sell-outs. On each of *f* chosen days the number of products were put up for sale would be doubled. Thus, if on *i*-th day shop planned to put up for sale *k**i* products and Noora has chosen this day for sell-out, shelves of the shop would keep 2·*k**i* products. Consequently, there is an opportunity to sell two times more products on days of sell-out. Noora's task is to choose *f* days to maximize total number of sold products. She asks you to help her with such a difficult problem.
```python line = [int(x) for x in input().split()] n = line[0] f = line[1] result = 0 diffs = [] for case in range(n): day = [int(x) for x in input().split()] k = day[0] l = day[1] sold = min(k,l) result += sold diffs.append(min(2*k,l)-sold) diffs.sort(reverse = True) for i in range(f): result += diffs[i] print(result) ```
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 the maximum possible least common multiple of these three integers?
```python from math import lcm n = int(input()) maxi = 0 for i in range(n,max(n-60,0),-1): maxi = max(maxi,lcm(i,i-1,i-2)) print(maxi) ```
MatrixStudio/Codeforces-Python-Submissions
You are given two positive integer numbers *a* and *b*. Permute (change order) of the digits of *a* to construct maximal number not exceeding *b*. No number in input and/or output can start with the digit 0. It is allowed to leave *a* as it is.
```python a = (input()) b_str = (input()) b_int = int(b_str) nums = [0] * 10 for char in b_str: nums[int(char)] +=1 print(nums) answ = "" if len(a)< len(b_str): for i in range(9,0,-1): while nums[i]!=0: answ += str(i) nums[i] -=1 print(answ) exit(0) for i in b_str : if nums[int(i)] != 0: nums[int(i)] -= 1 answ += i else: pass print(nums) ```
MatrixStudio/Codeforces-Python-Submissions
Polycarpus has a ribbon, its length is *n*. He wants to cut the ribbon in a way that fulfils the following two conditions: - After the cutting each ribbon piece should have length *a*, *b* or *c*. - After the cutting the number of ribbon pieces should be maximum. Help Polycarpus and find the number of ribbon pieces after the required cutting.
```python z = [] z[0:] = map(int ,input().split()) count = 0 counter = z[0] for i in range(1,4): if counter - z[i] == z[1] or counter - z[i] == z[2] or counter - z[i] == z[3]: count +=1 counter -=z[i] print(counter) ```
MatrixStudio/Codeforces-Python-Submissions
During the break the schoolchildren, boys and girls, formed a queue of *n* people in the canteen. Initially the children stood in the order they entered the canteen. However, after a while the boys started feeling awkward for standing in front of the girls in the queue and they started letting the girls move forward each second. Let's describe the process more precisely. Let's say that the positions in the queue are sequentially numbered by integers from 1 to *n*, at that the person in the position number 1 is served first. Then, if at time *x* a boy stands on the *i*-th position and a girl stands on the (*i*<=+<=1)-th position, then at time *x*<=+<=1 the *i*-th position will have a girl and the (*i*<=+<=1)-th position will have a boy. The time is given in seconds. You've got the initial position of the children, at the initial moment of time. Determine the way the queue is going to look after *t* seconds.
```python n, t = map(int, input().split()) s = input() for _ in range(t): for i in range(n - 1): if i != 0: if i != (n - 2): if s[-(i + 2):-i] == "BG": s = s[:-(i + 2)] + "GB" + s[-i:] else: if s[:-i] == "BG": s = "GB" + s[-i:] else: if s[-(i + 2):] == "BG": s = s[:-(i + 2)] + "GB" print(s) ```
MatrixStudio/Codeforces-Python-Submissions
We consider a positive integer perfect, if and only if the sum of its digits is exactly $10$. Given a positive integer $k$, your task is to find the $k$-th smallest perfect positive integer.
```python n=int(input()) print((n+1)*10 - n) ```
MatrixStudio/Codeforces-Python-Submissions
Roma works in a company that sells TVs. Now he has to prepare a report for the last year. Roma has got a list of the company's incomes. The list is a sequence that consists of *n* integers. The total income of the company is the sum of all integers in sequence. Roma decided to perform exactly *k* changes of signs of several numbers in the sequence. He can also change the sign of a number one, two or more times. The operation of changing a number's sign is the operation of multiplying this number by -1. Help Roma perform the changes so as to make the total income of the company (the sum of numbers in the resulting sequence) maximum. Note that Roma should perform exactly *k* changes.
```python n, k = map(int, input().split()) a = list(map(int, input().split())) a.sort() countn = 0 for i in range(min(k, n)): if (a[i] < 0): countn += 1 a[i] = -a[i] a.sort() if (k - countn) % 2 != 0: a[0] = - a[0] print(sum(a)) ```
MatrixStudio/Codeforces-Python-Submissions
Vitaly is a very weird man. He's got two favorite digits *a* and *b*. Vitaly calls a positive integer good, if the decimal representation of this integer only contains digits *a* and *b*. Vitaly calls a good number excellent, if the sum of its digits is a good number. For example, let's say that Vitaly's favourite digits are 1 and 3, then number 12 isn't good and numbers 13 or 311 are. Also, number 111 is excellent and number 11 isn't. Now Vitaly is wondering, how many excellent numbers of length exactly *n* are there. As this number can be rather large, he asks you to count the remainder after dividing it by 1000000007 (109<=+<=7). A number's length is the number of digits in its decimal representation without leading zeroes.
```python from math import factorial MOD = 10**9+7 fact = {} a, b, n = map(int, input().split()) fact[0]=1 for i in range(1, n+1): fact[i] = fact[i-1]*i%MOD ans = 0 for (i, j) in zip(range(n+1), range(n, -1, -1)): if set(str(a*i + b*j)) <= {f'{a}', f'{b}'}: ans+=(fact[n]*pow(fact[n-i]*fact[i]%MOD, MOD-2, MOD) % MOD) print(ans%MOD) ```
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 k,n=map(int,input().split()) r=k%n r=(k-r)+n print(r) ```
MatrixStudio/Codeforces-Python-Submissions
A and B are preparing themselves for programming contests. To train their logical thinking and solve problems better, A and B decided to play chess. During the game A wondered whose position is now stronger. For each chess piece we know its weight: - the queen's weight is 9, - the rook's weight is 5, - the bishop's weight is 3, - the knight's weight is 3, - the pawn's weight is 1, - the king's weight isn't considered in evaluating position. The player's weight equals to the sum of weights of all his pieces on the board. As A doesn't like counting, he asked you to help him determine which player has the larger position weight.
```python white = 0 black = 0 board = input() white += board.count('p') black += board.count('P') white += board.count('r')*5 black += board.count('R')*5 white += board.count('n')*3 black += board.count('N')*3 white += board.count('b')*3 black += board.count('B')*3 white += board.count('q')*9 black += board.count('Q')*9 if white > black: print("White") elif black > white: print("Black") else: print("Draw") ```
MatrixStudio/Codeforces-Python-Submissions
Kitahara Haruki has bought *n* apples for Touma Kazusa and Ogiso Setsuna. Now he wants to divide all the apples between the friends. Each apple weights 100 grams or 200 grams. Of course Kitahara Haruki doesn't want to offend any of his friend. Therefore the total weight of the apples given to Touma Kazusa must be equal to the total weight of the apples given to Ogiso Setsuna. But unfortunately Kitahara Haruki doesn't have a knife right now, so he cannot split any apple into some parts. Please, tell him: is it possible to divide all the apples in a fair way between his friends?
```python n = int(input()) arr = list(map(int,input().split())) s = int(str(sum(arr))[0]) if (s % 2 == 0): print("YES") else: print("NO") ```
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 string = input() text = '' i = 0 while i < len(string): if string[i] == '.': text += '0' i += 1 elif string[i] == '-' and string[i+1] == '.': text += '1' i += 2 else: text += '2' i += 2 print(text) ```
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 not keep information about the current month, so when a new day comes, it simply increases the current day number by one. The clock cannot display number *d*<=+<=1, so after day number *d* it shows day 1 (the current day counter resets). The mechanism of the clock allows you to increase the day number by one manually. When you execute this operation, day *d* is also followed by day 1. Vasya begins each day checking the day number on the clock. If the day number on the clock does not match the actual day number in the current month, then Vasya manually increases it by one. Vasya is persistent and repeats this operation until the day number on the clock matches the actual number of the current day in the current month. A year passed and Vasya wonders how many times he manually increased the day number by one, from the first day of the first month to the last day of the *n*-th month inclusive, considering that on the first day of the first month the clock display showed day 1.
```python import math def add(disp,m): disp+=m if disp>d: disp = disp-d return disp d = int(input()) n = int(input()) a = list(map(int,input().split())) disp = 0 count = 0 for i in range(n): if disp == 0: disp+=a[i] else: # if disp+a[i]*2 <= d: disp+=a[i]*2 count+=a[i] # else: if add(disp,2*a[i]) <= a[i]: disp = add(disp,2*a[i]) count+=a[i] else: k = add(disp,2*a[i]) - a[i] count+= a[i]-k disp = a[i] print(count) ```
MatrixStudio/Codeforces-Python-Submissions
Amr has got a large array of size *n*. Amr doesn't like large arrays so he intends to make it smaller. Amr doesn't care about anything in the array except the beauty of it. The beauty of the array is defined to be the maximum number of times that some number occurs in this array. He wants to choose the smallest subsegment of this array such that the beauty of it will be the same as the original array. Help Amr by choosing the smallest subsegment possible.
```python n=int(input()) a=list(map(int,input().split())) d={} for i in range(n): if(a[i] in d): d[a[i]]=[d[a[i]][0],i+1] else: d[a[i]]=[i+1,i+1] d1={} for i in a: if(i in d1): d1[i]+=1 else: d1[i]=1 b=list(d1.items()) b.sort(reverse=True,key=lambda x:x[1]) ym=b[0][1] m=9999999 s=e=-1 for i in b: x,y=i[0],i[1] if(y!=ym): break if(d[x][1]-d[x][0]<m): m=d[x][1]-d[x][0] s=d[x][0] e=d[x][1] print(s,e) ```
MatrixStudio/Codeforces-Python-Submissions
Today, hedgehog Filya went to school for the very first time! Teacher gave him a homework which Filya was unable to complete without your help. Filya is given an array of non-negative integers *a*1,<=*a*2,<=...,<=*a**n*. First, he pick an integer *x* and then he adds *x* to some elements of the array (no more than once), subtract *x* from some other elements (also, no more than once) and do no change other elements. He wants all elements of the array to be equal. Now he wonders if it's possible to pick such integer *x* and change some elements of the array using this *x* in order to make all elements equal.
```python n=int(input()) l=list(map(int,input().split())) mi=min(l) ma=max(l) if len(set(l))>3: print('NO') elif len(set(l))<3: print('YES') else: for i in set(l): if i!=ma and i!=mi: me=i if ma-me==me-mi: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Year 2118. Androids are in mass production for decades now, and they do all the work for humans. But androids have to go to school to be able to solve creative tasks. Just like humans before. It turns out that high school struggles are not gone. If someone is not like others, he is bullied. Vasya-8800 is an economy-class android which is produced by a little-known company. His design is not perfect, his characteristics also could be better. So he is bullied by other androids. One of the popular pranks on Vasya is to force him to compare $x^y$ with $y^x$. Other androids can do it in milliseconds while Vasya's memory is too small to store such big numbers. Please help Vasya! Write a fast program to compare $x^y$ with $y^x$ for Vasya, maybe then other androids will respect him.
```python x , y = map(int,input().split()) if x == y : print('=') exit() if x == 1 : print('<') exit() if y == 1 : print('>') exit() else: if x > y : print('<') else: print('>') ```
MatrixStudio/Codeforces-Python-Submissions
The School №0 of the capital of Berland has *n* children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value *t**i*: - *t**i*<==<=1, if the *i*-th child is good at programming, - *t**i*<==<=2, if the *i*-th child is good at maths, - *t**i*<==<=3, if the *i*-th child is good at PE Each child happens to be good at exactly one of these three subjects. The Team Scientific Decathlon Olympias requires teams of three students. The school teachers decided that the teams will be composed of three children that are good at different subjects. That is, each team must have one mathematician, one programmer and one sportsman. Of course, each child can be a member of no more than one team. What is the maximum number of teams that the school will be able to present at the Olympiad? How should the teams be formed for that?
```python n = int(input()) ins = [int(x) for x in input().split(" ")] ins123 = [[] , [] , []] for index in range(n): ins123[ins[index] - 1].append(index) minSize = min([len(x) for x in ins123]) print(minSize) for i in range(minSize): for j in ins123: print(j.pop(0)+1 , end = " ") print() ```
MatrixStudio/Codeforces-Python-Submissions
A permutation is a sequence of integers from 1 to *n* of length *n* containing each number exactly once. For example, (1), (4,<=3,<=5,<=1,<=2), (3,<=2,<=1) are permutations, and (1,<=1), (4,<=3,<=1), (2,<=3,<=4) are not. There are many tasks on permutations. Today you are going to solve one of them. Let’s imagine that somebody took several permutations (perhaps, with a different number of elements), wrote them down consecutively as one array and then shuffled the resulting array. The task is to restore the initial permutations if it is possible.
```python from collections import Counter def permutations(n, array): perms = [] counter = Counter(array) perms = [[] for x in range(counter.most_common(1)[0][1])] sorted_a = sorted(array) prev = 0 j = 0 for i in range(0, len(sorted_a)): if sorted_a[i] == prev: j = j+1 elif sorted_a[i] == prev + 1: j = 0 else: print(-1) return perms[j].append(sorted_a[i]) prev = sorted_a[i] if len(perms) > counter.get(1): print(-1) return s = "" for i in array: for index, j in enumerate(perms): if i in j: s += str(index + 1) + " " j.remove(i) break print(len(perms)) print(s) return nb = int(input()) numbers = [int(i) for i in input().split(' ')] permutations(nb, numbers) ```
MatrixStudio/Codeforces-Python-Submissions
Sengoku still remembers the mysterious "colourful meteoroids" she discovered with Lala-chan when they were little. In particular, one of the nights impressed her deeply, giving her the illusion that all her fancies would be realized. On that night, Sengoku constructed a permutation *p*1,<=*p*2,<=...,<=*p**n* of integers from 1 to *n* inclusive, with each integer representing a colour, wishing for the colours to see in the coming meteor outburst. Two incredible outbursts then arrived, each with *n* meteorids, colours of which being integer sequences *a*1,<=*a*2,<=...,<=*a**n* and *b*1,<=*b*2,<=...,<=*b**n* respectively. Meteoroids' colours were also between 1 and *n* inclusive, and the two sequences were not identical, that is, at least one *i* (1<=≤<=*i*<=≤<=*n*) exists, such that *a**i*<=≠<=*b**i* holds. Well, she almost had it all — each of the sequences *a* and *b* matched exactly *n*<=-<=1 elements in Sengoku's permutation. In other words, there is exactly one *i* (1<=≤<=*i*<=≤<=*n*) such that *a**i*<=≠<=*p**i*, and exactly one *j* (1<=≤<=*j*<=≤<=*n*) such that *b**j*<=≠<=*p**j*. For now, Sengoku is able to recover the actual colour sequences *a* and *b* through astronomical records, but her wishes have been long forgotten. You are to reconstruct any possible permutation Sengoku could have had on that night.
```python n = int(input()) a = [int(i) for i in input().split()] b = [int(i) for i in input().split()] razl = [] for i in range(n): if a[i]!=b[i]: razl.append(i) if len(razl)==1: for i in range(n): if i!=a[razl[0]] and i!=b[razl[0]] and (i not in a): a[razl[0]]=i break else: if (b[razl[0]] not in a) and (a.count(a[razl[1]])==1) and (a[razl[1]]!=b[razl[0]]): a[razl[0]] = b[razl[0]] else: a[razl[1]] = b[razl[1]] for i in a: print(i, end=' ') ```
MatrixStudio/Codeforces-Python-Submissions
You're given a row with $n$ chairs. We call a seating of people "maximal" if the two following conditions hold: 1. There are no neighbors adjacent to anyone seated. 1. It's impossible to seat one more person without violating the first rule. The seating is given as a string consisting of zeros and ones ($0$ means that the corresponding seat is empty, $1$ — occupied). The goal is to determine whether this seating is "maximal". Note that the first and last seats are not adjacent (if $n \ne 2$).
```python n = int(input()) s = input() adj_ones = False big_gap = False gap = 0 if s[0]=='1' else 1 if n == 1: print('Yes' if s[0]=='1' else 'No') else: for i in range(1, n): if s[i]=='1': if s[i-1] == '1': adj_ones = True break gap = 0 else: gap += 1 if gap > 2: big_gap = True break if big_gap or adj_ones: print('No') else: print('Yes') ```
MatrixStudio/Codeforces-Python-Submissions
There are *n* walruses standing in a queue in an airport. They are numbered starting from the queue's tail: the 1-st walrus stands at the end of the queue and the *n*-th walrus stands at the beginning of the queue. The *i*-th walrus has the age equal to *a**i*. The *i*-th walrus becomes displeased if there's a younger walrus standing in front of him, that is, if exists such *j* (*i*<=&lt;<=*j*), that *a**i*<=&gt;<=*a**j*. The displeasure of the *i*-th walrus is equal to the number of walruses between him and the furthest walrus ahead of him, which is younger than the *i*-th one. That is, the further that young walrus stands from him, the stronger the displeasure is. The airport manager asked you to count for each of *n* walruses in the queue his displeasure.
```python #!/usr/bin/env python3 num_lines = input() raw = input() items = raw.split(" ") temp = [] for i in range(len(items)): count = len(items) - i - 2 j = len(items) - 1 while (j > i): if(int(items[j]) < int(items[i])): break count = count - 1 j = j - 1 temp.append(count) print(temp) ```
MatrixStudio/Codeforces-Python-Submissions
In Berland it is the holiday of equality. In honor of the holiday the king decided to equalize the welfare of all citizens in Berland by the expense of the state treasury. Totally in Berland there are *n* citizens, the welfare of each of them is estimated as the integer in *a**i* burles (burle is the currency in Berland). You are the royal treasurer, which needs to count the minimum charges of the kingdom on the king's present. The king can only give money, he hasn't a power to take away them.
```python n = int(input()) a = list(map(int, input().split())) b = max(welfare_values) c = sum(b - welfare for welfare in a) print(c) ```
MatrixStudio/Codeforces-Python-Submissions
Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone. In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules of the game, Jury must use this second to touch the corresponding strip to make the square go away. As Jury is both smart and lazy, he counted that he wastes exactly *a**i* calories on touching the *i*-th strip. You've got a string *s*, describing the process of the game and numbers *a*1,<=*a*2,<=*a*3,<=*a*4. Calculate how many calories Jury needs to destroy all the squares?
```python s1=input() s1=s1.split() a1=int(s1[0]) b1=int(s1[1]) c1=int(s1[2]) d1=int(s1[3]) s2=input() a=0 b=0 c=0 d=0 for i in range(len(s2)): if s2[i]=='1': a=a+1 elif s2[i]=='2': b=b+1 elif s2[i]=='3': c=c+1 else: d=d+1 A=a1*a B=b1*b C=c1*c D=d1*d o=A+B+C+D print(o) ```
MatrixStudio/Codeforces-Python-Submissions
Consider some square matrix *A* with side *n* consisting of zeros and ones. There are *n* rows numbered from 1 to *n* from top to bottom and *n* columns numbered from 1 to *n* from left to right in this matrix. We'll denote the element of the matrix which is located at the intersection of the *i*-row and the *j*-th column as *A**i*,<=*j*. Let's call matrix *A* clear if no two cells containing ones have a common side. Let's call matrix *A* symmetrical if it matches the matrices formed from it by a horizontal and/or a vertical reflection. Formally, for each pair (*i*,<=*j*) (1<=≤<=*i*,<=*j*<=≤<=*n*) both of the following conditions must be met: *A**i*,<=*j*<==<=*A**n*<=-<=*i*<=+<=1,<=*j* and *A**i*,<=*j*<==<=*A**i*,<=*n*<=-<=*j*<=+<=1. Let's define the sharpness of matrix *A* as the number of ones in it. Given integer *x*, your task is to find the smallest positive integer *n* such that there exists a clear symmetrical matrix *A* with side *n* and sharpness *x*.
```python x = int(input()) for i in range(100): if (i % 2 == 1): if ((i * i + 1) // 2 >= x): print(i) break ```
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 a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog. Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.
```python R=raw_input r,c=map(int,R().split()) s='\n'.join(R().replace('.','D')for _ in[0]*r) print'No'if['S','W']in map(sorted,zip(s,s[1:])+zip(s,s[c+1:]))else'Yes\n'+s ```
MatrixStudio/Codeforces-Python-Submissions
You are given a weighted undirected graph. The vertices are enumerated from 1 to *n*. Your task is to find the shortest path between the vertex 1 and the vertex *n*.
```python from collections import defaultdict from heapq import * def dijkstra(edges, f, t): g = defaultdict(list) for l,r,c in edges: g[l].append((c,r)) q = [(0,f,())] seen = set() mins = {f: 0} while q: (cost,v1,path) = heappop(q) if v1 not in seen: seen.add(v1) path = (v1, path) if v1 == t: return (cost, path) for c, v2 in g.get(v1, ()): if v2 in seen: continue prev = mins.get(v2, None) next = cost + c if prev is None or next < prev: mins[v2] = next heappush(q, (next, v2, path)) return float("inf") if __name__ == "__main__": FirstInput = input() FirstInput=[int(s) for s in FirstInput.split(' ')] Element = FirstInput[0] SecondEle = FirstInput[1] edges = [] for x in range(SecondEle): vertices = input() vertices=[int(s) for s in vertices.split(' ')] edges.append(tuple([vertices[0], vertices[1], vertices[2]])) edges.append(list([vertices[1], vertices[0], vertices[2]])) make_path = lambda list: (*make_path(list[1]), list[0]) if list else () out = dijkstra(edges, 1, Element) if(str(out)=="inf"): print( -1) else: path = make_path(out[1]) length = len(path) for p in path: print (p, end=" ") print() ```
MatrixStudio/Codeforces-Python-Submissions
Oleg writes down the history of the days he lived. For each day he decides if it was good or bad. Oleg calls a non-empty sequence of days a zebra, if it starts with a bad day, ends with a bad day, and good and bad days are alternating in it. Let us denote bad days as 0 and good days as 1. Then, for example, sequences of days 0, 010, 01010 are zebras, while sequences 1, 0110, 0101 are not. Oleg tells you the story of days he lived in chronological order in form of string consisting of 0 and 1. Now you are interested if it is possible to divide Oleg's life history into several subsequences, each of which is a zebra, and the way it can be done. Each day must belong to exactly one of the subsequences. For each of the subsequences, days forming it must be ordered chronologically. Note that subsequence does not have to be a group of consecutive days.
```python # Codeforces Submission # User : sudoSieg # Time : 14:50:08 # Date : 21/10/2020 import io import os #input = lambda: io.BytesIO(os.read(0, os.fstat(0).st_size)).readline().strip() valid = True s = input() ze = [] oe = [] for i, j in enumerate(s): if j == '0': if len(oe) != 0: x = oe.pop() x.append(i + 1) ze.append(x) else: ze.append([i + 1]) else: if len(ze) != 0: x = ze.pop() x.append(i + 1) oe.append(x) else: print("-1") exit() if len(oe) != 0: print(-1) else: print(len(ze)) for i in ze: print(len(i), end=' ') print(*i) ```
MatrixStudio/Codeforces-Python-Submissions
You are given *n*<=×<=*m* table. Each cell of the table is colored white or black. Find the number of non-empty sets of cells such that: 1. All cells in a set have the same color. 1. Every two cells in a set share row or column.
```python n, m = map(int, input().split()) s = n*m a = [] for i in range(n): b = [int(c) for c in input().split()] s1 = 0 s2 = 0 a.append(b) for i in range(m): if b[i]==1: s1+=1 else: s2+=1 s+=((s1-1)*s1)//2 s+=((s2-1)*s2)//2 for i in range(m): s1 = 0 s2 = 0 for j in range(n): if a[j][i]==1: s1+=1 else: s2+=1 s += ((s1 - 1) * s1) // 2 s += ((s2 - 1) * s2) // 2 print(s) ```
MatrixStudio/Codeforces-Python-Submissions
Little Joty has got a task to do. She has a line of *n* tiles indexed from 1 to *n*. She has to paint them in a strange pattern. An unpainted tile should be painted Red if it's index is divisible by *a* and an unpainted tile should be painted Blue if it's index is divisible by *b*. So the tile with the number divisible by *a* and *b* can be either painted Red or Blue. After her painting is done, she will get *p* chocolates for each tile that is painted Red and *q* chocolates for each tile that is painted Blue. Note that she can paint tiles in any order she wants. Given the required information, find the maximum number of chocolates Joty can get.
```python def compute(): def gcd(a,b): return a if b==0 else gcd(b,a%b) def lcm(a,b): return a*(b//gcd(a,b)) n, a, b, p, q = map(int,input().split()) return (n//a)*p + (n//b)*q - (n//(lcm(a,b)))*min(p,q) if __name__=="__main__": print(compute()) ```
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 s=input() index=0 ans="" while index<len(s): if s[index]==".": ans+="0" index+=1 else: if s[index+1]=="-": ans+="2" index+=2 elif s[index+1]==".": ans+="1" index+=2 print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game. Rules of the game are very simple: at first number of rounds *n* is defined. In every round each of the players throws a cubical dice with distinct numbers from 1 to 6 written on its faces. Player, whose value after throwing the dice is greater, wins the round. In case if player dice values are equal, no one of them is a winner. In average, player, who won most of the rounds, is the winner of the game. In case if two players won the same number of rounds, the result of the game is draw. Mishka is still very little and can't count wins and losses, so she asked you to watch their game and determine its result. Please help her!
```python n = int(input()) timer = 0 Mishka = 0 Chris = 0 a = [] while timer != n: a = input().split() if a[0] < a[1]: Mishka += 1 elif a[0] > a[1]: Chris += 1 timer += 1 if Mishka == Chris: print('Friendship is magic!^^') elif Mishka > Chris: print('Mishka') elif Mishka < Chris: print('Chris') ```
MatrixStudio/Codeforces-Python-Submissions
You are given two integers *n* and *k*. Find *k*-th smallest divisor of *n*, or report that it doesn't exist. Divisor of *n* is any such natural number, that *n* can be divided by it without remainder.
```python import math as m n,k = map(int,input().split()) f = [] s = [] for x in range(1,int(m.sqrt(n))+1): if n%x == 0: f.append(x) if n//x not in f: s.append(n//x) c = f+s[::-1] try: print(c[k-1]) except: print(-1) ```
MatrixStudio/Codeforces-Python-Submissions
Kefa decided to make some money doing business on the Internet for exactly *n* days. He knows that on the *i*-th day (1<=≤<=*i*<=≤<=*n*) he makes *a**i* money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence *a**i*. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order. Help Kefa cope with this task!
```python n = int(input()) x = [int(x) for x in input().split(' ')] l = [] count = 1 for i in range (1,n) : if x[i] >= x[i-1] : count += 1 else : l.append(count) count = 1 l.sort print(l[(len(l)-1)]) ```
MatrixStudio/Codeforces-Python-Submissions
Once little Vasya read an article in a magazine on how to make beautiful handmade garland from colored paper. Vasya immediately went to the store and bought *n* colored sheets of paper, the area of each sheet is 1 square meter. The garland must consist of exactly *m* pieces of colored paper of arbitrary area, each piece should be of a certain color. To make the garland, Vasya can arbitrarily cut his existing colored sheets into pieces. Vasya is not obliged to use all the sheets to make the garland. Vasya wants the garland to be as attractive as possible, so he wants to maximize the total area of ​​*m* pieces of paper in the garland. Calculate what the maximum total area of ​​the pieces of paper in the garland Vasya can get.
```python s, a, b = 0, defaultdict(int), defaultdict(int) for i in input(): a[i] += 1 for i in input(): b[i] += 1 for i in b: if i in a: s += min(a[i], b[i]) else: s = -1 break print(s) ```
MatrixStudio/Codeforces-Python-Submissions
Recently, you bought a brand new smart lamp with programming features. At first, you set up a schedule to the lamp. Every day it will turn power on at moment $0$ and turn power off at moment $M$. Moreover, the lamp allows you to set a program of switching its state (states are "lights on" and "lights off"). Unfortunately, some program is already installed into the lamp. The lamp allows only good programs. Good program can be represented as a non-empty array $a$, where $0 &lt; a_1 &lt; a_2 &lt; \dots &lt; a_{|a|} &lt; M$. All $a_i$ must be integers. Of course, preinstalled program is a good program. The lamp follows program $a$ in next manner: at moment $0$ turns power and light on. Then at moment $a_i$ the lamp flips its state to opposite (if it was lit, it turns off, and vice versa). The state of the lamp flips instantly: for example, if you turn the light off at moment $1$ and then do nothing, the total time when the lamp is lit will be $1$. Finally, at moment $M$ the lamp is turning its power off regardless of its state. Since you are not among those people who read instructions, and you don't understand the language it's written in, you realize (after some testing) the only possible way to alter the preinstalled program. You can insert at most one element into the program $a$, so it still should be a good program after alteration. Insertion can be done between any pair of consecutive elements of $a$, or even at the begining or at the end of $a$. Find such a way to alter the program that the total time when the lamp is lit is maximum possible. Maybe you should leave program untouched. If the lamp is lit from $x$ till moment $y$, then its lit for $y - x$ units of time. Segments of time when the lamp is lit are summed up.
```python import copy n, m = map(int, input().split()) s = [int(x) for x in input().split()] s=[0]+s+[m] count_set = set() s1=copy.copy(s) s2=copy.copy(s) count2=0 count3=0 if n>1: for i2 in range(2, n+2,2): s2.insert(i2,s[i2-1]+1) for j2 in range(1,n+3,2): count2 = count2+s2[j2]-s2[j2-1] count_set.add(count2) count2=0 s2=copy.copy(s) for i3 in range(1,n+2,2): count3=count3+s[i3]-s[i3-1] count_set.add(count3) print(max(count_set)) else: print(m-1) ```
MatrixStudio/Codeforces-Python-Submissions
Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are *n* drinks in his fridge, the volume fraction of orange juice in the *i*-th drink equals *p**i* percent. One day Vasya decided to make himself an orange cocktail. He took equal proportions of each of the *n* drinks and mixed them. Then he wondered, how much orange juice the cocktail has. Find the volume fraction of orange juice in the final drink.
```python x=int(input()) p=[int(x) for x in input().split()] print(p/sum(p)) ```
MatrixStudio/Codeforces-Python-Submissions
You have a positive integer *m* and a non-negative integer *s*. Your task is to find the smallest and the largest of the numbers that have length *m* and sum of digits *s*. The required numbers should be non-negative integers written in the decimal base without leading zeroes.
```python n, sum = map(int, input().split()) from copy import deepcopy if sum > (n*9) or sum == 0: print(-1, -1) else: max_nums = [] min_nums = [] total_sum = sum for i in range(n): if sum >= 9: to_append = 9 else: to_append = sum sum -= to_append max_nums.append(to_append) for i in range(n): m = total_sum - (n-(i+1)) to_append = abs(min(9, m)) total_sum -= to_append min_nums.append(to_append) min_nums.reverse() if min_nums[0] == 0: for i in range(n): if min_nums[i] > 0: min_nums[0], min_nums[i] = min_nums[i], min_nums[0] break print(''.join(str(i) for i in min_nums), ''.join(str(i) for i in max_nums)) ```
MatrixStudio/Codeforces-Python-Submissions
Polycarp is a beginner programmer. He is studying how to use a command line. Polycarp faced the following problem. There are *n* files in a directory and he needs to delete some of them. Polycarp wants to run a single delete command with filename pattern as an argument. All the files to be deleted should match the pattern and all other files shouldn't match the pattern. Polycarp doesn't know about an asterisk '*', the only special character he knows is a question mark '?' which matches any single character. All other characters in the pattern match themselves only. Formally, a pattern matches a filename if and only if they have equal lengths and all characters in the corresponding positions are equal except when the character in the pattern is '?', in which case the corresponding filename character does not matter. For example, the filename pattern "a?ba?": - matches filenames "aabaa", "abba.", "a.ba9" and "a.ba."; - does not match filenames "aaba", "abaab", "aabaaa" and "aabaa.". Help Polycarp find a pattern which matches files to be deleted and only them or report if there is no such pattern.
```python num_file,num_delete = map(int, input().split()) list_file = [] for i in range(num_file): list_file.append(input()) delete_file = [int(i)-1 for i in input().split()] ans="" delete_list = sorted([list_file[i]for i in delete_file],key=len) tmp = list(delete_list[0]) lenght = len(tmp) no = 0 for i in delete_list[1:]: name = list(i) if lenght != len(i): no = 1 for j in range(len(tmp)): if name[j] != tmp[j]: tmp[j] = "?" if tmp == ['?'] or no: print("No") else: print("Yes") for c in tmp: print(c,end="") ```
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 Misha has already chosen the subject for his thesis: determining by two dwarven genomes, whether they belong to the same race. Two dwarves belong to the same race if we can swap two characters in the first dwarf's genome and get the second dwarf's genome as a result. Help Dwarf Misha and find out whether two gnomes belong to the same race or not.
```python s1 = input() s2 = input() if len(s1) != len(s2): print('NO') exit() c = 0 for i in range(len(s1)): if s1[i] != s2[i]: c += 1 if len(s1) <= 2: if c == 2 or c == 0: print('YES') exit() else: print('NO') exit() if c > 2: print('NO') else: print('YES') ```
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 she was fighting them off. Every *k*-th dragon got punched in the face with a frying pan. Every *l*-th dragon got his tail shut into the balcony door. Every *m*-th dragon got his paws trampled with sharp heels. Finally, she threatened every *n*-th dragon to call her mom, and he withdrew in panic. How many imaginary dragons suffered moral or physical damage tonight, if the princess counted a total of *d* dragons?
```python import sys sys.setrecursionlimit(100000000) input=lambda:sys.stdin.readline().strip() write=lambda x:sys.stdout.write(str(x)) # from random import randint # from copy import deepcopy # from collections import deque # from heapq import heapify,heappush,heappop # from bisect import bisect_left,bisect,insort # from math import inf,sqrt,gcd,ceil,floor,log,log2,log10 # from functools import cmp_to_key p=[] for i in range(4): p.append(int(input())) d=int(input()) N=d+10 st=[0]*N for i in range(4): x=p[i] while x<=d: st[x]=1 x+=p[i] cnt=0 for i in range(1,d+1): cnt+=st[i] print(cnt) ```
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 the store and buy some few more horseshoes, not to lose face in front of his stylish comrades. Fortunately, the store sells horseshoes of all colors under the sun and Valera has enough money to buy any four of them. However, in order to save the money, he would like to spend as little money as possible, so you need to help Valera and determine what is the minimum number of horseshoes he needs to buy to wear four horseshoes of different colors to a party.
```python a=list(set(list(map(int,input().split())))) print(4-len(a)) ```
MatrixStudio/Codeforces-Python-Submissions
Students in a class are making towers of blocks. Each student makes a (non-zero) tower by stacking pieces lengthwise on top of each other. *n* of the students use pieces made of two blocks and *m* of the students use pieces made of three blocks. The students don’t want to use too many blocks, but they also want to be unique, so no two students’ towers may contain the same number of blocks. Find the minimum height necessary for the tallest of the students' towers.
```python n, m = [int(x) for x in input().split()] h1 = lambda k: 6*((k-1)//2) + 2*((k-1)%2+1) if k > 0 else 0 h2 = lambda k: 3 + (k-1)*6 if k > 0 else 0 h3 = lambda l: 6*k newx = lambda k: k - 2 if k%6 == 4 else k - 4 newy = lambda k: k - 6 x, y, z = h1(n), h2(m), 0 while max(x, y) > z + 6: z += 6 if x > y: x = newx(x) else: y = newy(y) print(max(x, y, z)) ```
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 tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of *n*<=-<=1 positive integers *a*1,<=*a*2,<=...,<=*a**n*<=-<=1. For every integer *i* where 1<=≤<=*i*<=≤<=*n*<=-<=1 the condition 1<=≤<=*a**i*<=≤<=*n*<=-<=*i* holds. Next, he made *n*<=-<=1 portals, numbered by integers from 1 to *n*<=-<=1. The *i*-th (1<=≤<=*i*<=≤<=*n*<=-<=1) portal connects cell *i* and cell (*i*<=+<=*a**i*), and one can travel from cell *i* to cell (*i*<=+<=*a**i*) using the *i*-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (*i*<=+<=*a**i*) to cell *i* using the *i*-th portal. It is easy to see that because of condition 1<=≤<=*a**i*<=≤<=*n*<=-<=*i* one can't leave the Line World using portals. Currently, I am standing at cell 1, and I want to go to cell *t*. However, I don't know whether it is possible to go there. Please determine whether I can go to cell *t* by only using the construted transportation system.
```python a,b=map(int,input().split()) q=[int(w)for w in input().split()] e=q[0] for i in range(a): e=e+q[e-1] if e==b: print('YES') exit() e=q[e-1] print('NO') ```
MatrixStudio/Codeforces-Python-Submissions
A string is called a *k*-string if it can be represented as *k* concatenated copies of some string. For example, the string "aabaabaabaab" is at the same time a 1-string, a 2-string and a 4-string, but it is not a 3-string, a 5-string, or a 6-string and so on. Obviously any string is a 1-string. You are given a string *s*, consisting of lowercase English letters and a positive integer *k*. Your task is to reorder the letters in the string *s* in such a way that the resulting string is a *k*-string.
```python import sys k = int(input()) s = input() count = {} for i in s: if i in count: count[i] += 1 else: count[i] = 1 build = "" for letter in count: if count[letter] % k != 0: print(-1) sys.exit() else: build += letter*(int(count[letter] / k)) print(build*k) ```
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 queue wants either to take several ice cream packs for himself and his friends or to give several ice cream packs to Kay and Gerda (carriers that bring ice cream have to stand in the same queue). If a carrier with *d* ice cream packs comes to the house, then Kay and Gerda take all his packs. If a child who wants to take *d* ice cream packs comes to the house, then Kay and Gerda will give him *d* packs if they have enough ice cream, otherwise the child will get no ice cream at all and will leave in distress. Kay wants to find the amount of ice cream they will have after all people will leave from the queue, and Gerda wants to find the number of distressed kids.
```python import sys n1,n2 = input().split() n1,n2=int(n1),int(n2) num_in_distress = 0 for i in range(n1): n4,n3=input().split() n3 = int(n3) if n4=="-": if n2>=n3: n2 -= n3 else: num_in_distress += 1 elif n4=="+": n2+=n3 print(str(n2)+" "+str(num_in_distress)) ```
MatrixStudio/Codeforces-Python-Submissions
Natasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the string — concatenation of letters, which correspond to the stages. There are $n$ stages available. The rocket must contain exactly $k$ of them. Stages in the rocket should be ordered by their weight. So, after the stage with some letter can go only stage with a letter, which is at least two positions after in the alphabet (skipping one letter in between, or even more). For example, after letter 'c' can't go letters 'a', 'b', 'c' and 'd', but can go letters 'e', 'f', ..., 'z'. For the rocket to fly as far as possible, its weight should be minimal. The weight of the rocket is equal to the sum of the weights of its stages. The weight of the stage is the number of its letter in the alphabet. For example, the stage 'a 'weighs one ton,' b 'weighs two tons, and' z' — $26$ tons. Build the rocket with the minimal weight or determine, that it is impossible to build a rocket at all. Each stage can be used at most once.
```python def stages() n=int(input()) k=int(input()) s=input() w=0 count1=0 count2=0 x=[] for i in range(n): x.append(ord(s[i])-96) x.sort() j=x[0] w+=x[0] for l in range(n): if x[l]-j>=2 and x[l]<=26: j=x[l] count1+=1 if count1<=k-1: w+=x[l] count2+=1 if count2==k-1: print(w) else: print(-1) ```
MatrixStudio/Codeforces-Python-Submissions
"Contestant who earns a score equal to or greater than the *k*-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." — an excerpt from contest rules. A total of *n* participants took part in the contest (*n*<=≥<=*k*), and you already know their scores. Calculate how many participants will advance to the next round.
```python n, m = map(int, input().split()) arr = list(map(int, input().split())) count = 0 for i in range(n): if arr[i] > m: count += 1 print(count) ```
MatrixStudio/Codeforces-Python-Submissions
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array. According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is. Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to *n*) and ending with the *n*-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the *n*-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent. To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to *n*, and generated *m* queries of the form: find element with value *b**i* in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand. But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
```python from sys import stdin def main(): n = int(stdin.readline().strip()) a = list(map(int, stdin.readline().strip().split())) stdin.readline().strip() b = list(map(int, stdin.readline().strip().split())) totalV = 0 totalP = 0 for i in b: pos = a.index(i) totalV += pos + 1 totalP += n - pos print(f"{totalV} {totalP}") main() ```
MatrixStudio/Codeforces-Python-Submissions
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem. Given two strings *a* and *b*, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other. A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings "ac", "bc", "abc" and "a" are subsequences of string "abc" while strings "abbc" and "acb" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.
```python a = list(map(str, input())) b = list(map(str, input())) def solve(second, first): if first == [] or second == first: return -1 for i in range(len(first)): if first[i] not in second: return max(len(second), len(first[i:])) else: return solve(second, first[i + 1:]) print(solve(a, b)) ```
MatrixStudio/Codeforces-Python-Submissions
Let's consider a table consisting of *n* rows and *n* columns. The cell located at the intersection of *i*-th row and *j*-th column contains number *i*<=×<=*j*. The rows and columns are numbered starting from 1. You are given a positive integer *x*. Your task is to count the number of cells in a table that contain number *x*.
```python a,b = map(int, input().split()) y=0 for i in range(1, a+1): for j in range(1, a+1): if int(i*j) == int(b): y=y+1 print(y) ```
MatrixStudio/Codeforces-Python-Submissions
Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list. Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus.
```python n = int(input()) arr = [] for i in range(n): s = input() arr.append(s) st = [] for i in range(n-1,-1,-1): if arr[i] in st: continue else: st.append(arr[i]) print(arr[i]) ```
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 perfectly sure that if he outbids the current price of one of the items in the auction (in other words, offers the seller the money that is strictly greater than the current price of the item at the auction), the seller of the object will immediately sign a contract with him. Unfortunately, Valera has only *v* units of money. Help him to determine which of the *n* sellers he can make a deal with.
```python n,v = [int(i) for i in input().split()] count = 0 ans = [] arr = [] for _ in range(n): lst = [int(i) for i in input().split()] arr.append(lst) for i in range(len(arr)): for j in range(1,len(arr[i])): if arr[i][j]<v: count+=1 ans.append(i+1) break ans.sort() print(count) for i in ans: print(i,end=" ") ```
MatrixStudio/Codeforces-Python-Submissions
Right now she actually isn't. But she will be, if you don't solve this problem. You are given integers *n*, *k*, *A* and *B*. There is a number *x*, which is initially equal to *n*. You are allowed to perform two types of operations: 1. Subtract 1 from *x*. This operation costs you *A* coins. 1. Divide *x* by *k*. Can be performed only if *x* is divisible by *k*. This operation costs you *B* coins.
```python n = int(input()) k = int(input()) a = int(input()) b = int(input()) tot = 0 while n>1: if n%k == 0: if (n-n//k)*a < b: tot+=(n-1)*a n = 1 break else: tot+=b n //= k else: tot+=(n%k)*a n -= n%k if n == 0: tot-=a print(int(tot)) ```
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. Unfortunately, the bear has neither a honey barrel, nor the raspberry. At the same time, the bear's got a friend who is ready to lend him a barrel of honey for exactly one day for *c* kilograms of raspberry. That's why the bear came up with a smart plan. He wants to choose some day *d* (1<=≤<=*d*<=&lt;<=*n*), lent a barrel of honey and immediately (on day *d*) sell it according to a daily exchange rate. The next day (*d*<=+<=1) the bear wants to buy a new barrel of honey according to a daily exchange rate (as he's got some raspberry left from selling the previous barrel) and immediately (on day *d*<=+<=1) give his friend the borrowed barrel of honey as well as *c* kilograms of raspberry for renting the barrel. The bear wants to execute his plan at most once and then hibernate. What maximum number of kilograms of raspberry can he earn? Note that if at some point of the plan the bear runs out of the raspberry, then he won't execute such a plan.
```python I=lambda:list(map(int,input().split())) n,c=I() a=I() print(max([a[i]-a[i+1]-c for i in range(n-1)]+[0])) ```
MatrixStudio/Codeforces-Python-Submissions
A string is a palindrome if it reads the same from the left to the right and from the right to the left. For example, the strings "kek", "abacaba", "r" and "papicipap" are palindromes, while the strings "abb" and "iq" are not. A substring $s[l \ldots r]$ ($1<=\leq<=l<=\leq<=r<=\leq<=|s|$) of a string $s<==<=s_{1}s_{2} \ldots s_{|s|}$ is the string $s_{l}s_{l<=+<=1} \ldots s_{r}$. Anna does not like palindromes, so she makes her friends call her Ann. She also changes all the words she reads in a similar way. Namely, each word $s$ is changed into its longest substring that is not a palindrome. If all the substrings of $s$ are palindromes, she skips the word at all. Some time ago Ann read the word $s$. What is the word she changed it into?
```python s=input(); ans=0; flag=0; for t in range(1, len(s)): for i in range(t): p=s[i:t+1] if len(p)%2==0: if p[0:(len(p)//2)]!=p[len(p)//2:][::-1]: ans=max(t-i+1, ans) else: if p[0:(len(p)//2)]!=p[len(p)//2+1:][::-1]: ans=max(len(p), ans) print(ans) ```
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 1. A statement in language Bit++ is a sequence, consisting of exactly one operation and one variable *x*. The statement is written without spaces, that is, it can only contain characters "+", "-", "X". Executing a statement means applying the operation it contains. A programme in Bit++ is a sequence of statements, each of them needs to be executed. Executing a programme means executing all the statements it contains. You're given a programme in language Bit++. The initial value of *x* is 0. Execute the programme and find its final value (the value of the variable when this programme is executed).
```python x=0 n=input() n=int(n) karam=input() if karam==("++X")or karam==("X++"): x=x+1 else: x=x-1 print(x) ```
MatrixStudio/Codeforces-Python-Submissions
Ari the monster is not an ordinary monster. She is the hidden identity of Super M, the Byteforces’ superhero. Byteforces is a country that consists of *n* cities, connected by *n*<=-<=1 bidirectional roads. Every road connects exactly two distinct cities, and the whole road system is designed in a way that one is able to go from any city to any other city using only the given roads. There are *m* cities being attacked by humans. So Ari... we meant Super M have to immediately go to each of the cities being attacked to scare those bad humans. Super M can pass from one city to another only using the given roads. Moreover, passing through one road takes her exactly one kron - the time unit used in Byteforces. However, Super M is not on Byteforces now - she is attending a training camp located in a nearby country Codeforces. Fortunately, there is a special device in Codeforces that allows her to instantly teleport from Codeforces to any city of Byteforces. The way back is too long, so for the purpose of this problem teleportation is used exactly once. You are to help Super M, by calculating the city in which she should teleport at the beginning in order to end her job in the minimum time (measured in krons). Also, provide her with this time so she can plan her way back to Codeforces.
```python import sys def dfs(v, h): v.color = True s = 0 for g in v.nodes: if not g.color: s += dfs(g, h + 1) if v.a: s += h v.color = False return s class Node: def __init__(self, id_): self.id = id_ self.nodes = [] self.a = False self.color = False #sys.stdin = open('input.txt') goals = [] towns = [] n, m = map(int, input().split()) for i in range(n): towns.append(Node(i + 1)) goals.append(False) i = 0 while i < n - 1: u, v = map(int, input().split()) towns[u - 1].nodes.append(towns[v - 1]) towns[v - 1].nodes.append(towns[u - 1]) i += 1 st = input().split() for t in st: towns[int(t) - 1].a = True min_p = 123457 min_id = 123457 for v in towns: if len(v.nodes) == 1: res = dfs(v, 0) if res < min_p: min_p = res min_id = v.id print(min_id, min_p, sep='\n') ```
MatrixStudio/Codeforces-Python-Submissions
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point *x*(*x*<=&gt;<=0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order to get to his friend's house.
```python x= int(input()) if x < 6: print(1) else: if x%5 == 0: print((x//5)) else: print((x//5)+1) ```
MatrixStudio/Codeforces-Python-Submissions
DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter *c* DZY knows its value *w**c*. For each special string *s*<==<=*s*1*s*2... *s*|*s*| (|*s*| is the length of the string) he represents its value with a function *f*(*s*), where Now DZY has a string *s*. He wants to insert *k* lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get?
```python s = input() k = eval(input()) d = {} n = input() lst = n.split() for x in range(ord('a'), ord('z') + 1): d[chr(x)] = lst[x-ord('a')] a = 0 j = 1 for i in s: a = j*int(d[i]) + a j=j+1 a = int(d[max(d, key = d.get)])*k*(len(s) + (k+1)/2) + a print(int(a)) ```
MatrixStudio/Codeforces-Python-Submissions
Merge sort is a well-known sorting algorithm. The main function that sorts the elements of array *a* with indices from [*l*,<=*r*) can be implemented as follows: 1. If the segment [*l*,<=*r*) is already sorted in non-descending order (that is, for any *i* such that *l*<=≤<=*i*<=&lt;<=*r*<=-<=1 *a*[*i*]<=≤<=*a*[*i*<=+<=1]), then end the function call; 1. Let ; 1. Call *mergesort*(*a*,<=*l*,<=*mid*); 1. Call *mergesort*(*a*,<=*mid*,<=*r*); 1. Merge segments [*l*,<=*mid*) and [*mid*,<=*r*), making the segment [*l*,<=*r*) sorted in non-descending order. The merge algorithm doesn't call any other functions. The array in this problem is 0-indexed, so to sort the whole array, you need to call *mergesort*(*a*,<=0,<=*n*). The number of calls of function *mergesort* is very important, so Ivan has decided to calculate it while sorting the array. For example, if *a*<==<={1,<=2,<=3,<=4}, then there will be 1 call of *mergesort* — *mergesort*(0,<=4), which will check that the array is sorted and then end. If *a*<==<={2,<=1,<=3}, then the number of calls is 3: first of all, you call *mergesort*(0,<=3), which then sets *mid*<==<=1 and calls *mergesort*(0,<=1) and *mergesort*(1,<=3), which do not perform any recursive calls because segments (0,<=1) and (1,<=3) are sorted. Ivan has implemented the program that counts the number of *mergesort* calls, but now he needs to test it. To do this, he needs to find an array *a* such that *a* is a permutation of size *n* (that is, the number of elements in *a* is *n*, and every integer number from [1,<=*n*] can be found in this array), and the number of *mergesort* calls when sorting the array is exactly *k*. Help Ivan to find an array he wants!
```python n, k = map(int, input().split()) if k > n: print("-1") elif k == 1: print(*list(range(1, n+1))) else: l = list(range(1, n+1)) print(*(sorted(l[:k-1], reverse = True)+l[k-1:])) ```
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 is different in evenness.
```python import sys my_file = sys.stdin #my_file = open("input.txt", "r") n = int(my_file.readline()) a = [int(i) for i in my_file.readline().strip().split()] even = 0 odd = 0 for i in range(n): if a[i]%2 == 0: even += 1 if even == 2: break if even == 2: for i in range(n): if a[i]%2 != 0: print(i+1) break else: for i in range(n): if a[i]%2 == 0: print(i+1) break ```
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 two squares. 2. No two dominoes overlap. 3. Each domino lies entirely inside the board. It is allowed to touch the edges of the board. Find the maximum number of dominoes, which can be placed under these restrictions.
```python nums = list(int(input('arr :'))) multi = nums[0] * nums[1] print (multi // 2) ```
MatrixStudio/Codeforces-Python-Submissions
Mr. Santa asks all the great programmers of the world to solve a trivial problem. He gives them an integer *m* and asks for the number of positive integers *n*, such that the factorial of *n* ends with exactly *m* zeroes. Are you among those great programmers who can solve this problem?
```python def factorial(n): m = n while n>1: n -= 1 m = m*n return m zeros = int(input()) x = 10**zeros flag = True counter = 0 n = zeros*5 #print(n) for i in range(n): i += 1 if i%78125 == 0: n-=35 elif i%(5**6) == 0: n-=25 elif i%(5**5) == 0: n-=20 elif i%(5**4) == 0: n-=15 elif i%(5**3) == 0: n-=10 elif i%(5**2) == 0: n-=5 #print(i,n) answers = [] while flag: if factorial(n)%(x*10) == 0: flag = False elif factorial(n)%x == 0: counter += 1 answers.append(str(n)) n += 1 print(counter) print(" ".join(answers)) ```
MatrixStudio/Codeforces-Python-Submissions
Due to the increase in the number of students of Berland State University it was decided to equip a new computer room. You were given the task of buying mouses, and you have to spend as little as possible. After all, the country is in crisis! The computers bought for the room were different. Some of them had only USB ports, some — only PS/2 ports, and some had both options. You have found a price list of a certain computer shop. In it, for *m* mouses it is specified the cost and the type of the port that is required to plug the mouse in (USB or PS/2). Each mouse from the list can be bought at most once. You want to buy some set of mouses from the given price list in such a way so that you maximize the number of computers equipped with mouses (it is not guaranteed that you will be able to equip all of the computers), and in case of equality of this value you want to minimize the total cost of mouses you will buy.
```python usb=[] ps=[] nc=0 pr=0 s=input() s=s.split() u=int(s[0]) p=int(s[1]) up=int(s[2]) m=int(input()) for i in range(m): b=input() b=b.split() pri=int(b[0]) ty=b[1] if ty=='USB': usb.append(pri) else: ps.append(pri) usb.sort() ps.sort() if len(usb)<=u: pr+=sum(usb) nc+=len(usb) k1=[] else: for t in range(u): pr+=usb[t] #itll take the values till u-1 and values from u to len-1 r still not taken nc+=1 k1=usb[u:len(usb)] if len(ps)<=p: pr+=sum(ps) nc+=len(ps) k2=[] else: for h in range(p): pr+=ps[h] #itll take the values till p-1 and values from u to len-1 r still not taken nc+=1 k2=ps[p:len(ps)] k=k1+k2 k.sort() #print('usb:',usb) #print('ps:',ps) #print('NC=',nc,'PR=',pr) #print(k) if len(k)<=up: pr+=sum(k) nc+=len(k) else: for g in range(up): pr+=k[g] #itll take the values till u-1 and values from u to len-1 r still not taken nc+=1 ans=str(nc)+' '+str(pr) print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
You are given a rectangular cake, represented as an *r*<=×<=*c* grid. Each cell either has an evil strawberry, or is empty. For example, a 3<=×<=4 cake may look as follows: The cakeminator is going to eat the cake! Each time he eats, he chooses a row or a column that does not contain any evil strawberries and contains at least one cake cell that has not been eaten before, and eats all the cake cells there. He may decide to eat any number of times. Please output the maximum number of cake cells that the cakeminator can eat.
```python b = input().split() m = int(b[0]) n = int(b[1]) st = [] sr = [] for i in range(m): g = input() for j in range(n): if g[j] == 'S': st.append(i) sr.append(j) break n1 = len(sr) m1 = len(st) sum = (m - m1) * n + (n-n1) * m1 print(st,sr,sum) ```
MatrixStudio/Codeforces-Python-Submissions
Kyoya Ootori is selling photobooks of the Ouran High School Host Club. He has 26 photos, labeled "a" to "z", and he has compiled them into a photo booklet with some photos in some order (possibly with some photos being duplicated). A photo booklet can be described as a string of lowercase letters, consisting of the photos in the booklet in order. He now wants to sell some "special edition" photobooks, each with one extra photo inserted anywhere in the book. He wants to make as many distinct photobooks as possible, so he can make more money. He asks Haruhi, how many distinct photobooks can he make by inserting one extra photo into the photobook he already has? Please help Haruhi solve this problem.
```python l = len(input()) print((l+1)*26 - l) ```
MatrixStudio/Codeforces-Python-Submissions
Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. For example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. When a team plays as a guest on somebody else's stadium, the players put on the guest uniform. The only exception to that rule is: when the home uniform color of the host team matches the guests' uniform, the host team puts on its guest uniform as well. For each team the color of the home and guest uniform is different. There are *n* teams taking part in the national championship. The championship consists of *n*·(*n*<=-<=1) games: each team invites each other team to its stadium. At this point Manao wondered: how many times during the championship is a host team going to put on the guest uniform? Note that the order of the games does not affect this number. You know the colors of the home and guest uniform for each team. For simplicity, the colors are numbered by integers in such a way that no two distinct colors have the same number. Help Manao find the answer to his question.
```python n=int(input()) x,y=zip(*[input().split() for i in ' '*n]) print(sum([x.count(i) for i in y])) ```
MatrixStudio/Codeforces-Python-Submissions
Squirrel Liss loves nuts. There are *n* trees (numbered 1 to *n* from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree *i* is *h**i*. Liss wants to eat all nuts. Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions: - Walk up or down one unit on a tree. - Eat a nut on the top of the current tree. - Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height *h* of the tree *i* (1<=≤<=*i*<=≤<=*n*<=-<=1), she jumps to height *h* of the tree *i*<=+<=1. This action can't be performed if *h*<=&gt;<=*h**i*<=+<=1. Compute the minimal time (in seconds) required to eat all nuts.
```python n = int(input()) height = [] temp = n while temp > 0: height.append(int(input())) temp -= 1 eat = n jump = n-1 ud = height[0] for i in range(n-1): ud += abs(height[i] - height[i+1]) print(ud + eat + jump) ```
MatrixStudio/Codeforces-Python-Submissions
There are *n* cities and *n*<=-<=1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link [https://en.wikipedia.org/wiki/Expected_value](https://en.wikipedia.org/wiki/Expected_value).
```python import collections def LI(): return list(map(int, input().split())) def I(): return int(input()) def solve(): n = I() g = {i: collections.deque() for i in range(n)} for i in range(1, n): u, v = LI() u, v = u - 1, v - 1 g[u].append(v) g[v].append(u) dp = [0] * n def dfs(u: int, f: int): son = 0 for v in g[u]: if v == f: continue dfs(v, u) son += 1 dp[u] += dp[v] + 1 if son: dp[u] /= son dfs(0, 0) print("{0:.7f}".format(dp[0])) solve() ```
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 like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes. Thus, "localization" will be spelt as "l10n", and "internationalization» will be spelt as "i18n". You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.
```python word = input() n = len(word) if n > 10: print(word[0], n, word[n-1],sep="") else: print(word) ```
MatrixStudio/Codeforces-Python-Submissions
Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10*k*. In the given number of *n* Polycarp wants to remove the least number of digits to get a number that is divisible by 10*k*. For example, if *k*<==<=3, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by 103<==<=1000. Write a program that prints the minimum number of digits to be deleted from the given integer number *n*, so that the result is divisible by 10*k*. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit). It is guaranteed that the answer exists.
```python def solve(): if n == '0': return 0 cur = 0 for i in range(len(n) - 1, -1, -1): if n[i] == '0': cur += 1 if cur == k: return (len(n) - i - k) return len(n) - 1 read = lambda: map(int, input().split()) n, k = read() n = str(n) print(solve()) ```
MatrixStudio/Codeforces-Python-Submissions
Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they are not under its influence. He has names of *n* people who possessed the diary in order. You need to tell, for each person, if he/she possessed the diary at some point before or not. Formally, for a name *s**i* in the *i*-th line, output "YES" (without quotes) if there exists an index *j* such that *s**i*<==<=*s**j* and *j*<=&lt;<=*i*, otherwise, output "NO" (without quotes).
```python number_of_names = int(input()) # Number of names names = set(["lucius", "ginny", "harry"]) # Initialize the set with specific names for i in range(number_of_names): name = input().lower() # Convert the name to lowercase for case-insensitive comparison if name in names: print("YES") else: print("NO") names.add(name) ```
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* people living in it and the room can accommodate *q**i* people in total (*p**i*<=≤<=*q**i*). Your task is to count how many rooms has free place for both George and Alex.
```python num = int(input()) count = 0 for i in range(num): num1,num2 = map(int,input().split()) if(num1+2 <= num2): count +=1 print(count) ```
MatrixStudio/Codeforces-Python-Submissions
We'll define *S*(*n*) for positive integer *n* as follows: the number of the *n*'s digits in the decimal base. For example, *S*(893)<==<=3, *S*(114514)<==<=6. You want to make a consecutive integer sequence starting from number *m* (*m*,<=*m*<=+<=1,<=...). But you need to pay *S*(*n*)·*k* to add the number *n* to the sequence. You can spend a cost up to *w*, and you want to make the sequence as long as possible. Write a program that tells sequence's maximum length.
```python def S(n): lista = [number for number in str(n)] return len(lista) line = input() numbers = line.split(" ") numbers = [int(x) for x in numbers] w = numbers[0] m = numbers[1] k = numbers[2] output = 0 while w > 0: if w - S(m)*k > 0: w -= S(m)*k else: break m += 1 output += 1 print(output) ```
MatrixStudio/Codeforces-Python-Submissions
There is a straight snowy road, divided into *n* blocks. The blocks are numbered from 1 to *n* from left to right. If one moves from the *i*-th block to the (*i*<=+<=1)-th block, he will leave a right footprint on the *i*-th block. Similarly, if one moves from the *i*-th block to the (*i*<=-<=1)-th block, he will leave a left footprint on the *i*-th block. If there already is a footprint on the *i*-th block, the new footprint will cover the old one. At the beginning, there were no footprints. Then polar bear Alice starts from the *s*-th block, makes a sequence of moves and ends in the *t*-th block. It is known that Alice never moves outside of the road. You are given the description of Alice's footprints. Your task is to find a pair of possible values of *s*,<=*t* by looking at the footprints.
```python a=int(input()) b=list(input()) print((a-b.count('R')),(a.b.count('L'))) ```
MatrixStudio/Codeforces-Python-Submissions
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network. But yesterday, he came to see "her" in the real world and found out "she" is actually a very strong man! Our hero is very sad and he is too tired to love again now. So he came up with a way to recognize users' genders by their user names. This is his method: if the number of distinct characters in one's user name is odd, then he is a male, otherwise she is a female. You are given the string that denotes the user name, please help our hero to determine the gender of this user by his method.
```python if len(input()) % 2 == 0 print("CHAT WITH HER!") else print("IGNORE HIM!") ```
MatrixStudio/Codeforces-Python-Submissions
Polycarpus has a ribbon, its length is *n*. He wants to cut the ribbon in a way that fulfils the following two conditions: - After the cutting each ribbon piece should have length *a*, *b* or *c*. - After the cutting the number of ribbon pieces should be maximum. Help Polycarpus and find the number of ribbon pieces after the required cutting.
```python n, a, b, c = map(int, input().split()) dp = [0]*(n+1) for i in range(n+1): if i==0 or dp[i]: if i+a<=n: dp[i+a] = dp[i]+1 if i+c<=n: dp[i+c] = dp[i]+1 if i+b<=n: dp[i+b] = dp[i]+1 print(dp[n]) ```
MatrixStudio/Codeforces-Python-Submissions
You are given a tree with *n* vertexes and *n* points on a plane, no three points lie on one straight line. Your task is to paint the given tree on a plane, using the given points as vertexes. That is, you should correspond each vertex of the tree to exactly one point and each point should correspond to a vertex. If two vertexes of the tree are connected by an edge, then the corresponding points should have a segment painted between them. The segments that correspond to non-adjacent edges, should not have common points. The segments that correspond to adjacent edges should have exactly one common point.
```python print("_RANDOM_GUESS_1692431221.2318246")# 1692431221.231841 ```
MatrixStudio/Codeforces-Python-Submissions
Vasya learns to type. He has an unusual keyboard at his disposal: it is rectangular and it has *n* rows of keys containing *m* keys in each row. Besides, the keys are of two types. Some of the keys have lowercase Latin letters on them and some of the keys work like the "Shift" key on standard keyboards, that is, they make lowercase letters uppercase. Vasya can press one or two keys with one hand. However, he can only press two keys if the Euclidean distance between the centers of the keys does not exceed *x*. The keys are considered as squares with a side equal to 1. There are no empty spaces between neighbouring keys. Vasya is a very lazy boy, that's why he tries to type with one hand as he eats chips with his other one. However, it is possible that some symbol can't be typed with one hand only, because the distance between it and the closest "Shift" key is strictly larger than *x*. In this case he will have to use his other hand. Having typed the symbol, Vasya returns other hand back to the chips. You are given Vasya's keyboard and the text. Count the minimum number of times Vasya will have to use the other hand.
```python from math import floor def gcd(x, y): if y == 0: return x return gcd(y, x % y) # ======================================================= n, m, x = map(int, input().split(" ")) keyboard = [] d = {} for i in range(n): keyboard.append(input()) for j in range(m): if keyboard[i][j] in d: #print(d.get(keyboard[i][j])) d.get(keyboard[i][j]).append([i, j]) else: d.__setitem__(keyboard[i][j], [[i, j]]) q = int(input()) word = input() ans = 0 x = x * x for i in range(q): found = False if word[i:i+1].lower() in d: if word[i:i+1].isupper(): for c_index in d.get(word[i:i+1].lower()): if 'S' in d: for s_index in d.get('S'): if pow(c_index[0] - s_index[0], 2) + pow(c_index[1] - s_index[1], 2) <= x: found = True break if found: break else: print(-1) exit(0) if not found: ans += 1 else: print(-1) exit(0) print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
After finishing eating her bun, Alyona came up with two integers *n* and *m*. She decided to write down two columns of integers — the first column containing integers from 1 to *n* and the second containing integers from 1 to *m*. Now the girl wants to count how many pairs of integers she can choose, one from the first column and the other from the second column, such that their sum is divisible by 5. Formally, Alyona wants to count the number of pairs of integers (*x*,<=*y*) such that 1<=≤<=*x*<=≤<=*n*, 1<=≤<=*y*<=≤<=*m* and equals 0. As usual, Alyona has some troubles and asks you to help.
```python a=0 t=0 c,x=map(int,input().split()) a=x//5 #print('a=',a) if x%5==0: print(a*c) elif a==0: print(int((c/5)*x)) else: lst=list(range((a*5)+1,x+1)) #print('lst=',lst) for z in lst: # print('z=',z) e=5-(z%5) # print('e=',e) while e<=c : t+=1 e+=5 # print('t=',t) # print('eeeeeee=',e) print((a*c)+t) ```
MatrixStudio/Codeforces-Python-Submissions
There is a rectangular grid of size $n \times m$. Each cell has a number written on it; the number on the cell ($i, j$) is $a_{i, j}$. Your task is to calculate the number of paths from the upper-left cell ($1, 1$) to the bottom-right cell ($n, m$) meeting the following constraints: - You can move to the right or to the bottom only. Formally, from the cell ($i, j$) you may move to the cell ($i, j + 1$) or to the cell ($i + 1, j$). The target cell can't be outside of the grid. - The xor of all the numbers on the path from the cell ($1, 1$) to the cell ($n, m$) must be equal to $k$ (xor operation is the bitwise exclusive OR, it is represented as '^' in Java or C++ and "xor" in Pascal). Find the number of such paths in the given grid.
```python n, m, k = map(int, input().split()) a = [list(map(int, input().split())) for i in range(n)] ma = {} n1 = (n + m - 2) // 2 for mask in range(1 << n1): s, x, y = 0, 0, 0 for i in range(n1): if not(0 <= x < n and 0 <= y < m): break s ^= a[x][y] if (mask >> i) & 1: x += 1 else: y += 1 else: if not(0 <= x < n and 0 <= y < m): continue s ^= a[x][y] ma[(x, y)] = ma.get((x, y), set()) | {s} rez = 0 n2 = n + m - 2 - n1 for mask in range(1 << n2): s, x, y = 0, n-1, m-1 for i in range(n2): if not(0 <= x < n and 0 <= y < m): break s ^= a[x][y] if (mask >> i) & 1: x -= 1 else: y -= 1 else: if not(0 <= x < n and 0 <= y < m): continue if s ^ k in ma[(x, y)]: rez += 1 print(rez) # Mon Dec 14 2020 22:02:50 GMT+0300 (Москва, стандартное время) ```
MatrixStudio/Codeforces-Python-Submissions
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of *n* students (including Valera). This contest was an individual competition, so each student in the team solved problems individually. After the contest was over, Valera was interested in results. He found out that: - each student in the team scored at least *l* points and at most *r* points; - in total, all members of the team scored exactly *s**all* points; - the total score of the *k* members of the team who scored the most points is equal to exactly *s**k*; more formally, if *a*1,<=*a*2,<=...,<=*a**n* is the sequence of points earned by the team of students in the non-increasing order (*a*1<=≥<=*a*2<=≥<=...<=≥<=*a**n*), then *s**k*<==<=*a*1<=+<=*a*2<=+<=...<=+<=*a**k*. However, Valera did not find out exactly how many points each of *n* students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
```python from collections import deque n , k , l , r , st , sk = map(int,input().split()) d = deque() if (sk % k == 0): for i in range(k): d.append(sk // k) rem = st - sk nums = n - k if (rem % nums == 0): for i in range(nums): d.append(rem // nums) else: v = nums sm = 0 for j in range(nums): if (v != 1 ): d.append(l) v -=1 sm += l else: d.append(rem - sm) else: r1 = sk // k r2 = k * r1 r3 = sk - r2 d.append(r3+r1) for i in range(k - 1): d.append(r1) rem = st - sk nums = n - k if (rem % nums == 0): for i in range(nums): d.append(rem // nums) else: v = nums sm = 0 for j in range(nums): if (v != 1 ): d.append(l) v -=1 sm += l else: d.append(rem - sm) #print(d) for i in d : print(i , end = ' ') ```
MatrixStudio/Codeforces-Python-Submissions
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line. Unfortunately, from time to time Anton would forget writing some letter and write it again. He asks you to count the total number of distinct letters in his set.
```python input_string = input() letters = input_string.split(", ") set_of_letters = set(letters) print(len(set_of_letters)) ```
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, and each piece contains positive integer amount of squares. Would you help Bob solve this problem?
```python input() ans =0 arr = list(map(int,input().split())) for i in range(len(arr)-1): temp = sum(arr[:i+1]) temp2 = sum(arr[i+1:]) if temp ==temp2: ans +=1 print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line. Unfortunately, from time to time Anton would forget writing some letter and write it again. He asks you to count the total number of distinct letters in his set.
```python print(len(set(map(str,input()[1:-1].split(','))))) ```
MatrixStudio/Codeforces-Python-Submissions
Pasha decided to invite his friends to a tea party. For that occasion, he has a large teapot with the capacity of *w* milliliters and 2*n* tea cups, each cup is for one of Pasha's friends. The *i*-th cup can hold at most *a**i* milliliters of water. It turned out that among Pasha's friends there are exactly *n* boys and exactly *n* girls and all of them are going to come to the tea party. To please everyone, Pasha decided to pour the water for the tea as follows: - Pasha can boil the teapot exactly once by pouring there at most *w* milliliters of water; - Pasha pours the same amount of water to each girl; - Pasha pours the same amount of water to each boy; - if each girl gets *x* milliliters of water, then each boy gets 2*x* milliliters of water. In the other words, each boy should get two times more water than each girl does. Pasha is very kind and polite, so he wants to maximize the total amount of the water that he pours to his friends. Your task is to help him and determine the optimum distribution of cups between Pasha's friends.
```python p=input().split() n=int(p[0]) w=int(p[1]) q=input().split() a=[] s=0 for i in range(2*n): a.append(int(q[i])) a.sort() if a[n]>=2*a[0]: s=n*a[0]+n*2*a[0] else: s=n*a[n]+n*(a[n]/2) if s>w: print(w) else: print(s) ```
MatrixStudio/Codeforces-Python-Submissions
So, the New Year holidays are over. Santa Claus and his colleagues can take a rest and have guests at last. When two "New Year and Christmas Men" meet, thear assistants cut out of cardboard the letters from the guest's name and the host's name in honor of this event. Then the hung the letters above the main entrance. One night, when everyone went to bed, someone took all the letters of our characters' names. Then he may have shuffled the letters and put them in one pile in front of the door. The next morning it was impossible to find the culprit who had made the disorder. But everybody wondered whether it is possible to restore the names of the host and his guests from the letters lying at the door? That is, we need to verify that there are no extra letters, and that nobody will need to cut more letters. Help the "New Year and Christmas Men" and their friends to cope with this problem. You are given both inscriptions that hung over the front door the previous night, and a pile of letters that were found at the front door next morning.
```python a = input() b = input() c = input() missing_list = [] achive_words = a+b for i in achive_words : if i in c: c = c.replace(i,"",1) else: missing_list.append(i) if len(c) > 0 or len(missing_list)> 0 : print("NO") else: print("Yes") ```
MatrixStudio/Codeforces-Python-Submissions
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If there are at least 7 players of some team standing one after another, then the situation is considered dangerous. For example, the situation 00100110111111101 is dangerous and 11110111011101 is not. You are given the current situation. Determine whether it is dangerous or not.
```python s = input() count = 1 last_char = s[0] dangerous = False for i in range(1, len(s)): if s[i] == last_char: count += 1 if count >= 7: dangerous = True break else: count = 1 last_char = s[i] if dangerous: print("YES") else: print("NO") ```
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 that as little as possible letters should be changed in the word. For example, the word HoUse must be replaced with house, and the word ViP — with VIP. If a word contains an equal number of uppercase and lowercase letters, you should replace all the letters with lowercase ones. For example, maTRIx should be replaced by matrix. Your task is to use the given method on one given word.
```python s = input() upper = 0 for i in s: if i.upper() == i: upper += 1 else: continue if upper > len(s)-upper: print(s.upper()) else: print(s.lower()) ```
MatrixStudio/Codeforces-Python-Submissions
Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are *n* drinks in his fridge, the volume fraction of orange juice in the *i*-th drink equals *p**i* percent. One day Vasya decided to make himself an orange cocktail. He took equal proportions of each of the *n* drinks and mixed them. Then he wondered, how much orange juice the cocktail has. Find the volume fraction of orange juice in the final drink.
```python n=int(input()) s=list(map(int, input().split(' '))) sum=0 for i in range(n): sum+=s[i] print(sum/n) ```
MatrixStudio/Codeforces-Python-Submissions
A group of university students wants to get to the top of a mountain to have a picnic there. For that they decided to use a cableway. A cableway is represented by some cablecars, hanged onto some cable stations by a cable. A cable is scrolled cyclically between the first and the last cable stations (the first of them is located at the bottom of the mountain and the last one is located at the top). As the cable moves, the cablecar attached to it move as well. The number of cablecars is divisible by three and they are painted three colors: red, green and blue, in such manner that after each red cablecar goes a green one, after each green cablecar goes a blue one and after each blue cablecar goes a red one. Each cablecar can transport no more than two people, the cablecars arrive with the periodicity of one minute (i. e. every minute) and it takes exactly 30 minutes for a cablecar to get to the top. All students are divided into three groups: *r* of them like to ascend only in the red cablecars, *g* of them prefer only the green ones and *b* of them prefer only the blue ones. A student never gets on a cablecar painted a color that he doesn't like, The first cablecar to arrive (at the moment of time 0) is painted red. Determine the least time it will take all students to ascend to the mountain top.
```python r,g,b= list(map(int, input().split(" "))) r = ((r+1)/2-1)* 3 + 30 g = ((g+1)/2-1)* 3 + 31 b = ((b+1)/2-1)* 3 + 32 print(int(max(r,g,b))) ```
MatrixStudio/Codeforces-Python-Submissions
To make a paper airplane, one has to use a rectangular piece of paper. From a sheet of standard size you can make $s$ airplanes. A group of $k$ people decided to make $n$ airplanes each. They are going to buy several packs of paper, each of them containing $p$ sheets, and then distribute the sheets between the people. Each person should have enough sheets to make $n$ airplanes. How many packs should they buy?
```python import math k, s ,n,p = map(int, input().split()) f=math.ceil(((math.ceil(s/n))*k)/p) print(f) ```
MatrixStudio/Codeforces-Python-Submissions
Yet another Armageddon is coming! This time the culprit is the Julya tribe calendar. The beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows: "May the Great Beaver bless you! May your chacres open and may your third eye never turn blind from beholding the Truth! Take the magic number, subtract a digit from it (the digit must occur in the number) and get a new magic number. Repeat this operation until a magic number equals zero. The Earth will stand on Three Beavers for the time, equal to the number of subtractions you perform!" Distinct subtraction sequences can obviously get you different number of operations. But the Smart Beaver is ready to face the worst and is asking you to count the minimum number of operations he needs to reduce the magic number to zero.
```python n = int(input()) ans = 0 while n>0: i = n s = 0 while i>0: s = max(s,i%10) i=i//10 ans+=1 n-=s print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,<=1]. Next, *n* stones will fall and Liss will escape from the stones. The stones are numbered from 1 to *n* in order. The stones always fall to the center of Liss's interval. When Liss occupies the interval [*k*<=-<=*d*,<=*k*<=+<=*d*] and a stone falls to *k*, she will escape to the left or to the right. If she escapes to the left, her new interval will be [*k*<=-<=*d*,<=*k*]. If she escapes to the right, her new interval will be [*k*,<=*k*<=+<=*d*]. You are given a string *s* of length *n*. If the *i*-th character of *s* is "l" or "r", when the *i*-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the *n* stones falls.
```python s = input() s = list(s) a = [0]*len(s) i = 0 j = len(s)-1 for ij in range(len(s)): if(s[ij]=='r'): a[i]=ij+1 i+=1 else: a[j]=ij+1 j-=1 for i in a: print(i) ```
MatrixStudio/Codeforces-Python-Submissions
In the city of Ultima Thule job applicants are often offered an IQ test. The test is as follows: the person gets a piece of squared paper with a 4<=×<=4 square painted on it. Some of the square's cells are painted black and others are painted white. Your task is to repaint at most one cell the other color so that the picture has a 2<=×<=2 square, completely consisting of cells of the same color. If the initial picture already has such a square, the person should just say so and the test will be completed. Your task is to write a program that determines whether it is possible to pass the test. You cannot pass the test if either repainting any cell or no action doesn't result in a 2<=×<=2 square, consisting of cells of the same color.
```python def read_multi_dimensional_array(dimension): return [[int(item) for item in input().split(" ")] for j in range(dimension)] def iq_test(array): for i in range(3): for j in range(3): if int(array[i][j] == "#") + int(array[i][j + 1] == "#") \ + int(array[i + 1][j] == "#") + int(array[i + 1][j + 1] == "#") >= 3: print("YES") return print("NO") array = [[item for item in input()] for j in range(4)] iq_test(array) ```
MatrixStudio/Codeforces-Python-Submissions
Some natural number was written on the board. Its sum of digits was not less than *k*. But you were distracted a bit, and someone changed this number to *n*, replacing some digits with others. It's known that the length of the number didn't change. You have to find the minimum number of digits in which these two numbers can differ.
```python k = int(input()) n = [int(i) for i in input()] cs=0 for i in n: cs+=i n.sort() v = k-cs res = 0 for i in n: if v<=0: break else: v-=(9-i) res+=1 print(res) ```
MatrixStudio/Codeforces-Python-Submissions
You took a peek on Thanos wearing Infinity Gauntlet. In the Gauntlet there is a place for six Infinity Gems: - the Power Gem of purple color, - the Time Gem of green color, - the Space Gem of blue color, - the Soul Gem of orange color, - the Reality Gem of red color, - the Mind Gem of yellow color. Using colors of Gems you saw in the Gauntlet determine the names of absent Gems.
```python dicc={'purple':'Power','green':'Time','blue':'Space','orange':'Soul','red':'Reality','yellow':'Mind'} user=int(input()) for i in range(user): user2=input() dicc.pop(user2) print(len(dicc)) for i,j in dicc.items(): print(j) ```