source
stringclasses
3 values
instruction
stringlengths
23
3.97k
input
stringclasses
1 value
output
stringlengths
1
3.75k
MatrixStudio/Codeforces-Python-Submissions
Today, Wet Shark is given *n* integers. Using any of these integers no more than once, Wet Shark wants to get maximum possible even (divisible by 2) sum. Please, calculate this value for Wet Shark. Note, that if Wet Shark uses no integers from the *n* integers, the sum is an even integer 0.
```python # Wet Shark and Odd and Even def big_boi_sum(arr): ini = sum(arr) if ini % 2 == 0: return ini eve = [] odd = [] for i in arr: if i % 2 == 0: eve.append(i) else: odd.append(i) if sum(odd) % 2 != 0: odd.remove(min(odd)) fin = sum(eve + odd) return fin n = int(input()) arr = list(map(int, input().rstrip().split())) print(big_boi_sum(arr)) ```
MatrixStudio/Codeforces-Python-Submissions
Permutation *p* is an ordered set of integers *p*1,<=<=*p*2,<=<=...,<=<=*p**n*, consisting of *n* distinct positive integers, each of them doesn't exceed *n*. We'll denote the *i*-th element of permutation *p* as *p**i*. We'll call number *n* the size or the length of permutation *p*1,<=<=*p*2,<=<=...,<=<=*p**n*. The decreasing coefficient of permutation *p*1,<=*p*2,<=...,<=*p**n* is the number of such *i* (1<=≤<=*i*<=&lt;<=*n*), that *p**i*<=&gt;<=*p**i*<=+<=1. You have numbers *n* and *k*. Your task is to print the permutation of length *n* with decreasing coefficient *k*.
```python import sys def input(): return sys.stdin.readline().strip() def iinput(): return int(input()) def rinput(): return map(int, sys.stdin.readline().strip().split()) def get_list(): return list(map(int, sys.stdin.readline().strip().split())) n,k=rinput() a=[] for i in range(n,n-k,-1): a.append(i) for i in range(1,n-k+1): a.append(i) print(*a) ```
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 n=int(input()) for i in range(n): str=input() k=len(str) if len(str)<10: print(str) elif len(str)>10: print(str[0]+str(len(str)-2)+str[k-1]) ```
MatrixStudio/Codeforces-Python-Submissions
Arpa is researching the Mexican wave. There are *n* spectators in the stadium, labeled from 1 to *n*. They start the Mexican wave at time 0. - At time 1, the first spectator stands. - At time 2, the second spectator stands. - ... - At time *k*, the *k*-th spectator stands. - At time *k*<=+<=1, the (*k*<=+<=1)-th spectator stands and the first spectator sits. - At time *k*<=+<=2, the (*k*<=+<=2)-th spectator stands and the second spectator sits. - ... - At time *n*, the *n*-th spectator stands and the (*n*<=-<=*k*)-th spectator sits. - At time *n*<=+<=1, the (*n*<=+<=1<=-<=*k*)-th spectator sits. - ... - At time *n*<=+<=*k*, the *n*-th spectator sits. Arpa wants to know how many spectators are standing at time *t*.
```python n,k,t=map(int,input().split()) if(t<=k): print(t) if(k<=t<=n): print(k) if(n<=t<n+k): print(n+k-t) ```
MatrixStudio/Codeforces-Python-Submissions
Uncle Fyodor, Matroskin the Cat and Sharic the Dog live their simple but happy lives in Prostokvashino. Sometimes they receive parcels from Uncle Fyodor’s parents and sometimes from anonymous benefactors, in which case it is hard to determine to which one of them the package has been sent. A photographic rifle is obviously for Sharic who loves hunting and fish is for Matroskin, but for whom was a new video game console meant? Every one of the three friends claimed that the present is for him and nearly quarreled. Uncle Fyodor had an idea how to solve the problem justly: they should suppose that the console was sent to all three of them and play it in turns. Everybody got relieved but then yet another burning problem popped up — who will play first? This time Matroskin came up with a brilliant solution, suggesting the most fair way to find it out: play rock-paper-scissors together. The rules of the game are very simple. On the count of three every player shows a combination with his hand (or paw). The combination corresponds to one of three things: a rock, scissors or paper. Some of the gestures win over some other ones according to well-known rules: the rock breaks the scissors, the scissors cut the paper, and the paper gets wrapped over the stone. Usually there are two players. Yet there are three friends, that’s why they decided to choose the winner like that: If someone shows the gesture that wins over the other two players, then that player wins. Otherwise, another game round is required. Write a program that will determine the winner by the gestures they have shown.
```python F, M, S = input(), input(), input() if len({F, M, S}) != 2: print("?") else: lst = [F, M, S] for x in [("rock","scissors"), ("scissors", "paper"), ("paper", "rock")]: if lst.count(x[0]) == 1 and lst.count(x[1]) == 2: print("FMS"[lst.index(x[0])]) break else: print("?") ```
MatrixStudio/Codeforces-Python-Submissions
Johnny has a younger sister Anne, who is very clever and smart. As she came home from the kindergarten, she told his brother about the task that her kindergartener asked her to solve. The task was just to construct a triangle out of four sticks of different colours. Naturally, one of the sticks is extra. It is not allowed to break the sticks or use their partial length. Anne has perfectly solved this task, now she is asking Johnny to do the same. The boy answered that he would cope with it without any difficulty. However, after a while he found out that different tricky things can occur. It can happen that it is impossible to construct a triangle of a positive area, but it is possible to construct a degenerate triangle. It can be so, that it is impossible to construct a degenerate triangle even. As Johnny is very lazy, he does not want to consider such a big amount of cases, he asks you to help him.
```python a = sorted([int(i) for i in input().split()]) res = "IMPOSSIBLE" for i in range(2): if a[i] + a[i+1] > a[i+2] : res = "TRIANGLE"; break if res == "IMPOSSIBLE" : for i in range(2): if i == 1 : if a[i] + a[i+1] == a[i+2] : res = "SEGMENT"; break continue if a[i] + a[i+1] == a[i+2] or a[i] + a[i+1] == a[i+3]: res = "SEGMENT"; break print(res) ```
MatrixStudio/Codeforces-Python-Submissions
Pasha got a very beautiful string *s* for his birthday, the string consists of lowercase Latin letters. The letters in the string are numbered from 1 to |*s*| from left to right, where |*s*| is the length of the given string. Pasha didn't like his present very much so he decided to change it. After his birthday Pasha spent *m* days performing the following transformations on his string — each day he chose integer *a**i* and reversed a piece of string (a segment) from position *a**i* to position |*s*|<=-<=*a**i*<=+<=1. It is guaranteed that 2·*a**i*<=≤<=|*s*|. You face the following task: determine what Pasha's string will look like after *m* days.
```python a=input() b=input() c=list(map(int, input().split())) for i in c: a=a.replace(a[i-1:len(a)-i+1],a[i-1:len(a)-i+1][::-1]) print(a) ```
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 s = input() l = s.split(',') t=list(l) x = set(t) count = len(x) print(f"{count}") ```
MatrixStudio/Codeforces-Python-Submissions
The Little Elephant loves Ukraine very much. Most of all he loves town Rozdol (ukr. "Rozdil"). However, Rozdil is dangerous to settle, so the Little Elephant wants to go to some other town. The Little Elephant doesn't like to spend much time on travelling, so for his journey he will choose a town that needs minimum time to travel to. If there are multiple such cities, then the Little Elephant won't go anywhere. For each town except for Rozdil you know the time needed to travel to this town. Find the town the Little Elephant will go to or print "Still Rozdil", if he stays in Rozdil.
```python n = int(input()) cd = [int(x) for x in input().split(" ")] min_count = 1 min = 0 for i in range(1, n): if cd[i] < cd[min]: min = i min_count = 1 elif cd[i] == cd[min]: min_count += 1 if(min_count > 1): print("Still Rozdil") else: print(min + 1) ```
MatrixStudio/Codeforces-Python-Submissions
A company has *n* employees numbered from 1 to *n*. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee *A* is said to be the superior of another employee *B* if at least one of the following is true: - Employee *A* is the immediate manager of employee *B* - Employee *B* has an immediate manager employee *C* such that employee *A* is the superior of employee *C*. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager. Today the company is going to arrange a party. This involves dividing all *n* employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees *A* and *B* such that *A* is the superior of *B*. What is the minimum number of groups that must be formed?
```python def min_groups(n, managers): employees = list(range(n)) groups = set() while employees: group = set() group.add(employees[0]) employees.pop(0) while employees and employees[-1] in managers and managers[employees[-1]] in group: group.add(employees[-1]) employees.pop() groups.add(group) return len(groups) def main(): n = int(input()) managers = {} for i in range(n): pi = int(input()) managers[i] = pi if pi != -1 else None print(min_groups(n, managers)) if __name__ == '__main__': main() ```
MatrixStudio/Codeforces-Python-Submissions
Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers *a*, *b*, *c* on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting expression is as large as possible. Let's consider an example: assume that the teacher wrote numbers 1, 2 and 3 on the blackboard. Here are some ways of placing signs and brackets: - 1+2*3=7 - 1*(2+3)=5 - 1*2*3=6 - (1+2)*3=9 Note that you can insert operation signs only between *a* and *b*, and between *b* and *c*, that is, you cannot swap integers. For instance, in the given sample you cannot get expression (1+3)*2. It's easy to see that the maximum value that you can obtain is 9. Your task is: given *a*, *b* and *c* print the maximum value that you can get.
```python a=int(input()) b=int(input()) c=int(input()) z=[] z.append(a+b+c) z.append(a*b*c) z.append((a+b)*c) z.append(a*(b+c)) z.append(a+b*c) z.append(a*b+c) z.sort() print(z[-1]) ```
MatrixStudio/Codeforces-Python-Submissions
Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it. Given a sequence *a* consisting of *n* integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it *a**k*) and delete it, at that all elements equal to *a**k*<=+<=1 and *a**k*<=-<=1 also must be deleted from the sequence. That step brings *a**k* points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him.
```python tam = int(input()) seq = input().split() sumas = [0] * tam for a in seq: sumas[int(a)-1] = sumas[int(a)-1] + int(a) if len(sumas) < 3: print(max(sumas)) else: final = 0 primero = 0 while len(sumas) > 2: if sumas[0] >= sumas[1]: final = final + sumas[0] sumas.pop(0) sumas.pop(0) elif sumas[0] + sumas[2] > sumas[1]: final = final + sumas[0] sumas.pop(0) sumas.pop(0) else: sumas.pop(0) final = final + max(sumas) print(final) ```
MatrixStudio/Codeforces-Python-Submissions
Malek has recently found a treasure map. While he was looking for a treasure he found a locked door. There was a string *s* written on the door consisting of characters '(', ')' and '#'. Below there was a manual on how to open the door. After spending a long time Malek managed to decode the manual and found out that the goal is to replace each '#' with one or more ')' characters so that the final string becomes beautiful. Below there was also written that a string is called beautiful if for each *i* (1<=≤<=*i*<=≤<=|*s*|) there are no more ')' characters than '(' characters among the first *i* characters of *s* and also the total number of '(' characters is equal to the total number of ')' characters. Help Malek open the door by telling him for each '#' character how many ')' characters he must replace it with.
```python if __name__=='__main__': s=input().strip() diff=0 res=[] for i,c in enumerate(s): if c=='(': diff+=1 elif c==')': diff-=1 if diff<0: res=-1 break else: if diff>0: res.append(diff) else: res=-1 break if res==-1:print(res) elif diff>len(res): for n in res[:-1]: print(1) diff-=1 print(diff) else:print(-1) ```
MatrixStudio/Codeforces-Python-Submissions
It's that time of the year when the Russians flood their countryside summer cottages (dachas) and the bus stop has a lot of people. People rarely go to the dacha on their own, it's usually a group, so the people stand in queue by groups. The bus stop queue has *n* groups of people. The *i*-th group from the beginning has *a**i* people. Every 30 minutes an empty bus arrives at the bus stop, it can carry at most *m* people. Naturally, the people from the first group enter the bus first. Then go the people from the second group and so on. Note that the order of groups in the queue never changes. Moreover, if some group cannot fit all of its members into the current bus, it waits for the next bus together with other groups standing after it in the queue. Your task is to determine how many buses is needed to transport all *n* groups to the dacha countryside.
```python n,m=map(int,input().split()) l=list(map(int,input().split())) k=1 t=0 for i in range(n) : if t+l[i]>m : k=k+1 t=l[i] else : t=t+l[i] print(k) ```
MatrixStudio/Codeforces-Python-Submissions
Mike and some bears are playing a game just for fun. Mike is the judge. All bears except Mike are standing in an *n*<=×<=*m* grid, there's exactly one bear in each cell. We denote the bear standing in column number *j* of row number *i* by (*i*,<=*j*). Mike's hands are on his ears (since he's the judge) and each bear standing in the grid has hands either on his mouth or his eyes. They play for *q* rounds. In each round, Mike chooses a bear (*i*,<=*j*) and tells him to change his state i. e. if his hands are on his mouth, then he'll put his hands on his eyes or he'll put his hands on his mouth otherwise. After that, Mike wants to know the score of the bears. Score of the bears is the maximum over all rows of number of consecutive bears with hands on their eyes in that row. Since bears are lazy, Mike asked you for help. For each round, tell him the score of these bears after changing the state of a bear selected in that round.
```python n,m,q = map(int,input().split()) hor = [0] * n table = [0] * n for i in range(n): table[i] = list(map(int,input().split())) for h in range(n): tmp = 0 for v in range(m): if table[h][v]: tmp += 1 else: if hor[h] < tmp: hor[h] = tmp tmp = 0 if hor[h] < tmp: hor[h] = tmp for qu in range(q): i, j = tuple(map(int,input().split())) i-=1 j-=1 table[i][j] = 0 if table[i][j] else 1 #for elem in table: print (elem) hor[i] = 0 for v in range(m): if table[i][v]: tmp += 1 else: if hor[i] < tmp: hor[i] = tmp #print(hor[i], v) tmp = 0 if hor[i] < tmp : hor[i] = tmp tmp = 0 #print(hor) print(max(hor)) ```
MatrixStudio/Codeforces-Python-Submissions
The girl Taylor has a beautiful calendar for the year *y*. In the calendar all days are given with their days of week: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday. The calendar is so beautiful that she wants to know what is the next year after *y* when the calendar will be exactly the same. Help Taylor to find that year. Note that leap years has 366 days. The year is leap if it is divisible by 400 or it is divisible by 4, but not by 100 ([https://en.wikipedia.org/wiki/Leap_year](https://en.wikipedia.org/wiki/Leap_year)).
```python n=int(input()) if n%400==0 or (n%4==0 and n%100!=0): print(n+28) elif n%4==1: print(n+6) else: print(n+11) ```
MatrixStudio/Codeforces-Python-Submissions
One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality of the first laptop is higher (strictly greater) than the quality of the second laptop. Please, check the guess of Alex. You are given descriptions of *n* laptops. Determine whether two described above laptops exist.
```python n = int(input()) laptops = [tuple(map(int, input().split())) for i in range(n)] if any(a < b for a, b in laptops): print("Happy Alex") else: print("Poor Alex") ```
MatrixStudio/Codeforces-Python-Submissions
You are given two polynomials: - *P*(*x*)<==<=*a*0·*x**n*<=+<=*a*1·*x**n*<=-<=1<=+<=...<=+<=*a**n*<=-<=1·*x*<=+<=*a**n* and - *Q*(*x*)<==<=*b*0·*x**m*<=+<=*b*1·*x**m*<=-<=1<=+<=...<=+<=*b**m*<=-<=1·*x*<=+<=*b**m*. Calculate limit .
```python import math d1,d2=map(int,input().split()) l1=list(map(int,list(input().split()))) l2=list(map(int,list(input().split()))) if d1<d2: print("0/1") if d1==d2: g=math.gcd(l1[0],l2[0]) p=l1[0]//g q=l2[0]//g if p>0 and q>0: print(str(p)+"/"+str(q)) else: if p<0: p=-(p) if q<0: q=-(q) print("-"+str(p)+"/"+str(q)) if d1>d2: if l1[0]>0: print("INFINITY") else: print("-INFINITY") ```
MatrixStudio/Codeforces-Python-Submissions
Edogawa Conan got tired of solving cases, and invited his friend, Professor Agasa, over. They decided to play a game of cards. Conan has *n* cards, and the *i*-th card has a number *a**i* written on it. They take turns playing, starting with Conan. In each turn, the player chooses a card and removes it. Also, he removes all cards having a number strictly lesser than the number on the chosen card. Formally, if the player chooses the *i*-th card, he removes that card and removes the *j*-th card for all *j* such that *a**j*<=&lt;<=*a**i*. A player loses if he cannot make a move on his turn, that is, he loses if there are no cards left. Predict the outcome of the game, assuming both players play optimally.
```python n = int(input()) a = input().split(" ") a_int = [] for i in a: a_int.append(int(i)) a = a_int a.sort() if a.count(a[-1]) % 2 == 1: print("Conan") else: print("Agasa") ```
MatrixStudio/Codeforces-Python-Submissions
Makes solves problems on Decoforces and lots of other different online judges. Each problem is denoted by its difficulty — a positive integer number. Difficulties are measured the same across all the judges (the problem with difficulty *d* on Decoforces is as hard as the problem with difficulty *d* on any other judge). Makes has chosen *n* problems to solve on Decoforces with difficulties *a*1,<=*a*2,<=...,<=*a**n*. He can solve these problems in arbitrary order. Though he can solve problem *i* with difficulty *a**i* only if he had already solved some problem with difficulty (no matter on what online judge was it). Before starting this chosen list of problems, Makes has already solved problems with maximum difficulty *k*. With given conditions it's easy to see that Makes sometimes can't solve all the chosen problems, no matter what order he chooses. So he wants to solve some problems on other judges to finish solving problems from his list. For every positive integer *y* there exist some problem with difficulty *y* on at least one judge besides Decoforces. Makes can solve problems on any judge at any time, it isn't necessary to do problems from the chosen list one right after another. Makes doesn't have too much free time, so he asked you to calculate the minimum number of problems he should solve on other judges in order to solve all the chosen problems from Decoforces.
```python n, k = map(int, input().strip().split()) a = list(map(int, input().strip().split())) ans = 0 for now in a: while k*2 < now: k *= 2 ans += 1 k = max(k, now) print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Consider the decimal presentation of an integer. Let's call a number d-magic if digit *d* appears in decimal presentation of the number on even positions and nowhere else. For example, the numbers 1727374, 17, 1 are 7-magic but 77, 7, 123, 34, 71 are not 7-magic. On the other hand the number 7 is 0-magic, 123 is 2-magic, 34 is 4-magic and 71 is 1-magic. Find the number of d-magic numbers in the segment [*a*,<=*b*] that are multiple of *m*. Because the answer can be very huge you should only find its value modulo 109<=+<=7 (so you should find the remainder after dividing by 109<=+<=7).
```python import math MAX_SUM = 73 prime = [True for i in range(MAX_SUM)] def sieve(): prime[0] = prime[1] = False for i in range(2, int(math.sqrt(MAX_SUM))): if prime[i]: for j in range(i * i, MAX_SUM, i): prime[j] = False def compute_digits_list(n): digits = [] while n > 0: digits.append(n % 10) n //= 10 digits.reverse() return digits def compute_digit_dp(n): digits = compute_digits_list(n) digit_dp = [[[0 for k in range(2)] for j in range(MAX_SUM)] for i in range(len(digits))] for i in range(digits[0]): digit_dp[0][i][1] = 1 digit_dp[0][digits[0]][0] = 1 for i in range(1, len(digits)): for j in range(0, 10): for sum in range(j, MAX_SUM): digit_dp[i][sum][1] += digit_dp[i - 1][sum - j][1] if j < digits[i]: digit_dp[i][sum][1] += digit_dp[i - 1][sum - j][0] if j == digits[i]: digit_dp[i][sum][0] += digit_dp[i - 1][sum - j][0] return digit_dp def compute_g_one_numbers(n): if n < 2: return 0 g_one_nums = 0 digit_dp = compute_digit_dp(n) for sum in range(0, MAX_SUM): if prime[sum]: for isLessThan in range(2): g_one_nums += digit_dp[len(digit_dp) - 1][sum][isLessThan] return g_one_nums def main_program(): sieve() test_cases = int(input()) while test_cases > 0: start, end = map(int, input().split()) print(compute_g_one_numbers(end) - compute_g_one_numbers(start - 1)) test_cases -= 1 if __name__ == '__main__': main_program() ```
MatrixStudio/Codeforces-Python-Submissions
Today an outstanding event is going to happen in the forest — hedgehog Filya will come to his old fried Sonya! Sonya is an owl and she sleeps during the day and stay awake from minute *l*1 to minute *r*1 inclusive. Also, during the minute *k* she prinks and is unavailable for Filya. Filya works a lot and he plans to visit Sonya from minute *l*2 to minute *r*2 inclusive. Calculate the number of minutes they will be able to spend together.
```python a,b,c,d,r=map(int,input().split()) m=0 if c<=b: m=(b+1)-c if c <= r<=b: m=m-1 print(m) else: print(m) ```
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 import sys for line in sys.stdin: words= [line.strip().split()] print(words) ```
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 #include <bits/stdc++.h> #define ll long long #define int long long #define fi first #define se second #define ii pair<int, int> const ll N = 1e6+1; const ll mod = 1e9+7; const ll INF = 1e9; using namespace std; signed main() { ios_base::sync_with_stdio(0); cin.tie(0);cout.tie(0); string s; cin>>s; string s1="", s2=""; ll ans=0; for (ll i=0; i<s.size(); i++) { s1+=s[i]; s2=s[i]+s2; if (s1!=s2) ans=i+1; } cout<<ans; return 0; } ```
MatrixStudio/Codeforces-Python-Submissions
Mr Keks is a typical white-collar in Byteland. He has a bookshelf in his office with some books on it, each book has an integer positive price. Mr Keks defines the value of a shelf as the sum of books prices on it. Miraculously, Mr Keks was promoted and now he is moving into a new office. He learned that in the new office he will have not a single bookshelf, but exactly $k$ bookshelves. He decided that the beauty of the $k$ shelves is the [bitwise AND](https://en.wikipedia.org/wiki/Bitwise_operation#AND) of the values of all the shelves. He also decided that he won't spend time on reordering the books, so he will place several first books on the first shelf, several next books on the next shelf and so on. Of course, he will place at least one book on each shelf. This way he will put all his books on $k$ shelves in such a way that the beauty of the shelves is as large as possible. Compute this maximum possible beauty.
```python from functools import reduce N=55 dp = [ [-1 for i in range(N)] for i in range(N) ] N,K = list(map(int,input().strip().split())) A = list(map(int, input().strip().split())) # n,k divide just after before i into k segments def solve(i,k): if(dp[i][k]!=-1): return dp[i][k] if(k==1): m=sum(A[i:]) elif(N-i==k): m=reduce(lambda x,y: x&y, A[i:], 1) else: m=0 for j in range(i+1, N+1): m = max(m,solve(j,k-1)&sum(A[i:j])) dp[i][k]=m return m print(solve(0,K)) ```
MatrixStudio/Codeforces-Python-Submissions
The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has *n* students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times. The head of the SSU OPTC is recently gathering teams to participate in the world championship. Each team must consist of exactly three people, at that, any person cannot be a member of two or more teams. What maximum number of teams can the head make if he wants each team to participate in the world championship with the same members at least *k* times?
```python n, k = list(map(int, input().split())) l = list(map(int, input().split())) c = 0 for i in range(n): l[i] += k if l[i] <= 5: c += 1 print(c // 3) ```
MatrixStudio/Codeforces-Python-Submissions
You are going to the beach with the idea to build the greatest sand castle ever in your head! The beach is not as three-dimensional as you could have imagined, it can be decribed as a line of spots to pile up sand pillars. Spots are numbered 1 through infinity from left to right. Obviously, there is not enough sand on the beach, so you brought *n* packs of sand with you. Let height *h**i* of the sand pillar on some spot *i* be the number of sand packs you spent on it. You can't split a sand pack to multiple pillars, all the sand from it should go to a single one. There is a fence of height equal to the height of pillar with *H* sand packs to the left of the first spot and you should prevent sand from going over it. Finally you ended up with the following conditions to building the castle: - *h*1<=≤<=*H*: no sand from the leftmost spot should go over the fence; - For any |*h**i*<=-<=*h**i*<=+<=1|<=≤<=1: large difference in heights of two neighboring pillars can lead sand to fall down from the higher one to the lower, you really don't want this to happen; - : you want to spend all the sand you brought with you. As you have infinite spots to build, it is always possible to come up with some valid castle structure. Though you want the castle to be as compact as possible. Your task is to calculate the minimum number of spots you can occupy so that all the aforementioned conditions hold.
```python # -*- coding: utf-8 -*- import math vec = input().strip().split(' ') n = int(vec[0]) H = int(vec[1]) s = round(math.sqrt(n * 2)) - 1 while True: if s * (s + 1) / 2 > n: break s = s + 1 s = s - 1 if s > H: s = H diff = n - s * (s + 1) / 2 count = s xa = 1 xb = 2 * s xc = - diff d = xb * xb - 4 * xa * xc k = - xb + math.sqrt(d) k = math.floor(k / 2) diff = diff - k * k - xb * k s = s + k count = count + 2 * k if 0 < diff <= s: count = count + 1 diff = 0 elif diff == 0: count = count else: diff = 0 count = count + 2 print(count) ```
MatrixStudio/Codeforces-Python-Submissions
Little girl Tanya climbs the stairs inside a multi-storey building. Every time Tanya climbs a stairway, she starts counting steps from $1$ to the number of steps in this stairway. She speaks every number aloud. For example, if she climbs two stairways, the first of which contains $3$ steps, and the second contains $4$ steps, she will pronounce the numbers $1, 2, 3, 1, 2, 3, 4$. You are given all the numbers pronounced by Tanya. How many stairways did she climb? Also, output the number of steps in each stairway. The given sequence will be a valid sequence that Tanya could have pronounced when climbing one or more stairways.
```python n = int(input()) list = list(map(int , input().split())) li = [] c = 0 for i in range(n): if list[i] == 1: c += 1 if list[i] == 1 and i > 0: li.append(list[i-1]) li.append(list[-1]) print(c) for l in li: print(l , end = " ") ```
MatrixStudio/Codeforces-Python-Submissions
Little Elephant loves magic squares very much. A magic square is a 3<=×<=3 table, each cell contains some positive integer. At that the sums of integers in all rows, columns and diagonals of the table are equal. The figure below shows the magic square, the sum of integers in all its rows, columns and diagonals equals 15. The Little Elephant remembered one magic square. He started writing this square on a piece of paper, but as he wrote, he forgot all three elements of the main diagonal of the magic square. Fortunately, the Little Elephant clearly remembered that all elements of the magic square did not exceed 105. Help the Little Elephant, restore the original magic square, given the Elephant's notes.
```python a,b,c=map(int,input().split()) r,s,t=map(int,input().split()) x,y,z=map(int,input().split()) s=(2*c+b-r)//2 a=s+r+t-b-c z=s+r+t-x-y print(a,b,c) print(r,s,t) print(x,y,z) ```
MatrixStudio/Codeforces-Python-Submissions
Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built *n* towers in a row. The *i*-th tower is made of *h**i* identical blocks. For clarification see picture for the first sample. Limak will repeat the following operation till everything is destroyed. Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time. Limak is ready to start. You task is to count how many operations will it take him to destroy all towers.
```python N = int(input()) A = [int(i) for i in input().split()] A = [0] + A + [0] lo, hi = 0, N while lo <= hi: k = (lo + hi) // 2 H, N, K = A, N, k a = True for i in range(K + 1, N - K + 1): h = H[i] for j in range(K + 1): if h <= 0: break if i - j >= 0: h = min(h, H[i - j] - (K - j)) if i + j <= N: h = min(h, H[i + j] - (K - j)) if h > 0: a = False if a: hi = k - 1 else: lo = k + 1 print(lo) ```
MatrixStudio/Codeforces-Python-Submissions
It's one more school day now. Sasha doesn't like classes and is always bored at them. So, each day he invents some game and plays in it alone or with friends. Today he invented one simple game to play with Lena, with whom he shares a desk. The rules are simple. Sasha draws *n* sticks in a row. After that the players take turns crossing out exactly *k* sticks from left or right in each turn. Sasha moves first, because he is the inventor of the game. If there are less than *k* sticks on the paper before some turn, the game ends. Sasha wins if he makes strictly more moves than Lena. Sasha wants to know the result of the game before playing, you are to help him.
```python a,m = map(int,input().split()) print("YES" if(a//m)%2==1 else "NO") ```
MatrixStudio/Codeforces-Python-Submissions
Kuriyama Mirai has killed many monsters and got many (namely *n*) stones. She numbers the stones from 1 to *n*. The cost of the *i*-th stone is *v**i*. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions: 1. She will tell you two numbers, *l* and *r* (1<=≤<=*l*<=≤<=*r*<=≤<=*n*), and you should tell her . 1. Let *u**i* be the cost of the *i*-th cheapest stone (the cost that will be on the *i*-th place if we arrange all the stone costs in non-decreasing order). This time she will tell you two numbers, *l* and *r* (1<=≤<=*l*<=≤<=*r*<=≤<=*n*), and you should tell her . For every question you should give the correct answer, or Kuriyama Mirai will say "fuyukai desu" and then become unhappy.
```python n = int(input()) v = list(map(int,input().split())) m = int(input()) vps = [0] for x in v: vps.append(vps[-1]+x) v.sort() ups = [0] for x in v: ups.append(ups[-1]+x) for _ in range(m): t,l,r = map(int,input().split()) if t == 1: print(vps[r]-vps[l-1]) else: print(ups[r]-ups[l-1]) ```
MatrixStudio/Codeforces-Python-Submissions
Holidays have finished. Thanks to the help of the hacker Leha, Noora managed to enter the university of her dreams which is located in a town Pavlopolis. It's well known that universities provide students with dormitory for the period of university studies. Consequently Noora had to leave Vičkopolis and move to Pavlopolis. Thus Leha was left completely alone in a quiet town Vičkopolis. He almost even fell into a depression from boredom! Leha came up with a task for himself to relax a little. He chooses two integers *A* and *B* and then calculates the greatest common divisor of integers "*A* factorial" and "*B* factorial". Formally the hacker wants to find out GCD(*A*!,<=*B*!). It's well known that the factorial of an integer *x* is a product of all positive integers less than or equal to *x*. Thus *x*!<==<=1·2·3·...·(*x*<=-<=1)·*x*. For example 4!<==<=1·2·3·4<==<=24. Recall that GCD(*x*,<=*y*) is the largest positive integer *q* that divides (without a remainder) both *x* and *y*. Leha has learned how to solve this task very effective. You are able to cope with it not worse, aren't you?
```python def bored_life(x,y): res1=1 for i in range(1,x+1): res1=res1*i res2=1 for i in range(1,y+1): res2=res2*i temp=[res1,res2] print(min(temp)) (x,y)=map(int,input().split()) bored_life(x,y) ```
MatrixStudio/Codeforces-Python-Submissions
Array of integers is unimodal, if: - it is strictly increasing in the beginning; - after that it is constant; - after that it is strictly decreasing. The first block (increasing) and the last block (decreasing) may be absent. It is allowed that both of this blocks are absent. For example, the following three arrays are unimodal: [5,<=7,<=11,<=11,<=2,<=1], [4,<=4,<=2], [7], but the following three are not unimodal: [5,<=5,<=6,<=6,<=1], [1,<=2,<=1,<=2], [4,<=5,<=5,<=6]. Write a program that checks if an array is unimodal.
```python a = list( map(int,input().split()) ) n=0 m=0 x=0 for i in range(len(a)-1): if a[i+1]>a[i]: n=a[i+1] else: break for j in range(i,len(a)-1): if a[j]>a[j+1]: m=a[j] else: x=1 break if(x==1): print('no') else: print('yes') ```
MatrixStudio/Codeforces-Python-Submissions
Vadim is really keen on travelling. Recently he heard about kayaking activity near his town and became very excited about it, so he joined a party of kayakers. Now the party is ready to start its journey, but firstly they have to choose kayaks. There are 2·*n* people in the group (including Vadim), and they have exactly *n*<=-<=1 tandem kayaks (each of which, obviously, can carry two people) and 2 single kayaks. *i*-th person's weight is *w**i*, and weight is an important matter in kayaking — if the difference between the weights of two people that sit in the same tandem kayak is too large, then it can crash. And, of course, people want to distribute their seats in kayaks in order to minimize the chances that kayaks will crash. Formally, the instability of a single kayak is always 0, and the instability of a tandem kayak is the absolute difference between weights of the people that are in this kayak. Instability of the whole journey is the total instability of all kayaks. Help the party to determine minimum possible total instability!
```python import itertools if __name__ == '__main__': n = int(input()) weights = list(map(int, input().split())) combs = list(itertools.combinations(weights,len(weights)-2)) diff_list = [] for comb in combs: instability = 0 for num in range(0,len(comb),2): instability += abs(comb[num] - comb[num+1]) if instability not in diff_list: diff_list.append(instability) print(min(diff_list)) ```
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 str = input() sett = set(str) m = len(sett) if(m&1) !=1: print("CHAT WITH HER!") else: print("IGNORE HIM!") ```
MatrixStudio/Codeforces-Python-Submissions
Kirill plays a new computer game. He came to the potion store where he can buy any potion. Each potion is characterized by two integers — amount of experience and cost. The efficiency of a potion is the ratio of the amount of experience to the cost. Efficiency may be a non-integer number. For each two integer numbers *a* and *b* such that *l*<=≤<=*a*<=≤<=*r* and *x*<=≤<=*b*<=≤<=*y* there is a potion with experience *a* and cost *b* in the store (that is, there are (*r*<=-<=*l*<=+<=1)·(*y*<=-<=*x*<=+<=1) potions). Kirill wants to buy a potion which has efficiency *k*. Will he be able to do this?
```python l,r,x,y,k = input().split() min_k = int(l)/int(y) max_k = int(r)/int(x) k1 = float(k) if k1>=min_k and k1<=max_k: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
In a far away kingdom lived the King, the Prince, the Shoemaker, the Dressmaker and many other citizens. They lived happily until great trouble came into the Kingdom. The ACMers settled there. Most damage those strange creatures inflicted upon the kingdom was that they loved high precision numbers. As a result, the Kingdom healers had already had three appointments with the merchants who were asked to sell, say, exactly 0.273549107 beer barrels. To deal with the problem somehow, the King issued an order obliging rounding up all numbers to the closest integer to simplify calculations. Specifically, the order went like this: - If a number's integer part does not end with digit 9 and its fractional part is strictly less than 0.5, then the rounded up number coincides with the number’s integer part. - If a number's integer part does not end with digit 9 and its fractional part is not less than 0.5, the rounded up number is obtained if we add 1 to the last digit of the number’s integer part.- If the number’s integer part ends with digit 9, to round up the numbers one should go to Vasilisa the Wise. In the whole Kingdom she is the only one who can perform the tricky operation of carrying into the next position. Merchants found the algorithm very sophisticated and they asked you (the ACMers) to help them. Can you write a program that would perform the rounding according to the King’s order?
```python n= input() ip, fp = n.split('.') l = ip[-1] if l!= '9': if int(fp[0]) < 5: print(ip) else: print(int(ip) + 1) else: print("GOTO Vasilisa.") ```
MatrixStudio/Codeforces-Python-Submissions
You are given matrix with *n* rows and *n* columns filled with zeroes. You should put *k* ones in it in such a way that the resulting matrix is symmetrical with respect to the main diagonal (the diagonal that goes from the top left to the bottom right corner) and is lexicographically maximal. One matrix is lexicographically greater than the other if the first different number in the first different row from the top in the first matrix is greater than the corresponding number in the second one. If there exists no such matrix then output -1.
```python # -*- coding: utf-8 -*- """ Created on Mon Oct 30 19:33:01 2023 @author: ZHAO XUDI """ n, k = map(int, input().split()) matrix = [[0 for _ in range(n)] for _ in range(n)] if k > n * n: print(-1) else: # Placing 1's on the diagonal for i in range(n): if k > 0: matrix[i][i] = 1 k -= 1 # Placing the rest of the 1's to maintain symmetry for i in range(n): for j in range(i + 1, n): if k >= 2: matrix[i][j] = 1 matrix[j][i] = 1 k -= 2 # Checking if all 1's are placed if k == 0: for row in matrix: print(" ".join(map(str, row))) else: print(-1) ```
MatrixStudio/Codeforces-Python-Submissions
Little Lesha loves listening to music via his smartphone. But the smartphone doesn't have much memory, so Lesha listens to his favorite songs in a well-known social network InTalk. Unfortunately, internet is not that fast in the city of Ekaterinozavodsk and the song takes a lot of time to download. But Lesha is quite impatient. The song's duration is *T* seconds. Lesha downloads the first *S* seconds of the song and plays it. When the playback reaches the point that has not yet been downloaded, Lesha immediately plays the song from the start (the loaded part of the song stays in his phone, and the download is continued from the same place), and it happens until the song is downloaded completely and Lesha listens to it to the end. For *q* seconds of real time the Internet allows you to download *q*<=-<=1 seconds of the track. Tell Lesha, for how many times he will start the song, including the very first start.
```python t,s,q = input().split() t=int(t) s=int(s) q=int(q) if(s<t/q): print(2) else: print(1) ```
MatrixStudio/Codeforces-Python-Submissions
Jabber ID on the national Berland service «Babber» has a form &lt;username&gt;@&lt;hostname&gt;[/resource], where - &lt;username&gt; — is a sequence of Latin letters (lowercase or uppercase), digits or underscores characters «_», the length of &lt;username&gt; is between 1 and 16, inclusive. - &lt;hostname&gt; — is a sequence of word separated by periods (characters «.»), where each word should contain only characters allowed for &lt;username&gt;, the length of each word is between 1 and 16, inclusive. The length of &lt;hostname&gt; is between 1 and 32, inclusive. - &lt;resource&gt; — is a sequence of Latin letters (lowercase or uppercase), digits or underscores characters «_», the length of &lt;resource&gt; is between 1 and 16, inclusive. The content of square brackets is optional — it can be present or can be absent. There are the samples of correct Jabber IDs: [[email protected]](/cdn-cgi/l/email-protection), [[email protected]](/cdn-cgi/l/email-protection)/contest. Your task is to write program which checks if given string is a correct Jabber ID.
```python import sys from re import match,findall input = sys.stdin.readline import logging log = logging.getLogger() log.setLevel(logging.INFO) def not_an_id(): print('NO') exit(0) s = input() if '@' not in s: # log.error('@ not found') not_an_id() # def is_allowed_in_user(strings): # if any(len(s) < 1 or len(s) > 16 for s in strings): # return False # matched = map(lambda x:match('[\w\d_]+',x),strings) username, other = s.split('@') # log.error(f'username={username}, other={other}') matched = findall('[a-zA-Z\d_]{1,16}',username) # if (not matched) or len(matched.string) != len(username): # not_an_id() if len(matched) != 1: not_an_id() if '/' in other: rescourses = other.split('/') # log.error(f'rescourses={rescourses}') hostname = rescourses[0] rescourses = rescourses[1:] for rescourse in rescourses: matched = findall('[a-zA-Z\d_]{1,16}',rescourse) # if matched: # log.error(f'{rescourse}:matched {matched.string}') # if (not matched) or len(matched.string) != len(rescourse): if len(matched) == 1: not_an_id() else: hostname = other # log.error(f'hostname={hostname}') if len(hostname) < 1 or len(hostname) > 32: not_an_id() words = hostname.split('.') not_matcheds = list(map(lambda x:len(findall('[a-zA-Z\d_]{1,16}',x)) != 1,words)) # log.error(f'matcheds={matcheds}') if any(not_matcheds): not_an_id() print('YES') ```
MatrixStudio/Codeforces-Python-Submissions
Everybody knows what an arithmetic progression is. Let us remind you just in case that an arithmetic progression is such sequence of numbers *a*1,<=*a*2,<=...,<=*a**n* of length *n*, that the following condition fulfills: For example, sequences [1, 5], [10], [5, 4, 3] are arithmetic progressions and sequences [1, 3, 2], [1, 2, 4] are not. Alexander has *n* cards containing integers. Arthur wants to give Alexander exactly one more card with a number so that he could use the resulting *n*<=+<=1 cards to make an arithmetic progression (Alexander has to use all of his cards). Arthur has already bought a card but he hasn't written a number on it. Help him, print all integers that you can write on a card so that the described condition fulfilled.
```python from collections import defaultdict from sys import stdin input = stdin.buffer.readline def func(): if n == 1: print(-1) elif n == 2: d = a[1] - a[0] if a[0] % 2 == a[1] % 2: print(3) print(a[0] - d, (a[0] + a[1]) // 2, a[1] + d) else: print(2) print(a[0] - d, a[1] + d) else: freq = defaultdict(int) for i in range(n-1): freq[a[i+1] - a[i]] += 1 keys = sorted(freq.keys()) if len(keys) == 1: print(2) print(a[0] - keys[0], a[-1] + keys[0]) elif len(keys) == 2: if keys[1] == 2*keys[0]: curr = a[0] d = keys[0] for i in range(1, n): if curr + i*d == a[i]: continue else: print(1) print(curr + i*d) return else: print(0) else: print(0) n = int(input()) a = list(map(int, input().split())) a.sort() func() ```
MatrixStudio/Codeforces-Python-Submissions
There is a square matrix *n*<=×<=*n*, consisting of non-negative integer numbers. You should find such a way on it that - starts in the upper left cell of the matrix; - each following cell is to the right or down from the current cell; - the way ends in the bottom right cell. Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros.
```python def cou(n): five = 0 two = 0 n1 = n while n % 2 == 0: two += 1 n//=2 while n1 % 5 == 0: five += 1 n1//=5 return (two,five) n = int(input()) arr = [[(0,0) for i in range(n)] for i in range(n)] zeroes = [[0]*n for i in range(n)] for i in range(n): x = list(map(int,input().split())) y = [] for j in range(n): if x[j] == 0: zeroes[i][j] = 1 arr[i][j] = (1,1) else: arr[i][j] = cou(x[j]) for i in range(1,n): if zeroes[0][i-1] == 1 or zeroes[0][i] == 1: zeroes[0][i] = 1 arr[0][i] = (1,1) else: t = arr[0][i-1][0]+arr[0][i][0] f = arr[0][i-1][1]+arr[0][i][1] arr[0][i] = (t,f) for i in range(1,n): if zeroes[i-1][0] == 1 or zeroes[i][0] == 1: zeroes[i][0] = 1 arr[i][0] = (1,1) else: t = arr[i-1][0][0]+arr[i][0][0] f = arr[i-1][0][1]+arr[i][0][1] arr[i][0] = (t,f) for i in range(1,n): for j in range(1,n): t = arr[i][j][0]+arr[i][j-1][0] f = arr[i][j][1]+arr[i][j-1][1] t1 = arr[i][j][0]+arr[i-1][j][0] f1 = arr[i][j][1]+arr[i-1][j][1] if (zeroes[i][j-1] == 1 and min(t1,f1) != 0) or (zeroes[i-1][j] == 1 and min(t,f) != 0) or zeroes[i][j] == 1: zeroes[i][j] = 1 arr[i][j] = (1,1) elif min(t,f)<min(t1,f1): arr[i][j] = (t,f) else: arr[i][j] = (t1,f1) ans = '' ind_x = n-1 ind_y = n-1 k = n*2-2 for i in arr: print(i) while k != 0: if (ind_y-1>-1) and (min(arr[ind_y-1][ind_x]) <= min(arr[ind_y][ind_x-1])): ans += 'D' ind_y -= 1 else: ans += 'R' ind_x -= 1 k -= 1 print(ind_y,ind_x) print(min(arr[-1][-1][0],arr[-1][-1][1])) print(ans[::-1]) ```
MatrixStudio/Codeforces-Python-Submissions
There is a polyline going through points (0,<=0)<=–<=(*x*,<=*x*)<=–<=(2*x*,<=0)<=–<=(3*x*,<=*x*)<=–<=(4*x*,<=0)<=–<=...<=-<=(2*kx*,<=0)<=–<=(2*kx*<=+<=*x*,<=*x*)<=–<=.... We know that the polyline passes through the point (*a*,<=*b*). Find minimum positive value *x* such that it is true or determine that there is no such *x*.
```python a, b=[int(k) for k in input().split()] if b>a: print(-1) else: if (a%b)==0 and (a//b)%2==1: print(b) else: c=(a//b-1)//2*2+1 #print(c) #x-(a-c*x)=b #x+cx-a=b x=(a+b)/(1+c) print(x) #/\/\/\/\/\/\ ```
MatrixStudio/Codeforces-Python-Submissions
This is yet another problem dealing with regular bracket sequences. We should remind you that a bracket sequence is called regular, if by inserting «+» and «1» into it we can get a correct mathematical expression. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not. You are given a string of «(» and «)» characters. You are to find its longest substring that is a regular bracket sequence. You are to find the number of such substrings as well.
```python st = input() a = 0 b = 0 l = 0 cnt = 0 for i in st: if i=='(': cnt+=1 else: cnt-=1 if cnt==0 and l>0: if l>a: a=l b=1 elif l==a: b+=1 elif cnt<0: cnt=0 l=0 else: l+=1 if a: a+=1 if not b: b=1 print(str(a)," "+str(b)) ```
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()) a=b=c=0 for i in range(n): x,y=map(int,input().split()) if x==y: a+=1 if x>y: b+=1 if x<y: c+=1 if b>c: print('Mishka') elif b<c: print('Chris') elif b==c: print('Friendship is magic!^^') ```
MatrixStudio/Codeforces-Python-Submissions
Levko loves permutations very much. A permutation of length *n* is a sequence of distinct positive integers, each is at most *n*. Let’s assume that value *gcd*(*a*,<=*b*) shows the greatest common divisor of numbers *a* and *b*. Levko assumes that element *p**i* of permutation *p*1,<=*p*2,<=... ,<=*p**n* is good if *gcd*(*i*,<=*p**i*)<=&gt;<=1. Levko considers a permutation beautiful, if it has exactly *k* good elements. Unfortunately, he doesn’t know any beautiful permutation. Your task is to help him to find at least one of them.
```python print("_RANDOM_GUESS_1689637780.5135195")# 1689637780.51354 ```
MatrixStudio/Codeforces-Python-Submissions
A number is called quasibinary if its decimal representation contains only digits 0 or 1. For example, numbers 0, 1, 101, 110011 — are quasibinary and numbers 2, 12, 900 are not. You are given a positive integer *n*. Represent it as a sum of minimum number of quasibinary numbers.
```python import sys, threading import math from os import path from collections import defaultdict, Counter, deque from bisect import * from string import ascii_lowercase from functools import cmp_to_key import heapq def readInts(): x = list(map(int, (sys.stdin.readline().rstrip().split()))) return x[0] if len(x) == 1 else x def readList(type=int): x = sys.stdin.readline() x = list(map(type, x.rstrip('\n\r').split())) return x def readStr(): x = sys.stdin.readline().rstrip('\r\n') return x write = sys.stdout.write read = sys.stdin.readline MAXN = 1123456 MOD = 10**9 + 7 class mydict: def __init__(self, func): self.random = randint(0, 1 << 32) self.default = func self.dict = {} def __getitem__(self, key): mykey = self.random ^ key if mykey not in self.dict: self.dict[mykey] = self.default() return self.dict[mykey] def get(self, key, default): mykey = self.random ^ key if mykey not in self.dict: return default return self.dict[mykey] def __setitem__(self, key, item): mykey = self.random ^ key self.dict[mykey] = item def getkeys(self): return [self.random ^ i for i in self.dict] def __str__(self): return f'{[(self.random ^ i, self.dict[i]) for i in self.dict]}' def lcm(a, b): return (a*b)//(math.gcd(a,b)) def mod(n): return n%MOD def fls(): sys.stdout.flush() ans = float('inf') dp = [] def helper(ar, sm): global ans if sm == 0: return 0 if sm == 1: dp[1] = 1 return 1 if sm < 0: return if not dp[sm] is None: return dp[sm] cnt = float('inf') for num in ar: tmp = helper(ar, sm-num) if not tmp is None: cnt = min(cnt, tmp+1) dp[sm] = cnt return dp[sm] ans = [] def recur(ar, sm, cnt, n, cur): global ans if cnt == n: if sm == 0: ans = cur.copy() return True else: return False if cnt > n: return False for num in ar: cur.append(num) if recur(ar, sm-num, cnt+1, n, cur): return True cur.pop() return False def solve(t): # print(f'Case #{t}: ', end = '') n = readInts() ar = [] for i in range(1, 2**6+1): num = int(bin(i)[2:]) if num > n: break ar.append(num) global dp, ans dp = [None for _ in range(n+1)] helper(ar, n) mnnum = dp[n] recur(ar, n, 0, mnnum, []) print(mnnum) print(*ans) def main(): t = 1 if path.exists("F:/Comp Programming/input.txt"): sys.stdin = open("F:/Comp Programming/input.txt", 'r') sys.stdout = open("F:/Comp Programming/output1.txt", 'w') sys.setrecursionlimit(10**5) # t = readInts() for i in range(t): solve(i+1) if __name__ == '__main__': main() ```
MatrixStudio/Codeforces-Python-Submissions
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.
```python n = int(input()) vectors = [0]*n for i in range(0,n): vectors[i] = [int(x) for x in input().split(" ")] #print(vectors) if vectors[0][0]+vectors[1][0]+vectors[2][0] == 0 and vectors[0][1]+vectors[1][1]+vectors[2][1]==0: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced programmer. Actually he is not a programmer at all. So he wasn't able to solve them. That's why he asked you to help him with these tasks. One of these tasks is the following. A sequence of *l* integers *b*1,<=*b*2,<=...,<=*b**l* (1<=≤<=*b*1<=≤<=*b*2<=≤<=...<=≤<=*b**l*<=≤<=*n*) is called good if each number divides (without a remainder) by the next number in the sequence. More formally for all *i* (1<=≤<=*i*<=≤<=*l*<=-<=1). Given *n* and *k* find the number of good sequences of length *k*. As the answer can be rather large print it modulo 1000000007 (109<=+<=7).
```python n,k=map(int,input().split()) dp=[[1]*(n+1) for i in range(k+1)] for i in range(2,k+1): for j in range(2,n+1): for x in range(j,n+1,j): dp[i][x]+=dp[i-1][j] print(sum(dp[k][i] for i in range(1,n+1))%(10**9+7)) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word *s*. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if Vasya types the word "ahhellllloou", it will be considered that he said hello, and if he types "hlelo", it will be considered that Vasya got misunderstood and he didn't manage to say hello. Determine whether Vasya managed to say hello by the given word *s*.
```python a=input() b='' def chat(name): prov=[] b='' for i in range(len(a)): if a[i] not in prov: b+=a[i] prov+=a[i] return b b=chat(a) if 'helo'in b: print('YES') else: print('NO') ```
MatrixStudio/Codeforces-Python-Submissions
The HR manager was disappointed again. The last applicant failed the interview the same way as 24 previous ones. "Do I give such a hard task?" — the HR manager thought. "Just raise number 5 to the power of *n* and get last two digits of the number. Yes, of course, *n* can be rather big, and one cannot find the power using a calculator, but we need people who are able to think, not just follow the instructions." Could you pass the interview in the machine vision company in IT City?
```python print(25) ```
MatrixStudio/Codeforces-Python-Submissions
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an *n*<=×<=*n* size matrix, where *n* is odd. The Smart Beaver considers the following matrix elements good: - Elements of the main diagonal. - Elements of the secondary diagonal. - Elements of the "middle" row — the row which has exactly rows above it and the same number of rows below it. - Elements of the "middle" column — the column that has exactly columns to the left of it and the same number of columns to the right of it. Help the Smart Beaver count the sum of good elements of the given matrix.
```python a=int(input()) b=[] c=0 d=0 for i in range(a): c=list(map(int,input().split())) b.append(c) for i in range(len(b)): d+=b[i][i] d+=b[0-i-1][0-i-1] d+=b[(a-1)//2+1][i] d+=b[i][(a-1)//2+1] print(d-(b[(a-1)//2][(a-1)//2]*3)) ```
MatrixStudio/Codeforces-Python-Submissions
Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be *n* problems, sorted by difficulty, i.e. problem 1 is the easiest and problem *n* is the hardest. Limak knows it will take him 5·*i* minutes to solve the *i*-th problem. Limak's friends organize a New Year's Eve party and Limak wants to be there at midnight or earlier. He needs *k* minutes to get there from his house, where he will participate in the contest first. How many problems can Limak solve if he wants to make it to the party?
```python no_of_problems, time = map(int, input().split()) available_time = 240 - time solvable_problems_count = 0 for i in range(1, no_of_problems + 1): if available_time >= 5 * i: solvable_problems_count += 1 available_time -= 5 * i else: break print(solvable_problems_count) ```
MatrixStudio/Codeforces-Python-Submissions
You have *m*<==<=*n*·*k* wooden staves. The *i*-th stave has length *a**i*. You have to assemble *n* barrels consisting of *k* staves each, you can use any *k* staves to construct a barrel. Each stave must belong to exactly one barrel. Let volume *v**j* of barrel *j* be equal to the length of the minimal stave in it. You want to assemble exactly *n* barrels with the maximal total sum of volumes. But you have to make them equal enough, so a difference between volumes of any pair of the resulting barrels must not exceed *l*, i.e. |*v**x*<=-<=*v**y*|<=≤<=*l* for any 1<=≤<=*x*<=≤<=*n* and 1<=≤<=*y*<=≤<=*n*. Print maximal total sum of volumes of equal enough barrels or 0 if it's impossible to satisfy the condition above.
```python import sys input = lambda: sys.stdin.readline().rstrip() from collections import Counter N,K,L = map(int, input().split()) A = list(map(int, input().split())) A.sort() C = Counter(A) B = A[:N] if B[-1]-B[0]>L: exit(print(0)) t = min(N-1, C[B[-1]]) ans = t*B[-1]+(N-t)*B[0] print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Vasily the Programmer loves romance, so this year he decided to illuminate his room with candles. Vasily has *a* candles.When Vasily lights up a new candle, it first burns for an hour and then it goes out. Vasily is smart, so he can make *b* went out candles into a new candle. As a result, this new candle can be used like any other new candle. Now Vasily wonders: for how many hours can his candles light up the room if he acts optimally well? Help him find this number.
```python a,b=map(int,input().split()) if b%2==0: print(a+b+1) else: print(a+b-1) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At 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 def word(w): word = '' lower = 0 upper = 0 for i in w: if i.islower(): lower += 1 else: upper += 1 if upper > lower: word = w.upper() if upper < lower: word = w.lower() if upper == lower: word = w.lower() print(word) word('HoUse') word('ViP') word('maTRIx') ```
MatrixStudio/Codeforces-Python-Submissions
Bachgold problem is very easy to formulate. Given a positive integer *n* represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1. Recall that integer *k* is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and *k*.
```python n = int(input()) quotient = int(n/2) answer = str() count = 0 if int(n/2) < n/2 : for _ in range (0,quotient-1) : answer += '2 ' count+= 1 elif int(n/2) == n/2 : for _ in range (0,quotient) : answer += '2 ' count+= 1 if n % 2 != 0 : answer += '3 ' count += 1 print(count) print(answer) ```
MatrixStudio/Codeforces-Python-Submissions
Special Agent Smart Beaver works in a secret research department of ABBYY. He's been working there for a long time and is satisfied with his job, as it allows him to eat out in the best restaurants and order the most expensive and exotic wood types there. The content special agent has got an important task: to get the latest research by British scientists on the English Language. These developments are encoded and stored in a large safe. The Beaver's teeth are strong enough, so the authorities assured that upon arriving at the place the beaver won't have any problems with opening the safe. And he finishes his aspen sprig and leaves for this important task. Of course, the Beaver arrived at the location without any problems, but alas. He can't open the safe with his strong and big teeth. At this point, the Smart Beaver get a call from the headquarters and learns that opening the safe with the teeth is not necessary, as a reliable source has sent the following information: the safe code consists of digits and has no leading zeroes. There also is a special hint, which can be used to open the safe. The hint is string *s* with the following structure: - if *s**i* = "?", then the digit that goes *i*-th in the safe code can be anything (between 0 to 9, inclusively); - if *s**i* is a digit (between 0 to 9, inclusively), then it means that there is digit *s**i* on position *i* in code; - if the string contains letters from "A" to "J", then all positions with the same letters must contain the same digits and the positions with distinct letters must contain distinct digits. - The length of the safe code coincides with the length of the hint. For example, hint "?JGJ9" has such matching safe code variants: "51919", "55959", "12329", "93539" and so on, and has wrong variants such as: "56669", "00111", "03539" and "13666". After receiving such information, the authorities change the plan and ask the special agents to work quietly and gently and not to try to open the safe by mechanical means, and try to find the password using the given hint. At a special agent school the Smart Beaver was the fastest in his platoon finding codes for such safes, but now he is not in that shape: the years take their toll ... Help him to determine the number of possible variants of the code to the safe, matching the given hint. After receiving this information, and knowing his own speed of entering codes, the Smart Beaver will be able to determine whether he will have time for tonight's show "Beavers are on the trail" on his favorite TV channel, or he should work for a sleepless night...
```python hint = input() seen = [] if 'A' <= hint[0] <= 'J': num = 9 seen = [hint[0]] elif '0' <= hint[0] <= '9': num = 1 elif hint[0] == '?': num = 9 for l in hint[1:]: if 'A' <= l <= 'J': if not l in seen: num *= 10 - len(seen) seen += [l] elif l == '?': num *= 10 print(num) ```
MatrixStudio/Codeforces-Python-Submissions
High school student Vasya got a string of length *n* as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters. Vasya can change no more than *k* characters of the original string. What is the maximum beauty of the string he can achieve?
```python n, k = map(int, input().split()) s=input() j=0 c=0 ans=0 for i in range(n): if(s[i]=='a'): c+=1 while(j<n and c>k): if(s[j]=='a'): c-=1 j+=1 ans=max(ans,i-j+1) j=0 c=0 for i in range(n): if(s[i]=='b'): c+=1 while(j<n and c>k): if(s[j]=='b'): c-=1 j+=1 ans=max(ans,i-j+1) print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Mary has just graduated from one well-known University and is now attending celebration party. Students like to dream of a beautiful life, so they used champagne glasses to construct a small pyramid. The height of the pyramid is *n*. The top level consists of only 1 glass, that stands on 2 glasses on the second level (counting from the top), then 3 glasses on the third level and so on.The bottom level consists of *n* glasses. Vlad has seen in the movies many times how the champagne beautifully flows from top levels to bottom ones, filling all the glasses simultaneously. So he took a bottle and started to pour it in the glass located at the top of the pyramid. Each second, Vlad pours to the top glass the amount of champagne equal to the size of exactly one glass. If the glass is already full, but there is some champagne flowing in it, then it pours over the edge of the glass and is equally distributed over two glasses standing under. If the overflowed glass is at the bottom level, then the champagne pours on the table. For the purpose of this problem we consider that champagne is distributed among pyramid glasses immediately. Vlad is interested in the number of completely full glasses if he stops pouring champagne in *t* seconds. Pictures below illustrate the pyramid consisting of three levels.
```python poj = 1024 height, time = input().split() wynik = 0 height = int(height) time = int(time) table = [] for i in range(height): table.append([]) for j in range(height): table[i].append("") table[0][0] = time * poj for i in range(height): for j in range(i): if table[i][j] >= poj: wynik+=1 nadwyzka = table[i][j] - poj table[i + 1][j] += nadwyzka/2 table[i + 1][j + 1] += nadwyzka/2 print(wynik) ```
MatrixStudio/Codeforces-Python-Submissions
Fox Ciel is playing a game with numbers now. Ciel has *n* positive integers: *x*1, *x*2, ..., *x**n*. She can do the following operation as many times as needed: select two different indexes *i* and *j* such that *x**i* &gt; *x**j* hold, and then apply assignment *x**i* = *x**i* - *x**j*. The goal is to make the sum of all numbers as small as possible. Please help Ciel to find this minimal sum.
```python # python 3 """ """ def fox_and_number_game(n_int: int, numbers_list: list) -> int: numbers_list.sort(reverse=True) while numbers_list[0] > numbers_list[-1]: largest_2nd_idx = 1 while numbers_list[0] == numbers_list[largest_2nd_idx]: largest_2nd_idx += 1 numbers_list[0] = numbers_list[0] - numbers_list[largest_2nd_idx] numbers_list.sort(reverse=True) return sum(numbers_list) if __name__ == "__main__": """ Inside of this is the test. Outside is the API """ n = int(input()) numbers = list(map(int, input().split())) print(fox_and_number_game(n, numbers)) ```
MatrixStudio/Codeforces-Python-Submissions
In some game by Playrix it takes *t* minutes for an oven to bake *k* carrot cakes, all cakes are ready at the same moment *t* minutes after they started baking. Arkady needs at least *n* cakes to complete a task, but he currently don't have any. However, he has infinitely many ingredients and one oven. Moreover, Arkady can build one more similar oven to make the process faster, it would take *d* minutes to build the oven. While the new oven is being built, only old one can bake cakes, after the new oven is built, both ovens bake simultaneously. Arkady can't build more than one oven. Determine if it is reasonable to build the second oven, i.e. will it decrease the minimum time needed to get *n* cakes or not. If the time needed with the second oven is the same as with one oven, then it is unreasonable.
```python n, t, k, d = map(int, input().split()) x1 = (n * t) / k # Time required ta bake using only one oven c = (k * d) / t # Number of cakes baked while building the oven n = n - c # remaining cakes # Calculate the time required to bake the remiaing cakes after building the second oven-it will half time of course- then add the time taken in building the second one x2 = ((n * t) /k) / 2 + d print(["NO", "YES"][x2 < x1]) ```
MatrixStudio/Codeforces-Python-Submissions
Fox Ciel has some flowers: *r* red flowers, *g* green flowers and *b* blue flowers. She wants to use these flowers to make several bouquets. There are 4 types of bouquets: - To make a "red bouquet", it needs 3 red flowers. - To make a "green bouquet", it needs 3 green flowers. - To make a "blue bouquet", it needs 3 blue flowers. - To make a "mixing bouquet", it needs 1 red, 1 green and 1 blue flower. Help Fox Ciel to find the maximal number of bouquets she can make.
```python from itertools import permutations r,b,g=list(map(int,input().split())) lis=permutations([0,1,2,3]) def function(num,arr): ans=0 for i in range(4): if num[i]==0: if arr[0]>2: temp=arr[0]//3 arr[0]-=(3*temp) ans+temp elif num[i]==1: if arr[1]>2: temp=arr[1]//3 arr[1]-=(3*temp) ans+=temp elif num[i]==2: if arr[2]>2: temp=arr[2]//3 arr[2]-=(3*temp) ans+=temp else: if min(arr)>0: temp=min(arr) arr[0]-=temp arr[1]-=temp arr[2]-=temp ans+=temp return ans ans=0 for i in lis: arr=[r,b,g] ans=max(ans,function(i,arr)) print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
A classroom in a school has six rows with 3 desks in each row. Two people can use the same desk: one sitting on the left and one sitting on the right. Some places are already occupied, and some places are vacant. Petya has just entered the class and wants to occupy the most convenient place. The conveniences of the places are shown on the picture: Here, the desks in the top row are the closest to the blackboard, while the desks in the bottom row are the furthest from the blackboard. You are given a plan of the class, where '*' denotes an occupied place, '.' denotes a vacant place, and the aisles are denoted by '-'. Find any of the most convenient vacant places for Petya.
```python n=6 arr=[] convinience=[[3,3,0,4,4,0,3,3],[3,3,0,4,4,0,3,3],[2,2,0,3,3,0,3,3],[2,2,0,3,3,0,3,3],[1,1,0,2,2,0,1,1],[1,1,0,2,2,0,1,1]] for i in range(n): arr.append(input().strip()) ans=[] for i in range(n): for j in range(n): if arr[i][j]=='.': ans.append([convinience[i][j],i,j]) ans.sort(reverse=True) i_p=ans[0][1] j_p=ans[0][2] arr[i_p]=arr[i_p][:j_p]+"P"+arr[i_p][j_p+1:] for i in range(n): print(arr[i]) print("") ```
MatrixStudio/Codeforces-Python-Submissions
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation. The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xenia. She is only beginning to count, so she can calculate a sum only if the summands follow in non-decreasing order. For example, she can't calculate sum 1+3+2+1 but she can calculate sums 1+1+2 and 3+3. You've got the sum that was written on the board. Rearrange the summans and print the sum in such a way that Xenia can calculate the sum.
```python math = input() symbol = "+" mathstr = [] for char in math: if char not in symbol: mathstr += char mathstr.sort() mathstr2 = ''.join(mathstr) ans = "+".join(mathstr2) print(ans) ```
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 def div(n): li=set() for i in range(1,int(math.sqrt(n))+1): if n%i==0: li.add(i) li.add(n//i) return list(li) x=input().split(" ") n=div(int(x[0])) k=int(x[1]) print(n[k-1]) ```
MatrixStudio/Codeforces-Python-Submissions
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm: - if the last digit of the number is non-zero, she decreases the number by one; - if the last digit of the number is zero, she divides the number by 10 (i.e. removes the last digit). You are given an integer number $n$. Tanya will subtract one from it $k$ times. Your task is to print the result after all $k$ subtractions. It is guaranteed that the result will be positive integer number.
```python n = int(input()) k = int(input()) for i in range(k): if n % 10==0: n/10 else: n-1 print(n) ```
MatrixStudio/Codeforces-Python-Submissions
You are given two integers $a$ and $b$. Moreover, you are given a sequence $s_0, s_1, \dots, s_{n}$. All values in $s$ are integers $1$ or $-1$. It's known that sequence is $k$-periodic and $k$ divides $n+1$. In other words, for each $k \leq i \leq n$ it's satisfied that $s_{i} = s_{i - k}$. Find out the non-negative remainder of division of $\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}$ by $10^{9} + 9$. Note that the modulo is unusual!
```python def binPow(a,n): if n==0: return 1 result=binPow(a,n//2) if n%2==1: return ((result%mod)*(result%mod)*(a%mod))%mod else: return ((result%mod)*(result%mod))%mod def modInv(a): return binPow(a,mod-2) mod=10**9+9 n,a,b,k=map(int,input().split()) s=input() result=0 B=b*modInv(a)%mod x=binPow(B,n+1)-1 y=binPow(B,k)-1 if y==0: A=n+1 else: A=x*modInv(y) c=binPow(a,n) d=1 for i in range(k): p=c*d%mod if s[i]=="+": result+=p else: result-=p c=c//a d=d*b%mod print((A*result)%mod) ```
MatrixStudio/Codeforces-Python-Submissions
Mike is trying rock climbing but he is awful at it. There are *n* holds on the wall, *i*-th hold is at height *a**i* off the ground. Besides, let the sequence *a**i* increase, that is, *a**i*<=&lt;<=*a**i*<=+<=1 for all *i* from 1 to *n*<=-<=1; we will call such sequence a track. Mike thinks that the track *a*1, ..., *a**n* has difficulty . In other words, difficulty equals the maximum distance between two holds that are adjacent in height. Today Mike decided to cover the track with holds hanging on heights *a*1, ..., *a**n*. To make the problem harder, Mike decided to remove one hold, that is, remove one element of the sequence (for example, if we take the sequence (1,<=2,<=3,<=4,<=5) and remove the third element from it, we obtain the sequence (1,<=2,<=4,<=5)). However, as Mike is awful at climbing, he wants the final difficulty (i.e. the maximum difference of heights between adjacent holds after removing the hold) to be as small as possible among all possible options of removing a hold. The first and last holds must stay at their positions. Help Mike determine the minimum difficulty of the track after removing one hold.
```python input() nums=list(map(int,input().split())) ans=0 ans2=[] for i in range(1,len(nums)): s=sum(nums[:i]+nums[i+1:]) if s>ans: ans=s ans2=nums[:i]+nums[i+1:] maxii=0 for i in range(len(ans2)-1): maxii=max(maxii,ans2[i+1]-ans2[i]) print(maxii) ```
MatrixStudio/Codeforces-Python-Submissions
Famil Door wants to celebrate his birthday with his friends from Far Far Away. He has *n* friends and each of them can come to the party in a specific range of days of the year from *a**i* to *b**i*. Of course, Famil Door wants to have as many friends celebrating together with him as possible. Far cars are as weird as Far Far Away citizens, so they can only carry two people of opposite gender, that is exactly one male and one female. However, Far is so far from here that no other transportation may be used to get to the party. Famil Door should select some day of the year and invite some of his friends, such that they all are available at this moment and the number of male friends invited is equal to the number of female friends invited. Find the maximum number of friends that may present at the party.
```python T= int(input()) for h in range(T): n,g,b = map(int,input().split()) if n<=g: print(n) elif g>=b: print(n) elif b>g: k = (n+1)//2 h= k//g alpha = (h-1)*b+h*g if (k%g)!=0: alpha=alpha+b+(k%g) print(max(n,alpha)) ```
MatrixStudio/Codeforces-Python-Submissions
Little penguin Polo loves his home village. The village has *n* houses, indexed by integers from 1 to *n*. Each house has a plaque containing an integer, the *i*-th house has a plaque containing integer *p**i* (1<=≤<=*p**i*<=≤<=*n*). Little penguin Polo loves walking around this village. The walk looks like that. First he stands by a house number *x*. Then he goes to the house whose number is written on the plaque of house *x* (that is, to house *p**x*), then he goes to the house whose number is written on the plaque of house *p**x* (that is, to house *p**p**x*), and so on. We know that: 1. When the penguin starts walking from any house indexed from 1 to *k*, inclusive, he can walk to house number 1. 1. When the penguin starts walking from any house indexed from *k*<=+<=1 to *n*, inclusive, he definitely cannot walk to house number 1. 1. When the penguin starts walking from house number 1, he can get back to house number 1 after some non-zero number of walks from a house to a house. You need to find the number of ways you may write the numbers on the houses' plaques so as to fulfill the three above described conditions. Print the remainder after dividing this number by 1000000007 (109<=+<=7).
```python def number_of_ways(n: int, k: int) -> int: mod = int(1e9) + 7 return (pow(k,k-1,mod)*pow(n-k,n-k,mod))%mod n,k = [int(i) for i in input().split()] print(number_of_ways(n, k)) ```
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 n=int(input()) for i in range(n): a=str(input()) l=[i for i in a] if len(l)>10: print(str(l[0])+str(len(l)-2)+str(l[-1])) else: print(a) ```
MatrixStudio/Codeforces-Python-Submissions
You've got a rectangular table with length *a* and width *b* and the infinite number of plates of radius *r*. Two players play the following game: they take turns to put the plates on the table so that the plates don't lie on each other (but they can touch each other), and so that any point on any plate is located within the table's border. During the game one cannot move the plates that already lie on the table. The player who cannot make another move loses. Determine which player wins, the one who moves first or the one who moves second, provided that both players play optimally well.
```python a, b, r = map(int, input().split()) flag = 1 while 2 * r <= a and 2 * r <= b: a = a - 2 * r b = b - 2 * r flag = -1 * flag if flag == -1: print("First") else: print("Second") ```
MatrixStudio/Codeforces-Python-Submissions
Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers *a*, *b*, *c* on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting expression is as large as possible. Let's consider an example: assume that the teacher wrote numbers 1, 2 and 3 on the blackboard. Here are some ways of placing signs and brackets: - 1+2*3=7 - 1*(2+3)=5 - 1*2*3=6 - (1+2)*3=9 Note that you can insert operation signs only between *a* and *b*, and between *b* and *c*, that is, you cannot swap integers. For instance, in the given sample you cannot get expression (1+3)*2. It's easy to see that the maximum value that you can obtain is 9. Your task is: given *a*, *b* and *c* print the maximum value that you can get.
```python a = int(input()) b = int(input()) c = int(input()) case1 = (a + b) * c case2 = a * b * c print(max(case1, case2)) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya has found a strange device. On the front panel of a device there are: a red button, a blue button and a display showing some positive integer. After clicking the red button, device multiplies the displayed number by two. After clicking the blue button, device subtracts one from the number on the display. If at some point the number stops being positive, the device breaks down. The display can show arbitrarily large numbers. Initially, the display shows number *n*. Bob wants to get number *m* on the display. What minimum number of clicks he has to make in order to achieve this result?
```python import math a,b=input().split() a,b=int(a), int(b) j=0 if a<b: f= int(math.log2(b/a))+1 p=(a*2**f-b) while p>0: k=int(math.log2(p)) if k>f: k=f o=2**k p-=o j+=1 print(j+f) else: print(a-b) ```
MatrixStudio/Codeforces-Python-Submissions
You have *n* distinct points on a plane, none of them lie on *OY* axis. Check that there is a point after removal of which the remaining points are located on one side of the *OY* axis.
```python m=int(input()) cnt=0 cnt1=0 for i in range(m): m,n=map(int,input().split()) if m>0: cnt+=1 if m<0: cnt1+=1 if cnt==m or cnt==m-1 or cnt==0 or cnt==1: print("Yes") else: print("No") ```
MatrixStudio/Codeforces-Python-Submissions
A top-secret military base under the command of Colonel Zuev is expecting an inspection from the Ministry of Defence. According to the charter, each top-secret military base must include a top-secret troop that should... well, we cannot tell you exactly what it should do, it is a top secret troop at the end. The problem is that Zuev's base is missing this top-secret troop for some reasons. The colonel decided to deal with the problem immediately and ordered to line up in a single line all *n* soldiers of the base entrusted to him. Zuev knows that the loquacity of the *i*-th soldier from the left is equal to *q**i*. Zuev wants to form the top-secret troop using *k* leftmost soldiers in the line, thus he wants their total loquacity to be as small as possible (as the troop should remain top-secret). To achieve this, he is going to choose a pair of consecutive soldiers and swap them. He intends to do so no more than *s* times. Note that any soldier can be a participant of such swaps for any number of times. The problem turned out to be unusual, and colonel Zuev asked you to help. Determine, what is the minimum total loquacity of the first *k* soldiers in the line, that can be achieved by performing no more than *s* swaps of two consecutive soldiers.
```python # i'm from jasnah, do not ban me def main(): n, m, k = map(int, input().split()) f = [[float('inf')] * 40001 for _ in range(201)] for i in range(k + 1): f[0][i] = 0 x_list = list(map(int, input().split())) for i in range(1, n + 1): x = x_list[i-1] for j in range(min(i, m), 0, -1): for l in range(i - j, k + 1): f[j][l] = min(f[j][l], f[j - 1][l - i + j] + x) print(f[m][min(k, n * n)]) if __name__ == "__main__": main() ```
MatrixStudio/Codeforces-Python-Submissions
Imp likes his plush toy a lot. Recently, he found a machine that can clone plush toys. Imp knows that if he applies the machine to an original toy, he additionally gets one more original toy and one copy, and if he applies the machine to a copied toy, he gets two additional copies. Initially, Imp has only one original toy. He wants to know if it is possible to use machine to get exactly *x* copied toys and *y* original toys? He can't throw toys away, and he can't apply the machine to a copy if he doesn't currently have any copies.
```python x=int(input("Enter X copies")) y=int(input("Enter Y copies")) if (y==0)or(y==1 and x>0)or(x%2==y%2): print("NO") else: print("YES") ```
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()) l=list(map(int,input().split())) s=0 for i in l: s=s+max(l)-i print(s) ```
MatrixStudio/Codeforces-Python-Submissions
Today, Wet Shark is given *n* integers. Using any of these integers no more than once, Wet Shark wants to get maximum possible even (divisible by 2) sum. Please, calculate this value for Wet Shark. Note, that if Wet Shark uses no integers from the *n* integers, the sum is an even integer 0.
```python arr = [] n = input() n = int(n) summ = int(0) arr_sum = 0 # for i in range(n): #arr.append(input().split()) arr = list(map(int, input().strip().split())) # arr = [int(i) for i in arr] arr.sort(reverse = True) for i in arr: arr_sum = arr_sum + i # print(arr) # print(arr_sum) # for i in range(0, len(arr)): # for j in range(i+1, len(arr)): # if(arr[i] < arr[j]): # temp = arr[i]; # arr[i] = arr[j]; # arr[j] = temp; for i in range(len(arr)): if arr_sum % 2 == 0: print(arr_sum) break elif (i < len(arr)-2): summ = summ + arr[i] else: if((summ + arr[i]) % 2 == 0): summ = summ + arr[i] print(summ) break else: summ = summ + arr[i+1] print(summ) break ```
MatrixStudio/Codeforces-Python-Submissions
Ilya is a very clever lion, he lives in an unusual city ZooVille. In this city all the animals have their rights and obligations. Moreover, they even have their own bank accounts. The state of a bank account is an integer. The state of a bank account can be a negative number. This means that the owner of the account owes the bank money. Ilya the Lion has recently had a birthday, so he got a lot of gifts. One of them (the gift of the main ZooVille bank) is the opportunity to delete the last digit or the digit before last from the state of his bank account no more than once. For example, if the state of Ilya's bank account is -123, then Ilya can delete the last digit and get his account balance equal to -12, also he can remove its digit before last and get the account balance equal to -13. Of course, Ilya is permitted not to use the opportunity to delete a digit from the balance. Ilya is not very good at math, and that's why he asks you to help him maximize his bank account. Find the maximum state of the bank account that can be obtained using the bank's gift.
```python amount=int(input()) if amount>=0: print(amount) elif amount>=-9: print(0) else: s=str(amount) if s[1]>=s[2]: s=s[:len(s)-2:]+s[2] else: s=s[:len(s)-2:]+s[1] print(int(s)) ```
MatrixStudio/Codeforces-Python-Submissions
Andryusha is an orderly boy and likes to keep things in their place. Today he faced a problem to put his socks in the wardrobe. He has *n* distinct pairs of socks which are initially in a bag. The pairs are numbered from 1 to *n*. Andryusha wants to put paired socks together and put them in the wardrobe. He takes the socks one by one from the bag, and for each sock he looks whether the pair of this sock has been already took out of the bag, or not. If not (that means the pair of this sock is still in the bag), he puts the current socks on the table in front of him. Otherwise, he puts both socks from the pair to the wardrobe. Andryusha remembers the order in which he took the socks from the bag. Can you tell him what is the maximum number of socks that were on the table at the same time?
```python x=[] w=[] s=0 n=int(input()) z =list(map(int, str_in.strip().split())) for i in range n: if x.count(z[i])==0: s=s+1 x.append(z[i]) w.append(s) else: s=s-1 w.append(s) print(max(w)) ```
MatrixStudio/Codeforces-Python-Submissions
Ted has a pineapple. This pineapple is able to bark like a bulldog! At time *t* (in seconds) it barks for the first time. Then every *s* seconds after it, it barks twice with 1 second interval. Thus it barks at times *t*, *t*<=+<=*s*, *t*<=+<=*s*<=+<=1, *t*<=+<=2*s*, *t*<=+<=2*s*<=+<=1, etc. Barney woke up in the morning and wants to eat the pineapple, but he can't eat it when it's barking. Barney plans to eat it at time *x* (in seconds), so he asked you to tell him if it's gonna bark at that time.
```python t,s,x=map(int,input().split()) print(t,s,x) a=0 for i in range(x): if t==x : a+=1 elif t+s==x or t+s+1==x: a+=1 t+=s if t+1>x: break if a>0: print("Yes") else: print("No") ```
MatrixStudio/Codeforces-Python-Submissions
According to a new ISO standard, a flag of every country should have a chequered field *n*<=×<=*m*, each square should be of one of 10 colours, and the flag should be «striped»: each horizontal row of the flag should contain squares of the same colour, and the colours of adjacent horizontal rows should be different. Berland's government asked you to find out whether their flag meets the new ISO standard.
```python n,m = input().split() b = [] c = [] d = 0 e = 0 for x in range(1,int(n)+1): a = input() b.append(a) for x in b: for y in x: c.append(y) c = set(c) c = list(c) if len(c) == 1: d=1 else: d=0 break c.clear() if d==1: for x in range(0,int(n)): if b[x-1] == b[x]: e = 1 print("NO") break if e == 0: if b[0] != b[int(n)-1]: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Little penguin Polo likes permutations. But most of all he likes permutations of integers from 0 to *n*, inclusive. For permutation *p*<==<=*p*0,<=*p*1,<=...,<=*p**n*, Polo has defined its beauty — number . Expression means applying the operation of bitwise excluding "OR" to numbers *x* and *y*. This operation exists in all modern programming languages, for example, in language C++ and Java it is represented as "^" and in Pascal — as "xor". Help him find among all permutations of integers from 0 to *n* the permutation with the maximum beauty.
```python from itertools import permutations n = int(input()) bool = [False]*(n+1) ans = [0]*(n+1) mask = (1<<20)-1 for i in range(n,-1,-1): while (mask^i) > n or bool[mask^i]: mask = mask>>1 ans[i]= mask^i bool[mask^i] =True print(n*(n+1)) for i in range(n+1): print(ans[i],end=" ") ```
MatrixStudio/Codeforces-Python-Submissions
«Polygon» is a system which allows to create programming tasks in a simple and professional way. When you add a test to the problem, the corresponding form asks you for the test index. As in most cases it is clear which index the next test will have, the system suggests the default value of the index. It is calculated as the smallest positive integer which is not used as an index for some previously added test. You are to implement this feature. Create a program which determines the default index of the next test, given the indexes of the previously added tests.
```python # import math # import bisect import sys # from collections import OrderedDict input = sys.stdin.readline def inp(): return(int(input())) def inlt(): return(list(map(int,input().split()))) def insr(): s = input() return(s[:len(s)-1]) def invr(): return(map(int,input().split())) N = inp() A = inlt() m = set(A) i = 1 while True: if i not in m: print(i) break else: i += 1 ```
MatrixStudio/Codeforces-Python-Submissions
After passing a test, Vasya got himself a box of $n$ candies. He decided to eat an equal amount of candies each morning until there are no more candies. However, Petya also noticed the box and decided to get some candies for himself. This means the process of eating candies is the following: in the beginning Vasya chooses a single integer $k$, same for all days. After that, in the morning he eats $k$ candies from the box (if there are less than $k$ candies in the box, he eats them all), then in the evening Petya eats $10\%$ of the candies remaining in the box. If there are still candies left in the box, the process repeats — next day Vasya eats $k$ candies again, and Petya — $10\%$ of the candies left in a box, and so on. If the amount of candies in the box is not divisible by $10$, Petya rounds the amount he takes from the box down. For example, if there were $97$ candies in the box, Petya would eat only $9$ of them. In particular, if there are less than $10$ candies in a box, Petya won't eat any at all. Your task is to find out the minimal amount of $k$ that can be chosen by Vasya so that he would eat at least half of the $n$ candies he initially got. Note that the number $k$ must be integer.
```python n = int(input()) left = 1 right = n def check(middle): k1 = 0 k2 = 0 x = n while x > 0: if x < middle: x = 0 k1 += x else: x -= middle k1 += middle k2 += x // 10 x -= x // 10 if k1 >= n // 2 + n % 2: return True else: return False while right > left + 1: middle = (right + left) // 2 if check(middle): right = middle else: left = middle if check(right): print(right) else: print(left) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya decided to learn to play chess. Classic chess doesn't seem interesting to him, so he plays his own sort of chess. The queen is the piece that captures all squares on its vertical, horizontal and diagonal lines. If the cell is located on the same vertical, horizontal or diagonal line with queen, and the cell contains a piece of the enemy color, the queen is able to move to this square. After that the enemy's piece is removed from the board. The queen cannot move to a cell containing an enemy piece if there is some other piece between it and the queen. There is an *n*<=×<=*n* chessboard. We'll denote a cell on the intersection of the *r*-th row and *c*-th column as (*r*,<=*c*). The square (1,<=1) contains the white queen and the square (1,<=*n*) contains the black queen. All other squares contain green pawns that don't belong to anyone. The players move in turns. The player that moves first plays for the white queen, his opponent plays for the black queen. On each move the player has to capture some piece with his queen (that is, move to a square that contains either a green pawn or the enemy queen). The player loses if either he cannot capture any piece during his move or the opponent took his queen during the previous move. Help Vasya determine who wins if both players play with an optimal strategy on the board *n*<=×<=*n*.
```python import sys from math import * from fractions import gcd readints=lambda:map(int, input().strip('\n').split()) n=int(input()) if n==2: print('white') print('1 2') elif n==3: print('black') else: print('white') print('2 1') ```
MatrixStudio/Codeforces-Python-Submissions
Holidays have finished. Thanks to the help of the hacker Leha, Noora managed to enter the university of her dreams which is located in a town Pavlopolis. It's well known that universities provide students with dormitory for the period of university studies. Consequently Noora had to leave Vičkopolis and move to Pavlopolis. Thus Leha was left completely alone in a quiet town Vičkopolis. He almost even fell into a depression from boredom! Leha came up with a task for himself to relax a little. He chooses two integers *A* and *B* and then calculates the greatest common divisor of integers "*A* factorial" and "*B* factorial". Formally the hacker wants to find out GCD(*A*!,<=*B*!). It's well known that the factorial of an integer *x* is a product of all positive integers less than or equal to *x*. Thus *x*!<==<=1·2·3·...·(*x*<=-<=1)·*x*. For example 4!<==<=1·2·3·4<==<=24. Recall that GCD(*x*,<=*y*) is the largest positive integer *q* that divides (without a remainder) both *x* and *y*. Leha has learned how to solve this task very effective. You are able to cope with it not worse, aren't you?
```python import math d,m = map(int, input().split()) out = 1 d = min(d,m) for i in range(2,d+1): out= out*i print(out) ```
MatrixStudio/Codeforces-Python-Submissions
There is the faculty of Computer Science in Berland. In the social net "TheContact!" for each course of this faculty there is the special group whose name equals the year of university entrance of corresponding course of students at the university. Each of students joins the group of his course and joins all groups for which the year of student's university entrance differs by no more than *x* from the year of university entrance of this student, where *x* — some non-negative integer. A value *x* is not given, but it can be uniquely determined from the available data. Note that students don't join other groups. You are given the list of groups which the student Igor joined. According to this information you need to determine the year of Igor's university entrance.
```python n = int(input()) years = sorted((map(int, input().split()))) print(years[len(years)//2]) ```
MatrixStudio/Codeforces-Python-Submissions
You are given a string *A*. Find a string *B*, where *B* is a palindrome and *A* is a subsequence of *B*. A subsequence of a string is a string that can be derived from it by deleting some (not necessarily consecutive) characters without changing the order of the remaining characters. For example, "cotst" is a subsequence of "contest". A palindrome is a string that reads the same forward or backward. The length of string *B* should be at most 104. It is guaranteed that there always exists such string. You do not need to find the shortest answer, the only restriction is that the length of string *B* should not exceed 104.
```python line= input() len1=len(line) string = line[::-1] print(line+string) ```
MatrixStudio/Codeforces-Python-Submissions
Little Vasya has received a young builder’s kit. The kit consists of several wooden bars, the lengths of all of them are known. The bars can be put one on the top of the other if their lengths are the same. Vasya wants to construct the minimal number of towers from the bars. Help Vasya to use the bars in the best way possible.
```python n=int(input()) lst=list(map(int,input().split(' '))) lst2=list() for i in lst: if i not in lst2: lst2.append(i) dct=dict() for item in lst: if item not in dct: dct[item]=1 else: dct[item]= dct[item]+1 mx_lst=max(dct.values()) total=len(lst2) print(mx_lst,total) ```
MatrixStudio/Codeforces-Python-Submissions
As you may know, MemSQL has American offices in both San Francisco and Seattle. Being a manager in the company, you travel a lot between the two cities, always by plane. You prefer flying from Seattle to San Francisco than in the other direction, because it's warmer in San Francisco. You are so busy that you don't remember the number of flights you have made in either direction. However, for each of the last *n* days you know whether you were in San Francisco office or in Seattle office. You always fly at nights, so you never were at both offices on the same day. Given this information, determine if you flew more times from Seattle to San Francisco during the last *n* days, or not.
```python n = int(input()) s = input() cy , cn =0, 0 for i in range(len(s)-1): if s[i]+s[i+1]=='SF': cy+=1 continue if s[i]+s[i+1]=='FS': cn+=1 if cy>cn: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
You are given a rectangular board of *M*<=×<=*N* squares. Also you are given an unlimited number of standard domino pieces of 2<=×<=1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions: 1. Each domino completely covers 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 import math def req_sqs(n, m): if 1<=n<m<=16: b = math.ceil(n / 2) l = math.ceil(m / 1) elif n==m: b = math.ceil(n / 2) l = math.ceil(m / 2) elif n>m: b = math.ceil(n / 1) l = math.ceil(m / 2) result=l*b return result n,m=map(int,input().split()) result = req_sqs(n, m) print(result) ```
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 for _ in range(int(input())): x = input() if len(x)<=10: print(x) else: print(x[0],len(x)-2,x[-1]) ```
MatrixStudio/Codeforces-Python-Submissions
Sheldon, Leonard, Penny, Rajesh and Howard are in the queue for a "Double Cola" drink vending machine; there are no other people in the queue. The first one in the queue (Sheldon) buys a can, drinks it and doubles! The resulting two Sheldons go to the end of the queue. Then the next in the queue (Leonard) buys a can, drinks it and gets to the end of the queue as two Leonards, and so on. This process continues ad infinitum. For example, Penny drinks the third can of cola and the queue will look like this: Rajesh, Howard, Sheldon, Sheldon, Leonard, Leonard, Penny, Penny. Write a program that will print the name of a man who will drink the *n*-th can. Note that in the very beginning the queue looks like that: Sheldon, Leonard, Penny, Rajesh, Howard. The first person is Sheldon.
```python n = int(input()) i = 0 names = ["Sheldon","Leonard","Penny","Rajesh","Howard"] while n-(2**i)*5 > 0: n -= (2**i)*5 i += 1 b = 2**i for k in range(5): if k<4 and k*b<n and n<=(k+1)*b: break print(names[k]) ```
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 a,t=[input(),input(),input(),input()],1 for i in range(0,3): for j in range(0,3): l=a[i][j]+a[i][j+1]+a[i+1][j]+a[i+1][j+1] r=l.count("#") if r!=2: t=0 break if not t: break print("YNEOS"[t::2]) ```
MatrixStudio/Codeforces-Python-Submissions
Valera is a lazy student. He has *m* clean bowls and *k* clean plates. Valera has made an eating plan for the next *n* days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can eat dishes of the first type from bowls and dishes of the second type from either bowls or plates. When Valera finishes eating, he leaves a dirty plate/bowl behind. His life philosophy doesn't let him eat from dirty kitchenware. So sometimes he needs to wash his plate/bowl before eating. Find the minimum number of times Valera will need to wash a plate/bowl, if he acts optimally.
```python n,m,k=list(map(int,input().split())) a=list(map(int,input().split())) res=0 for i in range(n): if a[i]==1: if m==0: res+=1 else: m-=1 elif a[i]==2: if k==0: if m==0: res+=1 else: m-=1 else: k-=1 print(res) ```
MatrixStudio/Codeforces-Python-Submissions
An *n*<=×<=*n* table *a* is defined as follows: - The first row and the first column contain ones, that is: *a**i*,<=1<==<=*a*1,<=*i*<==<=1 for all *i*<==<=1,<=2,<=...,<=*n*. - Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the remaining elements are defined by the formula *a**i*,<=*j*<==<=*a**i*<=-<=1,<=*j*<=+<=*a**i*,<=*j*<=-<=1. These conditions define all the values in the table. You are given a number *n*. You need to determine the maximum value in the *n*<=×<=*n* table defined by the rules above.
```python from math import factorial n = int(input())-1 r = (factorial(2*n))//(pow(factorial(n),2)) print(r) ```