source
stringclasses
3 values
instruction
stringlengths
23
3.97k
input
stringclasses
1 value
output
stringlengths
1
3.75k
MatrixStudio/Codeforces-Python-Submissions
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition. Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character. The device consists of a wheel with a lowercase English letters written in a circle, static pointer to the current letter and a button that print the chosen letter. At one move it's allowed to rotate the alphabetic wheel one step clockwise or counterclockwise. Initially, static pointer points to letter 'a'. Other letters are located as shown on the picture: After Grigoriy add new item to the base he has to print its name on the plastic tape and attach it to the corresponding exhibit. It's not required to return the wheel to its initial position with pointer on the letter 'a'. Our hero is afraid that some exhibits may become alive and start to attack him, so he wants to print the names as fast as possible. Help him, for the given string find the minimum number of rotations of the wheel required to print it.
```python def main(): aname = input() anum = [] for char in aname: num = ord(char) - 96 anum.append(num) steps = 0 stnum = 1 for i in range(len(anum)): let1 = stnum let2 = anum[i] a1 = abs(let1 - let2) a2 = 26 - a1 step1 = min(a1, a2) steps += step1 stnum = let2 print(steps) if __name__ == '__main__': main() ```
MatrixStudio/Codeforces-Python-Submissions
You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes. You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consists of several words. For each language, all words are distinct, i.e. they are spelled differently. Moreover, the words of these languages have a one-to-one correspondence, that is, for each word in each language, there exists exactly one word in the other language having has the same meaning. You can write down every word the professor says in either the first language or the second language. Of course, during the lecture you write down each word in the language in which the word is shorter. In case of equal lengths of the corresponding words you prefer the word of the first language. You are given the text of the lecture the professor is going to read. Find out how the lecture will be recorded in your notes.
```python n,m = map(int,input().split()) d = dict(input().split() for _ in range(m)) print(' '.join(min((w,d[w]), key=len) for w in input().split())) ```
MatrixStudio/Codeforces-Python-Submissions
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given *n* numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given *n* numbers finds one that is different in evenness.
```python n = int(input()) nums = list(map(int, input().split())) flag = nums[0] % 2 + nums[1] % 2 + nums[2] % 2 if flag == 3: flag = 0 elif flag == 2: print((nums[0] % 2 == 0) * 1 + (nums[1] % 2 == 0) * 2 + (nums[2] % 2 == 0) * 3) exit(0) elif flag == 1: print((nums[0] % 2 == 1) * 1 + (nums[1] % 2 == 1) * 2 + (nums[2] % 2 == 1) * 3) exit(0) else: flag = 1 for i in range(3, n): if nums[i] % 2 == flag: print(i+1) ```
MatrixStudio/Codeforces-Python-Submissions
You are given an equation: Your task is to find the number of distinct roots of the equation and print all of them in ascending order.
```python from math import * a,b,c= map(int,input().split()) d=b**2-4*a*c if d>=0: x2 = (-b - sqrt(b ** 2 - 4 * a * c)) / (2 * a) x1 = (-b + sqrt(b ** 2 - 4 * a * c)) / (2 * a) if x1==x2: c=1 print(c) print('-1') else: c=2 print(c) print(x2) print(x1) else: print('0') ```
MatrixStudio/Codeforces-Python-Submissions
After waking up at *hh*:*mm*, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is *H* points, moreover each minute without food increases his hunger by *D* points. At any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs *C* roubles and decreases hunger by *N* points. Since the demand for bakery drops heavily in the evening, there is a special 20% discount for buns starting from 20:00 (note that the cost might become rational). Of course, buns cannot be sold by parts. Determine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero.
```python h, m = map(int, input().split()) H, D, C, N = map(int, input().split()) after = C * 0.8 ans = (H + N - 1) // N * C tm = h * 60 + m tm1 = 20 * 60 + 0 tm2 = 23 * 60 + 59 if tm1 < tm < tm2: print('{:.16f}'.format((H + N - 1) // N * after)) else: tm3 = tm1 - tm print('{:.16f}'.format(min(ans, (H + N - 1 + D * tm3) // N * after))) ```
MatrixStudio/Codeforces-Python-Submissions
Galois is one of the strongest chess players of Byteforces. He has even invented a new variant of chess, which he named «PawnChess». This new game is played on a board consisting of 8 rows and 8 columns. At the beginning of every game some black and white pawns are placed on the board. The number of black pawns placed is not necessarily equal to the number of white pawns placed. Lets enumerate rows and columns with integers from 1 to 8. Rows are numbered from top to bottom, while columns are numbered from left to right. Now we denote as (*r*,<=*c*) the cell located at the row *r* and at the column *c*. There are always two players A and B playing the game. Player A plays with white pawns, while player B plays with black ones. The goal of player A is to put any of his pawns to the row 1, while player B tries to put any of his pawns to the row 8. As soon as any of the players completes his goal the game finishes immediately and the succeeded player is declared a winner. Player A moves first and then they alternate turns. On his move player A must choose exactly one white pawn and move it one step upward and player B (at his turn) must choose exactly one black pawn and move it one step down. Any move is possible only if the targeted cell is empty. It's guaranteed that for any scenario of the game there will always be at least one move available for any of the players. Moving upward means that the pawn located in (*r*,<=*c*) will go to the cell (*r*<=-<=1,<=*c*), while moving down means the pawn located in (*r*,<=*c*) will go to the cell (*r*<=+<=1,<=*c*). Again, the corresponding cell must be empty, i.e. not occupied by any other pawn of any color. Given the initial disposition of the board, determine who wins the game if both players play optimally. Note that there will always be a winner due to the restriction that for any game scenario both players will have some moves available.
```python import sys m = [] for i in range(8): m.append(input()) a = -1 b = -1 for i in range(8): col = m[i].find('W') if col >= 0: a = i for j in range(i): if m[j][col] != '.': a = -1 break if a != -1: break i = 7 while i >= 0: col = m[i].find('B') if col >= 0: b = i j = i+1 while j < 8: if m[j][col] != '.': b = -1 break j += 1 if b != -1: break i -= 1 if a <= (7-b): print("A") else: print("B") ```
MatrixStudio/Codeforces-Python-Submissions
Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him? Given a *n*<=×<=*n* checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.
```python n=int(input()) l=[] for i in range(n): l1=input() l.append(l1) flag=0 for i in range(n): for j in range(n): s=0 if(i!=0): if(l[i-1][j]=='o'): s+=1 if(j!=0): if(l[i][j-1]=='o'): s+=1 if(i!=n-1): if(l[i+1][j]=='o'): s+=1 if(j!=n-1): if(l[i][j+1]=='o'): s+=1 if(s%2!=0): flag=1 break if(flag): print("NO") else: print("YES") ```
MatrixStudio/Codeforces-Python-Submissions
Mancala is a game famous in the Middle East. It is played on a board that consists of 14 holes. Initially, each hole has $a_i$ stones. When a player makes a move, he chooses a hole which contains a positive number of stones. He takes all the stones inside it and then redistributes these stones one by one in the next holes in a counter-clockwise direction. Note that the counter-clockwise order means if the player takes the stones from hole $i$, he will put one stone in the $(i+1)$-th hole, then in the $(i+2)$-th, etc. If he puts a stone in the $14$-th hole, the next one will be put in the first hole. After the move, the player collects all the stones from holes that contain even number of stones. The number of stones collected by player is the score, according to Resli. Resli is a famous Mancala player. He wants to know the maximum score he can obtain after one move.
```python holes = list(map(int, input().split())) mx = -1 for i in range(14): if holes[i]>0: temp2 = holes[i] temp = list(holes) temp[i] = 0 while(temp2>0): if i+1 == 14: i = 0 else: i+=1 temp[i]+=1 temp2-=1 #print(temp) sm = 0 for i in temp: if i%2 == 0: sm+=i mx = max(mx,sm) print(mx) ```
MatrixStudio/Codeforces-Python-Submissions
Pikachu had an array with him. He wrote down all the non-empty subsequences of the array on paper. Note that an array of size *n* has 2*n*<=-<=1 non-empty subsequences in it. Pikachu being mischievous as he always is, removed all the subsequences in which Maximum_element_of_the_subsequence <=-<= Minimum_element_of_subsequence <=≥<=*d* Pikachu was finally left with *X* subsequences. However, he lost the initial array he had, and now is in serious trouble. He still remembers the numbers *X* and *d*. He now wants you to construct any such array which will satisfy the above conditions. All the numbers in the final array should be positive integers less than 1018. Note the number of elements in the output array should not be more than 104. If no answer is possible, print <=-<=1.
```python import math x,d=map(int,input().split()) n=math.floor(math.log(x+1,2)) if (n-1>=d and x>10000): print(-1) elif (x<=10000 or n-1>=d): print(x) for i in range(1,x*d+2-d,d): print(i,end=' ') print() else: tb=2**n-1 diff=x-tb g=1 arr=[] c=tb while diff>0: for i in range(g,g+n): arr.append(i) g=g+n+d-1 n=math.floor(math.log(diff+1,2)) tb=2**n-1 diff=diff-tb c+=tb for i in range(g,g+n): arr.append(i) print(c) print(*arr) ```
MatrixStudio/Codeforces-Python-Submissions
Alice and Bob like games. And now they are ready to start a new game. They have placed *n* chocolate bars in a line. Alice starts to eat chocolate bars one by one from left to right, and Bob — from right to left. For each chocololate bar the time, needed for the player to consume it, is known (Alice and Bob eat them with equal speed). When the player consumes a chocolate bar, he immediately starts with another. It is not allowed to eat two chocolate bars at the same time, to leave the bar unfinished and to make pauses. If both players start to eat the same bar simultaneously, Bob leaves it to Alice as a true gentleman. How many bars each of the players will consume?
```python n=int(input()) l=list(map(int, input().split())) a,b,i,j=0,0,0,n-1 while i<j: if(sum(l[:i+1])>sum(l[j:])): b+=1 j+=1 elif(sum(l[:i+1])>sum(l[j:])): a+=1 i+=1 else: a+=1 b+=1 i+=1 j+=1 print(a,b) ```
MatrixStudio/Codeforces-Python-Submissions
Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number *n*. How many times can Gerald put a spell on it until the number becomes one-digit?
```python n = input() c = 0 while len(n) > 1: n = str(sum([int(i) for i in n])) c += 1 print(c) ```
MatrixStudio/Codeforces-Python-Submissions
Top-model Izabella participates in the competition. She wants to impress judges and show her mathematical skills. Her problem is following: for given string, consisting of only 0 and 1, tell if it's possible to remove some digits in such a way, that remaining number is a representation of some positive integer, divisible by 64, in the binary numerical system.
```python a=input() array=list(a) birBulundu=False sifirSayisi=0 for i in array: if(i=='1'): birBulundu=True else: if(birBulundu==True): sifirSayisi=sifirSayisi+1 if (sifirSayisi>5): print("yes") else: print("no") ```
MatrixStudio/Codeforces-Python-Submissions
The recent All-Berland Olympiad in Informatics featured *n* participants with each scoring a certain amount of points. As the head of the programming committee, you are to determine the set of participants to be awarded with diplomas with respect to the following criteria: - At least one participant should get a diploma. - None of those with score equal to zero should get awarded. - When someone is awarded, all participants with score not less than his score should also be awarded. Determine the number of ways to choose a subset of participants that will receive the diplomas.
```python if __name__ == '__main__': input() s = set(input().split()) print(len(s) - ('0' in s)) ```
MatrixStudio/Codeforces-Python-Submissions
Fedya studies in a gymnasium. Fedya's maths hometask is to calculate the following expression: for given value of *n*. Fedya managed to complete the task. Can you? Note that given number *n* can be extremely large (e.g. it can exceed any integer type of your programming language).
```python def dsd(a): sl = list(str(a)) ls = [] for i in range(len(sl)): ls.append(int(sl[i])) return ls for _ in range(int(input())): a, k = map(int,input().split()) ans = a while k > 1 and '0' not in list(str(a)): maxi = max(dsd(ans)) mini = min(dsd(ans)) ans = ans + maxi*mini k-=1 print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
*n* people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins *k* games in a row. This player becomes the winner. For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
```python import bisect import os from collections import Counter import bisect from collections import defaultdict import math import random import heapq as hq from math import sqrt import sys from functools import reduce, cmp_to_key from collections import deque import threading from itertools import combinations from io import BytesIO, IOBase from itertools import accumulate # sys.setrecursionlimit(200000) # mod = 10**9+7 # mod = 987 def lcm(a,b): return (a*b)//math.gcd(a,b) def sort_dict(key_value): return sorted(key_value.items(), key = lambda kv:(kv[1], kv[0])) def list_input(): return list(map(int,input().split())) def num_input(): return map(int,input().split()) def string_list(): return list(input()) def solve(): n,k = num_input() arr = list_input() if k < n: for i in range(n): j = (i+1)%n count = 0 while arr[i] > arr[j]: count += 1 if count == k: print(arr[i]) return j = (j+1)%n else: print(max(arr)) #t = int(input()) t = 1 for _ in range(t): solve() ```
MatrixStudio/Codeforces-Python-Submissions
After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her. The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons. A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $7$ because its subribbon a appears $7$ times, and the ribbon abcdabc has the beauty of $2$ because its subribbon abc appears twice. The rules are simple. The game will have $n$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $n$ turns wins the treasure. Could you find out who is going to be the winner if they all play optimally?
```python # Why do we fall ? So we can learn to pick ourselves up. from collections import Counter n = int(input()) ss = [] for _ in range(0,3): ss.append(input()) ans = ["Kuro","Shiro","Katie"] maxi = [0,0,0] for i in range(0,3): c = Counter(ss[i]) mx = max(c.values()) to = min(len(ss[i])-mx,n) maxi[i] = mx+to if n == 1 and mx == len(ss[i]): maxi[i] -= 1 # print(maxi) if maxi.count(max(maxi)) > 1: print("Draw") else: print(ans[maxi.index(max(maxi))]) """ 1 ooooo abcde abcde 3 Kuroo Shiro Katie """ ```
MatrixStudio/Codeforces-Python-Submissions
Vanya loves playing. He even has a special set of cards to play with. Each card has a single integer. The number on the card can be positive, negative and can even be equal to zero. The only limit is, the number on each card doesn't exceed *x* in the absolute value. Natasha doesn't like when Vanya spends a long time playing, so she hid all of his cards. Vanya became sad and started looking for the cards but he only found *n* of them. Vanya loves the balance, so he wants the sum of all numbers on found cards equal to zero. On the other hand, he got very tired of looking for cards. Help the boy and say what is the minimum number of cards does he need to find to make the sum equal to zero? You can assume that initially Vanya had infinitely many cards with each integer number from <=-<=*x* to *x*.
```python n, x = list(map(int, input().split())) a = list(map(int, input().split())) sums = sum(a) # print(sums) div = abs(sums) // x if (abs(sums) % x == 0): print(div) else: print(div + 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()) a=list(map(int,input().split())) l=sum(a) if(l%m==0): print(l//m) else: print(l//m+1) ```
MatrixStudio/Codeforces-Python-Submissions
Over time, Alexey's mail box got littered with too many letters. Some of them are read, while others are unread. Alexey's mail program can either show a list of all letters or show the content of a single letter. As soon as the program shows the content of an unread letter, it becomes read letter (if the program shows the content of a read letter nothing happens). In one click he can do any of the following operations: - Move from the list of letters to the content of any single letter.- Return to the list of letters from single letter viewing mode.- In single letter viewing mode, move to the next or to the previous letter in the list. You cannot move from the first letter to the previous one or from the last letter to the next one. The program cannot delete the letters from the list or rearrange them. Alexey wants to read all the unread letters and go watch football. Now he is viewing the list of all letters and for each letter he can see if it is read or unread. What minimum number of operations does Alexey need to perform to read all unread letters?
```python n = int(input()) x = list(map(int,input().split())) otv = 0 for i in range(n): if x[i] == 1: otv += 1 if i < n-1 and x[i+1] != 1: otv += 1 if x[i] != 1: print(max(otv-1,0)) else: print(otv) ```
MatrixStudio/Codeforces-Python-Submissions
Little Tanya decided to present her dad a postcard on his Birthday. She has already created a message — string *s* of length *n*, consisting of uppercase and lowercase English letters. Tanya can't write yet, so she found a newspaper and decided to cut out the letters and glue them into the postcard to achieve string *s*. The newspaper contains string *t*, consisting of uppercase and lowercase English letters. We know that the length of string *t* greater or equal to the length of the string *s*. The newspaper may possibly have too few of some letters needed to make the text and too many of some other letters. That's why Tanya wants to cut some *n* letters out of the newspaper and make a message of length exactly *n*, so that it looked as much as possible like *s*. If the letter in some position has correct value and correct letter case (in the string *s* and in the string that Tanya will make), then she shouts joyfully "YAY!", and if the letter in the given position has only the correct value but it is in the wrong case, then the girl says "WHOOPS". Tanya wants to make such message that lets her shout "YAY!" as much as possible. If there are multiple ways to do this, then her second priority is to maximize the number of times she says "WHOOPS". Your task is to help Tanya make the message.
```python TM = input() NM = input() LTM = list(TM) LNM = list(NM) cnt1 = 0 cnt2 = 0 for i in range(len(LTM)): for j in range(len(LNM)): if LTM[i] == LNM[j]: pass cnt1 += 1 LNM[j] = ' ' break else: if LTM[i] == LNM[j].upper(): cnt2 += 1 LNM[j] = 'A4' break elif(LTM[i] == LNM[j].lower()): cnt2 += 1 LNM[j] = 'A4' break print(cnt1,cnt2) ```
MatrixStudio/Codeforces-Python-Submissions
Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands: - Include a person to the chat ('Add' command). - Remove a person from the chat ('Remove' command). - Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command). Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands. Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends *l* bytes to each participant of the chat, where *l* is the length of the message. As Polycarp has no time, he is asking for your help in solving this problem.
```python from sys import stdin inputs = [] inputs = stdin.read().splitlines() s1=set() ans=0 for i in inputs: if i[0]=="+": s1.add(i[1:]) elif i[0]=='-': s1.remove(i[1:]) else: ind=i.index(':') msglen=len(i[ind:])-1 ans+=msglen*len(s1) print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed *w* kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem. Pete and Billy are great fans of even numbers, that's why they want to divide the watermelon in such a way that each of the two parts weighs even number of kilos, at the same time it is not obligatory that the parts are equal. The boys are extremely tired and want to start their meal as soon as possible, that's why you should help them and find out, if they can divide the watermelon in the way they want. For sure, each of them should get a part of positive weight.
```python a=input() a=int(a) if a%2!=0: print("NO") else: if a==2: print("NO") else: print("YES") ```
MatrixStudio/Codeforces-Python-Submissions
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are *n* flights that must depart today, the *i*-th of them is planned to depart at the *i*-th minute of the day. Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first *k* minutes of the day, so now the new departure schedule must be created. All *n* scheduled flights must now depart at different minutes between (*k*<=+<=1)-th and (*k*<=+<=*n*)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule. Helen knows that each minute of delay of the *i*-th flight costs airport *c**i* burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
```python n, k = map(int, input().split()) c = list(map(int, input().split())) s = [] max_elem = 0 max_elem_i = 0 for i in range(n): if c[i] > max_elem: max_elem_i = i max_elem = c[i] for i in range(n): s.append((c[i], i)) s.sort(reverse=True) res = [0] * n p = 0 q = 0 for i, pair in enumerate(s): if pair[1] + k < max_elem_i: res[q] = pair[1] + k + 1 q += 1 for i, pair in enumerate(s): if pair[1] + k >= max_elem_i: res[q] = pair[1] + k + 1 q += 1 for i in range(n): p += (res[i] - i - 1) * c[i] print(p) print(' '.join(map(str, res))) ```
MatrixStudio/Codeforces-Python-Submissions
You are given three integers $a$, $b$ and $x$. Your task is to construct a binary string $s$ of length $n = a + b$ such that there are exactly $a$ zeroes, exactly $b$ ones and exactly $x$ indices $i$ (where $1 \le i &lt; n$) such that $s_i \ne s_{i + 1}$. It is guaranteed that the answer always exists. For example, for the string "01010" there are four indices $i$ such that $1 \le i &lt; n$ and $s_i \ne s_{i + 1}$ ($i = 1, 2, 3, 4$). For the string "111001" there are two such indices $i$ ($i = 3, 5$). Recall that binary string is a non-empty sequence of characters where each character is either 0 or 1.
```python from math import* import os a,b,x=map(int,input().split()) c=0 d=0 if x%2==0: var=x//2 for i in range(var): if a>b: print("01",end='') else: print("10",end='') for i in range(min(a,b)-var): print("1" if a>b else 0,end='') for i in range(max(a,b)-var): print("0" if a>b else 1,end='') else: var=(x-1)//2 for i in range(var): if a>b: print("01",end='') else: print("10",end='') for i in range(max(a,b)-var): print("0" if a>b else "1",end='') for i in range(min(a,b)-var): print("1" if a>b else 0,end='') ```
MatrixStudio/Codeforces-Python-Submissions
Have you ever tried to explain to the coordinator, why it is eight hours to the contest and not a single problem has been prepared yet? Misha had. And this time he has a really strong excuse: he faced a space-time paradox! Space and time replaced each other. The entire universe turned into an enormous clock face with three hands — hour, minute, and second. Time froze, and clocks now show the time *h* hours, *m* minutes, *s* seconds. Last time Misha talked with the coordinator at *t*1 o'clock, so now he stands on the number *t*1 on the clock face. The contest should be ready by *t*2 o'clock. In the terms of paradox it means that Misha has to go to number *t*2 somehow. Note that he doesn't have to move forward only: in these circumstances time has no direction. Clock hands are very long, and Misha cannot get round them. He also cannot step over as it leads to the collapse of space-time. That is, if hour clock points 12 and Misha stands at 11 then he cannot move to 1 along the top arc. He has to follow all the way round the clock center (of course, if there are no other hands on his way). Given the hands' positions, *t*1, and *t*2, find if Misha can prepare the contest on time (or should we say on space?). That is, find if he can move from *t*1 to *t*2 by the clock face.
```python x=list(map(int,input().split())) x[0]=int((x[0]*(60/12))) % 60 m=x[1] s=x[2] x[3]=int((x[3]*(60/12))) % 60 x[4]=int((x[4]*(60/12))) % 60 z=[x[1],x[2],x[0]] z.sort() x1=[] x2=[] for i in range(1,3): if z[i-1]==z[i]: del(z[i]) break if len(z)==3: if x[3]>z[0] and x[3]<z[1]: x1.append(1) if x[3]>z[1] and x[3]<z[2]: x1.append(2) if x[3]==z[0]: x1.append(1) x1.append(3) if x[3]==z[1]: x1.append(2) x1.append(1) if x[3]==z[2]: x1.append(2) x1.append(3) elif len(x1)==0: x1.append(3) if x[4]>z[0] and x[4]<z[1]: x2.append(1) if x[4]>z[1] and x[4]<z[2]: x2.append(2) if x[4]==z[0]: x2.append(1) x2.append(3) if x[4]==z[1]: x2.append(2) x2.append(1) if x[4]==z[2]: x2.append(2) x2.append(3) elif len(x2)==0: x2.append(3) else: if x[3]>z[0] and x[3]<z[1]: x1.append(1) if x[3]==z[0]: x1.append(1) x1.append(2) if x[3]==z[1]: x1.append(1) x1.append(2) elif len(x)==0: x1.append(2) if x[4]>z[0] and x[4]<z[1]: x1.append(1) if x[4]==z[0]: x2.append(1) x2.append(2) if x[4]==z[1]: x2.append(1) x2.append(2) elif len(x2)==0: x2.append(2) d=x1 f=len(x1) s='NO' if len(x1)<len(x2): d=x2 f=len(x2) x2=x1 for i in range(f): if d[i]in x2: s='YES' print(s) ```
MatrixStudio/Codeforces-Python-Submissions
Petya and Vasya are brothers. Today is a special day for them as their parents left them home alone and commissioned them to do *n* chores. Each chore is characterized by a single parameter — its complexity. The complexity of the *i*-th chore equals *h**i*. As Petya is older, he wants to take the chores with complexity larger than some value *x* (*h**i*<=&gt;<=*x*) to leave to Vasya the chores with complexity less than or equal to *x* (*h**i*<=≤<=*x*). The brothers have already decided that Petya will do exactly *a* chores and Vasya will do exactly *b* chores (*a*<=+<=*b*<==<=*n*). In how many ways can they choose an integer *x* so that Petya got exactly *a* chores and Vasya got exactly *b* chores?
```python chores,petaya,vesaya = map(int,input().split()) order = sorted(map(int,input().split()), reverse = True) print (order[petaya-1] - order[petaya]) ```
MatrixStudio/Codeforces-Python-Submissions
Codeforces user' handle color depends on his rating — it is red if his rating is greater or equal to 2400; it is orange if his rating is less than 2400 but greater or equal to 2200, etc. Each time participant takes part in a rated contest, his rating is changed depending on his performance. Anton wants the color of his handle to become red. He considers his performance in the rated contest to be good if he outscored some participant, whose handle was colored red before the contest and his rating has increased after it. Anton has written a program that analyses contest results and determines whether he performed good or not. Are you able to do the same?
```python n=int(input()) for i in range(n): name=str(input()) before=int(input()) after=int(input()) count=0 for i in range (n): if before>=2400 and after >before: count+=1 else : break if count>0: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
You can not just take the file and send it. When Polycarp trying to send a file in the social network "Codehorses", he encountered an unexpected problem. If the name of the file contains three or more "x" (lowercase Latin letters "x") in a row, the system considers that the file content does not correspond to the social network topic. In this case, the file is not sent and an error message is displayed. Determine the minimum number of characters to remove from the file name so after that the name does not contain "xxx" as a substring. Print 0 if the file name does not initially contain a forbidden substring "xxx". You can delete characters in arbitrary positions (not necessarily consecutive). If you delete a character, then the length of a string is reduced by $1$. For example, if you delete the character in the position $2$ from the string "exxxii", then the resulting string is "exxii".
```python n=int(input()) s=input() count=0 for i in range(n-2): if s[i]+s[i+1]+s[i+2]=="xxx": count+=1 print(count) ```
MatrixStudio/Codeforces-Python-Submissions
A *k*-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by *k*. That is, there are no two integers *x* and *y* (*x*<=&lt;<=*y*) from the set, such that *y*<==<=*x*·*k*. You're given a set of *n* distinct positive integers. Your task is to find the size of it's largest *k*-multiple free subset.
```python def solve(arr, n, k): dp = [1 for i in range(n)] for i in range(1,n): temp = 0 for j in range(i): if arr[i]%arr[j]!=0: temp += 1 dp[i] = temp return max(dp) if __name__=="__main__": n,k = map(int, input().split()) arr = list(map(int, input().split())) arr.sort() ans = solve(arr,n,k) print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
*n* children are standing in a circle and playing a game. Children's numbers in clockwise order form a permutation *a*1,<=*a*2,<=...,<=*a**n* of length *n*. It is an integer sequence such that each integer from 1 to *n* appears exactly once in it. The game consists of *m* steps. On each step the current leader with index *i* counts out *a**i* people in clockwise order, starting from the next person. The last one to be pointed at by the leader becomes the new leader. You are given numbers *l*1,<=*l*2,<=...,<=*l**m* — indices of leaders in the beginning of each step. Child with number *l*1 is the first leader in the game. Write a program which will restore a possible permutation *a*1,<=*a*2,<=...,<=*a**n*. If there are multiple solutions then print any of them. If there is no solution then print -1.
```python n,m = map(int, input().split()) l = list(map(int,input().split())) a = [0 for i in range(n+1)] cur = l[0] for i in range(1,m): nx = l[i%m] if nx > l[i-1]: val = nx - l[i-1] else: val = n - l[i-1] + nx if not a[l[i-1]]: a[l[i-1]] = val elif a[l[i-1]] != val: print("-1") quit() cnt = [0 for i in range(n+1)] for i in range(1,n+1): cnt[a[i]] += 1 if cnt[a[i]] > 1: print("-1") quit() cr = 1 for i in range(1,n+1): if a[i]: continue while cnt[cr]: cr += 1 a[i] = cr cr += 1 for i in range(1, n+1): print(a[i],end=" ") ```
MatrixStudio/Codeforces-Python-Submissions
Each New Year Timofey and his friends cut down a tree of *n* vertices and bring it home. After that they paint all the *n* its vertices, so that the *i*-th vertex gets color *c**i*. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed.
```python R=lambda:map(int,input().split()) t,=R() for _ in range(t-1): x=list(R()) a=list(R()) s=set(a) c=0 d=0 for i in s: if(a.count(i)>1): c+=1 if(a.count(i)==1): d=i if(c>1): print("NO") else: print("YES") print(d) ```
MatrixStudio/Codeforces-Python-Submissions
Iahub helps his grandfather at the farm. Today he must milk the cows. There are *n* cows sitting in a row, numbered from 1 to *n* from left to right. Each cow is either facing to the left or facing to the right. When Iahub milks a cow, all the cows that see the current cow get scared and lose one unit of the quantity of milk that they can give. A cow facing left sees all the cows with lower indices than her index, and a cow facing right sees all the cows with higher indices than her index. A cow that got scared once can get scared again (and lose one more unit of milk). A cow that has been milked once cannot get scared and lose any more milk. You can assume that a cow never loses all the milk she can give (a cow gives an infinitely amount of milk). Iahub can decide the order in which he milks the cows. But he must milk each cow exactly once. Iahub wants to lose as little milk as possible. Print the minimum amount of milk that is lost.
```python from functools import reduce class GukziString: chars = 'abcdefghijklmnopqrstuvwxyz' def __init__(self, string=''): super(GukziString, self).__init__() for ch in GukziString.chars: setattr(self, ch, 0) for ch in string: setattr(self, ch, getattr(self, ch) + 1) def __sub__(self, other): ans = GukziString() for ch in GukziString.chars: setattr(ans, ch, getattr(self, ch) - getattr(other, ch)) return ans def __mul__(self, number): ans = GukziString() for ch in GukziString.chars: setattr(ans, ch, getattr(self, ch) * number) return ans def __floordiv__(self, other): valid_chars = filter(lambda ch: getattr(other, ch) != 0, GukziString.chars) return reduce(lambda x, y: min(x, y), [getattr(self, ch) // getattr(other, ch) for ch in valid_chars]) def __mod__(self, other): return self - other * (self // other) def __str__(self): ans = '' for ch in GukziString.chars: ans += ch * getattr(self, ch) return ans a_str = input() b_str = input() c_str = input() a = GukziString(a_str) b = GukziString(b_str) c = GukziString(c_str) b_count = max(b_count + (a - b * b_count) // c for b_count in range(a // b + 1)) print(f'{b_str * b_count}{c_str * ((a - b * b_count) // c)}{(a - b * b_count) % c}') ```
MatrixStudio/Codeforces-Python-Submissions
It is well known that the planet suffers from the energy crisis. Little Petya doesn't like that and wants to save the world. For this purpose he needs every accumulator to contain the same amount of energy. Initially every accumulator has some amount of energy: the *i*-th accumulator has *a**i* units of energy. Energy can be transferred from one accumulator to the other. Every time *x* units of energy are transferred (*x* is not necessarily an integer) *k* percent of it is lost. That is, if *x* units were transferred from one accumulator to the other, amount of energy in the first one decreased by *x* units and in other increased by units. Your task is to help Petya find what maximum equal amount of energy can be stored in each accumulator after the transfers.
```python def energy(acc, level, perc_loss): surplus = sum([max(x - level, 0) for x in acc]) en_cost = sum([(abs(min(0, x - level)) * 100) / (100 - perc_loss) for x in acc]) return surplus >= en_cost class CodeforcesTask68BSolution: def __init__(self): self.result = '' self.n_k = [] self.accumulators = [] def read_input(self): self.n_k = [int(x) for x in input().split(" ")] self.accumulators = [int(x) for x in input().split(" ")] def process_task(self): l = 0 r = sum(self.accumulators) / self.n_k[0] while r - l >= 0.000_0001: mid = l + (r - l) / 2 if energy(self.accumulators, mid, self.n_k[1]): l = mid else: r = mid self.result = str(r) def get_result(self): return self.result if __name__ == "__main__": Solution = CodeforcesTask68BSolution() Solution.read_input() Solution.process_task() print(Solution.get_result()) ```
MatrixStudio/Codeforces-Python-Submissions
Petr stands in line of *n* people, but he doesn't know exactly which position he occupies. He can say that there are no less than *a* people standing in front of him and no more than *b* people standing behind him. Find the number of different positions Petr can occupy.
```python n,a,b = map(int,input().split()) ans = a+1 print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity. There are *n* columns of toy cubes in the box arranged in a line. The *i*-th column contains *a**i* cubes. At first, the gravity in the box is pulling the cubes downwards. When Chris switches the gravity, it begins to pull all the cubes to the right side of the box. The figure shows the initial and final configurations of the cubes in the box: the cubes that have changed their position are highlighted with orange. Given the initial configuration of the toy cubes in the box, find the amounts of cubes in each of the *n* columns after the gravity switch!
```python n = int(input()) x = list(map(int, input().split())) x.sort() for i in range(n): print(x[i], end=' ') ```
MatrixStudio/Codeforces-Python-Submissions
Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. For example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. When a team plays as a guest on somebody else's stadium, the players put on the guest uniform. The only exception to that rule is: when the home uniform color of the host team matches the guests' uniform, the host team puts on its guest uniform as well. For each team the color of the home and guest uniform is different. There are *n* teams taking part in the national championship. The championship consists of *n*·(*n*<=-<=1) games: each team invites each other team to its stadium. At this point Manao wondered: how many times during the championship is a host team going to put on the guest uniform? Note that the order of the games does not affect this number. You know the colors of the home and guest uniform for each team. For simplicity, the colors are numbered by integers in such a way that no two distinct colors have the same number. Help Manao find the answer to his question.
```python N = int(input()) M = N*(N - 1) MISS = [] FI = [] C = 0 for i in range(N): T = input().split() MISS.append(T[1]) FI.append(T[0]) for i in range(N): for j in (FI) : if j == MISS[i]: C+=1 print(C) ```
MatrixStudio/Codeforces-Python-Submissions
A and B are preparing themselves for programming contests. To train their logical thinking and solve problems better, A and B decided to play chess. During the game A wondered whose position is now stronger. For each chess piece we know its weight: - the queen's weight is 9, - the rook's weight is 5, - the bishop's weight is 3, - the knight's weight is 3, - the pawn's weight is 1, - the king's weight isn't considered in evaluating position. The player's weight equals to the sum of weights of all his pieces on the board. As A doesn't like counting, he asked you to help him determine which player has the larger position weight.
```python w=0 b=0 m=[input() for i in range(8)] for line in m: for p in line: if p=="Q": w+=9 elif p=="R": w+=5 elif p=="B" or p=="N": w+=3 elif p=="P": w+=1 if p=="q": b+=9 elif p=="r": b+=5 elif p=="b" or p=="n": b+=3 elif p=="p": b+=1 if w>b: print("White") elif b>w: print("Black") else: print("Draw") ```
MatrixStudio/Codeforces-Python-Submissions
One rainy gloomy evening when all modules hid in the nearby cafes to drink hot energetic cocktails, the Hexadecimal virus decided to fly over the Mainframe to look for a Great Idea. And she has found one! Why not make her own Codeforces, with blackjack and other really cool stuff? Many people will surely be willing to visit this splendid shrine of high culture. In Mainframe a standard pack of 52 cards is used to play blackjack. The pack contains cards of 13 values: 2, 3, 4, 5, 6, 7, 8, 9, 10, jacks, queens, kings and aces. Each value also exists in one of four suits: hearts, diamonds, clubs and spades. Also, each card earns some value in points assigned to it: cards with value from two to ten earn from 2 to 10 points, correspondingly. An ace can either earn 1 or 11, whatever the player wishes. The picture cards (king, queen and jack) earn 10 points. The number of points a card earns does not depend on the suit. The rules of the game are very simple. The player gets two cards, if the sum of points of those cards equals *n*, then the player wins, otherwise the player loses. The player has already got the first card, it's the queen of spades. To evaluate chances for victory, you should determine how many ways there are to get the second card so that the sum of points exactly equals *n*.
```python n = int(input()) if n <= 10 : print(0) else: if n <= 19: print(4) elif n == 20: print(15) elif n == 21: print(4) else: print(0) ```
MatrixStudio/Codeforces-Python-Submissions
Some dwarves that are finishing the StUDY (State University for Dwarven Youngsters) Bachelor courses, have been told "no genome, no degree". That means that all dwarves should write a thesis on genome. Dwarven genome is far from simple. It is represented by a string that consists of lowercase Latin letters. Dwarf Misha has already chosen the subject for his thesis: determining by two dwarven genomes, whether they belong to the same race. Two dwarves belong to the same race if we can swap two characters in the first dwarf's genome and get the second dwarf's genome as a result. Help Dwarf Misha and find out whether two gnomes belong to the same race or not.
```python s1=input() s2=input() s1=[s1[k] for k in range(len(s1))] s2=[s2[k] for k in range(len(s2))] x=0 ans="" if len(s1)!=len(s2): print("NO") for i in range(len(s1)): for j in range(i+1,len(s1)): s1[i],s1[j]=s1[j],s1[i] if s1==s2: x+=1 ans="YES" break else: s1[i],s1[j]=s1[j],s1[i] if x==1 and ans=="YES": print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of *n* distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers *x* and *y* from the board, he gets *gcd*(*x*,<=*y*) points. At the beginning of the game Bimokh has zero points. Mashmokh wants to win in the game. For this reason he wants his boss to get exactly *k* points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find *n* distinct integers *a*1,<=*a*2,<=...,<=*a**n* such that his boss will score exactly *k* points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
```python n,k=map(int,input().split()) if(k<int(n/2) or (n==1 and k>0)): print(-1) else: v=[] v.append(k-int(n/2)+1) v.append(2*(k-int(n/2)+1)) i=1 while(len(v)<n): if(i!=v[0] and i!=v[1]): v.append(i) i=i+1 f=0 for i in v: if(i>1000000000): f=1 print(-1) if(f==0): for i in v: print(i,end=" ") ```
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 m,n=input().split() m=int(m) n=int(n) if(1<=m and m<=n and n<=16): p=m*n t=p//2 print(t) else: print('Invalid Input') ```
MatrixStudio/Codeforces-Python-Submissions
Dr. Moriarty is about to send a message to Sherlock Holmes. He has a string *s*. String *p* is called a substring of string *s* if you can read it starting from some position in the string *s*. For example, string "aba" has six substrings: "a", "b", "a", "ab", "ba", "aba". Dr. Moriarty plans to take string *s* and cut out some substring from it, let's call it *t*. Then he needs to change the substring *t* zero or more times. As a result, he should obtain a fixed string *u* (which is the string that should be sent to Sherlock Holmes). One change is defined as making one of the following actions: - Insert one letter to any end of the string. - Delete one letter from any end of the string. - Change one letter into any other one. Moriarty is very smart and after he chooses some substring *t*, he always makes the minimal number of changes to obtain *u*. Help Moriarty choose the best substring *t* from all substrings of the string *s*. The substring *t* should minimize the number of changes Moriarty should make to obtain the string *u* from it.
```python print("_RANDOM_GUESS_1689418688.3535597")# 1689418688.3535807 ```
MatrixStudio/Codeforces-Python-Submissions
Iahub and Iahubina went to a date at a luxury restaurant. Everything went fine until paying for the food. Instead of money, the waiter wants Iahub to write a Hungry sequence consisting of *n* integers. A sequence *a*1, *a*2, ..., *a**n*, consisting of *n* integers, is Hungry if and only if: - Its elements are in increasing order. That is an inequality *a**i*<=&lt;<=*a**j* holds for any two indices *i*,<=*j* (*i*<=&lt;<=*j*). - For any two indices *i* and *j* (*i*<=&lt;<=*j*), *a**j* must not be divisible by *a**i*. Iahub is in trouble, so he asks you for help. Find a Hungry sequence with *n* elements.
```python # for _ in range(1,int(input())+1): n=int(input()) # n,k=map(int,input().split()) # s=(input()) # a=list(map(int,input().split())) arr=[True]*(10**7) # arr[0],arr[1]=True,True for i in range(2,10**5): if arr[i]==True: print(i,end=" ") n-=1 if n==0: exit() for j in range(i*i,10**5+1,i): arr[j]=False ```
MatrixStudio/Codeforces-Python-Submissions
Igor is in the museum and he wants to see as many pictures as possible. Museum can be represented as a rectangular field of *n*<=×<=*m* cells. Each cell is either empty or impassable. Empty cells are marked with '.', impassable cells are marked with '*'. Every two adjacent cells of different types (one empty and one impassable) are divided by a wall containing one picture. At the beginning Igor is in some empty cell. At every moment he can move to any empty cell that share a side with the current one. For several starting positions you should calculate the maximum number of pictures that Igor can see. Igor is able to see the picture only if he is in the cell adjacent to the wall with this picture. Igor have a lot of time, so he will examine every picture he can see.
```python def dfs(x, y): vis[x][y] = True path.append((x, y)) paintings = 0 for dx, dy in ((-1, 0), (1, 0), (0, -1), (0, 1)): x1, y1 = x+dx, y+dy if x1 < 0 or x1 >= n or y1 < 0 or y1 >= m or vis[x1][y1]: continue if grid[x1][y1] == "*": paintings += 1 else: vis[x1][y1] = True paintings += dfs(x1, y1) return paintings if __name__ == "__main__": n, m, k = map(int, input().split()) grid = [input() for _ in range(n)] count = [[0 for _ in range(m)] for _ in range(n)] vis = [[False for _ in range(m)] for _ in range(n)] for i in range(n): for j in range(m): if not vis[i][j] and grid[i][j] != "*": path = list() paintings = dfs(i, j) for x, y in path: count[x][y] = paintings for _ in range(k): x, y = map(int, input().split()) print(count[x-1][y-1]) ```
MatrixStudio/Codeforces-Python-Submissions
After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer. At the start of the day they have *x* ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. Each person in the queue wants either to take several ice cream packs for himself and his friends or to give several ice cream packs to Kay and Gerda (carriers that bring ice cream have to stand in the same queue). If a carrier with *d* ice cream packs comes to the house, then Kay and Gerda take all his packs. If a child who wants to take *d* ice cream packs comes to the house, then Kay and Gerda will give him *d* packs if they have enough ice cream, otherwise the child will get no ice cream at all and will leave in distress. Kay wants to find the amount of ice cream they will have after all people will leave from the queue, and Gerda wants to find the number of distressed kids.
```python n,x=map(int,input().split()) count=0 for i in range(0,n,1): s,c=map(str,input().split()) c=int(c) if s=='+': x=x+c else: if x-c<0: count=count+1 else: x=x-c print(str(x)+" "+str(count)) ```
MatrixStudio/Codeforces-Python-Submissions
There exists an island called Arpa’s land, some beautiful girls live there, as ugly ones do. Mehrdad wants to become minister of Arpa’s land. Arpa has prepared an exam. Exam has only one question, given *n*, print the last digit of 1378*n*. Mehrdad has become quite confused and wants you to help him. Please help, although it's a naive cheat.
```python n=int(input()) if n==0: print(1) else: w=n%4 if w==1: print(8) elif w==2: print(4) elif w==3: print(2) else: print(6) ```
MatrixStudio/Codeforces-Python-Submissions
Pig is visiting a friend. Pig's house is located at point 0, and his friend's house is located at point *m* on an axis. Pig can use teleports to move along the axis. To use a teleport, Pig should come to a certain point (where the teleport is located) and choose where to move: for each teleport there is the rightmost point it can move Pig to, this point is known as the limit of the teleport. Formally, a teleport located at point *x* with limit *y* can move Pig from point *x* to any point within the segment [*x*;<=*y*], including the bounds. Determine if Pig can visit the friend using teleports only, or he should use his car.
```python n,m = map(int,input().split()) st = 0 a,b = map(int,input().split()) if a != 0: print("NO") else: st = a end = b flag = True for i in range(n-1): a,b = map(int,input().split()) if end>=m: break if end>=a: st = a end = b else: flag = False break if flag: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At that as little as possible letters should be changed in the word. For example, the word HoUse must be replaced with house, and the word ViP — with VIP. If a word contains an equal number of uppercase and lowercase letters, you should replace all the letters with lowercase ones. For example, maTRIx should be replaced by matrix. Your task is to use the given method on one given word.
```python for _ in range(1): string = list(input()) n = len(string) upperCase = 0 lowerCase = 0 for i in range(n): if string[i].isupper(); upperCase += 1 else: lowerCase += 1 if upperCase <= lowerCase: print(string.lower()) else: print(string.upper()) ```
MatrixStudio/Codeforces-Python-Submissions
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob. Right now, Limak and Bob weigh *a* and *b* respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight. Limak eats a lot and his weight is tripled after every year, while Bob's weight is doubled after every year. After how many full years will Limak become strictly larger (strictly heavier) than Bob?
```python raj,shiv= list(map(int, input().split())) r = int() while raj <shiv: raj= raj*3 shiv = shiv*2 r =r+ 1 print(r) ```
MatrixStudio/Codeforces-Python-Submissions
Mancala is a game famous in the Middle East. It is played on a board that consists of 14 holes. Initially, each hole has $a_i$ stones. When a player makes a move, he chooses a hole which contains a positive number of stones. He takes all the stones inside it and then redistributes these stones one by one in the next holes in a counter-clockwise direction. Note that the counter-clockwise order means if the player takes the stones from hole $i$, he will put one stone in the $(i+1)$-th hole, then in the $(i+2)$-th, etc. If he puts a stone in the $14$-th hole, the next one will be put in the first hole. After the move, the player collects all the stones from holes that contain even number of stones. The number of stones collected by player is the score, according to Resli. Resli is a famous Mancala player. He wants to know the maximum score he can obtain after one move.
```python ai = list(map(int,input().split())) i = 0 ans = 0 while i < 14: j = 0 ai2 = [0] * 14 while j < 14: ai2[j] = ai[j] j+= 1 j = 0 temp = ai2[i] temp2 = temp % 14 temp3 = temp // 14 ai2[i] = 0 tempans= 0 while j < 14: ai2[j] += temp3 j += 1 j = (i+1)%14 while temp2 > 0: ai2[j] += 1 temp2 -= 1 j = (j+1)%14 j = 0 while j < 14: if ai2[j] % 2 == 0: tempans += ai2[j] j += 1 ans = max(ans,tempans) i += 1 print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
The bear has a string *s*<==<=*s*1*s*2... *s*|*s*| (record |*s*| is the string's length), consisting of lowercase English letters. The bear wants to count the number of such pairs of indices *i*,<=*j* (1<=≤<=*i*<=≤<=*j*<=≤<=|*s*|), that string *x*(*i*,<=*j*)<==<=*s**i**s**i*<=+<=1... *s**j* contains at least one string "bear" as a substring. String *x*(*i*,<=*j*) contains string "bear", if there is such index *k* (*i*<=≤<=*k*<=≤<=*j*<=-<=3), that *s**k*<==<=*b*, *s**k*<=+<=1<==<=*e*, *s**k*<=+<=2<==<=*a*, *s**k*<=+<=3<==<=*r*. Help the bear cope with the given problem.
```python def bear(s): b =0 for i in range(len(s)): c = s.find('bear' , i) if c >=0: b+=len(s)-c-3 return b if __name__ == '__main__': s = input() print(bear(s)) ```
MatrixStudio/Codeforces-Python-Submissions
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc. However, it's easy to make a mistake during the «translation». Vasya translated word *s* from Berlandish into Birlandish as *t*. Help him: find out if he translated the word correctly.
```python s = input() t = input() s = ' '.join(s) s = list(s.split()) s.reverse() t = ' '.join(t) t = list(t.split()) if s == t: print('YES') else: print('NO') ```
MatrixStudio/Codeforces-Python-Submissions
The polar bears are going fishing. They plan to sail from (*s**x*,<=*s**y*) to (*e**x*,<=*e**y*). However, the boat can only sail by wind. At each second, the wind blows in one of these directions: east, south, west or north. Assume the boat is currently at (*x*,<=*y*). - If the wind blows to the east, the boat will move to (*x*<=+<=1,<=*y*). - If the wind blows to the south, the boat will move to (*x*,<=*y*<=-<=1). - If the wind blows to the west, the boat will move to (*x*<=-<=1,<=*y*). - If the wind blows to the north, the boat will move to (*x*,<=*y*<=+<=1). Alternatively, they can hold the boat by the anchor. In this case, the boat stays at (*x*,<=*y*). Given the wind direction for *t* seconds, what is the earliest time they sail to (*e**x*,<=*e**y*)?
```python t, s_x, s_y, e_x, e_y = map(int, input().split()) directions = list(input()) x_dir = e_x - s_x y_dir = e_y - s_y duration = 0 reached = False cur_point = [s_x, s_y] for d in directions: if x_dir == 0 and y_dir == 0: reached = True break if d == 'S' and y_dir<0: y_dir +=1 elif d == "N" and y_dir > 0: y_dir -=1 elif d == "E" and x_dir > 0: x_dir -=1 elif d == 'W' and x_dir < 0: x_dir += 1 duration += 1 if not reached: print('-1') else: print(duration) ```
MatrixStudio/Codeforces-Python-Submissions
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second. One day in 230 AD Shapur was trying to find out if any one can possibly do calculations faster than him. As a result he made a very great contest and asked every one to come and take part. In his contest he gave the contestants many different pairs of numbers. Each number is made from digits 0 or 1. The contestants should write a new number corresponding to the given pair of numbers. The rule is simple: The *i*-th digit of the answer is 1 if and only if the *i*-th digit of the two given numbers differ. In the other case the *i*-th digit of the answer is 0. Shapur made many numbers and first tried his own speed. He saw that he can perform these operations on numbers of length ∞ (length of a number is number of digits in it) in a glance! He always gives correct answers so he expects the contestants to give correct answers, too. He is a good fellow so he won't give anyone very big numbers and he always gives one person numbers of same length. Now you are going to take part in Shapur's contest. See if you are faster and more accurate.
```python num1,num2 = input(),input() str1 = '' for i in range(0,len(num1)): if num1[i] != num2[i]: str1 += '1' else: str1 += '0' print(str1) ```
MatrixStudio/Codeforces-Python-Submissions
Pig is visiting a friend. Pig's house is located at point 0, and his friend's house is located at point *m* on an axis. Pig can use teleports to move along the axis. To use a teleport, Pig should come to a certain point (where the teleport is located) and choose where to move: for each teleport there is the rightmost point it can move Pig to, this point is known as the limit of the teleport. Formally, a teleport located at point *x* with limit *y* can move Pig from point *x* to any point within the segment [*x*;<=*y*], including the bounds. Determine if Pig can visit the friend using teleports only, or he should use his car.
```python t, f = [int(x) for x in input().split()] l = [] while(t): a, b = [int(x) for x in input().split()] l.append([a, b]) t -= 1 prev_a = 0 prev_d = 0 flag = "NO" for point in l: if(prev_a == 0 and prev_d == 0): prev_a = point[0] prev_d = point[1] else: if(point[1] > prev_d and point[1] != f): prev_a = point[0] prev_d = point[1] elif(point[1] > prev_d and point[1] == f): if(point[0] >= prev_a and point[0] <= prev_d): flag = "YES" break print(flag) ```
MatrixStudio/Codeforces-Python-Submissions
*n* soldiers stand in a circle. For each soldier his height *a**i* is known. A reconnaissance unit can be made of such two neighbouring soldiers, whose heights difference is minimal, i.e. |*a**i*<=-<=*a**j*| is minimal. So each of them will be less noticeable with the other. Output any pair of soldiers that can form a reconnaissance unit.
```python n = int(input()) arr = list(map(int, input().split())) pair = [] dif = float("inf") for i in range(1, n): temp = abs(arr[i] - arr[i - 1]) if temp < dif: dif = temp pair = [i, i+1] if abs(arr[0] - arr[-1]) < dif: pair = [n, 1] print(*pair, sep=" ") ```
MatrixStudio/Codeforces-Python-Submissions
An exam for *n* students will take place in a long and narrow room, so the students will sit in a line in some order. The teacher suspects that students with adjacent numbers (*i* and *i*<=+<=1) always studied side by side and became friends and if they take an exam sitting next to each other, they will help each other for sure. Your task is to choose the maximum number of students and make such an arrangement of students in the room that no two students with adjacent numbers sit side by side.
```python n = int(input()) def main(): if n in [1, 2]: print(1) print(1) return elif n == 3: print(2) print(1, 3) return elif n == 4: print(3) print(1, 4, 2) return print(n) for i in range(1, n+1, 2): print(i, end=' ') for i in range(2, n+1, 2): print(i, end=' ') main() ```
MatrixStudio/Codeforces-Python-Submissions
ZS the Coder is coding on a crazy computer. If you don't type in a word for a *c* consecutive seconds, everything you typed disappear! More formally, if you typed a word at second *a* and then the next word at second *b*, then if *b*<=-<=*a*<=≤<=*c*, just the new word is appended to other words on the screen. If *b*<=-<=*a*<=&gt;<=*c*, then everything on the screen disappears and after that the word you have typed appears on the screen. For example, if *c*<==<=5 and you typed words at seconds 1,<=3,<=8,<=14,<=19,<=20 then at the second 8 there will be 3 words on the screen. After that, everything disappears at the second 13 because nothing was typed. At the seconds 14 and 19 another two words are typed, and finally, at the second 20, one more word is typed, and a total of 3 words remain on the screen. You're given the times when ZS the Coder typed the words. Determine how many words remain on the screen after he finished typing everything.
```python """ https://codeforces.com/problemset/problem/716/A """ def ints(inp): return list(map(int, inp.split())) w = list() n, c = ints(input()) nums = ints(input()) for i in range(n - 1): if nums[i+1] - nums[i] <= c: w.append(nums[i+1]) w.append(nums[i]) else: w.clear() print(len(set(w))) ```
MatrixStudio/Codeforces-Python-Submissions
Vanya got bored and he painted *n* distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area.
```python import functools class Point: def __init__(self, x, y): self.x = x self.y = y def area_triangle(self, p1, p2): vector_1 = [p1.x - self.x, p1.y - self.y] vector_2 = [p2.x - self.x, p2.y - self.y] return vector_1[0] * vector_2[1] - vector_1[1] * vector_2[0] class NumberTriangles: def solution(self): num_points = int(input()) points = [] for _ in range(num_points): point = input() point = point.split(" ") points.append(Point(int(point[0]), int(point[1]))) num_triangles = 0 for i in range(num_points): for j in range(i + 1, num_points): for k in range(j + 1, num_points): area = points[i].area_triangle(points[j], points[k]) if area != 0: num_triangles += 1 print(num_triangles) if __name__ == "__main__": num_triangles = NumberTriangles() num_triangles.solution() ```
MatrixStudio/Codeforces-Python-Submissions
Valera runs a 24/7 fast food cafe. He magically learned that next day *n* people will visit his cafe. For each person we know the arrival time: the *i*-th person comes exactly at *h**i* hours *m**i* minutes. The cafe spends less than a minute to serve each client, but if a client comes in and sees that there is no free cash, than he doesn't want to wait and leaves the cafe immediately. Valera is very greedy, so he wants to serve all *n* customers next day (and get more profit). However, for that he needs to ensure that at each moment of time the number of working cashes is no less than the number of clients in the cafe. Help Valera count the minimum number of cashes to work at his cafe next day, so that they can serve all visitors.
```python t=int(input()) count=1 a=-1 b=-1 for i in range(t): n=int(input()) m=int(input()) if n==a and m==b: count=count+1 a=n b=m print(count) ```
MatrixStudio/Codeforces-Python-Submissions
"Contestant who earns a score equal to or greater than the *k*-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." — an excerpt from contest rules. A total of *n* participants took part in the contest (*n*<=≥<=*k*), and you already know their scores. Calculate how many participants will advance to the next round.
```python n,k=map(int,input().split()) x=list(input().split()) mw=0 for i in range(0,n): a=x[i] if a=='0': break if i<k-1: mw += 1 la=a elif a==la: mw += 1 print(mw) ```
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 r1 = list(map(int,input().split())) r2 = list(map(int,input().split())) r3 = list(map(int,input().split())) r = sum(r1)+sum(r2)+sum(r3) r1[0] = r//2 - sum(r1) r2[1] = r//2 - sum(r2) r3[2] = r//2 - sum(r3) print(*r1) print(*r2) print(*r3) ```
MatrixStudio/Codeforces-Python-Submissions
ZS the Coder loves to read the dictionary. He thinks that a word is nice if there exists a substring (contiguous segment of letters) of it of length 26 where each letter of English alphabet appears exactly once. In particular, if the string has length strictly less than 26, no such substring exists and thus it is not nice. Now, ZS the Coder tells you a word, where some of its letters are missing as he forgot them. He wants to determine if it is possible to fill in the missing letters so that the resulting word is nice. If it is possible, he needs you to find an example of such a word as well. Can you help him?
```python s = input() n = len(s) al = set([chr(i + ord('A')) for i in range(26)]) for i in range(n - 26 + 1): c = 0 a = set() for j in range(i, i + 26): if(s[j] == '?'): c += 1 else: a.add(s[j]) if(c + len(a) == 26): l = list(al - a) k = 0 ans = '' for j in range(i, i + 26): if(s[j] == '?'): ans += l[k] k += 1 else: ans += s[j] print(ans) break else: print(-1) ```
MatrixStudio/Codeforces-Python-Submissions
Just in case somebody missed it: we have wonderful girls in Arpa’s land. Arpa has a rooted tree (connected acyclic graph) consisting of *n* vertices. The vertices are numbered 1 through *n*, the vertex 1 is the root. There is a letter written on each edge of this tree. Mehrdad is a fan of Dokhtar-kosh things. He call a string Dokhtar-kosh, if we can shuffle the characters in string such that it becomes palindrome. He asks Arpa, for each vertex *v*, what is the length of the longest simple path in subtree of *v* that form a Dokhtar-kosh string.
```python #include <bits/stdc++.h> #define mem(a,b) memset(a,b,sizeof a); #define rep(i,a,b) for(int i = a; i <= b; i++) #define per(i,a,b) for(int i = a; i >= b; i--) #define __ ios::sync_with_stdio(0);cin.tie(0);cout.tie(0) typedef long long ll; typedef double db; const int inf = 1e8; const int N = 5e5+10; const db EPS = 1e-9; using namespace std; void dbg() {cout << "\n";} template<typename T, typename... A> void dbg(T a, A... x) {cout << a << ' '; dbg(x...);} #define logs(x...) {cout << #x << " -> "; dbg(x);} int n,a[N],tot,head[N],sz[N],son[N],f[1<<22],dep[N],ans[N]; //f[i]:表示子树中异或和为f[i]的最大深度 struct Node{ int to,next; }e[N]; void add(int x,int y){ e[++tot].to = y, e[tot].next = head[x], head[x] = tot; } void dfs1(int x){ ans[x] = -inf; sz[x] = 1; for(int i = head[x]; i; i = e[i].next){ int y = e[i].to; dep[y] = dep[x]+1; a[y] ^= a[x]; dfs1(y); sz[x] += sz[y]; if(sz[y] > sz[son[x]]) son[x] = y; } } void Delete(int x){ f[a[x]] = -inf; for(int i = head[x]; i; i = e[i].next) Delete(e[i].to); } void modify(int x,int fa){ ans[fa] = max(ans[fa],f[a[x]]+dep[x]-2*dep[fa]); for(int i = 0; i < 22; i++) ans[fa] = max(ans[fa],f[a[x]^(1<<i)]+dep[x]-2*dep[fa]); for(int i = head[x]; i; i = e[i].next) modify(e[i].to,fa); } void ins(int x){ f[a[x]] = max(f[a[x]],dep[x]); for(int i = head[x]; i; i = e[i].next) ins(e[i].to); } void dfs2(int x){ ans[x] = 0; for(int i = head[x]; i; i = e[i].next) if(e[i].to != son[x]) dfs2(e[i].to), Delete(e[i].to); if(son[x]) dfs2(son[x]); f[a[x]] = max(f[a[x]],dep[x]); //路径经过x for(int i = head[x]; i; i = e[i].next) if(e[i].to != son[x]) modify(e[i].to,x), ins(e[i].to); //x为路径端点 ans[x] = max(ans[x],f[a[x]]-dep[x]); for(int i = 0; i < 22; i++) ans[x] = max(ans[x],f[a[x]^(1<<i)]-dep[x]); //路径不经过x for(int i = head[x]; i; i = e[i].next) ans[x] = max(ans[x],ans[e[i].to]); } int main() { scanf("%d",&n); tot = 1; rep(i,0,(1<<22)-1) f[i] = -inf; //不要忘记赋初值 rep(i,2,n){ int p; char s[10]; scanf("%d%s",&p,s); add(p,i); a[i] = 1<<(s[0]-'a'); } dfs1(1); dfs2(1); rep(i,1,n) printf("%d%c",ans[i]," \n"[i==n]); return 0; } ```
MatrixStudio/Codeforces-Python-Submissions
Victor tries to write his own text editor, with word correction included. However, the rules of word correction are really strange. Victor thinks that if a word contains two consecutive vowels, then it's kinda weird and it needs to be replaced. So the word corrector works in such a way: as long as there are two consecutive vowels in the word, it deletes the first vowel in a word such that there is another vowel right before it. If there are no two consecutive vowels in the word, it is considered to be correct. You are given a word *s*. Can you predict what will it become after correction? In this problem letters a, e, i, o, u and y are considered to be vowels.
```python n=int(input()) l=list(input()) i=0 while(len(l)>1 and i<len(l)-1): if(l[i]=='o' or l[i]=='e' or l[i]=='a' or l[i]=='i' or l[i]=='u' or l[i]=='y'): if(l[i+1]=='o' or l[i+1]=='e' or l[i+1]=='a' or l[i+1]=='i' or l[i+1]=='u' or l[i+1]=='y'): l.remove(l[i+1]) else: i+=2 else: i+=1 print(''.join(l)) ```
MatrixStudio/Codeforces-Python-Submissions
Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water. The only dry land there is an archipelago of *n* narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island *i* has coordinates [*l**i*,<=*r**i*], besides, *r**i*<=&lt;<=*l**i*<=+<=1 for 1<=≤<=*i*<=≤<=*n*<=-<=1. To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length *a* can be placed between the *i*-th and the (*i*<=+<=1)-th islads, if there are such coordinates of *x* and *y*, that *l**i*<=≤<=*x*<=≤<=*r**i*, *l**i*<=+<=1<=≤<=*y*<=≤<=*r**i*<=+<=1 and *y*<=-<=*x*<==<=*a*. The detective was supplied with *m* bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands.
```python import sys from bisect import bisect_left, bisect_right from math import inf input = sys.stdin.readline def sovle(): n, m = list(map(int, input().split())) intervals = [] for _ in range(m): l, r = list(map(int, input().split())) intervals.append([l, r]) a = list(map(int, input().split())) lengths = [] # [minn, maxn] for i in range(1, n): l1, r1 = intervals[i - 1][0], intervals[i - 1][1] l2, r2 = intervals[i][0], intervals[i][1] lengths.append([l2 - r1, r2 - l1]) # 能否在a中选出n - 1个(可重复)落在lengths的n - 1个区间中的 # 要把对应的第几座桥给选出来, 每个桥最多只能用一次啊 # 按桥的长度二分,多加一维记录第几个 bridges = [] for i, v in enumerate(a): bridges.append([v, i + 1]) bridges.sort() print(lengths) print(bridges) ans = [] flag = True for minn, maxn in lengths: idx1 = bisect_left(bridges, [minn, -inf]) idx2 = bisect_right(bridges, [maxn, inf]) # 在[idx1, idx2)中选一个代表 print(idx1, idx2) if idx1 == idx2: flag = False break if not flag: print('No') else: print(*ans) if __name__ == '__main__': sovle() ```
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 n=input() uc=0 lc=0 for i in n: if i.islower(): lc+=1 else: uc+=1 if(uc>lc): print(n.upper()) else: print(n.lower()) ```
MatrixStudio/Codeforces-Python-Submissions
After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer. At the start of the day they have *x* ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. Each person in the queue wants either to take several ice cream packs for himself and his friends or to give several ice cream packs to Kay and Gerda (carriers that bring ice cream have to stand in the same queue). If a carrier with *d* ice cream packs comes to the house, then Kay and Gerda take all his packs. If a child who wants to take *d* ice cream packs comes to the house, then Kay and Gerda will give him *d* packs if they have enough ice cream, otherwise the child will get no ice cream at all and will leave in distress. Kay wants to find the amount of ice cream they will have after all people will leave from the queue, and Gerda wants to find the number of distressed kids.
```python n, ans = map(int, input().split()) d = 0 for i in range(n): p = input() if "+ " in p: p = p.replace("+ ", "") ans += int(p) else: p = p.replace("- ", "") p = int(p) if ans >= p: ans -= p else: d += 1 print(ans, d) ```
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 import re import sys s=input() if s==s[::-1]: s=s.replace(s[-1],"",1) if s==s[::-1]: print("0") else: print(len(s)) else: print(len(s)) ```
MatrixStudio/Codeforces-Python-Submissions
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second. One day in 230 AD Shapur was trying to find out if any one can possibly do calculations faster than him. As a result he made a very great contest and asked every one to come and take part. In his contest he gave the contestants many different pairs of numbers. Each number is made from digits 0 or 1. The contestants should write a new number corresponding to the given pair of numbers. The rule is simple: The *i*-th digit of the answer is 1 if and only if the *i*-th digit of the two given numbers differ. In the other case the *i*-th digit of the answer is 0. Shapur made many numbers and first tried his own speed. He saw that he can perform these operations on numbers of length ∞ (length of a number is number of digits in it) in a glance! He always gives correct answers so he expects the contestants to give correct answers, too. He is a good fellow so he won't give anyone very big numbers and he always gives one person numbers of same length. Now you are going to take part in Shapur's contest. See if you are faster and more accurate.
```python num1=input() num2=input() for i in range(0,len(num1)): if(num1[i]==num2[i]):print(0,end='') else:print(1,end='') ```
MatrixStudio/Codeforces-Python-Submissions
A little boy Gerald entered a clothes shop and found out something very unpleasant: not all clothes turns out to match. For example, Gerald noticed that he looks rather ridiculous in a smoking suit and a baseball cap. Overall the shop sells *n* clothing items, and exactly *m* pairs of clothing items match. Each item has its price, represented by an integer number of rubles. Gerald wants to buy three clothing items so that they matched each other. Besides, he wants to spend as little money as possible. Find the least possible sum he can spend.
```python n,m=map(int,input().split()) l=list(map(int,input().split())) a=[] for i in range(m): x=list(map(int,input().split())) a.append(x) if m==2: print(-1) else: r=[] for i in range(len(a)): for j in range(i+1,len(a)): for k in range(j+1,len(a)): q=list(set(a[i])|set(a[j])|set(a[k])) if q not in r and len(q)==3: r.append(q) if len(r)==0: print(-1) else: t=[] for i in r: s=0 for j in i: s=s+l[j-1] t.append(s) print(min(t)) ```
MatrixStudio/Codeforces-Python-Submissions
There are *n* boys and *m* girls studying in the class. They should stand in a line so that boys and girls alternated there as much as possible. Let's assume that positions in the line are indexed from left to right by numbers from 1 to *n*<=+<=*m*. Then the number of integers *i* (1<=≤<=*i*<=&lt;<=*n*<=+<=*m*) such that positions with indexes *i* and *i*<=+<=1 contain children of different genders (position *i* has a girl and position *i*<=+<=1 has a boy or vice versa) must be as large as possible. Help the children and tell them how to form the line.
```python nm = input("").split(" ") nm = [int(x) for x in nm] n, m = nm finalString = "" if n > m: for item in range(m): finalString += "BG" for item in range(n-m): finalString += "B" else: for item in range(n): finalString += "GB" for item in range(m-n): finalString += "G" print(finalString) ```
MatrixStudio/Codeforces-Python-Submissions
Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpredictable place. But to their great regret, the leave turned to be very short, so it will be enough to visit one of the three above named places. That's why Yakko, as the cleverest, came up with a truly genius idea: let each of the three roll an ordinary six-sided die, and the one with the highest amount of points will be the winner, and will take the other two to the place of his/her dreams. Yakko thrown a die and got Y points, Wakko — W points. It was Dot's turn. But she didn't hurry. Dot wanted to know for sure what were her chances to visit Transylvania. It is known that Yakko and Wakko are true gentlemen, that's why if they have the same amount of points with Dot, they will let Dot win.
```python from fractions import Fraction Yakko, Wakko = input().split() Yakko = int(Yakko) Wakko = int(Wakko) max_v = max(Yakko, Wakko) Die_Roll = 6 - max_v + 1 for i in range(6, 0, -1): if(Yakko == 1 and Wakko == 1): print(str(Yakko) + "/" + str(Wakko)) break elif(Die_Roll == 5): print(Fraction(Die_Roll / i).limit_denominator()) break elif(Die_Roll == 4): print(Fraction(Die-Roll / i).limit_denominator()) break elif(i % Die_Roll == 0): print(Fraction(Die_Roll / i).limit_denominator()) break ```
MatrixStudio/Codeforces-Python-Submissions
Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are *n* drinks in his fridge, the volume fraction of orange juice in the *i*-th drink equals *p**i* percent. One day Vasya decided to make himself an orange cocktail. He took equal proportions of each of the *n* drinks and mixed them. Then he wondered, how much orange juice the cocktail has. Find the volume fraction of orange juice in the final drink.
```python t=int(input()) x=list(map(int,input().split())) b=sum(x) a=len(x) c="{:.12f}".format(b/a) print(c) ```
MatrixStudio/Codeforces-Python-Submissions
Noora is a student of one famous high school. It's her final year in school — she is going to study in university next year. However, she has to get an «A» graduation certificate in order to apply to a prestigious one. In school, where Noora is studying, teachers are putting down marks to the online class register, which are integers from 1 to *k*. The worst mark is 1, the best is *k*. Mark that is going to the certificate, is calculated as an average of all the marks, rounded to the closest integer. If several answers are possible, rounding up is produced. For example, 7.3 is rounded to 7, but 7.5 and 7.8784 — to 8. For instance, if Noora has marks [8,<=9], then the mark to the certificate is 9, because the average is equal to 8.5 and rounded to 9, but if the marks are [8,<=8,<=9], Noora will have graduation certificate with 8. To graduate with «A» certificate, Noora has to have mark *k*. Noora got *n* marks in register this year. However, she is afraid that her marks are not enough to get final mark *k*. Noora decided to ask for help in the internet, where hacker Leha immediately responded to her request. He is ready to hack class register for Noora and to add Noora any number of additional marks from 1 to *k*. At the same time, Leha want his hack be unseen to everyone, so he decided to add as less as possible additional marks. Please help Leha to calculate the minimal number of marks he has to add, so that final Noora's mark will become equal to *k*.
```python import math n, k = map(int, input().split()) amt = 0 nums = [int(x) for x in input().split()] amt = sum(nums) ans = 2*n*k - n - 2*amt print(math.ceil(ans) if ans >=0 else 0) ```
MatrixStudio/Codeforces-Python-Submissions
The New Year is coming! That's why many people today are busy preparing New Year presents. Vasily the Programmer is no exception. Vasily knows that the best present is (no, it's not a contest) money. He's put *n* empty wallets from left to right in a row and decided how much money to put in what wallet. Vasily decided to put *a**i* coins to the *i*-th wallet from the left. Vasily is a very busy man, so the money are sorted into the bags by his robot. Initially, the robot stands by the leftmost wallet in the row. The robot can follow instructions of three types: go to the wallet that is to the left of the current one (if such wallet exists), go to the wallet that is to the right of the current one (if such wallet exists), put a coin to the current wallet. Due to some technical malfunctions the robot cannot follow two "put a coin" instructions in a row. Vasily doesn't want to wait for long, so he wants to write a program for the robot that contains at most 106 operations (not necessarily minimum in length) the robot can use to put coins into the wallets. Help him.
```python import sys input = sys.stdin.readline n = int(input()) w = list(map(int, input().split())) d = '' for i in range(n-1): d += 'PRL'*w[i] d += 'R' d += 'PLR'*w[-1] print(d) ```
MatrixStudio/Codeforces-Python-Submissions
Sereja and Dima play a game. The rules of the game are very simple. The players have *n* cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The game ends when there is no more cards. The player who has the maximum sum of numbers on his cards by the end of the game, wins. Sereja and Dima are being greedy. Each of them chooses the card with the larger number during his move. Inna is a friend of Sereja and Dima. She knows which strategy the guys are using, so she wants to determine the final score, given the initial state of the game. Help her.
```python n=int(input()) a=list(map(int,input().split())) s=0 d=0 for i in range(n): b=max(a[0],a[-1]) if i%2==0: s+=b else: d+=b a.remove(b) print(s,d) ```
MatrixStudio/Codeforces-Python-Submissions
Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he wants to give Dumbledore exactly *x* drops of the potion he made. Value of *x* is calculated as maximum of *p*·*a**i*<=+<=*q*·*a**j*<=+<=*r*·*a**k* for given *p*,<=*q*,<=*r* and array *a*1,<=*a*2,<=... *a**n* such that 1<=≤<=*i*<=≤<=*j*<=≤<=*k*<=≤<=*n*. Help Snape find the value of *x*. Do note that the value of *x* may be negative.
```python class MarvoloGauntRing: def __init__(self, p, q, r, arr): self.arr = arr self.p = p self.q = q self.r = r def give_x_potions(self): p_max = self.prefix_max() print(p_max) s_max = self.sufix_max() print(s_max) x = float('-inf') for i in range(0, len(self.arr)): x = max(x, p_max[i] + self.q * self.arr[i] + s_max[i]) return x def prefix_max(self): p_max = [0]*len(self.arr) p_max[0] = self.arr[0] * self.p for i in range(1, len(self.arr)): p_max[i] = max(p_max[i-1], self.p * self.arr[i]) return p_max def sufix_max(self): s_max = [0]*len(self.arr) s_max[len(self.arr)-1] = self.arr[len(self.arr)-1] * self.r for i in range(len(self.arr)-2, -1, -1): s_max[i] = max(s_max[i+1], self.r * self.arr[i]) return s_max n,p,q,r = map(int, input().split()) arr = list(map(int, input().split())) print(MarvoloGauntRing(p,q,r, arr).give_x_potions()) ```
MatrixStudio/Codeforces-Python-Submissions
Last week, Hamed learned about a new type of equations in his math class called Modular Equations. Lets define *i* modulo *j* as the remainder of division of *i* by *j* and denote it by . A Modular Equation, as Hamed's teacher described, is an equation of the form in which *a* and *b* are two non-negative integers and *x* is a variable. We call a positive integer *x* for which a solution of our equation. Hamed didn't pay much attention to the class since he was watching a movie. He only managed to understand the definitions of these equations. Now he wants to write his math exercises but since he has no idea how to do that, he asked you for help. He has told you all he knows about Modular Equations and asked you to write a program which given two numbers *a* and *b* determines how many answers the Modular Equation has.
```python a, b = map(int, input().split(" ")) a1 = a - b if a == b: print("infinity") else: cont = 0 i = 1 while i ** 2 <= a1: if a1 % i == 0 and i > b: cont += 1 if a1 % i == 0 and b < a1 // i != i: cont += 1 i += 1 print(cont) ```
MatrixStudio/Codeforces-Python-Submissions
Bash wants to become a Pokemon master one day. Although he liked a lot of Pokemon, he has always been fascinated by Bulbasaur the most. Soon, things started getting serious and his fascination turned into an obsession. Since he is too young to go out and catch Bulbasaur, he came up with his own way of catching a Bulbasaur. Each day, he takes the front page of the newspaper. He cuts out the letters one at a time, from anywhere on the front page of the newspaper to form the word "Bulbasaur" (without quotes) and sticks it on his wall. Bash is very particular about case — the first letter of "Bulbasaur" must be upper case and the rest must be lower case. By doing this he thinks he has caught one Bulbasaur. He then repeats this step on the left over part of the newspaper. He keeps doing this until it is not possible to form the word "Bulbasaur" from the newspaper. Given the text on the front page of the newspaper, can you tell how many Bulbasaurs he will catch today? Note: uppercase and lowercase letters are considered different.
```python s = input() b1 = u = b = l = a = s1 = u = r = 0 for i in range(len(s)): if s[i] == 'B': b1 +=1 if s[i] == 'u': u +=1 if s[i] == 'l': l +=1 if s[i] == 'b': b +=1 if s[i] == 'a': a +=1 if s[i] == 's': s1 +=1 if s[i] == 'r': r +=1 a = a//2 u = u//2 print (min(b1,u,b,l,a,s1,u,r)) ```
MatrixStudio/Codeforces-Python-Submissions
When Valera has got some free time, he goes to the library to read some books. Today he's got *t* free minutes to read. That's why Valera took *n* books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to *n*. Valera needs *a**i* minutes to read the *i*-th book. Valera decided to choose an arbitrary book with number *i* and read the books one by one, starting from this book. In other words, he will first read book number *i*, then book number *i*<=+<=1, then book number *i*<=+<=2 and so on. He continues the process until he either runs out of the free time or finishes reading the *n*-th book. Valera reads each book up to the end, that is, he doesn't start reading the book if he doesn't have enough free time to finish reading it. Print the maximum number of books Valera can read.
```python n,t=map(int,input().split()) m=list(map(int,input().split())) a=-1 for i in range(len(m)): count=0 sum=0 while(i<=len(m)-1 and (sum+m[i])<=t): sum=sum+m[i] count=count+1 i=i+1 if(count>a): a=count print(a) ```
MatrixStudio/Codeforces-Python-Submissions
Do you remember a kind cartoon "Beauty and the Beast"? No, no, there was no firing from machine guns or radiation mutants time-travels! There was a beauty named Belle. Once she had violated the Beast's order and visited the West Wing. After that she was banished from the castle... Everybody was upset. The beautiful Belle was upset, so was the Beast, so was Lumiere the candlestick. But the worst thing was that Cogsworth was upset. Cogsworth is not a human, but is the mantel clock, which was often used as an alarm clock. Due to Cogsworth's frustration all the inhabitants of the castle were in trouble: now they could not determine when it was time to drink morning tea, and when it was time for an evening stroll. Fortunately, deep in the basement are lying digital clock showing the time in the format HH:MM. Now the residents of the castle face a difficult task. They should turn Cogsworth's hour and minute mustache hands in such a way, that Cogsworth began to show the correct time. Moreover they need to find turn angles in degrees for each mustache hands. The initial time showed by Cogsworth is 12:00. You can only rotate the hands forward, that is, as is shown in the picture: As since there are many ways too select such angles because of full rotations, choose the smallest angles in the right (non-negative) direction. Note that Cogsworth's hour and minute mustache hands move evenly and continuously. Hands are moving independently, so when turning one hand the other hand remains standing still.
```python time = input() h = int(time[0])*10 + int(time[1]) m = int(time[3])*10 + int(time[4]) h = h % 12 angle1 = h*30 + m//2 if m%2 == 1: angle1 += 0.5 angle2 = m*6 print(angle1, angle2) ```
MatrixStudio/Codeforces-Python-Submissions
Let's define the sum of two permutations *p* and *q* of numbers 0,<=1,<=...,<=(*n*<=-<=1) as permutation , where *Perm*(*x*) is the *x*-th lexicographically permutation of numbers 0,<=1,<=...,<=(*n*<=-<=1) (counting from zero), and *Ord*(*p*) is the number of permutation *p* in the lexicographical order. For example, *Perm*(0)<==<=(0,<=1,<=...,<=*n*<=-<=2,<=*n*<=-<=1), *Perm*(*n*!<=-<=1)<==<=(*n*<=-<=1,<=*n*<=-<=2,<=...,<=1,<=0) Misha has two permutations, *p* and *q*. Your task is to find their sum. Permutation *a*<==<=(*a*0,<=*a*1,<=...,<=*a**n*<=-<=1) is called to be lexicographically smaller than permutation *b*<==<=(*b*0,<=*b*1,<=...,<=*b**n*<=-<=1), if for some *k* following conditions hold: *a*0<==<=*b*0,<=*a*1<==<=*b*1,<=...,<=*a**k*<=-<=1<==<=*b**k*<=-<=1,<=*a**k*<=&lt;<=*b**k*.
```python num=1 for i in range(1, 200001):num*=i print("Done") ```
MatrixStudio/Codeforces-Python-Submissions
Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, info. If the word consists of single letter, then according to above definition this letter is the median letter. Polycarp encodes each word in the following way: he writes down the median letter of the word, then deletes it and repeats the process until there are no letters left. For example, he encodes the word volga as logva. You are given an encoding *s* of some word, your task is to decode it.
```python l=int(input()) str=input() str1="" lst=list(str) while len(lst)>=3: if l%2==0: str1+=lst[(l//2)-1] lst.pop((l//2)-1] else: str1+=lst[l//2] lst.pop((l//2)) str1+=lst[0]+lst[1] print(str1) ```
MatrixStudio/Codeforces-Python-Submissions
Do you know a story about the three musketeers? Anyway, you will learn about its origins now. Richelimakieu is a cardinal in the city of Bearis. He is tired of dealing with crime by himself. He needs three brave warriors to help him to fight against bad guys. There are *n* warriors. Richelimakieu wants to choose three of them to become musketeers but it's not that easy. The most important condition is that musketeers must know each other to cooperate efficiently. And they shouldn't be too well known because they could be betrayed by old friends. For each musketeer his recognition is the number of warriors he knows, excluding other two musketeers. Help Richelimakieu! Find if it is possible to choose three musketeers knowing each other, and what is minimum possible sum of their recognitions.
```python def dfs(knights,k,st,cycle,limit=2): if limit == 0: if st not in knights[k]: return total=0 for k in cycle: total+=len(knights[k])-2 cycles.append(total) return for i in knights[k]: cycle.append(i) dfs(knights,i,st,cycle,limit-1) cycle.pop(-1) n,m=map(int,input().split()) knights={str(i):[] for i in range(1,n+1)} for _ in range(m): key,value=input().split() knights[key].append(value) knights[value].append(key) cycles=[] for k in knights: dfs(knights,k,k,[k]) print(min(cycles) if cycles else -1) ```
MatrixStudio/Codeforces-Python-Submissions
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed *w* kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem. Pete and Billy are great fans of even numbers, that's why they want to divide the watermelon in such a way that each of the two parts weighs even number of kilos, at the same time it is not obligatory that the parts are equal. The boys are extremely tired and want to start their meal as soon as possible, that's why you should help them and find out, if they can divide the watermelon in the way they want. For sure, each of them should get a part of positive weight.
```python n = int(input()) if n%2==0 and n>=2:print("Yes") else:print("No") ```
MatrixStudio/Codeforces-Python-Submissions
While swimming at the beach, Mike has accidentally dropped his cellphone into the water. There was no worry as he bought a cheap replacement phone with an old-fashioned keyboard. The keyboard has only ten digital equal-sized keys, located in the following way: Together with his old phone, he lost all his contacts and now he can only remember the way his fingers moved when he put some number in. One can formally consider finger movements as a sequence of vectors connecting centers of keys pressed consecutively to put in a number. For example, the finger movements for number "586" are the same as finger movements for number "253": Mike has already put in a number by his "finger memory" and started calling it, so he is now worrying, can he be sure that he is calling the correct number? In other words, is there any other number, that has the same finger movements?
```python # LUOGU_RID: 101608072 _, s = input(), input() print(all(set(t) & set(s) for t in '0147 0369 079 123'.split()) and 'YES' or 'NO') ```
MatrixStudio/Codeforces-Python-Submissions
The on-board computer on Polycarp's car measured that the car speed at the beginning of some section of the path equals *v*1 meters per second, and in the end it is *v*2 meters per second. We know that this section of the route took exactly *t* seconds to pass. Assuming that at each of the seconds the speed is constant, and between seconds the speed can change at most by *d* meters per second in absolute value (i.e., the difference in the speed of any two adjacent seconds does not exceed *d* in absolute value), find the maximum possible length of the path section in meters.
```python v1,v2 = map(int,input().split()) t,d = map(int,input().split()) if v1>v2: z = v1 v1 = v2 v2 = z ans = v1 cur = v1 for i in range(2,t+1): temp = (t-i)*d f = 0 for j in range(d,-1,-1): if abs((cur+j)-v2)<=temp: f=1 cur += j ans+=cur break #print(cur,ans,i) if f==0: req = cur-v2 z = i if (req%d)!=0: cur-=(req%d) z = i+1 ans+=cur for j in range(z,t+1): cur-=d if cur>=v2: ans+=cur else: ans+=v2 break #print(j) print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
You are given an array *a* with *n* elements. Each element of *a* is either 0 or 1. Let's denote the length of the longest subsegment of consecutive elements in *a*, consisting of only numbers one, as *f*(*a*). You can change no more than *k* zeroes to ones to maximize *f*(*a*).
```python def maximize_subsegment_length(n, k, a): left = 0 right = 0 max_length = 0 max_zeros = k best_left = 0 best_right = 0 while right < n: if a[right] == 0: max_zeros -= 1 while max_zeros < 0: if a[left] == 0: max_zeros += 1 left += 1 if right - left + 1 > max_length: max_length = right - left + 1 best_left = left best_right = right right += 1 for i in range(best_left, best_right + 1): a[i] = 1 print(max_length) print(*a) # Read input n, k = map(int, input().split()) a = list(map(int, input().split())) # Call the function maximize_subsegment_length(n, k, a) ```
MatrixStudio/Codeforces-Python-Submissions
Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number *a* and Antisimon receives number *b*. They also have a heap of *n* stones. The players take turns to make a move and Simon starts. During a move a player should take from the heap the number of stones equal to the greatest common divisor of the fixed number he has received and the number of stones left in the heap. A player loses when he cannot take the required number of stones (i. e. the heap has strictly less stones left than one needs to take). Your task is to determine by the given *a*, *b* and *n* who wins the game.
```python import math test_case=input().split(' ') def heap_left(fixed,gcd):return gcd-math.gcd(fixed,gcd) def assignment(p1,p2,n): list=[int(n)] flag=int(n) count=0 while flag!=0: if count%2==0:flag=heap_left(int(p1),list[count]);list.append(heap_left(int(p1),list[count])) else:flag=heap_left(int(p2),list[count]);list.append(heap_left(int(p2),list[count])) count+=1 if len(list)%2==0:print(0) else:print(1) if __name__=="__main__": assignment(test_case[0],test_case[1],test_case[2]) #print(test_case[0],test_case[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 s=input() low=0 upp=0 for i in s: if i==i.upper(): upp=upp+1 else: low=low+1 if upp>low: print(s.upper()) else: print(s.lower()) ```
MatrixStudio/Codeforces-Python-Submissions
There is a very secret base in Potatoland where potato mash is made according to a special recipe. The neighbours from Porridgia decided to seize this recipe and to sell it to Pilauland. For this mission they have been preparing special agent Pearlo for many years. When, finally, Pearlo learned all secrets of espionage, he penetrated into the Potatoland territory and reached the secret base. Now he is standing at the entrance, but to get inside he need to pass combination lock. Minute ago one of the workers entered the password on the terminal and opened the door. The terminal is a square digital keyboard 3<=×<=3 with digits from 1 to 9. Pearlo knows that the password consists from distinct digits and is probably symmetric with respect to the central button of the terminal. He has heat sensor which allowed him to detect the digits which the worker pressed. Now he wants to check whether the password entered by the worker is symmetric with respect to the central button of the terminal. This fact can Help Pearlo to reduce the number of different possible password combinations.
```python a = input() b = input() c = input() s = a+b+c if s == s[::-1]: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Patrick has just finished writing a message to his sweetheart Stacey when he noticed that the message didn't look fancy. Patrick was nervous while writing the message, so some of the letters there were lowercase and some of them were uppercase. Patrick believes that a message is fancy if any uppercase letter stands to the left of any lowercase one. In other words, this rule describes the strings where first go zero or more uppercase letters, and then — zero or more lowercase letters. To make the message fancy, Patrick can erase some letter and add the same letter in the same place in the opposite case (that is, he can replace an uppercase letter with the lowercase one and vice versa). Patrick got interested in the following question: what minimum number of actions do we need to make a message fancy? Changing a letter's case in the message counts as one action. Patrick cannot perform any other actions.
```python import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline s = list(input().rstrip()) cnt = [0] for i in s: cnt.append(cnt[-1] + i // 97) n = len(s) ans = n for i in range(n + 1): u, v = cnt[i], n - i - (cnt[n] - cnt[i]) ans = min(ans, u + v) print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
You are given two very long integers *a*,<=*b* (leading zeroes are allowed). You should check what number *a* or *b* is greater or determine that they are equal. The input size is very large so don't use the reading of symbols one by one. Instead of that use the reading of a whole line or token. As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java. Don't use the function input() in Python2 instead of it use the function raw_input().
```python # LUOGU_RID: 126991992 a=input().lstrip('0');b=input().lstrip() if len(a)>len(b):print('>') elif len(a)<len(b):print('<') elif a>b:print('>') elif a<b:print('<') else:print('=') ```
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 # URL: https://codeforces.com/problemset/problem/630/A import io import os import sys input_buffer = io.BytesIO(os.read(0, os.fstat(0).st_size)) inp = lambda: input_buffer.readline().rstrip(b"\n").rstrip(b"\r") out = sys.stdout.write out("25") ```
MatrixStudio/Codeforces-Python-Submissions
A necklace can be described as a string of links ('-') and pearls ('o'), with the last link or pearl connected to the first one. You can remove a link or a pearl and insert it between two other existing links or pearls (or between a link and a pearl) on the necklace. This process can be repeated as many times as you like, but you can't throw away any parts. Can you make the number of links between every two adjacent pearls equal? Two pearls are considered to be adjacent if there is no other pearl between them. Note that the final necklace should remain as one circular part of the same length as the initial necklace.
```python s = input() a = s.count('o') b = s.count('-') print("NO" if a and b % a else "YES") ```
MatrixStudio/Codeforces-Python-Submissions
A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all *n* squad soldiers to line up on the parade ground. By the military charter the soldiers should stand in the order of non-increasing of their height. But as there's virtually no time to do that, the soldiers lined up in the arbitrary order. However, the general is rather short-sighted and he thinks that the soldiers lined up correctly if the first soldier in the line has the maximum height and the last soldier has the minimum height. Please note that the way other solders are positioned does not matter, including the case when there are several soldiers whose height is maximum or minimum. Only the heights of the first and the last soldier are important. For example, the general considers the sequence of heights (4, 3, 4, 2, 1, 1) correct and the sequence (4, 3, 1, 2, 2) wrong. Within one second the colonel can swap any two neighboring soldiers. Help him count the minimum time needed to form a line-up which the general will consider correct.
```python n=int(input()) a=list(map(int,input().split())) mx=max(a) mn=min(a) ind_mx=a.index(mx) ind_mn=0 for i in range(n-1,-1,-1): if(a[i]==mn): ind_mn+=1 break ind_mn+=1 if(n-ind_mn<ind_mx): print(ind_mx+(ind_mn-2)) else: print(ind_mx+ind_mn-1) ```
MatrixStudio/Codeforces-Python-Submissions
Levko loves tables that consist of *n* rows and *n* columns very much. He especially loves beautiful tables. A table is beautiful to Levko if the sum of elements in each row and column of the table equals *k*. Unfortunately, he doesn't know any such table. Your task is to help him to find at least one of them.
```python n,k=map(int,input().split()) a=[] b=[] for i in range(n): b=[] for j in range(n): if i==j: b.append(k) else: b.append(0) a.append(b) for i in range(n): for j in range(n): print(a[i][j],'',end='') print() ```
MatrixStudio/Codeforces-Python-Submissions
Petr stands in line of *n* people, but he doesn't know exactly which position he occupies. He can say that there are no less than *a* people standing in front of him and no more than *b* people standing behind him. Find the number of different positions Petr can occupy.
```python def canteen(n,m,o): x=1+m y=n-o if y<=x: return (n-x)+1 else: return 0 a,b,c=map(int,input().split()) print(canteen(a,b,c)) ```
MatrixStudio/Codeforces-Python-Submissions
You are given an array of integers. Vasya can permute (change order) its integers. He wants to do it so that as many as possible integers will become on a place where a smaller integer used to stand. Help Vasya find the maximal number of such integers. For instance, if we are given an array $[10, 20, 30, 40]$, we can permute it so that it becomes $[20, 40, 10, 30]$. Then on the first and the second positions the integers became larger ($20&gt;10$, $40&gt;20$) and did not on the third and the fourth, so for this permutation, the number that Vasya wants to maximize equals $2$. Read the note for the first example, there is one more demonstrative test case. Help Vasya to permute integers in such way that the number of positions in a new array, where integers are greater than in the original one, is maximal.
```python n=int(input()) arr=[int(c) for c in input().split()] ans=0 temp=sorted(arr) arr.sort() i=n-1 curr=temp.pop() while i>=0: if arr[i]<curr: ans+=1 curr=temp.pop() i-=1 else: i-=1 print(ans) ```