\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\tint n;\r\n\tcin >> n;\r\n\tint razlozhenie, cur;\r\n\tcin >> razlozhenie;\r\n\twhile(razlozhenie % 2 == 0)\r\n\t\trazlozhenie /= 2;\r\n\twhile(razlozhenie % 3 == 0)\r\n\t\trazlozhenie /= 3;\r\n\t\r\n\tfor(int i = 1; i < n; i++) {\r\n\t\tcin >> cur;\r\n\t\twhile(cur % 2 == 0)\r\n\t\t\tcur /= 2;\r\n\t\twhile(cur % 3 == 0)\r\n\t\t\tcur /= 3;\r\n\t\tif(cur != razlozhenie) {\r\n\t\t\tcout << \"No\" << endl;\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t}\r\n\tcout << \"Yes\" << endl;\r\n}\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer.\n\nAt 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).\n\nIf 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.\n\nKay 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.",
"input": "",
"output": "```python\nn,x=input().split()\nn=int(n);x=int(x)\ndistressed=0\nfor i in range(n):\n a,b=input().split()\n b=int(b)\n if a=='+':\n x+=b\n elif x>=b:\n x-=b\n else:\n distressed+=1\nprint(x,distressed)\n\t\t \t \t\t \t \t \t \t\t \t\t\t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A dice is a cube, its faces contain distinct integers from 1 to 6 as black points. The sum of numbers at the opposite dice faces always equals 7. Please note that there are only two dice (these dices are mirror of each other) that satisfy the given constraints (both of them are shown on the picture on the left).\n\nAlice and Bob play dice. Alice has built a tower from *n* dice. We know that in this tower the adjacent dice contact with faces with distinct numbers. Bob wants to uniquely identify the numbers written on the faces of all dice, from which the tower is built. Unfortunately, Bob is looking at the tower from the face, and so he does not see all the numbers on the faces. Bob sees the number on the top of the tower and the numbers on the two adjacent sides (on the right side of the picture shown what Bob sees).\n\nHelp Bob, tell whether it is possible to uniquely identify the numbers on the faces of all the dice in the tower, or not.",
"input": "",
"output": "```python\nn = int(input())\r\nx = int(input())\r\nhid = 7-x\r\nfor i in range(n):\r\n hid = 7-x\r\n a, b = map(int, input().split())\r\n if hid in [7-a, 7-b, a, b]:\r\n print(\"NO\")\r\n break\r\n else:\r\n x = hid\r\nelse:\r\n print('YES')\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.\n\nYou've got string *s*<==<=*s*1*s*2... *s**n* (*n* is the length of the string), consisting only of characters \".\" and \"#\" and *m* queries. Each query is described by a pair of integers *l**i*,<=*r**i* (1<=≤<=*l**i*<=<<=*r**i*<=≤<=*n*). The answer to the query *l**i*,<=*r**i* is the number of such integers *i* (*l**i*<=≤<=*i*<=<<=*r**i*), that *s**i*<==<=*s**i*<=+<=1.\n\nIlya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.",
"input": "",
"output": "```python\ndef count_pref(s: str) -> list[int]:\n pref = [0] * (len(s))\n for i in range(1, len(pref)):\n pref[i] += pref[i-1]\n if s[i-1] == s[i]:\n pref[i] += 1\n\n return pref\n\n\ndef process(pref: list[int], queries: list[list[int]]) -> list[int]:\n res = []\n for query in queries:\n i, j = query\n value = pref[j-1] - pref[i-1]\n res.append(value)\n\n return res\n\nif __name__ == \"__main__\":\n sequence = input().strip()\n n = int(input().strip())\n pref = count_pref(sequence)\n queries = []\n for _ in range(n):\n query = list(map(int, input().strip().split()))\n queries.append(query)\n ans = process(pref, queries)\n print(\"\\n\".join(map(str, ans)))\n\t \t \t \t\t \t \t \t\t \t\t \t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "The Little Elephant has an integer *a*, written in the binary notation. He wants to write this number on a piece of paper.\n\nTo make sure that the number *a* fits on the piece of paper, the Little Elephant ought to delete exactly one any digit from number *a* in the binary record. At that a new number appears. It consists of the remaining binary digits, written in the corresponding order (possible, with leading zeroes).\n\nThe Little Elephant wants the number he is going to write on the paper to be as large as possible. Help him find the maximum number that he can obtain after deleting exactly one binary digit and print it in the binary notation.",
"input": "",
"output": "```python\nn=input()\r\na=[x for x in n]\r\nif n.count('0')>0:\r\n a.remove('0')\r\n print(''.join(a))\r\nelse:\r\n del a[-1]\r\n print(''.join(a))\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Alice likes word \"nineteen\" very much. She has a string *s* and wants the string to contain as many such words as possible. For that reason she can rearrange the letters of the string.\n\nFor example, if she has string \"xiineteenppnnnewtnee\", she can get string \"xnineteenppnineteenw\", containing (the occurrences marked) two such words. More formally, word \"nineteen\" occurs in the string the number of times you can read it starting from some letter of the string. Of course, you shouldn't skip letters.\n\nHelp her to find the maximum number of \"nineteen\"s that she can get in her string.",
"input": "",
"output": "```python\ndef printMatrix(matrix):\r\n for matrixrow in matrix:\r\n row = ''\r\n for value in matrixrow:\r\n row += str(value) + ' '\r\n print(row)\r\n\r\n\r\nn = int(input())\r\nw = [[0 for i in range(n)] for i in range(n)]\r\na = [[0 for i in range(n)] for i in range(n)]\r\nb = [[0 for i in range(n)] for i in range(n)]\r\nfor i in range(n):\r\n row = input().split(' ')\r\n for e in range(n):\r\n w[i][e] = int(row[e])\r\nfor i in range(n):\r\n for e in range(n):\r\n a[e][i] = a[i][e] = (w[i][e]+w[e][i]) / 2\r\n b[e][i] = w[e][i] - a[e][i]\r\nprintMatrix(a)\r\nprintMatrix(b)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "While Mike was walking in the subway, all the stuff in his back-bag dropped on the ground. There were several fax messages among them. He concatenated these strings in some order and now he has string *s*.\n\nHe is not sure if this is his own back-bag or someone else's. He remembered that there were exactly *k* messages in his own bag, each was a palindrome string and all those strings had the same length.\n\nHe asked you to help him and tell him if he has worn his own back-bag. Check if the given string *s* is a concatenation of *k* palindromes of the same length.",
"input": "",
"output": "```python\ns=input()\r\ns=list(s)\r\np=int(input())\r\nf=0\r\n#lst = list(map(int, input().strip().split(' ')))\r\ni=0\r\nk=len(s)//p\r\nwhile(i<=len(s)-k):\r\n t=[]\r\n for j in range(i,i+k):\r\n t.append(s[j])\r\n\r\n if s[i:i+k]==t[::-1]:\r\n i+=k \r\n \r\n else:\r\n print('NO')\r\n f=1\r\n break\r\nif f==0:\r\n print('YES')\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "In a Berland's zoo there is an enclosure with camels. It is known that camels like to spit. Bob watched these interesting animals for the whole day and registered in his notepad where each animal spitted. Now he wants to know if in the zoo there are two camels, which spitted at each other. Help him to solve this task.\n\nThe trajectory of a camel's spit is an arc, i.e. if the camel in position *x* spits *d* meters right, he can hit only the camel in position *x*<=+<=*d*, if such a camel exists.",
"input": "",
"output": "```python\nx = []\r\nd = []\r\nfor i in ' '*int(input()):\r\n x2, d2 = map(int, input().split())\r\n x.append(x2)\r\n d.append(d2)\r\nf = 0\r\nkol = 0\r\nfor i in range(len(x)):\r\n for j in range(len(x)):\r\n if x[i]+d[i] == x[j] and x[j] + d[j] == x[i] and kol != 2:\r\n f = 1\r\n kol += 1\r\nprint('YES' if f == 1 else 'NO')\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "There is a game called \"I Wanna Be the Guy\", consisting of *n* levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game.\n\nLittle X can pass only *p* levels of the game. And Little Y can pass only *q* levels of the game. You are given the indices of levels Little X can pass and the indices of levels Little Y can pass. Will Little X and Little Y pass the whole game, if they cooperate each other?",
"input": "",
"output": "```python\nn=int(input())\r\nlist1=list( map(int,input().split()))\r\nlist2= list (map(int,input().split()))\r\nMergedList=list1+list2\r\nX=set(MergedList())\r\nif len(X)==n:\r\n print(\"I become the guy.\")\r\nelse:\r\n print(\"Oh, my keyboard!\")\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Two boys decided to compete in text typing on the site \"Key races\". During the competition, they have to type a text consisting of *s* characters. The first participant types one character in *v*1 milliseconds and has ping *t*1 milliseconds. The second participant types one character in *v*2 milliseconds and has ping *t*2 milliseconds.\n\nIf connection ping (delay) is *t* milliseconds, the competition passes for a participant as follows: \n 1. Exactly after *t* milliseconds after the start of the competition the participant receives the text to be entered. 1. Right after that he starts to type it. 1. Exactly *t* milliseconds after he ends typing all the text, the site receives information about it. \nThe winner is the participant whose information on the success comes earlier. If the information comes from both participants at the same time, it is considered that there is a draw.\n\nGiven the length of the text and the information about participants, determine the result of the game.",
"input": "",
"output": "```python\ns,v1,v2,t1,t2=map(int,input().split())\r\nz1=s*v1+2*t1\r\nz2=s*v2+2*t2\r\nif z1>z2:\r\n print(\"Second\")\r\nelif z2>z1:\r\n print(\"First\")\r\nelse:\r\n print(\"Friendship\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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. \n\nPolycarp 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.\n\nYou are given an encoding *s* of some word, your task is to decode it.",
"input": "",
"output": "```python\n\"\"\"\r\nabcd \r\n\r\nbcad\r\n\r\nabcd \r\n\"\"\"\r\n\r\nn = int(input()) \r\ns = input() \r\nans = [' '] * n \r\nif len(s) % 2 == 0:\r\n l = (n - 1) // 2 \r\n r = (n) // 2 \r\n i = 0\r\n j = 1 \r\n ans[l] = s[i] \r\n ans[r] = s[j] \r\n while j + 2 < n:\r\n j += 2\r\n i += 2 \r\n l -= 1 \r\n r += 1 \r\n ans[l] = s[i] \r\n ans[r] = s[j]\r\nelse: \r\n m = n // 2 \r\n ans[m] = s[0] \r\n l = m - 1 \r\n r = m + 1\r\n i = 1 \r\n j = 2 \r\n while i + 1 < n:\r\n ans[l] = s[i] \r\n ans[r] = s[j] \r\n l -= 1 \r\n r += 1 \r\n i += 2 \r\n j += 2 \r\n\r\nprint(\"\".join(ans))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Eugeny has array *a*<==<=*a*1,<=*a*2,<=...,<=*a**n*, consisting of *n* integers. Each integer *a**i* equals to -1, or to 1. Also, he has *m* queries:\n - Query number *i* is given as a pair of integers *l**i*, *r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*). - The response to the query will be integer 1, if the elements of array *a* can be rearranged so as the sum *a**l**i*<=+<=*a**l**i*<=+<=1<=+<=...<=+<=*a**r**i*<==<=0, otherwise the response to the query will be integer 0. \nHelp Eugeny, answer all his queries.",
"input": "",
"output": "```python\nimport sys\r\n\r\n(n, m) = [int(x) for x in sys.stdin.readline().split()]\r\nn_one = sys.stdin.readline().count(\"-\")\r\none = n - n_one\r\n\r\nfor i in range(0, m):\r\n (l, r) = [int(x) for x in sys.stdin.readline().split()]\r\n q = r - l + 1\r\n if q % 2 == 1:\r\n print(0)\r\n else:\r\n if q / 2 <= one and q / 2 <= n_one:\r\n print(1)\r\n else:\r\n print(0)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are given $n$ strings. Each string consists of lowercase English letters. Rearrange (reorder) the given strings in such a way that for every string, all strings that are placed before it are its substrings.\n\nString $a$ is a substring of string $b$ if it is possible to choose several consecutive letters in $b$ in such a way that they form $a$. For example, string \"for\" is contained as a substring in strings \"codeforces\", \"for\" and \"therefore\", but is not contained as a substring in strings \"four\", \"fofo\" and \"rof\".",
"input": "",
"output": "```python\nn = int(input())\nstrings = dict()\nlength = []\nfor i in range(n):\n a = input()\n strings[len(a)] = a\n length.append(len(a))\n\nlength.sort()\nfor j in range(n):\n length[j] = strings[length[j]]\n\npos = True\nfor k in range(n - 1):\n if length[k] not in length[k + 1]:\n pos = False\n\nif pos:\n print(\"YES\")\n for o in length:\n print(o)\nelse:\n print(\"NO\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Duff is in love with lovely numbers! A positive integer *x* is called lovely if and only if there is no such positive integer *a*<=><=1 such that *a*2 is a divisor of *x*.\n\nMalek has a number store! In his store, he has only divisors of positive integer *n* (and he has all of them). As a birthday present, Malek wants to give her a lovely number from his store. He wants this number to be as big as possible.\n\nMalek always had issues in math, so he asked for your help. Please tell him what is the biggest lovely number in his store.",
"input": "",
"output": "```python\nimport math\r\n\r\n\r\ndef check_square_division(n):\r\n for i in range(2, math.floor(math.sqrt(n))):\r\n if n % (i ** 2) == 0:\r\n return False\r\n return True\r\n\r\ndef main():\r\n n= int(input())\r\n\r\n divisors = []\r\n for i in range(1, n+1):\r\n if n % i == 0:\r\n divisors.append(i)\r\n \r\n final_answer = -1\r\n for divisor in reversed(divisors):\r\n if check_square_division(divisor):\r\n final_answer = divisor\r\n break\r\n\r\n print(final_answer)\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory. \n\nGeorge and Alex want to live in the same room. The dormitory has *n* rooms in total. At the moment the *i*-th room has *p**i* people living in it and the room can accommodate *q**i* people in total (*p**i*<=≤<=*q**i*). Your task is to count how many rooms has free place for both George and Alex.",
"input": "",
"output": "```python\nn =input()\nn =int(n)\nX = 0\nfor i in range(1,n+1):\n a, b =input().split()\n a =int(a)\n b =int(b)\n if(b - a >= 2):\n x=x+1\nprint(x)\n \t \t\t \t\t \t\t\t\t\t\t \t \t \t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Fedya studies in a gymnasium. Fedya's maths hometask is to calculate the following expression:\n\nfor 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).",
"input": "",
"output": "```python\ndef expression(n):\n if (n%4):\n return 0\n else:\n return 4\n\nn = int(input())\nresult = expression(n)\nprint(result)\n\t\t\t\t\t \t \t \t\t\t \t\t \t \t \t \t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Your friend has recently learned about coprime numbers. A pair of numbers {*a*,<=*b*} is called coprime if the maximum number that divides both *a* and *b* is equal to one. \n\nYour friend often comes up with different statements. He has recently supposed that if the pair (*a*,<=*b*) is coprime and the pair (*b*,<=*c*) is coprime, then the pair (*a*,<=*c*) is coprime. \n\nYou want to find a counterexample for your friend's statement. Therefore, your task is to find three distinct numbers (*a*,<=*b*,<=*c*), for which the statement is false, and the numbers meet the condition *l*<=≤<=*a*<=<<=*b*<=<<=*c*<=≤<=*r*. \n\nMore specifically, you need to find three numbers (*a*,<=*b*,<=*c*), such that *l*<=≤<=*a*<=<<=*b*<=<<=*c*<=≤<=*r*, pairs (*a*,<=*b*) and (*b*,<=*c*) are coprime, and pair (*a*,<=*c*) is not coprime.",
"input": "",
"output": "```python\ndef gcd(a, b):\r\n rem = 0\r\n while b != 0:\r\n rem = a%b\r\n a = b\r\n b = rem\r\n return a\r\n\r\n\r\na, b = map(int, input().split())\r\nif b-a == 1:\r\n print (-1)\r\nelse: \r\n found = False\r\n for i in range(a, b+1):\r\n for j in range(i+1, b+1):\r\n for k in range(j+1, b+1):\r\n if gcd(i, j) == 1 and gcd(j, k) == 1 and gcd(i, k) != 1:\r\n found = True\r\n print (i, j, k)\r\n break\r\n if found:\r\n break\r\n if found:\r\n break\r\n if not found:\r\n print (-1)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "String can be called correct if it consists of characters \"0\" and \"1\" and there are no redundant leading zeroes. Here are some examples: \"0\", \"10\", \"1001\".\n\nYou are given a correct string *s*.\n\nYou can perform two different operations on this string: \n 1. swap any pair of adjacent characters (for example, \"101\" \"110\"); 1. replace \"11\" with \"1\" (for example, \"110\" \"10\"). \nLet *val*(*s*) be such a number that *s* is its binary representation.\n\nCorrect string *a* is less than some other correct string *b* iff *val*(*a*)<=<<=*val*(*b*).\n\nYour task is to find the minimum correct string that you can obtain from the given one using the operations described above. You can use these operations any number of times in any order (or even use no operations at all).",
"input": "",
"output": "```python\n\r\nn = int(input())\r\nst = list(input())\r\nif not \"1\" in st:\r\n print(0)\r\n quit()\r\nprint(\"1\", end = \"\")\r\nfor i in st:\r\n if i == \"0\": \r\n print(i, end = \"\")\r\nprint()\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.",
"input": "",
"output": "```python\ndata = input()\r\n\r\nl=u = 0\r\n\r\nfor x in data:\r\n if x.islower():\r\n l+=1\r\n else:\r\n u+=1\r\n\r\nif l>=u:\r\n print(data.lower())\r\nelse:\r\n print(data.upper())\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "«Polygon» is a system which allows to create programming tasks in a simple and professional way. When you add a test to the problem, the corresponding form asks you for the test index. As in most cases it is clear which index the next test will have, the system suggests the default value of the index. It is calculated as the smallest positive integer which is not used as an index for some previously added test.\n\nYou are to implement this feature. Create a program which determines the default index of the next test, given the indexes of the previously added tests.",
"input": "",
"output": "```python\nn=int(input())\r\nl=list(map(int,input().split()))\r\nl.sort()\r\nif l[0]>1:\r\n print(1)\r\nelse:\r\n for i in range(len(l)-1):\r\n if l[i+1]-l[i]>1:\r\n print(l[i]+1)\r\n break\r\n else:\r\n print(l[-1]+1)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "On the way to Rio de Janeiro Ostap kills time playing with a grasshopper he took with him in a special box. Ostap builds a line of length *n* such that some cells of this line are empty and some contain obstacles. Then, he places his grasshopper to one of the empty cells and a small insect in another empty cell. The grasshopper wants to eat the insect.\n\nOstap knows that grasshopper is able to jump to any empty cell that is exactly *k* cells away from the current (to the left or to the right). Note that it doesn't matter whether intermediate cells are empty or not as the grasshopper makes a jump over them. For example, if *k*<==<=1 the grasshopper can jump to a neighboring cell only, and if *k*<==<=2 the grasshopper can jump over a single cell.\n\nYour goal is to determine whether there is a sequence of jumps such that grasshopper will get from his initial position to the cell with an insect.",
"input": "",
"output": "```python\nn,k = map(int,input().split())\r\ns = input()\r\nfirst = s.index('G')\r\nlast = s.index('T')\r\nif first < last:\r\n if s[first+k] == 'T':\r\n print(\"YES\")\r\n elif s[first+k] == '#':\r\n print(\"NO\")\r\n elif first+k > last:\r\n print(\"NO\")\r\n elif s[first+k] == '.':\r\n if s[(first+k)+1] == '#':\r\n print(\"NO\")\r\n else:\r\n print(\"YES\")\r\n\r\nelse:\r\n if s[first-k] == 'T':\r\n print(\"YES\")\r\n elif s[first-k] == '#':\r\n print(\"NO\")\r\n elif s[first-k] == '.':\r\n if s[(first-k)-1] == '#':\r\n print(\"NO\")\r\n else:\r\n print(\"YES\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nYour 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.",
"input": "",
"output": "```python\nn=int(input())\r\nif n==3:\r\n print (2)\r\n print ('1 3')\r\n exit()\r\nif n==2:\r\n print (1)\r\n print (1)\r\na=[]\r\nb=[]\r\nfor i in range (1,n+1):\r\n if i%2==0:\r\n a.append(i)\r\n else :\r\n b.append(i)\r\nc=a+b\r\nprint (n)\r\nprint (\" \".join(map(str,c)))\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Sometimes some words like \"localization\" or \"internationalization\" are so long that writing them many times in one text is quite tiresome.\n\nLet's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.\n\nThis abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.\n\nThus, \"localization\" will be spelt as \"l10n\", and \"internationalization» will be spelt as \"i18n\".\n\nYou are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.",
"input": "",
"output": "```python\np=int(input())\r\nfor i in range(p):\r\n sedd=input()\r\n if(len(sedd)<=10):\r\n print(sedd)\r\n else:\r\n print(sedd[0]+str(len(sedd)-2)+sedd[len(sedd)-1])\r\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A sum of *p* rubles is charged from Arkady's mobile phone account every day in the morning. Among the following *m* days, there are *n* days when Arkady will top up the account: in the day *d**i* he will deposit *t**i* rubles on his mobile phone account. Arkady will always top up the account before the daily payment will be done. There will be no other payments nor tops up in the following *m* days.\n\nDetermine the number of days starting from the 1-st to the *m*-th such that the account will have a negative amount on it after the daily payment (i. e. in evening). Initially the account's balance is zero rubles.",
"input": "",
"output": "```python\nn,p,m=map(int,input().split())\n\nl2=[]\nld=[]\nlt=[]\nk=0\nfor i in range(n):\n d,t=map(int,input().split())\n ld.append(d)\n lt.append(t)\nfor i in range(1,m+1):\n if i in ld:\n k+=lt[ld.index(i)]\n l2.append(k)\ns=0\nfor i in range(m):\n if l2[i]= dista[w]:\r\n distb[w] = d + 1\r\n continue\r\n dfsb(w, u, d + 1)\r\n\r\n\r\ndfsa(0, -1, 0)\r\ndfsb(x, -1, 0)\r\nnum = 0\r\nfor i in range(n):\r\n if distb[i] != -1:\r\n num = max(num, dista[i] * 2)\r\nprint(num)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Several ages ago Berland was a kingdom. The King of Berland adored math. That's why, when he first visited one of his many palaces, he first of all paid attention to the floor in one hall. The floor was tiled with hexagonal tiles.\n\nThe hall also turned out hexagonal in its shape. The King walked along the perimeter of the hall and concluded that each of the six sides has *a*, *b*, *c*, *a*, *b* and *c* adjacent tiles, correspondingly.\n\nTo better visualize the situation, look at the picture showing a similar hexagon for *a*<==<=2, *b*<==<=3 and *c*<==<=4.\n\nAccording to the legend, as the King of Berland obtained the values *a*, *b* and *c*, he almost immediately calculated the total number of tiles on the hall floor. Can you do the same?",
"input": "",
"output": "```python\n\r\n\r\n\r\na,b,c = map(int,input().split())\r\n\r\n\r\n\r\nt = min(a,b,c)-1\r\n\r\ns=a+b+c\r\n\r\n\r\np=0\r\n\r\nfor k in range(t):\r\n s+=(s-3)\r\n\r\n\r\n\r\nprint(s*2-((t+1)*6))\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are given a string *s* consisting only of characters 0 and 1. A substring [*l*,<=*r*] of *s* is a string *s**l**s**l*<=+<=1*s**l*<=+<=2... *s**r*, and its length equals to *r*<=-<=*l*<=+<=1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring.\n\nYou have to determine the length of the longest balanced substring of *s*.",
"input": "",
"output": "```python\nn=int(input())\r\nc=[]\r\nmaxx=[]\r\nfor i in range(n):\r\n m=int(input())\r\n c.append(m)\r\n\r\nif len(c)==2 :\r\n if c.count(1)==c.count(0):\r\n print(2)\r\n \r\nelse : \r\n for a in range(n):\r\n for b in range(n):\r\n q=c[a:b]\r\n if q.count(1)==q.count(0):\r\n maxx.append(len(q))\r\n else :\r\n pass\r\n print (max(maxx))\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nSereja and Dima are being greedy. Each of them chooses the card with the larger number during his move.\n\nInna 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.",
"input": "",
"output": "```python\nn=int(input())\r\nl1=list(map(int,input().split()))\r\ns=0\r\nd=0\r\nle=len(l1)\r\nif(le%2==0):\r\n while len(l1)>0:\r\n if(l1[0]>=l1[-1]):\r\n s=s+l1[0]\r\n l1.pop(0)\r\n else:\r\n s=s+l1[-1]\r\n l1.pop(-1)\r\n if(l1[0]>=l1[-1]):\r\n d=d+l1[0]\r\n l1.pop(0)\r\n else:\r\n d=d+l1[-1]\r\n l1.pop(-1)\r\nelse:\r\n while len(l1)>1:\r\n if(l1[0]>=l1[-1]):\r\n s=s+l1[0]\r\n l1.pop(0)\r\n else:\r\n s=s+l1[-1]\r\n l1.pop(-1)\r\n if(l1[0]>=l1[-1]):\r\n d=d+l1[0]\r\n l1.pop(0)\r\n else:\r\n d=d+l1[-1]\r\n l1.pop(-1)\r\n s=s+l1[0]\r\nprint(s,d)\r\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $n - 2$ intermediate planets. Formally: we number all the planets from $1$ to $n$. $1$ is Earth, $n$ is Mars. Natasha will make exactly $n$ flights: $1 \\to 2 \\to \\ldots n \\to 1$.\n\nFlight from $x$ to $y$ consists of two phases: take-off from planet $x$ and landing to planet $y$. This way, the overall itinerary of the trip will be: the $1$-st planet $\\to$ take-off from the $1$-st planet $\\to$ landing to the $2$-nd planet $\\to$ $2$-nd planet $\\to$ take-off from the $2$-nd planet $\\to$ $\\ldots$ $\\to$ landing to the $n$-th planet $\\to$ the $n$-th planet $\\to$ take-off from the $n$-th planet $\\to$ landing to the $1$-st planet $\\to$ the $1$-st planet.\n\nThe mass of the rocket together with all the useful cargo (but without fuel) is $m$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $1$ ton of fuel can lift off $a_i$ tons of rocket from the $i$-th planet or to land $b_i$ tons of rocket onto the $i$-th planet. \n\nFor example, if the weight of rocket is $9$ tons, weight of fuel is $3$ tons and take-off coefficient is $8$ ($a_i = 8$), then $1.5$ tons of fuel will be burnt (since $1.5 \\cdot 8 = 9 + 3$). The new weight of fuel after take-off will be $1.5$ tons. \n\nPlease note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.\n\nHelp Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.",
"input": "",
"output": "```python\nimport sys\r\nfrom math import *\r\nfrom collections import Counter,defaultdict,deque\r\ninput=sys.stdin.readline\r\nmod=10**9+7\r\ndef get_ints():return map(int,input().split())\r\ndef get_int():return int(input())\r\ndef get_array():return list(map(int,input().split()))\r\ndef input():return sys.stdin.readline().strip()\r\n\r\n# for _ in range(int(input())):\r\nn=get_int()\r\nm=get_int()\r\no=m\r\na=get_array()\r\nb=get_array()\r\ns=[a[0]]\r\nfor i in range(1,n-1):\r\n s.append(b[i])\r\n s.append(a[i])\r\ns.append(b[-1])\r\ns.append(a[-1])\r\ns.append(b[0])\r\nif 1 in s:\r\n print(-1)\r\nfor j in s[::-1]:\r\n m=m*j/(j-1)\r\nprint(m-o)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "So, the New Year holidays are over. Santa Claus and his colleagues can take a rest and have guests at last. When two \"New Year and Christmas Men\" meet, thear assistants cut out of cardboard the letters from the guest's name and the host's name in honor of this event. Then the hung the letters above the main entrance. One night, when everyone went to bed, someone took all the letters of our characters' names. Then he may have shuffled the letters and put them in one pile in front of the door.\n\nThe next morning it was impossible to find the culprit who had made the disorder. But everybody wondered whether it is possible to restore the names of the host and his guests from the letters lying at the door? That is, we need to verify that there are no extra letters, and that nobody will need to cut more letters.\n\nHelp the \"New Year and Christmas Men\" and their friends to cope with this problem. You are given both inscriptions that hung over the front door the previous night, and a pile of letters that were found at the front door next morning.",
"input": "",
"output": "```python\na = list(input())\nb= list(input())\nc = list(input())\n\nfor i in c:\n if i in a:\n a.remove(i)\n elif i in b:\n b.remove(i)\n else:\n print(\"NO\")\n quit()\nif len(a) ==0 and len(b)==0:\n print(\"YES\")\nelse:\n print('NO')\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nOne 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.\n\nIn 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.\n\nShapur 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.\n\nNow you are going to take part in Shapur's contest. See if you are faster and more accurate.",
"input": "",
"output": "```python\nn=list(map(str,input().split()))\r\nm=list(map(str,input().split()))\r\nlst=[]\r\nfor i in n:\r\n for j in m:\r\n if i!=j:\r\n x=1\r\n lst.append(x)\r\n else:\r\n y=0\r\n lst.append(y)\r\n \r\nprint(''.join(lst))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Petya loves lucky numbers. Everybody knows that positive integers are lucky if their decimal representation doesn't contain digits other than 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.\n\nLucky number is super lucky if it's decimal representation contains equal amount of digits 4 and 7. For example, numbers 47, 7744, 474477 are super lucky and 4, 744, 467 are not.\n\nOne day Petya came across a positive integer *n*. Help him to find the least super lucky number which is not less than *n*.",
"input": "",
"output": "```python\nimport sys\r\n\r\nn = sys.stdin.readline()\r\nt = map(int, sys.stdin.readline().split())\r\n\r\ncount = {}\r\nfor i in xrange(-10, 11):\r\n count[i] = 0;\r\n\r\nret = 0\r\nfor x in t:\r\n count[x] += 1\r\n\r\nfor x in t:\r\n ret += count[-x]\r\n if x == 0:\r\n ret -= 1\r\n\r\nprint ret / 2\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are solving the crossword problem K from IPSC 2014. You solved all the clues except for one: who does Eevee evolve into? You are not very into pokemons, but quick googling helped you find out, that Eevee can evolve into eight different pokemons: Vaporeon, Jolteon, Flareon, Espeon, Umbreon, Leafeon, Glaceon, and Sylveon.\n\nYou know the length of the word in the crossword, and you already know some letters. Designers of the crossword made sure that the answer is unambiguous, so you can assume that exactly one pokemon out of the 8 that Eevee evolves into fits the length and the letters given. Your task is to find it.",
"input": "",
"output": "```python\nimport re\ninput()\ns = input()\narr = ['vaporeon', 'jolteon', 'flareon', 'espeon', 'umbreon', 'leafeon', 'glaceon', 'sylveon']\nfor res in arr:\n\tif re.match(s, res):\n\t\tprint(res)\n\t\tbreak\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vasya wants to turn on Christmas lights consisting of *m* bulbs. Initially, all bulbs are turned off. There are *n* buttons, each of them is connected to some set of bulbs. Vasya can press any of these buttons. When the button is pressed, it turns on all the bulbs it's connected to. Can Vasya light up all the bulbs?\n\nIf Vasya presses the button such that some bulbs connected to it are already turned on, they do not change their state, i.e. remain turned on.",
"input": "",
"output": "```python\nn,m=map(int,input().split())\r\nnum=[(int(x) for x in input().split())for i in range(n)]\r\nx=0\r\nfor i in range(m):\r\n if i in num:\r\n x+=1\r\nprint(['NO','YES'][x!=m])\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Lolek and Bolek are about to travel abroad by plane. The local airport has a special \"Choose Your Plane\" offer. The offer's conditions are as follows:\n - it is up to a passenger to choose a plane to fly on; - if the chosen plane has *x* (*x*<=><=0) empty seats at the given moment, then the ticket for such a plane costs *x* zlotys (units of Polish currency). \nThe only ticket office of the airport already has a queue of *n* passengers in front of it. Lolek and Bolek have not stood in the queue yet, but they are already wondering what is the maximum and the minimum number of zlotys the airport administration can earn if all *n* passengers buy tickets according to the conditions of this offer?\n\nThe passengers buy tickets in turn, the first person in the queue goes first, then goes the second one, and so on up to *n*-th person.",
"input": "",
"output": "```python\ndef get_cost(command,zlotys,passengers,cost = 0):\r\n while passengers:\r\n\r\n cost += command(zlotys)\r\n\r\n zlotys[zlotys.index(command(zlotys))] -= 1\r\n\r\n if not zlotys[zlotys.index(command(zlotys))]:\r\n zlotys.pop(zlotys.index(command(zlotys)))\r\n \r\n passengers -= 1\r\n \r\n return cost\r\n\r\npassengers,planes = map(int,input().split())\r\nzlotys = [int(x) for x in input().split()]\r\n\r\nexpensive = get_cost(max,zlotys[:],passengers)\r\ncheap = get_cost(min,zlotys,passengers)\r\n\r\nprint (expensive,cheap)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "There are *n* cards (*n* is even) in the deck. Each card has a positive integer written on it. *n*<=/<=2 people will play new card game. At the beginning of the game each player gets two cards, each card is given to exactly one player. \n\nFind the way to distribute cards such that the sum of values written of the cards will be equal for each player. It is guaranteed that it is always possible.",
"input": "",
"output": "```python\ndef division():\r\n\tn = int(input())\r\n\ta = [(int(num), i) for i, num in enumerate(input().split(), 1)]\r\n\r\n\ta.sort()\r\n\tfor i in range(n // 2):\r\n\t\tprint(a[i][1], a[n - 1 - i][1])\r\n\r\ndivision()\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corresponding lowercase letter. Help Petya perform the comparison.",
"input": "",
"output": "```python\nword1 = str(input()).lower()\r\nword2 = str(input()).lower()\r\n\r\nif (word1 == word2): print(0)\r\nelif (word1 < word2): print(-1)\r\nelse: print(1)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vitaly is a diligent student who never missed a lesson in his five years of studying in the university. He always does his homework on time and passes his exams in time. \n\nDuring the last lesson the teacher has provided two strings *s* and *t* to Vitaly. The strings have the same length, they consist of lowercase English letters, string *s* is lexicographically smaller than string *t*. Vitaly wondered if there is such string that is lexicographically larger than string *s* and at the same is lexicographically smaller than string *t*. This string should also consist of lowercase English letters and have the length equal to the lengths of strings *s* and *t*. \n\nLet's help Vitaly solve this easy problem!",
"input": "",
"output": "```python\ndef charToInt(c): #'a'->0\r\n return ord(c)-ord('a')\r\ndef intToChar(x): #0->'a'\r\n return chr(ord('a')+x)\r\n\r\ns=input()\r\nt=input()\r\n\r\ntt=[charToInt(c) for c in t]\r\nss=[charToInt(c) for c in s]\r\nn=len(tt)\r\n\r\nfor i in range(n-1,-1,-1):\r\n ss[i]+=1\r\n if ss[i]==26:\r\n ss[i]-=1\r\n else:\r\n break\r\n\r\ns=''.join([intToChar(x) for x in ss])\r\nif s==t:\r\n print('No such string')\r\nelse:\r\n print(s)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.",
"input": "",
"output": "```python\ndef main():\r\n n = int(input())\r\n arr = list(map(int, input().split()))\r\n even = 0\r\n odd = 0\r\n\r\n for i in arr:\r\n if i % 2 == 0:\r\n even += 1\r\n else:\r\n odd += 1\r\n\r\n for i in range(n):\r\n if even == 1:\r\n if arr[i] % 2 == 0:\r\n print(i + 1)\r\n exit()\r\n else:\r\n if arr[i] % 2 != 0:\r\n print(i + 1)\r\n exit()\r\n\r\n\r\nmain()\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?\n\nYou are given a system of equations: \n\nYou should count, how many there are pairs of integers (*a*,<=*b*) (0<=≤<=*a*,<=*b*) which satisfy the system.",
"input": "",
"output": "```python\n# your code goes here# your code goes her\r\nn,m=map(int,input().split())\r\ndiff= n-m\r\nans=0\r\nfor i in range(1001):\r\n\tfor j in range(1001):\r\n\t\teq=(i-j)*(i+j-1)\r\n\t\tif eq==diff and (i*i+j)==n and (j*j+i)==m:\r\n\t\t\tans=ans+1\r\n\t\t\r\nprint(ans)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Jon fought bravely to rescue the wildlings who were attacked by the white-walkers at Hardhome. On his arrival, Sam tells him that he wants to go to Oldtown to train at the Citadel to become a maester, so he can return and take the deceased Aemon's place as maester of Castle Black. Jon agrees to Sam's proposal and Sam sets off his journey to the Citadel. However becoming a trainee at the Citadel is not a cakewalk and hence the maesters at the Citadel gave Sam a problem to test his eligibility. \n\nInitially Sam has a list with a single element *n*. Then he has to perform certain operations on this list. In each operation Sam must remove any element *x*, such that *x*<=><=1, from the list and insert at the same position , , sequentially. He must continue with these operations until all the elements in the list are either 0 or 1.\n\nNow the masters want the total number of 1s in the range *l* to *r* (1-indexed). Sam wants to become a maester but unfortunately he cannot solve this problem. Can you help Sam to pass the eligibility test?",
"input": "",
"output": "```python\nn,l,r = map(int,input().split(' '))\nx = n\nlen = 0\ndef lon(c):\n if c > 0:\n return 1 + lon(c // 2) + lon(c // 2)\n else:\n return 0\nlen =lon(x)\n\ndef f(n,left,right):\n if right < l or left > r:\n return 0\n else:\n mid = (left + right) // 2\n if mid <= r and mid >= l:\n if n == 1:\n return 1\n else:\n return n % 2 + f(n // 2,left,mid - 1) + f(n // 2,mid + 1,right)\n elif mid > r:\n return 0 + f(n // 2,left,mid - 1)\n elif mid < l:\n return 0 + f(n // 2,mid + 1,right)\n\nprint(f(n,1,len))\n\t\t\t \t \t \t\t \t \t\t\t \t\t \t\t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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:\n - 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). \nNow Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.\n\nPolycarp 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.\n\nAs Polycarp has no time, he is asking for your help in solving this problem.",
"input": "",
"output": "```python\nans = 0\ntry:\n\tn = 0\n\twhile True:\n\t\ts = input()\n\t\tif s[0] == '+':\n\t\t\tn += 1\n\t\telif s[0] == '-':\n\t\t\tn -= 1\n\t\telse:\n\t\t\tans += len(s.split(':')[1]) * n\nexcept:\n\tpass\nprint(ans)\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm:\n - if the last digit of the number is non-zero, she decreases the number by one; - if the last digit of the number is zero, she divides the number by 10 (i.e. removes the last digit). \nYou are given an integer number $n$. Tanya will subtract one from it $k$ times. Your task is to print the result after all $k$ subtractions.\n\nIt is guaranteed that the result will be positive integer number.",
"input": "",
"output": "```python\n# for _ in range(int(input())):\r\nn,k = input().split()\r\nn = int(n)\r\nk=int(k)\r\nwhile k !=0:\r\n if n%10 >=k:\r\n n = n-k\r\n k=0\r\n elif n%10 ==0:\r\n n = n//10\r\n k -=1\r\n else:\r\n temp = n%10\r\n n -= temp\r\n k -=temp\r\n # print(n)\r\nprint(n)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Yaroslav has an array that consists of *n* integers. In one second Yaroslav can swap two neighboring array elements. Now Yaroslav is wondering if he can obtain an array where any two neighboring elements would be distinct in a finite time.\n\nHelp Yaroslav.",
"input": "",
"output": "```python\n\r\nn = int( input() )\r\n\r\na = list( map( int, input().strip().split( ' ' ) ) )\r\n\r\nm = max( set( a ), key=a.count )\r\nif (n == 1):\r\n print( \"YES\" )\r\nelif (m > n / 2):\r\n print( \"NO\" )\r\nelse:\r\n print( \"YES\" )\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A sequence *a*0,<=*a*1,<=...,<=*a**t*<=-<=1 is called increasing if *a**i*<=-<=1<=<<=*a**i* for each *i*:<=0<=<<=*i*<=<<=*t*.\n\nYou are given a sequence *b*0,<=*b*1,<=...,<=*b**n*<=-<=1 and a positive integer *d*. In each move you may choose one element of the given sequence and add *d* to it. What is the least number of moves required to make the given sequence increasing?",
"input": "",
"output": "```python\nn,d = map(int,input().split())\r\na = list(map(int,input().split()))\r\nans = 1\r\nfor i in range(1,n):\r\n if a[i] <= a[i-1]:\r\n ans += (a[i - 1] - a[i]) // d + 1\r\n a[i] = d*((a[i - 1] - a[i]) // d + 1)\r\nprint(ans)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are given *n* switches and *m* lamps. The *i*-th switch turns on some subset of the lamps. This information is given as the matrix *a* consisting of *n* rows and *m* columns where *a**i*,<=*j*<==<=1 if the *i*-th switch turns on the *j*-th lamp and *a**i*,<=*j*<==<=0 if the *i*-th switch is not connected to the *j*-th lamp.\n\nInitially all *m* lamps are turned off.\n\nSwitches change state only from \"off\" to \"on\". It means that if you press two or more switches connected to the same lamp then the lamp will be turned on after any of this switches is pressed and will remain its state even if any switch connected to this lamp is pressed afterwards.\n\nIt is guaranteed that if you push all *n* switches then all *m* lamps will be turned on.\n\nYour think that you have too many switches and you would like to ignore one of them. \n\nYour task is to say if there exists such a switch that if you will ignore (not use) it but press all the other *n*<=-<=1 switches then all the *m* lamps will be turned on.",
"input": "",
"output": "```python\ndef adding(a, b):\r\n res = \"\"\r\n tracker = True\r\n for i in range(len(a)):\r\n res += str(int(a[i]) + int(b[i]))\r\n if int(a[i]) == 0 and int(b[i]) == 1:\r\n tracker = False\r\n return res, tracker\r\n\r\nif __name__ == \"__main__\":\r\n n, m = list(map(int, input().rstrip().split()))\r\n \r\n switches = []\r\n \r\n while n > 0:\r\n switches.append(input().rstrip())\r\n n -= 1\r\n \r\n total = \"\" \r\n for i in range(m):\r\n total += \"0\"\r\n \r\n #print(total)\r\n #print(switches)\r\n \r\n tracker = False\r\n \r\n for i in range(len(switches)):\r\n total, tracker = adding(total, switches[i])\r\n \r\n #print(total)\r\n \r\n \r\n if tracker:\r\n print(\"YES\")\r\n else:\r\n print(\"NO\")\r\n \r\n \r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "In the beginning of the new year Keivan decided to reverse his name. He doesn't like palindromes, so he changed Naviek to Navick.\n\nHe is too selfish, so for a given *n* he wants to obtain a string of *n* characters, each of which is either 'a', 'b' or 'c', with no palindromes of length 3 appearing in the string as a substring. For example, the strings \"abc\" and \"abca\" suit him, while the string \"aba\" doesn't. He also want the number of letters 'c' in his string to be as little as possible.",
"input": "",
"output": "```python\nimport random\r\nn = int(input()) # the length of the string\r\noptions = ['a', 'b', 'c']\r\noutput = []\r\n\r\ni = 0\r\n\r\nwhile len(output) < n:\r\n if i % 3 == 0:\r\n i = 0\r\n\r\n next = options[i]\r\n output.append(next)\r\n i += 1\r\n\r\nprint(\"\".join(output))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "One day shooshuns found a sequence of *n* integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps:\n 1. Find the number that goes *k*-th in the current sequence and add the same number to the end of the sequence; 1. Delete the first number of the current sequence. \nThe shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.",
"input": "",
"output": "```python\nimport math\r\n\r\ndef input_list_int():\r\n return list(map(int, input().split()))\r\n\r\n\r\nn, _k = input_list_int()\r\na = input_list_int()\r\n\r\nk = _k - 1\r\n\r\ns = False\r\nel = a[k]\r\nfor i in range(k, n):\r\n if a[i] != el:\r\n print(-1)\r\n exit()\r\n\r\nj = 0\r\nfor i in range(k):\r\n if a[i] != a[k+1]:\r\n j = i\r\n\r\nprint(j+1)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "This problem's actual name, \"Lexicographically Largest Palindromic Subsequence\" is too long to fit into the page headline.\n\nYou are given string *s* consisting of lowercase English letters only. Find its lexicographically largest palindromic subsequence.\n\nWe'll call a non-empty string *s*[*p*1*p*2... *p**k*] = *s**p*1*s**p*2... *s**p**k* (1 <=≤<= *p*1<=<<=*p*2<=<<=...<=<<=*p**k* <=≤<= |*s*|) a subsequence of string *s* = *s*1*s*2... *s*|*s*|, where |*s*| is the length of string *s*. For example, strings \"abcb\", \"b\" and \"abacaba\" are subsequences of string \"abacaba\".\n\nString *x* = *x*1*x*2... *x*|*x*| is lexicographically larger than string *y* = *y*1*y*2... *y*|*y*| if either |*x*| > |*y*| and *x*1<==<=*y*1, *x*2<==<=*y*2, ...,<=*x*|*y*|<==<=*y*|*y*|, or there exists such number *r* (*r*<=<<=|*x*|, *r*<=<<=|*y*|) that *x*1<==<=*y*1, *x*2<==<=*y*2, ..., *x**r*<==<=*y**r* and *x**r*<=<=+<=<=1<=><=*y**r*<=<=+<=<=1. Characters in the strings are compared according to their ASCII codes. For example, string \"ranger\" is lexicographically larger than string \"racecar\" and string \"poster\" is lexicographically larger than string \"post\".\n\nString *s* = *s*1*s*2... *s*|*s*| is a palindrome if it matches string *rev*(*s*) = *s*|*s*|*s*|*s*|<=-<=1... *s*1. In other words, a string is a palindrome if it reads the same way from left to right and from right to left. For example, palindromic strings are \"racecar\", \"refer\" and \"z\".",
"input": "",
"output": "```python\nans = \"\"\r\ns = input()\r\nfor m in range(1 << len(s)):\r\n f = \"\".join([s[i] for i in range(len(s)) if m & (1 << i)])\r\n if f == f[::-1]:\r\n ans = max(ans,f)\r\nprint(ans)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "The input contains a single integer *a* (0<=≤<=*a*<=≤<=35).\n\nOutput a single integer.",
"input": "",
"output": "```python\nn = int(input())\r\nprint(2 ** n if n < 35 else 33940307968)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.",
"input": "",
"output": "```python\ns=input()\nt=input()\nprint(\"YES\") if s[::-1]==t else print(\"NO\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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). \n\nYour task is to determine by the given *a*, *b* and *n* who wins the game.",
"input": "",
"output": "```python\na, b, n = map(int, input().split())\r\n\r\n\r\nwhile n > 0:\r\n temp_a, temp_n = a, n\r\n\r\n while temp_n > 0:\r\n temp_a, temp_n = temp_n, temp_a % temp_n\r\n\r\n n -= temp_a\r\n\r\n if n > 0:\r\n temp_b, temp_n = b, n\r\n\r\n while temp_n > 0:\r\n temp_b, temp_n = temp_b, temp_b % temp_n\r\n\r\n n -= temp_b\r\n if n == 0:\r\n print(1)\r\n elif n < 0:\r\n print(0)\r\n elif n == 0:\r\n print(0)\r\n else:\r\n print(1)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Today Vasya visited a widely known site and learned that the continuation of his favourite game Codecraft II will appear after exactly *k* months. He looked at the calendar and learned that at the moment is the month number *s*. Vasya immediately got interested in what month Codecraft III will appear. Help him understand that.\n\nAll the twelve months in Vasya's calendar are named using their usual English names: January, February, March, April, May, June, July, August, September, October, November, December.",
"input": "",
"output": "```python\n#include\r\nusing namespace std;\r\n\r\nint main(void){\r\n string s;\r\n cin>>s;\r\n int k;\r\n cin>>k;\r\n mapm;\r\n m[\"January\"]=1;\r\n m[\"February\"]=2;\r\n m[\"March\"]=3;\r\n m[\"April\"]=4;\r\n m[\"May\"]=5;\r\n m[\"June\"]=6;\r\n m[\"July\"]=7;\r\n m[\"August\"]=8;\r\n m[\"September\"]=9;\r\n m[\"October\"]=10;\r\n m[\"November\"]=11;\r\n m[\"December\"]=12;\r\n int y;\r\n int z;\r\n for(auto x:m){\r\n if(x.first==s){\r\n y=x.second+k;\r\n z=y%12;\r\n }\r\n }\r\n for(auto y:m){\r\n if(y.second==z){\r\n cout<=0\r\nc1,c2,x,y=map(int,input().strip().split())\r\n\r\nlo=1\r\nhi=10**9\r\nans=-1\r\nwhile lo<=hi:\r\n mid=(lo+hi)//2\r\n if check(mid,c1,c2,x,y):\r\n hi=mid-1\r\n ans=mid\r\n else:\r\n lo=mid+1\r\nprint(ans)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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! \n\nMore 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*<=><=*c*, then everything on the screen disappears and after that the word you have typed appears on the screen.\n\nFor 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.\n\nYou're given the times when ZS the Coder typed the words. Determine how many words remain on the screen after he finished typing everything.",
"input": "",
"output": "```python\nn,c=map(int,input().split())\r\nsum=1\r\nwords=list(map(int,input().split()))\r\nfor k in range(1,n):\r\n if words[k]-words[k-1]<=c:\r\n sum+=1\r\n else:\r\n sum=1\r\nprint(sum)\r\n \r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Your security guard friend recently got a new job at a new security company. The company requires him to patrol an area of the city encompassing exactly *N* city blocks, but they let him choose which blocks. That is, your friend must walk the perimeter of a region whose area is exactly *N* blocks. Your friend is quite lazy and would like your help to find the shortest possible route that meets the requirements. The city is laid out in a square grid pattern, and is large enough that for the sake of the problem it can be considered infinite.",
"input": "",
"output": "```python\n#http://codeforces.com/problemset/problem/859/B\r\n\r\n#not done\r\n\r\nimport math\r\n\r\ndef GCD(a,b):\r\n #print(a,b)\r\n if a < b:\r\n a, b = b, a\r\n if a%b == 0:\r\n return b\r\n else:\r\n return GCD(b,a%b)\r\n\r\ndef minLengthsCall(n):\r\n RA = minLengths(n)\r\n #if len(RA) > 2:\r\n #RA.pop()\r\n return RA\r\n\r\ndef minLengths(n):\r\n #print(n)\r\n if n <= 0:\r\n return []\r\n has = n\r\n while has > n//2:\r\n if math.sqrt(has)%1 == 0:\r\n if has == n:\r\n return [int(math.sqrt(has)),int(math.sqrt(has))]\r\n else:\r\n return [int(math.sqrt(has)),int(math.sqrt(has))]+minLengths(n-has)\r\n has -= 1\r\n else:\r\n maxVol = 1*n\r\n pos = [1,n]\r\n #print(pos)\r\n for i in range(1,n+1):\r\n if i*(n-i) > maxVol:\r\n #print(\"HERE\")\r\n maxVol = i*(n-i)\r\n pos = [i,n-i]\r\n return pos\r\n #RA = [int(math.sqrt(n)),int(math.sqrt(n))]+minLengths(n-int(math.sqrt(n))**2)\r\n #return RA\r\n x = 0\r\n\r\ndef minStreets(n):\r\n lengths = minLengthsCall(n)\r\n streets = []\r\n i = 0\r\n while i < len(lengths):\r\n #print(lengths[i],lengths[i+1])\r\n streets.append(2*lengths[i]+2*lengths[i+1])\r\n i += 2\r\n i = 0\r\n j = 2\r\n total = 0\r\n if len(streets) == 1:\r\n return streets[0]\r\n currentStreets = 2*lengths[0]+2*lengths[1]\r\n if streets[0] > streets[1]:\r\n maxW = streets[0]\r\n else:\r\n maxW = streets[1]\r\n #print((lengths))\r\n del lengths[0]\r\n del lengths[0]\r\n currentW = 0\r\n while len(lengths) > 0:\r\n if lengths[0] > lengths[1]:\r\n addW = lengths[0]\r\n width = lengths[0]\r\n height = lengths[1]\r\n else:\r\n addW = lengths[1]\r\n width = lengths[1]\r\n height = lengths[0]\r\n #print(currentStreets,height)\r\n if currentW == 0:\r\n currentStreets += 2*height\r\n currentW = addW\r\n elif addW + currentW <= maxW:\r\n currentStreets += 0\r\n currentW += addW\r\n if currentW > maxW:\r\n currentW = 0\r\n else:\r\n currentStreets += height\r\n currentW += addW\r\n if currentW > maxWL:\r\n currentW = 0\r\n del lengths[0]\r\n del lengths[0]\r\n return currentStreets\r\n \r\nwhile True:\r\n try:\r\n case = input()\r\n temp = int(case)\r\n print(minStreets(temp))\r\n except EOFError:\r\n break\r\n\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vasily the bear has a favorite rectangle, it has one vertex at point (0,<=0), and the opposite vertex at point (*x*,<=*y*). Of course, the sides of Vasya's favorite rectangle are parallel to the coordinate axes. \n\nVasya also loves triangles, if the triangles have one vertex at point *B*<==<=(0,<=0). That's why today he asks you to find two points *A*<==<=(*x*1,<=*y*1) and *C*<==<=(*x*2,<=*y*2), such that the following conditions hold:\n - the coordinates of points: *x*1, *x*2, *y*1, *y*2 are integers. Besides, the following inequation holds: *x*1<=<<=*x*2; - the triangle formed by point *A*, *B* and *C* is rectangular and isosceles ( is right); - all points of the favorite rectangle are located inside or on the border of triangle *ABC*; - the area of triangle *ABC* is as small as possible. \nHelp the bear, find the required points. It is not so hard to proof that these points are unique.",
"input": "",
"output": "```python\n# coding: utf-8\nx, y = [int(i) for i in input().split()]\nlength = abs(x)+abs(y)\nans = []\nif x < 0:\n ans.append([-length,0])\nelse:\n ans.append([length,0])\nif y < 0:\n ans.append([0,-length])\nelse:\n ans.append([0,length])\nans.sort()\nprint(ans[0][0],ans[0][1],ans[1][0],ans[1][1])\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "DZY loves chessboard, and he enjoys playing with it.\n\nHe has a chessboard of *n* rows and *m* columns. Some cells of the chessboard are bad, others are good. For every good cell, DZY wants to put a chessman on it. Each chessman is either white or black. After putting all chessmen, DZY wants that no two chessmen with the same color are on two adjacent cells. Two cells are adjacent if and only if they share a common edge.\n\nYou task is to find any suitable placement of chessmen on the given chessboard.",
"input": "",
"output": "```python\nvalues = input().split()\r\nrows = int(values[0])\r\ncols = int(values[1])\r\n\r\nchessboard = []\r\nfor i in range(rows):\r\n row = []\r\n for j in range(cols):\r\n if i % 2 == 0:\r\n if j % 2 == 0:\r\n row.append('B')\r\n else:\r\n row.append('W')\r\n else:\r\n if j % 2 == 0:\r\n row.append('W')\r\n else:\r\n row.append('B')\r\n chessboard.append(row)\r\n\r\nfor i in range(rows):\r\n row = input()\r\n for j in range(cols):\r\n if row[j] == '-':\r\n chessboard[i][j] = '-'\r\n\r\nfor i in range(rows):\r\n for j in range(cols):\r\n print(chessboard[i][j], end = \"\")\r\n print()\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Little boy Valera studies an algorithm of sorting an integer array. After studying the theory, he went on to the practical tasks. As a result, he wrote a program that sorts an array of *n* integers *a*1,<=*a*2,<=...,<=*a**n* in the non-decreasing order. The pseudocode of the program, written by Valera, is given below. The input of the program gets number *n* and array *a*.\n\nBut Valera could have made a mistake, because he hasn't yet fully learned the sorting algorithm. If Valera made a mistake in his program, you need to give a counter-example that makes his program work improperly (that is, the example that makes the program sort the array not in the non-decreasing order). If such example for the given value of *n* doesn't exist, print -1.",
"input": "",
"output": "```python\nn = int(input())\nif n < 3:\n print(-1)\nelse:\n print(2, 2, *([1] * (n-2)))\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You're given a string of lower-case Latin letters. Your task is to find the length of its longest substring that can be met in the string at least twice. These occurrences can overlap (see sample test 2).",
"input": "",
"output": "```python\ns=input()\r\no=len(s)\r\nk=0\r\nfor i in range(o):\r\n r={0}\r\n for j in range(o-i+1):\r\n if s[j:j+i] in r:k=max(i,k)\r\n else:r.add(s[j:j+i])\r\nprint(k)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "While Mike was walking in the subway, all the stuff in his back-bag dropped on the ground. There were several fax messages among them. He concatenated these strings in some order and now he has string *s*.\n\nHe is not sure if this is his own back-bag or someone else's. He remembered that there were exactly *k* messages in his own bag, each was a palindrome string and all those strings had the same length.\n\nHe asked you to help him and tell him if he has worn his own back-bag. Check if the given string *s* is a concatenation of *k* palindromes of the same length.",
"input": "",
"output": "```python\ntar = input()\r\nk = int(input())\r\nn = len(tar)\r\nall = []\r\nans = True\r\nfor i in range(0,k):\r\n\tall.append(tar[int(i*n/k):int((i+1)*(n/k))])\r\n\t# print(all[i])\r\n\tx = int(n/k/2)\r\n\t# print(all[i][0:x])\r\n\t# print(all[i][x:x*2][::-1])\r\n\tans &= (all[i][0:x] == all[i][x:x*2][::-1])\r\nif ans:\r\n\tprint(\"YES\")\r\nelse:\r\n\tprint(\"NO\")\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You will receive 3 points for solving this problem.\n\nManao is designing the genetic code for a new type of algae to efficiently produce fuel. Specifically, Manao is focusing on a stretch of DNA that encodes one protein. The stretch of DNA is represented by a string containing only the characters 'A', 'T', 'G' and 'C'.\n\nManao has determined that if the stretch of DNA contains a maximal sequence of consecutive identical nucleotides that is of even length, then the protein will be nonfunctional. For example, consider a protein described by DNA string \"GTTAAAG\". It contains four maximal sequences of consecutive identical nucleotides: \"G\", \"TT\", \"AAA\", and \"G\". The protein is nonfunctional because sequence \"TT\" has even length.\n\nManao is trying to obtain a functional protein from the protein he currently has. Manao can insert additional nucleotides into the DNA stretch. Each additional nucleotide is a character from the set {'A', 'T', 'G', 'C'}. Manao wants to determine the minimum number of insertions necessary to make the DNA encode a functional protein.",
"input": "",
"output": "```python\ns=input()\r\nl=len(s)\r\nans=0\r\ni=0\r\nwhile i odd else '0') + 1)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vasya has a non-negative integer *n*. He wants to round it to nearest integer, which ends up with 0. If *n* already ends up with 0, Vasya considers it already rounded.\n\nFor example, if *n*<==<=4722 answer is 4720. If *n*<==<=5 Vasya can round it to 0 or to 10. Both ways are correct.\n\nFor given *n* find out to which integer will Vasya round it.",
"input": "",
"output": "```python\nn=int(input())\r\na=n%10\r\nif a<=5:\r\n print(n-a)\r\nelse:\r\n print(n+(10-a))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "In mathematics, the Pythagorean theorem — is a relation in Euclidean geometry among the three sides of a right-angled triangle. In terms of areas, it states:\n\n In any right-angled triangle, the area of the square whose side is the hypotenuse (the side opposite the right angle) is equal to the sum of the areas of the squares whose sides are the two legs (the two sides that meet at a right angle). \n\nThe theorem can be written as an equation relating the lengths of the sides *a*, *b* and *c*, often called the Pythagorean equation:\n\nwhere *c* represents the length of the hypotenuse, and *a* and *b* represent the lengths of the other two sides.\n\nGiven *n*, your task is to count how many right-angled triangles with side-lengths *a*, *b* and *c* that satisfied an inequality 1<=≤<=*a*<=≤<=*b*<=≤<=*c*<=≤<=*n*.",
"input": "",
"output": "```python\nfrom math import ceil,sqrt\r\nn=int(input())\r\namt=0\r\nfor a in range(1,n+1):\r\n for b in range(a,n+1):\r\n if (sqrt(a**2+b**2))==ceil((sqrt(a**2+b**2))) and (sqrt(a**2+b**2))<=n:\r\n amt+=1\r\nprint(amt) \r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A big company decided to launch a new series of rectangular displays, and decided that the display must have exactly *n* pixels. \n\nYour task is to determine the size of the rectangular display — the number of lines (rows) of pixels *a* and the number of columns of pixels *b*, so that:\n - there are exactly *n* pixels on the display; - the number of rows does not exceed the number of columns, it means *a*<=≤<=*b*; - the difference *b*<=-<=*a* is as small as possible.",
"input": "",
"output": "```python\nn=int(input())\r\ndmin=100000000\r\na=0\r\nb=0\r\nfor i in range(1,n+1,1):\r\n\tfor k in range(1,n+1,1):\r\n\t\tj=k\r\n\t\t#print(i,j,sep=\" \")\r\n\t\tif i*j==n:\r\n\t\t\t#print(i,j,sep=\" \")\r\n\r\n\t\t\tif i<=j:\r\n\t\t\t\t#print(i,j,sep=\" \")\r\n\r\n\t\t\t\tminn=j-i\r\n\t\t\t\tif minn x_now:\r\n if x_now + step_size > x:\r\n x_now -= step_size\r\n else:\r\n x_now += step_size\r\n else:\r\n if x_now - step_size < x:\r\n x_now += step_size\r\n else:\r\n x_now -= step_size\r\n\r\n step_num += 1\r\n step_size += 1\r\n\r\nprint(step_num)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "There are three friend living on the straight line *Ox* in Lineland. The first friend lives at the point *x*1, the second friend lives at the point *x*2, and the third friend lives at the point *x*3. They plan to celebrate the New Year together, so they need to meet at one point. What is the minimum total distance they have to travel in order to meet at some point and celebrate the New Year?\n\nIt's guaranteed that the optimal answer is always integer.",
"input": "",
"output": "```python\n\ninput_str = input(\"Enter space-separated integers: \")\n\n\ninput_list = list(map(int, input_str.split()))\n\nmax_value = max(input_list)\nmin_value = min(input_list)\n\ndifference = max_value - min_value\n\nprint(\"The difference between the maximum and minimum values is:\", difference)\n\n\t\t\t \t\t\t \t \t\t \t \t \t \t\t\t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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:\n\n1. Each domino completely covers two squares.\n\n2. No two dominoes overlap.\n\n3. Each domino lies entirely inside the board. It is allowed to touch the edges of the board.\n\nFind the maximum number of dominoes, which can be placed under these restrictions.",
"input": "",
"output": "```python\nm, n = map(int, input().split())\r\nprint(m * (n - (n%2))//2 + (n%2) * m//2)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Iahub got bored, so he invented a game to be played on paper. \n\nHe writes *n* integers *a*1,<=*a*2,<=...,<=*a**n*. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices *i* and *j* (1<=≤<=*i*<=≤<=*j*<=≤<=*n*) and flips all values *a**k* for which their positions are in range [*i*,<=*j*] (that is *i*<=≤<=*k*<=≤<=*j*). Flip the value of *x* means to apply operation *x*<==<=1 - *x*.\n\nThe goal of the game is that after exactly one move to obtain the maximum number of ones. Write a program to solve the little game of Iahub.",
"input": "",
"output": "```python\nn = int(input())\r\nlis = list(map(int, input().split()))\r\ncnt = 0\r\nmx = 0\r\nmxx = 0\r\nfor i in lis:\r\n if i == 1:\r\n cnt += 1\r\n if mx:\r\n mx -= 1\r\n else:\r\n mx += 1\r\n mxx = max(mx, mxx)\r\nprint(cnt + mxx)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "This task is very simple. Given a string *S* of length *n* and *q* queries each query is on the format *i* *j* *k* which means sort the substring consisting of the characters from *i* to *j* in non-decreasing order if *k*<==<=1 or in non-increasing order if *k*<==<=0.\n\nOutput the final string after applying the queries.",
"input": "",
"output": "```python\nstrLength, n = list(map(int, input().split()))\ninputString = input()\n\nfor i in range(n):\n start, end, method = list(map(int, input().split()))\n\n firstPart = inputString[:start - 1]\n lastPart = inputString[end:]\n\n mainPart = inputString[start -1: end]\n\n if method == 1:\n reverseOrder = 0\n else:\n reverseOrder = 1\n\n mainPart = ''.join(sorted(list(mainPart), reverse=reverseOrder))\n\n inputString = firstPart + mainPart + lastPart\n\n\n\nprint(inputString)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "\"QAQ\" is a word to denote an expression of crying. Imagine \"Q\" as eyes with tears and \"A\" as a mouth.\n\nNow Diamond has given Bort a string consisting of only uppercase English letters of length *n*. There is a great number of \"QAQ\" in the string (Diamond is so cute!).\n\nBort wants to know how many subsequences \"QAQ\" are in the string Diamond has given. Note that the letters \"QAQ\" don't have to be consecutive, but the order of letters should be exact.",
"input": "",
"output": "```python\ns = input()\r\nc = 0\r\nfirst_q_count = 0\r\nlast_q_count = s.count(\"Q\")\r\nfor i in range(len(s)):\r\n char = s[i]\r\n if char == \"Q\":\r\n first_q_count += 1\r\n last_q_count -= 1\r\n if char == \"A\":\r\n c += first_q_count * last_q_count\r\nprint(c)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "What joy! Petya's parents went on a business trip for the whole year and the playful kid is left all by himself. Petya got absolutely happy. He jumped on the bed and threw pillows all day long, until... \n\nToday Petya opened the cupboard and found a scary note there. His parents had left him with duties: he should water their favourite flower all year, each day, in the morning, in the afternoon and in the evening. \"Wait a second!\" — thought Petya. He know for a fact that if he fulfills the parents' task in the *i*-th (1<=≤<=*i*<=≤<=12) month of the year, then the flower will grow by *a**i* centimeters, and if he doesn't water the flower in the *i*-th month, then the flower won't grow this month. Petya also knows that try as he might, his parents won't believe that he has been watering the flower if it grows strictly less than by *k* centimeters. \n\nHelp Petya choose the minimum number of months when he will water the flower, given that the flower should grow no less than by *k* centimeters.",
"input": "",
"output": "```python\nlength = int(input())\r\nmonth = list(map(int, input().split()))\r\nmonth.sort(reverse=True)\r\nbig = month[0]\r\ndays = 1\r\nif length == 0:\r\n print(0)\r\n exit()\r\nfor i in range(1, 12):\r\n if big >= length:\r\n break\r\n else:\r\n big += month[i]\r\n days += 1\r\n\r\n\r\nif big >= length:\r\n print(days)\r\nelse:\r\n print(-1)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Given an array *a*1,<=*a*2,<=...,<=*a**n* of *n* integers, find the largest number in the array that is not a perfect square.\n\nA number *x* is said to be a perfect square if there exists an integer *y* such that *x*<==<=*y*2.",
"input": "",
"output": "```python\ndef isPerfect(num):\r\n cnt = 0\r\n for i in range(2,num):\r\n if num%i==0:\r\n cnt += 1\r\n if cnt%2==0:\r\n return False\r\n else:\r\n return True\r\n\r\nn = int(input())\r\ndata = list(map(int, input().split()))\r\ndata.sort(reverse=True)\r\n\r\nfor num in data:\r\n if not isPerfect(num):\r\n print(num)\r\n break\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be. \n\nIn order to make sure that he's right and restore the correct order of keys, Santa typed his favorite patter looking only to his keyboard.\n\nYou are given the Santa's favorite patter and the string he actually typed. Determine which pairs of keys could be mixed. Each key must occur in pairs at most once.",
"input": "",
"output": "```python\np = input()\ntec = input()\n\nres = {}\n\nfudeu = 0\n\nfor i in range(len(p)):\n\n\tif p[i] != tec[i]:\n\t\tif p[i] in res:\n\t\t\tif res[p[i]] != tec[i]:\n\t\t\t\tfudeu=1\n\t\telif tec[i] in res:\n\t\t\tif res[tec[i]] != p[i]:\n\t\t\t\tfudeu = 1\n\t\telse:\n\t\t\tres[p[i]] = tec[i]\n\n\nif fudeu == 0:\n\tprint(len(res))\n\tfor i in res:\n\t\tprint(i,res[i])\nelse:\n\tprint(-1)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are given *n* segments on the Ox-axis. You can drive a nail in any integer point on the Ox-axis line nail so, that all segments containing this point, are considered nailed down. If the nail passes through endpoint of some segment, this segment is considered to be nailed too. What is the smallest number of nails needed to nail all the segments down?",
"input": "",
"output": "```python\nn=int(input())\r\nc=[]\r\nfor i in range(n):\r\n x,y=map(int,input().split())\r\n if x>y: x,y=y,x\r\n c.append([x,0,i])\r\n c.append([y,1,i])\r\nc.sort()\r\nans=0\r\nstack=[]\r\nb=[]\r\nfor z in c:\r\n if z[1]==0:\r\n stack.append(z[2])\r\n else:\r\n if z[2] in stack:\r\n ans+=1\r\n b.append(z[0])\r\n stack=[]\r\nprint(ans)\r\nprint(*b)\r\n \r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Cucumber boy is fan of Kyubeat, a famous music game.\n\nKyubeat has 16 panels for playing arranged in 4<=×<=4 table. When a panel lights up, he has to press that panel.\n\nEach panel has a timing to press (the preffered time when a player should press it), and Cucumber boy is able to press at most *k* panels in a time with his one hand. Cucumber boy is trying to press all panels in perfect timing, that is he wants to press each panel exactly in its preffered time. If he cannot press the panels with his two hands in perfect timing, his challenge to press all the panels in perfect timing will fail.\n\nYou are given one scene of Kyubeat's panel from the music Cucumber boy is trying. Tell him is he able to press all the panels in perfect timing.",
"input": "",
"output": "```python\nk = int(input())\r\nd={}\r\nt=[]\r\nfor i in range(10):\r\n d[i]=0\r\nfor i in range(4):\r\n arr=input()\r\n t.append(arr)\r\nfor i in range(4):\r\n for j in range(4):\r\n if t[i][j]==\".\":\r\n continue\r\n else:\r\n d[int(t[i][j])]+=1\r\nfor i in range(9):\r\n if d[i]>2*k:\r\n print(\"NO\")\r\n break\r\nelse:\r\n print(\"YES\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nPatrick 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.\n\nTo 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.",
"input": "",
"output": "```python\ndef min_changes(s: str) -> int:\n n = len(s)\n dp = [0] * (n + 1)\n for i in range(1, n + 1):\n if s[i - 1].isupper():\n dp[i] = dp[i - 1]\n else:\n dp[i] = min(dp[i - 1] + 1, sum(1 for c in s if c.isupper()))\n return dp[n]\n\ns = input().strip()\nprint(min_changes(s))\n \t \t \t \t \t\t \t \t\t \t \t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Polycarp has created his own training plan to prepare for the programming contests. He will train for $n$ days, all days are numbered from $1$ to $n$, beginning from the first.\n\nOn the $i$-th day Polycarp will necessarily solve $a_i$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.\n\nDetermine the index of day when Polycarp will celebrate the equator.",
"input": "",
"output": "```python\nn=int(input())\r\na=list(map(int,input().split()))\r\ns=sum(a)/2\r\nss=0\r\nfor i in range(n):\r\n ss+=a[i]\r\n if(ss>=s):\r\n print(i+1)\r\n break\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Mishka started participating in a programming contest. There are $n$ problems in the contest. Mishka's problem-solving skill is equal to $k$.\n\nMishka arranges all problems from the contest into a list. Because of his weird principles, Mishka only solves problems from one of the ends of the list. Every time, he chooses which end (left or right) he will solve the next problem from. Thus, each problem Mishka solves is either the leftmost or the rightmost problem in the list.\n\nMishka cannot solve a problem with difficulty greater than $k$. When Mishka solves the problem, it disappears from the list, so the length of the list decreases by $1$. Mishka stops when he is unable to solve any problem from any end of the list.\n\nHow many problems can Mishka solve?",
"input": "",
"output": "```python\nn, k = map(int, input().split())\r\nls = list(map(int, input().split()))\r\ncount = 0\r\nwhile len(ls) > 0:\r\n if ls[0] <= k:\r\n count+=1\r\n ls.pop(0)\r\n else: break\r\nwhile len(ls) > 0:\r\n if ls[len(ls)-1] <= k:\r\n count+=1\r\n ls.pop(len(ls)-1)\r\n else: break\r\n\r\nprint(count)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:\n\nVladik is at initial train station, and now *n* people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code *a**i* is known (the code of the city in which they are going to).\n\nTrain chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city *x*, then all people who are going to city *x* should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city *x*, either go to it and in the same railway carriage, or do not go anywhere at all.\n\nComfort of a train trip with people on segment from position *l* to position *r* is equal to XOR of all distinct codes of cities for people on the segment from position *l* to position *r*. XOR operation also known as exclusive OR.\n\nTotal comfort of a train trip is equal to sum of comfort for each segment.\n\nHelp Vladik to know maximal possible total comfort.",
"input": "",
"output": "```python\nn = int(input())\r\na = list(map(int,input().split()))\r\ndl = dict()\r\ndr = dict()\r\nfor i in range(n):\r\n if a[i] not in dl:\r\n dl[a[i]] = i\r\n dr[a[i]] = i\r\ndef XOR(l):\r\n c = list(set(l))\r\n k = len(c)\r\n x = c[0]\r\n for i in range(1,k):\r\n x ^= c[i]\r\n return x\r\nfrom collections import defaultdict\r\nDP = defaultdict(int)\r\nfor i in range(n):\r\n if dr[a[i]] > i:\r\n DP[i] = DP[i-1]\r\n else:\r\n k = dl[a[i]]\r\n xor = XOR(a[k:i+1])\r\n DP[i] = max(DP[i-1],DP[k-1]+xor)\r\n for j in range(k-1,-1,-1):\r\n if dl[a[j]] == j and dr[a[j]] <= i:\r\n xor ^= a[j]\r\n DP[i] = max(DP[i],DP[j-1] + xor)\r\nprint(DP[n-1])\r\n \r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "This problem's actual name, \"Lexicographically Largest Palindromic Subsequence\" is too long to fit into the page headline.\n\nYou are given string *s* consisting of lowercase English letters only. Find its lexicographically largest palindromic subsequence.\n\nWe'll call a non-empty string *s*[*p*1*p*2... *p**k*] = *s**p*1*s**p*2... *s**p**k* (1 <=≤<= *p*1<=<<=*p*2<=<<=...<=<<=*p**k* <=≤<= |*s*|) a subsequence of string *s* = *s*1*s*2... *s*|*s*|, where |*s*| is the length of string *s*. For example, strings \"abcb\", \"b\" and \"abacaba\" are subsequences of string \"abacaba\".\n\nString *x* = *x*1*x*2... *x*|*x*| is lexicographically larger than string *y* = *y*1*y*2... *y*|*y*| if either |*x*| > |*y*| and *x*1<==<=*y*1, *x*2<==<=*y*2, ...,<=*x*|*y*|<==<=*y*|*y*|, or there exists such number *r* (*r*<=<<=|*x*|, *r*<=<<=|*y*|) that *x*1<==<=*y*1, *x*2<==<=*y*2, ..., *x**r*<==<=*y**r* and *x**r*<=<=+<=<=1<=><=*y**r*<=<=+<=<=1. Characters in the strings are compared according to their ASCII codes. For example, string \"ranger\" is lexicographically larger than string \"racecar\" and string \"poster\" is lexicographically larger than string \"post\".\n\nString *s* = *s*1*s*2... *s*|*s*| is a palindrome if it matches string *rev*(*s*) = *s*|*s*|*s*|*s*|<=-<=1... *s*1. In other words, a string is a palindrome if it reads the same way from left to right and from right to left. For example, palindromic strings are \"racecar\", \"refer\" and \"z\".",
"input": "",
"output": "```python\ns=input()\r\nm=max(s)\r\nwhile s.count(max(s))==1:\r\n s.remove(max(s))\r\n if s==\"\":\r\n break\r\nif s==\"\":\r\n print(m)\r\nelse:\r\n print(max(s)*s.count(max(s)))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.\n\nA tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (*u*,<=*v*) that belongs to the graph, *u* and *v* belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.\n\nDr. Evil gave Mahmoud and Ehab a tree consisting of *n* nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?\n\nA loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .",
"input": "",
"output": "```python\nimport pprint\r\n\r\nclass Bipartite_Graph:\r\n\r\n def __init__(self):\r\n self.graph={\r\n # 1:[2,4,3],\r\n # 2:[1,3,5],\r\n # 3:[2,4,1],\r\n # 4:[5,3,1],\r\n # 5:[4,2]\r\n }\r\n self.vis=set()\r\n self.colored={}\r\n self.bipartite=True\r\n \r\n\r\n def add_edge(self,a,b): \r\n if(not a in self.graph):\r\n self.graph[a] = set()\r\n if(not b in self.graph):\r\n self.graph[b] = set()\r\n\r\n self.graph[a].add(b)\r\n self.graph[b].add(a)\r\n\r\n\r\n def del_edge(self, a, b): #if not making bipartiness then delete\r\n self.graph[a].remove(b)\r\n self.graph[b].remove(a)\r\n\r\n\r\n def dfs_util(self,v,visited,color=1):\r\n # print(v)\r\n visited.add(v)\r\n self.vis=visited\r\n\r\n if(v in self.colored and self.colored[v]!=color):\r\n self.bipartite=False\r\n return False\r\n\r\n self.colored[v]=color\r\n\r\n for neighbour in self.graph[v]:\r\n if neighbour not in visited:\r\n self.dfs_util(neighbour,visited,color*-1)\r\n else:\r\n if(self.colored[neighbour]==color): #if parent and child have the same color \r\n self.bipartite=False\r\n return False\r\n\r\n\r\n def dfs(self): #handling disconnected graph DFS\r\n visited = set()\r\n self.vis=set()\r\n\r\n for vertex in self.graph:\r\n if vertex not in visited:\r\n self.dfs_util(vertex, visited)\r\n \r\n\r\n\r\n\r\nN=int(input())\r\narr=[int(x) for x in range(1,N+1)]\r\n\r\nedges={}\r\n\r\nfor i in range(N-1): #making all the possible edges regardless of bipartiness\r\n for j in range(i+1,N):\r\n a,b=arr[i],arr[j]\r\n key=str(a)+str(b)\r\n edges[key]=[a,b]\r\n\r\n\r\n# pprint.pprint(edges)\r\n# #creating object of the class\r\nGraph=Bipartite_Graph() \r\n\r\nfor i in range(N-1): #adding edges\r\n a,b=[int(x) for x in input().split()]\r\n Graph.add_edge(a,b)\r\n\r\n# # #remove from the edges dictionary\r\n key=str(a)+str(b)\r\n if(key in edges):\r\n del edges[key]\r\n\r\n\r\nGraph.dfs()\r\n\r\nprint(Graph.graph)\r\nprint(Graph.colored)\r\n\r\ncount=0\r\n\r\nfor edge in edges:\r\n a=int(edge[0])\r\n b=int(edge[1])\r\n\r\n if(Graph.colored[a]!=Graph.colored[b]):\r\n # print(a,b)\r\n count+=1\r\nprint(count)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "In a Berland's zoo there is an enclosure with camels. It is known that camels like to spit. Bob watched these interesting animals for the whole day and registered in his notepad where each animal spitted. Now he wants to know if in the zoo there are two camels, which spitted at each other. Help him to solve this task.\n\nThe trajectory of a camel's spit is an arc, i.e. if the camel in position *x* spits *d* meters right, he can hit only the camel in position *x*<=+<=*d*, if such a camel exists.",
"input": "",
"output": "```python\nn=int(input())\r\nX=set()\r\nXD=set()\r\nfor i in range(n):\r\n x,d=list(map(int,input().split(' ')))\r\n X.add(x)\r\n XD.add(x+d)\r\nif X&XD: print('YES')\r\nelse: print('NO')\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are given a rectangular cake, represented as an *r*<=×<=*c* grid. Each cell either has an evil strawberry, or is empty. For example, a 3<=×<=4 cake may look as follows:\n\nThe cakeminator is going to eat the cake! Each time he eats, he chooses a row or a column that does not contain any evil strawberries and contains at least one cake cell that has not been eaten before, and eats all the cake cells there. He may decide to eat any number of times.\n\nPlease output the maximum number of cake cells that the cakeminator can eat.",
"input": "",
"output": "```python\nr, c = map(int, input().split())\r\n\r\ncake = []\r\nfor i in range(r):\r\n row = input()\r\n cake.append(list(row))\r\n\r\nrow_count = 0\r\ncol_count = 0\r\n\r\nfor i in range(r):\r\n has_strawberry = False\r\n for j in range(c):\r\n if cake[i][j] == 'S':\r\n has_strawberry = True\r\n break\r\n if not has_strawberry:\r\n row_count += 1\r\n\r\nfor j in range(c):\r\n has_strawberry = False\r\n for i in range(r):\r\n if cake[i][j] == 'S':\r\n has_strawberry = True\r\n break\r\n if not has_strawberry:\r\n col_count += 1\r\n\r\nmax_cells = row_count * c + col_count * (r - row_count)\r\nprint(max_cells)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "The nation of Panel holds an annual show called The Number Games, where each district in the nation will be represented by one contestant.\n\nThe nation has $n$ districts numbered from $1$ to $n$, each district has exactly one path connecting it to every other district. The number of fans of a contestant from district $i$ is equal to $2^i$.\n\nThis year, the president decided to reduce the costs. He wants to remove $k$ contestants from the games. However, the districts of the removed contestants will be furious and will not allow anyone to cross through their districts. \n\nThe president wants to ensure that all remaining contestants are from districts that can be reached from one another. He also wishes to maximize the total number of fans of the participating contestants.\n\nWhich contestants should the president remove?",
"input": "",
"output": "```python\nfrom typing import *\n\nV = TypeVar(\"V\")\nclass graph:\n vertices:List[V]\n graphDict:Dict[V,Set[V]]\n def __init__(self,vertices,graphDict):\n self.vertices = vertices\n self.graphDict = graphDict\n\n for v in vertices:\n if not v in self.graphDict:\n self.graphDict[v] = set()\n\n def isEdge(self,a:V,b:V):\n return b in self.graphDict[a]\n\n def neighbours(self,a:V)->List[V]:\n return self.graphDict.get(a,[])\n\n def appendEdge(self,a:V,b:V):\n assert not self.isEdge(a,b)\n self.graphDict[a].add(b)\n self.graphDict[b].add(a)\n\n def deleteEdge(self,a:V,b:V):\n assert self.isEdge(a,b)\n self.graphDict[a].remove(b)\n self.graphDict[b].remove(a)\n\n def rootedEnumeration(self,root:V):\n # Make sure graph is connected\n S:Set[V] = set([root])\n discovered:Set[V] = set()\n decendentDict: Dict[V, List[V]] = dict()\n ordering:List[V] = []\n while bool(S):\n v = S.pop()\n if not v in discovered:\n discovered.add(v)\n ordering.append(v)\n decendentDict[v] = self.graphDict[v] - discovered\n for n in self.graphDict[v]:\n S.add(n)\n\n return decendentDict,ordering\n\n def DFS(self,root:V):\n return self.rootedEnumeration(root)[1]\n\n def spanningTree(self,root:V):\n decendents,order = self.rootedEnumeration(root)\n return rootedTree(root,self.vertices,decendents,order)\n\n @property\n def connected(self)->bool:\n v = self.vertices[0]\n dfs = self.rootedEnumeration(v)\n return (len(dfs) == len(self.vertices))\n\n @staticmethod\n def typicalTree():\n G = graph([1,2,3,4,5],dict())\n G.appendEdge(1,3)\n G.appendEdge(1,4)\n G.appendEdge(4,2)\n G.appendEdge(4,5)\n\n return G\n #Custom Implementations here\n\nclass rootedTree:\n vertices:List[V]\n root:V\n decendents:Dict[V,Set[V]]\n parents:Dict[V,V]\n order:List[V]\n\n def __init__(self,root,vertices,decendents,order):\n self.root = root\n self.vertices = vertices\n self.decendents = decendents\n self.order = order\n\n self.parents = dict()\n\n for v in decendents:\n for child in decendents[v]:\n self.parents[child] = v\n\n\n\ndef decendentMax(G:graph,k:int):\n T = G.spanningTree(len(G.vertices))\n available:List[V] = [v for v in T.vertices if not bool(T.decendents[v])]\n eliminated:Set[V] = set()\n chosen:List[int] = []\n\n while len(chosen) < k:\n taking = min(available)\n eliminated.add(taking)\n chosen.append(taking)\n available.remove(taking)\n\n assert taking != T.root\n p = T.parents[taking]\n\n if(eliminated.issuperset(T.decendents[p])):\n available.append(p)\n\n assert len(chosen) == k\n return chosen\n\ndef readInt():\n return int(input())\n\ndef readLine():\n return [int(s) for s in input().split(\" \")]\n\n\nvertices, k = readLine()\nnewGraph = graph(range(1,vertices+1),dict())\n\nfor _ in range(vertices-1):\n a,b = readLine()\n newGraph.appendEdge(a,b)\n\nchosen = decendentMax(newGraph,k)\nchosen.sort()\nprint(\" \".join([str(c) for c in chosen]))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A string is called a *k*-string if it can be represented as *k* concatenated copies of some string. For example, the string \"aabaabaabaab\" is at the same time a 1-string, a 2-string and a 4-string, but it is not a 3-string, a 5-string, or a 6-string and so on. Obviously any string is a 1-string.\n\nYou are given a string *s*, consisting of lowercase English letters and a positive integer *k*. Your task is to reorder the letters in the string *s* in such a way that the resulting string is a *k*-string.",
"input": "",
"output": "```python\nk = int(input())\r\nvisited = {}\r\nword = input()\r\n\r\nfor c in word:\r\n if not c in visited:\r\n visited[c] = 0\r\n visited[c] += 1\r\n\r\nresult = []\r\n\r\nfor c in visited:\r\n if visited[c] % k == 0:\r\n result.append(c * (visited[c] // k))\r\n else:\r\n print(-1)\r\n exit(0)\r\nprint(''.join(result) * k)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are given two strings $s$ and $t$. In a single move, you can choose any of two strings and delete the first (that is, the leftmost) character. After a move, the length of the string decreases by $1$. You can't choose a string if it is empty.\n\nFor example:\n - by applying a move to the string \"where\", the result is the string \"here\", - by applying a move to the string \"a\", the result is an empty string \"\". \nYou are required to make two given strings equal using the fewest number of moves. It is possible that, in the end, both strings will be equal to the empty string, and so, are equal to each other. In this case, the answer is obviously the sum of the lengths of the initial strings.\n\nWrite a program that finds the minimum number of moves to make two given strings $s$ and $t$ equal.",
"input": "",
"output": "```python\na=str(input())\r\nb=str(input())\r\nff=0\r\nc=0\r\nfor l,i in enumerate(a):\r\n for f,j in enumerate(b):\r\n if(i==j):\r\n ia=l\r\n ib=f\r\n stra=a[ia:]\r\n strb=b[ib:]\r\n if(stra==strb):\r\n ff=ia+ib\r\n c=1\r\n break\r\n if c==1:\r\n break\r\nprint(ff) \r\n #EEEEEEEEEEEEEEEEEE\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vasya has recently bought some land and decided to surround it with a wooden fence.\n\nHe went to a company called \"Wooden board\" that produces wooden boards for fences. Vasya read in the catalog of products that the company has at its disposal *n* different types of wood. The company uses the *i*-th type of wood to produce a board of this type that is a rectangular *a**i* by *b**i* block.\n\nVasya decided to order boards in this company and build a fence from them. It turned out that the storehouse of the company is so large that Vasya can order arbitrary number of boards of every type. Note that Vasya is allowed to turn the boards as he builds the fence. However, Vasya cannot turn square boards.\n\nVasya is required to construct a fence of length *l*, however, an arbitrary fence won't do. Vasya wants his fence to look beautiful. We'll say that a fence is beautiful if and only if the following two conditions are fulfilled:\n - there are no two successive boards of the same type - the first board of the fence has an arbitrary length, and the length of each subsequent board equals the width of the previous one \nIn other words, the fence is considered beautiful, if the type of the *i*-th board in the fence is different from the *i*<=-<=1-th board's type; besides, the *i*-th board's length is equal to the *i*<=-<=1-th board's width (for all *i*, starting from 2).\n\nNow Vasya wonders, how many variants of arranging a fence for his land exist. Your task is to count the number of different beautiful fences of length *l*.\n\nTwo fences will be considered the same if the corresponding sequences of fence boards types and rotations are the same, otherwise the fences are different. Since the sought number can be large enough, you need to calculate the answer modulo 1000000007 (109<=+<=7).",
"input": "",
"output": "```python\nmod = int(1e9+7)\r\n\r\nn, len = map(int, input().split())\r\n\r\na = [0] * n\r\nb = [0] * n\r\n\r\nf = [[[0] * 2 for i in range(len+1)] for j in range(n)]\r\nfor i in range(n):\r\n a[i], b[i] = map(int, input().split())\r\n if a[i] <= len:\r\n f[i][a[i]][0] += 1\r\n if a[i] != b[i] and b[i] <= len:\r\n f[i][b[i]][1] += 1\r\n\r\nfor i in range(len + 1):\r\n for j in range(n):\r\n for k in range(n):\r\n if j == k: continue\r\n\r\n if a[k] == a[j] and i + a[k] <= len:\r\n f[k][i + a[k]][0] += f[j][i][1]\r\n f[k][i + a[k]][0] %= mod\r\n\r\n if a[k] == b[j] and i + a[k] <= len:\r\n f[k][i + a[k]][0] += f[j][i][0]\r\n f[k][i + a[k]][0] %= mod\r\n\r\n if a[k] == b[k]: continue\r\n\r\n if b[k] == a[j] and i + b[k] <= len:\r\n f[k][i + b[k]][1] += f[j][i][1]\r\n f[k][i + b[k]][1] %= mod\r\n\r\n if b[k] == b[j] and i + b[k] <= len:\r\n f[k][i + b[k]][1] += f[j][i][0]\r\n f[k][i + b[k]][1] %= mod\r\n\r\nans = sum([(f[i][len][0] + f[i][len][1]) % mod for i in range(n)]) % mod\r\nprint(ans)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vasya has got two number: *a* and *b*. However, Vasya finds number *a* too short. So he decided to repeat the operation of lengthening number *a* *n* times.\n\nOne operation of lengthening a number means adding exactly one digit to the number (in the decimal notation) to the right provided that the resulting number is divisible by Vasya's number *b*. If it is impossible to obtain the number which is divisible by *b*, then the lengthening operation cannot be performed.\n\nYour task is to help Vasya and print the number he can get after applying the lengthening operation to number *a* *n* times.",
"input": "",
"output": "```python\nimport sys,os,io,time,copy,math\r\nfrom functools import lru_cache\r\nif os.path.exists('input.txt'):\r\n sys.stdin = open('input.txt', 'r')\r\n sys.stdout = open('output.txt', 'w') \r\n\r\ndef is_sorted(arr):\r\n if all(arr[i]<=arr[i+1] for i in range(len(arr)-1)):\r\n return True\r\n else:\r\n return False\r\n\r\ndef main(): \r\n a,b,n=map(int,input().split())\r\n if b<=10:\r\n a1=-1\r\n for i in range(10):\r\n a1=a*10+i\r\n if a1&b==0:\r\n break\r\n if a1==-1:\r\n print(-1)\r\n else:\r\n print(a1,end=\"\")\r\n for i in range(n-2):\r\n print(b,end=\"\")\r\n print(\"\")\r\n else:\r\n a1=-1\r\n for i in range(10):\r\n a1=a*10+i\r\n if a1&b==0:\r\n break\r\n print(a1)\r\n \r\n\r\n\r\n\r\n\r\nmain()\r\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Once Bob needed to find the second order statistics of a sequence of integer numbers. Lets choose each number from the sequence exactly once and sort them. The value on the second position is the second order statistics of the given sequence. In other words it is the smallest element strictly greater than the minimum. Help Bob solve this problem.",
"input": "",
"output": "```python\ni = int(input())\nl = [int(x) for x in input().split()]\nl = sorted(set(l))\nif len(l)==1:\n print('NO')\nelse:\n print(l[1])\n\n\t\t \t\t \t\t \t\t\t \t \t\t \t\t \t\t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "As technologies develop, manufacturers are making the process of unlocking a phone as user-friendly as possible. To unlock its new phone, Arkady's pet dog Mu-mu has to bark the password once. The phone represents a password as a string of two lowercase English letters.\n\nMu-mu's enemy Kashtanka wants to unlock Mu-mu's phone to steal some sensible information, but it can only bark *n* distinct words, each of which can be represented as a string of two lowercase English letters. Kashtanka wants to bark several words (not necessarily distinct) one after another to pronounce a string containing the password as a substring. Tell if it's possible to unlock the phone in this way, or not.",
"input": "",
"output": "```python\ndef solution():\r\n password = input()\r\n num_words = int(input())\r\n words = []\r\n for _ in range(num_words):\r\n words.append(input())\r\n\r\n for x in range(num_words):\r\n for y in range(num_words):\r\n possible = words[x] + words[y]\r\n if password in possible:\r\n print('YES')\r\n return\r\n print('NO')\r\n\r\n\r\nsolution()\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Someday, Drazil wanted to go on date with Varda. Drazil and Varda live on Cartesian plane. Drazil's home is located in point (0,<=0) and Varda's home is located in point (*a*,<=*b*). In each step, he can move in a unit distance in horizontal or vertical direction. In other words, from position (*x*,<=*y*) he can go to positions (*x*<=+<=1,<=*y*), (*x*<=-<=1,<=*y*), (*x*,<=*y*<=+<=1) or (*x*,<=*y*<=-<=1). \n\nUnfortunately, Drazil doesn't have sense of direction. So he randomly chooses the direction he will go to in each step. He may accidentally return back to his house during his travel. Drazil may even not notice that he has arrived to (*a*,<=*b*) and continue travelling. \n\nLuckily, Drazil arrived to the position (*a*,<=*b*) successfully. Drazil said to Varda: \"It took me exactly *s* steps to travel from my house to yours\". But Varda is confused about his words, she is not sure that it is possible to get from (0,<=0) to (*a*,<=*b*) in exactly *s* steps. Can you find out if it is possible for Varda?",
"input": "",
"output": "```python\na,b,s =map(int,input().split())\r\nx = abs(a) + abs(b)\r\nprint(\"NO\" if s0:\n m=m-1\n else:\n washed=washed+1\n elif a==2:\n if k>0:\n k=k-1\n elif k<=0 and m>0:\n m=m-1\n else:\n washed=washed+1\nprint(washed)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "In Arcady's garden there grows a peculiar apple-tree that fruits one time per year. Its peculiarity can be explained in following way: there are *n* inflorescences, numbered from 1 to *n*. Inflorescence number 1 is situated near base of tree and any other inflorescence with number *i* (*i*<=><=1) is situated at the top of branch, which bottom is *p**i*-th inflorescence and *p**i*<=<<=*i*.\n\nOnce tree starts fruiting, there appears exactly one apple in each inflorescence. The same moment as apples appear, they start to roll down along branches to the very base of tree. Each second all apples, except ones in first inflorescence simultaneously roll down one branch closer to tree base, e.g. apple in *a*-th inflorescence gets to *p**a*-th inflorescence. Apples that end up in first inflorescence are gathered by Arcady in exactly the same moment. Second peculiarity of this tree is that once two apples are in same inflorescence they annihilate. This happens with each pair of apples, e.g. if there are 5 apples in same inflorescence in same time, only one will not be annihilated and if there are 8 apples, all apples will be annihilated. Thus, there can be no more than one apple in each inflorescence in each moment of time.\n\nHelp Arcady with counting number of apples he will be able to collect from first inflorescence during one harvest.",
"input": "",
"output": "```python\nfrom collections import Counter,UserString\r\nimport sys\r\nimport threading\r\nsys.setrecursionlimit(10000000)\r\ntry:\r\n pass\r\n #sys.stdin=open('test','r')\r\nexcept:\r\n pass\r\ndef main():\r\n n=int(input())\r\n a=[0,-1]+list(map(int,input().split()))\r\n b=[[] for i in range(n+1)]\r\n for i in range(2,n+1):\r\n b[a[i]].append(i)\r\n a.clear()\r\n d=[0 for i in range(n)]\r\n\r\n\r\n def dfs(i,l):\r\n d[l]=d[l]+1\r\n for i0 in b[i]:\r\n dfs(i0,l+1)\r\n\r\n def deff(a):\r\n return a%2\r\n dfs(1,0)\r\n print(sum(list(map(deff,d))))\r\nthreading.stack_size=10000000\r\nth=threading.Thread(target=main)\r\nth.run()\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "One fine October day a mathematics teacher Vasily Petrov went to a class and saw there *n* pupils who sat at the desks, two people at each desk. Vasily quickly realized that number *n* is even. Like all true mathematicians, Vasily has all students numbered from 1 to *n*.\n\nBut Vasily Petrov did not like the way the children were seated at the desks. According to him, the students whose numbers differ by 1, can not sit together, as they talk to each other all the time, distract others and misbehave.\n\nOn the other hand, if a righthanded student sits at the left end of the desk and a lefthanded student sits at the right end of the desk, they hit elbows all the time and distract each other. In other cases, the students who sit at the same desk, do not interfere with each other.\n\nVasily knows very well which students are lefthanders and which ones are righthanders, and he asks you to come up with any order that meets these two uncomplicated conditions (students do not talk to each other and do not bump their elbows). It is guaranteed that the input is such that at least one way to seat the students always exists.",
"input": "",
"output": "```python\nfr = open('input.txt','r')\r\nstudents = int(fr.readline())\r\ntext = fr.readline()\r\nprint(students)\r\nprint(text)\r\nfw = open(\"output.txt\",\"w\")\r\nfw.write(\"Ay 7AGA\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Kolya is going to make fresh orange juice. He has *n* oranges of sizes *a*1,<=*a*2,<=...,<=*a**n*. Kolya will put them in the juicer in the fixed order, starting with orange of size *a*1, then orange of size *a*2 and so on. To be put in the juicer the orange must have size not exceeding *b*, so if Kolya sees an orange that is strictly greater he throws it away and continues with the next one.\n\nThe juicer has a special section to collect waste. It overflows if Kolya squeezes oranges of the total size strictly greater than *d*. When it happens Kolya empties the waste section (even if there are no more oranges) and continues to squeeze the juice. How many times will he have to empty the waste section?",
"input": "",
"output": "```python\na, b, d = map(int, input().split())\r\narr = list(map(int, input().split()))\r\n\r\nans = 0\r\nbin = 0\r\nfor n in arr:\r\n if n <= b:\r\n bin += n\r\n if bin > d:\r\n ans += 1\r\n bin = 0\r\n\r\nprint(ans)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "This winter is so cold in Nvodsk! A group of *n* friends decided to buy *k* bottles of a soft drink called \"Take-It-Light\" to warm up a bit. Each bottle has *l* milliliters of the drink. Also they bought *c* limes and cut each of them into *d* slices. After that they found *p* grams of salt.\n\nTo make a toast, each friend needs *nl* milliliters of the drink, a slice of lime and *np* grams of salt. The friends want to make as many toasts as they can, provided they all drink the same amount. How many toasts can each friend make?",
"input": "",
"output": "```python\nn, k, l, c, d, p, nl, np = list(map(int, input().split()))\r\n\r\ntotML = k * l\r\ntotLP = c * d\r\n\r\ntoastML = totML // nl\r\ntotSalt = p // np\r\n\r\nprint(min(toastML, totLP, totSalt) // n)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Mahmoud has *n* line segments, the *i*-th of them has length *a**i*. Ehab challenged him to use exactly 3 line segments to form a non-degenerate triangle. Mahmoud doesn't accept challenges unless he is sure he can win, so he asked you to tell him if he should accept the challenge. Given the lengths of the line segments, check if he can choose exactly 3 of them to form a non-degenerate triangle.\n\nMahmoud should use exactly 3 line segments, he can't concatenate two line segments or change any length. A non-degenerate triangle is a triangle with positive area.",
"input": "",
"output": "```python\n#accumalated 2d matrix\r\n# listy=[list(accumulate(row)) for row in accumulate([[i for i in list(map(int,input().split()))] for j in range(n)])] \r\n\r\nimport sys\r\ninput = lambda: sys.stdin.readline().rstrip()\r\n\r\nx=int(input())\r\nlisty=list(map(int,input().split()))\r\nlisty.sort()\r\ncheck =0\r\nfor i in range(0,x-2,3):\r\n if((listy[i]+listy[i+1])>=listy[i+2]):\r\n check =1\r\n break\r\nif(check):\r\n print(\"YES\")\r\n \r\nelse :\r\n print(\"NO\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A group of *n* friends enjoys playing popular video game Toda 2. There is a rating system describing skill level of each player, initially the rating of the *i*-th friend is *r**i*.\n\nThe friends decided to take part in the championship as a team. But they should have equal ratings to be allowed to compose a single team consisting of all *n* friends. So the friends are faced with the problem: how to make all their ratings equal.\n\nOne way to change ratings is to willingly lose in some matches. Friends can form a party consisting of two to five (but not more than *n*) friends and play a match in the game. When the party loses, the rating of each of its members decreases by 1. A rating can't become negative, so *r**i*<==<=0 doesn't change after losing.\n\nThe friends can take part in multiple matches, each time making a party from any subset of friends (but remember about constraints on party size: from 2 to 5 members).\n\nThe friends want to make their ratings equal but as high as possible.\n\nHelp the friends develop a strategy of losing the matches so that all their ratings become equal and the resulting rating is maximum possible.",
"input": "",
"output": "```python\n# coding=utf-8\r\n\"\"\"Codeforces 730a solution.\"\"\"\r\n\r\nfrom operator import itemgetter\r\n\r\n\r\nclass CodeforcesTask730ASolution:\r\n def __init__(self):\r\n self.result = ''\r\n self.players = 0\r\n self.rating = []\r\n\r\n def read_input(self):\r\n self.players = int(input())\r\n self.rating = [int(x) for x in input().split(\" \")]\r\n\r\n def process_task(self):\r\n\r\n if self.players > 2:\r\n moves = []\r\n players = [[x + 1, self.rating[x]] for x in range(self.players)]\r\n players.sort(key=itemgetter(1), reverse=True)\r\n while players[1][1] != players[-1][1]:\r\n players[0][1] = max(0, players[0][1] - 1)\r\n players[1][1] = max(0, players[1][1] - 1)\r\n moves.append([players[0][0], players[1][0]])\r\n players.sort(key=itemgetter(1), reverse=True)\r\n if players[0][1] != players[-1][1]:\r\n added = False\r\n for m in moves:\r\n if not players[0][0] in m:\r\n m.append(players[0][0])\r\n players[0][1] = max(0, players[0][1] - 1)\r\n added = True\r\n break\r\n if not added:\r\n #print(\"edge case 1\")\r\n #print(players)\r\n moves.append([players[-1][0], players[0][0]])\r\n players[0][1] = max(0, players[0][1] - 1)\r\n players[-1][1] = max(0, players[-1][1] - 1)\r\n while players[0][1] != players[-1][1]:\r\n players[0][1] = max(0, players[0][1] - 1)\r\n players[1][1] = max(0, players[1][1] - 1)\r\n moves.append([players[0][0], players[1][0]])\r\n players.sort(key=itemgetter(1), reverse=True)\r\n if players[0][1] != players[-1][1]:\r\n added = False\r\n for m in moves:\r\n if not players[0][0] in m:\r\n m.append(players[0][0])\r\n players[0][1] = max(0, players[0][1] - 1)\r\n added = True\r\n break\r\n if not added:\r\n #print(players)\r\n print(\"edge case 2\")\r\n players.sort(key=itemgetter(1), reverse=True)\r\n print(players[-1][1])\r\n print(len(moves))\r\n for m in moves:\r\n print(\"\".join([\"1\" if x + 1 in m else \"0\" for x in range(self.players)]))\r\n else:\r\n if self.rating[0] == self.rating[1]:\r\n print(self.rating[0])\r\n print(\"0\")\r\n else:\r\n print(\"0\")\r\n for x in range(max(self.rating)):\r\n print(\"11\")\r\n\r\n def get_result(self):\r\n return self.result\r\n\r\n\r\nif __name__ == \"__main__\":\r\n Solution = CodeforcesTask730ASolution()\r\n Solution.read_input()\r\n Solution.process_task()\r\n print(Solution.get_result())\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.\n\nRules of the game are very simple: at first number of rounds *n* is defined. In every round each of the players throws a cubical dice with distinct numbers from 1 to 6 written on its faces. Player, whose value after throwing the dice is greater, wins the round. In case if player dice values are equal, no one of them is a winner.\n\nIn average, player, who won most of the rounds, is the winner of the game. In case if two players won the same number of rounds, the result of the game is draw.\n\nMishka is still very little and can't count wins and losses, so she asked you to watch their game and determine its result. Please help her!",
"input": "",
"output": "```python\nca,cb = 0,0\r\nt = int(input())\r\nwhile t!=0:\r\n a,b = map(int,input().split())\r\n if a>b:\r\n ca = ca + 1\r\n if b>a:\r\n cb = cb + 1\r\n t-=1\r\nif ca > cb:\r\n print(\"Mishka\")\r\nelif cb > ca:\r\n print(\"Chris\")\r\nelse:\r\n print(\"Friendship is magic!^^\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "When Petya went to school, he got interested in large numbers and what they were called in ancient times. For instance, he learned that the Russian word \"tma\" (which now means \"too much to be counted\") used to stand for a thousand and \"tma tmyschaya\" (which literally means \"the tma of tmas\") used to stand for a million.\n\nPetya wanted to modernize the words we use for numbers and invented a word petricium that represents number *k*. Moreover, petricium la petricium stands for number *k*2, petricium la petricium la petricium stands for *k*3 and so on. All numbers of this form are called petriciumus cifera, and the number's importance is the number of articles la in its title.\n\nPetya's invention brought on a challenge that needed to be solved quickly: does some number *l* belong to the set petriciumus cifera? As Petya is a very busy schoolboy he needs to automate the process, he asked you to solve it.",
"input": "",
"output": "```python\nfrom math import log\r\nn = int(input())\r\nl = int(input())\r\ns = int(log(l,n))\r\ny = s+1\r\nif n**s==l:\r\n print(\"YES\")\r\n print(s-1)\r\nelif n**y==l:\r\n print(\"YES\")\r\n print(y-1)\r\nelse:\r\n print(\"NO\")\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Now Fox Ciel becomes a commander of Tree Land. Tree Land, like its name said, has *n* cities connected by *n*<=-<=1 undirected roads, and for any two cities there always exists a path between them.\n\nFox Ciel needs to assign an officer to each city. Each officer has a rank — a letter from 'A' to 'Z'. So there will be 26 different ranks, and 'A' is the topmost, so 'Z' is the bottommost.\n\nThere are enough officers of each rank. But there is a special rule must obey: if *x* and *y* are two distinct cities and their officers have the same rank, then on the simple path between *x* and *y* there must be a city *z* that has an officer with higher rank. The rule guarantee that a communications between same rank officers will be monitored by higher rank officer.\n\nHelp Ciel to make a valid plan, and if it's impossible, output \"Impossible!\".",
"input": "",
"output": "```python\nPrint(\"I am jocking\");;;\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Two boys decided to compete in text typing on the site \"Key races\". During the competition, they have to type a text consisting of *s* characters. The first participant types one character in *v*1 milliseconds and has ping *t*1 milliseconds. The second participant types one character in *v*2 milliseconds and has ping *t*2 milliseconds.\n\nIf connection ping (delay) is *t* milliseconds, the competition passes for a participant as follows: \n 1. Exactly after *t* milliseconds after the start of the competition the participant receives the text to be entered. 1. Right after that he starts to type it. 1. Exactly *t* milliseconds after he ends typing all the text, the site receives information about it. \nThe winner is the participant whose information on the success comes earlier. If the information comes from both participants at the same time, it is considered that there is a draw.\n\nGiven the length of the text and the information about participants, determine the result of the game.",
"input": "",
"output": "```python\nx,y,z,w=map(int,input().split())\r\np=max(x,y,z,w)\r\nif (p-x)!=0:\r\n print(p-x,end=' ')\r\nif (p-y)!=0:\r\n print(p-y,end=' ')\r\nif (p-z)!=0:\r\n print(p-z,end=' ')\r\nif (p-w)!=0:\r\n print(p-w,end=' ')\r\n\r\n\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nNow 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.\n\nPearlo 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.",
"input": "",
"output": "```python\nstr1=\"\"\r\nfor i in range(3):\r\n str1+=input()\r\nif str1==str1[::-1]:\r\n print(\"YES\")\r\nelse:\r\n print(\"NO\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Arkady wants to water his only flower. Unfortunately, he has a very poor watering system that was designed for $n$ flowers and so it looks like a pipe with $n$ holes. Arkady can only use the water that flows from the first hole.\n\nArkady can block some of the holes, and then pour $A$ liters of water into the pipe. After that, the water will flow out from the non-blocked holes proportionally to their sizes $s_1, s_2, \\ldots, s_n$. In other words, if the sum of sizes of non-blocked holes is $S$, and the $i$-th hole is not blocked, $\\frac{s_i \\cdot A}{S}$ liters of water will flow out of it.\n\nWhat is the minimum number of holes Arkady should block to make at least $B$ liters of water flow out of the first hole?",
"input": "",
"output": "```python\nimport sys\r\nimport math\r\n\r\n#to read string\r\nget_string = lambda: sys.stdin.readline().strip()\r\n#to read list of integers\r\nget_int_list = lambda: list( map(int,sys.stdin.readline().strip().split()) )\r\n#to read integers\r\nget_int = lambda: int(sys.stdin.readline())\r\n#to print fast\r\npt = lambda x: sys.stdout.write(str(x)+'\\n')\r\n\r\n#--------------------------------WhiteHat010--------------------------------------#\r\nn,a,b = get_int_list()\r\nlst = get_int_list()\r\n\r\ns = a*(lst[0])/b\r\n\r\nl = sorted(lst[1:])\r\ntotal = lst[0]\r\ncount = 1\r\nfor i in l:\r\n if total+i <= s:\r\n total += i\r\n count += 1\r\n else:\r\n break\r\n\r\nprint(n-count)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "There is a given string *S* consisting of *N* symbols. Your task is to find the number of ordered pairs of integers *i* and *j* such that\n\n1. 1<=≤<=*i*,<=*j*<=≤<=*N*\n\n2. *S*[*i*]<==<=*S*[*j*], that is the *i*-th symbol of string *S* is equal to the *j*-th.",
"input": "",
"output": "```python\ns = str(input())\r\nlist1 = []\r\nsum = 0\r\nfor x in s:\r\n if x not in list1:\r\n list1.append(x)\r\n if s.count(x) > 1:\r\n sum += (s.count(x) * s.count(x))\r\nif sum == 0:\r\n print(len(s))\r\nelse:\r\n print(sum)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "The winner of the card game popular in Berland \"Berlogging\" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line \"name score\", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to *m*) at the end of the game, than wins the one of them who scored at least *m* points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points.",
"input": "",
"output": "```python\nimport sys \n#from math import gcd\n#from bisect import bisect_left, bisect_right\n\nread_line = lambda: sys.stdin.readline().strip()\nread_intmap = lambda: map(int, read_line().split())\n\ndef testCase():\n n = int(input())\n players = dict()\n for ind in range(1, n + 1):\n name, score = read_line().split()\n score = int(score)\n\n if not name in players:\n players[name] = [0, {0:0}] #curr score, rounds at which score acheived\n\n curr, rec = players[name]\n\n curr += score\n if not curr in rec:\n rec[curr] = ind\n\n players[name] = [curr, rec]\n \n maxScore = max([v[0] for k,v in players.items()])\n minInd = n + 100\n winner = None\n\n for k,v in players.items():\n rec = v[1]\n \n tmpInd = 1e9\n for k2, v2 in rec.items():\n if k2 >= maxScore and v2 < tmpInd:\n tmpInd = v2\n\n if tmpInd < minInd:\n minInd = tmpInd\n winner = k\n\n print(winner)\n\n\nt = 1\n#t = int(input())\nfor i in range(t):\n testCase()\n\n \n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Greatest common divisor *GCD*(*a*,<=*b*) of two positive integers *a* and *b* is equal to the biggest integer *d* such that both integers *a* and *b* are divisible by *d*. There are many efficient algorithms to find greatest common divisor *GCD*(*a*,<=*b*), for example, Euclid algorithm. \n\nFormally, find the biggest integer *d*, such that all integers *a*,<=*a*<=+<=1,<=*a*<=+<=2,<=...,<=*b* are divisible by *d*. To make the problem even more complicated we allow *a* and *b* to be up to googol, 10100 — such number do not fit even in 64-bit integer type!",
"input": "",
"output": "```python\nstart , end = list(map(int ,input().split()))\r\n\r\n\r\ndef gcd(a, b):\r\n if b == 0:\r\n return a\r\n return gcd(b, a % b)\r\n\r\n\r\nres = start\r\nfor i in range(start +1 ,end):\r\n res = gcd(res, i)\r\nprint(res)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it?\n\nThe market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out the name of the company on a piece of paper in a line (horizontally, from left to right) with large English letters, then put this piece of paper in front of the mirror, then the reflection of the name in the mirror should perfectly match the line written on the piece of paper.\n\nThere are many suggestions for the company name, so coming up to the mirror with a piece of paper for each name wouldn't be sensible. The founders of the company decided to automatize this process. They asked you to write a program that can, given a word, determine whether the word is a 'mirror' word or not.",
"input": "",
"output": "```python\n# https://codeforces.com/contest/421/problem/B\r\n# 1000\r\ndef palin(n,k):\r\n for i in range(k//2):\r\n if n[i]!=n[k-i-1]:\r\n return False\r\n return True\r\ns=input()\r\nl=['A','H','W','I','M','Y','X','O','T','U','V']\r\nif palin(s,len(s)):\r\n for i in s:\r\n if i not in l:\r\n print(\"NO\")\r\n exit()\r\n print(\"YES\")\r\nelse:\r\n print(\"NO\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Polycarpus has a ribbon, its length is *n*. He wants to cut the ribbon in a way that fulfils the following two conditions: \n - After the cutting each ribbon piece should have length *a*, *b* or *c*. - After the cutting the number of ribbon pieces should be maximum. \nHelp Polycarpus and find the number of ribbon pieces after the required cutting.",
"input": "",
"output": "```python\nimport sys \r\n \r\nsys.setrecursionlimit(500000000) \r\n \r\ndef f(n): \r\n\r\n if n in memo.keys(): \r\n return memo[n] \r\n \r\n ans = float(\"-inf\") \r\n if n == 0: \r\n return 0 \r\n for length in l: \r\n\r\n if n >= length: \r\n ans = max(ans, 1 + f(n - length)) \r\n\r\n memo[n] = ans \r\n return ans \r\n \r\n\r\nmemo = dict() \r\n \r\nl = list(map(int, input().split())) \r\nn, l = l[0], l[1:] \r\nprint(f(n)) \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "There are *n* parliamentarians in Berland. They are numbered with integers from 1 to *n*. It happened that all parliamentarians with odd indices are Democrats and all parliamentarians with even indices are Republicans.\n\nNew parliament assembly hall is a rectangle consisting of *a*<=×<=*b* chairs — *a* rows of *b* chairs each. Two chairs are considered neighbouring if they share as side. For example, chair number 5 in row number 2 is neighbouring to chairs number 4 and 6 in this row and chairs with number 5 in rows 1 and 3. Thus, chairs have four neighbours in general, except for the chairs on the border of the hall\n\nWe know that if two parliamentarians from one political party (that is two Democrats or two Republicans) seat nearby they spent all time discussing internal party issues.\n\nWrite the program that given the number of parliamentarians and the sizes of the hall determine if there is a way to find a seat for any parliamentarian, such that no two members of the same party share neighbouring seats.",
"input": "",
"output": "```python\nimport sys\r\nn, a, b = map(int, input().split())\r\nif n > a*b:\r\n print(-1)\r\n sys.exit(0)\r\npar = []\r\nfor i in range(1, n+1, b):\r\n s = ['0']*b\r\n for j in range(b):\r\n if i+j <= n:\r\n s[j] = str(i+j)\r\n par.append(s)\r\nwhile len(par) < a:\r\n par.append(['0']*b)\r\nfor i in range(a):\r\n if i%2 == 0:\r\n par[i].reverse()\r\n print(' '.join(par[i]))\r\n else:\r\n print(' '.join(par[i]))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.\n\nFor example, there is a statement called the \"Goldbach's conjecture\". It says: \"each even number no less than four can be expressed as the sum of two primes\". Let's modify it. How about a statement like that: \"each integer no less than 12 can be expressed as the sum of two composite numbers.\" Not like the Goldbach's conjecture, I can prove this theorem.\n\nYou are given an integer *n* no less than 12, express it as a sum of two composite numbers.",
"input": "",
"output": "```python\na=int(input())\r\nif a%2==0:\r\n print('4',a-4)\r\nelse:\r\n print('9',a-9)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Karen is getting ready for a new school day!\n\nIt is currently hh:mm, given in a 24-hour format. As you know, Karen loves palindromes, and she believes that it is good luck to wake up when the time is a palindrome.\n\nWhat is the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome?\n\nRemember that a palindrome is a string that reads the same forwards and backwards. For instance, 05:39 is not a palindrome, because 05:39 backwards is 93:50. On the other hand, 05:50 is a palindrome, because 05:50 backwards is 05:50.",
"input": "",
"output": "```python\nc = [70, 140, 210, 280, 350, 601, 671, 741, 811, 881, 951, 1202, 1272, 1342, 1412, 1440]\r\nd = input().split(':')\r\nd = int(d[0]) * 60 + int(d[1])\r\nm = 10000\r\nfor i in c:\r\n if (i - d) >= 0 and (i - d) <= m:\r\n m = i - d\r\nprint(m)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "The Elements of Harmony are six supernatural artifacts representing subjective aspects of harmony. They are arguably the most powerful force in Equestria. The inside of Elements of Harmony can be seen as a complete graph with *n* vertices labeled from 0 to *n*<=-<=1, where *n* is a power of two, equal to 2*m*.\n\nThe energy in Elements of Harmony is in constant movement. According to the ancient book, the energy of vertex *u* in time *i* (*e**i*[*u*]) equals to: \n\nHere *b*[] is the transformation coefficient — an array of *m*<=+<=1 integers and *f*(*u*,<=*v*) is the number of ones in the binary representation of number (*u* *xor* *v*).\n\nGiven the transformation coefficient and the energy distribution at time 0 (*e*0[]). Help Twilight Sparkle predict the energy distribution at time *t* (*e**t*[]). The answer can be quite large, so output it modulo *p*.",
"input": "",
"output": "```python\ndef Bit(n) :\r\n cnt = 0\r\n while n :\r\n if n & 1 : cnt += 1\r\n n >>= 1\r\n return cnt\r\nb = [];\r\ntmp = input().split();\r\nm = int(tmp[0]); t = int(tmp[1]); kMod = int(tmp[2]);\r\nn = 1 << m\r\na = input().split()\r\nfor i in range(n) : a[i] = int(a[i])\r\nfor i in range(n) : b.append(0)\r\nv = input().split()\r\nfor i in range(m + 1) : v[i] = int(v[i])\r\nfor i in range(n) : b[i] = v[Bit(i)]\r\nkMod <<= m\r\ndef Pow(a, b) :\r\n ans = 1\r\n while b :\r\n if b & 1 : ans = ans * a % kMod\r\n a = a * a % kMod\r\n b >>= 1\r\n return ans;\r\ni = 2\r\nwhile i <= n :\r\n for j in range(0, n, i) :\r\n for k in range(j, j + (i >> 1)) :\r\n tx = (a[k] + a[k + (i >> 1)]) % kMod\r\n ty = (kMod + a[k] - a[k + (i >> 1)]) % kMod\r\n a[k] = tx; a[k + (i >> 1)] = ty\r\n i <<= 1\r\ni = 2\r\nwhile i <= n :\r\n for j in range(0, n, i) :\r\n for k in range(j, j + (i >> 1)) :\r\n tx = (b[k] + b[k + (i >> 1)]) % kMod\r\n ty = (kMod + b[k] - b[k + (i >> 1)]) % kMod\r\n b[k] = tx; b[k + (i >> 1)] = ty\r\n i <<= 1\r\nfor i in range(n) : a[i] = a[i] * Pow(b[i], t) % kMod\r\ni = 2\r\nwhile i <= n :\r\n for j in range(0, n, i) :\r\n for k in range(j, j + (i >> 1)) :\r\n tx = (a[k] + a[k + (i >> 1)]) % kMod\r\n ty = (kMod + a[k] - a[k + (i >> 1)]) % kMod\r\n a[k] = tx; a[k + (i >> 1)] = ty\r\n i <<= 1\r\nfor i in range(n) : a[i] >>= m\r\nkMod >>= m\r\nfor i in range(n) : print(a[i] % kMod)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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:\n\n1. Each domino completely covers two squares.\n\n2. No two dominoes overlap.\n\n3. Each domino lies entirely inside the board. It is allowed to touch the edges of the board.\n\nFind the maximum number of dominoes, which can be placed under these restrictions.",
"input": "",
"output": "```python\ndef domino_piling(m: int, n: int) -> int:\r\n\treturn int((m * n) / 2)\r\n\r\nif __name__ == '__main__':\r\n\t[m, n] = [int(s) for s in input().split()]\r\n\tprint(domino_piling(m, n))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You've got array *a*[1],<=*a*[2],<=...,<=*a*[*n*], consisting of *n* integers. Count the number of ways to split all the elements of the array into three contiguous parts so that the sum of elements in each part is the same. \n\nMore formally, you need to find the number of such pairs of indices *i*,<=*j* (2<=≤<=*i*<=≤<=*j*<=≤<=*n*<=-<=1), that .",
"input": "",
"output": "```python\nn = int(input())\r\n\r\narr = [0]*n\r\ntemp = 0\r\ninp = input().split()\r\nfor i in range(n):\r\n arr[i] = int(inp[i])\r\n temp += arr[i]\r\n arr[i] = temp\r\nif temp%3 != 0:\r\n print(0)\r\n exit()\r\nfirst = 0\r\nsecond = 0\r\nthird = 0\r\nif temp == 0:\r\n for i in arr:\r\n if i == 0:\r\n first += 1\r\n print(first*(first-1)*(first-2)//6)\r\n exit()\r\nfor i in arr:\r\n if i == temp/3:\r\n first += 1\r\n elif i == (temp/3)*2:\r\n second += 1\r\n elif i == temp:\r\n third += 1\r\nprint(first*second*third)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Pig is visiting a friend.\n\nPig's house is located at point 0, and his friend's house is located at point *m* on an axis.\n\nPig can use teleports to move along the axis.\n\nTo 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.\n\nFormally, 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.\n\nDetermine if Pig can visit the friend using teleports only, or he should use his car.",
"input": "",
"output": "```python\nli = []\nn, m = map(int, input().split())\nfor i in range(n):\n a, b = map(int, input().split())\n li.append([a, b])\n\nli.sort()\ni = 0\n\nwhile len(li) != 1 and li[i][1] >= li[i + 1][0]:\n li[i][1] = max(li[i][1], li[i + 1][1])\n del li[i + 1]\n\n\nif len(li) == 0 and m == 0:\n print(\"YES\")\nelif len(li) == 1 and li[-1][-1] >= m and li[-1][0] == 0:\n print(\"YES\")\nelse:\n print(\"NO\")\n\n\n\t \t \t\t \t \t \t\t \t\t \t\t \t\t\t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Sometimes some words like \"localization\" or \"internationalization\" are so long that writing them many times in one text is quite tiresome.\n\nLet's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.\n\nThis abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.\n\nThus, \"localization\" will be spelt as \"l10n\", and \"internationalization» will be spelt as \"i18n\".\n\nYou are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.",
"input": "",
"output": "```python\nw = input()\n\ns = 0\nfor i in w:\n \n s += 1\ntry:\n w = int(w)\n quit()\nexcept:\n\n if s>=10:\n print(w[0]+str(s-2)+w[-1])\n else:print(w)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A rare article in the Internet is posted without a possibility to comment it. On a Polycarp's website each article has comments feed.\n\nEach comment on Polycarp's website is a non-empty string consisting of uppercase and lowercase letters of English alphabet. Comments have tree-like structure, that means each comment except root comments (comments of the highest level) has exactly one parent comment.\n\nWhen Polycarp wants to save comments to his hard drive he uses the following format. Each comment he writes in the following format: \n - at first, the text of the comment is written; - after that the number of comments is written, for which this comment is a parent comment (i. e. the number of the replies to this comments); - after that the comments for which this comment is a parent comment are written (the writing of these comments uses the same algorithm). \nFor example, if the comments look like:\n\nthen the first comment is written as \"hello,2,ok,0,bye,0\", the second is written as \"test,0\", the third comment is written as \"one,1,two,2,a,0,b,0\". The whole comments feed is written as: \"hello,2,ok,0,bye,0,test,0,one,1,two,2,a,0,b,0\". For a given comments feed in the format specified above print the comments in a different format: \n - at first, print a integer *d* — the maximum depth of nesting comments; - after that print *d* lines, the *i*-th of them corresponds to nesting level *i*; - for the *i*-th row print comments of nesting level *i* in the order of their appearance in the Policarp's comments feed, separated by space.",
"input": "",
"output": "```python\ndef find_depth(line,depth,tree):\r\n if(len(tree) < depth):\r\n branch = list()\r\n tree.append(branch)\r\n tree[depth-1].append(line[0])\r\n if(int(line[1]) == 0):\r\n if(len(line)>0):\r\n return [1,1,line[2:]]\r\n else:\r\n return [1,1]\r\n else:\r\n a = list()\r\n length = int()\r\n temp_line = line[2:]\r\n for i in range(0,int(line[1])):\r\n ans = find_depth(temp_line,depth+1,tree)\r\n a.append(ans[0])\r\n length += ans[1]\r\n temp_line = ans[2]\r\n return [max(a)+1,length+1,temp_line]\r\n\r\ntext = input().split(',')\r\ntotal_word = int(len(text)/2)\r\nmax_depth = 1\r\ndepth = 1\r\ntree = list()\r\ntemp_line = text[:]\r\n\r\nwhile(total_word > 0):\r\n ans = find_depth(temp_line,depth,tree)\r\n max_depth = max(max_depth, ans[0])\r\n temp_line = ans[2]\r\n total_word -= ans[1]\r\n\r\n\r\nprint(max_depth)\r\nfor x in tree:\r\n print(' '.join(str(y) for y in x))\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them.\n\nLet's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain number of words \"WUB\" before the first word of the song (the number may be zero), after the last word (the number may be zero), and between words (at least one between any pair of neighbouring words), and then the boy glues together all the words, including \"WUB\", in one string and plays the song at the club.\n\nFor example, a song with words \"I AM X\" can transform into a dubstep remix as \"WUBWUBIWUBAMWUBWUBX\" and cannot transform into \"WUBWUBIAMWUBX\".\n\nRecently, Petya has heard Vasya's new dubstep track, but since he isn't into modern music, he decided to find out what was the initial song that Vasya remixed. Help Petya restore the original song.",
"input": "",
"output": "```python\ns = input()\r\n\r\nans = s.replace(\"WUB\", \" \").strip() #strip removes spaces at the beginning and end of the string\r\nprint(ans)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.",
"input": "",
"output": "```python\nn = int(input())\r\nline = list(map(int, input().split()))\r\ni = 0\r\nj = 1\r\nk = 2\r\n\r\nif (line[0] % 2 == 0) and (line[1] % 2 == 0):\r\n while k < n:\r\n if (line[k] % 2 != 0):\r\n print(k+1)\r\n break\r\n k += 1\r\n \r\nelif ((line[0] % 2 != 0) or (line[1] % 2 == 0)) or ((line[0] % 2 == 0) or (line[1] % 2 != 0)):\r\n while j < 2:\r\n x = 1\r\n if line[j-1] % 2 != 0:\r\n print(x)\r\n break\r\n x += 1\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Mikhail walks on a 2D plane. He can go either up or right. You are given a sequence of Mikhail's moves. He thinks that this sequence is too long and he wants to make it as short as possible.\n\nIn the given sequence moving up is described by character U and moving right is described by character R. Mikhail can replace any pair of consecutive moves RU or UR with a diagonal move (described as character D). After that, he can go on and do some other replacements, until there is no pair of consecutive moves RU or UR left.\n\nYour problem is to print the minimum possible length of the sequence of moves after the replacements.",
"input": "",
"output": "```python\n\r\n1.\ty=int(input())\r\n2.\ttxt=input()\r\n3.\tn=len(txt)\r\n4.\tD=['RU','UR']\r\n5.\ti=0\r\n6.\twhile i < y-1:\r\n7.\t if txt[i]+txt[i+1] in D:\r\n8.\t n=n-1\r\n9.\t i=i+2\r\n10.\t else:\r\n11.\t i=i+1\r\n12.\tprint(n)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Your friend has *n* cards.\n\nYou know that each card has a lowercase English letter on one side and a digit on the other.\n\nCurrently, your friend has laid out the cards on a table so only one side of each card is visible.\n\nYou would like to know if the following statement is true for cards that your friend owns: \"If a card has a vowel on one side, then it has an even digit on the other side.\" More specifically, a vowel is one of 'a', 'e', 'i', 'o' or 'u', and even digit is one of '0', '2', '4', '6' or '8'.\n\nFor example, if a card has 'a' on one side, and '6' on the other side, then this statement is true for it. Also, the statement is true, for example, for a card with 'b' and '4', and for a card with 'b' and '3' (since the letter is not a vowel). The statement is false, for example, for card with 'e' and '5'. You are interested if the statement is true for all cards. In particular, if no card has a vowel, the statement is true.\n\nTo determine this, you can flip over some cards to reveal the other side. You would like to know what is the minimum number of cards you need to flip in the worst case in order to verify that the statement is true.",
"input": "",
"output": "```python\ns = input()\ncount = 0\nfor c in s:\n if c in \"aeiou\":\n count+=1\n if c in \"13579\":\n count += 1\nprint(count)\n\t \t\t \t \t \t \t \t\t \t\t \t \t \t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A family consisting of father bear, mother bear and son bear owns three cars. Father bear can climb into the largest car and he likes it. Also, mother bear can climb into the middle car and she likes it. Moreover, son bear can climb into the smallest car and he likes it. It's known that the largest car is strictly larger than the middle car, and the middle car is strictly larger than the smallest car. \n\nMasha came to test these cars. She could climb into all cars, but she liked only the smallest car. \n\nIt's known that a character with size *a* can climb into some car with size *b* if and only if *a*<=≤<=*b*, he or she likes it if and only if he can climb into this car and 2*a*<=≥<=*b*.\n\nYou are given sizes of bears and Masha. Find out some possible integer non-negative sizes of cars.",
"input": "",
"output": "```python\npai, mae, filho, maria = [int(x) for x in input().split(' ')]\r\n \r\n \r\ndef solve():\r\n if filho > 2*maria or maria > 2*filho or maria >= mae:\r\n return -1\r\n \r\n if filho > maria:\r\n return max(pai, 2*maria + 2), max(mae, 2*maria + 1), filho\r\n \r\n return max(pai, 2*maria + 2), max(mae, 2*maria + 1), maria\r\n \r\n \r\nx = solve()\r\nif x == -1:\r\n print(-1)\r\nelse:\r\n print(x[0])\r\n print(x[1])\r\n print(x[2])\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vanya got an important task — he should enumerate books in the library and label each book with its number. Each of the *n* books should be assigned with a number from 1 to *n*. Naturally, distinct books should be assigned distinct numbers.\n\nVanya wants to know how many digits he will have to write down as he labels the books.",
"input": "",
"output": "```python\nfrom sys import stdin, stdout\r\nimport math\r\n\r\nn=int(stdin.readline())\r\ni=0\r\nj=1\r\nans=0\r\nfinal=9*pow(10,i)\r\nif(n<=9):\r\n ans=n\r\nelse:\r\n while(n>final):\r\n n = n - final\r\n ans+=final*j\r\n j+=1\r\n i+=1\r\n final = 9 * pow(10, i)\r\n ans+=n*j\r\nstdout.write(str(ans)+\"\\n\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.\n\nRules of the game are very simple: at first number of rounds *n* is defined. In every round each of the players throws a cubical dice with distinct numbers from 1 to 6 written on its faces. Player, whose value after throwing the dice is greater, wins the round. In case if player dice values are equal, no one of them is a winner.\n\nIn average, player, who won most of the rounds, is the winner of the game. In case if two players won the same number of rounds, the result of the game is draw.\n\nMishka is still very little and can't count wins and losses, so she asked you to watch their game and determine its result. Please help her!",
"input": "",
"output": "```python\nl=0\r\nm=0\r\nfor i in range(int(input())):\r\n a,b=map(int,input().split())\r\n if a>b:\r\n l=l+1\r\n elif b>a:\r\n m=m+1\r\nif l>m:\r\n print(\"Miskha\")\r\nelif(l 0:\r\n mid += d * n * (n - 1) / 2.0\r\n else:\r\n mid += (n*n - 1) / 4 * d\r\n else:\r\n if d > 0:\r\n mid += d * n * (n - 1) / 2.0\r\n else:\r\n mid += n*n / 4 * d\r\n\r\nprint(\"%.15f\" % (mid / n))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Greatest common divisor *GCD*(*a*,<=*b*) of two positive integers *a* and *b* is equal to the biggest integer *d* such that both integers *a* and *b* are divisible by *d*. There are many efficient algorithms to find greatest common divisor *GCD*(*a*,<=*b*), for example, Euclid algorithm. \n\nFormally, find the biggest integer *d*, such that all integers *a*,<=*a*<=+<=1,<=*a*<=+<=2,<=...,<=*b* are divisible by *d*. To make the problem even more complicated we allow *a* and *b* to be up to googol, 10100 — such number do not fit even in 64-bit integer type!",
"input": "",
"output": "```python\na , b = map(int, input().split())\r\n\r\ndef gcd(a,b):\r\n if b < a:\r\n a , b = b, a\r\n if b%a == 0:\r\n return a\r\n return gcd(a,b%a)\r\nprint(gcd(a,b))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vitya has just started learning Berlanese language. It is known that Berlanese uses the Latin alphabet. Vowel letters are \"a\", \"o\", \"u\", \"i\", and \"e\". Other letters are consonant.\n\nIn Berlanese, there has to be a vowel after every consonant, but there can be any letter after any vowel. The only exception is a consonant \"n\"; after this letter, there can be any letter (not only a vowel) or there can be no letter at all. For example, the words \"harakiri\", \"yupie\", \"man\", and \"nbo\" are Berlanese while the words \"horse\", \"king\", \"my\", and \"nz\" are not.\n\nHelp Vitya find out if a word $s$ is Berlanese.",
"input": "",
"output": "```python\nn=input()+\"*\"\r\ns=\"Yes\"\r\nfor i in range(len(s)-1):\r\n if n[i] not in \"aeiou\" and n[i+1] not in \"aeiou\":\r\n s=\"No\"\r\n else:\r\n s=\"Yes\"\r\nprint(s)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word *s*. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word \"hello\". For example, if Vasya types the word \"ahhellllloou\", it will be considered that he said hello, and if he types \"hlelo\", it will be considered that Vasya got misunderstood and he didn't manage to say hello. Determine whether Vasya managed to say hello by the given word *s*.",
"input": "",
"output": "```python\nz = 0\nm = input()\nls = ['h', 'e', 'l', 'l', 'o']\nfor i in range(len(m)):\n if len(ls) == 0:\n tm=\"YES\"\n break\n\n if ls[0] == m[i]:\n ls.remove(ls[0])\n\nif len(ls) == 0:\n tm = \"YES\"\n\nif len(ls) != 0:\n tm = \"NO\"\n\nprint(tm)\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw.\n\nThe first player wrote number *a*, the second player wrote number *b*. How many ways to throw a dice are there, at which the first player wins, or there is a draw, or the second player wins?",
"input": "",
"output": "```python\nimport math\r\na,b=map(int,input().split())\r\nx=y=z=0\r\nfor n in range(1,7):\r\n if math.fabs(n-a)>math.fabs(n-b):\r\n x+=1\r\n elif math.fabs(n-a)= 6:\r\n c += n // 4\r\n else:\r\n c = -1\r\n print(c)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Sometimes some words like \"localization\" or \"internationalization\" are so long that writing them many times in one text is quite tiresome.\n\nLet's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.\n\nThis abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.\n\nThus, \"localization\" will be spelt as \"l10n\", and \"internationalization» will be spelt as \"i18n\".\n\nYou are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.",
"input": "",
"output": "```python\nt = int(input())\nfor _ in range(t):\n s = input()\n l = len(s)\n if l > 10:\n r = s[0] + str(l - 2) + s[l-1]\n print(r)\n else:\n print(s)\n \t \t \t\t\t \t \t \t \t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vasya has recently found out what a digital root of a number is and he decided to share his knowledge with you.\n\nLet's assume that *S*(*n*) is the sum of digits of number *n*, for example, *S*(4098)<==<=4<=+<=0<=+<=9<=+<=8<==<=21. Then the digital root of number *n* equals to: \n 1. *dr*(*n*)<==<=*S*(*n*), if *S*(*n*)<=<<=10; 1. *dr*(*n*)<==<=*dr*(<=*S*(*n*)<=), if *S*(*n*)<=≥<=10. \nFor example, *dr*(4098)<=<==<=<=*dr*(21)<=<==<=<=3.\n\nVasya is afraid of large numbers, so the numbers he works with are at most 101000. For all such numbers, he has proved that *dr*(*n*)<=<==<=<=*S*(<=*S*(<=*S*(<=*S*(*n*)<=)<=)<=) (*n*<=≤<=101000).\n\nNow Vasya wants to quickly find numbers with the given digital root. The problem is, he hasn't learned how to do that and he asked you to help him. You task is, given numbers *k* and *d*, find the number consisting of exactly *k* digits (the leading zeroes are not allowed), with digital root equal to *d*, or else state that such number does not exist.",
"input": "",
"output": "```python\nk,d=map(int,input().split())\r\nx=1\r\nfor i in range(1,k):\r\n x=x*10\r\nprint(x*d) \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "According to rules of the Berland fashion, a jacket should be fastened by all the buttons except only one, but not necessarily it should be the last one. Also if the jacket has only one button, it should be fastened, so the jacket will not swinging open.\n\nYou are given a jacket with *n* buttons. Determine if it is fastened in a right way.",
"input": "",
"output": "```python\nn=int(input())\r\nl=list(map(int,input().split()))\r\nif l.count(0)==1 and l[-1]!=0:\r\n print('YES')\r\nelse:\r\n print('NO')\r\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "DZY has a sequence *a*, consisting of *n* integers.\n\nWe'll call a sequence *a**i*,<=*a**i*<=+<=1,<=...,<=*a**j* (1<=≤<=*i*<=≤<=*j*<=≤<=*n*) a subsegment of the sequence *a*. The value (*j*<=-<=*i*<=+<=1) denotes the length of the subsegment.\n\nYour task is to find the longest subsegment of *a*, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing.\n\nYou only need to output the length of the subsegment you find.",
"input": "",
"output": "```python\nfrom collections import deque\nfrom sys import stdin\nlines = deque(line.strip() for line in stdin.readlines())\n\ndef nextline():\n return lines.popleft()\n\ndef types(cast):\n return tuple(int(x) for x in nextline().split())\n\ndef ints():\n return types(int)\n\ndef strs():\n return nextline().split()\n\ndef main():\n # lines will now contain all of the input's lines in a list\n (n,) = ints()\n nums = ints()\n if n == 1:\n return n\n inc = [1]*n\n for i in range(1, n):\n if nums[i] > nums[i-1]:\n inc[i] = inc[i-1]+1\n dec = [1]*n\n for i in range(n-2, -1, -1):\n if nums[i] < nums[i+1]:\n dec[i] = dec[i+1]+1\n m = max(inc[1], dec[-2])+1\n for i in range(1, n-1):\n if nums[i-1]+1 < nums[i+1]:\n length = inc[i-1]+dec[i+1]+1\n if length > m:\n m = length\n return m\n\nif __name__ == '__main__':\n print(main())\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Pashmak decided to give Parmida a pair of flowers from the garden. There are *n* flowers in the garden and the *i*-th of them has a beauty number *b**i*. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty difference is maximal possible!\n\nYour task is to write a program which calculates two things:\n 1. The maximum beauty difference of flowers that Pashmak can give to Parmida. 1. The number of ways that Pashmak can pick the flowers. Two ways are considered different if and only if there is at least one flower that is chosen in the first way and not chosen in the second way.",
"input": "",
"output": "```python\nnum = int(input())\r\nflowers = sorted(list(map(int, input().split())))\r\nfirstdigit = [e for e in flowers[0:num//2] if e == flowers[0]]\r\nlastdigit = [e for e in flowers[num//2::] if e == flowers[-1]]\r\ndifference = lastdigit[0] - firstdigit[0]\r\nprint(difference, len(firstdigit)*len(lastdigit))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nDetermine 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\".\n\nYou 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\".",
"input": "",
"output": "```python\nn = int(input())\r\ns = input()\r\nk = \"\"\r\nfor var in s:\r\n if var == \"x\":\r\n k += \"x\"\r\n else:\r\n k += \" \"\r\ncnt = 0\r\nfor var in k.split():\r\n cnt += max(0, len(var)-2)\r\nprint(cnt)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "There are well-known formulas: , , . Also mathematicians found similar formulas for higher degrees.\n\nFind the value of the sum modulo 109<=+<=7 (so you should find the remainder after dividing the answer by the value 109<=+<=7).",
"input": "",
"output": "```python\nimport sys\r\ninput = sys.stdin.readline\r\n\r\nn, k = [int(i) for i in input().split()]\r\nN = 10 ** 9 + 7\r\n\r\ny = [0]\r\nfor i in range(1, k + 2):\r\n y.append((y[-1] + pow(i, k, N)) % N)\r\n\r\nif n < k + 2:\r\n print(y[n] % N)\r\nelse:\r\n m = k + 2\r\n x = n\r\n modinv = [1] * m\r\n for i in range(2, m):\r\n modinv[i] = (-(N // i) * modinv[N % i]) % N\r\n\r\n invfac = [1]\r\n for i in range(1, m):\r\n invfac.append((invfac[-1]* modinv[i]) % N)\r\n invneg_fac = [invfac[i] * (1 - 2 * (i & 1)) for i in range(m)]\r\n\r\n xfac_down = [1]\r\n for j in reversed(range(x - (m - 1), x + 1)):\r\n xfac_down.append((xfac_down[-1]* j) % N)\r\n\r\n xfac_up = [1]\r\n for j in range(x - (m - 1), x + 1):\r\n xfac_up.append((xfac_up[-1] * j) % N)\r\n\r\n s = 0\r\n for i, pr in enumerate(y):\r\n pr = (pr * xfac_down[i]) % N\r\n pr = (pr * xfac_up[m - 1 - i]) % N\r\n pr = (pr * invfac[i]) % N\r\n pr = (pr * invneg_fac[m - i - 1]) % N\r\n s = (s + pr) % N\r\n\r\n print(s)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "There are *n* pictures delivered for the new exhibition. The *i*-th painting has beauty *a**i*. We know that a visitor becomes happy every time he passes from a painting to a more beautiful one.\n\nWe are allowed to arranged pictures in any order. What is the maximum possible number of times the visitor may become happy while passing all pictures from first to last? In other words, we are allowed to rearrange elements of *a* in any order. What is the maximum possible number of indices *i* (1<=≤<=*i*<=≤<=*n*<=-<=1), such that *a**i*<=+<=1<=><=*a**i*.",
"input": "",
"output": "```python\ninput()\nl=list(map(int,input().split()))\nl=sorted(l)\ncount=0\nfor i in range(0,len(l)-1):\n if l[0] n*(n - 1)//2:\r\n print('Impossible')\r\nelse:\r\n ans = []\r\n cur = 0\r\n acc = 0\r\n for i in range(n):\r\n while cur + acc > m:\r\n ans.append(')')\r\n acc -= 1\r\n ans.append('(')\r\n cur += acc\r\n acc += 1\r\n left_cnt = 0\r\n for i in ans:\r\n if i == '(':\r\n left_cnt += 1\r\n else:\r\n left_cnt -= 1\r\n for i in range(left_cnt):\r\n ans.append(')')\r\n print(''.join(ans))\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are given a set of points on a straight line. Each point has a color assigned to it. For point *a*, its neighbors are the points which don't have any other points between them and *a*. Each point has at most two neighbors - one from the left and one from the right.\n\nYou perform a sequence of operations on this set of points. In one operation, you delete all points which have a neighbor point of a different color than the point itself. Points are deleted simultaneously, i.e. first you decide which points have to be deleted and then delete them. After that you can perform the next operation etc. If an operation would not delete any points, you can't perform it.\n\nHow many operations will you need to perform until the next operation does not have any points to delete?",
"input": "",
"output": "```python\ns = list(input())\r\nk = 0\r\n\r\n\r\ndef check(s):\r\n ind = []\r\n for i, elem in enumerate(s):\r\n if i == 0:\r\n if s[i + 1] != elem:\r\n ind.append(i)\r\n elif i == len(s) - 1:\r\n if s[i - 1] != elem:\r\n ind.append(i)\r\n else:\r\n if s[i + 1] != elem:\r\n ind.append(i)\r\n elif s[i - 1] != elem:\r\n ind.append(i)\r\n return ind\r\n\r\n\r\nn = 0\r\nwhile s:\r\n len_now = len(s)\r\n delete = check(s)\r\n for index in delete:\r\n s.pop(index - n)\r\n n += 1\r\n n = 0\r\n if len(s) == len_now:\r\n break\r\n k += 1\r\n\r\nprint(k)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting.\n\nThe game consists of multiple rounds. Its rules are very simple: in each round, a natural number *k* is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's score is multiplied by *k*2, and the loser's score is multiplied by *k*. In the beginning of the game, both Slastyona and Pushok have scores equal to one.\n\nUnfortunately, Slastyona had lost her notepad where the history of all *n* games was recorded. She managed to recall the final results for each games, though, but all of her memories of them are vague. Help Slastyona verify their correctness, or, to put it another way, for each given pair of scores determine whether it was possible for a game to finish with such result or not.",
"input": "",
"output": "```python\nn=int(input())\r\nfor i in range(n):\r\n a,b=[int(s) for s in input().split()]\r\n l=0\r\n a=a*b\r\n r=10**6+1\r\n while r-l>1:\r\n m=(l+r)//2\r\n k=m**3\r\n if ka:\r\n r=m\r\n else:\r\n print('Yes')\r\n break\r\n else:\r\n if l**3==a or r**3==a:\r\n print('Yes')\r\n else:\r\n print('No')\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Professor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest. \n\nIn total, *n* students will attend, and before the start, every one of them has some positive integer rating. Students are indexed from 1 to *n*. Let's denote the rating of *i*-th student as *a**i*. After the contest ends, every student will end up with some positive integer position. GukiZ expects that his students will take places according to their ratings. \n\nHe thinks that each student will take place equal to . In particular, if student *A* has rating strictly lower then student *B*, *A* will get the strictly better position than *B*, and if two students have equal ratings, they will share the same position. \n\nGukiZ would like you to reconstruct the results by following his expectations. Help him and determine the position after the end of the contest for each of his students if everything goes as expected.",
"input": "",
"output": "```python\nx=int(input())\nstudents=\"\"\nplace=[]\n\n\nstudents=raw_input()\nstudent=list(students)\n\n\n\nfor i in range(x + (x-1)):\n place.append(0)\nfor i in range(x):\n for j in range(x + (x-1)):\n if student[i] mx:\r\n mx = c \r\nprint(mx)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be *n* problems, sorted by difficulty, i.e. problem 1 is the easiest and problem *n* is the hardest. Limak knows it will take him 5·*i* minutes to solve the *i*-th problem.\n\nLimak's friends organize a New Year's Eve party and Limak wants to be there at midnight or earlier. He needs *k* minutes to get there from his house, where he will participate in the contest first.\n\nHow many problems can Limak solve if he wants to make it to the party?",
"input": "",
"output": "```python\nenter=list(map(int,input().split()))\r\n\r\nre_minute=240-enter[1]\r\nlist_of_five=[ x*5 for x in range(1,enter[0]+1)]\r\nres=0\r\n\r\nfor i in range(0,enter[0]):\r\n if re_minute >= list_of_five[i]:\r\n re_minute=re_minute-list_of_five[i]\r\n \r\n res+=1\r\n else:break\r\nprint(res)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Every year, hundreds of people come to summer camps, they learn new algorithms and solve hard problems.\n\nThis is your first year at summer camp, and you are asked to solve the following problem. All integers starting with 1 are written in one line. The prefix of these line is \"123456789101112131415...\". Your task is to print the *n*-th digit of this string (digits are numbered starting with 1.",
"input": "",
"output": "```python\nt=int(input())\r\nchk=\"123456789101112131415\"\r\nif t<=21:\r\n print(chk[t-1])\r\nelse:\r\n print(chk[(t//2)-1])\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Reca company makes monitors, the most popular of their models is AB999 with the screen size *a*<=×<=*b* centimeters. Because of some production peculiarities a screen parameters are integer numbers. Recently the screen sides ratio *x*:<=*y* became popular with users. That's why the company wants to reduce monitor AB999 size so that its screen sides ratio becomes *x*:<=*y*, at the same time they want its total area to be maximal of all possible variants. Your task is to find the screen parameters of the reduced size model, or find out that such a reduction can't be performed.",
"input": "",
"output": "```python\ndef f(a,b,x,y):\r\n if a>=b and a%x ==0 and (a*y//x)<=b :\r\n return (a,(a*y//x))\r\n if a= c):\r\n\t\t\tarr[j] = max(arr[j], arr[j - c] + d)\r\n\t\t\tj -= 1\r\nprint arr[n]\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "The little girl loves the problems on array queries very much.\n\nOne day she came across a rather well-known problem: you've got an array of $n$ elements (the elements of the array are indexed starting from 1); also, there are $q$ queries, each one is defined by a pair of integers $l_i$, $r_i$ $(1 \\le l_i \\le r_i \\le n)$. You need to find for each query the sum of elements of the array with indexes from $l_i$ to $r_i$, inclusive.\n\nThe little girl found the problem rather boring. She decided to reorder the array elements before replying to the queries in a way that makes the sum of query replies maximum possible. Your task is to find the value of this maximum sum.",
"input": "",
"output": "```python\nn,q=map(int,input().split())\na=sorted(map(int,input().split()))\nb=[0]*n\nfor _ in[0]*q:\n l,r=map(int,input().split())\n b[l-1]+=1\n if r f[1]):\r\n maxf = f[1]\r\nmaxs = x - maxf - t[0]\r\nif(maxs > s[1]):\r\n maxs = s[1]\r\nmaxt = x - maxs - maxf\r\nprint(\"{0} {1} {2}\".format(maxf, maxs, maxt))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.\n\nUnfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky digits in it is a lucky number. He wonders whether number *n* is a nearly lucky number.",
"input": "",
"output": "```python\nn = input()\r\nlucky_digits = n.count('4') + n.count('7')\r\n\r\nlucky_count = 0\r\nfor digit in str(lucky_digits):\r\n if digit == '4' or digit == '7':\r\n lucky_count += 1\r\n\r\nif lucky_count == len(str(lucky_digits)):\r\n print(\"YES\")\r\nelse:\r\n print(\"NO\")\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "DZY loves chessboard, and he enjoys playing with it.\n\nHe has a chessboard of *n* rows and *m* columns. Some cells of the chessboard are bad, others are good. For every good cell, DZY wants to put a chessman on it. Each chessman is either white or black. After putting all chessmen, DZY wants that no two chessmen with the same color are on two adjacent cells. Two cells are adjacent if and only if they share a common edge.\n\nYou task is to find any suitable placement of chessmen on the given chessboard.",
"input": "",
"output": "```python\ndef sol(row, col, board, new_board = \"\"):\r\n for i in range(row):\r\n for j in range(col):\r\n if board[i][j] == \"-\": new_board += \"-\"\r\n elif (i + j) % 2 == 0: new_board += \"B\"\r\n else: new_board += \"W\"\r\n new_board += \"\\n\"\r\n \r\n return new_board\r\n\r\n\r\nif __name__ == \"__main__\":\r\n row, col = map(int, input().split())\r\n board = [[x for x in input()] for _ in range(row)]\r\n board = sol(row, col, board)\r\n print (board)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Little Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.\n\nNow he wonders what is an average value of sum of digits of the number *A* written in all bases from 2 to *A*<=-<=1.\n\nNote that all computations should be done in base 10. You should find the result as an irreducible fraction, written in base 10.",
"input": "",
"output": "```python\na, f = int(input()), 0\r\nk = a - 2\r\nfor i in range(2, a):\r\n s = 0\r\n b = a\r\n while True:\r\n s = s * 10 + b%i\r\n if b // i == 0:\r\n break\r\n b = b//i\r\n f += sum([int(i) for i in str(s)])\r\nr = 2\r\nwhile True:\r\n if f%r == 0 and k%r == 0:\r\n f //= r\r\n k //= r\r\n r = 2\r\n else:\r\n r = r + 1\r\n if r > k:\r\n break\r\nprint(f, \"/\", k, sep=\"\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are given an array of *n* elements, you must make it a co-prime array in as few moves as possible.\n\nIn each move you can insert any positive integral number you want not greater than 109 in any place in the array.\n\nAn array is co-prime if any two adjacent numbers of it are co-prime.\n\nIn the number theory, two integers *a* and *b* are said to be co-prime if the only positive integer that divides both of them is 1.",
"input": "",
"output": "```python\n\nfrom math import *\n\nn=int(input())\na=list(map(int,input().split(\" \")))\n\nl=[]\nl.append(a[0])\n\nfor i in range(1,n):\n\tif(gcd(a[i],a[i-1])!=1):\n\t\tl.append(1)\n\n\tl.append(a[i])\n\nprint(len(l)-n)\nprint(*l)\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are given a tetrahedron. Let's mark its vertices with letters *A*, *B*, *C* and *D* correspondingly.\n\nAn ant is standing in the vertex *D* of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place.\n\nYou do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertex *D* to itself in exactly *n* steps. In other words, you are asked to find out the number of different cyclic paths with the length of *n* from vertex *D* to itself. As the number can be quite large, you should print it modulo 1000000007 (109<=+<=7).",
"input": "",
"output": "```python\n#!/usr/bin/env python3\ndef pow(b,e):\n if e == 1:\n return b\n if e%2 == 0:\n result = pow(b,e//2)\n result = result * result\n return result\n else:\n result = pow(b,e//2)\n result = result * result * b\n return result\n return result\n\nn = int(input(\"\"))\nif n%2 == 0:\n print(((pow(3,n)+3)//4)%1000000007)\nelse:\n print(((pow(3,n)-3)//4)%1000000007)\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "One day Kefa found *n* baloons. For convenience, we denote color of *i*-th baloon as *s**i* — lowercase letter of the Latin alphabet. Also Kefa has *k* friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. Help Kefa to find out, can he give out all his baloons, such that no one of his friens will be upset — print «YES», if he can, and «NO», otherwise. Note, that Kefa's friend will not upset, if he doesn't get baloons at all.",
"input": "",
"output": "```python\nn, k = [int(x) for x in input().split()]\r\nl = list(input())\r\ns = list(set(l))\r\nf = -1\r\nfor i in s:\r\n count = 0\r\n for j in l:\r\n if i == j:\r\n count -= -1\r\n f = max(f, count)\r\nif f > k: print(\"NO\")\r\nelse: print(\"YES\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Let's consider a table consisting of *n* rows and *n* columns. The cell located at the intersection of *i*-th row and *j*-th column contains number *i*<=×<=*j*. The rows and columns are numbered starting from 1.\n\nYou are given a positive integer *x*. Your task is to count the number of cells in a table that contain number *x*.",
"input": "",
"output": "```python\nn, x = map(int, input().split())\r\ncn = 0\r\nif n >= x:\r\n cn += 2\r\n n = x // 2+1\r\nif x == 1:\r\n cn -= 1\r\nfor i in range(2, n):\r\n if x % i == 0:\r\n cn += 1\r\nprint(cn)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Alice and Bob love playing one-dimensional battle ships. They play on the field in the form of a line consisting of *n* square cells (that is, on a 1<=×<=*n* table).\n\nAt the beginning of the game Alice puts *k* ships on the field without telling their positions to Bob. Each ship looks as a 1<=×<=*a* rectangle (that is, it occupies a sequence of *a* consecutive squares of the field). The ships cannot intersect and even touch each other.\n\nAfter that Bob makes a sequence of \"shots\". He names cells of the field and Alice either says that the cell is empty (\"miss\"), or that the cell belongs to some ship (\"hit\").\n\nBut here's the problem! Alice like to cheat. May be that is why she responds to each Bob's move with a \"miss\". \n\nHelp Bob catch Alice cheating — find Bob's first move, such that after it you can be sure that Alice cheated.",
"input": "",
"output": "```python\nfrom bisect import bisect_left\r\n\r\ndef solve(n, k, a, m, x):\r\n pre = [0]*(n+2)\r\n pos = [0]*(n+2)\r\n d = [-1]*(n+2)\r\n \r\n for i in range(1, n+1):\r\n pre[i] = pre[i-1] + (i in x)\r\n pos[i] = pos[i-1] + ((i%(a+1)==0) and (i+a <= n) and (i-1 not in x) and (i+a not in x))\r\n \r\n l = 1\r\n r = m\r\n while l <= r:\r\n mid = (l+r)//2\r\n d[mid] = pre[n] - pre[mid] - (pos[n] - pos[mid])\r\n \r\n if d[mid] < k:\r\n l = mid + 1\r\n else:\r\n r = mid - 1\r\n \r\n if l > m:\r\n return -1\r\n else:\r\n return l\r\nn, b, a = map(int, input().split())\r\nm = int(input())\r\nx = list(map(int, input().split()))\r\nprint(solve(n,b,a,m,x))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. \"Piece of cake\" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.",
"input": "",
"output": "```python\nn=int(input())\r\nx,y,z=[],[],[]\r\nfor i in range(n):\r\n s=list(map(int,input().split()))\r\n x.append(s[0])\r\n y.append(s[1])\r\n z.append(s[2])\r\nif sum(x)==0 and sum(y)==0 and sum(z)==0:\r\n print(\"YES\")\r\nelse:\r\n print(\"NO\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Sonya decided that having her own hotel business is the best way of earning money because she can profit and rest wherever she wants.\n\nThe country where Sonya lives is an endless line. There is a city in each integer coordinate on this line. She has $n$ hotels, where the $i$-th hotel is located in the city with coordinate $x_i$. Sonya is a smart girl, so she does not open two or more hotels in the same city.\n\nSonya understands that her business needs to be expanded by opening new hotels, so she decides to build one more. She wants to make the minimum distance from this hotel to all others to be equal to $d$. The girl understands that there are many possible locations to construct such a hotel. Thus she wants to know the number of possible coordinates of the cities where she can build a new hotel. \n\nBecause Sonya is lounging in a jacuzzi in one of her hotels, she is asking you to find the number of cities where she can build a new hotel so that the minimum distance from the original $n$ hotels to the new one is equal to $d$.",
"input": "",
"output": "```python\nn,l=map(int,input().split())\r\nli=list(map(int,input().split()))\r\ncount=0\r\nfor i in range(1,n):\r\n k= li[i]-li[i-1]\r\n if k-(2*l)==0:\r\n count+=1\r\n if k-(2*l)>0:\r\n count+=2\r\nprint(count+2)\r\n\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word *s*. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word \"hello\". For example, if Vasya types the word \"ahhellllloou\", it will be considered that he said hello, and if he types \"hlelo\", it will be considered that Vasya got misunderstood and he didn't manage to say hello. Determine whether Vasya managed to say hello by the given word *s*.",
"input": "",
"output": "```python\nstring = str(input())\r\ntext = 'hello'\r\npointer = 0\r\nfor j in range(len(string)):\r\n if string[j] == text[pointer]:\r\n pointer += 1\r\n if pointer == len(text):\r\n break\r\nif pointer == len(text):\r\n print(\"YES\")\r\nelse:\r\n print(\"NO\")\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Winnie-the-Pooh likes honey very much! That is why he decided to visit his friends. Winnie has got three best friends: Rabbit, Owl and Eeyore, each of them lives in his own house. There are winding paths between each pair of houses. The length of a path between Rabbit's and Owl's houses is *a* meters, between Rabbit's and Eeyore's house is *b* meters, between Owl's and Eeyore's house is *c* meters.\n\nFor enjoying his life and singing merry songs Winnie-the-Pooh should have a meal *n* times a day. Now he is in the Rabbit's house and has a meal for the first time. Each time when in the friend's house where Winnie is now the supply of honey is about to end, Winnie leaves that house. If Winnie has not had a meal the required amount of times, he comes out from the house and goes to someone else of his two friends. For this he chooses one of two adjacent paths, arrives to the house on the other end and visits his friend. You may assume that when Winnie is eating in one of his friend's house, the supply of honey in other friend's houses recover (most probably, they go to the supply store).\n\nWinnie-the-Pooh does not like physical activity. He wants to have a meal *n* times, traveling minimum possible distance. Help him to find this distance.",
"input": "",
"output": "```python\nn = int(input())\r\na = int(input())\r\nb = int(input())\r\nc = int(input())\r\nm = min(a,b,c)\r\n\r\nif m == a:\r\n n -= 1\r\n dist = 0\r\n if n > 0:\r\n dist += n*a\r\n print(dist)\r\nelif m == b:\r\n n -= 1\r\n dist = 0\r\n if n > 0:\r\n dist += n*b\r\n print(dist)\r\nelse:\r\n n -= 1\r\n dist = 0\r\n if n>0:\r\n n -= 1\r\n dist += min(a,b)\r\n if n>0:\r\n dist += n*c\r\n print(dist)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Polycarpus has been working in the analytic department of the \"F.R.A.U.D.\" company for as much as *n* days. Right now his task is to make a series of reports about the company's performance for the last *n* days. We know that the main information in a day report is value *a**i*, the company's profit on the *i*-th day. If *a**i* is negative, then the company suffered losses on the *i*-th day.\n\nPolycarpus should sort the daily reports into folders. Each folder should include data on the company's performance for several consecutive days. Of course, the information on each of the *n* days should be exactly in one folder. Thus, Polycarpus puts information on the first few days in the first folder. The information on the several following days goes to the second folder, and so on.\n\nIt is known that the boss reads one daily report folder per day. If one folder has three or more reports for the days in which the company suffered losses (*a**i*<=<<=0), he loses his temper and his wrath is terrible.\n\nTherefore, Polycarpus wants to prepare the folders so that none of them contains information on three or more days with the loss, and the number of folders is minimal.\n\nWrite a program that, given sequence *a**i*, will print the minimum number of folders.",
"input": "",
"output": "```python\nn=int(input())\r\na=list(map(int,input().split()))\r\npo=0\r\nne=0\r\nno=0\r\nl=[]\r\nfor i in range(n):\r\n\tif(a[i]<0):\r\n\t\tne=ne+1\r\n\tif(a[i]>=0):\r\n\t\tpo=po+1\r\n\tif(ne==2):\r\n\t\tl.append(po+ne)\r\n\t\tpo=0\r\n\t\tne=0\r\nif(len(l)>0):\r\n\tif(po>0 and ne==0 ):\r\n\t\tl[-1]=l[-1]+po\r\n\tif(ne>0 and po>0):\r\n\t\tl.append(ne+po)\r\n\tif(ne>0 and po==0):\r\n\t\tl.append(ne)\r\n\r\nelse:\r\n\tl.append(po+ne)\r\nprint(len(l))\r\nprint(*l)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nPatrick 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.\n\nTo 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.",
"input": "",
"output": "```python\ns = input()\r\nn = len(s)\r\nsml = list(map(lambda i: int('a' <= i <= 'z'), s))\r\ncap = list(map(lambda i: int('A' <= i <= 'Z'), s))\r\nprefsml = [0] * (n+1)\r\nfor i in range(n):\r\n prefsml[i+1] = prefsml[i] + sml[i]\r\nsuffcap = [0] * (n+1)\r\nfor i in range(n-1, -1, -1):\r\n suffcap[i] = suffcap[i+1] + cap[i]\r\nres = 2e9\r\nfor i in range(n):\r\n res = min(res, prefsml[i+1] + suffcap[i])\r\nprint(res - 1)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Recently, a chaotic virus Hexadecimal advanced a new theorem which will shake the Universe. She thinks that each Fibonacci number can be represented as sum of three not necessary different Fibonacci numbers.\n\nLet's remember how Fibonacci numbers can be calculated. *F*0<==<=0, *F*1<==<=1, and all the next numbers are *F**i*<==<=*F**i*<=-<=2<=+<=*F**i*<=-<=1.\n\nSo, Fibonacci numbers make a sequence of numbers: 0, 1, 1, 2, 3, 5, 8, 13, ...\n\nIf you haven't run away from the PC in fear, you have to help the virus. Your task is to divide given Fibonacci number *n* by three not necessary different Fibonacci numbers or say that it is impossible.",
"input": "",
"output": "```python\nn = int(input())\r\n\r\na=0\r\nb=1\r\n\r\nfibs = [a,b]\r\n\r\nwhile(b 10:\r\n print(word[0] + str(len(word) - 2) + word[-1])\r\n else:\r\n print(word)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their average. Of course, with the usual sizes of data, it's nothing challenging — but why not make a similar programming contest problem while we're at it?\n\nYou're given a sequence of *n* data points *a*1,<=...,<=*a**n*. There aren't any big jumps between consecutive data points — for each 1<=≤<=*i*<=<<=*n*, it's guaranteed that |*a**i*<=+<=1<=-<=*a**i*|<=≤<=1.\n\nA range [*l*,<=*r*] of data points is said to be almost constant if the difference between the largest and the smallest value in that range is at most 1. Formally, let *M* be the maximum and *m* the minimum value of *a**i* for *l*<=≤<=*i*<=≤<=*r*; the range [*l*,<=*r*] is almost constant if *M*<=-<=*m*<=≤<=1.\n\nFind the length of the longest almost constant range.",
"input": "",
"output": "```python\nINT_MAX = float('inf')\r\n\r\ndef main():\r\n\r\n n = int(input())\r\n a = [int(i) for i in input().split()]\r\n\r\n mx = -INT_MAX\r\n l = 0\r\n r = 1\r\n while l < n:\r\n while r < n:\r\n if max(a[l:r + 1]) - min(a[l:r + 1]) <= 1:\r\n mx = max(mx, r - l + 1)\r\n r += 1\r\n else:\r\n break\r\n l += 1\r\n\r\n\r\n print(mx)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n\r\n\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You have *n* distinct points on a plane, none of them lie on *OY* axis. Check that there is a point after removal of which the remaining points are located on one side of the *OY* axis.",
"input": "",
"output": "```python\nn=int(input())\r\na=0\r\ny1=0\r\nfor i in range(n):\r\n x,y=[int(i) for i in input().split()]\r\n if x<0:\r\n a+=1\r\n else:\r\n y1+=1\r\nif a<=1 or y1<=1:\r\n print('YES')\r\nelse:\r\n print('NO')\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "The farmer Polycarp has a warehouse with hay, which can be represented as an *n*<=×<=*m* rectangular table, where *n* is the number of rows, and *m* is the number of columns in the table. Each cell of the table contains a haystack. The height in meters of the hay located in the *i*-th row and the *j*-th column is equal to an integer *a**i*,<=*j* and coincides with the number of cubic meters of hay in the haystack, because all cells have the size of the base 1<=×<=1. Polycarp has decided to tidy up in the warehouse by removing an arbitrary integer amount of cubic meters of hay from the top of each stack. You can take different amounts of hay from different haystacks. Besides, it is allowed not to touch a stack at all, or, on the contrary, to remove it completely. If a stack is completely removed, the corresponding cell becomes empty and no longer contains the stack.\n\nPolycarp wants the following requirements to hold after the reorganization:\n - the total amount of hay remaining in the warehouse must be equal to *k*, - the heights of all stacks (i.e., cells containing a non-zero amount of hay) should be the same, - the height of at least one stack must remain the same as it was, - for the stability of the remaining structure all the stacks should form one connected region. \nThe two stacks are considered adjacent if they share a side in the table. The area is called connected if from any of the stack in the area you can get to any other stack in this area, moving only to adjacent stacks. In this case two adjacent stacks necessarily belong to the same area.\n\nHelp Polycarp complete this challenging task or inform that it is impossible.",
"input": "",
"output": "```python\nprint(\"_RANDOM_GUESS_1689592554.5392647\")# 1689592554.539285\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "wHAT DO WE NEED cAPS LOCK FOR?\n\nCaps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage. \n\nLet's consider that a word has been typed with the Caps lock key accidentally switched on, if: \n - either it only contains uppercase letters; - or all letters except for the first one are uppercase. \nIn this case we should automatically change the case of all letters. For example, the case of the letters that form words \"hELLO\", \"HTTP\", \"z\" should be changed.\n\nWrite a program that applies the rule mentioned above. If the rule cannot be applied, the program should leave the word unchanged.",
"input": "",
"output": "```python\ns = str(input())\r\nuppercase_test = 0\r\nuppercase_except_1 = 0\r\n\r\nfor i in range(len(s)):\r\n if ord(s[i])>=65 and ord(s[i])<=90:\r\n uppercase_test += 1\r\nfor i in range(1,len(s)):\r\n if ord(s[i])>=65 and ord(s[i])<=90:\r\n uppercase_except_1 += 1\r\n\r\nif uppercase_except_1 == len(s)-1:\r\n print(str(s[0]).upper()+str(s[1:]).lower())\r\nelif uppercase_test == len(s):\r\n print(str(s[0]).upper()+str(s[1:]).lower())\r\nelse:\r\n print(s)\r\n \r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Linear Kingdom has exactly one tram line. It has *n* stops, numbered from 1 to *n* in the order of tram's movement. At the *i*-th stop *a**i* passengers exit the tram, while *b**i* passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it becomes empty.\n\nYour task is to calculate the tram's minimum capacity such that the number of people inside the tram at any time never exceeds this capacity. Note that at each stop all exiting passengers exit before any entering passenger enters the tram.",
"input": "",
"output": "```python\nstations = int(input())\r\nexist =0\r\nprivious_exist=0\r\nfor _ in range(stations):\r\n privious_exist = exist\r\n exit,enter = map(int,input().split(\" \"))\r\n if _ == stations :\r\n enter =0\r\n exist = privious_exist + (enter - exit)\r\n print(exist)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Tom is interested in power consumption of his favourite laptop. His laptop has three modes. In normal mode laptop consumes *P*1 watt per minute. *T*1 minutes after Tom moved the mouse or touched the keyboard for the last time, a screensaver starts and power consumption changes to *P*2 watt per minute. Finally, after *T*2 minutes from the start of the screensaver, laptop switches to the \"sleep\" mode and consumes *P*3 watt per minute. If Tom moves the mouse or touches the keyboard when the laptop is in the second or in the third mode, it switches to the first (normal) mode. Tom's work with the laptop can be divided into *n* time periods [*l*1,<=*r*1],<=[*l*2,<=*r*2],<=...,<=[*l**n*,<=*r**n*]. During each interval Tom continuously moves the mouse and presses buttons on the keyboard. Between the periods Tom stays away from the laptop. Find out the total amount of power consumed by the laptop during the period [*l*1,<=*r**n*].",
"input": "",
"output": "```python\nn, p1, p2, p3, t1, t2 = list(map(int, input().split(\" \")))\r\n\r\nl = []\r\nfor _ in range(n):\r\n l += list(map(int, input().split(\" \")))\r\n\r\np = 0\r\nfor i in range(len(l) // 2 - 1):\r\n x = l[2 * i + 2] - l[2 * i + 1]\r\n p += p1 * min(t1, x) + p2 * min(t2, max(0, x - t1)) + p3 * max(0, x - t1 - t2)\r\n\r\nfor i in range(len(l) // 2):\r\n x = l[2 * i + 1] - l[2 * i]\r\n p += p1 * x \r\n\r\nprint(p)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "As a result of Pinky and Brain's mysterious experiments in the Large Hadron Collider some portals or black holes opened to the parallel dimension. And the World Evil has crept to the veil between their world and ours. Brain quickly evaluated the situation and he understood that the more evil tentacles creep out and become free, the higher is the possibility that Brain will rule the world.\n\nThe collider's constriction is a rectangular grid rolled into a cylinder and consisting of *n* rows and *m* columns such as is shown in the picture below:\n\nIn this example *n*<==<=4, *m*<==<=5. Dotted lines are corridores that close each column to a ring, i. e. connect the *n*-th and the 1-th rows of the grid.\n\nIn the leftmost column of the grid the portals are situated and the tentacles of the World Evil are ready to creep out from there. In the rightmost column the exit doors are located. The tentacles can only get out through those doors. The segments joining the nodes of the grid are corridors.\n\nBrain would be glad to let all the tentacles out but he faces a problem: the infinite number of tentacles can creep out of the portals, every tentacle possesses infinite length and some width and the volume of the corridors are, unfortunately, quite limited. Brain could approximately evaluate the maximal number of tentacles that will be able to crawl through every corridor.\n\nNow help the mice to determine the maximal number of tentacles of the World Evil that will crawl out of the Large Hadron Collider.",
"input": "",
"output": "```python\nprint(\"_RANDOM_GUESS_1689416376.18644\")# 1689416376.1864593\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A social network for dogs called DH (DogHouse) has *k* special servers to recompress uploaded videos of cute cats. After each video is uploaded, it should be recompressed on one (any) of the servers, and only after that it can be saved in the social network.\n\nWe know that each server takes one second to recompress a one minute fragment. Thus, any server takes *m* seconds to recompress a *m* minute video.\n\nWe know the time when each of the *n* videos were uploaded to the network (in seconds starting from the moment all servers started working). All videos appear at different moments of time and they are recompressed in the order they appear. If some video appeared at time *s*, then its recompressing can start at that very moment, immediately. Some videos can await recompressing when all the servers are busy. In this case, as soon as a server is available, it immediately starts recompressing another video. The videos that await recompressing go in a queue. If by the moment the videos started being recompressed some servers are available, then any of them starts recompressing the video.\n\nFor each video find the moment it stops being recompressed.",
"input": "",
"output": "```python\nn, k = (int(p) for p in input().split())\nInputVideo = [] \nDownLoad = []\nOutputVideo = []\nfor o in range(n):\n I, D = (int(v) for v in input().split())\n InputVideo.append(I)\n DownLoad.append(D)\ni = 0\nfor j in range(k):\n OutputVideo.append(InputVideo[i] + DownLoad[i])\n i += 1\n if i == n:\n break\nbzzz=len(OutputVideo)-k\nwhile(i != n):\n flag = 0\n for l in range(bzzz,k):\n if (InputVideo[i] >= OutputVideo[l]):\n OutputVideo.append(InputVideo[i] + DownLoad[i])\n flag = 1\n break\n if (flag == 0):\n OutputVideo.append(min(OutputVideo[len(OutputVideo)-k:]) + DownLoad[i])\n i += 1\nfor elem in OutputVideo:\n print(elem)\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Two players play a game.\n\nInitially there are $n$ integers $a_1, a_2, \\ldots, a_n$ written on the board. Each turn a player selects one number and erases it from the board. This continues until there is only one number left on the board, i. e. $n - 1$ turns are made. The first player makes the first move, then players alternate turns.\n\nThe first player wants to minimize the last number that would be left on the board, while the second player wants to maximize it.\n\nYou want to know what number will be left on the board after $n - 1$ turns if both players make optimal moves.",
"input": "",
"output": "```python\nn = int(input())\r\na = list(map(int, input().split()))\r\n\r\na.sort()\r\n\r\nfor i in range(n - 1):\r\n if i % 2 == 0:\r\n del a[-1]\r\n elif i % 2 == 1:\r\n del a[0]\r\n\r\nprint(a[0])\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "This problem differs from one which was on the online contest.\n\nThe sequence *a*1,<=*a*2,<=...,<=*a**n* is called increasing, if *a**i*<=<<=*a**i*<=+<=1 for *i*<=<<=*n*.\n\nThe sequence *s*1,<=*s*2,<=...,<=*s**k* is called the subsequence of the sequence *a*1,<=*a*2,<=...,<=*a**n*, if there exist such a set of indexes 1<=≤<=*i*1<=<<=*i*2<=<<=...<=<<=*i**k*<=≤<=*n* that *a**i**j*<==<=*s**j*. In other words, the sequence *s* can be derived from the sequence *a* by crossing out some elements.\n\nYou are given two sequences of integer numbers. You are to find their longest common increasing subsequence, i.e. an increasing sequence of maximum length that is the subsequence of both sequences.",
"input": "",
"output": "```python\nn = int(input())\r\nA = list(map(int, input().split()))\r\nm = int(input())\r\nB = list(map(int, input().split()))\r\nF = [[0 for j in range(m)] for i in range(n)]\r\nP = [0 for j in range(m)]\r\nfor i in range(n):\r\n s = -1\r\n t = 0\r\n for j in range(m):\r\n F[i][j] = F[i-1][j]\r\n if A[i] > B[j] and F[i-1][j] > t:\r\n s = j\r\n t = F[i-1][j] \r\n elif A[i] == B[j] and F[i-1][j] < t+1:\r\n F[i][j] = t + 1 \r\n P[j] = s \r\nR = []\r\nl = 0\r\nfor j in range(m):\r\n if F[n-1][l] < F[n-1][j]:\r\n l = j\r\nwhile l != -1:\r\n R.append(B[l])\r\n l = P[l]\r\nprint(len(R))\r\nprint(*R[::-1])\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "The Little Elephant has an integer *a*, written in the binary notation. He wants to write this number on a piece of paper.\n\nTo make sure that the number *a* fits on the piece of paper, the Little Elephant ought to delete exactly one any digit from number *a* in the binary record. At that a new number appears. It consists of the remaining binary digits, written in the corresponding order (possible, with leading zeroes).\n\nThe Little Elephant wants the number he is going to write on the paper to be as large as possible. Help him find the maximum number that he can obtain after deleting exactly one binary digit and print it in the binary notation.",
"input": "",
"output": "```python\na = input()\r\nfor i in range(len(a)):\r\n if a[i] == \"0\":\r\n print(a[:i] + a[i + 1:])\r\n quit()\r\nprint(a[:len(a) - 1])\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "After the fourth season Sherlock and Moriary have realized the whole foolishness of the battle between them and decided to continue their competitions in peaceful game of Credit Cards.\n\nRules of this game are simple: each player bring his favourite *n*-digit credit card. Then both players name the digits written on their cards one by one. If two digits are not equal, then the player, whose digit is smaller gets a flick (knock in the forehead usually made with a forefinger) from the other player. For example, if *n*<==<=3, Sherlock's card is 123 and Moriarty's card has number 321, first Sherlock names 1 and Moriarty names 3 so Sherlock gets a flick. Then they both digit 2 so no one gets a flick. Finally, Sherlock names 3, while Moriarty names 1 and gets a flick.\n\nOf course, Sherlock will play honestly naming digits one by one in the order they are given, while Moriary, as a true villain, plans to cheat. He is going to name his digits in some other order (however, he is not going to change the overall number of occurences of each digit). For example, in case above Moriarty could name 1, 2, 3 and get no flicks at all, or he can name 2, 3 and 1 to give Sherlock two flicks.\n\nYour goal is to find out the minimum possible number of flicks Moriarty will get (no one likes flicks) and the maximum possible number of flicks Sherlock can get from Moriarty. Note, that these two goals are different and the optimal result may be obtained by using different strategies.",
"input": "",
"output": "```python\nimport bisect\nn = int(input())\n\ns = list(input())\nt = list(input())\n\ns1 = ''\nt1 = ''\n\nfor i in range(len(s)):\n s1+=s[i]\n t1+=t[i]\n\nfor i in range(len(s)):\n s[i] = int(s[i])\n t[i] = int(t[i])\ns = sorted(s)\nt = sorted(t)\ns1 = sorted(s1)\nt1 = sorted(t1)\nwin = 0\ni = 0\nwhile is[i]:\n win+=1\n del t[j]\n break\n else:\n j+=1\n i+=1\nmark = 0\nfor i in range(len(t1)):\n k = bisect.bisect_right(s1,t1[i])\n if k-1>=0:\n if t1[i] >= s1[k-1]:\n mark+=1\n del s1[k-1]\n\nprint(len(s1))\nprint(win)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A well-known art union called \"Kalevich is Alive!\" manufactures objects d'art (pictures). The union consists of *n* painters who decided to organize their work as follows.\n\nEach painter uses only the color that was assigned to him. The colors are distinct for all painters. Let's assume that the first painter uses color 1, the second one uses color 2, and so on. Each picture will contain all these *n* colors. Adding the *j*-th color to the *i*-th picture takes the *j*-th painter *t**ij* units of time.\n\nOrder is important everywhere, so the painters' work is ordered by the following rules:\n - Each picture is first painted by the first painter, then by the second one, and so on. That is, after the *j*-th painter finishes working on the picture, it must go to the (*j*<=+<=1)-th painter (if *j*<=<<=*n*); - each painter works on the pictures in some order: first, he paints the first picture, then he paints the second picture and so on; - each painter can simultaneously work on at most one picture. However, the painters don't need any time to have a rest; - as soon as the *j*-th painter finishes his part of working on the picture, the picture immediately becomes available to the next painter. \nGiven that the painters start working at time 0, find for each picture the time when it is ready for sale.",
"input": "",
"output": "```python\nm,n=map(int,input().split())\r\nf=[[0 for i in range(0,n)] for j in range(0,m)]\r\nfor i in range(0,m):\r\n a=list( map(int,input().split()) )\r\n for j in range(0,n):\r\n if i>0:\r\n f[i][j]=max(f[i-1][j], f[i][j])\r\n if j>0:\r\n f[i][j]=max(f[i][j-1], f[i][j])\r\n f[i][j]+=a[j]\r\n print(f[i][n-1])\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Alice got an array of length $n$ as a birthday present once again! This is the third year in a row! \n\nAnd what is more disappointing, it is overwhelmengly boring, filled entirely with zeros. Bob decided to apply some changes to the array to cheer up Alice.\n\nBob has chosen $m$ changes of the following form. For some integer numbers $x$ and $d$, he chooses an arbitrary position $i$ ($1 \\le i \\le n$) and for every $j \\in [1, n]$ adds $x + d \\cdot dist(i, j)$ to the value of the $j$-th cell. $dist(i, j)$ is the distance between positions $i$ and $j$ (i.e. $dist(i, j) = |i - j|$, where $|x|$ is an absolute value of $x$).\n\nFor example, if Alice currently has an array $[2, 1, 2, 2]$ and Bob chooses position $3$ for $x = -1$ and $d = 2$ then the array will become $[2 - 1 + 2 \\cdot 2,~1 - 1 + 2 \\cdot 1,~2 - 1 + 2 \\cdot 0,~2 - 1 + 2 \\cdot 1]$ = $[5, 2, 1, 3]$. Note that Bob can't choose position $i$ outside of the array (that is, smaller than $1$ or greater than $n$).\n\nAlice will be the happiest when the elements of the array are as big as possible. Bob claimed that the arithmetic mean value of the elements will work fine as a metric.\n\nWhat is the maximum arithmetic mean value Bob can achieve?",
"input": "",
"output": "```python\nn, m = map(int, input().split())\nx = y = z = 0\nwhile m != 0:\n m -= 1\n a, b = map(int, input().split())\n x += a\n if b > 0:\n y += b\n else:\n z += b\n##print(x, y, z)\nans = (n * (n - 1) // 2) * y\nif n & 1:\n ans += ((n // 2) * ((n // 2) - 1) // 2) * z\nelse:\n ans += ((((n - 1) // 2) * (((n - 1) // 2) - 1) // 2) + (n // 2)) * z\nans += x * n\nprint(ans / n)\n\n\t\t\t \t\t \t \t \t\t \t\t\t \t\t\t \t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are given *n* integers *a*1,<=*a*2,<=...,<=*a**n*. Find the number of pairs of indexes *i*,<=*j* (*i*<=<<=*j*) that *a**i*<=+<=*a**j* is a power of 2 (i. e. some integer *x* exists so that *a**i*<=+<=*a**j*<==<=2*x*).",
"input": "",
"output": "```python\nfrom math import log2\r\n\r\nn = int(input())\r\nlista = [*map(int, input().split())]\r\n\r\na = 0\r\n\r\nfor _ in lista:\r\n num = log2(_)\r\n if num.is_integer() == True:\r\n a += 1\r\n\r\nprint(a)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are given two integers *n* and *k*. Find *k*-th smallest divisor of *n*, or report that it doesn't exist.\n\nDivisor of *n* is any such natural number, that *n* can be divided by it without remainder.",
"input": "",
"output": "```python\nfrom math import sqrt\r\ndef kthDivisor(n, k):\r\n p=int(sqrt(n))\r\n \r\n alist=[]\r\n for i in range(1,p+1,1):\r\n if (n%i==0):\r\n alist.append(i)\r\n if (i !=p):\r\n alist.append(int(n/i))\r\n alist.sort()\r\n print(alist)\r\n if k >len(alist):\r\n print(-1)\r\n else:\r\n return alist[k-1]\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are given a following process. \n\nThere is a platform with $n$ columns. $1 \\times 1$ squares are appearing one after another in some columns on this platform. If there are no squares in the column, a square will occupy the bottom row. Otherwise a square will appear at the top of the highest square of this column. \n\nWhen all of the $n$ columns have at least one square in them, the bottom row is being removed. You will receive $1$ point for this, and all the squares left will fall down one row. \n\nYou task is to calculate the amount of points you will receive.",
"input": "",
"output": "```python\nif __name__ == '__main__':\n n, m = input().split()\n n = int(n)\n m = int(m)\n\n squares = input().split(\" \")\n cont = [0] * n\n for i in squares:\n cont[int(i) - 1] += 1\n print(min(cont))\n\n\n\t \t \t\t\t\t\t \t\t\t \t \t \t\t\t \t \t \t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Kefa decided to make some money doing business on the Internet for exactly *n* days. He knows that on the *i*-th day (1<=≤<=*i*<=≤<=*n*) he makes *a**i* money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence *a**i*. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.\n\nHelp Kefa cope with this task!",
"input": "",
"output": "```python\ndias = int(input())\r\ndinero = list(map(int,input().split()))\r\n\r\ncanti_num_ord = 1\r\nj = 1\r\n\r\nfor i in range(1,dias):\r\n if dinero[i] >= dinero[i-1]:\r\n j += 1\r\n else:\r\n canti_num_ord = j\r\n j = 1\r\n\r\n\r\nprint(max(canti_num_ord,j))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Every year, hundreds of people come to summer camps, they learn new algorithms and solve hard problems.\n\nThis is your first year at summer camp, and you are asked to solve the following problem. All integers starting with 1 are written in one line. The prefix of these line is \"123456789101112131415...\". Your task is to print the *n*-th digit of this string (digits are numbered starting with 1.",
"input": "",
"output": "```python\nn = int(input())\r\nif n < 10:\r\n print(n)\r\nelif n < 90 * 2 + 9:\r\n x = (n - 10) // 2 + 10\r\n if n % 2:\r\n print(x % 10)\r\n else:\r\n print(x // 10)\r\nelif n < 900 * 3 + 90 * 2 + 9:\r\n x = (n - 10 - 90 * 2) // 3 + 100\r\n print(x)\r\n if (n - 10 - 90 * 2) % 3 == 1:\r\n print(x % 10)\r\n elif (n - 10 - 90 * 2) % 3 == 2:\r\n print(x // 10 % 10)\r\n else:\r\n print(x // 100)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Tavas is a cheerleader in the new sports competition named \"Pashmaks\".\n\nThis competition consists of two part: swimming and then running. People will immediately start running *R* meters after they finished swimming exactly *S* meters. A winner is a such person that nobody else finishes running before him/her (there may be more than one winner).\n\nBefore the match starts, Tavas knows that there are *n* competitors registered for the match. Also, he knows that *i*-th person's swimming speed is *s**i* meters per second and his/her running speed is *r**i* meters per second. Unfortunately, he doesn't know the values of *R* and *S*, but he knows that they are real numbers greater than 0.\n\nAs a cheerleader, Tavas wants to know who to cheer up. So, he wants to know all people that might win. We consider a competitor might win if and only if there are some values of *R* and *S* such that with these values, (s)he will be a winner.\n\nTavas isn't really familiar with programming, so he asked you to help him.",
"input": "",
"output": "```python\nprint(\"_RANDOM_GUESS_1689183198.028277\")# 1689183198.0283232\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Zxr960115 is owner of a large farm. He feeds *m* cute cats and employs *p* feeders. There's a straight road across the farm and *n* hills along the road, numbered from 1 to *n* from left to right. The distance between hill *i* and (*i*<=-<=1) is *d**i* meters. The feeders live in hill 1.\n\nOne day, the cats went out to play. Cat *i* went on a trip to hill *h**i*, finished its trip at time *t**i*, and then waited at hill *h**i* for a feeder. The feeders must take all the cats. Each feeder goes straightly from hill 1 to *n* without waiting at a hill and takes all the waiting cats at each hill away. Feeders walk at a speed of 1 meter per unit time and are strong enough to take as many cats as they want.\n\nFor example, suppose we have two hills (*d*2<==<=1) and one cat that finished its trip at time 3 at hill 2 (*h*1<==<=2). Then if the feeder leaves hill 1 at time 2 or at time 3, he can take this cat, but if he leaves hill 1 at time 1 he can't take it. If the feeder leaves hill 1 at time 2, the cat waits him for 0 time units, if the feeder leaves hill 1 at time 3, the cat waits him for 1 time units.\n\nYour task is to schedule the time leaving from hill 1 for each feeder so that the sum of the waiting time of all cats is minimized.",
"input": "",
"output": "```python\nprint(\"_RANDOM_GUESS_1693418570.8905473\")# 1693418570.8905644\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.",
"input": "",
"output": "```python\nn=input()\r\nupp=0\r\n\r\nfor i in n:\r\n if i.isupper():\r\n upp+=1\r\nif upp>len(n)/2:\r\n n=n.upper()\r\nelse:\r\n n=n.lower()\r\nprint(n)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings *a* and *b* of equal length are called equivalent in one of the two cases: \n 1. They are equal. 1. If we split string *a* into two halves of the same size *a*1 and *a*2, and string *b* into two halves of the same size *b*1 and *b*2, then one of the following is correct: *a*1 is equivalent to *b*1, and *a*2 is equivalent to *b*2 1. *a*1 is equivalent to *b*2, and *a*2 is equivalent to *b*1 \nAs a home task, the teacher gave two strings to his students and asked to determine if they are equivalent.\n\nGerald has already completed this home task. Now it's your turn!",
"input": "",
"output": "```python\ntry:\r\n import sys\r\n from functools import lru_cache, cmp_to_key\r\n from heapq import merge, heapify, heappop, heappush\r\n # from math import *\r\n from collections import defaultdict as dd, deque, Counter as C\r\n from itertools import combinations as comb, permutations as perm\r\n from bisect import bisect_left as bl, bisect_right as br, bisect, insort\r\n from time import perf_counter\r\n from fractions import Fraction\r\n import copy\r\n from copy import deepcopy\r\n import time\r\n starttime = time.time()\r\n mod = int(pow(10, 9) + 7)\r\n mod2 = 998244353\r\n\r\n def data(): return sys.stdin.readline().strip()\r\n def out(*var, end=\"\\n\"): sys.stdout.write(' '.join(map(str, var))+end)\r\n def L(): return list(sp())\r\n def sl(): return list(ssp())\r\n def sp(): return map(int, data().split())\r\n def ssp(): return map(str, data().split())\r\n def l1d(n, val=0): return [val for i in range(n)]\r\n def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)]\r\n def A2(n,m): return [[0]*m for i in range(n)]\r\n def A(n):return [0]*n\r\n # sys.setrecursionlimit(int(pow(10,6)))\r\n # from sys import stdin\r\n # input = stdin.buffer.readline\r\n # I = lambda : list(map(int,input().split()))\r\n # import sys\r\n # input=sys.stdin.readline\r\n import math\r\n import string\r\n\r\n sys.stdin = open(\"input.txt\", \"r\")\r\n sys.stdout = open(\"output.txt\", \"w\")\r\nexcept:\r\n pass\r\n\r\ndef compute_hash( s ):\r\n\r\n \"\"\"\r\n This will work work string consisting of only lower characters\r\n If you want to do it for \r\n - only upper characters: change ord(\"a\") to ord(\"A\")\r\n - both lower and upper: change p to 53\r\n \"\"\"\r\n\r\n p = 31\r\n mod = 10**9 + 7\r\n hash_value = 0\r\n p_pow = 1\r\n H = [0]\r\n for c in s:\r\n hash_value = ( hash_value + ( ord(c) - ord(\"a\") + 1) * p_pow ) % mod\r\n p_pow = ( p_pow * p ) % mod\r\n H.append(hash_value)\r\n\r\n return H\r\na = input()\r\nb = input()\r\n\r\n\r\nHa = compute_hash(a)\r\nHb = compute_hash(b)\r\n\r\nn = len(a)\r\ndef rec(al,ar,bl,br):\r\n\r\n if ar-al!=br-bl:\r\n return False\r\n\r\n hash_a = ((Ha[ar] - Ha[al-1])*pow(pow(31,al-1,mod),mod-2,mod))%mod\r\n hash_b = ((Hb[br] - Hb[bl-1])*pow(pow(31,bl-1,mod),mod-2,mod))%mod\r\n\r\n if hash_a == hash_b:\r\n return True\r\n if (ar-al+1)%2:\r\n return False\r\n mid = (ar-al+1)//2\r\n \r\n ans = ( rec(al,al+mid-1,bl,bl+mid-1) & rec(al+mid,ar,bl+mid,br) ) | ( rec(al,al+mid-1,bl+mid,br) & rec(al+mid,ar,bl,bl+mid-1) )\r\n # print(al, ar, bl, br, ans, hash_a, hash_b)\r\n return ans\r\n\r\nif rec(1,n,1,n):\r\n print(\"YES\")\r\nelse:\r\n print(\"NO\")\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Sonya decided to organize an exhibition of flowers. Since the girl likes only roses and lilies, she decided that only these two kinds of flowers should be in this exhibition.\n\nThere are $n$ flowers in a row in the exhibition. Sonya can put either a rose or a lily in the $i$-th position. Thus each of $n$ positions should contain exactly one flower: a rose or a lily.\n\nShe knows that exactly $m$ people will visit this exhibition. The $i$-th visitor will visit all flowers from $l_i$ to $r_i$ inclusive. The girl knows that each segment has its own beauty that is equal to the product of the number of roses and the number of lilies.\n\nSonya wants her exhibition to be liked by a lot of people. That is why she wants to put the flowers in such way that the sum of beauties of all segments would be maximum possible.",
"input": "",
"output": "```python\ntd=list(map(int,input().split()))\r\nt=td[0]\r\nd=td[1]\r\nl=[]\r\nfor i in range(1,t+1):\r\n if(i%2==0):\r\n l.append(\"1\")\r\n else:\r\n l.append(\"0\")\r\nfor i in l:\r\n print(i,end='')\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "After the lessons *n* groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the *i*-th group consists of *s**i* friends (1<=≤<=*s**i*<=≤<=4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)?",
"input": "",
"output": "```python\ndef min_number_of_taxis(n, groups):\r\n count = [0] * 5\r\n for group in groups:\r\n count[group] += 1\r\n\r\n taxis = count[4]\r\n taxis += count[3]\r\n count[1] = max(0, count[1] - count[3])\r\n taxis += count[2] // 2\r\n count[2] %= 2\r\n\r\n if count[2] == 1:\r\n taxis += 1\r\n count[1] = max(0, count[1] - 2)\r\n\r\n taxis += (count[1] + 3) // 4\r\n\r\n return taxis\r\n\r\nn = int(input())\r\ngroups = list(map(int, input().split()))\r\nresult = min_number_of_taxis(n, groups)\r\nprint(result)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Eleven wants to choose a new name for herself. As a bunch of geeks, her friends suggested an algorithm to choose a name for her. Eleven wants her name to have exactly *n* characters. \n\nHer friend suggested that her name should only consist of uppercase and lowercase letters 'O'. More precisely, they suggested that the *i*-th letter of her name should be 'O' (uppercase) if *i* is a member of Fibonacci sequence, and 'o' (lowercase) otherwise. The letters in the name are numbered from 1 to *n*. Fibonacci sequence is the sequence *f* where\n - *f*1<==<=1, - *f*2<==<=1, - *f**n*<==<=*f**n*<=-<=2<=+<=*f**n*<=-<=1 (*n*<=><=2). \nAs her friends are too young to know what Fibonacci sequence is, they asked you to help Eleven determine her new name.",
"input": "",
"output": "```python\ndef fib(limit):\r\n a=[1,2]\r\n while a[-1]<=limit:\r\n a.append(a[-1]+a[-2])\r\n return a\r\n\r\nn=int(input())\r\nlst=fib(n)\r\ns=\"\"\r\npos=0\r\nfor i in range(1,n+1):\r\n if lst[pos]==i:\r\n pos+=1\r\n s+=\"O\"\r\n else:\r\n s+=\"o\"\r\nprint(s)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Consider the function *p*(*x*), where *x* is an array of *m* integers, which returns an array *y* consisting of *m*<=+<=1 integers such that *y**i* is equal to the sum of first *i* elements of array *x* (0<=≤<=*i*<=≤<=*m*).\n\nYou have an infinite sequence of arrays *A*0,<=*A*1,<=*A*2..., where *A*0 is given in the input, and for each *i*<=≥<=1 *A**i*<==<=*p*(*A**i*<=-<=1). Also you have a positive integer *k*. You have to find minimum possible *i* such that *A**i* contains a number which is larger or equal than *k*.",
"input": "",
"output": "```python\nn, k = [int(x) for x in input().split()]\r\na = [int(x) for x in input().split()]\r\ncnt, ind, mx = 0, [], 0\r\nfor i in range(n):\r\n if a[i] > 0:\r\n cnt += 1\r\n ind.append(i)\r\n mx = max(mx, a[i])\r\ndef p(a):\r\n pref = [0]\r\n for i in range(len(a)):\r\n pref.append(pref[-1] + a[i])\r\n return pref\r\nif cnt > 7 or mx >= k:\r\n it = 0\r\n while True:\r\n mx = 0\r\n for i in range(len(a)):\r\n mx = max(mx, a[i])\r\n if mx >= k:\r\n print(it)\r\n exit()\r\n a = p(a)\r\n it += 1\r\nl, r = 0, k\r\nwhile r - l > 1:\r\n m = (l + r) >> 1\r\n sum = 0\r\n f = False\r\n for i in ind:\r\n c, j = a[i], n - 1 - i\r\n if j > m:\r\n continue\r\n while j > 0:\r\n c *= m + j - 1\r\n j -= 1\r\n j = i\r\n while j > 0:\r\n c //= j\r\n j -= 1\r\n sum += c\r\n if sum >= k:\r\n f = True\r\n break\r\n if f:\r\n r = m\r\n else:\r\n l = m\r\nprint(r)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be *n* problems, sorted by difficulty, i.e. problem 1 is the easiest and problem *n* is the hardest. Limak knows it will take him 5·*i* minutes to solve the *i*-th problem.\n\nLimak's friends organize a New Year's Eve party and Limak wants to be there at midnight or earlier. He needs *k* minutes to get there from his house, where he will participate in the contest first.\n\nHow many problems can Limak solve if he wants to make it to the party?",
"input": "",
"output": "```python\nn, m = list(map(int, input().split()))\r\n\r\ntotal_time_dk = 4 * 60\r\n\r\nmin_time_dk = total_time_dk - m\r\n\r\ntotal = 0\r\ny = 0\r\n\r\nfor i in range(1, n+1):\r\n answer_time = 5\r\n x = answer_time * i\r\n y += x\r\n if min_time_dk - y >= 0:\r\n total += 1\r\n\r\nprint(total)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Summer holidays! Someone is going on trips, someone is visiting grandparents, but someone is trying to get a part-time job. This summer Noora decided that she wants to earn some money, and took a job in a shop as an assistant.\n\nShop, where Noora is working, has a plan on the following *n* days. For each day sales manager knows exactly, that in *i*-th day *k**i* products will be put up for sale and exactly *l**i* clients will come to the shop that day. Also, the manager is sure, that everyone, who comes to the shop, buys exactly one product or, if there aren't any left, leaves the shop without buying anything. Moreover, due to the short shelf-life of the products, manager established the following rule: if some part of the products left on the shelves at the end of the day, that products aren't kept on the next day and are sent to the dump.\n\nFor advertising purposes manager offered to start a sell-out in the shop. He asked Noora to choose any *f* days from *n* next for sell-outs. On each of *f* chosen days the number of products were put up for sale would be doubled. Thus, if on *i*-th day shop planned to put up for sale *k**i* products and Noora has chosen this day for sell-out, shelves of the shop would keep 2·*k**i* products. Consequently, there is an opportunity to sell two times more products on days of sell-out.\n\nNoora's task is to choose *f* days to maximize total number of sold products. She asks you to help her with such a difficult problem.",
"input": "",
"output": "```python\nplanDays,chosenDays=map(int,input().split())\r\ntotal=[0 for _ in range(planDays)]\r\nfor i in range(planDays):\r\n products,clients=map(int,input().split())\r\n if (i+1)% chosenDays ==0:\r\n products=2*products\r\n if products >= clients:\r\n total[i]= clients\r\n elif products < clients and products !=0 :\r\n total[i]=clients\r\nprint(sum(total))\r\n \r\n \r\n \r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Amr is a young coder who likes music a lot. He always wanted to learn how to play music but he was busy coding so he got an idea.\n\nAmr has *n* instruments, it takes *a**i* days to learn *i*-th instrument. Being busy, Amr dedicated *k* days to learn how to play the maximum possible number of instruments.\n\nAmr asked for your help to distribute his free days between instruments so that he can achieve his goal.",
"input": "",
"output": "```python\nn, k = map(int,input().split()) \r\nsum=0 \r\nl2=[]\r\nl=sorted([(x,i) for i,x in enumerate(map(int,input().split()),1)])\r\n \r\nfor i,j in l:\r\n sum=sum+i \r\n if(sum<=k): \r\n l2.append(j) \r\nprint(len(l2)) \r\nfor h in l2:\r\n print(h, end=' ') \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "The new operating system BerOS has a nice feature. It is possible to use any number of characters '/' as a delimiter in path instead of one traditional '/'. For example, strings //usr///local//nginx/sbin// and /usr/local/nginx///sbin are equivalent. The character '/' (or some sequence of such characters) at the end of the path is required only in case of the path to the root directory, which can be represented as single character '/'.\n\nA path called normalized if it contains the smallest possible number of characters '/'.\n\nYour task is to transform a given path to the normalized form.",
"input": "",
"output": "```python\ns=input()\r\nx=[s[0]]\r\nfor i in range(1,len(s)-1):\r\n if s[i]!='/':\r\n x.append(s[i])\r\n elif s[i]=='/' and s[i+1]!='/':\r\n x.append('/')\r\nfor k in range(len(x)):\r\n print(x[k],end='')\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nMetropolis 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.\n\nAll *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.\n\nHelen 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.",
"input": "",
"output": "```python\nimport itertools\r\nk, n = map(int, input().split())\r\ndata = list(map(int, input().split()))\r\nmin_v = []\r\nmin_value = 99999\r\nv = []\r\nfor i in range(k):\r\n v.append(i + n + 1)\r\nvariants = list(itertools.permutations(v, k))\r\nfor variant in variants:\r\n summ = 0\r\n for i in range(len(variant)):\r\n summ += (variant[i] - i - 1) * data[i]\r\n if variant[i] - i - 1 < 0:\r\n summ = 9999999\r\n break\r\n if summ <= min_value:\r\n min_value = summ\r\n min_v = variant\r\nprint(min_value)\r\nprint(min_v)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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:\n\n1. Each domino completely covers two squares.\n\n2. No two dominoes overlap.\n\n3. Each domino lies entirely inside the board. It is allowed to touch the edges of the board.\n\nFind the maximum number of dominoes, which can be placed under these restrictions.",
"input": "",
"output": "```python\nn=int(input())\r\nm=int(input())\r\nparameter=m*n\r\nMaximum_number_of_dominoes=parameter//2\r\nprint(Maximum_number_of_dominoes)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "One day Polycarp published a funny picture in a social network making a poll about the color of his handle. Many of his friends started reposting Polycarp's joke to their news feed. Some of them reposted the reposts and so on.\n\nThese events are given as a sequence of strings \"name1 reposted name2\", where name1 is the name of the person who reposted the joke, and name2 is the name of the person from whose news feed the joke was reposted. It is guaranteed that for each string \"name1 reposted name2\" user \"name1\" didn't have the joke in his feed yet, and \"name2\" already had it in his feed by the moment of repost. Polycarp was registered as \"Polycarp\" and initially the joke was only in his feed.\n\nPolycarp measures the popularity of the joke as the length of the largest repost chain. Print the popularity of Polycarp's joke.",
"input": "",
"output": "```python\nfrom collections import defaultdict\r\n\r\npost = defaultdict(list)\r\nn = int(input())\r\n\r\nfor _ in range(n):\r\n c, b, a = input().split()\r\n post[a.lower()].append(c.lower())\r\n\r\nposters = set([\"polycarp\"])\r\n\r\ndef dfs(person, count):\r\n c = count \r\n for friend in post[person]:\r\n if friend in posters:\r\n continue\r\n posters.add(friend)\r\n c = max(c, dfs(friend, count + 1))\r\n # print(person, c)\r\n return c\r\n\r\nprint(dfs(\"polycarp\", 1))\r\n\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "During the winter holidays, the demand for Christmas balls is exceptionally high. Since it's already 2018, the advances in alchemy allow easy and efficient ball creation by utilizing magic crystals.\n\nGrisha needs to obtain some yellow, green and blue balls. It's known that to produce a yellow ball one needs two yellow crystals, green — one yellow and one blue, and for a blue ball, three blue crystals are enough.\n\nRight now there are *A* yellow and *B* blue crystals in Grisha's disposal. Find out how many additional crystals he should acquire in order to produce the required number of balls.",
"input": "",
"output": "```python\nsh = [int(w) for w in input().split()]\r\ne = [int(q) for q in input().split()]\r\na = sh[0]\r\nb = sh[1]\r\nx = e[0]\r\ny = e[1]\r\nz = e[2]\r\nn = a+b\r\nka = 2*x+1*y\r\nkb = 1*y+3*z\r\nd = (ka+kb)-n\r\nprint(d)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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). \n\nYour task is to determine by the given *a*, *b* and *n* who wins the game.",
"input": "",
"output": "```python\nx=list(map(int,input().split()))\r\na=x[0]\r\nb=x[1]\r\nn=x[2]\r\nif(n%2==0):\r\n print(\"1\")\r\nelse:\r\n print(\"0\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "After seeing the \"ALL YOUR BASE ARE BELONG TO US\" meme for the first time, numbers *X* and *Y* realised that they have different bases, which complicated their relations.\n\nYou're given a number *X* represented in base *b**x* and a number *Y* represented in base *b**y*. Compare those two numbers.",
"input": "",
"output": "```python\nn1 = 0\r\nn, b = map(int, input().split())\r\na = list(map(int, input().split()))\r\na.reverse()\r\nfor i in range(n):\r\n n1 += a[i] * (b ** i)\r\nn2 = 0\r\nn, b = map(int, input().split())\r\na = list(map(int, input().split()))\r\na.reverse()\r\nfor i in range(n):\r\n n2 += a[i] * (b ** i)\r\nif n1 < n2:\r\n print(\"<\")\r\nif n1 == n2:\r\n print(\"=\")\r\nif n1 > n2:\r\n print(\">\")\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.",
"input": "",
"output": "```python\ndef sol():\r\n s=input()\r\n u=0\r\n l=0\r\n for i in s:\r\n if ord(i)<93:\r\n u=u+1\r\n else:\r\n l=l+1\r\n if l>=u:\r\n print(s.lower())\r\n else:\r\n print(s.upper())\r\n\r\n\r\n\r\nsol()\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Maria participates in a bicycle race.\n\nThe speedway takes place on the shores of Lake Lucerne, just repeating its contour. As you know, the lake shore consists only of straight sections, directed to the north, south, east or west.\n\nLet's introduce a system of coordinates, directing the *Ox* axis from west to east, and the *Oy* axis from south to north. As a starting position of the race the southernmost point of the track is selected (and if there are several such points, the most western among them). The participants start the race, moving to the north. At all straight sections of the track, the participants travel in one of the four directions (north, south, east or west) and change the direction of movement only in bends between the straight sections. The participants, of course, never turn back, that is, they do not change the direction of movement from north to south or from east to west (or vice versa).\n\nMaria is still young, so she does not feel confident at some turns. Namely, Maria feels insecure if at a failed or untimely turn, she gets into the water. In other words, Maria considers the turn dangerous if she immediately gets into the water if it is ignored.\n\nHelp Maria get ready for the competition — determine the number of dangerous turns on the track.",
"input": "",
"output": "```python\nn = int(intput())\r\n\r\nfor i in range(n+1):\r\n m = input()\r\n\r\nprint((n-4)/2)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Gargari is jealous that his friend Caisa won the game from the previous problem. He wants to prove that he is a genius.\n\nHe has a *n*<=×<=*n* chessboard. Each cell of the chessboard has a number written on it. Gargari wants to place two bishops on the chessboard in such a way that there is no cell that is attacked by both of them. Consider a cell with number *x* written on it, if this cell is attacked by one of the bishops Gargari will get *x* dollars for it. Tell Gargari, how to place bishops on the chessboard to get maximum amount of money.\n\nWe assume a cell is attacked by a bishop, if the cell is located on the same diagonal with the bishop (the cell, where the bishop is, also considered attacked by it).",
"input": "",
"output": "```python\nimport itertools\n\nn = int(input())\narr = [list(map(int, input().split())) for i in range(n)]\nr_diag = {}\nfor i in range(-n+1, n):\n diag_total = 0\n # for j in range(0, n):\n # x, y = i+j, j\n # if 0 <= x < n and 0 <= y < n:\n # diag_total += arr[x][y]\n r_diag[i%(2*n-1)] = sum([arr[i+j][j] for j in range(0, n) if 0<=(i+j)= best_val:\n# best_val = val\n# best_pos = x, y\n# best_val_black = best_val\n# best_pos_black = best_pos\n\nbest_val_black, black_x, black_y = max([\n (l_diag[(x+y) % (2*n-1)] + r_diag[(x-y) % (2*n-1)] - arr[x][y], x, y)\n for x, y in itertools.product(range(0, n), range(0, n))\n if (x+y) % 2 == 0\n])\n\nbest_val_white, white_x, white_y = max([\n (l_diag[(x+y) % (2*n-1)] + r_diag[(x-y) % (2*n-1)] - arr[x][y], x, y)\n for x, y in itertools.product(range(0, n), range(0, n))\n if (x+y) % 2 == 1\n])\n\n\n# best_val = None\n# best_pos = None, None\n# for x in range(0, n):\n# for y in range(0, n):\n# if not ((x+y) % 2):\n# continue\n# r = (x-y) % (2*n-1)\n# l = (x+y) % (2*n-1)\n# val = l_diag[l] + r_diag[r] - arr[x][y]\n# if best_val is None or val >= best_val:\n# best_val = val\n# best_pos = x, y\n\nprint(best_val_black + best_val_white)\nprint(*[i+1 for i in [black_x, black_y, white_x, white_y]])\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "People in the Tomskaya region like magic formulas very much. You can see some of them below.\n\nImagine you are given a sequence of positive integer numbers *p*1, *p*2, ..., *p**n*. Lets write down some magic formulas:\n\nHere, \"mod\" means the operation of taking the residue after dividing.\n\nThe expression means applying the bitwise *xor* (excluding \"OR\") operation to integers *x* and *y*. The given operation exists in all modern programming languages. For example, in languages C++ and Java it is represented by \"^\", in Pascal — by \"xor\".\n\nPeople in the Tomskaya region like magic formulas very much, but they don't like to calculate them! Therefore you are given the sequence *p*, calculate the value of *Q*.",
"input": "",
"output": "```python\ndef main():\n n = int(input())\n nums = map(int, input().split())\n\n chunk = []\n base = 0\n for i in range(n + 1):\n base ^= i\n chunk.append(base)\n\n Q = 0\n for i, num in enumerate(nums):\n q = num\n chunks, res = divmod(n, i + 1)\n q ^= chunk[res]\n if chunks % 2 == 1:\n q ^= chunk[i]\n Q ^= q\n\n print(Q)\n\n\nmain()\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A wise man told Kerem \"Different is good\" once, so Kerem wants all things in his life to be different. \n\nKerem recently got a string *s* consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string *s* to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string \"aba\" has substrings \"\" (empty substring), \"a\", \"b\", \"a\", \"ab\", \"ba\", \"aba\".\n\nIf string *s* has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.\n\nYour task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.",
"input": "",
"output": "```python\nn = int(input())\r\nstring = input()\r\nalphabets = \"abcdefghijklmnopqrstuvwxyz\"\r\ncount = 0\r\nflag = 1\r\nfor i in alphabets:\r\n if i not in string:\r\n count += 1\r\n\r\nlength = len(set(string))\r\nif length > count or n > 26:\r\n flag = 0\r\nif(flag == 1):\r\n print(n - len(string))\r\nelse:\r\n print(\"-1\")\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nOne 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.\n\nFind the volume fraction of orange juice in the final drink.",
"input": "",
"output": "```python\ndef code(*args):\r\n arr, n = args\r\n\r\n result = float(sum(arr)/n) \r\n\r\n return \"{:.12f}\".format(result) \r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n # Take inputs here\r\n n = int(input())\r\n arr = list(map(int, input().split()))\r\n result = code(arr, n) # Pass arguments\r\n print(result)\r\n\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nPete 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.",
"input": "",
"output": "```python\nn,w=list(map(int,input().split()))\nwhile(n%2==0 and w%2==0):\n if((n+w)%2==0)\n print(\"YES\")\n else:\n print(\"NO\")\nprint(\"NO\")\n#5l7\n \t\t\t \t\t\t \t\t\t \t\t\t\t\t \t \t \t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Holidays have finished. Thanks to the help of the hacker Leha, Noora managed to enter the university of her dreams which is located in a town Pavlopolis. It's well known that universities provide students with dormitory for the period of university studies. Consequently Noora had to leave Vičkopolis and move to Pavlopolis. Thus Leha was left completely alone in a quiet town Vičkopolis. He almost even fell into a depression from boredom!\n\nLeha came up with a task for himself to relax a little. He chooses two integers *A* and *B* and then calculates the greatest common divisor of integers \"*A* factorial\" and \"*B* factorial\". Formally the hacker wants to find out GCD(*A*!,<=*B*!). It's well known that the factorial of an integer *x* is a product of all positive integers less than or equal to *x*. Thus *x*!<==<=1·2·3·...·(*x*<=-<=1)·*x*. For example 4!<==<=1·2·3·4<==<=24. Recall that GCD(*x*,<=*y*) is the largest positive integer *q* that divides (without a remainder) both *x* and *y*.\n\nLeha has learned how to solve this task very effective. You are able to cope with it not worse, aren't you?",
"input": "",
"output": "```python\n\r\na, b = map(int, input().split())\r\nans = 0\r\nmn = min(a, b)\r\nfor i in range(1, mn + 1):\r\n ans += i\r\nprint(ans)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Reca company makes monitors, the most popular of their models is AB999 with the screen size *a*<=×<=*b* centimeters. Because of some production peculiarities a screen parameters are integer numbers. Recently the screen sides ratio *x*:<=*y* became popular with users. That's why the company wants to reduce monitor AB999 size so that its screen sides ratio becomes *x*:<=*y*, at the same time they want its total area to be maximal of all possible variants. Your task is to find the screen parameters of the reduced size model, or find out that such a reduction can't be performed.",
"input": "",
"output": "```python\nimport sys\r\nfrom collections import defaultdict as dd\r\nfrom collections import deque\r\n\r\ndef eprint(*args):\r\n print(*args, file=sys.stderr)\r\npl=1\r\nfrom math import *\r\nimport copy\r\n#sys.setrecursionlimit(10**6)\r\nif pl:\r\n\tinput=sys.stdin.readline\r\n\r\ndef li():\r\n\treturn [int(xxx) for xxx in input().split()]\r\ndef fi():\r\n\treturn int(input())\r\ndef si():\r\n\treturn list(input().rstrip())\t\r\ndef mi():\r\n\treturn \tmap(int,input().split())\t\r\n \r\n\r\nd=[]\t\t\r\nfrom bisect import *\t\t\r\n\r\nfrom itertools import permutations \r\nfrom bisect import *\r\nf=[0 for i in range(100)]\r\n\r\nfor i in range(1,100):\r\n\tif i==1:\r\n\t\tf[i]=1\r\n\telse:\r\n\t\tf[i]=2*f[i-1]+1\r\n\r\n#print(f[:15])\r\ndef rec(n,k):\r\n\ts=[]\r\n\twhile n!=0:\r\n\t\tn,r=n//k,n%k\r\n\t\t#print(n,r)\r\n\t\tif r<0:\r\n\t\t\tr-=k\r\n\t\t\tn+=1\r\n\t\t#print(s,n,r)\t\r\n\t\ts.append(r)\t\t\r\n\treturn s\t\t\r\na,b,x,y=mi()\r\na,b=max(a,b),min(a,b)\r\nx,y=max(x,y),min(x,y)\r\nl=1\r\nr=10**10\r\nans=0\r\naa=[0,0]\r\nwhile l<=r:\r\n\tmid=(l+r)//2\r\n\tif x*mid<=a and y*mid<=b:\r\n\t\tans=max(ans,x*y*mid**2)\r\n\t\taa=[x*mid,y*mid]\r\n\t\tl=mid+1\r\n\telse:\r\n\t\tr=mid-1\r\nprint(*aa)\t\t\r\n\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "\"Night gathers, and now my watch begins. It shall not end until my death. I shall take no wife, hold no lands, father no children. I shall wear no crowns and win no glory. I shall live and die at my post. I am the sword in the darkness. I am the watcher on the walls. I am the shield that guards the realms of men. I pledge my life and honor to the Night's Watch, for this night and all the nights to come.\" — The Night's Watch oath.\n\nWith that begins the watch of Jon Snow. He is assigned the task to support the stewards.\n\nThis time he has *n* stewards with him whom he has to provide support. Each steward has his own strength. Jon Snow likes to support a steward only if there exists at least one steward who has strength strictly less than him and at least one steward who has strength strictly greater than him.\n\nCan you find how many stewards will Jon support?",
"input": "",
"output": "```python\nn = int(input()) \r\nx = list(map(int,input().split())) \r\nn = int(input()) \r\nx = list(map(int,input().split())) \r\nx = [*set(x)] \r\nc = 0 \r\nfor i in x: \r\n if i > min(x) and i v<'\r\nch2int = {}\r\nfor i, c in enumerate(s):\r\n ch2int[c] = i\r\na, b, n = sys.stdin.read().split()\r\na = ch2int[a]; b = ch2int[b]; n = int(n)\r\niscw = s[a] == s[(b+n)%n]\r\nisccw = s[a] == s[(b-n)%n]\r\nif iscw and not isccw:\r\n print('cw')\r\nelif not iscw and isccw:\r\n print('ccw')\r\nelse:\r\n print('undefined')\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Let's denote a function \n\n\n\nYou are given an array *a* consisting of *n* integers. You have to calculate the sum of *d*(*a**i*,<=*a**j*) over all pairs (*i*,<=*j*) such that 1<=≤<=*i*<=≤<=*j*<=≤<=*n*.",
"input": "",
"output": "```python\ndef set(x) : \n\tif(x not in m) : \n\t\tm[x] = 0\n\nn = int(input())\na = list(map(int, input().split()))\nm = {}\nans, total = 0, 0\n\nfor i in range(0, n) : \n\tx = a[i]; \n\tset(x), set(x - 1), set(x + 1)\n\tans = ans + (i - m[x] - m[x - 1] - m[x + 1]) * x; \n\tans = ans -(total - m[x] * x - m[x - 1] * (x - 1) - m[x + 1] * (x + 1)); \n\n\tm[x], total = m[x] + 1, total + x\n\nprint(ans) \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.",
"input": "",
"output": "```python\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Apr 29 22:39:01 2021\r\n\r\n@author: Corey.Smith\r\n\"\"\"\r\n\r\n\r\ns = input()\r\ni=0\r\n\r\nfor l in s: \r\n i = [i,i+1][l.upper()==l]\r\n \r\nprint([s.lower(),s.upper()][i>len(s)/2])\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Mike is trying rock climbing but he is awful at it. \n\nThere are *n* holds on the wall, *i*-th hold is at height *a**i* off the ground. Besides, let the sequence *a**i* increase, that is, *a**i*<=<<=*a**i*<=+<=1 for all *i* from 1 to *n*<=-<=1; we will call such sequence a track. Mike thinks that the track *a*1, ..., *a**n* has difficulty . In other words, difficulty equals the maximum distance between two holds that are adjacent in height.\n\nToday Mike decided to cover the track with holds hanging on heights *a*1, ..., *a**n*. To make the problem harder, Mike decided to remove one hold, that is, remove one element of the sequence (for example, if we take the sequence (1,<=2,<=3,<=4,<=5) and remove the third element from it, we obtain the sequence (1,<=2,<=4,<=5)). However, as Mike is awful at climbing, he wants the final difficulty (i.e. the maximum difference of heights between adjacent holds after removing the hold) to be as small as possible among all possible options of removing a hold. The first and last holds must stay at their positions.\n\nHelp Mike determine the minimum difficulty of the track after removing one hold.",
"input": "",
"output": "```python\nn = int(input())\na = [int(x) for x in input().split()]\nval = []\nmv = 0\nfor i in range(1,n):\n mv = max(mv,a[i]-a[i-1])\n \nz = 1000\nfor i in range(1,n-1):\n z = min(z, a[i+1]-a[i-1])\n\nif z <= mv:\n print(mv)\nelse:\n print(z)\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "In Aramic language words can only represent objects.\n\nWords in Aramic have special properties: \n - A word is a root if it does not contain the same letter more than once. - A root and all its permutations represent the same object. - The root $x$ of a word $y$ is the word that contains all letters that appear in $y$ in a way that each letter appears once. For example, the root of \"aaaa\", \"aa\", \"aaa\" is \"a\", the root of \"aabb\", \"bab\", \"baabb\", \"ab\" is \"ab\". - Any word in Aramic represents the same object as its root. \nYou have an ancient script in Aramic. What is the number of different objects mentioned in the script?",
"input": "",
"output": "```python\nn = int(input())\r\na = []\r\ns = input().split()\r\nans = 0\r\nfor i in range(n):\r\n if set(s[i]) not in a:\r\n a.append(set(s[i]))\r\n ans += 1\r\nprint(ans)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "There are *n* cities and *n*<=-<=1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads.\n\nTheon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. \n\nLet the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link [https://en.wikipedia.org/wiki/Expected_value](https://en.wikipedia.org/wiki/Expected_value).",
"input": "",
"output": "```python\nfrom collections import defaultdict\r\n\r\ndef solve():\r\n n = int(input())\r\n graph = defaultdict(list)\r\n for _ in range(n-1):\r\n \tx,y = map(int, input().split())\r\n \tgraph[x].append(y)\r\n \tgraph[y].append(x)\r\n \r\n dep = defaultdict(int)\r\n \r\n dep[0]=-1\r\n \r\n sum=0\r\n total=0\r\n \r\n def dfs(curr, par):\r\n nonlocal sum\r\n nonlocal total\r\n dep[curr]=dep[par]+1\r\n for nxt in graph[curr]:\r\n \t if nxt!=par: dfs(nxt, curr)\r\n \t\r\n if len(graph[curr])==1 :\r\n \t sum+=dep[curr]\r\n \t total+=1\r\n \r\n dfs(1, 0)\r\n print(sum/total)\r\n\r\nsolve()\r\n\t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Pasha loves his phone and also putting his hair up... But the hair is now irrelevant.\n\nPasha has installed a new game to his phone. The goal of the game is following. There is a rectangular field consisting of *n* row with *m* pixels in each row. Initially, all the pixels are colored white. In one move, Pasha can choose any pixel and color it black. In particular, he can choose the pixel that is already black, then after the boy's move the pixel does not change, that is, it remains black. Pasha loses the game when a 2<=×<=2 square consisting of black pixels is formed. \n\nPasha has made a plan of *k* moves, according to which he will paint pixels. Each turn in his plan is represented as a pair of numbers *i* and *j*, denoting respectively the row and the column of the pixel to be colored on the current move.\n\nDetermine whether Pasha loses if he acts in accordance with his plan, and if he does, on what move the 2<=×<=2 square consisting of black pixels is formed.",
"input": "",
"output": "```python\nn,m,k=map(int,input().split())\r\nl = [[0 for _ in range(n+2)] for _ in range(m+2)]#baohuquan\r\ntemp=1\r\nif k<=3:\r\n print(0)\r\nelse:\r\n for c in range(1,k+1):\r\n j,i=map(int,input().split())\r\n l[i][j]=1\r\n if l[i][j+1]+l[i+1][j]+l[i+1][j+1]==3 or l[i][j+1]+l[i-1][j]+l[i-1][j+1]==3 or l[i][j-1]+l[i+1][j]+l[i][j-1]==3 or l[i][j-1]+l[i-1][j]+l[i-1][j-1]==3:\r\n print(c)\r\n temp=0\r\n break\r\n if temp==1:\r\n print(0)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "The cows have just learned what a primitive root is! Given a prime *p*, a primitive root is an integer *x* (1<=≤<=*x*<=<<=*p*) such that none of integers *x*<=-<=1,<=*x*2<=-<=1,<=...,<=*x**p*<=-<=2<=-<=1 are divisible by *p*, but *x**p*<=-<=1<=-<=1 is. \n\nUnfortunately, computing primitive roots can be time consuming, so the cows need your help. Given a prime *p*, help the cows find the number of primitive roots .",
"input": "",
"output": "```python\ndef power(x, y, p):\r\n result = 1\r\n x = x % p\r\n while y > 0:\r\n if y % 2 == 1:\r\n result = (result * x) % p\r\n y = y // 2\r\n x = (x * x) % p\r\n return result\r\n\r\ndef phi(n):\r\n result = n\r\n p = 2\r\n while p * p <= n:\r\n if n % p == 0:\r\n while n % p == 0:\r\n n //= p\r\n result -= result // p\r\n p += 1\r\n if n > 1:\r\n result -= result // n\r\n return result\r\n\r\ndef count_primitive_roots(p):\r\n phi_p = phi(p)\r\n primitive_roots = 0\r\n for x in range(2, p):\r\n if power(x, phi_p, p) == 1:\r\n primitive_roots += 1\r\n return primitive_roots\r\n\r\np = int(input())\r\nresult = count_primitive_roots(p)\r\nprint(result)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nAt 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.\n\nDetermine 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.",
"input": "",
"output": "```python\nimport math\r\nfirst = input().split(\" \")\r\nhh = int(first[0])\r\nmm = int(first[1])\r\nt = hh * 60 + mm\r\ndisc = 20 * 60\r\n\r\nsecond = input().split(\" \")\r\nh = int(second[0])\r\nd = int(second[1])\r\nc = int(second[2])\r\nn = int(second[3])\r\n\r\nif(t > disc):\r\n print(0.8 * math.ceil(h/float(n)) * c)\r\nelse:\r\n wait = 0.8 * math.ceil((h + d * (disc-t))/float(n))\r\n imme = math.ceil(h/float(n))\r\n print(min(c * imme, c * wait))\r\n \r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?\n\nYou are given a set of digits, your task is to find the maximum integer that you can make from these digits. The made number must be divisible by 2, 3, 5 without a residue. It is permitted to use not all digits from the set, it is forbidden to use leading zeroes.\n\nEach digit is allowed to occur in the number the same number of times it occurs in the set.",
"input": "",
"output": "```python\nimport decimal\r\nfrom errno import ETIMEDOUT\r\nimport heapq as hq\r\nimport os\r\nimport sys\r\nfrom collections import Counter as ctr, deque as dq\r\netd=dq()\r\nfrom io import BytesIO, IOBase\r\n \r\n \r\nBUFSIZE = 8192\r\n \r\n \r\nclass FastIO(IOBase):\r\n newlines = 0\r\n \r\n def __init__(self, file):\r\n self._fd = file.fileno()\r\n self.buffer = BytesIO()\r\n self.writable = 'x' in file.mode or 'r' not in file.mode\r\n self.write = self.buffer.write if self.writable else None\r\n \r\n def read(self):\r\n while True:\r\n b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))\r\n if not b:\r\n break\r\n ptr = self.buffer.tell()\r\n self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)\r\n self.newlines = 0\r\n return self.buffer.read()\r\n \r\n def readline(self):\r\n while self.newlines == 0:\r\n b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))\r\n self.newlines = b.count(b'\\n') + (not b)\r\n ptr = self.buffer.tell()\r\n self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)\r\n self.newlines -= 1\r\n return self.buffer.readline()\r\n \r\n def flush(self):\r\n if self.writable:\r\n os.write(self._fd, self.buffer.getvalue())\r\n self.buffer.truncate(0), self.buffer.seek(0)\r\n \r\n \r\nclass IOWrapper(IOBase):\r\n def __init__(self, file):\r\n self.buffer = FastIO(file)\r\n self.flush = self.buffer.flush\r\n self.writable = self.buffer.writable\r\n self.write = lambda s: self.buffer.write(s.encode('ascii'))\r\n self.read = lambda: self.buffer.read().decode('ascii')\r\n self.readline = lambda: self.buffer.readline().decode('ascii')\r\n \r\n \r\nsys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)\r\ninput = lambda: sys.stdin.readline().rstrip('\\r\\n')\r\n \r\nfrom math import *\r\nfrom bisect import bisect_left as bl, insort\r\nfrom bisect import bisect_right as br\r\nfrom itertools import permutations\r\n\r\ninp = lambda: int(input())\r\nli = lambda: list(map(int, input().split()))\r\nlb = lambda: list(map(int, input()))\r\nls = lambda: list(input())\r\nbi = lambda n: bin(n).replace(\"0b\", \"0\"*(18-int(log(n,2))-1))\r\ndef yn(f):\r\n print('NYOE S'[f::2])\r\n\r\n\r\n\r\ndef main(__=1):\r\n for _ in range(__):\r\n n=inp()\r\n a=li()\r\n a.sort(reverse=True)\r\n if a[-1]!=0:\r\n print(-1)\r\n else:\r\n rmd1=[]\r\n rmd2=[]\r\n s=0\r\n for i in range(n):\r\n t=a[i]%3\r\n s=(s+t)%3\r\n if t==1:\r\n rmd1.append(i)\r\n elif t==2:\r\n rmd2.append(i)\r\n if s==0:\r\n print(\"\".join(map(str,a)))\r\n elif s==1:\r\n if len(rmd1)>0:\r\n a.pop(rmd1[-1])\r\n elif len(rmd2)>1:\r\n a.pop(rmd2[-1])\r\n a.pop(rmd2[-2])\r\n else:\r\n a=[0]\r\n print(\"\".join(map(str,a)))\r\n else:\r\n if len(rmd2)>0:\r\n a.pop(rmd2[-1])\r\n elif len(rmd1)>1:\r\n a.pop(rmd1[-1])\r\n a.pop(rmd1[-2])\r\n else:\r\n a=[0]\r\n print(\"\".join(map(str,a)))\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n #main(inp())\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "There are *n* pearls in a row. Let's enumerate them with integers from 1 to *n* from the left to the right. The pearl number *i* has the type *a**i*.\n\nLet's call a sequence of consecutive pearls a segment. Let's call a segment good if it contains two pearls of the same type.\n\nSplit the row of the pearls to the maximal number of good segments. Note that each pearl should appear in exactly one segment of the partition.\n\nAs 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.",
"input": "",
"output": "```python\n#!/usr/bin/python3\n\nn = int(input())\na = [int(x) for x in input().split()]\n\nr = []\ns = set()\nl = 0\nfor i, x in enumerate(a):\n if x in s:\n r.append([l + 1, i + 1])\n l = i + 1\n s = set()\n else:\n s.add(x)\nif l == 0:\n print(-1)\nelse:\n if s:\n r[-1][1] = n\n print(len(r))\n print('\\n'.join('{0} {1}'.format(p, q) for (p, q) in r))\n\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.\n\nGiven a sequence *a* consisting of *n* integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it *a**k*) and delete it, at that all elements equal to *a**k*<=+<=1 and *a**k*<=-<=1 also must be deleted from the sequence. That step brings *a**k* points to the player. \n\nAlex is a perfectionist, so he decided to get as many points as possible. Help him.",
"input": "",
"output": "```python\n# Read the number of elements in the sequence\r\nn = int(input())\r\n\r\n# Read the sequence of elements\r\nelements = list(map(int, input().split()))\r\n\r\n# Count the frequency of each element\r\nfrequency = {}\r\nfor num in elements:\r\n frequency[num] = frequency.get(num, 0) + 1\r\n\r\n# Initialize the dp array\r\ndp = [0] * n\r\n\r\n# Initialize dp[0] with the product of frequency and the value of the first element\r\ndp[0] = frequency.get(elements[0], 0) * elements[0]\r\n\r\n# Iterate through the sequence to calculate dp[i]\r\nfor i in range(1, n):\r\n dp[i] = max(dp[i - 1], dp[i - 2] + frequency.get(elements[i], 0) * elements[i])\r\n\r\n# The maximum points that can be earned will be the maximum value in the dp array\r\nmax_points = max(dp)\r\n\r\n# Print the maximum points\r\nprint(max_points)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "One day shooshuns found a sequence of *n* integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps:\n 1. Find the number that goes *k*-th in the current sequence and add the same number to the end of the sequence; 1. Delete the first number of the current sequence. \nThe shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.",
"input": "",
"output": "```python\nn = [int(x) for x in input().split()]\r\np = [int(x) for x in input().split()]\r\ni = 0\r\nfor j in range(len(p) - 1):\r\n num = p[n[1]-1]\r\n p.append(num)\r\n p.pop(0)\r\n i = i+1\r\nif len(set(p)) == 1:\r\n print(i)\r\nelse:\r\n print(-1)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "PolandBall is a young, clever Ball. He is interested in prime numbers. He has stated a following hypothesis: \"There exists such a positive integer *n* that for each positive integer *m* number *n*·*m*<=+<=1 is a prime number\".\n\nUnfortunately, PolandBall is not experienced yet and doesn't know that his hypothesis is incorrect. Could you prove it wrong? Write a program that finds a counterexample for any *n*.",
"input": "",
"output": "```python\nn = int(input())\r\n\r\nflag = False\r\n\r\nfor i in range(1, n + 1):\r\n \r\n tempNum = n * i + i\r\n \r\n for j in range(2, int(tempNum / 2) + 1):\r\n \r\n if tempNum % j == 0:\r\n flag = True\r\n break\r\n \r\n if flag == True:\r\n print(i)\r\n break\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Array of integers is unimodal, if:\n - it is strictly increasing in the beginning; - after that it is constant; - after that it is strictly decreasing. \nThe first block (increasing) and the last block (decreasing) may be absent. It is allowed that both of this blocks are absent.\n\nFor example, the following three arrays are unimodal: [5,<=7,<=11,<=11,<=2,<=1], [4,<=4,<=2], [7], but the following three are not unimodal: [5,<=5,<=6,<=6,<=1], [1,<=2,<=1,<=2], [4,<=5,<=5,<=6].\n\nWrite a program that checks if an array is unimodal.",
"input": "",
"output": "```python\narr=[]\r\nn=int(input(\"Number of elements in array:\"))\r\nfor i in range(0,n):\r\n ele=int(input())\r\n arr.append(ele)\r\n\r\ndef f(m,n,flag):\r\n if flag==1:\r\n return mn\r\n\r\ndef is_unimodal(a, lst):\r\n flag=1\r\n for i in range(1,n):\r\n if f(lst[i-1], lst[i], flag):\r\n continue\r\n else:\r\n flag += 1\r\n if f(lst[i-1], lst[i], flag):\r\n continue\r\n else:\r\n flag += 1\r\n if f(lst[i-1], lst[i], flag):\r\n continue\r\n else:\r\n return \"NO\"\r\n return \"YES\"\r\n\r\nprint(is_unimodal(n, arr))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "What joy! Petya's parents went on a business trip for the whole year and the playful kid is left all by himself. Petya got absolutely happy. He jumped on the bed and threw pillows all day long, until... \n\nToday Petya opened the cupboard and found a scary note there. His parents had left him with duties: he should water their favourite flower all year, each day, in the morning, in the afternoon and in the evening. \"Wait a second!\" — thought Petya. He know for a fact that if he fulfills the parents' task in the *i*-th (1<=≤<=*i*<=≤<=12) month of the year, then the flower will grow by *a**i* centimeters, and if he doesn't water the flower in the *i*-th month, then the flower won't grow this month. Petya also knows that try as he might, his parents won't believe that he has been watering the flower if it grows strictly less than by *k* centimeters. \n\nHelp Petya choose the minimum number of months when he will water the flower, given that the flower should grow no less than by *k* centimeters.",
"input": "",
"output": "```python\nn=int(input())\r\nf=list(map(int,input().split()))\r\ns=k=0\r\nwhile k=n:\r\n\tans=sum(l)/(n-k+1)\r\n\tprint(ans)\r\nelse:\r\n\ti=n-k+1\r\n\tj=[l[i] for i in range(n-k+1)]\r\n\ts=sum(j)\r\n\twhile i= 1:\r\n ans += AIB[pos]\r\n pos -= pos & (-pos)\r\n return ans\r\n\r\ndef query2(pos):\r\n ans = 0\r\n if pos < 0: return 0\r\n while pos >= 1:\r\n ans += AIB2[pos]\r\n pos -= pos & (-pos)\r\n return ans\r\n\r\nv = [int(x) for x in input().split()]\r\nfor i in range(len(v)):\r\n v[i] = n - v[i] + 1\r\n\r\nv.insert(0,0)\r\nans = 0; ans2 = 0\r\nfor i in range(1, n+1):\r\n ans += 1 * (n-i+1) * query1(v[i]-1)\r\n add1(v[i], i)\r\n ans2 += query2(v[i]-1)\r\n add2(v[i], 1)\r\n\r\nans3 = 0\r\nfor i in range(1, n+1):\r\n ans3 += ((n-i+1) * (i-1) * i / 4) / (n * (n+1) / 2)\r\n\r\nans /= (n * (n+1) / 2)\r\nans = ans2 - ans + ans3\r\nprint(\"{:.10f}\".format(ans))\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are given a non-negative integer *n*, its decimal representation consists of at most 100 digits and doesn't contain leading zeroes.\n\nYour task is to determine if it is possible in this case to remove some of the digits (possibly not remove any digit at all) so that the result contains at least one digit, forms a non-negative integer, doesn't have leading zeroes and is divisible by 8. After the removing, it is forbidden to rearrange the digits.\n\nIf a solution exists, you should print it.",
"input": "",
"output": "```python\ns = \"00\" + input()\r\nl = len(s)\r\nfor i in range(l):\r\n\tfor j in range(i + 1, l):\r\n\t\tfor k in range(j + 1, l):\r\n\t\t\tans = s[i] + s[j] + s[k]\r\n\t\t\tif (int(ans) % 8 == 0):\r\n\t\t\t\tprint(\"YES\")\r\n\t\t\t\tprint(int(ans))\r\n\t\t\t\texit()\r\nprint(\"NO\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "In a building where Polycarp lives there are equal number of flats on each floor. Unfortunately, Polycarp don't remember how many flats are on each floor, but he remembers that the flats are numbered from 1 from lower to upper floors. That is, the first several flats are on the first floor, the next several flats are on the second and so on. Polycarp don't remember the total number of flats in the building, so you can consider the building to be infinitely high (i.e. there are infinitely many floors). Note that the floors are numbered from 1.\n\nPolycarp remembers on which floors several flats are located. It is guaranteed that this information is not self-contradictory. It means that there exists a building with equal number of flats on each floor so that the flats from Polycarp's memory have the floors Polycarp remembers.\n\nGiven this information, is it possible to restore the exact floor for flat *n*?",
"input": "",
"output": "```python\nn, m = map(int, input().split())\n\nflats = {}\n\nfor i in range(m):\n flat, floor = map(int, input().split())\n if floor not in flats.keys():\n flats[floor] = []\n flats[floor].append(flat)\n\n\nfloors = sorted(flats.keys())\n\ndef check():\n for i in range(1, len(floors)):\n a,b=min(flats[floors[i]]), max(flats[floors[i-1]])\n if a-b == 1:\n return b, floors[i-1]\n return False\n\nside_flat=check()\nif not side_flat:\n print(-1)\n exit()\nelse:\n n_flats_floor=side_flat[0]//side_flat[1]\n\nprint((n-1)//n_flats_floor + 1)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "As you may know, MemSQL has American offices in both San Francisco and Seattle. Being a manager in the company, you travel a lot between the two cities, always by plane.\n\nYou prefer flying from Seattle to San Francisco than in the other direction, because it's warmer in San Francisco. You are so busy that you don't remember the number of flights you have made in either direction. However, for each of the last *n* days you know whether you were in San Francisco office or in Seattle office. You always fly at nights, so you never were at both offices on the same day. Given this information, determine if you flew more times from Seattle to San Francisco during the last *n* days, or not.",
"input": "",
"output": "```python\ni = input()\r\ni = int(i)\r\ns = input()\r\n\r\nif s[0] == 'S' and s[i-1] == 'F':\r\n\tprint ('YES')\r\nelse:\r\n\tprint ('NO')\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Fox Ciel saw a large field while she was on a bus. The field was a *n*<=×<=*m* rectangle divided into 1<=×<=1 cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes. \n\nAfter seeing the field carefully, Ciel found that the crop plants of each cell were planted in following procedure:\n - Assume that the rows are numbered 1 to *n* from top to bottom and the columns are numbered 1 to *m* from left to right, and a cell in row *i* and column *j* is represented as (*i*,<=*j*). - First, each field is either cultivated or waste. Crop plants will be planted in the cultivated cells in the order of (1,<=1)<=→<=...<=→<=(1,<=*m*)<=→<=(2,<=1)<=→<=...<=→<=(2,<=*m*)<=→<=...<=→<=(*n*,<=1)<=→<=...<=→<=(*n*,<=*m*). Waste cells will be ignored. - Crop plants (either carrots or kiwis or grapes) will be planted in each cell one after another cyclically. Carrots will be planted in the first cell, then kiwis in the second one, grapes in the third one, carrots in the forth one, kiwis in the fifth one, and so on. \nThe following figure will show you the example of this procedure. Here, a white square represents a cultivated cell, and a black square represents a waste cell.\n\nNow she is wondering how to determine the crop plants in some certain cells.",
"input": "",
"output": "```python\nfrom queue import Queue\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom bisect import bisect_left\r\nfrom sortedcontainers import SortedSet\r\n\r\n\r\ndef ColorfulFields():\r\n n, m, k, t = map(int, input().split())\r\n wastes = SortedSet()\r\n for i in range(k):\r\n x, y = map(int, input().split())\r\n wastes.add((x-1) * m + y)\r\n \r\n fruits = [\"Carrots\", \"Kiwis\", \"Grapes\"]\r\n for i in range(t):\r\n x, y = map(int, input().split())\r\n cellNO = (x-1) * m + y\r\n if cellNO in wastes:\r\n print(\"Waste\")\r\n else:\r\n wasteCount = bisect_left(wastes, cellNO)\r\n print(fruits[(cellNO % 3 - 1) - wasteCount])\r\n \r\n \r\nColorfulFields()\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.\n\nRules of the game are very simple: at first number of rounds *n* is defined. In every round each of the players throws a cubical dice with distinct numbers from 1 to 6 written on its faces. Player, whose value after throwing the dice is greater, wins the round. In case if player dice values are equal, no one of them is a winner.\n\nIn average, player, who won most of the rounds, is the winner of the game. In case if two players won the same number of rounds, the result of the game is draw.\n\nMishka is still very little and can't count wins and losses, so she asked you to watch their game and determine its result. Please help her!",
"input": "",
"output": "```python\nusing namespace std;\r\nint main()\r\n{\r\n int n;\r\n while(cin>>n)\r\n {\r\n int p1=0,p2=0;\r\n while(n--)\r\n {\r\n int P1,P2;\r\n cin>>P1>>P2;\r\n p1+=(P1>P2);\r\n p2+=(P2>P1);\r\n }\r\n if(p1>p2)\r\n cout<<\"Mishka\"< score:\r\n score = r_score\r\n pos +=1\r\n out[r[0]] = pos\r\nprint (' '.join(str(x) for x in out))\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are given a multiset of *n* integers. You should select exactly *k* of them in a such way that the difference between any two of them is divisible by *m*, or tell that it is impossible.\n\nNumbers can be repeated in the original multiset and in the multiset of selected numbers, but number of occurrences of any number in multiset of selected numbers should not exceed the number of its occurrences in the original multiset.",
"input": "",
"output": "```python\nn, k, m = [int(z) for z in input().split()]\r\na = [int(z) for z in input().split()]\r\nd = dict()\r\nfor i in range(n):\r\n mod = a[i] % m\r\n if mod in d:\r\n d[mod].append(a[i])\r\n else:\r\n d[mod] = [a[i]]\r\nfor elem in d:\r\n if len(d[elem]) >= k:\r\n print(\"Yes\")\r\n for i in range(k):\r\n print(d[elem][i], end=\" \")\r\n exit(0)\r\nprint(\"No\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nEmbosser 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:\n\nAfter 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'.\n\nOur 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.",
"input": "",
"output": "```python\ndef main():\r\n aname = input()\r\n anum = []\r\n for char in aname:\r\n num = ord(char) - 96\r\n anum.append(num)\r\n steps = 0\r\n stnum = 1\r\n for i in range(len(anum)):\r\n let1 = stnum\r\n let2 = anum[i]\r\n a1 = abs(let1 - let2)\r\n a2 = 26 - a1\r\n step1 = min(a1, a2)\r\n steps += step1\r\n stnum = let2\r\n print(steps)\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nYou 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.\n\nYou 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.\n\nYou are given the text of the lecture the professor is going to read. Find out how the lecture will be recorded in your notes.",
"input": "",
"output": "```python\nn,m = map(int,input().split())\r\nd = dict(input().split() for _ in range(m))\r\nprint(' '.join(min((w,d[w]), key=len) for w in input().split()))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.",
"input": "",
"output": "```python\nn = int(input())\r\nnums = list(map(int, input().split()))\r\n\r\nflag = nums[0] % 2 + nums[1] % 2 + nums[2] % 2\r\n\r\nif flag == 3:\r\n flag = 0\r\nelif flag == 2:\r\n print((nums[0] % 2 == 0) * 1 + (nums[1] % 2 == 0) * 2 + (nums[2] % 2 == 0) * 3)\r\n exit(0)\r\nelif flag == 1:\r\n print((nums[0] % 2 == 1) * 1 + (nums[1] % 2 == 1) * 2 + (nums[2] % 2 == 1) * 3)\r\n exit(0)\r\nelse:\r\n flag = 1\r\n \r\nfor i in range(3, n):\r\n if nums[i] % 2 == flag:\r\n print(i+1)\r\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are given an equation: \n\nYour task is to find the number of distinct roots of the equation and print all of them in ascending order.",
"input": "",
"output": "```python\nfrom math import *\r\na,b,c= map(int,input().split())\r\n\r\nd=b**2-4*a*c\r\nif d>=0:\r\n x2 = (-b - sqrt(b ** 2 - 4 * a * c)) / (2 * a)\r\n x1 = (-b + sqrt(b ** 2 - 4 * a * c)) / (2 * a)\r\n if x1==x2:\r\n c=1\r\n print(c)\r\n print('-1')\r\n else:\r\n c=2\r\n print(c)\r\n print(x2)\r\n print(x1)\r\nelse: print('0')\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nAt 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.\n\nDetermine 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.",
"input": "",
"output": "```python\nh, m = map(int, input().split())\r\nH, D, C, N = map(int, input().split())\r\nafter = C * 0.8\r\nans = (H + N - 1) // N * C\r\ntm = h * 60 + m\r\ntm1 = 20 * 60 + 0\r\ntm2 = 23 * 60 + 59\r\nif tm1 < tm < tm2:\r\n print('{:.16f}'.format((H + N - 1) // N * after))\r\nelse:\r\n tm3 = tm1 - tm\r\n print('{:.16f}'.format(min(ans, (H + N - 1 + D * tm3) // N * after)))\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Galois is one of the strongest chess players of Byteforces. He has even invented a new variant of chess, which he named «PawnChess».\n\nThis 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. \n\nLets 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*.\n\nThere 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.\n\nPlayer 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.\n\nMoving 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.\n\nGiven 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.",
"input": "",
"output": "```python\nimport sys\n\nm = []\nfor i in range(8):\n m.append(input())\n\na = -1\nb = -1\nfor i in range(8):\n col = m[i].find('W')\n if col >= 0:\n a = i\n for j in range(i):\n if m[j][col] != '.':\n a = -1\n break\n\n if a != -1:\n break\n\ni = 7\nwhile i >= 0:\n col = m[i].find('B')\n if col >= 0:\n b = i\n j = i+1\n while j < 8:\n if m[j][col] != '.':\n b = -1\n break\n j += 1\n\n if b != -1:\n break\n i -= 1\n\nif a <= (7-b):\n print(\"A\")\nelse:\n print(\"B\")\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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?\n\nGiven 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.",
"input": "",
"output": "```python\nn=int(input())\r\nl=[]\r\nfor i in range(n):\r\n l1=input()\r\n l.append(l1)\r\nflag=0\r\nfor i in range(n):\r\n for j in range(n):\r\n s=0\r\n if(i!=0):\r\n if(l[i-1][j]=='o'):\r\n s+=1\r\n if(j!=0):\r\n if(l[i][j-1]=='o'):\r\n s+=1\r\n if(i!=n-1):\r\n if(l[i+1][j]=='o'):\r\n s+=1\r\n if(j!=n-1):\r\n if(l[i][j+1]=='o'):\r\n s+=1\r\n if(s%2!=0):\r\n flag=1\r\n break\r\nif(flag):\r\n print(\"NO\")\r\nelse:\r\n print(\"YES\")\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Mancala is a game famous in the Middle East. It is played on a board that consists of 14 holes. \n\nInitially, 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.\n\nNote 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.\n\nAfter 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.\n\nResli is a famous Mancala player. He wants to know the maximum score he can obtain after one move.",
"input": "",
"output": "```python\nholes = list(map(int, input().split()))\r\nmx = -1\r\nfor i in range(14):\r\n if holes[i]>0:\r\n temp2 = holes[i]\r\n temp = list(holes)\r\n temp[i] = 0\r\n while(temp2>0):\r\n if i+1 == 14:\r\n i = 0\r\n else:\r\n i+=1\r\n temp[i]+=1\r\n temp2-=1\r\n #print(temp)\r\n sm = 0\r\n for i in temp:\r\n if i%2 == 0:\r\n sm+=i\r\n mx = max(mx,sm)\r\nprint(mx)\r\n\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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. \n\nPikachu being mischievous as he always is, removed all the subsequences in which Maximum_element_of_the_subsequence <=-<= Minimum_element_of_subsequence <=≥<=*d*\n\nPikachu was finally left with *X* subsequences. \n\nHowever, 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. \n\nNote the number of elements in the output array should not be more than 104. If no answer is possible, print <=-<=1.",
"input": "",
"output": "```python\nimport math\r\nx,d=map(int,input().split())\r\n\r\nn=math.floor(math.log(x+1,2))\r\nif (n-1>=d and x>10000):\r\n print(-1)\r\nelif (x<=10000 or n-1>=d):\r\n print(x)\r\n for i in range(1,x*d+2-d,d):\r\n print(i,end=' ')\r\n print()\r\nelse:\r\n tb=2**n-1\r\n diff=x-tb\r\n g=1\r\n arr=[]\r\n c=tb\r\n while diff>0:\r\n for i in range(g,g+n):\r\n arr.append(i)\r\n g=g+n+d-1\r\n n=math.floor(math.log(diff+1,2))\r\n tb=2**n-1\r\n diff=diff-tb\r\n c+=tb\r\n for i in range(g,g+n):\r\n arr.append(i)\r\n print(c)\r\n print(*arr)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nHow many bars each of the players will consume?",
"input": "",
"output": "```python\nn=int(input())\r\nl=list(map(int, input().split()))\r\na,b,i,j=0,0,0,n-1\r\nwhile isum(l[j:])):\r\n\t\tb+=1\r\n\t\tj+=1\r\n\telif(sum(l[:i+1])>sum(l[j:])):\r\n\t\ta+=1\r\n\t\ti+=1\r\n\telse:\r\n\t\ta+=1\r\n\t\tb+=1\r\n\t\ti+=1\r\n\t\tj+=1\r\nprint(a,b)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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?",
"input": "",
"output": "```python\nn = input()\n\nc = 0\n\nwhile len(n) > 1:\n\tn = str(sum([int(i) for i in n]))\n\tc += 1\n\nprint(c)\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Top-model Izabella participates in the competition. She wants to impress judges and show her mathematical skills.\n\nHer 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.",
"input": "",
"output": "```python\na=input()\r\narray=list(a)\r\nbirBulundu=False\r\nsifirSayisi=0\r\nfor i in array:\r\n if(i=='1'):\r\n birBulundu=True\r\n else:\r\n if(birBulundu==True):\r\n sifirSayisi=sifirSayisi+1\r\n \r\nif (sifirSayisi>5):\r\n print(\"yes\")\r\nelse:\r\n print(\"no\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "The recent All-Berland Olympiad in Informatics featured *n* participants with each scoring a certain amount of points.\n\nAs 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: \n - 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. \nDetermine the number of ways to choose a subset of participants that will receive the diplomas.",
"input": "",
"output": "```python\nif __name__ == '__main__':\r\n input()\r\n s = set(input().split())\r\n print(len(s) - ('0' in s))\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Fedya studies in a gymnasium. Fedya's maths hometask is to calculate the following expression:\n\nfor 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).",
"input": "",
"output": "```python\ndef dsd(a):\r\n sl = list(str(a))\r\n ls = [] \r\n for i in range(len(sl)):\r\n ls.append(int(sl[i]))\r\n return ls \r\n\r\nfor _ in range(int(input())):\r\n a, k = map(int,input().split())\r\n ans = a \r\n while k > 1 and '0' not in list(str(a)):\r\n maxi = max(dsd(ans))\r\n mini = min(dsd(ans))\r\n ans = ans + maxi*mini \r\n k-=1\r\n print(ans)\r\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "*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.\n\nFor 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.",
"input": "",
"output": "```python\nimport bisect\r\nimport os\r\nfrom collections import Counter\r\nimport bisect\r\nfrom collections import defaultdict\r\nimport math\r\nimport random\r\nimport heapq as hq\r\nfrom math import sqrt\r\nimport sys\r\nfrom functools import reduce, cmp_to_key\r\nfrom collections import deque\r\nimport threading\r\nfrom itertools import combinations\r\nfrom io import BytesIO, IOBase\r\nfrom itertools import accumulate\r\n\r\n# sys.setrecursionlimit(200000)\r\n# mod = 10**9+7\r\n# mod = 987\r\n\r\ndef lcm(a,b):\r\n return (a*b)//math.gcd(a,b)\r\n\r\ndef sort_dict(key_value):\r\n return sorted(key_value.items(), key = lambda kv:(kv[1], kv[0]))\r\n\r\ndef list_input():\r\n return list(map(int,input().split()))\r\n \r\ndef num_input():\r\n return map(int,input().split())\r\n \r\ndef string_list():\r\n return list(input())\r\n \r\n \r\ndef solve():\r\n n,k = num_input()\r\n arr = list_input()\r\n if k < n:\r\n for i in range(n):\r\n j = (i+1)%n\r\n count = 0\r\n while arr[i] > arr[j]:\r\n count += 1\r\n if count == k:\r\n print(arr[i])\r\n return\r\n j = (j+1)%n\r\n else:\r\n print(max(arr))\r\n\r\n\r\n#t = int(input())\r\nt = 1\r\nfor _ in range(t):\r\n solve()\r\n\r\n\r\n \r\n \r\n \r\n \r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nThe 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.\n\nA 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.\n\nThe 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.\n\nCould you find out who is going to be the winner if they all play optimally?",
"input": "",
"output": "```python\n# Why do we fall ? So we can learn to pick ourselves up.\r\n\r\n\r\nfrom collections import Counter\r\nn = int(input())\r\nss = []\r\nfor _ in range(0,3):\r\n ss.append(input())\r\nans = [\"Kuro\",\"Shiro\",\"Katie\"]\r\nmaxi = [0,0,0]\r\nfor i in range(0,3):\r\n c = Counter(ss[i])\r\n mx = max(c.values())\r\n to = min(len(ss[i])-mx,n)\r\n maxi[i] = mx+to\r\n if n == 1 and mx == len(ss[i]):\r\n maxi[i] -= 1\r\n# print(maxi)\r\nif maxi.count(max(maxi)) > 1:\r\n print(\"Draw\")\r\nelse:\r\n print(ans[maxi.index(max(maxi))])\r\n\r\n\r\n\r\n\r\n\"\"\"\r\n\r\n1\r\nooooo\r\nabcde\r\nabcde\r\n\r\n3\r\nKuroo\r\nShiro\r\nKatie\r\n\r\n\r\n\r\n\"\"\"\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nNatasha 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?\n\nYou can assume that initially Vanya had infinitely many cards with each integer number from <=-<=*x* to *x*.",
"input": "",
"output": "```python\nn, x = list(map(int, input().split()))\r\na = list(map(int, input().split()))\r\nsums = sum(a)\r\n# print(sums)\r\n\r\ndiv = abs(sums) // x\r\nif (abs(sums) % x == 0):\r\n print(div)\r\nelse:\r\n print(div + 1)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nThe 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.\n\nYour task is to determine how many buses is needed to transport all *n* groups to the dacha countryside.",
"input": "",
"output": "```python\nn,m=map(int,input().split())\r\na=list(map(int,input().split()))\r\nl=sum(a)\r\nif(l%m==0):\r\n print(l//m)\r\nelse:\r\n print(l//m+1)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Over time, Alexey's mail box got littered with too many letters. Some of them are read, while others are unread.\n\nAlexey'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:\n- 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.\nThe program cannot delete the letters from the list or rearrange them.\n\nAlexey 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?",
"input": "",
"output": "```python\nn = int(input())\r\nx = list(map(int,input().split()))\r\notv = 0\r\nfor i in range(n):\r\n\tif x[i] == 1:\r\n\t\totv += 1\r\n\t\tif i < n-1 and x[i+1] != 1:\r\n\t\t\totv += 1\r\nif x[i] != 1:\r\n\tprint(max(otv-1,0))\r\nelse:\r\n\tprint(otv)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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*.\n\nThe 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\".\n\nTanya 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.",
"input": "",
"output": "```python\nTM = input()\r\nNM = input()\r\nLTM = list(TM)\r\nLNM = list(NM)\r\ncnt1 = 0\r\ncnt2 = 0\r\nfor i in range(len(LTM)):\r\n\tfor j in range(len(LNM)):\r\n\t\tif LTM[i] == LNM[j]:\r\n\t\t\tpass\r\n\t\t\tcnt1 += 1\r\n\t\t\tLNM[j] = ' '\r\n\t\t\tbreak\r\n\t\telse:\r\n\t\t\tif LTM[i] == LNM[j].upper():\r\n\t\t\t\tcnt2 += 1\r\n\t\t\t\tLNM[j] = 'A4'\r\n\t\t\t\tbreak\r\n\t\t\telif(LTM[i] == LNM[j].lower()):\r\n\t\t\t\tcnt2 += 1\r\n\t\t\t\tLNM[j] = 'A4'\r\n\t\t\t\tbreak\r\nprint(cnt1,cnt2)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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:\n - 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). \nNow Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.\n\nPolycarp 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.\n\nAs Polycarp has no time, he is asking for your help in solving this problem.",
"input": "",
"output": "```python\nfrom sys import stdin \r\ninputs = []\r\ninputs = stdin.read().splitlines()\r\ns1=set()\r\nans=0\r\nfor i in inputs:\r\n if i[0]==\"+\":\r\n s1.add(i[1:])\r\n elif i[0]=='-':\r\n s1.remove(i[1:])\r\n else:\r\n ind=i.index(':')\r\n msglen=len(i[ind:])-1\r\n ans+=msglen*len(s1)\r\nprint(ans) \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nPete 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.",
"input": "",
"output": "```python\na=input()\r\na=int(a)\r\nif a%2!=0:\r\n print(\"NO\")\r\nelse:\r\n if a==2:\r\n print(\"NO\")\r\n else:\r\n print(\"YES\")\r\n \r\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nMetropolis 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.\n\nAll *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.\n\nHelen 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.",
"input": "",
"output": "```python\nn, k = map(int, input().split())\r\nc = list(map(int, input().split()))\r\ns = []\r\nmax_elem = 0\r\nmax_elem_i = 0\r\nfor i in range(n):\r\n if c[i] > max_elem:\r\n max_elem_i = i\r\n max_elem = c[i]\r\nfor i in range(n):\r\n s.append((c[i], i))\r\ns.sort(reverse=True)\r\nres = [0] * n\r\np = 0\r\nq = 0\r\nfor i, pair in enumerate(s):\r\n if pair[1] + k < max_elem_i:\r\n res[q] = pair[1] + k + 1\r\n q += 1\r\nfor i, pair in enumerate(s):\r\n if pair[1] + k >= max_elem_i:\r\n res[q] = pair[1] + k + 1\r\n q += 1\r\nfor i in range(n):\r\n p += (res[i] - i - 1) * c[i]\r\nprint(p)\r\nprint(' '.join(map(str, res)))\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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 < n$) such that $s_i \\ne s_{i + 1}$. It is guaranteed that the answer always exists.\n\nFor example, for the string \"01010\" there are four indices $i$ such that $1 \\le i < 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$).\n\nRecall that binary string is a non-empty sequence of characters where each character is either 0 or 1.",
"input": "",
"output": "```python\nfrom math import*\r\nimport os\r\n\r\na,b,x=map(int,input().split())\r\nc=0\r\nd=0\r\nif x%2==0:\r\n\tvar=x//2\r\n\tfor i in range(var):\r\n\t\tif a>b:\r\n\t\t\tprint(\"01\",end='')\r\n\t\telse:\r\n\t\t\tprint(\"10\",end='')\r\n\tfor i in range(min(a,b)-var):\r\n\t\tprint(\"1\" if a>b else 0,end='')\r\n\tfor i in range(max(a,b)-var):\r\n\t\tprint(\"0\" if a>b else 1,end='')\r\nelse:\r\n\tvar=(x-1)//2\r\n\tfor i in range(var):\r\n\t\tif a>b:\r\n\t\t\tprint(\"01\",end='')\r\n\t\telse:\r\n\t\t\tprint(\"10\",end='')\r\n\tfor i in range(max(a,b)-var):\r\n\t\tprint(\"0\" if a>b else \"1\",end='')\r\n\tfor i in range(min(a,b)-var):\r\n\t\tprint(\"1\" if a>b else 0,end='')\r\n\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nThe 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.\n\nLast 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.\n\nClock 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).\n\nGiven 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.",
"input": "",
"output": "```python\nx=list(map(int,input().split()))\r\nx[0]=int((x[0]*(60/12))) % 60 \r\nm=x[1]\r\ns=x[2]\r\nx[3]=int((x[3]*(60/12))) % 60 \r\nx[4]=int((x[4]*(60/12))) % 60 \r\n\r\nz=[x[1],x[2],x[0]]\r\nz.sort()\r\nx1=[]\r\nx2=[]\r\nfor i in range(1,3):\r\n if z[i-1]==z[i]:\r\n del(z[i])\r\n break\r\nif len(z)==3:\r\n if x[3]>z[0] and x[3]z[1] and x[3]z[0] and x[4]z[1] and x[4]z[0] and x[3]z[0] and x[4]=2400 and after >before:\r\n count+=1\r\n else :\r\n break\r\nif count>0:\r\n print(\"YES\")\r\nelse:\r\n print(\"NO\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nDetermine 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\".\n\nYou 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\".",
"input": "",
"output": "```python\nn=int(input())\r\ns=input()\r\ncount=0\r\nfor i in range(n-2):\r\n if s[i]+s[i+1]+s[i+2]==\"xxx\":\r\n count+=1\r\nprint(count)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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*<=<<=*y*) from the set, such that *y*<==<=*x*·*k*.\n\nYou're given a set of *n* distinct positive integers. Your task is to find the size of it's largest *k*-multiple free subset.",
"input": "",
"output": "```python\ndef solve(arr, n, k):\r\n dp = [1 for i in range(n)]\r\n \r\n for i in range(1,n):\r\n temp = 0\r\n for j in range(i):\r\n if arr[i]%arr[j]!=0:\r\n temp += 1\r\n dp[i] = temp\r\n \r\n return max(dp)\r\n \r\nif __name__==\"__main__\":\r\n n,k = map(int, input().split())\r\n arr = list(map(int, input().split()))\r\n arr.sort()\r\n \r\n ans = solve(arr,n,k)\r\n print(ans)\r\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "*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.\n\nThe 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.\n\nYou 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. \n\nWrite 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.",
"input": "",
"output": "```python\nn,m = map(int, input().split())\r\nl = list(map(int,input().split()))\r\na = [0 for i in range(n+1)]\r\ncur = l[0]\r\nfor i in range(1,m):\r\n nx = l[i%m]\r\n if nx > l[i-1]:\r\n val = nx - l[i-1]\r\n else:\r\n val = n - l[i-1] + nx\r\n if not a[l[i-1]]:\r\n a[l[i-1]] = val \r\n elif a[l[i-1]] != val:\r\n print(\"-1\")\r\n quit()\r\ncnt = [0 for i in range(n+1)]\r\nfor i in range(1,n+1):\r\n cnt[a[i]] += 1 \r\n if cnt[a[i]] > 1:\r\n print(\"-1\") \r\n quit()\r\ncr = 1 \r\nfor i in range(1,n+1):\r\n if a[i]: continue\r\n while cnt[cr]:\r\n cr += 1 \r\n a[i] = cr \r\n cr += 1 \r\nfor i in range(1, n+1):\r\n print(a[i],end=\" \")\r\n\r\n \r\n \r\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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*.\n\nNow 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.\n\nTimofey 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.\n\nA subtree of some vertex is a subgraph containing that vertex and all its descendants.\n\nYour task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed.",
"input": "",
"output": "```python\nR=lambda:map(int,input().split())\r\nt,=R()\r\n\r\nfor _ in range(t-1):\r\n x=list(R())\r\na=list(R())\r\ns=set(a)\r\nc=0\r\nd=0\r\nfor i in s:\r\n if(a.count(i)>1):\r\n c+=1\r\n if(a.count(i)==1):\r\n d=i\r\nif(c>1):\r\n print(\"NO\")\r\nelse:\r\n print(\"YES\")\r\n print(d)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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).\n\nIahub 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.",
"input": "",
"output": "```python\nfrom functools import reduce\n\n\nclass GukziString:\n chars = 'abcdefghijklmnopqrstuvwxyz'\n\n def __init__(self, string=''):\n super(GukziString, self).__init__()\n for ch in GukziString.chars:\n setattr(self, ch, 0)\n for ch in string:\n setattr(self, ch, getattr(self, ch) + 1)\n\n def __sub__(self, other):\n ans = GukziString()\n for ch in GukziString.chars:\n setattr(ans, ch, getattr(self, ch) - getattr(other, ch))\n return ans\n\n def __mul__(self, number):\n ans = GukziString()\n for ch in GukziString.chars:\n setattr(ans, ch, getattr(self, ch) * number)\n return ans\n\n def __floordiv__(self, other):\n valid_chars = filter(lambda ch: getattr(other, ch) != 0, GukziString.chars)\n return reduce(lambda x, y: min(x, y), [getattr(self, ch) // getattr(other, ch) for ch in valid_chars])\n\n def __mod__(self, other):\n return self - other * (self // other)\n\n def __str__(self):\n ans = ''\n for ch in GukziString.chars:\n ans += ch * getattr(self, ch)\n return ans\n\n\na_str = input()\nb_str = input()\nc_str = input()\n\na = GukziString(a_str)\nb = GukziString(b_str)\nc = GukziString(c_str)\n\nb_count = max(b_count + (a - b * b_count) // c for b_count in range(a // b + 1))\nprint(f'{b_str * b_count}{c_str * ((a - b * b_count) // c)}{(a - b * b_count) % c}')\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nYour task is to help Petya find what maximum equal amount of energy can be stored in each accumulator after the transfers.",
"input": "",
"output": "```python\ndef energy(acc, level, perc_loss):\n surplus = sum([max(x - level, 0) for x in acc])\n en_cost = sum([(abs(min(0, x - level)) * 100) / (100 - perc_loss) for x in acc])\n return surplus >= en_cost\n\n\nclass CodeforcesTask68BSolution:\n def __init__(self):\n self.result = ''\n self.n_k = []\n self.accumulators = []\n\n def read_input(self):\n self.n_k = [int(x) for x in input().split(\" \")]\n self.accumulators = [int(x) for x in input().split(\" \")]\n\n def process_task(self):\n l = 0\n r = sum(self.accumulators) / self.n_k[0]\n while r - l >= 0.000_0001:\n mid = l + (r - l) / 2\n if energy(self.accumulators, mid, self.n_k[1]):\n l = mid\n else:\n r = mid\n self.result = str(r)\n\n def get_result(self):\n return self.result\n\n\nif __name__ == \"__main__\":\n Solution = CodeforcesTask68BSolution()\n Solution.read_input()\n Solution.process_task()\n print(Solution.get_result())\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.",
"input": "",
"output": "```python\nn,a,b = map(int,input().split())\nans = a+1\nprint(ans)\n \t\t\t \t \t \t\t\t\t\t \t\t \t \t \t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nThere 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.\n\nGiven 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!",
"input": "",
"output": "```python\nn = int(input())\r\nx = list(map(int, input().split()))\r\nx.sort()\r\nfor i in range(n):\r\n print(x[i], end=' ')\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nThere 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.\n\nYou 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.",
"input": "",
"output": "```python\nN = int(input())\r\nM = N*(N - 1)\r\n\r\nMISS = []\r\nFI = []\r\nC = 0\r\nfor i in range(N):\r\n \r\n T = input().split()\r\n MISS.append(T[1])\r\n FI.append(T[0])\r\n \r\n \r\nfor i in range(N):\r\n for j in (FI) : \r\n if j == MISS[i]:\r\n C+=1\r\n \r\nprint(C)\r\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A and B are preparing themselves for programming contests.\n\nTo 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.\n\nFor each chess piece we know its weight: \n - 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. \nThe player's weight equals to the sum of weights of all his pieces on the board.\n\nAs A doesn't like counting, he asked you to help him determine which player has the larger position weight.",
"input": "",
"output": "```python\nw=0\r\nb=0\r\nm=[input() for i in range(8)]\r\nfor line in m:\r\n for p in line:\r\n if p==\"Q\":\r\n w+=9\r\n elif p==\"R\":\r\n w+=5\r\n elif p==\"B\" or p==\"N\":\r\n w+=3\r\n elif p==\"P\":\r\n w+=1\r\n if p==\"q\":\r\n b+=9\r\n elif p==\"r\":\r\n b+=5\r\n elif p==\"b\" or p==\"n\":\r\n b+=3\r\n elif p==\"p\":\r\n b+=1\r\nif w>b:\r\n print(\"White\")\r\nelif b>w:\r\n print(\"Black\")\r\nelse:\r\n print(\"Draw\")\r\n \r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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!\n\nWhy 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.\n\nIn 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.\n\nThe 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*.",
"input": "",
"output": "```python\nn = int(input())\r\n\r\nif n <= 10 :\r\n print(0)\r\nelse:\r\n if n <= 19:\r\n print(4)\r\n elif n == 20:\r\n print(15)\r\n elif n == 21:\r\n print(4)\r\n else:\r\n print(0)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nDwarf 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.",
"input": "",
"output": "```python\ns1=input()\r\ns2=input()\r\ns1=[s1[k] for k in range(len(s1))]\r\ns2=[s2[k] for k in range(len(s2))]\r\nx=0\r\nans=\"\"\r\nif len(s1)!=len(s2):\r\n print(\"NO\")\r\nfor i in range(len(s1)):\r\n for j in range(i+1,len(s1)):\r\n \r\n s1[i],s1[j]=s1[j],s1[i]\r\n if s1==s2:\r\n x+=1\r\n ans=\"YES\"\r\n break\r\n else:\r\n s1[i],s1[j]=s1[j],s1[i]\r\n \r\nif x==1 and ans==\"YES\":\r\n print(\"YES\")\r\nelse:\r\n print(\"NO\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. \n\nIn 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.\n\nMashmokh 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. \n\nPlease, 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.",
"input": "",
"output": "```python\nn,k=map(int,input().split())\r\n\r\nif(k0)):\r\n print(-1)\r\nelse:\r\n v=[]\r\n v.append(k-int(n/2)+1)\r\n v.append(2*(k-int(n/2)+1))\r\n i=1\r\n while(len(v)1000000000):\r\n f=1\r\n print(-1)\r\n if(f==0):\r\n for i in v:\r\n print(i,end=\" \")\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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:\n\n1. Each domino completely covers two squares.\n\n2. No two dominoes overlap.\n\n3. Each domino lies entirely inside the board. It is allowed to touch the edges of the board.\n\nFind the maximum number of dominoes, which can be placed under these restrictions.",
"input": "",
"output": "```python\nm,n=input().split()\r\nm=int(m)\r\nn=int(n)\r\nif(1<=m and m<=n and n<=16):\r\n p=m*n\r\n t=p//2\r\n print(t)\r\nelse:\r\n print('Invalid Input')\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Dr. Moriarty is about to send a message to Sherlock Holmes. He has a string *s*. \n\nString *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\".\n\nDr. 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: \n - 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. \nMoriarty is very smart and after he chooses some substring *t*, he always makes the minimal number of changes to obtain *u*. \n\nHelp 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.",
"input": "",
"output": "```python\nprint(\"_RANDOM_GUESS_1689418688.3535597\")# 1689418688.3535807\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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. \n\nA sequence *a*1, *a*2, ..., *a**n*, consisting of *n* integers, is Hungry if and only if: \n - Its elements are in increasing order. That is an inequality *a**i*<=<<=*a**j* holds for any two indices *i*,<=*j* (*i*<=<<=*j*). - For any two indices *i* and *j* (*i*<=<<=*j*), *a**j* must not be divisible by *a**i*. \nIahub is in trouble, so he asks you for help. Find a Hungry sequence with *n* elements.",
"input": "",
"output": "```python\n# for _ in range(1,int(input())+1):\r\nn=int(input())\r\n # n,k=map(int,input().split()) \r\n # s=(input()) \r\n # a=list(map(int,input().split()))\r\narr=[True]*(10**7)\r\n# arr[0],arr[1]=True,True\r\nfor i in range(2,10**5):\r\n if arr[i]==True:\r\n print(i,end=\" \")\r\n n-=1\r\n if n==0:\r\n exit()\r\n for j in range(i*i,10**5+1,i):\r\n arr[j]=False\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Igor is in the museum and he wants to see as many pictures as possible.\n\nMuseum 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.\n\nAt 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.\n\nFor 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.",
"input": "",
"output": "```python\ndef dfs(x, y):\r\n vis[x][y] = True\r\n path.append((x, y))\r\n paintings = 0\r\n for dx, dy in ((-1, 0), (1, 0), (0, -1), (0, 1)):\r\n x1, y1 = x+dx, y+dy\r\n if x1 < 0 or x1 >= n or y1 < 0 or y1 >= m or vis[x1][y1]:\r\n continue\r\n if grid[x1][y1] == \"*\":\r\n paintings += 1\r\n else:\r\n vis[x1][y1] = True\r\n paintings += dfs(x1, y1)\r\n return paintings\r\n\r\nif __name__ == \"__main__\":\r\n n, m, k = map(int, input().split())\r\n grid = [input() for _ in range(n)]\r\n count = [[0 for _ in range(m)] for _ in range(n)]\r\n vis = [[False for _ in range(m)] for _ in range(n)]\r\n\r\n for i in range(n):\r\n for j in range(m):\r\n if not vis[i][j] and grid[i][j] != \"*\":\r\n path = list()\r\n paintings = dfs(i, j)\r\n for x, y in path:\r\n count[x][y] = paintings\r\n\r\n for _ in range(k):\r\n x, y = map(int, input().split())\r\n print(count[x-1][y-1])\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer.\n\nAt 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).\n\nIf 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.\n\nKay 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.",
"input": "",
"output": "```python\nn,x=map(int,input().split())\r\ncount=0\r\nfor i in range(0,n,1):\r\n s,c=map(str,input().split())\r\n c=int(c)\r\n if s=='+':\r\n x=x+c\r\n else:\r\n if x-c<0:\r\n count=count+1\r\n else:\r\n x=x-c\r\nprint(str(x)+\" \"+str(count))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "There exists an island called Arpa’s land, some beautiful girls live there, as ugly ones do.\n\nMehrdad 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*. \n\nMehrdad has become quite confused and wants you to help him. Please help, although it's a naive cheat.",
"input": "",
"output": "```python\nn=int(input())\r\nif n==0:\r\n print(1)\r\nelse:\r\n w=n%4\r\n if w==1:\r\n print(8)\r\n elif w==2:\r\n print(4)\r\n elif w==3:\r\n print(2)\r\n else:\r\n print(6)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Pig is visiting a friend.\n\nPig's house is located at point 0, and his friend's house is located at point *m* on an axis.\n\nPig can use teleports to move along the axis.\n\nTo 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.\n\nFormally, 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.\n\nDetermine if Pig can visit the friend using teleports only, or he should use his car.",
"input": "",
"output": "```python\nn,m = map(int,input().split())\r\nst = 0\r\na,b = map(int,input().split())\r\nif a != 0:\r\n print(\"NO\")\r\nelse:\r\n st = a\r\n end = b\r\n flag = True\r\n for i in range(n-1):\r\n a,b = map(int,input().split())\r\n if end>=m:\r\n break\r\n if end>=a:\r\n st = a\r\n end = b\r\n else:\r\n flag = False\r\n break\r\n if flag:\r\n print(\"YES\")\r\n else:\r\n print(\"NO\")\r\n \r\n \r\n \r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.",
"input": "",
"output": "```python\nfor _ in range(1):\r\n string = list(input())\r\n n = len(string)\r\n upperCase = 0\r\n lowerCase = 0\r\n for i in range(n):\r\n if string[i].isupper();\r\n upperCase += 1\r\n else:\r\n lowerCase += 1\r\n\r\n \r\n if upperCase <= lowerCase:\r\n print(string.lower()) \r\n\r\n else:\r\n print(string.upper())\r\n\r\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob.\n\nRight 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.\n\nLimak eats a lot and his weight is tripled after every year, while Bob's weight is doubled after every year.\n\nAfter how many full years will Limak become strictly larger (strictly heavier) than Bob?",
"input": "",
"output": "```python\nraj,shiv= list(map(int, input().split()))\r\nr = int()\r\nwhile raj 0:\r\n ai2[j] += 1\r\n temp2 -= 1\r\n j = (j+1)%14\r\n j = 0\r\n while j < 14:\r\n if ai2[j] % 2 == 0:\r\n tempans += ai2[j]\r\n j += 1\r\n ans = max(ans,tempans)\r\n i += 1\r\nprint(ans)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nString *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*.\n\nHelp the bear cope with the given problem.",
"input": "",
"output": "```python\ndef bear(s):\r\n\tb =0\r\n\tfor i in range(len(s)):\r\n\t\tc = s.find('bear' , i)\r\n\t\tif c >=0:\r\n\t\t\tb+=len(s)-c-3\r\n\treturn b\r\nif __name__ == '__main__':\r\n\ts = input()\r\n\tprint(bear(s))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.",
"input": "",
"output": "```python\ns = input()\r\nt = input()\r\ns = ' '.join(s)\r\ns = list(s.split())\r\ns.reverse()\r\nt = ' '.join(t)\r\nt = list(t.split())\r\nif s == t:\r\n print('YES')\r\nelse:\r\n print('NO')\r\n\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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*).\n - 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). \nAlternatively, 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*)?",
"input": "",
"output": "```python\nt, s_x, s_y, e_x, e_y = map(int, input().split())\ndirections = list(input())\n\nx_dir = e_x - s_x\ny_dir = e_y - s_y\n\nduration = 0\nreached = False\ncur_point = [s_x, s_y]\nfor d in directions:\n if x_dir == 0 and y_dir == 0:\n reached = True\n break\n if d == 'S' and y_dir<0:\n y_dir +=1\n elif d == \"N\" and y_dir > 0:\n y_dir -=1\n elif d == \"E\" and x_dir > 0:\n x_dir -=1\n elif d == 'W' and x_dir < 0:\n x_dir += 1\n duration += 1\n\nif not reached:\n print('-1')\nelse:\n print(duration)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nOne 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.\n\nIn 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.\n\nShapur 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.\n\nNow you are going to take part in Shapur's contest. See if you are faster and more accurate.",
"input": "",
"output": "```python\nnum1,num2 = input(),input()\r\nstr1 = ''\r\nfor i in range(0,len(num1)):\r\n if num1[i] != num2[i]:\r\n str1 += '1'\r\n else:\r\n str1 += '0'\r\nprint(str1)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Pig is visiting a friend.\n\nPig's house is located at point 0, and his friend's house is located at point *m* on an axis.\n\nPig can use teleports to move along the axis.\n\nTo 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.\n\nFormally, 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.\n\nDetermine if Pig can visit the friend using teleports only, or he should use his car.",
"input": "",
"output": "```python\n\nt, f = [int(x) for x in input().split()]\nl = []\nwhile(t):\n a, b = [int(x) for x in input().split()]\n l.append([a, b])\n t -= 1\nprev_a = 0\nprev_d = 0\nflag = \"NO\"\nfor point in l:\n if(prev_a == 0 and prev_d == 0):\n prev_a = point[0]\n prev_d = point[1]\n else:\n if(point[1] > prev_d and point[1] != f):\n prev_a = point[0]\n prev_d = point[1]\n elif(point[1] > prev_d and point[1] == f):\n if(point[0] >= prev_a and point[0] <= prev_d):\n flag = \"YES\"\n break\nprint(flag)\n\n\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "*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.",
"input": "",
"output": "```python\nn = int(input())\r\narr = list(map(int, input().split()))\r\npair = []\r\ndif = float(\"inf\")\r\nfor i in range(1, n):\r\n temp = abs(arr[i] - arr[i - 1])\r\n if temp < dif:\r\n dif = temp\r\n pair = [i, i+1]\r\nif abs(arr[0] - arr[-1]) < dif:\r\n pair = [n, 1]\r\nprint(*pair, sep=\" \")\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nYour 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.",
"input": "",
"output": "```python\nn = int(input())\n\ndef main():\n if n in [1, 2]:\n print(1)\n print(1)\n return\n elif n == 3:\n print(2)\n print(1, 3)\n return\n elif n == 4:\n print(3)\n print(1, 4, 2)\n return\n\n print(n)\n\n for i in range(1, n+1, 2):\n print(i, end=' ')\n\n for i in range(2, n+1, 2):\n print(i, end=' ')\n\nmain()\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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! \n\nMore 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*<=><=*c*, then everything on the screen disappears and after that the word you have typed appears on the screen.\n\nFor 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.\n\nYou're given the times when ZS the Coder typed the words. Determine how many words remain on the screen after he finished typing everything.",
"input": "",
"output": "```python\n\"\"\"\r\nhttps://codeforces.com/problemset/problem/716/A\r\n\"\"\"\r\n\r\ndef ints(inp):\r\n return list(map(int, inp.split()))\r\n\r\n\r\nw = list()\r\nn, c = ints(input())\r\nnums = ints(input())\r\nfor i in range(n - 1):\r\n if nums[i+1] - nums[i] <= c:\r\n w.append(nums[i+1])\r\n w.append(nums[i])\r\n else:\r\n w.clear()\r\n \r\nprint(len(set(w)))\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.",
"input": "",
"output": "```python\nimport functools\r\n\r\nclass Point:\r\n def __init__(self, x, y):\r\n self.x = x\r\n self.y = y\r\n\r\n def area_triangle(self, p1, p2):\r\n vector_1 = [p1.x - self.x, p1.y - self.y]\r\n vector_2 = [p2.x - self.x, p2.y - self.y]\r\n return vector_1[0] * vector_2[1] - vector_1[1] * vector_2[0]\r\n\r\nclass NumberTriangles: \r\n def solution(self):\r\n num_points = int(input())\r\n points = []\r\n for _ in range(num_points):\r\n point = input()\r\n point = point.split(\" \")\r\n points.append(Point(int(point[0]), int(point[1])))\r\n\r\n num_triangles = 0\r\n for i in range(num_points):\r\n for j in range(i + 1, num_points):\r\n for k in range(j + 1, num_points):\r\n area = points[i].area_triangle(points[j], points[k])\r\n if area != 0:\r\n num_triangles += 1\r\n \r\n print(num_triangles)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n num_triangles = NumberTriangles()\r\n num_triangles.solution()\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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. \n\nValera 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. \n\nHelp Valera count the minimum number of cashes to work at his cafe next day, so that they can serve all visitors.",
"input": "",
"output": "```python\nt=int(input())\r\ncount=1\r\na=-1\r\nb=-1\r\nfor i in range(t):\r\n n=int(input())\r\n m=int(input())\r\n if n==a and m==b:\r\n count=count+1\r\n a=n\r\n b=m\r\nprint(count)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "\"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.\n\nA 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.",
"input": "",
"output": "```python\nn,k=map(int,input().split())\r\nx=list(input().split())\r\nmw=0\r\n\r\nfor i in range(0,n):\r\n a=x[i]\r\n if a=='0':\r\n break\r\n if i\r\n#define mem(a,b) memset(a,b,sizeof a);\r\n#define rep(i,a,b) for(int i = a; i <= b; i++)\r\n#define per(i,a,b) for(int i = a; i >= b; i--)\r\n#define __ ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)\r\ntypedef long long ll;\r\ntypedef double db;\r\nconst int inf = 1e8;\r\nconst int N = 5e5+10;\r\nconst db EPS = 1e-9;\r\nusing namespace std;\r\n\r\nvoid dbg() {cout << \"\\n\";}\r\ntemplate void dbg(T a, A... x) {cout << a << ' '; dbg(x...);}\r\n#define logs(x...) {cout << #x << \" -> \"; dbg(x);}\r\n\r\nint n,a[N],tot,head[N],sz[N],son[N],f[1<<22],dep[N],ans[N]; //f[i]:表示子树中异或和为f[i]的最大深度\r\nstruct Node{\r\n int to,next;\r\n}e[N];\r\n\r\nvoid add(int x,int y){\r\n e[++tot].to = y, e[tot].next = head[x], head[x] = tot;\r\n}\r\n\r\nvoid dfs1(int x){\r\n ans[x] = -inf; sz[x] = 1;\r\n for(int i = head[x]; i; i = e[i].next){\r\n int y = e[i].to;\r\n dep[y] = dep[x]+1; a[y] ^= a[x];\r\n dfs1(y); sz[x] += sz[y];\r\n if(sz[y] > sz[son[x]]) son[x] = y;\r\n }\r\n}\r\n\r\nvoid Delete(int x){\r\n f[a[x]] = -inf;\r\n for(int i = head[x]; i; i = e[i].next) Delete(e[i].to);\r\n}\r\n\r\nvoid modify(int x,int fa){\r\n ans[fa] = max(ans[fa],f[a[x]]+dep[x]-2*dep[fa]);\r\n for(int i = 0; i < 22; i++)\r\n ans[fa] = max(ans[fa],f[a[x]^(1<1 and ilc):\r\n print(n.upper())\r\nelse:\r\n print(n.lower())\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer.\n\nAt 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).\n\nIf 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.\n\nKay 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.",
"input": "",
"output": "```python\nn, ans = map(int, input().split())\r\nd = 0\r\nfor i in range(n):\r\n p = input()\r\n if \"+ \" in p:\r\n p = p.replace(\"+ \", \"\")\r\n ans += int(p)\r\n else:\r\n p = p.replace(\"- \", \"\")\r\n p = int(p)\r\n if ans >= p:\r\n ans -= p\r\n else:\r\n d += 1\r\nprint(ans, d)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nA 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}$.\n\nAnna 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.\n\nSome time ago Ann read the word $s$. What is the word she changed it into?",
"input": "",
"output": "```python\nimport re\r\nimport sys\r\ns=input()\r\nif s==s[::-1]:\r\n s=s.replace(s[-1],\"\",1)\r\n if s==s[::-1]:\r\n print(\"0\")\r\n else:\r\n print(len(s))\r\nelse:\r\n print(len(s))\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nOne 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.\n\nIn 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.\n\nShapur 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.\n\nNow you are going to take part in Shapur's contest. See if you are faster and more accurate.",
"input": "",
"output": "```python\nnum1=input()\r\nnum2=input()\r\nfor i in range(0,len(num1)):\r\n if(num1[i]==num2[i]):print(0,end='')\r\n else:print(1,end='')\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nOverall 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.",
"input": "",
"output": "```python\nn,m=map(int,input().split())\r\nl=list(map(int,input().split()))\r\na=[]\r\nfor i in range(m):\r\n x=list(map(int,input().split()))\r\n a.append(x)\r\nif m==2:\r\n print(-1)\r\nelse:\r\n r=[]\r\n for i in range(len(a)):\r\n for j in range(i+1,len(a)):\r\n for k in range(j+1,len(a)):\r\n q=list(set(a[i])|set(a[j])|set(a[k]))\r\n if q not in r and len(q)==3:\r\n r.append(q)\r\n if len(r)==0:\r\n print(-1)\r\n else:\r\n t=[]\r\n for i in r:\r\n s=0\r\n for j in i:\r\n s=s+l[j-1]\r\n t.append(s)\r\n print(min(t))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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*<=<<=*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. \n\nHelp the children and tell them how to form the line.",
"input": "",
"output": "```python\nnm = input(\"\").split(\" \")\r\nnm = [int(x) for x in nm]\r\nn, m = nm\r\nfinalString = \"\"\r\nif n > m:\r\n for item in range(m):\r\n finalString += \"BG\"\r\n for item in range(n-m):\r\n finalString += \"B\"\r\nelse:\r\n for item in range(n):\r\n finalString += \"GB\"\r\n for item in range(m-n):\r\n finalString += \"G\"\r\nprint(finalString)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nBut 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.\n\nYakko 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.\n\nIt 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.",
"input": "",
"output": "```python\nfrom fractions import Fraction\r\nYakko, Wakko = input().split()\r\nYakko = int(Yakko)\r\nWakko = int(Wakko)\r\nmax_v = max(Yakko, Wakko)\r\n\r\nDie_Roll = 6 - max_v + 1\r\n\r\nfor i in range(6, 0, -1):\r\n if(Yakko == 1 and Wakko == 1):\r\n print(str(Yakko) + \"/\" + str(Wakko))\r\n break\r\n elif(Die_Roll == 5):\r\n print(Fraction(Die_Roll / i).limit_denominator())\r\n break\r\n elif(Die_Roll == 4):\r\n print(Fraction(Die-Roll / i).limit_denominator())\r\n break\r\n elif(i % Die_Roll == 0):\r\n print(Fraction(Die_Roll / i).limit_denominator())\r\n break\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nOne 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.\n\nFind the volume fraction of orange juice in the final drink.",
"input": "",
"output": "```python\nt=int(input())\r\nx=list(map(int,input().split()))\r\nb=sum(x)\r\na=len(x)\r\nc=\"{:.12f}\".format(b/a)\r\nprint(c)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nIn 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. \n\nFor 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.\n\nTo graduate with «A» certificate, Noora has to have mark *k*.\n\nNoora 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*.",
"input": "",
"output": "```python\nimport math\r\nn, k = map(int, input().split())\r\namt = 0\r\nnums = [int(x) for x in input().split()]\r\namt = sum(nums)\r\nans = 2*n*k - n - 2*amt\r\nprint(math.ceil(ans) if ans >=0 else 0)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "The New Year is coming! That's why many people today are busy preparing New Year presents. Vasily the Programmer is no exception.\n\nVasily 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.\n\nVasily 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.\n\nVasily 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.",
"input": "",
"output": "```python\nimport sys\r\ninput = sys.stdin.readline\r\n\r\nn = int(input())\r\nw = list(map(int, input().split()))\r\n\r\nd = ''\r\nfor i in range(n-1):\r\n d += 'PRL'*w[i]\r\n d += 'R'\r\n\r\nd += 'PLR'*w[-1]\r\nprint(d)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nSereja and Dima are being greedy. Each of them chooses the card with the larger number during his move.\n\nInna 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.",
"input": "",
"output": "```python\nn=int(input())\na=list(map(int,input().split()))\ns=0\nd=0\nfor i in range(n):\n\tb=max(a[0],a[-1])\n\tif i%2==0:\n\t\ts+=b\n\telse:\n\t\td+=b\t\n\ta.remove(b)\nprint(s,d)\n \t\t \t\t \t \t \t\t \t\t \t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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. \n\nValue 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.",
"input": "",
"output": "```python\nclass MarvoloGauntRing:\r\n def __init__(self, p, q, r, arr):\r\n self.arr = arr\r\n self.p = p\r\n self.q = q\r\n self.r = r\r\n \r\n def give_x_potions(self):\r\n p_max = self.prefix_max()\r\n print(p_max)\r\n \r\n s_max = self.sufix_max()\r\n print(s_max)\r\n \r\n x = float('-inf')\r\n \r\n for i in range(0, len(self.arr)):\r\n x = max(x, p_max[i] + self.q * self.arr[i] + s_max[i])\r\n \r\n return x\r\n \r\n def prefix_max(self):\r\n \r\n p_max = [0]*len(self.arr)\r\n p_max[0] = self.arr[0] * self.p \r\n \r\n for i in range(1, len(self.arr)):\r\n p_max[i] = max(p_max[i-1], self.p * self.arr[i])\r\n \r\n return p_max\r\n \r\n def sufix_max(self):\r\n \r\n s_max = [0]*len(self.arr)\r\n s_max[len(self.arr)-1] = self.arr[len(self.arr)-1] * self.r \r\n \r\n for i in range(len(self.arr)-2, -1, -1):\r\n s_max[i] = max(s_max[i+1], self.r * self.arr[i])\r\n \r\n return s_max\r\n \r\n \r\n \r\nn,p,q,r = map(int, input().split())\r\narr = list(map(int, input().split()))\r\n\r\nprint(MarvoloGauntRing(p,q,r, arr).give_x_potions())\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nHamed didn't pay much attention to the class since he was watching a movie. He only managed to understand the definitions of these equations.\n\nNow 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.",
"input": "",
"output": "```python\na, b = map(int, input().split(\" \"))\na1 = a - b\nif a == b:\n print(\"infinity\")\nelse:\n cont = 0\n i = 1\n while i ** 2 <= a1:\n if a1 % i == 0 and i > b: cont += 1\n if a1 % i == 0 and b < a1 // i != i: cont += 1\n i += 1\n print(cont)\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nEach 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.\n\nGiven the text on the front page of the newspaper, can you tell how many Bulbasaurs he will catch today?\n\nNote: uppercase and lowercase letters are considered different.",
"input": "",
"output": "```python\ns = input()\r\nb1 = u = b = l = a = s1 = u = r = 0\r\nfor i in range(len(s)):\r\n if s[i] == 'B':\r\n b1 +=1\r\n if s[i] == 'u':\r\n u +=1\r\n if s[i] == 'l':\r\n l +=1\r\n if s[i] == 'b':\r\n b +=1\r\n if s[i] == 'a':\r\n a +=1\r\n if s[i] == 's':\r\n s1 +=1\r\n if s[i] == 'r':\r\n r +=1\r\na = a//2\r\nu = u//2\r\nprint (min(b1,u,b,l,a,s1,u,r))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nValera 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. \n\nPrint the maximum number of books Valera can read.",
"input": "",
"output": "```python\nn,t=map(int,input().split())\r\nm=list(map(int,input().split()))\r\na=-1\r\nfor i in range(len(m)):\r\n\r\n count=0\r\n sum=0\r\n while(i<=len(m)-1 and (sum+m[i])<=t):\r\n sum=sum+m[i]\r\n count=count+1\r\n i=i+1\r\n if(count>a):\r\n a=count\r\nprint(a)\r\n\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Do you remember a kind cartoon \"Beauty and the Beast\"? No, no, there was no firing from machine guns or radiation mutants time-travels!\n\nThere 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... \n\nEverybody 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.\n\nDue 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. \n\nFortunately, 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.\n\nYou can only rotate the hands forward, that is, as is shown in the picture: \n\nAs since there are many ways too select such angles because of full rotations, choose the smallest angles in the right (non-negative) direction.\n\nNote 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.",
"input": "",
"output": "```python\ntime = input()\r\nh = int(time[0])*10 + int(time[1])\r\nm = int(time[3])*10 + int(time[4])\r\nh = h % 12\r\nangle1 = h*30 + m//2\r\nif m%2 == 1:\r\n angle1 += 0.5\r\nangle2 = m*6\r\nprint(angle1, angle2)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nFor example, *Perm*(0)<==<=(0,<=1,<=...,<=*n*<=-<=2,<=*n*<=-<=1), *Perm*(*n*!<=-<=1)<==<=(*n*<=-<=1,<=*n*<=-<=2,<=...,<=1,<=0)\n\nMisha has two permutations, *p* and *q*. Your task is to find their sum.\n\nPermutation *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*<=<<=*b**k*.",
"input": "",
"output": "```python\nnum=1\r\nfor i in range(1, 200001):num*=i\r\nprint(\"Done\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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. \n\nPolycarp 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.\n\nYou are given an encoding *s* of some word, your task is to decode it.",
"input": "",
"output": "```python\nl=int(input())\r\nstr=input()\r\nstr1=\"\"\r\nlst=list(str)\r\nwhile len(lst)>=3:\r\n if l%2==0:\r\n str1+=lst[(l//2)-1]\r\n lst.pop((l//2)-1]\r\n else:\r\n str1+=lst[l//2]\r\n lst.pop((l//2))\r\nstr1+=lst[0]+lst[1]\r\nprint(str1)\r\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Do you know a story about the three musketeers? Anyway, you will learn about its origins now.\n\nRichelimakieu 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.\n\nThere 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.\n\nHelp Richelimakieu! Find if it is possible to choose three musketeers knowing each other, and what is minimum possible sum of their recognitions.",
"input": "",
"output": "```python\ndef dfs(knights,k,st,cycle,limit=2):\n if limit == 0:\n if st not in knights[k]:\n return\n total=0\n for k in cycle:\n total+=len(knights[k])-2\n cycles.append(total)\n return\n for i in knights[k]:\n cycle.append(i)\n dfs(knights,i,st,cycle,limit-1)\n cycle.pop(-1)\n\n \n\nn,m=map(int,input().split())\nknights={str(i):[] for i in range(1,n+1)}\nfor _ in range(m):\n key,value=input().split()\n knights[key].append(value)\n knights[value].append(key)\ncycles=[]\nfor k in knights:\n dfs(knights,k,k,[k])\nprint(min(cycles) if cycles else -1)\n\t\t \t \t \t \t\t\t \t\t\t\t\t \t\t\t \t\t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nPete 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.",
"input": "",
"output": "```python\nn = int(input())\r\nif n%2==0 and n>=2:print(\"Yes\")\r\nelse:print(\"No\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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:\n\nTogether 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\":\n\nMike 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?",
"input": "",
"output": "```python\n# LUOGU_RID: 101608072\n_, s = input(), input()\r\nprint(all(set(t) & set(s) for t in '0147 0369 079 123'.split()) and 'YES' or 'NO')\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nAssuming 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.",
"input": "",
"output": "```python\nv1,v2 = map(int,input().split())\nt,d = map(int,input().split())\nif v1>v2:\n z = v1\n v1 = v2\n v2 = z\nans = v1\ncur = v1\nfor i in range(2,t+1):\n temp = (t-i)*d\n f = 0\n for j in range(d,-1,-1):\n if abs((cur+j)-v2)<=temp:\n f=1\n cur += j\n ans+=cur\n break\n #print(cur,ans,i)\n if f==0:\n req = cur-v2\n z = i\n if (req%d)!=0:\n cur-=(req%d)\n z = i+1\n ans+=cur\n for j in range(z,t+1):\n cur-=d\n if cur>=v2:\n ans+=cur\n else:\n ans+=v2\n break\n#print(j)\nprint(ans)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are given an array *a* with *n* elements. Each element of *a* is either 0 or 1.\n\nLet'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*).",
"input": "",
"output": "```python\ndef maximize_subsegment_length(n, k, a):\n left = 0\n right = 0\n max_length = 0\n max_zeros = k\n best_left = 0\n best_right = 0\n\n while right < n:\n if a[right] == 0:\n max_zeros -= 1\n\n while max_zeros < 0:\n if a[left] == 0:\n max_zeros += 1\n left += 1\n\n if right - left + 1 > max_length:\n max_length = right - left + 1\n best_left = left\n best_right = right\n\n right += 1\n\n for i in range(best_left, best_right + 1):\n a[i] = 1\n\n print(max_length)\n print(*a)\n\n# Read input\nn, k = map(int, input().split())\na = list(map(int, input().split()))\n\n# Call the function\nmaximize_subsegment_length(n, k, a)\n\n\t \t\t \t\t\t \t\t \t\t\t\t\t\t \t \t\t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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). \n\nYour task is to determine by the given *a*, *b* and *n* who wins the game.",
"input": "",
"output": "```python\nimport math\r\n\r\ntest_case=input().split(' ')\r\n\r\n\r\ndef heap_left(fixed,gcd):return gcd-math.gcd(fixed,gcd)\r\n\r\n\r\ndef assignment(p1,p2,n):\r\n list=[int(n)]\r\n flag=int(n)\r\n count=0\r\n while flag!=0:\r\n if count%2==0:flag=heap_left(int(p1),list[count]);list.append(heap_left(int(p1),list[count]))\r\n else:flag=heap_left(int(p2),list[count]);list.append(heap_left(int(p2),list[count]))\r\n count+=1\r\n\r\n if len(list)%2==0:print(0)\r\n else:print(1)\r\n\r\n\r\n\r\n\r\n\r\n\r\nif __name__==\"__main__\":\r\n assignment(test_case[0],test_case[1],test_case[2])\r\n #print(test_case[0],test_case[1],)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.",
"input": "",
"output": "```python\ns=input()\r\nlow=0\r\nupp=0\r\nfor i in s:\r\n if i==i.upper():\r\n upp=upp+1\r\n else:\r\n low=low+1\r\nif upp>low:\r\n print(s.upper())\r\nelse:\r\n print(s.lower())\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nNow 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.\n\nPearlo 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.",
"input": "",
"output": "```python\na = input()\nb = input()\nc = input()\n\ns = a+b+c\n\nif s == s[::-1]:\n print(\"YES\")\nelse:\n print(\"NO\")\n\n \t \t\t\t\t \t \t\t\t\t \t\t\t\t\t\t\t \t\t\t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nPatrick 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.\n\nTo 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.",
"input": "",
"output": "```python\nimport sys, os, io\r\ninput = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline\r\n\r\ns = list(input().rstrip())\r\ncnt = [0]\r\nfor i in s:\r\n cnt.append(cnt[-1] + i // 97)\r\nn = len(s)\r\nans = n\r\nfor i in range(n + 1):\r\n u, v = cnt[i], n - i - (cnt[n] - cnt[i])\r\n ans = min(ans, u + v)\r\nprint(ans)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nThe 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.\n\nAs 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().",
"input": "",
"output": "```python\n# LUOGU_RID: 126991992\na=input().lstrip('0');b=input().lstrip()\nif len(a)>len(b):print('>')\nelif len(a)b:print('>')\nelif a=0:\r\n if arr[i]= 0 and board[i-1][j] == board[i][j]:\r\n return False\r\n if i+1 < len(board) and board[i+1][j] == board[i][j]:\r\n return False\r\n if j-1 >= 0 and board[i][j-1] == board[i][j]:\r\n return False\r\n if j+1 < len(board[i]) and board[i][j+1] == board[i][j]:\r\n return False\r\n \r\n return True\r\n\r\ndef make_a_copy(board):\r\n result = []\r\n for i in board:\r\n r = []\r\n for j in i:\r\n r.append(j)\r\n result.append(r)\r\n return result\r\n\r\ndef print_board(board):\r\n for row in board:\r\n result = ''\r\n for element in row:\r\n result += element\r\n print(result)\r\n\r\ndef all_binary_combinations(k, arr, i, solution_space):\r\n if i == k:\r\n solution_space.append(arr.copy())\r\n else: \r\n arr[i] = False\r\n all_binary_combinations(k, arr, i + 1, solution_space)\r\n arr[i] = True\r\n all_binary_combinations(k, arr, i + 1, solution_space)\r\n\r\ndef main():\r\n size = input().split()\r\n n = int(size[0])\r\n m = int(size[1])\r\n\r\n board = []\r\n white_places = []\r\n\r\n for i in range(n):\r\n board.append(list(input().replace('.', 'B')))\r\n \r\n for i in range(n):\r\n for j in range(m):\r\n if board[i][j] == 'B':\r\n white_places.append((i, j))\r\n \r\n solution_space = []\r\n k = len(white_places)\r\n arr = [None] * k\r\n all_binary_combinations(k, arr, 0, solution_space)\r\n \r\n solutions = []\r\n \r\n for possible_solution in solution_space:\r\n board_copy = board.copy()\r\n for i, val in enumerate(possible_solution):\r\n if val:\r\n board_copy[white_places[i][0]][white_places[i][1]] = 'W'\r\n \r\n if is_valid(board_copy):\r\n print_board(board)\r\n return\r\n \r\n\r\nmain()\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vadim is really keen on travelling. Recently he heard about kayaking activity near his town and became very excited about it, so he joined a party of kayakers.\n\nNow the party is ready to start its journey, but firstly they have to choose kayaks. There are 2·*n* people in the group (including Vadim), and they have exactly *n*<=-<=1 tandem kayaks (each of which, obviously, can carry two people) and 2 single kayaks. *i*-th person's weight is *w**i*, and weight is an important matter in kayaking — if the difference between the weights of two people that sit in the same tandem kayak is too large, then it can crash. And, of course, people want to distribute their seats in kayaks in order to minimize the chances that kayaks will crash.\n\nFormally, the instability of a single kayak is always 0, and the instability of a tandem kayak is the absolute difference between weights of the people that are in this kayak. Instability of the whole journey is the total instability of all kayaks.\n\nHelp the party to determine minimum possible total instability!",
"input": "",
"output": "```python\ndef work():\n diffs = sorted([weight[i]-weight[i-1] for i in range(1, len(weight), 2)])\n sep_diffs = sorted([weight[i]-weight[i-1] for i in range(2, len(weight), 2)])\n diffs.pop()\n print(min(sum(diffs), sum(sep_diffs)))\n\n\nn = int(input())\nweight = sorted([int(i) for i in input().strip().split()])\nwork()\n# for i in range(10)\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "As you very well know, this year's funkiest numbers are so called triangular numbers (that is, integers that are representable as , where *k* is some positive integer), and the coolest numbers are those that are representable as a sum of two triangular numbers.\n\nA well-known hipster Andrew adores everything funky and cool but unfortunately, he isn't good at maths. Given number *n*, help him define whether this number can be represented by a sum of two triangular numbers (not necessarily different)!",
"input": "",
"output": "```python\ndef triangular(num):\n # Funcion para ver si es triangular o no el numero\n n = 1\n while num > 0:\n num -= n\n n += 1\n return num == 0\n\ndef suma_triangulres(n):\n for t1 in range(1, n + 1):\n # Funcion para revisar que t1 sea triangular\n if triangular(t1):\n diff = n - t1\n # Funcion para revisar si la diferencia tambien es triangular\n if triangular(diff):\n return \"YES\"\n return \"NO\"\n\nn = int(input())\nresult = suma_triangulres(n)\nprint(result)\n\t \t \t\t \t \t\t\t \t\t \t\t\t \t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "There is a given string *S* consisting of *N* symbols. Your task is to find the number of ordered pairs of integers *i* and *j* such that\n\n1. 1<=≤<=*i*,<=*j*<=≤<=*N*\n\n2. *S*[*i*]<==<=*S*[*j*], that is the *i*-th symbol of string *S* is equal to the *j*-th.",
"input": "",
"output": "```python\nS=input()\nd={}\ncnt=0\nfor i in S:\n d[i]=d.get(i,0)+1\nfor i in S:\n cnt+=d.get(i,0)\nprint(cnt)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Recently Luba bought a very interesting book. She knows that it will take *t* seconds to read the book. Luba wants to finish reading as fast as she can.\n\nBut she has some work to do in each of *n* next days. The number of seconds that Luba has to spend working during *i*-th day is *a**i*. If some free time remains, she can spend it on reading.\n\nHelp Luba to determine the minimum number of day when she finishes reading.\n\nIt is guaranteed that the answer doesn't exceed *n*.\n\nRemember that there are 86400 seconds in a day.",
"input": "",
"output": "```python\nn,t = map(int,input().split())\r\nd = [*((86400-int(x)) for x in input().split())]\r\ncnt = 0\r\ni = 0\r\nwhile cnt < t:\r\n cnt += d[i]\r\n i += 1\r\nprint(i)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Sereja has an array *a*, consisting of *n* integers *a*1, *a*2, ..., *a**n*. The boy cannot sit and do nothing, he decided to study an array. Sereja took a piece of paper and wrote out *m* integers *l*1,<=*l*2,<=...,<=*l**m* (1<=≤<=*l**i*<=≤<=*n*). For each number *l**i* he wants to know how many distinct numbers are staying on the positions *l**i*, *l**i*<=+<=1, ..., *n*. Formally, he want to find the number of distinct numbers among *a**l**i*,<=*a**l**i*<=+<=1,<=...,<=*a**n*.?\n\nSereja wrote out the necessary array elements but the array was so large and the boy was so pressed for time. Help him, find the answer for the described question for each *l**i*.",
"input": "",
"output": "```python\n\"\"\"n,m=map(int,input().split())\r\nA=list(map(int,input().split()))\r\nB=list(map(int,input().split()))\r\ni=1\r\ns=0\r\nfor tot_num in B:\r\n tot_num-=s\r\n while i<=n:\r\n if tot_num<=A[i-1]:\r\n j=tot_num\r\n break\r\n else:\r\n tot_num-=A[i-1] \r\n s+=A[i-1]\r\n i+=1\r\n print(i,j)\r\n\r\n\r\n\r\n#from collections import Counter\r\nn,m=map(int,input().split())\r\nA=list(map(int,input().split()))\r\nfor _ in range(m):\r\n #C=[]\r\n #j=0\r\n l=int(input())\r\n #print(len(Counter(A[l-1:])))\r\n #for i in range(l-1,n):\r\n # if A[i] not in C:\r\n # C.append(A[i])\r\n # j+=1\r\n #print(len(set(A[l-1:])))\r\n\r\n\r\nn,m=map(int,input().split())\r\nA=list(map(int,input().split()))\r\nB=[]\r\nfor _ in range(m):\r\n B.append(int(input()))\r\n\r\n#D=sorted(B,reverse=True)\r\nd=[0]*m\r\nC=[]\r\nj=0\r\ni=n-1\r\n#for l in D:\r\nfor king in range(m): #l is B[-king-1]\r\n while i>=B[-king-1]-1:\r\n if A[i] not in C:\r\n C.append(A[i])\r\n j+=1\r\n i-=1\r\n d[-king-1]=j\r\nfor l in d:\r\n print(l)\"\"\"\r\n\r\n\r\n\r\n# Read input values\r\nn, m = map(int, input().split())\r\narray = list(map(int, input().split()))\r\n\r\nqueries = []\r\nfor _ in range(m):\r\n queries.append(int(input()))\r\nans=[]\r\n\r\nd=set()\r\nfor i in range(n):\r\n d.add(array[-i-1])\r\n ans.append(len(d))\r\nfor l in queries:\r\n print(ans[-l])\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A recently found Ancient Prophesy is believed to contain the exact Apocalypse date. The prophesy is a string that only consists of digits and characters \"-\".\n\nWe'll say that some date is mentioned in the Prophesy if there is a substring in the Prophesy that is the date's record in the format \"dd-mm-yyyy\". We'll say that the number of the date's occurrences is the number of such substrings in the Prophesy. For example, the Prophesy \"0012-10-2012-10-2012\" mentions date 12-10-2012 twice (first time as \"0012-10-2012-10-2012\", second time as \"0012-10-2012-10-2012\").\n\nThe date of the Apocalypse is such correct date that the number of times it is mentioned in the Prophesy is strictly larger than that of any other correct date.\n\nA date is correct if the year lies in the range from 2013 to 2015, the month is from 1 to 12, and the number of the day is strictly more than a zero and doesn't exceed the number of days in the current month. Note that a date is written in the format \"dd-mm-yyyy\", that means that leading zeroes may be added to the numbers of the months or days if needed. In other words, date \"1-1-2013\" isn't recorded in the format \"dd-mm-yyyy\", and date \"01-01-2013\" is recorded in it.\n\nNotice, that any year between 2013 and 2015 is not a leap year.",
"input": "",
"output": "```python\np=input()\ndata={}\nfor i in range(len(p)-9):\n if p[i+2] == p[i+5] and (p[i+6:i+10]).isdecimal():\n print(p[i:i+10])\n if p[i:i+10] in data:\n data[p[i:i+10]]+=1\n else:\n data[p[i:i+10]]=1\n\n\nmax_item=None\nmaximum=0\n\nfor i in data.keys():\n if data[i] > maximum:\n maximum = data[i]\n max_item=i\n\n\nprint(max_item)\n\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.\n\nThere are *n* trees located along the road at points with coordinates *x*1,<=*x*2,<=...,<=*x**n*. Each tree has its height *h**i*. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [*x**i*<=-<=*h**i*,<=*x**i*] or [*x**i*;*x**i*<=+<=*h**i*]. The tree that is not cut down occupies a single point with coordinate *x**i*. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.",
"input": "",
"output": "```python\nn=int(input())\r\ns=[[int(x) for x in input().split( )] for i in range(n)]\r\ncount=2\r\n\r\nif n == 1:\r\n print('1')\r\nif n!= 1:\r\n for j in range(1,n-1):\r\n if s[j][0]-s[j-1][0] > s[j][1]:\r\n count+=1\r\n elif s[j+1][0]-s[j][0] > s[j][1]:\r\n count+=1\r\n s[j][0]+=s[j][1]\r\n\r\n print(count)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Sometimes some words like \"localization\" or \"internationalization\" are so long that writing them many times in one text is quite tiresome.\n\nLet's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.\n\nThis abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.\n\nThus, \"localization\" will be spelt as \"l10n\", and \"internationalization» will be spelt as \"i18n\".\n\nYou are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.",
"input": "",
"output": "```python\nimport math\nimport sys\nimport collections\n\nn = int(input())\n\ndef solve():\n s = input()\n if len(s) < 10:\n print(s)\n return\n res = ''\n dig = str(len(s) - 2)\n res += s[0] + dig + s[len(s) - 1]\n print(res)\n\nfor _ in range(n):\n solve()\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Jzzhu has picked *n* apples from his big apple tree. All the apples are numbered from 1 to *n*. Now he wants to sell them to an apple store. \n\nJzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be greater than 1. Of course, each apple can be part of at most one group.\n\nJzzhu wonders how to get the maximum possible number of groups. Can you help him?",
"input": "",
"output": "```python\n#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\nfrom math import *\r\ndef prm(x):\r\n s = int(sqrt(x+0.5))\r\n for i in range(2, s+1):\r\n if not (x%i): return False\r\n return True\r\ndef ap(a):\r\n while(len(a) >= 2):\r\n print(a[-1], a[-2])\r\n a.pop()\r\n a.pop()\r\nn, cnt, ans, vis, ansl, ansr = int(input()), 0, 0, [False]*100100, [], []\r\nprime = filter(prm, range(3, n//2+1))\r\nfor x in prime:\r\n tcnt, nlst = 0, []\r\n for i in range(1, n//x+1):\r\n if not vis[i*x]:\r\n vis[i*x] = True\r\n nlst.append(i)\r\n tcnt += 1\r\n ans += tcnt >> 1\r\n cnt += tcnt & 1\r\n if tcnt & 1 :\r\n nlst = nlst[0:1] + nlst[2:]\r\n ansr.append(x<<1)\r\n ansl += list(map(lambda k : x*k, nlst))\r\nfor i in range(1, n+1):\r\n if not vis[i] and not (i&1):\r\n ansr.append(i)\r\n cnt += 1\r\nprint(ans+(cnt>>1))\r\nap(ansl)\r\nap(ansr)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "$k$ people want to split $n$ candies between them. Each candy should be given to exactly one of them or be thrown away.\n\nThe people are numbered from $1$ to $k$, and Arkady is the first of them. To split the candies, Arkady will choose an integer $x$ and then give the first $x$ candies to himself, the next $x$ candies to the second person, the next $x$ candies to the third person and so on in a cycle. The leftover (the remainder that is not divisible by $x$) will be thrown away.\n\nArkady can't choose $x$ greater than $M$ as it is considered greedy. Also, he can't choose such a small $x$ that some person will receive candies more than $D$ times, as it is considered a slow splitting.\n\nPlease find what is the maximum number of candies Arkady can receive by choosing some valid $x$.",
"input": "",
"output": "```python\ns = list(map(int, input().split()))\nn=int(s[0])\nk=int(s[1])\nm=int(s[2])\nd=int(s[3])\nans=int(0)\nfor i in range(1,d+1):\n if (n-1)/k < (i-1):\n break\n op=k*(i-1)+1\n ans=max(ans,min(m,n/op)*i)\nprint(int(ans))\n\t \t\t \t\t \t \t \t\t \t \t \t\t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Polycarp has created his own training plan to prepare for the programming contests. He will train for $n$ days, all days are numbered from $1$ to $n$, beginning from the first.\n\nOn the $i$-th day Polycarp will necessarily solve $a_i$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.\n\nDetermine the index of day when Polycarp will celebrate the equator.",
"input": "",
"output": "```python\ndays = int(input())\r\nproblems = list(map(int, input().split()))\r\nsumma = sum(problems)\r\nif summa % 2 == 0:\r\n half_sum = summa // 2\r\nelse:\r\n half_sum = summa // 2 + 1\r\nproblems_sum = 0\r\ni = 0\r\nwhile problems_sum < half_sum:\r\n problems_sum += problems[i]\r\n i += 1\r\nprint(i)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nYou 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.\n\nYou 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.\n\nYou are given the text of the lecture the professor is going to read. Find out how the lecture will be recorded in your notes.",
"input": "",
"output": "```python\nn,m = [int(x) for x in input().split()]\r\nwords = {}\r\nfor i in range(m):\r\n word = input().split()\r\n words[word[0]] = word[0] if len(word[0]) < len(word[1]) else word[1]\r\n\r\nlecture = input().split()\r\nnote = \"\"\r\nfor word in lecture:\r\n note += words[word] + \" \"\r\nprint(note[:-1])\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nAnton 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.\n\nAnton has written a program that analyses contest results and determines whether he performed good or not. Are you able to do the same?",
"input": "",
"output": "```python\n\r\nimport sys,bisect\r\n\r\nfrom sys import stdin,stdout\r\n\r\nfrom bisect import bisect_left,bisect_right,bisect,insort,insort_left,insort_right\r\n\r\nfrom math import gcd,ceil,floor,sqrt\r\n\r\nfrom collections import Counter,defaultdict,deque,OrderedDict\r\n\r\nfrom queue import Queue,PriorityQueue\r\n\r\nfrom string import ascii_lowercase\r\n\r\nfrom heapq import *\r\n\r\nfrom itertools import islice\r\n\r\n\r\nsys.setrecursionlimit(10**6)\r\nINF = float('inf')\r\nMOD = 998244353\r\nmod = 10**9+7\r\n\r\ndef isPrime(n):\r\n if (n <= 1) :return False\r\n if (n <= 3) :return True\r\n if (n%2 == 0 or n%3 == 0):return False\r\n for i in range(5,ceil(sqrt(n))+1,6):\r\n if (n%i==0 or n%(i+2)==0):\r\n return False\r\n return True\r\n\r\ndef st():\r\n return list(stdin.readline().strip())\r\n\r\ndef inp():\r\n return int(stdin.readline())\r\n\r\ndef li():\r\n return list(map(int,stdin.readline().split()))\r\n\r\ndef mp():\r\n return map(int,stdin.readline().split())\r\n\r\ndef pr(n):\r\n stdout.write(str(n)+\"\\n\")\r\n \r\ndef DFS(dictionary,vertex,visited):\r\n visited[vertex]=True\r\n stack=[vertex]\r\n print(vertex)\r\n while stack:\r\n a=stack.pop()\r\n for i in dictionary[a]:\r\n if not visited[i]:\r\n print(i)\r\n visited[i]=True\r\n stack.append(i)\r\n\r\n\r\ndef BFS(dictionary, vertex,visited):\r\n visited[vertex]=True\r\n q=deque()\r\n q.append(vertex)\r\n while q:\r\n a=q.popleft()\r\n for i in dictionary[a]:\r\n if not visited[i]:\r\n visited[i]=True\r\n q.append(i)\r\n print(i)\r\n\r\n \r\n\r\n\r\ndef soe(limit):\r\n l=[1]*(limit+1)\r\n l[0]=0\r\n l[1]=0\r\n prime=[]\r\n for i in range(2,limit+1):\r\n if l[i]:\r\n for j in range(i*i,limit+1,i):\r\n l[j]=0\r\n \r\n for i in range(2,limit+1):\r\n if l[i]:\r\n prime.append(i)\r\n return prime\r\n\r\ndef segsoe(low,high):\r\n limit=int(high**0.5)+1\r\n prime=soe(limit)\r\n n=high-low+1\r\n l=[0]*(n+1)\r\n for i in range(len(prime)):\r\n lowlimit=(low//prime[i])*prime[i]\r\n if lowlimit>1\r\n return r\r\n\r\ndef don(d,ans,vi,i):\r\n vi[i]=True\r\n stack=[i]\r\n while stack:\r\n a=stack.pop()\r\n for x in d[a]:\r\n if not vi[x]:\r\n ans[i]+=1\r\n vi[x]=True\r\n stack.append(x)\r\n \r\n\r\ndef solve():\r\n n=inp()\r\n c=0\r\n for i in range(n):\r\n s=input().split()\r\n a,b=int(s[1]),int(s[2])\r\n if a>=2400 and b>a:\r\n c=1\r\n if c:\r\n pr('YES')\r\n else:\r\n pr('NO')\r\n\r\nfor _ in range(1):\r\n solve()\r\n## print(\"Case #{}:\".format(_+1),c)\r\n## \r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nBy 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.\n\nFor example, the general considers the sequence of heights (4, 3, 4, 2, 1, 1) correct and the sequence (4, 3, 1, 2, 2) wrong.\n\nWithin 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.",
"input": "",
"output": "```python\nn = int(input())\r\nvls = list(map(int, input().split()))\r\n\r\nx = min(vls)\r\niX = len(vls) - 1 - vls[::-1].index(x)\r\ndel vls[iX]\r\nvls.append(x)\r\n\r\nr = len(vls) - iX - 1\r\nr += vls.index(max(vls))\r\nprint(r)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A + B is often used as an example of the easiest problem possible to show some contest platform. However, some scientists have observed that sometimes this problem is not so easy to get accepted. Want to try?",
"input": "",
"output": "```python\na = input()\r\nb = input()\r\nif int(a) >=0 and int(b)<=1000:\r\n print(int(a)+int(b))\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. \"Piece of cake\" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.",
"input": "",
"output": "```python\nimport sys\r\nn = int(input())\r\nx = []\r\ny = []\r\nz = []\r\nfor i in range(0, n):\r\n force = list(map(int, input().split()))\r\n x.append(force[0])\r\n y.append(force[1])\r\n z.append(force[2])\r\nif((sum(x)+sum(y)+sum(z)) == 0):\r\n print(\"YES\")\r\nelse:\r\n print(\"NO\")\r\n\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A bus moves along the coordinate line *Ox* from the point *x*<==<=0 to the point *x*<==<=*a*. After starting from the point *x*<==<=0, it reaches the point *x*<==<=*a*, immediately turns back and then moves to the point *x*<==<=0. After returning to the point *x*<==<=0 it immediately goes back to the point *x*<==<=*a* and so on. Thus, the bus moves from *x*<==<=0 to *x*<==<=*a* and back. Moving from the point *x*<==<=0 to *x*<==<=*a* or from the point *x*<==<=*a* to *x*<==<=0 is called a bus journey. In total, the bus must make *k* journeys.\n\nThe petrol tank of the bus can hold *b* liters of gasoline. To pass a single unit of distance the bus needs to spend exactly one liter of gasoline. The bus starts its first journey with a full petrol tank.\n\nThere is a gas station in point *x*<==<=*f*. This point is between points *x*<==<=0 and *x*<==<=*a*. There are no other gas stations on the bus route. While passing by a gas station in either direction the bus can stop and completely refuel its tank. Thus, after stopping to refuel the tank will contain *b* liters of gasoline.\n\nWhat is the minimum number of times the bus needs to refuel at the point *x*<==<=*f* to make *k* journeys? The first journey starts in the point *x*<==<=0.",
"input": "",
"output": "```python\na, b, f, k=map(int,input().split())\r\nd=b\r\nn=0\r\ns=0\r\nx=a-f\r\nd -= f\r\nif (x*2>b) or (f*2>b):\r\n if k<3:\r\n if k==1:\r\n if a<=b:\r\n print(0)\r\n elif (f<=b) and (x<=b):\r\n print(1)\r\n else:\r\n print(-1)\r\n if k==2:\r\n if a+x<=b:\r\n print(1)\r\n elif (f<=b) and (x*2<=b):\r\n print(2)\r\n else:\r\n print(-1)\r\n else:\r\n print(-1)\r\nelse:\r\n while n=n-1:\n if k==n-1:\n print('0',end='')\n n+=1\n while(True):\n if k==n:\n print('10',end='')\n k-=1\n n-=1\n else:\n print('110',end='')\n k-=2\n n-=1\n if k==0:\n break\n if n==0:\n break\nelse:\n print(-1)\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Drazil is playing a math game with Varda.\n\nLet's define for positive integer *x* as a product of factorials of its digits. For example, .\n\nFirst, they choose a decimal number *a* consisting of *n* digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then they should find maximum positive number *x* satisfying following two conditions:\n\n1. *x* doesn't contain neither digit 0 nor digit 1.\n\n2. = .\n\nHelp friends find such number.",
"input": "",
"output": "```python\ndef findNum(a):\r\n numCount = [0]*11\r\n for num in a:\r\n for i in range(2, num+1):\r\n numCount[i] += 1\r\n\r\n # print(numCount)\r\n\r\n for i in range(9, 3, -1):\r\n shifts = max(0, numCount[i]-numCount[i+1])\r\n if i == 4:\r\n numCount[2] += 2*shifts\r\n numCount[i] -= shifts\r\n elif i == 6:\r\n numCount[2] += shifts\r\n numCount[3] += shifts\r\n numCount[i] -= shifts\r\n elif i == 8:\r\n numCount[2] += 3*shifts\r\n numCount[i] -= shifts\r\n elif i == 9:\r\n numCount[3] += 3*shifts\r\n numCount[i] -= shifts\r\n\r\n # print(numCount)\r\n\r\n res = []\r\n for i in range(9, 1, -1):\r\n for j in range(numCount[i]):\r\n res.append(str(i))\r\n for k in range(2, i):\r\n numCount[k] -= 1\r\n return ''.join(res)\r\n\r\nn = int(input())\r\na = list(map(int, input()))\r\nprint(findNum(a))\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "At regular competition Vladik and Valera won *a* and *b* candies respectively. Vladik offered 1 his candy to Valera. After that Valera gave Vladik 2 his candies, so that no one thought that he was less generous. Vladik for same reason gave 3 candies to Valera in next turn.\n\nMore formally, the guys take turns giving each other one candy more than they received in the previous turn.\n\nThis continued until the moment when one of them couldn’t give the right amount of candy. Candies, which guys got from each other, they don’t consider as their own. You need to know, who is the first who can’t give the right amount of candy.",
"input": "",
"output": "```python\nX = list(map(int, input().split()))\r\nTurn = True\r\nN = 1\r\nwhile True:\r\n if True:\r\n if X[0] - N < 0:\r\n print(\"Valera\")\r\n exit()\r\n X[1] += X[0] - N\r\n X[0] -= N\r\n N += 1\r\n Turn = False\r\n else:\r\n if X[1] - N < 0:\r\n print(\"Vladik\")\r\n exit()\r\n X[0] += X[1] - N\r\n X[1] -= N\r\n N += 1\r\n Turn = True\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Santa Claus has *n* candies, he dreams to give them as gifts to children.\n\nWhat is the maximal number of children for whose he can give candies if Santa Claus want each kid should get distinct positive integer number of candies. Santa Class wants to give all *n* candies he has.",
"input": "",
"output": "```python\n# http://codeforces.com/problemset/problem/753/A\n\ndef getSweets(sweetCount):\n sweetsList = []\n sumN = 0\n n = 1\n while sumN + n < sweetCount:\n sumN += n\n sweetsList.append(n)\n n += 1\n\n sweetsList[-1] += sweetCount - sumN\n return sweetsList\n\n\nif __name__ == '__main__':\n sweetCount = int(input())\n sweets = getSweets(sweetCount)\n sweets = list(map(str, sweets))\n\n print(len(sweets))\n print(' '.join(sweets))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.",
"input": "",
"output": "```python\ns=input()\r\nl=len(s)\r\nc=0\r\nfor i in range (l):\r\n if i>='a' and i<='z':\r\n c+=1\r\nif c>=l/2:\r\n print(s.lower)\r\nelse:\r\n print(s.upper) \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vanya plays a game of balloons on the field of size *n*<=×<=*n*, where each cell contains a balloon with one of the values 0, 1, 2 or 3. The goal is to destroy a cross, such that the product of all values of balloons in the cross is maximum possible. There are two types of crosses: normal and rotated. For example:\n\nor\n\nFormally, the cross is given by three integers *r*, *c* and *d*, such that *d*<=≤<=*r*,<=*c*<=≤<=*n*<=-<=*d*<=+<=1. The normal cross consists of balloons located in cells (*x*,<=*y*) (where *x* stay for the number of the row and *y* for the number of the column), such that |*x*<=-<=*r*|·|*y*<=-<=*c*|<==<=0 and |*x*<=-<=*r*|<=+<=|*y*<=-<=*c*|<=<<=*d*. Rotated cross consists of balloons located in cells (*x*,<=*y*), such that |*x*<=-<=*r*|<==<=|*y*<=-<=*c*| and |*x*<=-<=*r*|<=<<=*d*.\n\nVanya wants to know the maximum possible product of the values of balls forming one cross. As this value can be large, output it modulo 109<=+<=7.",
"input": "",
"output": "```python\nprint(\"_RANDOM_GUESS_1690489311.5176659\")# 1690489311.5176845\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Maxim wants to buy some games at the local game shop. There are $n$ games in the shop, the $i$-th game costs $c_i$.\n\nMaxim has a wallet which can be represented as an array of integers. His wallet contains $m$ bills, the $j$-th bill has value $a_j$.\n\nGames in the shop are ordered from left to right, Maxim tries to buy every game in that order.\n\nWhen Maxim stands at the position $i$ in the shop, he takes the first bill from his wallet (if his wallet is empty then he proceeds to the next position immediately) and tries to buy the $i$-th game using this bill. After Maxim tried to buy the $n$-th game, he leaves the shop.\n\nMaxim buys the $i$-th game if and only if the value of the first bill (which he takes) from his wallet is greater or equal to the cost of the $i$-th game. If he successfully buys the $i$-th game, the first bill from his wallet disappears and the next bill becomes first. Otherwise Maxim leaves the first bill in his wallet (this bill still remains the first one) and proceeds to the next game.\n\nFor example, for array $c = [2, 4, 5, 2, 4]$ and array $a = [5, 3, 4, 6]$ the following process takes place: Maxim buys the first game using the first bill (its value is $5$), the bill disappears, after that the second bill (with value $3$) becomes the first one in Maxim's wallet, then Maxim doesn't buy the second game because $c_2 > a_2$, the same with the third game, then he buys the fourth game using the bill of value $a_2$ (the third bill becomes the first one in Maxim's wallet) and buys the fifth game using the bill of value $a_3$.\n\nYour task is to get the number of games Maxim will buy.",
"input": "",
"output": "```python\nn,m = list(map(int, input().split()))\nc = list(map(int, input().split()))\na = list(map(int, input().split()))\n\ni=0\nj=0\nb=0\nwhile i lis [i+1] - lis[i]):\n print(f'{lis[i+1] - lis[i]}', end = ' ')\n else:\n print(f'{lis[i] - lis[i-1]}', end = ' ')\n if(lis[i] - lis[0] > lis [x-1] - lis[i]):\n print(f'{lis[i] - lis[0]}')\n else:\n print(f'{lis[x-1] - lis[i]}')\n \t \t\t\t \t \t\t\t\t\t\t\t \t \t \t \t\t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are *n* lines in that description each of which described one goal. Every goal was marked with the name of the team that had scored it. Help Vasya, learn the name of the team that won the finals. It is guaranteed that the match did not end in a tie.",
"input": "",
"output": "```python\nn=int(input(\"\"))\r\ndict1={}\r\nm=0\r\ns=''\r\nfor i in range(n):\r\n a=input(\"\")\r\n if a not in dict1.keys():\r\n dict1[a]=1\r\n else:\r\n dict1[a]+=1 \r\n\r\nfor j in dict1.keys():\r\n if dict1[j]>m:\r\n m=dict1[j]\r\n s=j\r\n \r\nprint(s)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Valera is a little boy. Yesterday he got a huge Math hometask at school, so Valera didn't have enough time to properly learn the English alphabet for his English lesson. Unfortunately, the English teacher decided to have a test on alphabet today. At the test Valera got a square piece of squared paper. The length of the side equals *n* squares (*n* is an odd number) and each unit square contains some small letter of the English alphabet.\n\nValera needs to know if the letters written on the square piece of paper form letter \"X\". Valera's teacher thinks that the letters on the piece of paper form an \"X\", if:\n - on both diagonals of the square paper all letters are the same; - all other squares of the paper (they are not on the diagonals) contain the same letter that is different from the letters on the diagonals. \nHelp Valera, write the program that completes the described task for him.",
"input": "",
"output": "```python\nn=int(input())\r\nmat=[]\r\nc=0\r\nfor i in range(n):\r\n s=input()\r\n mat+=[s]\r\nfor i in range(n):\r\n if mat[i][i]==mat[i][n-i-1]:\r\n c+=1\r\nif c==n and len(set(mat))==2:\r\n print('YES')\r\nelse:\r\n print('NO')\r\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nBy 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.\n\nFor example, the general considers the sequence of heights (4, 3, 4, 2, 1, 1) correct and the sequence (4, 3, 1, 2, 2) wrong.\n\nWithin 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.",
"input": "",
"output": "```python\nn = int(input())\na = list(map(int, input().split()))\n\nmin_val = max_val = a[0]\nmin_index = max_index = 0\n\nfor i in range(n):\n if min_val >= a[i]:\n min_val = a[i]\n min_index = i\n if max_val < a[i]:\n max_val = a[i]\n max_index = i\n\nif min_index < max_index:\n min_index = (n - 1) - min_index\n print(min_index + max_index - 1)\nelse:\n min_index = (n - 1) - min_index\n print(min_index + max_index)\n\n \t \t\t\t\t\t \t\t \t \t \t \t \t\t\t \t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Natasha is planning an expedition to Mars for $n$ people. One of the important tasks is to provide food for each participant.\n\nThe warehouse has $m$ daily food packages. Each package has some food type $a_i$.\n\nEach participant must eat exactly one food package each day. Due to extreme loads, each participant must eat the same food type throughout the expedition. Different participants may eat different (or the same) types of food.\n\nFormally, for each participant $j$ Natasha should select his food type $b_j$ and each day $j$-th participant will eat one food package of type $b_j$. The values $b_j$ for different participants may be different.\n\nWhat is the maximum possible number of days the expedition can last, following the requirements above?",
"input": "",
"output": "```python\n\r\n# Main\r\ndef main():\r\n n, m = map(int, input().split())\r\n food = list(map(int, input().split()))\r\n\r\n arr = dict()\r\n for i in food:\r\n if i not in arr:\r\n arr[i] = 1\r\n else:\r\n arr[i] += 1\r\n \r\n maxD = 0\r\n for d in range(1, 101, 1):\r\n temp = arr\r\n k = 0\r\n flag = 0\r\n for key, val in temp.items():\r\n while val >= d:\r\n flag += 1\r\n k += 1\r\n val -= d\r\n if k >= n and d > maxD:\r\n maxD = d\r\n if flag == 0:\r\n break\r\n \r\n print(maxD)\r\n\r\n# End main\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n\r\n\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Yet another Armageddon is coming! This time the culprit is the Julya tribe calendar. \n\nThe beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows: \n\n\"May the Great Beaver bless you! May your chacres open and may your third eye never turn blind from beholding the Truth! Take the magic number, subtract a digit from it (the digit must occur in the number) and get a new magic number. Repeat this operation until a magic number equals zero. The Earth will stand on Three Beavers for the time, equal to the number of subtractions you perform!\"\n\nDistinct subtraction sequences can obviously get you different number of operations. But the Smart Beaver is ready to face the worst and is asking you to count the minimum number of operations he needs to reduce the magic number to zero.",
"input": "",
"output": "```python\nt=int(input())\r\nrem=t%10\r\nc=1\r\nno=t-rem\r\nc+=(no/10)*2\r\nprint(c)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vasya has *n* pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every *m*-th day (at days with numbers *m*,<=2*m*,<=3*m*,<=...) mom buys a pair of socks to Vasya. She does it late in the evening, so that Vasya cannot put on a new pair of socks before the next day. How many consecutive days pass until Vasya runs out of socks?",
"input": "",
"output": "```python\nn,m = list(map(int,input().split()))\r\nn += (n//m)\r\nif n%m == 0:\r\n n += 1\r\nprint(n)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You have *r* red, *g* green and *b* blue balloons. To decorate a single table for the banquet you need exactly three balloons. Three balloons attached to some table shouldn't have the same color. What maximum number *t* of tables can be decorated if we know number of balloons of each color?\n\nYour task is to write a program that for given values *r*, *g* and *b* will find the maximum number *t* of tables, that can be decorated in the required manner.",
"input": "",
"output": "```python\nl = list(map(int,input().split()))\r\nl.sort()\r\nl[2]-=l[0]\r\nl[1]-=l[0]\r\nans = l[0]\r\n\r\nans += min(l[1],l[2]//2)\r\n\r\nprint(ans)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Sometimes some words like \"localization\" or \"internationalization\" are so long that writing them many times in one text is quite tiresome.\n\nLet's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.\n\nThis abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.\n\nThus, \"localization\" will be spelt as \"l10n\", and \"internationalization» will be spelt as \"i18n\".\n\nYou are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.",
"input": "",
"output": "```python\ntests = int(input())\r\nfor _ in range (0,tests):\r\n s = input()\r\n if len(s)>10:\r\n print(s[0],len(s)-2,s[-1],sep=\"\")\r\n else:\r\n print(s)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner.\n\nOutput the probability that SmallR will win the match.",
"input": "",
"output": "```python\na, b, c, d = (int(s) for s in input().split(\" \"))\n\nMAX = 100\ncoef = sum((((c - d) * (a - b)) / (b * d)) ** i for i in range(MAX + 1))\nptotal = (a/b) * coef\n\nprint(\"{:.15f}\".format(ptotal))\n\n \t\t\t \t\t\t \t\t\t \t \t\t\t\t \t\t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are a lover of bacteria. You want to raise some bacteria in a box. \n\nInitially, the box is empty. Each morning, you can put any number of bacteria into the box. And each night, every bacterium in the box will split into two bacteria. You hope to see exactly *x* bacteria in the box at some moment. \n\nWhat is the minimum number of bacteria you need to put into the box across those days?",
"input": "",
"output": "```python\n'''\nx = 2345234\nprint(bin(x)[2:])\n\ns = '101110011100'\nprint(int(s, 2))\n'''\n\nn = int(input())\n\nk = bin(n)[2:]\n\nprint(k.count('1'))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Beroffice text editor has a wide range of features that help working with text. One of the features is an automatic search for typos and suggestions of how to fix them.\n\nBeroffice works only with small English letters (i.e. with 26 letters from a to z). Beroffice thinks that a word is typed with a typo if there are three or more consonants in a row in the word. The only exception is that if the block of consonants has all letters the same, then this block (even if its length is greater than three) is not considered a typo. Formally, a word is typed with a typo if there is a block of not less that three consonants in a row, and there are at least two different letters in this block.\n\nFor example:\n - the following words have typos: \"hellno\", \"hackcerrs\" and \"backtothefutttture\"; - the following words don't have typos: \"helllllooooo\", \"tobeornottobe\" and \"oooooo\". \nWhen Beroffice editor finds a word with a typo, it inserts as little as possible number of spaces in this word (dividing it into several words) in such a way that each of the resulting words is typed without any typos.\n\nImplement this feature of Beroffice editor. Consider the following letters as the only vowels: 'a', 'e', 'i', 'o' and 'u'. All the other letters are consonants in this problem.",
"input": "",
"output": "```python\ndef insert_spacebar(s,n):\n\ts1=''\n\ts2=''\n\tfor i in range(n+1):\n\t s1+=s[i]\n\tfor i in range(n+1,len(s)):\n\t s2+=s[i]\n\treturn s1+' '+s2\n\n\ns=input()\nglas_arr=['a','i','e','u','o']\n\n\nfor i in range(len(s)-2):\n\tif(s[i]==' ' or s[i] in glas_arr):\n\t\tcontinue\n\telse:\n\t\tif((s[i] not in glas_arr)and (s[i+1] not in glas_arr) and (s[i+2] not in glas_arr)):\n\t\t\tif(s[i]==s[i+1]==s[i+2]):\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\ts=insert_spacebar(s,i+1)\n\nif((s[len(s)-1] not in glas_arr)and (s[len(s)-2] not in glas_arr) and (s[len(s)-3] not in glas_arr)):\n\tif((s[len(s)-1]==s[len(s)-2]==s[len(s)-3])==False):\n\t\ts=insert_spacebar(s,len(s)-2)\n\n\nprint(s)\n\t\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings *a* and *b* of equal length are called equivalent in one of the two cases: \n 1. They are equal. 1. If we split string *a* into two halves of the same size *a*1 and *a*2, and string *b* into two halves of the same size *b*1 and *b*2, then one of the following is correct: *a*1 is equivalent to *b*1, and *a*2 is equivalent to *b*2 1. *a*1 is equivalent to *b*2, and *a*2 is equivalent to *b*1 \nAs a home task, the teacher gave two strings to his students and asked to determine if they are equivalent.\n\nGerald has already completed this home task. Now it's your turn!",
"input": "",
"output": "```python\na = input()\nb = input()\n\ndef equivalente(a,b):\n if(a == b):\n return 1\n elif(len(a) > 1):\n half = int(len(a)/2)\n end = int(len(a))\n\n if(len(a) > 1):\n ax = a[0:half]\n ay = a[half:end]\n bx = b[0:half]\n by = b[half:end]\n else:\n ax, ay, bx, by = a, a, b, b\n\n if(equivalente(ax,bx) * equivalente(ay,by) == 1):\n return 1\n elif(equivalente(ax,by) * equivalente(ay,bx) == 1):\n return 1\n else:\n return 0\n else:\n return 0\n\nx = equivalente(a,b)\nif(x == 1):\n print(\"YES\")\nelse:\n print(\"NO\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a \"plus\") and negative (a \"minus\"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.\n\nMike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own.\n\nMike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.",
"input": "",
"output": "```python\nn = int(input())\r\ncontrol = n\r\ncount = 0\r\ntemp = 0\r\n\r\nwhile n > 0:\r\n magnet = input()\r\n if n != control and temp != magnet:\r\n count += 1\r\n temp = magnet\r\n n -= 1\r\n\r\nprint(count + 1)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "There are *n* students in a class working on group projects. The students will divide into groups (some students may be in groups alone), work on their independent pieces, and then discuss the results together. It takes the *i*-th student *a**i* minutes to finish his/her independent piece.\n\nIf students work at different paces, it can be frustrating for the faster students and stressful for the slower ones. In particular, the imbalance of a group is defined as the maximum *a**i* in the group minus the minimum *a**i* in the group. Note that a group containing a single student has an imbalance of 0. How many ways are there for the students to divide into groups so that the total imbalance of all groups is at most *k*?\n\nTwo divisions are considered distinct if there exists a pair of students who work in the same group in one division but different groups in the other.",
"input": "",
"output": "```python\nimport sys, math\r\nfrom functools import lru_cache\r\ninput = sys.stdin.readline\r\n\r\nif __name__ == \"__main__\":\r\n MOD = 10 ** 9 + 7\r\n n, k = map(int, input().split())\r\n a = list(map(int, input().split()))\r\n a.sort()\r\n a.append(0)\r\n\r\n @lru_cache(None)\r\n def dfs(i, groups, leftK):\r\n if leftK < 0 or groups > i+1:\r\n return 0\r\n if i < 0:\r\n if groups == 0: return 1\r\n return 0\r\n leftK -= (a[i+1] - a[i]) * groups \r\n res = dfs(i-1, groups+1, leftK)\r\n res += dfs(i-1, groups, leftK) * (groups + 1)\r\n if groups > 0:\r\n res += dfs(i-1, groups-1, leftK) * groups \r\n \r\n res %= MOD\r\n return res\r\n \r\n res = dfs(n-1, 0, k)\r\n print(res)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "As you could know there are no male planes nor female planes. However, each plane on Earth likes some other plane. There are *n* planes on Earth, numbered from 1 to *n*, and the plane with number *i* likes the plane with number *f**i*, where 1<=≤<=*f**i*<=≤<=*n* and *f**i*<=≠<=*i*.\n\nWe call a love triangle a situation in which plane *A* likes plane *B*, plane *B* likes plane *C* and plane *C* likes plane *A*. Find out if there is any love triangle on Earth.",
"input": "",
"output": "```python\n# cook your dish here\r\nimport bisect \r\nn=int(input())\r\nA=[0]\r\nfor k in input().split():\r\n A.append(int(k))\r\n# s=input()\r\n\r\nfor k in range(1,n+1):\r\n if A[A[A[k]]]==k:\r\n print(\"YES\")\r\n break \r\nelse:\r\n print(\"NO\")\r\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "For a positive integer *n* let's define a function *f*:\n\n*f*(*n*)<==<=<=-<=1<=+<=2<=-<=3<=+<=..<=+<=(<=-<=1)*n**n* \n\nYour task is to calculate *f*(*n*) for a given integer *n*.",
"input": "",
"output": "```python\nn = int(input())\r\nf = 0\r\nfor i in range(1,n+1):\r\n f += ((-1)**i)*i \r\nprint(f)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are given a ternary string (it is a string which consists only of characters '0', '1' and '2').\n\nYou can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace \"01\" with \"10\" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace \"12\" with \"21\" or vice versa).\n\nFor example, for string \"010210\" we can perform the following moves: \n - \"010210\" $\\rightarrow$ \"100210\"; - \"010210\" $\\rightarrow$ \"001210\"; - \"010210\" $\\rightarrow$ \"010120\"; - \"010210\" $\\rightarrow$ \"010201\". \nNote than you cannot swap \"02\" $\\rightarrow$ \"20\" and vice versa. You cannot perform any other operations with the given string excluding described above.\n\nYou task is to obtain the minimum possible (lexicographically) string by using these swaps arbitrary number of times (possibly, zero).\n\nString $a$ is lexicographically less than string $b$ (if strings $a$ and $b$ have the same length) if there exists some position $i$ ($1 \\le i \\le |a|$, where $|s|$ is the length of the string $s$) such that for every $j < i$ holds $a_j = b_j$, and $a_i < b_i$.",
"input": "",
"output": "```python\ns=list(input())\r\na=[]\r\nt=0\r\nl=0\r\nfor i in range(len(s)):\r\n if s[i]=='2':t=1\r\n if s[i]=='0'and t==1:\r\n t=0\r\n a+=sorted(s[l:i])\r\n l=i\r\n if i==len(s)-1:a+=sorted(s[l:])\r\nprint(''.join(a))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Gerald has *n* younger brothers and their number happens to be even. One day he bought *n*2 candy bags. One bag has one candy, one bag has two candies, one bag has three candies and so on. In fact, for each integer *k* from 1 to *n*2 he has exactly one bag with *k* candies. \n\nHelp him give *n* bags of candies to each brother so that all brothers got the same number of candies.",
"input": "",
"output": "```python\nn=int(input())\r\nx=n*(n**2+1)//2\r\nfor i in range(1,n+1):\r\n print(i,x-i)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Natasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the string — concatenation of letters, which correspond to the stages.\n\nThere are $n$ stages available. The rocket must contain exactly $k$ of them. Stages in the rocket should be ordered by their weight. So, after the stage with some letter can go only stage with a letter, which is at least two positions after in the alphabet (skipping one letter in between, or even more). For example, after letter 'c' can't go letters 'a', 'b', 'c' and 'd', but can go letters 'e', 'f', ..., 'z'.\n\nFor the rocket to fly as far as possible, its weight should be minimal. The weight of the rocket is equal to the sum of the weights of its stages. The weight of the stage is the number of its letter in the alphabet. For example, the stage 'a 'weighs one ton,' b 'weighs two tons, and' z' — $26$ tons.\n\nBuild the rocket with the minimal weight or determine, that it is impossible to build a rocket at all. Each stage can be used at most once.",
"input": "",
"output": "```python\nfrom math import *\r\nfrom collections import *\r\nfrom operator import itemgetter\r\nimport bisect\r\nii = lambda: int(input())\r\niia = lambda: list(map(int,input().split()))\r\nisa = lambda: list(input().split())\r\nI = lambda:list(map(int,input().split()))\r\nchrIdx = lambda x: ord(x)-96\r\nidxChr = lambda x: chr(96+x)\r\n\r\nn, k = iia()\r\ns = input()\r\ns = sorted(s)\r\n#print(s)\r\nx = 1\r\nflag = -1\r\nprev = s[0]\r\nval = chrIdx(s[0])\r\nif(k==1):\r\n flag = val\r\n#print(val)\r\nfor i in range(1,n):\r\n if(chrIdx(s[i])-chrIdx(prev)>2):\r\n x+=1\r\n prev = s[i]\r\n val += chrIdx(s[i])\r\n #print(s[i], x , val)\r\n if(x>=k):\r\n flag = val\r\n break\r\nprint(flag)\r\n\r\n\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Luba has a ticket consisting of 6 digits. In one move she can choose digit in any position and replace it with arbitrary digit. She wants to know the minimum number of digits she needs to replace in order to make the ticket lucky.\n\nThe ticket is considered lucky if the sum of first three digits equals to the sum of last three digits.",
"input": "",
"output": "```python\nl=[int(i) for i in input()]\r\na=sum(l[:3]);b=sum(l[3:])\r\nif a==b:\r\n print(0)\r\nelse:\r\n print(abs(a-b)//9+1)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are given a sequence *a* consisting of *n* integers. You may partition this sequence into two sequences *b* and *c* in such a way that every element belongs exactly to one of these sequences. \n\nLet *B* be the sum of elements belonging to *b*, and *C* be the sum of elements belonging to *c* (if some of these sequences is empty, then its sum is 0). What is the maximum possible value of *B*<=-<=*C*?",
"input": "",
"output": "```python\nraw_input()\r\nprint(eval(input().replace(\"-\",\"\").replace(\" \",\"+\")))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times *b*,<=*b*<=+<=*a*,<=*b*<=+<=2*a*,<=*b*<=+<=3*a*,<=... and Morty screams at times *d*,<=*d*<=+<=*c*,<=*d*<=+<=2*c*,<=*d*<=+<=3*c*,<=.... \n\nThe Monster will catch them if at any point they scream at the same time, so it wants to know when it will catch them (the first time they scream at the same time) or that they will never scream at the same time.",
"input": "",
"output": "```python\nimport math\r\nimport cmath\r\nimport string\r\n# how to find minimum prime factor in log(n)\r\ndef sieve(n):\r\n l = [0]*(n+1)\r\n l[0] = l[1] = 1 \r\n for i in range(2,int(n**.5)+1):\r\n if not l[i]:\r\n for j in range(i*i,n+1,i):\r\n l[j] = 1 \r\n return [i for i in range(n+1) if l[i] == 0]\r\n#pass n+1 \r\ndef sieveOptemised(n,prime):\r\n l = [0]*(n+1)\r\n l[0] = l[1] = 1 \r\n for i in range(2,n):\r\n if not l[i] : prime.append(i) \r\n for j in range(len(prime)):\r\n if i*prime[j] >= n :\r\n break\r\n l[i*prime[j]] = 1 \r\n if i % prime[j] == 0 : break \r\ndef XOR(n):\r\n return [n, 1, n + 1, 0][n % 4]\r\ndef isprime(n):\r\n return all([False for i in range(2, n) if n % i == 0]) and not n < 2\r\ndef searchBinary(lis, l, r, e):\r\n ans = 0\r\n while l <= r:\r\n m = (l + r) // 2\r\n if lis[m][0] > e:\r\n r = m - 1\r\n else:\r\n l = m + 1\r\n ans = l\r\n return ans\r\ndef f(l, i, j, n, m):\r\n c = l[i][j]\r\n i1 = i\r\n j1 = j\r\n i2 = i\r\n j2 = j\r\n i3 = i\r\n j3 = j\r\n i4 = i\r\n j4 = j\r\n while i1 > 0 and j1 > 0:\r\n i1 -= 1\r\n j1 -= 1\r\n c += l[i1][j1]\r\n while i2 < n - 1 and j2 < m - 1:\r\n i2 += 1\r\n j2 += 1\r\n c += l[i2][j2]\r\n while i3 > 0 and j3 < m - 1:\r\n i3 -= 1\r\n j3 += 1\r\n c += l[i3][j3]\r\n while i4 < n - 1 and j4 > 0:\r\n i4 += 1\r\n j4 -= 1\r\n c += l[i4][j4]\r\n\r\n return c\r\ndef gcd(a,b):\r\n if b == 0 :\r\n return a \r\n else :\r\n return gcd(b,a%b) \r\ndef binarySearch(lis, l, r, e):\r\n while l <= r:\r\n m = (l + r) // 2\r\n if lis[m] == e:\r\n return 1\r\n elif lis[m] > e:\r\n r = m - 1\r\n else:\r\n l = m + 1\r\n return 0\r\ndef isSqrt(n):\r\n for i in range(1,int(n**.5)+2):\r\n if i*i == n :\r\n return True \r\n return False\r\n# math.ceil(n/i) = (n-1)//i+1\r\nresult = list(string.ascii_lowercase)\r\nalpha = {}\r\nfor i in range(26):\r\n alpha[result[i]] = i + 1\r\naa = []\r\n\r\na,b = map(int,input().split())\r\nc,d = map(int,input().split())\r\nl1 = []\r\nl2 = []\r\nfor i in range(100000):\r\n l1.append(b+i*a)\r\n l2.append(d+i*c)\r\n\r\ns = list(set(set(l1).intersection(set(l2))))\r\ns.sort()\r\nif s :\r\n aa.append(s[0])\r\nelse :\r\n aa.append(-1) \r\nfor i in aa :\r\n print(i)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nYou 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.\n\nYou 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.\n\nYou are given the text of the lecture the professor is going to read. Find out how the lecture will be recorded in your notes.",
"input": "",
"output": "```python\nn,m=map(int,input().split())\r\nmp={}\r\nfor i in range(m):\r\n s1,s2=input().split()\r\n mp[s1]=s2\r\n\r\nl=input().split()\r\nfor i in range(n) :\r\n if len(mp[l[i]])d:\r\n print(-1)\r\nelse:\r\n print((len(l)-1)*2+(d-temp)//5)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Devu is a renowned classical singer. He is invited to many big functions/festivals. Recently he was invited to \"All World Classical Singing Festival\". Other than Devu, comedian Churu was also invited.\n\nDevu has provided organizers a list of the songs and required time for singing them. He will sing *n* songs, *i**th* song will take *t**i* minutes exactly. \n\nThe Comedian, Churu will crack jokes. All his jokes are of 5 minutes exactly.\n\nPeople have mainly come to listen Devu. But you know that he needs rest of 10 minutes after each song. On the other hand, Churu being a very active person, doesn't need any rest.\n\nYou as one of the organizers should make an optimal sсhedule for the event. For some reasons you must follow the conditions:\n - The duration of the event must be no more than *d* minutes; - Devu must complete all his songs; - With satisfying the two previous conditions the number of jokes cracked by Churu should be as many as possible. \nIf it is not possible to find a way to conduct all the songs of the Devu, output -1. Otherwise find out maximum number of jokes that Churu can crack in the grand event.",
"input": "",
"output": "```python\nt = input()\r\ntemp = t.split()\r\nn = int(temp[0])\r\nd = int(temp[1])\r\nsongLenthList = []\r\nsongLength = input()\r\nList = songLength.split()\r\nsongLenthList = [int(i) for i in List]\r\ndevuBreaktime = (n-1)*10\r\ndevuTotalTime = devuBreaktime + sum(songLenthList)\r\nchuruTime = d - devuTotalTime + devuBreaktime\r\nif (devuTotalTime > d):\r\n print(-1)\r\nelse:\r\n print(int(churuTime/5))\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Top-model Izabella participates in the competition. She wants to impress judges and show her mathematical skills.\n\nHer 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.",
"input": "",
"output": "```python\nstr=input()\r\nif len(str)>6:\r\n print('yes')\r\nelse:\r\n print('no')\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Om Nom really likes candies and doesn't like spiders as they frequently steal candies. One day Om Nom fancied a walk in a park. Unfortunately, the park has some spiders and Om Nom doesn't want to see them at all.\n\nThe park can be represented as a rectangular *n*<=×<=*m* field. The park has *k* spiders, each spider at time 0 is at some cell of the field. The spiders move all the time, and each spider always moves in one of the four directions (left, right, down, up). In a unit of time, a spider crawls from his cell to the side-adjacent cell in the corresponding direction. If there is no cell in the given direction, then the spider leaves the park. The spiders do not interfere with each other as they move. Specifically, one cell can have multiple spiders at the same time.\n\nOm Nom isn't yet sure where to start his walk from but he definitely wants:\n - to start walking at time 0 at an upper row cell of the field (it is guaranteed that the cells in this row do not contain any spiders); - to walk by moving down the field towards the lowest row (the walk ends when Om Nom leaves the boundaries of the park). \nWe know that Om Nom moves by jumping. One jump takes one time unit and transports the little monster from his cell to either a side-adjacent cell on the lower row or outside the park boundaries.\n\nEach time Om Nom lands in a cell he sees all the spiders that have come to that cell at this moment of time. Om Nom wants to choose the optimal cell to start the walk from. That's why he wonders: for each possible starting cell, how many spiders will he see during the walk if he starts from this cell? Help him and calculate the required value for each possible starting cell.",
"input": "",
"output": "```python\nn,m,k = map(int,input().split())\r\ngrid = [list(input()) for _ in range(n)]\r\nsol = []\r\nfor col in range(m):\r\n ans = 0\r\n for t in range(1,n):\r\n x,y = t,col\r\n try:\r\n if grid[x][y+t] == 'L':\r\n ans += 1\r\n except: pass\r\n try:\r\n if grid[x][y-t] == 'R':\r\n ans += 1\r\n except: pass\r\n try:\r\n if grid[x+t][y] == 'U':\r\n ans += 1\r\n except: pass\r\n try:\r\n if grid[x-t][y] == 'D':\r\n ans += 1\r\n except: pass\r\n sol.append(ans)\r\nprint(\" \".join(map(str,sol)))\r\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Imagine that there is a group of three friends: A, B and С. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The debts still mean the same but the total sum of the debts now equals 20 rubles.\n\nThis task is a generalisation of a described example. Imagine that your group of friends has *n* people and you know the debts between the people. Optimize the given debts without changing their meaning. In other words, finally for each friend the difference between the total money he should give and the total money he should take must be the same. Print the minimum sum of all debts in the optimal rearrangement of the debts. See the notes to the test samples to better understand the problem.",
"input": "",
"output": "```python\nn, m = map(int, input().split())\r\n\r\nown = dict()\r\n\r\nfor _ in range(m):\r\n a, b, c = map(int, input().split())\r\n if a in own:\r\n own[a] += c\r\n else:\r\n own[a] = c\r\n\r\n if b in own:\r\n own[b] -= c\r\n else:\r\n own[b] = -c\r\n\r\nans = 0\r\n\r\nfor i in own.values():\r\n ans += i if i > 0 else 0\r\n\r\nprint(ans)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "There will be a launch of a new, powerful and unusual collider very soon, which located along a straight line. *n* particles will be launched inside it. All of them are located in a straight line and there can not be two or more particles located in the same point. The coordinates of the particles coincide with the distance in meters from the center of the collider, *x**i* is the coordinate of the *i*-th particle and its position in the collider at the same time. All coordinates of particle positions are even integers.\n\nYou know the direction of each particle movement — it will move to the right or to the left after the collider's launch start. All particles begin to move simultaneously at the time of the collider's launch start. Each particle will move straight to the left or straight to the right with the constant speed of 1 meter per microsecond. The collider is big enough so particles can not leave it in the foreseeable time.\n\nWrite the program which finds the moment of the first collision of any two particles of the collider. In other words, find the number of microseconds before the first moment when any two particles are at the same point.",
"input": "",
"output": "```python\n\"\"\"\r\n4\r\nRLRL\r\n2 4 6 10\r\n\r\n\r\n3\r\nLLR\r\n40 50 60\r\n\r\n\r\n4\r\nLRLR\r\n2 4 8 10\r\n\r\n\r\n5\r\nLRLRL\r\n2 4 16 20 22\r\n\r\n\r\n5\r\nLRRRL\r\n2 4 16 20 22\r\n\r\n\r\n\"\"\"\r\nn = int(input())\r\ndirs = input()\r\nfirst_right = dirs.index(\"R\")\r\nlast_left = dirs.rfind(\"L\")\r\nbens = [int(i) for i in input().split()]\r\ndirs = dirs[first_right:last_left + 1]\r\nbens = bens[first_right:last_left+1]\r\n\r\nleft = []\r\nright = []\r\nfor i in range(len(dirs)):\r\n if dirs[i] == 'R':\r\n right.append(bens[i])\r\n else:\r\n left.append(bens[i])\r\n\r\nif len(right) == 0 or len(left) == 0:\r\n print(-1)\r\n\r\nelse:\r\n res = float('inf')\r\n for i in left:\r\n for j in right:\r\n dis = abs(i - j) // 2\r\n if dis < res:\r\n res = dis\r\n print(res)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Squirrel Liss loves nuts. There are *n* trees (numbered 1 to *n* from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree *i* is *h**i*. Liss wants to eat all nuts.\n\nNow Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions:\n - Walk up or down one unit on a tree. - Eat a nut on the top of the current tree. - Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height *h* of the tree *i* (1<=≤<=*i*<=≤<=*n*<=-<=1), she jumps to height *h* of the tree *i*<=+<=1. This action can't be performed if *h*<=><=*h**i*<=+<=1. \nCompute the minimal time (in seconds) required to eat all nuts.",
"input": "",
"output": "```python\nn = int(input())\n\n# Assume squirrel has had nut on the prev tree and is at it's top. \n# In this, compute time to jump to next tree, go to top and have nut\n\nh_prev = int(input())\ntime = h_prev + 1\n\nfor i in range(n-1):\n\th_cur = int(input())\n\ttime += abs((h_prev-h_cur)) + 2\n\th_prev = h_cur\n\nprint(time)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Arya has *n* opponents in the school. Each day he will fight with all opponents who are present this day. His opponents have some fighting plan that guarantees they will win, but implementing this plan requires presence of them all. That means if one day at least one of Arya's opponents is absent at the school, then Arya will beat all present opponents. Otherwise, if all opponents are present, then they will beat Arya.\n\nFor each opponent Arya knows his schedule — whether or not he is going to present on each particular day. Tell him the maximum number of consecutive days that he will beat all present opponents.\n\nNote, that if some day there are no opponents present, Arya still considers he beats all the present opponents.",
"input": "",
"output": "```python\nio = input().split()\r\n\r\nn = int(io[0])\r\nd = int(io[1])\r\n\r\nl = []\r\n\r\nstreak = 0\r\nnew_streak = 0\r\n\r\nfor _ in range(d):\r\n l.append(list(map(int, input())))\r\n\r\nfor i in l:\r\n if 0 in i:\r\n streak += 1\r\n else:\r\n new_streak = streak\r\n streak = 0\r\nif streak > new_streak:\r\n print(streak)\r\nelse:\r\n print(new_streak)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vasya likes everything infinite. Now he is studying the properties of a sequence *s*, such that its first element is equal to *a* (*s*1<==<=*a*), and the difference between any two neighbouring elements is equal to *c* (*s**i*<=-<=*s**i*<=-<=1<==<=*c*). In particular, Vasya wonders if his favourite integer *b* appears in this sequence, that is, there exists a positive integer *i*, such that *s**i*<==<=*b*. Of course, you are the person he asks for a help.",
"input": "",
"output": "```python\na,b,c=map(int,input().split(\" \"))\r\ni=0\r\nX=[a]\r\nif(a==b):\r\n print(\"YES\")\r\nelif((a>b and c<=0) or (a=0)):\r\n\r\n if(c!=0):\r\n if(max(abs(b),abs(c))%min(abs(b),abs(c))==a):\r\n print(\"YES\")\r\n else:\r\n print(\"NO\") \r\n\r\n if(c==0):\r\n if(a==b):\r\n print(\"YES\")\r\n else:\r\n print(\"NO\") \r\n\r\n\r\nelse:\r\n print(\"NO\") \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to the store and buy some few more horseshoes, not to lose face in front of his stylish comrades.\n\nFortunately, the store sells horseshoes of all colors under the sun and Valera has enough money to buy any four of them. However, in order to save the money, he would like to spend as little money as possible, so you need to help Valera and determine what is the minimum number of horseshoes he needs to buy to wear four horseshoes of different colors to a party.",
"input": "",
"output": "```python\narr = list(map(int,input().split()))\r\narrS = set(arr)\r\nprint(len(arr)-len(arrS))\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.\n\nFor example, there is a statement called the \"Goldbach's conjecture\". It says: \"each even number no less than four can be expressed as the sum of two primes\". Let's modify it. How about a statement like that: \"each integer no less than 12 can be expressed as the sum of two composite numbers.\" Not like the Goldbach's conjecture, I can prove this theorem.\n\nYou are given an integer *n* no less than 12, express it as a sum of two composite numbers.",
"input": "",
"output": "```python\n\r\n\r\ndef iscomposite(n):\r\n for i in range(2,int(n/2 +1)):\r\n if n % i == 0 :\r\n return False\r\n else:\r\n continue\r\n return True\r\n\r\nm= int(input())\r\nfor i in range(4,m):\r\n if iscomposite(i):\r\n #print(\"{} is composite\".format(i))\r\n continue\r\n else:\r\n if iscomposite(m -i):\r\n #print(\"{} is composite\".format(m-i))\r\n continue\r\n else:\r\n print(m-i,i)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "One day a well-known sponsor of a well-known contest decided to give every participant of the contest a T-shirt as a present. A natural problem occurred: on the one hand, it is not clear how many T-shirts of what sizes should be ordered, and on the other hand, one doesn't want to order too many T-shirts (and we do not exactly paper the walls with the oversupply). After considerable brain racking and some pre-estimating, the sponsor representatives ordered a certain number of T-shirts of sizes S, M, L, XL and XXL. The T-shirts turned out to bring good luck, that's why on the contest day there built up a line of *K* participants willing to get one. Every contestant is characterized by his/her desired T-shirt size (so it happens that for all the participants it is also one of the sizes S, M, L, XL and XXL). The participants come up to get a T-shirt one by one and try to choose the most suitable one, choosing it like this. If there is still a T-shirt of the optimal size left, that he/she takes it without further ado. Otherwise the contestant would prefer to choose a T-shirt with the size as close to the optimal one as possible (the distance between neighboring sizes is considered equal to one). If the variant of choice is not unique, the contestant will take a T-shirt of a bigger size (in case he/she grows more). For example, for a person whose optimal size is L the preference list looks like this: L, XL, M, XXL, S. Using the data on how many T-shirts of every size had been ordered by the organizers, on the size of contestants in the line determine who got a T-shirt of what size.",
"input": "",
"output": "```python\nsizes = list(map(int, input().split()))\r\nf = {\"S\":0, \"M\":1, \"L\":2, \"XL\":3, \"XXL\":4}\r\ng = [\"S\", \"M\", \"L\", \"XL\", \"XXL\"]\r\nfor i in range(int(input())):\r\n size = input()\r\n idx = f[size]\r\n for j in range(5):\r\n try:\r\n #print(\"...\")\r\n if sizes[idx+j]>0:\r\n print(g[idx+j])\r\n sizes[idx+j] -= 1\r\n break\r\n if sizes[max(0, idx-j)]>0:\r\n print(g[max(0, idx-j)])\r\n sizes[max(0, idx-j)] -= 1\r\n break\r\n except:\r\n if sizes[max(0, idx-j)]>0:\r\n print(g[max(0, idx-j)])\r\n sizes[max(0, idx-j)] -= 1\r\n break\r\n \r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You've got a rectangular table with length *a* and width *b* and the infinite number of plates of radius *r*. Two players play the following game: they take turns to put the plates on the table so that the plates don't lie on each other (but they can touch each other), and so that any point on any plate is located within the table's border. During the game one cannot move the plates that already lie on the table. The player who cannot make another move loses. Determine which player wins, the one who moves first or the one who moves second, provided that both players play optimally well.",
"input": "",
"output": "```python\na, b, r = map(int, input().split())\r\nr *= 2\r\nprint('Second' if r > a or b < r else 'First')\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Your security guard friend recently got a new job at a new security company. The company requires him to patrol an area of the city encompassing exactly *N* city blocks, but they let him choose which blocks. That is, your friend must walk the perimeter of a region whose area is exactly *N* blocks. Your friend is quite lazy and would like your help to find the shortest possible route that meets the requirements. The city is laid out in a square grid pattern, and is large enough that for the sake of the problem it can be considered infinite.",
"input": "",
"output": "```python\nimport math\ndef Solution(N):\n N = math.sqrt(N)\n perimeter = 4 * N\n return perimeter\nN = int(input())\nSolution(N)\n\t\t \t\t \t\t \t\t \t\t\t \t\t\t \t\t \t\t\t\t\t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited *n* his friends there.\n\nIf there's one thing Petya likes more that receiving gifts, that's watching others giving gifts to somebody else. Thus, he safely hid the laptop until the next New Year and made up his mind to watch his friends exchanging gifts while he does not participate in the process. He numbered all his friends with integers from 1 to *n*. Petya remembered that a friend number *i* gave a gift to a friend number *p**i*. He also remembered that each of his friends received exactly one gift.\n\nNow Petya wants to know for each friend *i* the number of a friend who has given him a gift.",
"input": "",
"output": "```python\nn = input()\r\na = list(map(int, input().split()))\r\ndic = {i: g for i, g in enumerate(a, start=1)}\r\nnew_dict = {v: k for k, v in dic.items()}\r\nsorted_dict = sorted(new_dict.items())\r\nfor key, value in sorted_dict:\r\n print(value, end=\" \")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.\n\nReliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer *n*. Help Anton to determine the exchange rate of currency you all know for tomorrow!",
"input": "",
"output": "```python\n\n\nif __name__ == '__main__':\n s = list(input())\n smallest_even = -1\n has_even = False\n for i in range(len(s)):\n if int(s[i]) % 2 == 0:\n has_even = True\n if int(s[i]) < int(s[-1]):\n s[i], s[-1] = s[-1], s[i]\n print(''.join(s))\n break\n smallest_even = i\n\n if smallest_even == -1:\n print(\"-1\")\n else:\n s[smallest_even], s[-1] = s[-1], s[smallest_even]\n print(''.join(s))\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. \"Piece of cake\" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.",
"input": "",
"output": "```python\nsum = [0, 0, 0]\r\n\r\nfor _ in range(int(input())):\r\n a, b, c = map(int, input().split())\r\n sum[0] += a\r\n sum[1] += b\r\n sum[2] += c\r\n\r\nprint(\"YES\" if sum == [0, 0, 0] else \"NO\")\r\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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*.\n\nThe 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\".\n\nTanya 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.",
"input": "",
"output": "```python\nfrom collections import *\r\n\r\ns, t = deque(input()), input()\r\nmem, a1, a2 = Counter(t), 0, 0\r\n\r\nfor i in range(len(s)):\r\n if mem[s[0]]:\r\n a1 += 1\r\n mem[s[0]] -= 1\r\n s.popleft()\r\n else:\r\n s.rotate(-1)\r\n# print(s)\r\nfor i in s:\r\n if i.isupper() and mem[i.lower()]:\r\n a2 += 1\r\n mem[i.lower()] = 0\r\n elif i.islower() and mem[i.upper()]:\r\n a2 += 1\r\n mem[i.upper()] = 0\r\n\r\nprint(a1, a2)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word.\n\nHongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character of the word to the beginning of the word. He calls this a cyclic shift. He can apply cyclic shift many times. For example, consecutively applying cyclic shift operation to the word \"abracadabra\" Hongcow will get words \"aabracadabr\", \"raabracadab\" and so on.\n\nHongcow is now wondering how many distinct words he can generate by doing the cyclic shift arbitrarily many times. The initial string is also counted.",
"input": "",
"output": "```python\na = input()\r\nt = a\r\nr1 = len(a)\r\nfor i in range(len(a)):\r\n\ta = a[r1-1] + a[0:r1-1]\r\n\tif a == t:\r\n\t\tbreak\r\nprint(i+1)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "One day Vasya painted a Cartesian coordinate system on a piece of paper and marked some set of points (*x*1,<=*y*1),<=(*x*2,<=*y*2),<=...,<=(*x**n*,<=*y**n*). Let's define neighbors for some fixed point from the given set (*x*,<=*y*): \n - point (*x*',<=*y*') is (*x*,<=*y*)'s right neighbor, if *x*'<=><=*x* and *y*'<==<=*y* - point (*x*',<=*y*') is (*x*,<=*y*)'s left neighbor, if *x*'<=<<=*x* and *y*'<==<=*y* - point (*x*',<=*y*') is (*x*,<=*y*)'s lower neighbor, if *x*'<==<=*x* and *y*'<=<<=*y* - point (*x*',<=*y*') is (*x*,<=*y*)'s upper neighbor, if *x*'<==<=*x* and *y*'<=><=*y* \nWe'll consider point (*x*,<=*y*) from the given set supercentral, if it has at least one upper, at least one lower, at least one left and at least one right neighbor among this set's points.\n\nVasya marked quite many points on the paper. Analyzing the picture manually is rather a challenge, so Vasya asked you to help him. Your task is to find the number of supercentral points in the given set.",
"input": "",
"output": "```python\ntests = int(input())\r\nsetlist = []\r\n\r\ndef solution(setlist):\r\n points = 0\r\n for i in range(len(setlist)):\r\n right = 0\r\n left = 0\r\n upper = 0\r\n lower = 0\r\n for j in range(len(setlist)):\r\n \r\n if setlist[i][0] == setlist[j][0] and setlist[j][1] setlist[j][0] and setlist[j][1] == setlist[i][1]:\r\n left+=1\r\n \r\n if right>=1 and left>=1 and upper>=1 and lower>=1:\r\n points+=1\r\n return points\r\n\r\nfor _ in range(tests):\r\n sets = list(map(int,input().split()))\r\n setlist.append(sets)\r\n \r\nprint(solution(setlist))\r\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "The administration of the Tomsk Region firmly believes that it's time to become a megacity (that is, get population of one million). Instead of improving the demographic situation, they decided to achieve its goal by expanding the boundaries of the city.\n\nThe city of Tomsk can be represented as point on the plane with coordinates (0; 0). The city is surrounded with *n* other locations, the *i*-th one has coordinates (*x**i*, *y**i*) with the population of *k**i* people. You can widen the city boundaries to a circle of radius *r*. In such case all locations inside the circle and on its border are included into the city.\n\nYour goal is to write a program that will determine the minimum radius *r*, to which is necessary to expand the boundaries of Tomsk, so that it becomes a megacity.",
"input": "",
"output": "```python\nimport math\r\nx,y=map(int,input().split())\r\nr=dict()\r\nfor i in range(x):\r\n a,b,c = map(int, input().split())\r\n a=math.sqrt(pow(a,2)+pow(b,2))\r\n r[a]=c\r\nif(y>=1000000):\r\n print(\"0\")\r\nelse:\r\n for key in sorted(r):\r\n y+=r[key]\r\n if(y>=1000000):\r\n print(key)\r\n break\r\n #print(\"%s %s\"%(key,r[key]))\r\n else:\r\n print(\"-1\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Okabe and Super Hacker Daru are stacking and removing boxes. There are *n* boxes numbered from 1 to *n*. Initially there are no boxes on the stack.\n\nOkabe, being a control freak, gives Daru 2*n* commands: *n* of which are to add a box to the top of the stack, and *n* of which are to remove a box from the top of the stack and throw it in the trash. Okabe wants Daru to throw away the boxes in the order from 1 to *n*. Of course, this means that it might be impossible for Daru to perform some of Okabe's remove commands, because the required box is not on the top of the stack.\n\nThat's why Daru can decide to wait until Okabe looks away and then reorder the boxes in the stack in any way he wants. He can do it at any point of time between Okabe's commands, but he can't add or remove boxes while he does it.\n\nTell Daru the minimum number of times he needs to reorder the boxes so that he can successfully complete all of Okabe's commands. It is guaranteed that every box is added before it is required to be removed.",
"input": "",
"output": "```python\nn = int(input())\r\nst = 1\r\nstack = []\r\nans = 0\r\nfor _ in range(2*n):\r\n ops = input()\r\n if ops[0]=='a':\r\n _,k = ops.split()\r\n stack.append(int(k))\r\n else:\r\n if stack[-1]!=st:\r\n stack.sort(reverse=True)\r\n ans+=1\r\n stack.pop()\r\n st+=1\r\nprint(ans)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: \n - Tetrahedron. Tetrahedron has 4 triangular faces. - Cube. Cube has 6 square faces. - Octahedron. Octahedron has 8 triangular faces. - Dodecahedron. Dodecahedron has 12 pentagonal faces. - Icosahedron. Icosahedron has 20 triangular faces. \nAll five kinds of polyhedrons are shown on the picture below:\n\nAnton has a collection of *n* polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!",
"input": "",
"output": "```python\nn = int(input())\r\ntotal_faces = 0\r\nfor _ in range(n):\r\n shape = input().capitalize()\r\n if shape == \"Tetrahedron\" :\r\n total_faces +=4\r\n if shape == \"Cube\" :\r\n total_faces +=6\r\n if shape == \"Octahedron\" :\r\n total_faces +=8\r\n if shape == \"Dodecahedron\" :\r\n total_faces +=12\r\n if shape == \"Icosahedron\" :\r\n total_faces +=20\r\nprint(total_faces)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "The School №0 of the capital of Berland has *n* children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value *t**i*:\n - *t**i*<==<=1, if the *i*-th child is good at programming, - *t**i*<==<=2, if the *i*-th child is good at maths, - *t**i*<==<=3, if the *i*-th child is good at PE \nEach child happens to be good at exactly one of these three subjects.\n\nThe Team Scientific Decathlon Olympias requires teams of three students. The school teachers decided that the teams will be composed of three children that are good at different subjects. That is, each team must have one mathematician, one programmer and one sportsman. Of course, each child can be a member of no more than one team.\n\nWhat is the maximum number of teams that the school will be able to present at the Olympiad? How should the teams be formed for that?",
"input": "",
"output": "```python\ndef finder(point, x):\r\n inx = 0\r\n for i in range(len(point)):\r\n if point[i] == x:\r\n inx = i\r\n break\r\n return inx\r\n\r\ndef main():\r\n n = int(input())\r\n num = list(range(1, n + 1))\r\n point = list(map(int, input().split()))\r\n count = [0, 0, 0]\r\n\r\n for i in range(n):\r\n count[point[i] - 1] += 1\r\n\r\n min_count = min(count)\r\n print(min_count)\r\n \r\n for i in range(n - 1):\r\n swapped = True\r\n for j in range(n - 1 - i):\r\n if point[j] > point[j + 1]:\r\n point[j], point[j + 1] = point[j + 1], point[j]\r\n num[j], num[j + 1] = num[j + 1], num[j]\r\n swapped = False\r\n if swapped:\r\n break\r\n \r\n one_ind = finder(point, 1)\r\n two_ind = finder(point, 2)\r\n three_ind = finder(point, 3)\r\n\r\n for i in range(min_count):\r\n print(num[one_ind], num[two_ind], num[three_ind])\r\n one_ind += 1\r\n two_ind += 1\r\n three_ind += 1\r\n\r\nif __name__ == \"__main__\":\r\n main()# 1698230401.854687\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Limak is a little polar bear. He has *n* balls, the *i*-th ball has size *t**i*.\n\nLimak wants to give one ball to each of his three friends. Giving gifts isn't easy — there are two rules Limak must obey to make friends happy:\n - No two friends can get balls of the same size. - No two friends can get balls of sizes that differ by more than 2. \nFor example, Limak can choose balls with sizes 4, 5 and 3, or balls with sizes 90, 91 and 92. But he can't choose balls with sizes 5, 5 and 6 (two friends would get balls of the same size), and he can't choose balls with sizes 30, 31 and 33 (because sizes 30 and 33 differ by more than 2).\n\nYour task is to check whether Limak can choose three balls that satisfy conditions above.",
"input": "",
"output": "```python\nn = int(input())\na = sorted(map(int, input().split()))\nq = 0\np = -1\nans = False\nfor i in a:\n if i == p + 1:\n q += 1\n else:\n q = 1\n if q == 3:\n ans = True\n p = i\nprint('YES' if ans else 'NO')\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.\n\nAs for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:\n - There are *n* knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to *n*. - The tournament consisted of *m* fights, in the *i*-th fight the knights that were still in the game with numbers at least *l**i* and at most *r**i* have fought for the right to continue taking part in the tournament. - After the *i*-th fight among all participants of the fight only one knight won — the knight number *x**i*, he continued participating in the tournament. Other knights left the tournament. - The winner of the last (the *m*-th) fight (the knight number *x**m*) became the winner of the tournament. \nYou fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number *b* was conquered by the knight number *a*, if there was a fight with both of these knights present and the winner was the knight number *a*.\n\nWrite the code that calculates for each knight, the name of the knight that beat him.",
"input": "",
"output": "```python\n#!/usr/bin/env python3\n#-*- encoding: utf-8 -*-\n\nimport sys\n\ndef main():\n n, m = map(int, sys.stdin.readline().split())\n res = [0 for _ in range(n)]\n for i in range(m):\n l, r, x = map(int, sys.stdin.readline().split())\n for j in range(l,r+1):\n if res[j-1] == 0 and j !=x:\n res[j-1] = x\n print(' '.join(map(str, res)))\n return\n\nmain()\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Find an *n*<=×<=*n* matrix with different numbers from 1 to *n*2, so the sum in each row, column and both main diagonals are odd.",
"input": "",
"output": "```python\nN = int(input())\ncnt = 0\nthe_odd = -1\nthe_eve = 0\ndef get_with_eve_N(x, y) :\n\treturn -1\ndef get_with_odd_N(x, y) :\n\tglobal the_odd\n\tglobal the_eve\n\tif (x + y <= N + 1 >> 1 or x + y >= N + (N + 1 >> 1) + 1 or y - x >= N + 1 >> 1 or x - y >= N + 1 >> 1) :\n\t\tthe_eve += 2\n\t\treturn the_eve\n\telse :\n\t\tthe_odd += 2\n\t\treturn the_odd\nif N % 2 == 0 :\n\tfor i in range(1, N + 1) :\n\t\tfor j in range(1, N + 1) :\n\t\t\tif j == N :\n\t\t\t\tprint(get_with_eve_N(i, j))\n\t\t\telse :\n\t\t\t\tprint(get_with_eve_N(i, j), end = ' ')\nelse :\n\tfor i in range(1, N + 1) :\n\t\tfor j in range(1, N + 1) :\n\t\t\tif j == N :\n\t\t\t\tprint(get_with_odd_N(i, j))\n\t\t\telse :\n\t\t\t\tprint(get_with_odd_N(i, j), end = ' ')\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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:\n\n1. Each domino completely covers two squares.\n\n2. No two dominoes overlap.\n\n3. Each domino lies entirely inside the board. It is allowed to touch the edges of the board.\n\nFind the maximum number of dominoes, which can be placed under these restrictions.",
"input": "",
"output": "```python\na = str(input()).split()\r\n#for i in a:\r\nif (int(a[0]) * int(a[1]))%2 == 0:\r\n print((int(a[0]) * int(a[1]))//2)\r\nelif (int(a[0]) * int(a[1]))%2 != 0:\r\n print((int(a[0]) * int(a[1]))//2 )\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vova promised himself that he would never play computer games... But recently Firestorm — a well-known game developing company — published their newest game, World of Farcraft, and it became really popular. Of course, Vova started playing it.\n\nNow he tries to solve a quest. The task is to come to a settlement named Overcity and spread a rumor in it.\n\nVova knows that there are *n* characters in Overcity. Some characters are friends to each other, and they share information they got. Also Vova knows that he can bribe each character so he or she starts spreading the rumor; *i*-th character wants *c**i* gold in exchange for spreading the rumor. When a character hears the rumor, he tells it to all his friends, and they start spreading the rumor to their friends (for free), and so on.\n\nThe quest is finished when all *n* characters know the rumor. What is the minimum amount of gold Vova needs to spend in order to finish the quest?\n\nTake a look at the notes if you think you haven't understood the problem completely.",
"input": "",
"output": "```python\n\r\n\r\n''' Depth First Search (DFS) '''\r\ndef dfs(x, menor, a):\r\n\ta.append(prec[x])\r\n\tif prec[x] < menor:\r\n\t\tmenor = prec[x]\r\n\tvisited[x] = True\r\n\tfor y in graph[x]:\r\n\t\tif not(visited[y]):\r\n\t\t\tdfs(y, menor, a)\r\n \r\n \r\n \r\n \r\nn, m = map(int, input().split())\r\nprec = list(map(int, input().split()))\r\nprec = [0] + prec\r\ngraph = [[] for _ in range(n + 1)]\r\nvisited = [False] * (n + 1)\r\ntotal = 0\r\n\r\nfor _ in range(m):\r\n x, y = map(int, input().split())\r\n graph[x].append(y)\r\n graph[y].append(x)\r\n \r\n\r\nfor i in range(1, n+1):\r\n\r\n\tif visited[i] == False:\r\n\t\tr = []\r\n\t\tdfs(i, 10**10, r)\r\n\t\ttotal += min(r)\r\n\t\t\r\nprint(total)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "As you may know, MemSQL has American offices in both San Francisco and Seattle. Being a manager in the company, you travel a lot between the two cities, always by plane.\n\nYou prefer flying from Seattle to San Francisco than in the other direction, because it's warmer in San Francisco. You are so busy that you don't remember the number of flights you have made in either direction. However, for each of the last *n* days you know whether you were in San Francisco office or in Seattle office. You always fly at nights, so you never were at both offices on the same day. Given this information, determine if you flew more times from Seattle to San Francisco during the last *n* days, or not.",
"input": "",
"output": "```python\nip_no_days=int(input())\r\ndata_diff_days=input()\r\n\r\ncountSF=0\r\ncountFS=0\r\n\r\nfor i in range(1,len(data_diff_days)):\r\n if data_diff_days[i-1]=='S' and data_diff_days[i]=='F':\r\n countSF+=1\r\n elif data_diff_days[i-1]=='F' and data_diff_days[i]=='S':\r\n countFS+=1\r\n else:\r\n continue\r\n\r\nif countSF>countFS:\r\n print(\"YES\")\r\nelse:\r\n print(\"NO\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vasya plays the sleuth with his friends. The rules of the game are as follows: those who play for the first time, that is Vasya is the sleuth, he should investigate a \"crime\" and find out what is happening. He can ask any questions whatsoever that can be answered with \"Yes\" or \"No\". All the rest agree beforehand to answer the questions like that: if the question’s last letter is a vowel, they answer \"Yes\" and if the last letter is a consonant, they answer \"No\". Of course, the sleuth knows nothing about it and his task is to understand that.\n\nUnfortunately, Vasya is not very smart. After 5 hours of endless stupid questions everybody except Vasya got bored. That’s why Vasya’s friends ask you to write a program that would give answers instead of them.\n\nThe English alphabet vowels are: A, E, I, O, U, Y\n\nThe English alphabet consonants are: B, C, D, F, G, H, J, K, L, M, N, P, Q, R, S, T, V, W, X, Z",
"input": "",
"output": "```python\ns=input().upper().split()\r\ns=\"\".join(s)\r\nl=['A','E','I','O','U','Y']\r\nn=len(s)\r\nif s[n-2] in l:\r\n\tprint(\"YES\")\r\nelse:\r\n\tprint(\"NO\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "This winter is so cold in Nvodsk! A group of *n* friends decided to buy *k* bottles of a soft drink called \"Take-It-Light\" to warm up a bit. Each bottle has *l* milliliters of the drink. Also they bought *c* limes and cut each of them into *d* slices. After that they found *p* grams of salt.\n\nTo make a toast, each friend needs *nl* milliliters of the drink, a slice of lime and *np* grams of salt. The friends want to make as many toasts as they can, provided they all drink the same amount. How many toasts can each friend make?",
"input": "",
"output": "```python\nn, k, l, c, d, p, nl, np = map(int, input().split())\r\nres = min(((k*l)//nl), (c*d), (p//np))//n\r\nprint(int(res))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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:\n\n1. Each domino completely covers two squares.\n\n2. No two dominoes overlap.\n\n3. Each domino lies entirely inside the board. It is allowed to touch the edges of the board.\n\nFind the maximum number of dominoes, which can be placed under these restrictions.",
"input": "",
"output": "```python\nn,b=map(int,input().split())\r\ncount=0\r\nif n%2==0 or b%2==0:\r\n count=(n*b)//2\r\nelse:\r\n count=((n*b)-1)//2\r\nprint(count)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. \"Piece of cake\" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.",
"input": "",
"output": "```python\nn=int(input())\r\nsum1=sum2=sum3=0\r\nfor i in range(n):\r\n x,y,z=map(int,input().split())\r\n sum1+=x\r\n sum2+=y\r\n sum3+=z\r\nif sum1==0 and sum2==0 and sum3==0:\r\n print('YES')\r\nelse:\r\n print('NO')\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Appleman and Toastman play a game. Initially Appleman gives one group of *n* numbers to the Toastman, then they start to complete the following tasks:\n - Each time Toastman gets a group of numbers, he sums up all the numbers and adds this sum to the score. Then he gives the group to the Appleman. - Each time Appleman gets a group consisting of a single number, he throws this group out. Each time Appleman gets a group consisting of more than one number, he splits the group into two non-empty groups (he can do it in any way) and gives each of them to Toastman. \nAfter guys complete all the tasks they look at the score value. What is the maximum possible value of score they can get?",
"input": "",
"output": "```python\ndef f(x):\r\n i =-1\r\n while 2**(i+1) <= x:\r\n i += 1\r\n return i\r\nn = int(input())\r\ns = list(map(int,input().split()))\r\nadd = 0\r\nfor i in range(len(s)):\r\n add += s[i]\r\n\r\ntotal = 0\r\ns.sort(reverse = True)\r\nline = []\r\nwhile n > 0:\r\n t = f(n)\r\n line.append(t)\r\n n -= 2**t\r\n\r\na,b = 0,0\r\nfor i in range(len(line)):\r\n b += 2**line[i]\r\n sum = 0\r\n for j in range(a,b):\r\n sum += s[j]\r\n total += sum*(1+line[i])\r\n a = b\r\n\r\nif 2**line[0] < add:\r\n total += add\r\n \r\nprint(total)\r\n \r\n \r\n \r\n\r\n\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "According to a new ISO standard, a flag of every country should have a chequered field *n*<=×<=*m*, each square should be of one of 10 colours, and the flag should be «striped»: each horizontal row of the flag should contain squares of the same colour, and the colours of adjacent horizontal rows should be different. Berland's government asked you to find out whether their flag meets the new ISO standard.",
"input": "",
"output": "```python\nn, m = [int(i) for i in input().split()]\r\nlast = '.'\r\n\r\nfor i in range(n):\r\n s = input()\r\n if last == s[0]:\r\n print('NO')\r\n exit(0)\r\n if s != s[0] * m:\r\n print('NO')\r\n exit(0)\r\n last = s[0]\r\nprint('YES')\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.",
"input": "",
"output": "```python\ns = list(input())\nt = input()\nn = len(s)\nfor i in range(n//2):\n temp = s[i]\n s[i] = s[n - (i+1)]\n s[n - (i+1)] = temp\nnew_s = ''.join(map(str, s))\nif t == new_s:\n print('YES')\nelse:\n print('NO')\n\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Let's consider one interesting word game. In this game you should transform one word into another through special operations. \n\nLet's say we have word *w*, let's split this word into two non-empty parts *x* and *y* so, that *w*<==<=*xy*. A split operation is transforming word *w*<==<=*xy* into word *u*<==<=*yx*. For example, a split operation can transform word \"wordcut\" into word \"cutword\".\n\nYou are given two words *start* and *end*. Count in how many ways we can transform word *start* into word *end*, if we apply exactly *k* split operations consecutively to word *start*. \n\nTwo ways are considered different if the sequences of applied operations differ. Two operation sequences are different if exists such number *i* (1<=≤<=*i*<=≤<=*k*), that in the *i*-th operation of the first sequence the word splits into parts *x* and *y*, in the *i*-th operation of the second sequence the word splits into parts *a* and *b*, and additionally *x*<=≠<=*a* holds.",
"input": "",
"output": "```python\nMOD=10**9+7\r\n\r\n# @cache\r\ndef slove():\r\n # if v==0: return 0\r\n # n=int(input())\r\n a=str(input())\r\n b=str(input())\r\n n=len(a)\r\n k=int(input())\r\n if n==2:\r\n if a==b: \r\n print('1' if k&1==0 else '0')\r\n elif a[::-1]==b:\r\n print('1' if k&1 else '0')\r\n else:\r\n print('0')\r\n return \r\n if k==0:\r\n print('1' if a==b else '0')\r\n return \r\n \r\n cut=[]\r\n for i in range(n):\r\n w=a[i:]+a[:i]\r\n if w==b:\r\n cut.append(i)\r\n if len(cut)==0:\r\n print('0')\r\n # elif len(cut)>=1:\r\n else:\r\n f=1 if a==b else 0\r\n for i in range(k):\r\n f=pow(n-1,i)*len(cut)-f\r\n f%=MOD\r\n print(f)\r\n return \r\n return \r\n\r\n \r\n \r\n# t=int(input())\r\nt=1\r\n# M=1<<30\r\nfor _ in range(t):\r\n # v=int(input())\r\n slove()\r\n # print(ans)\r\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Email address in Berland is a string of the form *A*@*B*, where *A* and *B* are arbitrary strings consisting of small Latin letters. \n\nBob is a system administrator in «Bersoft» company. He keeps a list of email addresses of the company's staff. This list is as a large string, where all addresses are written in arbitrary order, separated by commas. The same address can be written more than once.\n\nSuddenly, because of unknown reasons, all commas in Bob's list disappeared. Now Bob has a string, where all addresses are written one after another without any separators, and there is impossible to determine, where the boundaries between addresses are. Unfortunately, on the same day his chief asked him to bring the initial list of addresses. Now Bob wants to disjoin addresses in some valid way. Help him to do that.",
"input": "",
"output": "```python\ns = input()\nindexsi = []\nfor i in range(len(s)):\n if s[i] == \"@\":\n indexsi.append(i)\nans = \"\"\nleft = 0\ntemp = True\n#print(*indexsi)\nfor i in range(len(indexsi)):\n if indexsi[i] == 0 or indexsi[i] == len(s)-1:\n temp = False\n break\n if i != 0 and indexsi[i] - indexsi[i-1] <= 2:\n temp = False\n break\n ans += s[left:indexsi[i]+2]\n left = indexsi[i]+2\n if i != len(indexsi)-1:\n ans += ','\n\nif temp:\n print(ans)\nelse:\n print(\"No solution\")\n\n\n \t\t \t \t\t \t\t\t \t \t \t\t\t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array *a* consisting of *n* distinct integers.\n\nUnfortunately, the size of *a* is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question correctly: is it possible to sort the array *a* (in increasing order) by reversing exactly one segment of *a*? See definitions of segment and reversing in the notes.",
"input": "",
"output": "```python\ndef check(arr):\r\n \r\n temp = sorted(arr)\r\n n = len(arr)\r\n\r\n cnt = 0 \r\n\r\n segment = False \r\n\r\n p1 = -1 \r\n p2 = -2 \r\n for i in range(n):\r\n if arr[i] != temp[i]:\r\n if not segment :\r\n segment = True \r\n p1 = i \r\n elif segment :\r\n segment = False \r\n p2 = i \r\n cnt += 1 \r\n \r\n if cnt > 1: \r\n print(\"no\")\r\n return \r\n\r\n if cnt == 0 : \r\n print(\"yes\")\r\n print(\"1 1\")\r\n return \r\n for i in range(p2-1, p1+1, -1):\r\n if arr[i] > arr[i-1] : \r\n print(\"no\")\r\n return \r\n\r\n print(\"yes\")\r\n\r\n p1 += 1 \r\n if p1 > p2 :\r\n p1, p2 = p2, p1\r\n print(f\"{p1} {p2}\")\r\n \r\n\r\n\r\nn = int(input())\r\narr = [int(i) for i in input().split()]\r\n\r\nispossible = check(arr)\r\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Little Susie loves strings. Today she calculates distances between them. As Susie is a small girl after all, her strings contain only digits zero and one. She uses the definition of Hamming distance:\n\nWe will define the distance between two strings *s* and *t* of the same length consisting of digits zero and one as the number of positions *i*, such that *s**i* isn't equal to *t**i*. \n\nAs besides everything else Susie loves symmetry, she wants to find for two strings *s* and *t* of length *n* such string *p* of length *n*, that the distance from *p* to *s* was equal to the distance from *p* to *t*.\n\nIt's time for Susie to go to bed, help her find such string *p* or state that it is impossible.",
"input": "",
"output": "```python\na = input()\r\nb = input() \r\nx = str(int(a) ^ int(b))\r\nif x.count(\"1\") %2 != 0 :\r\n print(\"IMPOSSIBLE\")\r\nelse : \r\n res = \"\"\r\n flag1 = True \r\n for idx , value in enumerate(x) : \r\n if value == \"0\":\r\n res += str(a)[idx] \r\n else: \r\n if flag1 :\r\n res += \"1\"\r\n flag1 =False\r\n else:\r\n res += \"0\"\r\n flag1 = True\r\n print(res) \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "— I experienced so many great things.\n\n— You gave me memories like dreams... But I have to leave now...\n\n— One last request, can you...\n\n— Help me solve a Codeforces problem?\n\n— ......\n\n— What?\n\nChtholly has been thinking about a problem for days:\n\nIf a number is palindrome and length of its decimal representation without leading zeros is even, we call it a zcy number. A number is palindrome means when written in decimal representation, it contains no leading zeros and reads the same forwards and backwards. For example 12321 and 1221 are palindromes and 123 and 12451 are not. Moreover, 1221 is zcy number and 12321 is not.\n\nGiven integers *k* and *p*, calculate the sum of the *k* smallest zcy numbers and output this sum modulo *p*.\n\nUnfortunately, Willem isn't good at solving this kind of problems, so he asks you for help!",
"input": "",
"output": "```python\ndef main(length, r, num, rev, length2):\r\n global left, res, p\r\n if length == 0:\r\n if left == 0:\r\n return\r\n res += num * r * 10 + rev\r\n res %= p\r\n left -= 1\r\n else:\r\n for j in range(10):\r\n if left == 0:\r\n return\r\n main(length - 1, r, num * 10 + j, j * (10 ** length2) + rev, length2 + 1)\r\n\r\nk, p = map(int, input().split())\r\nleft = k\r\nres = 0\r\nindicator = True\r\nfor length in range(1, 100):\r\n if not indicator:\r\n break\r\n r = 10 ** (length - 1)\r\n for i in range(1, 10):\r\n if left == 0:\r\n indicator = False\r\n break\r\n main(length - 1, r, i, i, 1)\r\nprint(res)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are given an array of positive integers *a*1,<=*a*2,<=...,<=*a**n*<=×<=*T* of length *n*<=×<=*T*. We know that for any *i*<=><=*n* it is true that *a**i*<==<=*a**i*<=-<=*n*. Find the length of the longest non-decreasing sequence of the given array.",
"input": "",
"output": "```python\nf = lambda: map(int, input().split())\r\nn, m = f()\r\nt = list(f())\r\ns = [0] * 301\r\nd = s[:]\r\nfor i in t: d[i] += 1\r\nfor i in t * min(m, 2 * n): s[i] = max(s[:i + 1]) + 1\r\nprint(max(s) + max((m - n * 2) * max(d), 0))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A and B are preparing themselves for programming contests.\n\nB loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.\n\nInitially, the compiler displayed *n* compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix some mistake and then another one mistake.\n\nHowever, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared — the compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, compilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change.\n\nCan you help B find out exactly what two errors he corrected?",
"input": "",
"output": "```python\nn = int(input())\r\nlst = [int(i) for i in input().split()]\r\nlst.sort()\r\nfor i in range(2):\r\n new_lst = [int(i) for i in input().split()]\r\n new_lst.sort()\r\n #print(new_lst)\r\n #print(lst)\r\n fl = True\r\n for i in range(len(new_lst)):\r\n if new_lst[i] != lst[i]:\r\n print(lst[i])\r\n fl = False\r\n break\r\n if fl:\r\n print(lst[-1])\r\n lst = new_lst.copy()\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Little girl Alyona is in a shop to buy some copybooks for school. She study four subjects so she wants to have equal number of copybooks for each of the subjects. There are three types of copybook's packs in the shop: it is possible to buy one copybook for *a* rubles, a pack of two copybooks for *b* rubles, and a pack of three copybooks for *c* rubles. Alyona already has *n* copybooks.\n\nWhat is the minimum amount of rubles she should pay to buy such number of copybooks *k* that *n*<=+<=*k* is divisible by 4? There are infinitely many packs of any type in the shop. Alyona can buy packs of different type in the same purchase.",
"input": "",
"output": "```python\nn, a, b, c = map(int, input().split())\r\nx = n%4\r\nans = 0\r\nif x == 0:\r\n\tans = 0\r\nelif x == 3:\r\n\tans = a\r\nelif x == 2:\r\n\tans = min(a*2,b)\r\nelse:\r\n\tans = min(a*3,a+b,c)\r\nprint (ans)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Polycarpus takes part in the \"Field of Wonders\" TV show. The participants of the show have to guess a hidden word as fast as possible. Initially all the letters of the word are hidden.\n\nThe game consists of several turns. At each turn the participant tells a letter and the TV show host responds if there is such letter in the word or not. If there is such letter then the host reveals all such letters. For example, if the hidden word is \"abacaba\" and the player tells the letter \"a\", the host will reveal letters at all positions, occupied by \"a\": 1, 3, 5 and 7 (positions are numbered from left to right starting from 1).\n\nPolycarpus knows *m* words of exactly the same length as the hidden word. The hidden word is also known to him and appears as one of these *m* words.\n\nAt current moment a number of turns have already been made and some letters (possibly zero) of the hidden word are already revealed. Previously Polycarp has told exactly the letters which are currently revealed.\n\nIt is Polycarpus' turn. He wants to tell a letter in such a way, that the TV show host will assuredly reveal at least one more letter. Polycarpus cannot tell the letters, which are already revealed.\n\nYour task is to help Polycarpus and find out the number of letters he can tell so that the show host will assuredly reveal at least one of the remaining letters.",
"input": "",
"output": "```python\nn=int(input())\r\ns=input()\r\nlet=dict()\r\na=[]\r\nc=0\r\nfor i in range(n):\r\n let[s[i]]=let.get(s[i],0)+1\r\nm=int(input())\r\nfor i in range(m):\r\n a.append(input())\r\nfor i in range(ord('a'),ord('z')+1):\r\n if let.get(chr(i),0)!=0: continue\r\n flag2=1\r\n for j in range(m):\r\n flag1=1\r\n letc=dict()\r\n for k in range(n):\r\n if s[k]==\"*\" and let.get(a[j][k],0)!=0:\r\n flag1=0\r\n break\r\n if s[k]==\"*\":\r\n letc[a[j][k]]=letc.get(a[j][k],0)+1\r\n elif s[k]!=a[j][k]:\r\n flag1=0\r\n if flag1 and letc.get(chr(i),0)==0:\r\n flag2=0\r\n if flag2:\r\n c=+1\r\nprint(c)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "wHAT DO WE NEED cAPS LOCK FOR?\n\nCaps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage. \n\nLet's consider that a word has been typed with the Caps lock key accidentally switched on, if: \n - either it only contains uppercase letters; - or all letters except for the first one are uppercase. \nIn this case we should automatically change the case of all letters. For example, the case of the letters that form words \"hELLO\", \"HTTP\", \"z\" should be changed.\n\nWrite a program that applies the rule mentioned above. If the rule cannot be applied, the program should leave the word unchanged.",
"input": "",
"output": "```python\nword = input()\n\nif word == word.upper():\n print(word.swapcase())\nelif word == word.capitalize().swapcase():\n print(word.swapcase())\nelse:\n print(word)\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer.\n\nAt 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).\n\nIf 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.\n\nKay 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.",
"input": "",
"output": "```python\n#####--------------Template Begin-------------------####\r\nimport math\r\nimport sys\r\n#input = sys.stdin.readline\r\ndef ri(): #Regular input\r\n\treturn input()\r\ndef ii(): #integer input\r\n\treturn int(input())\r\ndef li(): #list input\r\n\treturn input().split()\r\ndef mi(): #map input\r\n\treturn list(map(int, input().split()))\r\n#####---------------Template Ends-------------------######\r\nn,x=mi()\r\nd=0\r\nfor i in range(n):\r\n\tline=ri().split()\r\n\tif line[0]==\"+\":\r\n\t\tx+=int(line[1])\r\n\telse:\r\n\t\tif x>=int(line[1]):\r\n\t\t\tx-=int(line[1])\r\n\t\telse:\r\n\t\t\td+=1\r\n\r\n\r\nprint(x, d)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are given two arrays of integers *a* and *b*. For each element of the second array *b**j* you should find the number of elements in array *a* that are less than or equal to the value *b**j*.",
"input": "",
"output": "```python\nlengths = list(map(int, input().split()))\na = list(map(int, input().split()))\nb = list(map(int, input().split()))\n\nres = []\n\na.sort()\nfor i in range(len(b)):\n low = 0\n high = lengths[0]\n chosen = 0\n control = 0\n while low < high:\n mid = int((low + high) // 2)\n if a[mid] <= b[i]:\n chosen = mid + 1\n low = mid\n else:\n high = mid\n\n if control == mid: break\n control = mid\n res.append(chosen)\n\nprint(*res)\n\t\t \t\t\t\t\t \t \t\t\t\t \t \t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?\n\nYou are given a system of equations: \n\nYou should count, how many there are pairs of integers (*a*,<=*b*) (0<=≤<=*a*,<=*b*) which satisfy the system.",
"input": "",
"output": "```python\nimport math\n\nn, m = [int(x) for x in input().split()]\ncount = 0\na_limit = min(math.floor(math.sqrt(n)), m)\nb_limit = min(math.floor(math.sqrt(m)), n)\nfor a in range(0, a_limit + 1):\n for b in range(0, b_limit + 1):\n if (a**2 + b) == n and (a + b**2) == m:\n count+=1\nprint(count)\n \t \t\t\t\t \t\t \t \t\t\t \t\t\t \t\t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You're given a row with $n$ chairs. We call a seating of people \"maximal\" if the two following conditions hold:\n 1. There are no neighbors adjacent to anyone seated. 1. It's impossible to seat one more person without violating the first rule. \nThe seating is given as a string consisting of zeros and ones ($0$ means that the corresponding seat is empty, $1$ — occupied). The goal is to determine whether this seating is \"maximal\".\n\nNote that the first and last seats are not adjacent (if $n \\ne 2$).",
"input": "",
"output": "```python\ndef is_maximal(seating):\r\n # Count the number of zeros and ones in the seating\r\n zeros = seating.count(\"0\")\r\n ones = seating.count(\"1\")\r\n\r\n # Check if the seating is maximal\r\n if (zeros == 1 and ones == 0) or (ones == 1 and zeros == 0):\r\n return \"Yes\"\r\n else:\r\n return \"No\"\r\n\r\n# Test the function with some examples\r\nprint(is_maximal(\"001\")) # Should print \"Yes\"\r\nprint(is_maximal(\"101\")) # Should print \"No\"\r\nprint(is_maximal(\"110\")) # Should print \"Yes\"\r\nprint(is_maximal(\"010\")) # Should print \"No\"\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "— Willem...\n\n— What's the matter?\n\n— It seems that there's something wrong with Seniorious...\n\n— I'll have a look...\n\n\n\nSeniorious is made by linking special talismans in particular order.\n\nAfter over 500 years, the carillon is now in bad condition, so Willem decides to examine it thoroughly.\n\nSeniorious has *n* pieces of talisman. Willem puts them in a line, the *i*-th of which is an integer *a**i*.\n\nIn order to maintain it, Willem needs to perform *m* operations.\n\nThere are four types of operations:\n- 1 *l* *r* *x*: For each *i* such that *l*<=≤<=*i*<=≤<=*r*, assign *a**i*<=+<=*x* to *a**i*.- 2 *l* *r* *x*: For each *i* such that *l*<=≤<=*i*<=≤<=*r*, assign *x* to *a**i*.- 3 *l* *r* *x*: Print the *x*-th smallest number in the index range [*l*,<=*r*], i.e. the element at the *x*-th position if all the elements *a**i* such that *l*<=≤<=*i*<=≤<=*r* are taken and sorted into an array of non-decreasing integers. It's guaranteed that 1<=≤<=*x*<=≤<=*r*<=-<=*l*<=+<=1.- 4 *l* *r* *x* *y*: Print the sum of the *x*-th power of *a**i* such that *l*<=≤<=*i*<=≤<=*r*, modulo *y*, i.e. .",
"input": "",
"output": "```python\n#warning By KonJAC_xrs\n#warning ( testing == 0 ) ? Yes : No\n\n#include\n#define ll long long\n#define ull unsigned long long\n#define ld long double\nusing namespace std;\n\ninline ll read()\n{\n ll x=0,f=1; char ch=getchar();\n while (!isdigit(ch)) {if(ch=='-') f=-1; ch=getchar();}\n while ( isdigit(ch)) {x = x * 10+ch-48; ch=getchar();}\n return x*f;\n}\n\ninline void xrs(ll x)\n{\n if(x<0) putchar('-') , x=-x;\n if(x>9) xrs(x/10);\n putchar(x%10+'0');\n}\n\n//const ll inf=;\nconst ll mod=1e9+7;\nconst ll nore=2e5+20;\n\nll n,m,sed,vmax;\n\nstruct Chtholly_Tree{\n\t\n\tstruct node{\n\t\tll l,r;\n\t\tmutable ll val;\n\t\tnode (ll x,ll y,ll z) : l(x),r(y),val(z) {}\n\t\tnode (ll x) : l(x) {}\n\t\tbool operator < (const node &b) const {return l s;\n\t#define ss set < node > :: iterator\n\t\n\tinline ss spilt(ll pos)\n\t{\n\t\t#define louwo_bengda lower_bound\n\t\tss it=s.louwo_bengda(node(pos));\n\t\tif(it!=s.end() and it->l==pos)\n\t\t\treturn it;\n\t\tit--;\n\t\tll l=it->l , r=it->r , val=it->val;\n\t\ts.erase(it);\n\t\ts.insert(node(l,pos-1,val));\n\t\treturn s.insert(node(pos,r,val)).first;\n\t}\n\t\n\tinline void assign(ll l,ll r,ll val)\n\t{\n\t\tss it_r=spilt(r+1); ss it_l=spilt(l);\n\t\ts.erase(it_l,it_r);\n\t\ts.insert(node(l,r,val));\n\t}\n\t\n\tinline void add(ll l,ll r,ll val)\n\t{\n\t\tss it_r=spilt(r+1); ss it_l=spilt(l);\n\t\tfor(register ss it=it_l;it!=it_r;it++)\n\t\t\tit->val+=val;\n\t}\n\t\n\tinline ll kth(ll l,ll r,ll k)\n\t{\n\t\tss it_r=spilt(r+1); ss it_l=spilt(l);\n\t\tvector < pair < ll , ll > > v;\n\t\tfor(register ss it=it_l;it!=it_r;it++)\n\t\t\tv.push_back(make_pair(it->val,it->r-it->l+1));\n\t\tsort(v.begin(),v.end());\n\t\tfor(register ll i=0;i>=1;\n\t\t}\n\t\treturn ans;\n\t}\n\t\n\tinline ll ask(ll l,ll r,ll x,ll y)\n\t{\n\t\tss it_r=spilt(r+1); ss it_l=spilt(l);\n\t\tll ans=0;\n\t\tfor(register ss it=it_l;it!=it_r;it++)\n\t\t\tans=(ans+((it->r-it->l+1)*ksm(it->val,x,y)))%y;\n\t\treturn ans;\n\t}\n\t\n}ODT;\n\ninline ll randd()\n{\n\tll ret=sed;\n\tsed=(sed*7+13)%mod;\n\treturn ret;\n}\n\nint main()\n{\n//\tfreopen(\".in\",\"r\",stdin);\n//\tfreopen(\".out\",\"w\",stdout);\n\tn=read(); m=read(); sed=read(); vmax=read();\n\tfor(register ll i=1;i<=n;i++)\n\t{\n\t\tll a=randd()%vmax+1;\n\t\tODT.s.insert(Chtholly_Tree::node(i,i,a));\n\t}\n//\tODT.s.insert(Chtholly_Tree::node(n+1,n+1,0));\n\tfor(register ll i=1;i<=m;i++)\n\t{\n\t\tshort int opt=randd()%4+1;\n\t\tll l=randd()%n+1; ll r=randd()%n+1;\n\t\tll x,y;\n\t\tif(l>r) swap(l,r);\n\t\tif(opt==3)\n\t\t\tx=randd()%(r-l+1)+1;\n\t\telse\n\t\t\tx=randd()%vmax+1;\n\t\tif(opt==4)\n\t\t\ty=randd()%vmax+1;\n\t\tif(opt==1)\n\t\t\tODT.add(l,r,x);\n\t\telse if(opt==2)\n\t\t\tODT.assign(l,r,x);\n\t\telse if(opt==3)\n\t\t\txrs(ODT.kth(l,r,x)) , puts(\"\");\n\t\telse\n\t\t\txrs(ODT.ask(l,r,x,y)) , puts(\"\");\n\t}\n getchar();\n return 0;\n}\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "В самолёте есть *n* рядов мест. Если смотреть на ряды сверху, то в каждом ряду есть 3 места слева, затем проход между рядами, затем 4 центральных места, затем ещё один проход между рядами, а затем ещё 3 места справа.\n\nИзвестно, что некоторые места уже заняты пассажирами. Всего есть два вида пассажиров — статусные (те, которые часто летают) и обычные. \n\nПеред вами стоит задача рассадить ещё *k* обычных пассажиров так, чтобы суммарное число соседей у статусных пассажиров было минимально возможным. Два пассажира считаются соседями, если они сидят в одном ряду и между ними нет других мест и прохода между рядами. Если пассажир является соседним пассажиром для двух статусных пассажиров, то его следует учитывать в сумме соседей дважды.",
"input": "",
"output": "```python\nfrom collections import Counter\r\nn,k=list(map(int,input().split()))\r\n#n,k=1,2\r\na=set()\r\nc=[set() for i in range(3)]\r\nb=set()\r\nz=0\r\nfor i in range(n):\r\n s=input()\r\n for i0 in range(len(s)):\r\n if s[i0]=='.':\r\n a.add(tuple([i,i0]))\r\n elif s[i0]=='S':\r\n b.add(tuple([i,i0]))\r\n for i0 in range(len(s)):\r\n if s[i0]=='.':\r\n zz=0\r\n if tuple([i,i0+1]) in b:\r\n zz=zz+1\r\n if tuple([i,i0-1]) in b:\r\n zz=zz+1\r\n c[zz].add(tuple([i,i0]))\r\nc=list(c[0])+list(c[1])+list(c[2])\r\nfor i in range(k):\r\n a.remove(c[i])\r\nfor i in b:\r\n if (i[1]!=2)and(i[1]!=7)and(i[1]!=11):\r\n if not(tuple([i[0],i[1]+1])in a):\r\n z=z+1\r\n if (i[1]!=4)and(i[1]!=9)and(i[1]!=0):\r\n if not(tuple([i[0],i[1]-1])in a):\r\n z=z+1\r\nc=set(c)\r\n\r\nprint(z)\r\nfor i in range(n):\r\n s=''\r\n for i0 in range(12):\r\n if i0==3 or i0==8:\r\n s=s+'-'\r\n elif tuple([i,i0])in a:\r\n s=s+'.'\r\n elif tuple([i,i0])in b:\r\n s=s+'S'\r\n elif tuple([i,i0])in c:\r\n s=s+'x'\r\n else:\r\n s=s+'P'\r\n print(s)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Jon fought bravely to rescue the wildlings who were attacked by the white-walkers at Hardhome. On his arrival, Sam tells him that he wants to go to Oldtown to train at the Citadel to become a maester, so he can return and take the deceased Aemon's place as maester of Castle Black. Jon agrees to Sam's proposal and Sam sets off his journey to the Citadel. However becoming a trainee at the Citadel is not a cakewalk and hence the maesters at the Citadel gave Sam a problem to test his eligibility. \n\nInitially Sam has a list with a single element *n*. Then he has to perform certain operations on this list. In each operation Sam must remove any element *x*, such that *x*<=><=1, from the list and insert at the same position , , sequentially. He must continue with these operations until all the elements in the list are either 0 or 1.\n\nNow the masters want the total number of 1s in the range *l* to *r* (1-indexed). Sam wants to become a maester but unfortunately he cannot solve this problem. Can you help Sam to pass the eligibility test?",
"input": "",
"output": "```python\nn, l, r = map(int, input().split())\r\narr = [n]\r\ndef helper(n):\r\n if n <=1:\r\n return\r\n elif n>1:\r\n substitute = [n//2, n%2,n//2]\r\n i = arr.index(n)\r\n arr[i:i+1] = substitute\r\n helper(n//2)\r\n helper(n%2)\r\n helper(n//2)\r\nhelper(n)\r\n\r\nprint(sum(arr[l-1:r]))\r\n \r\n\r\n\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.",
"input": "",
"output": "```python\nn=int(input())\r\nl=list(map(int,input().split()))\r\neven,odd,evenind,oddind=0,0,0,0\r\nfor i in range(n):\r\n if (l[i]%2==0):\r\n even += 1\r\n evenind = i\r\n else:\r\n even -= 1\r\n oddind = i\r\nif(even > 0):\r\n print(oddind+1)\r\nelse:\r\n print(evenind+1)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vasya has become interested in wrestling. In wrestling wrestlers use techniques for which they are awarded points by judges. The wrestler who gets the most points wins.\n\nWhen the numbers of points of both wrestlers are equal, the wrestler whose sequence of points is lexicographically greater, wins.\n\nIf the sequences of the awarded points coincide, the wrestler who performed the last technique wins. Your task is to determine which wrestler won.",
"input": "",
"output": "```python\nimport math\r\nfrom decimal import *\r\nimport random\r\nmod = int(1e9)+7\r\n\r\nf, s = 0,0\r\nx, y= [],[]\r\nlast = -1\r\nfor _ in range(int(input())):\r\n n = int(input())\r\n if(n>0):\r\n x.append(n)\r\n f+=n\r\n last = 1\r\n else:\r\n y.append(abs(n))\r\n s+=abs(n)\r\n last = 0\r\nif(f>s):\r\n print('first')\r\nif(s>f):\r\n print('second')\r\nif(s==f):\r\n if(len(x)>len(y)):\r\n fnd = True\r\n for i in range(len(y)):\r\n if(x[i]!=y[i]):\r\n fnd = False\r\n break\r\n if(fnd):\r\n print('first')\r\n else:\r\n fwin = True\r\n pnt=0\r\n while(pnty[pnt]):\r\n fwin = True\r\n break\r\n elif(x[pnt]==y[pnt]):\r\n pnt+=1\r\n else:\r\n fwin =False\r\n if(fwin and pnt!= len(y)):\r\n print('first')\r\n elif(not fwin and pnt!= len(y)):\r\n print('second')\r\n else:\r\n if(last):\r\n print('first')\r\n else:\r\n print('second')\r\n elif(len(y)>len(x)):\r\n fnd = True\r\n for i in range(len(x)):\r\n if(x[i]!=y[i]):\r\n fnd = False\r\n break\r\n if(fnd):\r\n print('second')\r\n else:\r\n fwin = True\r\n pnt=0\r\n while(pnty[pnt]):\r\n fwin = True\r\n break\r\n elif(x[pnt]==y[pnt]):\r\n pnt+=1\r\n else:\r\n fwin =False\r\n if(fwin and pnt!= len(y)):\r\n print('first')\r\n elif(not fwin and pnt!= len(y)):\r\n print('second')\r\n else:\r\n if(last):\r\n print('first')\r\n else:\r\n print('second') \r\n else:\r\n fwin = True\r\n pnt=0\r\n while(pnty[pnt]):\r\n fwin = True\r\n break\r\n elif(x[pnt]==y[pnt]):\r\n pnt+=1\r\n else:\r\n fwin =False\r\n if(fwin and pnt!= len(y)):\r\n print('first')\r\n elif(not fwin and pnt!= len(y)):\r\n print('second')\r\n else:\r\n if(last):\r\n print('first')\r\n else:\r\n print('second')\r\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Pasha loves his phone and also putting his hair up... But the hair is now irrelevant.\n\nPasha has installed a new game to his phone. The goal of the game is following. There is a rectangular field consisting of *n* row with *m* pixels in each row. Initially, all the pixels are colored white. In one move, Pasha can choose any pixel and color it black. In particular, he can choose the pixel that is already black, then after the boy's move the pixel does not change, that is, it remains black. Pasha loses the game when a 2<=×<=2 square consisting of black pixels is formed. \n\nPasha has made a plan of *k* moves, according to which he will paint pixels. Each turn in his plan is represented as a pair of numbers *i* and *j*, denoting respectively the row and the column of the pixel to be colored on the current move.\n\nDetermine whether Pasha loses if he acts in accordance with his plan, and if he does, on what move the 2<=×<=2 square consisting of black pixels is formed.",
"input": "",
"output": "```python\nn,m,k=map(int,input().split());l=[];ans=0\r\nfor i in range(n+2):\r\n t=[]\r\n for j in range(m+2):\r\n t.append(0)\r\n l.append(t)\r\nfor i in range(k):\r\n p,q=map(int,input().split())\r\n l[p][q]=1\r\n if l[p-1][q-1]+l[p][q-1]+l[p-1][q]==3:\r\n ans=i+1;break\r\n if l[p-1][q]+l[p-1][q+1]+l[p][q]==3:\r\n ans=i+1;break\r\n if l[p][q-1]+l[p+1][q-1]+l[p+1][q]==3:\r\n ans=i+1;break\r\n if l[p][q+1]+l[p+1][q]+l[p+1][q+1]==3:\r\n ans=i+1;break\r\nprint(ans)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nThere 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.\n\nGiven 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!",
"input": "",
"output": "```python\nn = input()\r\nli= list(map(int,input().split()))\r\nli.sort()\r\nfor i in li:\r\n print(i,end=\" \")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Little Elephant loves magic squares very much.\n\nA 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.\n\nThe 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. \n\nHelp the Little Elephant, restore the original magic square, given the Elephant's notes.",
"input": "",
"output": "```python\na =[]\r\nfor i in range(3):\r\n\ta.append(list(map(int,input().split())))\r\n\r\nfor n in range(1,10**5):\r\n\ts = n+ a[0][1] + a[0][2]\r\n\tk = s - a[1][0] - a[1][2]\r\n\tw = s - a[2][0] - a[2][1]\r\n\tif n+k+w==s:\r\n\t\ta[0][0] = n\r\n\t\ta[1][1] = k\r\n\t\ta[2][2] = w\r\n\t\tbreak\r\nfor i in range(3):\r\n\tprint(*a[i])\r\n\t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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. \n\nValera 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. \n\nHelp Valera count the minimum number of cashes to work at his cafe next day, so that they can serve all visitors.",
"input": "",
"output": "```python\nt=int(input())\r\ncash=1\r\ni=0\r\nM=[]\r\nfor j in range(t):\r\n L=list(map(int,input().split(\" \")))\r\n M.append(L)\r\n if j!=0:\r\n if M[j]==M[j-1]:\r\n i+=1\r\n else:\r\n i=0\r\n if i>=cash:\r\n cash+=1\r\nprint(cash)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "\"Hey, it's homework time\" — thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him.\n\nThe sequence of *n* integers is called a permutation if it contains all integers from 1 to *n* exactly once.\n\nYou are given an arbitrary sequence *a*1,<=*a*2,<=...,<=*a**n* containing *n* integers. Each integer is not less than 1 and not greater than 5000. Determine what minimum number of elements Polycarpus needs to change to get a permutation (he should not delete or add numbers). In a single change he can modify any single sequence element (i. e. replace it with another integer).",
"input": "",
"output": "```python\nn = int(input())\r\nok = [False]*n\r\ninp = input().split(' ')\r\ncount = n\r\nfor i in inp:\r\n i = int(i)-1\r\n if not ok[i]:\r\n count -= 1\r\n ok[i] = True\r\nprint(count)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "$k$ people want to split $n$ candies between them. Each candy should be given to exactly one of them or be thrown away.\n\nThe people are numbered from $1$ to $k$, and Arkady is the first of them. To split the candies, Arkady will choose an integer $x$ and then give the first $x$ candies to himself, the next $x$ candies to the second person, the next $x$ candies to the third person and so on in a cycle. The leftover (the remainder that is not divisible by $x$) will be thrown away.\n\nArkady can't choose $x$ greater than $M$ as it is considered greedy. Also, he can't choose such a small $x$ that some person will receive candies more than $D$ times, as it is considered a slow splitting.\n\nPlease find what is the maximum number of candies Arkady can receive by choosing some valid $x$.",
"input": "",
"output": "```python\nn, k, M, D = map(int, input().split())\r\n\r\nans = 0\r\nfor i in range(1, D+1):\r\n\tx = n //((i-1)*k+1)\r\n\r\n\tif x <= M:\t\r\n\t\tans = max(ans, x*i)\r\n\r\nif n//k <= M:\r\n ans = max(ans, n//k)\r\nelse:\r\n ans = max(ans, M)\r\n\r\nprint(ans)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Luba thinks about watering her garden. The garden can be represented as a segment of length *k*. Luba has got *n* buckets, the *i*-th bucket allows her to water some continuous subsegment of garden of length exactly *a**i* each hour. Luba can't water any parts of the garden that were already watered, also she can't water the ground outside the garden.\n\nLuba has to choose one of the buckets in order to water the garden as fast as possible (as mentioned above, each hour she will water some continuous subsegment of length *a**i* if she chooses the *i*-th bucket). Help her to determine the minimum number of hours she has to spend watering the garden. It is guaranteed that Luba can always choose a bucket so it is possible water the garden.\n\nSee the examples for better understanding.",
"input": "",
"output": "```python\nimport re\r\n\r\nx = input()\r\nres = 0\r\nlist_1 = re.split('\\s', x,0)\r\nm = int(list_1[0])\r\ny = int(list_1[1])\r\nres = 0\r\nstr = input()\r\nlist_2 = re.split('\\s',str,0)\r\nfor i in list_2:\r\n if y % int(i) == 0:\r\n res = int(i)\r\nprint(int(y / res))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are given a sequence *a* consisting of *n* integers. You may partition this sequence into two sequences *b* and *c* in such a way that every element belongs exactly to one of these sequences. \n\nLet *B* be the sum of elements belonging to *b*, and *C* be the sum of elements belonging to *c* (if some of these sequences is empty, then its sum is 0). What is the maximum possible value of *B*<=-<=*C*?",
"input": "",
"output": "```python\ninput()\r\na = sorted(list(map(int, input().split())))\r\nprint(a[-1] - a[0] if a[0] < 1 else sum(a))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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?",
"input": "",
"output": "```python\nn = input()\r\nc = 0\r\n\r\nwhile int(n) > 9:\r\n\ttemp = 0\r\n\r\n\tc += 1\r\n\r\n\tfor i in n :\r\n\t\ttemp += int(i)\r\n\r\n\tn = str(temp)\r\n\t# print(temp)\r\n\r\n\r\nprint(c)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer.\n\nAt 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).\n\nIf 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.\n\nKay 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.",
"input": "",
"output": "```python\nn, x = list(map(int, input().split(' ')))\r\nd = 0\r\nfor i in range(n):\r\n a, b = input().split(' ')\r\n b = int(b)\r\n if a == '+':\r\n x += b\r\n elif a == '-' and b <= x:\r\n x -= b\r\n else:\r\n d += 1\r\nprint(x, d)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Little Artem got *n* stones on his birthday and now wants to give some of them to Masha. He knows that Masha cares more about the fact of receiving the present, rather than the value of that present, so he wants to give her stones as many times as possible. However, Masha remembers the last present she received, so Artem can't give her the same number of stones twice in a row. For example, he can give her 3 stones, then 1 stone, then again 3 stones, but he can't give her 3 stones and then again 3 stones right after that.\n\nHow many times can Artem give presents to Masha?",
"input": "",
"output": "```python\nn = int(input())\r\na = [1, 1]\r\nfor i in range(2, n):\r\n a.append(a[i - 1] + a[i - 2])\r\nprint(a[n - 1])\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word *s*. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word \"hello\". For example, if Vasya types the word \"ahhellllloou\", it will be considered that he said hello, and if he types \"hlelo\", it will be considered that Vasya got misunderstood and he didn't manage to say hello. Determine whether Vasya managed to say hello by the given word *s*.",
"input": "",
"output": "```python\ns = input()\r\na = []\r\nfor i in range(len(s)):\r\n if s[i] == 'h' and 1 not in a:\r\n a.append(1)\r\n elif s[i] == 'e' and a[-1] == 1:\r\n a.append(2)\r\n elif s[i] == 'l' and a[-1] == 2:\r\n a.append(3)\r\n elif s[i] == 'l' and a[-1] == 3:\r\n a.append(4)\r\n elif s[i] == 'o' and a[-1] == 4:\r\n a.append(5)\r\nif a[-1] == 5:\r\n print('YES')\r\nelse:\r\n print('NO')\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "We consider a positive integer perfect, if and only if the sum of its digits is exactly $10$. Given a positive integer $k$, your task is to find the $k$-th smallest perfect positive integer.",
"input": "",
"output": "```python\n\r\n\r\nn = int(input())\r\ni = 10\r\nwhile n>0:\r\n i += 9\r\n if sum(map(int, str(i))) == 10: n-=1\r\nprint(i)\r\n\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Nick is interested in prime numbers. Once he read about Goldbach problem. It states that every even integer greater than 2 can be expressed as the sum of two primes. That got Nick's attention and he decided to invent a problem of his own and call it Noldbach problem. Since Nick is interested only in prime numbers, Noldbach problem states that at least *k* prime numbers from 2 to *n* inclusively can be expressed as the sum of three integer numbers: two neighboring prime numbers and 1. For example, 19 = 7 + 11 + 1, or 13 = 5 + 7 + 1.\n\nTwo prime numbers are called neighboring if there are no other prime numbers between them.\n\nYou are to help Nick, and find out if he is right or wrong.",
"input": "",
"output": "```python\ndef f(rangeint):\r\n List = []\r\n for j in range(2, rangeint+1):\r\n List.append(j)\r\n \r\n z = 2*len(List)\r\n a = 0 \r\n for i in range(0, int(rangeint**(1/2))):\r\n \r\n a += 1\r\n \r\n \r\n m = List[a-1]\r\n\r\n for k in List:\r\n \r\n if k % m == 0 and k > m :\r\n List.remove(k)\r\n \r\n \r\n return List \r\n \r\n\r\ninnput = input()\r\ninputspl = innput.split()\r\nn = int(inputspl[0])\r\nk = int(inputspl[1])\r\ncounter = 0\r\nListprime = f(n)\r\nfor d in range(0, len(Listprime)-1):\r\n if ((Listprime[d]+Listprime[d+1]+1) in Listprime) and ((Listprime[d]+Listprime[d+1]+1) <= n):\r\n counter += 1\r\nif counter >= k:\r\n print(\"YES\")\r\nelse:\r\n print(\"NO\") \r\n\r\n\r\n\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.",
"input": "",
"output": "```python\ns=input()\r\nt=input()\r\nl=len(s)\r\nf=0\r\nfor i in range(l):\r\n if s[i]!=t[l-i-1]:\r\n f=1\r\n break\r\nif f==1:\r\n print(\"NO\")\r\nelse:\r\n print(\"YES\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Caisa solved the problem with the sugar and now he is on the way back to home. \n\nCaisa is playing a mobile game during his path. There are (*n*<=+<=1) pylons numbered from 0 to *n* in this game. The pylon with number 0 has zero height, the pylon with number *i* (*i*<=><=0) has height *h**i*. The goal of the game is to reach *n*-th pylon, and the only move the player can do is to jump from the current pylon (let's denote its number as *k*) to the next one (its number will be *k*<=+<=1). When the player have made such a move, its energy increases by *h**k*<=-<=*h**k*<=+<=1 (if this value is negative the player loses energy). The player must have non-negative amount of energy at any moment of the time. \n\nInitially Caisa stand at 0 pylon and has 0 energy. The game provides a special opportunity: one can pay a single dollar and increase the height of anyone pylon by one. Caisa may use that opportunity several times, but he doesn't want to spend too much money. What is the minimal amount of money he must paid to reach the goal of the game?",
"input": "",
"output": "```python\n_ = input()\nl = list(map(int, input().split()))\n\nprint(max(l))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock.\n\nThe combination lock is represented by *n* rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has to turn some disks so that the combination of digits on the disks forms a secret combination. In one move, he can rotate one disk one digit forwards or backwards. In particular, in one move he can go from digit 0 to digit 9 and vice versa. What minimum number of actions does he need for that?",
"input": "",
"output": "```python\nN = int(input())\r\norg = input()\r\nfin = input()\r\n\r\nsol = 0\r\nfor i in range(N):\r\n a, b = int(min(org[i],fin[i])), int(max(org[i],fin[i]))\r\n sol += min(abs(b-a), a+10-b)\r\nprint(sol)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Catherine has a deck of *n* cards, each of which is either red, green, or blue. As long as there are at least two cards left, she can do one of two actions: \n - take any two (not necessarily adjacent) cards with different colors and exchange them for a new card of the third color; - take any two (not necessarily adjacent) cards with the same color and exchange them for a new card with that color. \nShe repeats this process until there is only one card left. What are the possible colors for the final card?",
"input": "",
"output": "```python\nint(input())\r\nb=set(input())\r\nif len(b)==1:print(''.join(b))\r\nelif len(b)==2:print(*[i for i in 'GRB' if i not in b])\r\nelse:print('B')\r\n\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nYou 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.\n\nYou 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.\n\nYou are given the text of the lecture the professor is going to read. Find out how the lecture will be recorded in your notes.",
"input": "",
"output": "```python\nn,m = map(int,input().split())\r\n\r\na = []\r\nb = []\r\nans = []\r\n\r\nfor i in range(0,m):\r\n w1,w2 = [str(x) for x in input().split()]\r\n a.append(w1)\r\n b.append(w2)\r\n\r\ns = input()\r\ns = s.split()\r\n\r\n\r\nfor word in s:\r\n cnt = a.index(word)\r\n if len(a[cnt]) <= len(b[cnt]):\r\n ans.append(a[cnt])\r\n else:\r\n ans.append(b[cnt])\r\n\r\nprint(\" \".join(ans))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Our brave travelers reached an island where pirates had buried treasure. However as the ship was about to moor, the captain found out that some rat ate a piece of the treasure map.\n\nThe treasure map can be represented as a rectangle *n*<=×<=*m* in size. Each cell stands for an islands' square (the square's side length equals to a mile). Some cells stand for the sea and they are impenetrable. All other cells are penetrable (i.e. available) and some of them contain local sights. For example, the large tree on the hills or the cave in the rocks.\n\nBesides, the map also has a set of *k* instructions. Each instruction is in the following form:\n\n\"Walk *n* miles in the *y* direction\"\n\nThe possible directions are: north, south, east, and west. If you follow these instructions carefully (you should fulfill all of them, one by one) then you should reach exactly the place where treasures are buried. \n\nUnfortunately the captain doesn't know the place where to start fulfilling the instructions — as that very piece of the map was lost. But the captain very well remembers that the place contained some local sight. Besides, the captain knows that the whole way goes through the island's penetrable squares.\n\nThe captain wants to know which sights are worth checking. He asks you to help him with that.",
"input": "",
"output": "```python\nprint(\"_RANDOM_GUESS_1689180180.4521961\")# 1689180180.4522119\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vanya and his friends are walking along the fence of height *h* and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed *h*. If the height of some person is greater than *h* he can bend down and then he surely won't be noticed by the guard. The height of the *i*-th person is equal to *a**i*.\n\nConsider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?",
"input": "",
"output": "```python\nn = input().split()\r\na = input().split()\r\nMP=0\r\nfor i in range(0,int(n[0])):\r\n if int(a[i]) > int(n[1]) :\r\n MP+=2\r\n else:\r\n MP+=1\r\n\r\nprint(MP)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains *n* different items numbered from 1 to *n*. The *i*-th item has base cost *a**i* Egyptian pounds. If Sagheer buys *k* items with indices *x*1,<=*x*2,<=...,<=*x**k*, then the cost of item *x**j* is *a**x**j*<=+<=*x**j*·*k* for 1<=≤<=*j*<=≤<=*k*. In other words, the cost of an item is equal to its base cost in addition to its index multiplied by the factor *k*.\n\nSagheer wants to buy as many souvenirs as possible without paying more than *S* Egyptian pounds. Note that he cannot buy a souvenir more than once. If there are many ways to maximize the number of souvenirs, he will choose the way that will minimize the total cost. Can you help him with this task?",
"input": "",
"output": "```python\nn, s = map(int, input().split())\r\nv = list(map(int, input().split()))\r\n#for i in range(n):\r\nr = n + 1\r\nl = 0\r\no = 0\r\nwhile r - l != 1:\r\n s1 = s\r\n b = []\r\n t = True\r\n for i in range(n):\r\n b.append(v[i] + (i + 1) * ((r + l) // 2))\r\n b.sort()\r\n i = 0\r\n sum = 0\r\n for i in range((r + l) // 2):\r\n sum += b[i]\r\n if sum <= s:\r\n l = (r + l) // 2\r\n o = sum\r\n else:\r\n r = (r + l) // 2\r\n s = s1\r\nprint(l, o)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "It was recycling day in Kekoland. To celebrate it Adil and Bera went to Central Perk where they can take bottles from the ground and put them into a recycling bin.\n\nWe can think Central Perk as coordinate plane. There are *n* bottles on the ground, the *i*-th bottle is located at position (*x**i*,<=*y**i*). Both Adil and Bera can carry only one bottle at once each. \n\nFor both Adil and Bera the process looks as follows: \n 1. Choose to stop or to continue to collect bottles. 1. If the choice was to continue then choose some bottle and walk towards it. 1. Pick this bottle and walk to the recycling bin. 1. Go to step 1. \nAdil and Bera may move independently. They are allowed to pick bottles simultaneously, all bottles may be picked by any of the two, it's allowed that one of them stays still while the other one continues to pick bottles.\n\nThey want to organize the process such that the total distance they walk (the sum of distance walked by Adil and distance walked by Bera) is minimum possible. Of course, at the end all bottles should lie in the recycling bin.",
"input": "",
"output": "```python\nimport math\r\nAx , Ay , Bx , By , Rx , Ry = map(int,input().split())\r\na , b = [100009] , [100009]\r\nmaxDis ,mDx,mDy ,res ,mx , my ,minDis,x1,y1= 0,0,0,0,0,0,10000000000,0,0\r\nn = int(input())\r\nfor i in range(n):\r\n x , y = map(int,input().split())\r\n a.append(x)\r\n b.append(y)\r\n d = math.dist([x,y] , [Rx,Ry])\r\n if d > maxDis:\r\n maxDis = d\r\n mDx = x\r\n mDy = y\r\n res += 2 * d\r\nd1 = math . dist([mDx , mDy] , [Ax , Ay])\r\nd2 = math . dist([mDx , mDy] , [Bx , By])\r\nif d1 < d2 :\r\n mx = Bx\r\n my = By\r\nelse:\r\n mx = Ax\r\n my = Ay\r\nres +=min(d1,d2)\r\nres -= math . dist([mDx , mDy] , [Rx , Ry])\r\nfor i in range(1,n+1):\r\n x = a[i]\r\n y = b[i]\r\n d = math.dist([x,y] , [mx,my])\r\n if d abc:\r\n print(s.upper())\r\nelse:\r\n print(s.lower())\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nEmbosser 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:\n\nAfter 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'.\n\nOur 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.",
"input": "",
"output": "```python\nn=input()\r\nrotations=0\r\nstarting_point=\"a\"\r\nfor i in n:\r\n r=(abs(ord(i)-ord(starting_point)))%26\r\n if r>13:\r\n rotations+=26-r\r\n else:\r\n rotations+=r\r\n starting_point=i\r\nprint(rotations)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "*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.",
"input": "",
"output": "```python\nn = int(input())\r\na = list(map(int, input().split()))\r\nx = 99999\r\nfor i in range(n):\r\n if abs(a[i] - a[(i+1)%n]) < x:\r\n x = abs(a[i%n] - a[(i+1)%n])\r\n x1 = i%n\r\n x2 = (i+1)%n\r\n\r\nprint(x1, x2, sep=\" \")\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house.\n\nKarlsson's gaze immediately fell on *n* wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find.\n\nAnd now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open.\n\nKarlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds *t*, in which he is able to bring all the cupboard doors in the required position.\n\nYour task is to write a program that will determine the required number of seconds *t*.",
"input": "",
"output": "```python\nn = int(input())\r\nleft_open = 0\r\nright_open = 0\r\nfor i in range(n):\r\n l, r = map(int, input().split())\r\n left_open += l\r\n right_open += r\r\ncase1 = min(left_open, n - left_open) + min(right_open, n - right_open)\r\ncase2 = min(left_open, n - left_open) + min(right_open, n - right_open) + abs(left_open - right_open)\r\nprint(min(case1, case2))\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All *n* crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to *n*) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:\n\nThe first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.\n\nIf we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).\n\nFor each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew.",
"input": "",
"output": "```python\ndict={}\r\nd={'captain':4,'man':3,'child':2,'woman':2,'rat':1}\r\nn=int(input())\r\nfor i in range(n):\r\n ip=list(map(str,input().split(' ')))\r\n name=ip[0]\r\n dict[name]=d[ip[1]]\r\nfor i in sorted(dict.items(), key=lambda kv:(kv[1], kv[0])):\r\n print(i[0])\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "The Travelling Salesman spends a lot of time travelling so he tends to get bored. To pass time, he likes to perform operations on numbers. One such operation is to take a positive integer *x* and reduce it to the number of bits set to 1 in the binary representation of *x*. For example for number 13 it's true that 1310<==<=11012, so it has 3 bits set and 13 will be reduced to 3 in one operation.\n\nHe calls a number special if the minimum number of operations to reduce it to 1 is *k*.\n\nHe wants to find out how many special numbers exist which are not greater than *n*. Please help the Travelling Salesman, as he is about to reach his destination!\n\nSince the answer can be large, output it modulo 109<=+<=7.",
"input": "",
"output": "```python\nMX = 1030\r\nM = 1000 * 1000 * 1000 + 7\r\nc = [[0] * MX for i in range(MX)]\r\nfor i in range(MX):\r\n c[i][0] = 1\r\nfor i in range(1, MX):\r\n for j in range(1, MX):\r\n c[i][j] = c[i - 1][j] + c[i - 1][j - 1]\r\n c[i][j] %= M\r\n \r\nnum = list(map(int, list(input())))\r\ncnt = int(input())\r\ndp = [0] * MX\r\nfor i in range(2, MX):\r\n dp[i] = dp[bin(i).count('1')] + 1\r\n \r\nif cnt == 0:\r\n print(1)\r\n exit()\r\n \r\nres = 0\r\n \r\nfor i in range(1, MX):\r\n if dp[i] != cnt - 1: continue\r\n n = len(num) - 1\r\n k = i\r\n for pos in range(len(num)):\r\n if num[pos] == 1:\r\n # print(n, k)\r\n #if we put 0 here\r\n res += c[n][k]\r\n res %= M\r\n k -= 1\r\n n -= 1 \r\n # print(k) \r\n if n == -1 and k == 0:\r\n res += 1\r\nif cnt == 1: res -= 1\r\nprint(res)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You're given a list of *n* strings *a*1,<=*a*2,<=...,<=*a**n*. You'd like to concatenate them together in some order such that the resulting string would be lexicographically smallest.\n\nGiven the list of strings, output the lexicographically smallest concatenation.",
"input": "",
"output": "```python\n\r\ndef function():\r\n temp=input().split()\r\n customers=int(temp[0])\r\n cost=int(temp[1])\r\n custArray=[]\r\n for customer in range(customers):\r\n temp=input()\r\n custArray.append(temp)\r\n apples=0\r\n profit=0\r\n for index in range(customers):\r\n if(custArray[customers-1-index]=='half'):\r\n if(apples==0):\r\n apples=1\r\n profit=cost\r\n else:\r\n profit+=cost*apples\r\n apples=2*apples\r\n else:\r\n if(apples==0):\r\n apples=1\r\n profit=cost/2\r\n else:\r\n profit+=(apples+.5)*cost\r\n apples=apples*2+1\r\n return int(profit)\r\n\r\ndef concat():\r\n size=int(input())\r\n stringArray=[]\r\n for temp in range(size):\r\n stringArray.append(input())\r\n superString=''\r\n for index in range(len(stringArray)):\r\n if superString=='':\r\n superString=stringArray[index]\r\n else:\r\n if superString.find(stringArray[index])==-1:\r\n flag=False\r\n for innerIndex in range (len(stringArray[index])):\r\n if(superString[-(len(stringArray[index])-1-innerIndex):]==stringArray[index][:len(stringArray[index])-1-innerIndex]):\r\n superString+=stringArray[index][len(stringArray[index])-1-innerIndex:]\r\n flag=True\r\n break\r\n if(not flag):\r\n superString+=stringArray[index]\r\n return superString\r\n \r\n\r\n'''\r\ndef lcmString():\r\n temp=input().split()\r\n size=int(temp[0])\r\n m=int(temp[1])\r\n temp=input().split()\r\n for index in range(len(temp)):\r\n if \r\n'''\r\nprint(concat())\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter *c* DZY knows its value *w**c*. For each special string *s*<==<=*s*1*s*2... *s*|*s*| (|*s*| is the length of the string) he represents its value with a function *f*(*s*), where \n\nNow DZY has a string *s*. He wants to insert *k* lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get?",
"input": "",
"output": "```python\ns=input()\r\nk=int(input())\r\nw=list(map(int,input().split()))\r\ns=list(s)\r\nq=0\r\nfor i in range(len(s)):\r\n q=q+(i+1)*w[i]\r\na=max(w)\r\nb=len(s)+1\r\nfor i in range(k):\r\n q=q+b*a\r\n b=b+1\r\nprint(q)\r\n \r\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.",
"input": "",
"output": "```python\n#25A IQ Test\r\nimport sys\r\nimport math\r\n\r\ninputs = int(input())\r\ninput2 = sys.stdin.readline().split()\r\ni = 0\r\na = 0\r\nb = 0\r\n\r\nif inputs == 2:\r\n print(\"1\")\r\n sys.exit()\r\n\r\nfor i in range(inputs):\r\n if int(input2[i])%2 == 0:\r\n \r\n a = a + 1\r\n else:\r\n b = b + 1\r\n \r\n\r\nif a>b: #Even\r\n for i in range(inputs):\r\n if int(input2[i])%2 == 1:\r\n print(i + 1)\r\nelse: #Even\r\n for i in range(inputs):\r\n if int(input2[i])%2 == 0:\r\n print(i + 1)\r\n \r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Recently, Mike was very busy with studying for exams and contests. Now he is going to chill a bit by doing some sight seeing in the city.\n\nCity consists of *n* intersections numbered from 1 to *n*. Mike starts walking from his house located at the intersection number 1 and goes along some sequence of intersections. Walking from intersection number *i* to intersection *j* requires |*i*<=-<=*j*| units of energy. The total energy spent by Mike to visit a sequence of intersections *p*1<==<=1,<=*p*2,<=...,<=*p**k* is equal to units of energy.\n\nOf course, walking would be boring if there were no shortcuts. A shortcut is a special path that allows Mike walking from one intersection to another requiring only 1 unit of energy. There are exactly *n* shortcuts in Mike's city, the *i**th* of them allows walking from intersection *i* to intersection *a**i* (*i*<=≤<=*a**i*<=≤<=*a**i*<=+<=1) (but not in the opposite direction), thus there is exactly one shortcut starting at each intersection. Formally, if Mike chooses a sequence *p*1<==<=1,<=*p*2,<=...,<=*p**k* then for each 1<=≤<=*i*<=<<=*k* satisfying *p**i*<=+<=1<==<=*a**p**i* and *a**p**i*<=≠<=*p**i* Mike will spend only 1 unit of energy instead of |*p**i*<=-<=*p**i*<=+<=1| walking from the intersection *p**i* to intersection *p**i*<=+<=1. For example, if Mike chooses a sequence *p*1<==<=1,<=*p*2<==<=*a**p*1,<=*p*3<==<=*a**p*2,<=...,<=*p**k*<==<=*a**p**k*<=-<=1, he spends exactly *k*<=-<=1 units of total energy walking around them.\n\nBefore going on his adventure, Mike asks you to find the minimum amount of energy required to reach each of the intersections from his home. Formally, for each 1<=≤<=*i*<=≤<=*n* Mike is interested in finding minimum possible total energy of some sequence *p*1<==<=1,<=*p*2,<=...,<=*p**k*<==<=*i*.",
"input": "",
"output": "```python\nfrom collections import defaultdict\r\n\r\nclass Graph:\r\n def __init__(self):\r\n self.node=set()\r\n self.edges= defaultdict(list)\r\n self.distance={}\r\n\r\n def addNode(self,value):\r\n self.node.add(value)\r\n\r\n def addEdge(self,start,end,distance):\r\n self.edges[start].append(end)\r\n self.distance[(start,end)]=distance\r\n\r\n\r\ndef dij(graph,ini):\r\n visited={ini:0}\r\n path= defaultdict(list)\r\n nodes=set(graph.node)\r\n\r\n while nodes:\r\n minNode=None\r\n for node in nodes:\r\n if node in visited:\r\n if(minNode is None):\r\n minNode=node\r\n elif(visited[node] 0:\n # pega o valor medio, valores entre (m+1)/2 até m\n print(str(int((m+i%m+1)/2)))\n else:\n # Pega o valor médio que seja menor ou igual a metade de m.\n # Portanto valores entre 1 até m/2\n print(str(int((m-(i%m))/2)))\n \t\t \t\t\t\t\t \t\t\t\t \t \t \t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.\n\nUnfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky digits in it is a lucky number. He wonders whether number *n* is a nearly lucky number.",
"input": "",
"output": "```python\nn = input()\r\n\r\nif n.count('4') + n.count('7') in [4,7]:\r\n print(\"YES\")\r\nelse:\r\n print(\"NO\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.",
"input": "",
"output": "```python\ntext = str(input())\r\ntext2 = str(input())\r\nif text2 == text[::-1]:\r\n print(\"YES\")\r\nelse:\r\n print(\"NO\")\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You can find anything whatsoever in our Galaxy! A cubical planet goes round an icosahedral star. Let us introduce a system of axes so that the edges of the cubical planet are parallel to the coordinate axes and two opposite vertices lay in the points (0,<=0,<=0) and (1,<=1,<=1). Two flies live on the planet. At the moment they are sitting on two different vertices of the cubical planet. Your task is to determine whether they see each other or not. The flies see each other when the vertices they occupy lie on the same face of the cube.",
"input": "",
"output": "```python\nif (int(input()[::2], 2) + int(input()[::2], 2)) == 7:\n print(\"NO\")\nelse:\n print(\"YES\")\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A burglar got into a matches warehouse and wants to steal as many matches as possible. In the warehouse there are *m* containers, in the *i*-th container there are *a**i* matchboxes, and each matchbox contains *b**i* matches. All the matchboxes are of the same size. The burglar's rucksack can hold *n* matchboxes exactly. Your task is to find out the maximum amount of matches that a burglar can carry away. He has no time to rearrange matches in the matchboxes, that's why he just chooses not more than *n* matchboxes so that the total amount of matches in them is maximal.",
"input": "",
"output": "```python\nn,m=map(int,input().split())\r\nl=[]\r\nfor i in range(m):\r\n l.append(list(map(int,input().split())))\r\nl.sort(key= lambda x : (x[1],x[0]), reverse= True)\r\nprint(l)\r\nans=0\r\nfor i in l:\r\n a=min(n,i[0])\r\n ans+=a*i[1]\r\n n-=a\r\nprint(ans)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "In Aramic language words can only represent objects.\n\nWords in Aramic have special properties: \n - A word is a root if it does not contain the same letter more than once. - A root and all its permutations represent the same object. - The root $x$ of a word $y$ is the word that contains all letters that appear in $y$ in a way that each letter appears once. For example, the root of \"aaaa\", \"aa\", \"aaa\" is \"a\", the root of \"aabb\", \"bab\", \"baabb\", \"ab\" is \"ab\". - Any word in Aramic represents the same object as its root. \nYou have an ancient script in Aramic. What is the number of different objects mentioned in the script?",
"input": "",
"output": "```python\nn = int(input())\r\na = input().split()\r\nb = set()\r\nfor i in a:\r\n c = [0] * 37\r\n for j in i:\r\n c[ord(j) - ord('a')] = 1\r\n now = 0\r\n p = 37\r\n for j in range(26):\r\n if c[j] == 1:\r\n now += p * (j + 1)\r\n p *= 37\r\n b.add(now)\r\nprint(len(b))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "One day Misha and Andrew were playing a very simple game. First, each player chooses an integer in the range from 1 to *n*. Let's assume that Misha chose number *m*, and Andrew chose number *a*.\n\nThen, by using a random generator they choose a random integer *c* in the range between 1 and *n* (any integer from 1 to *n* is chosen with the same probability), after which the winner is the player, whose number was closer to *c*. The boys agreed that if *m* and *a* are located on the same distance from *c*, Misha wins.\n\nAndrew wants to win very much, so he asks you to help him. You know the number selected by Misha, and number *n*. You need to determine which value of *a* Andrew must choose, so that the probability of his victory is the highest possible.\n\nMore formally, you need to find such integer *a* (1<=≤<=*a*<=≤<=*n*), that the probability that is maximal, where *c* is the equiprobably chosen integer from 1 to *n* (inclusive).",
"input": "",
"output": "```python\nimport sys, collections, bisect, heapq, functools, itertools, math\r\ninput = sys.stdin.readline\r\n\r\nn, m = [int(x) for x in input().split()]\r\n\r\nif n - m > m - 1:\r\n print(min(n, m + 1))\r\nelse:\r\n print(max(1, m - 1))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Amr loves Geometry. One day he came up with a very interesting problem.\n\nAmr has a circle of radius *r* and center in point (*x*,<=*y*). He wants the circle center to be in new position (*x*',<=*y*').\n\nIn one step Amr can put a pin to the border of the circle in a certain point, then rotate the circle around that pin by any angle and finally remove the pin.\n\nHelp Amr to achieve his goal in minimum number of steps.",
"input": "",
"output": "```python\nimport math\r\n \r\nr,x0,y0,x1,y1=map(int,input().split())\r\nd = math.sqrt((x1-x0)^2+(y1-y0)^2)\r\ns = d/(r<<1)\r\nprint(math.ceil(s))\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Dima and his friends have been playing hide and seek at Dima's place all night. As a result, Dima's place got messy. In the morning they decided that they need to clean the place.\n\nTo decide who exactly would clean the apartment, the friends want to play a counting-out game. First, all the guys stand in a circle, and then each of them shows some number of fingers on one hand (one to five), and then the boys count in a circle, starting from Dima, the number of people, respective to the total number of fingers shown. The person on who the countdown stops will clean the apartment.\n\nFor example, if Dima and one of his friends played hide and seek, and 7 fingers were shown during the counting-out, then Dima would clean the place. If there were 2 or say, 8 fingers shown, then his friend would clean the place.\n\nDima knows how many fingers each of his friends will show during the counting-out. Now he is interested in the number of ways to show some number of fingers on one hand (one to five), so that he did not have to clean the place. Help Dima.",
"input": "",
"output": "```python\nn = int(input())\ntotal = 0\nz = [x for x in map(int,input().split())]\nfor i in z:\n total += i\nanswer = 0\nfor i in range(1,5+1):\n if(total+i) % (n+1) != 1:\n answer += 1\nprint(answer)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Professor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest. \n\nIn total, *n* students will attend, and before the start, every one of them has some positive integer rating. Students are indexed from 1 to *n*. Let's denote the rating of *i*-th student as *a**i*. After the contest ends, every student will end up with some positive integer position. GukiZ expects that his students will take places according to their ratings. \n\nHe thinks that each student will take place equal to . In particular, if student *A* has rating strictly lower then student *B*, *A* will get the strictly better position than *B*, and if two students have equal ratings, they will share the same position. \n\nGukiZ would like you to reconstruct the results by following his expectations. Help him and determine the position after the end of the contest for each of his students if everything goes as expected.",
"input": "",
"output": "```python\nfrom sys import stdin\n\nn=int(stdin.readline())\na=[int(x) for x in stdin.readline().split()]\nfor i in range(n):\n c=0\n for j in range(n):\n if a[i]q):\r\n print((n//a)*p+(n//b)*q-(n//x)*q)\r\nelse:\r\n print((n//a)*p+(n//b)*q-(n//x)*p)\r\n \r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vasya plays the sleuth with his friends. The rules of the game are as follows: those who play for the first time, that is Vasya is the sleuth, he should investigate a \"crime\" and find out what is happening. He can ask any questions whatsoever that can be answered with \"Yes\" or \"No\". All the rest agree beforehand to answer the questions like that: if the question’s last letter is a vowel, they answer \"Yes\" and if the last letter is a consonant, they answer \"No\". Of course, the sleuth knows nothing about it and his task is to understand that.\n\nUnfortunately, Vasya is not very smart. After 5 hours of endless stupid questions everybody except Vasya got bored. That’s why Vasya’s friends ask you to write a program that would give answers instead of them.\n\nThe English alphabet vowels are: A, E, I, O, U, Y\n\nThe English alphabet consonants are: B, C, D, F, G, H, J, K, L, M, N, P, Q, R, S, T, V, W, X, Z",
"input": "",
"output": "```python\nf = str(input())\ng = f[::-1]\ng = g.lower()\ng= g.replace(\"?\",\" \")\nl1= ['a','e','y','i','o','u']\nx=0\nl = ''\nfor y in g:\n if ord(y) in range(97,123):\n l =y\n break\n else:\n pass\n\nif l in l1:\n print(\"YES\")\nelse:\n print(\"NO\")\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Hongcow really likes the color red. Hongcow doesn't like the color blue.\n\nHongcow is standing in an infinite field where there are *n* red points and *m* blue points.\n\nHongcow wants to draw a circle in the field such that this circle contains at least one red point, and no blue points. Points that line exactly on the boundary of the circle can be counted as either inside or outside.\n\nCompute the radius of the largest circle that satisfies this condition. If this circle can have arbitrarily large size, print <=-<=1. Otherwise, your answer will be accepted if it has relative or absolute error at most 10<=-<=4.",
"input": "",
"output": "```python\n\nimport itertools\nred = []\nblue = []\n\ninput_ = input()\nx = input_.split(\" \")\ni = 0\nj = 0\npoints = []\n#blue = []\nwhile i < int(x[0]):\n k = input()\n points.append(k)\n red.append(k)\n i+=1\nwhile j < int(x[1]):\n l = input()\n points.append(l)\n blue.append(l)\n j+=1\n# print(\"red: \",red)\n# print(\"blue: \",blue)\n# print(\"points: \",points)\n\ndef GetRadandCenter(x):\n x1, y1, x2, y2, x3, y3 = map(float, x.split(\" \"))\n c = (x1-x2)**2 + (y1-y2)**2\n a = (x2-x3)**2 + (y2-y3)**2\n b = (x3-x1)**2 + (y3-y1)**2\n s = 2*(a*b + b*c + c*a) - (a*a + b*b + c*c) \n if s == 0:\n return -1,1,1\n else:\n px = (a*(b+c-a)*x1 + b*(c+a-b)*x2 + c*(a+b-c)*x3) / s\n py = (a*(b+c-a)*y1 + b*(c+a-b)*y2 + c*(a+b-c)*y3) / s \n ar = a**0.5\n br = b**0.5\n cr = c**0.5 \n r = ar*br*cr / ((ar+br+cr)*(-ar+br+cr)*(ar-br+cr)*(ar+br-cr))**0.5\n return r,px,py\n\n#Create all possible permutations\nperm = []\nfor comb in itertools.combinations(points, 3):\n perm.append(comb)\n# print(\"perm: \",perm)\n\nvalidity = []\nradii = []\n\n#Special case if no limit\nfor z in red:\n for q in blue:\n # print(\"---------------\")\n # print(\"red: \",z)\n # print(\"blue: \",q)\n # print(\"blue whole list: \",blue)\n side1 = \"No\"\n side2 = \"No\"\n # other_blue = blue\n # other_blue.remove(q)\n # print(\"q: \",q)\n z_temp = z.split(\" \")\n x1 = int(z_temp[0])\n y1 = int(z_temp[1])\n q_temp = q.split(\" \")\n x2 = int(q_temp[0])\n y2 = int(q_temp[1])\n if (x2 - x1) == 0:\n side1,side2 = \"Yes\",\"Yes\"\n continue\n slope = (y2 - y1)/(x2 - x1)\n b = y1 - slope*x1\n for o in blue:\n o_temp = o.split(\" \")\n x3 = int(o_temp[0])\n y3 = int(o_temp[1])\n # print(\"Test Coordinates: \", x3,y3)\n if y3 > slope*x3 + b:\n side1 = \"Yes\"\n # print(\"Blue point: \", o)\n if y3 < slope*x3 + b:\n side2 = \"Yes\"\n # print(\"Blue point: \", o)\n # print(\"side1: \", side1)\n # print(\"side2: \", side2)\n if side1 == \"No\" or side2 == \"No\":\n print(\"-1\")\n else:\n \n #If red is not included, check if red is inside\n for t in perm:\n status = \"Invalid\"\n r,px,py = GetRadandCenter(t[0]+\" \"+t[1]+\" \"+t[2])\n # print(\"------------------------\")\n # print(\"radius: \",r)\n # print(\"center: \",px,py)\n # print(\"points: \", t)\n #Check if arc contains a red point\n for u in t:\n if u in red:\n status = \"Valid\"\n break\n #Check if any red is inside it\n if status == \"Invalid\":\n for m in red:\n m = m.split(\" \")\n x = int(m[0])\n y = int(m[1])\n # print(x,y,px,py,r)\n if ((x-int(px))**2) +((y-int(py))**2) <= int(r)**2:\n status = \"Valid\"\n break\n #Check if there are any blue dots within the circle\n if status == \"Valid\":\n for c in blue:\n if c in t:\n continue\n c = c.split(\" \")\n x = int(c[0])\n y = int(c[1])\n if int(((x-int(px))**2) +((y-int(py))**2)) < int(int(r)**2):\n status = \"Invalid\"\n # print(\"x,y: \",x,y)\n # print(\"LHS: \",((x-int(px))**2) +((y-int(py))**2))\n # print(\"RHS: \",int(r)**2 )\n break\n if status == \"Invalid\":\n r = -1\n # print(status)\n validity.append(status)\n radii.append(r)\n # print(validity)\n # print(radii)\n print(max(radii))\n exit()\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Little Robber Girl likes to scare animals in her zoo for fun. She decided to arrange the animals in a row in the order of non-decreasing height. However, the animals were so scared that they couldn't stay in the right places.\n\nThe robber girl was angry at first, but then she decided to arrange the animals herself. She repeatedly names numbers *l* and *r* such that *r*<=-<=*l*<=+<=1 is even. After that animals that occupy positions between *l* and *r* inclusively are rearranged as follows: the animal at position *l* swaps places with the animal at position *l*<=+<=1, the animal *l*<=+<=2 swaps with the animal *l*<=+<=3, ..., finally, the animal at position *r*<=-<=1 swaps with the animal *r*.\n\nHelp the robber girl to arrange the animals in the order of non-decreasing height. You should name at most 20<=000 segments, since otherwise the robber girl will become bored and will start scaring the animals again.",
"input": "",
"output": "```python\ndef solve(a):\r\n segments = []\r\n while True:\r\n changed = False\r\n\r\n for i in range(len(a) - 1):\r\n if a[i] > a[i + 1]:\r\n a[i], a[i + 1] = a[i + 1], a[i]\r\n\r\n segments.append(f\"{i + 1} {i + 2}\")\r\n changed = True\r\n\r\n if not changed:\r\n break\r\n\r\n return \"\\n\".join(segments)\r\n\r\ndef main():\r\n n = int(input())\r\n a = list(map(int, input().split()))\r\n result = solve(a)\r\n print(result)\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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). \n\nYour task is to determine by the given *a*, *b* and *n* who wins the game.",
"input": "",
"output": "```python\nfor t in range(int(input())):\r\n\r\n a,b,c = map(int, input().split())\r\n\r\n if c%2==0:\r\n print(1)\r\n else:\r\n print(0)\r\n\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "The School №0 of the capital of Berland has *n* children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value *t**i*:\n - *t**i*<==<=1, if the *i*-th child is good at programming, - *t**i*<==<=2, if the *i*-th child is good at maths, - *t**i*<==<=3, if the *i*-th child is good at PE \nEach child happens to be good at exactly one of these three subjects.\n\nThe Team Scientific Decathlon Olympias requires teams of three students. The school teachers decided that the teams will be composed of three children that are good at different subjects. That is, each team must have one mathematician, one programmer and one sportsman. Of course, each child can be a member of no more than one team.\n\nWhat is the maximum number of teams that the school will be able to present at the Olympiad? How should the teams be formed for that?",
"input": "",
"output": "```python\nimport sys; R = sys.stdin.readline\r\nfor _ in range(int(R())):\r\n s = R().split()[0]\r\n sys.stdin.flush()\r\n for i in range(1, len(s) - 1):\r\n sub1 = s[:i]\r\n sub2 = s[i]\r\n sub3 = s[i + 1:]\r\n if (sub2 >= sub1 and sub2 >= sub3) or (sub2 <= sub1 and sub2 <= sub3):\r\n print(sub1, sub2, sub3)\r\n break\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "We've got no test cases. A big olympiad is coming up. But the problemsetters' number one priority should be adding another problem to the round. \n\nThe diameter of a multiset of points on the line is the largest distance between two points from this set. For example, the diameter of the multiset {1,<=3,<=2,<=1} is 2.\n\nDiameter of multiset consisting of one point is 0.\n\nYou are given *n* points on the line. What is the minimum number of points you have to remove, so that the diameter of the multiset of the remaining points will not exceed *d*?",
"input": "",
"output": "```python\nn, d = list(map(int, input().split()))\na = list(map(int, input().split()))\na.sort()\n\ni = 0\nj = 1\nl = 0\ntl = 1\n\nwhile True:\n\tif abs(a[i] - a[j]) <= d:\n\t\ttl += 1\n\t\tj += 1\n\telse:\n\t\tif tl > l:\n\t\t\tl = tl\n\t\ttl = 1\n\t\ti += 1\n\t\tj = i + 1\n\n\tif i >= n - 1 or j >= n:\n\t\tif tl > l:\n\t\t\tl = tl\n\t\tbreak\n\n\nprint(n - l)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "The School №0 of the capital of Berland has *n* children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value *t**i*:\n - *t**i*<==<=1, if the *i*-th child is good at programming, - *t**i*<==<=2, if the *i*-th child is good at maths, - *t**i*<==<=3, if the *i*-th child is good at PE \nEach child happens to be good at exactly one of these three subjects.\n\nThe Team Scientific Decathlon Olympias requires teams of three students. The school teachers decided that the teams will be composed of three children that are good at different subjects. That is, each team must have one mathematician, one programmer and one sportsman. Of course, each child can be a member of no more than one team.\n\nWhat is the maximum number of teams that the school will be able to present at the Olympiad? How should the teams be formed for that?",
"input": "",
"output": "```python\nNoOfstudents=int(input())\r\nstudents=[int(x) for x in input().split()]\r\nmaths=[]\r\nprogramming=[]\r\nPE=[]\r\nif NoOfstudents>=3:\r\n for i in range(len(students)):\r\n if students[i]==1:\r\n programming.append(i+1)\r\n elif students[i]==2:\r\n maths.append(i+1)\r\n elif students[i]==3:\r\n PE.append(i+1)\r\nNoOfTeams=min(len(programming),len(maths),len(PE))\r\nprint(NoOfTeams)\r\nfor i in range(NoOfTeams):\r\n print(programming[i],maths[i],PE[i])\r\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Little Vasya has received a young builder’s kit. The kit consists of several wooden bars, the lengths of all of them are known. The bars can be put one on the top of the other if their lengths are the same.\n\nVasya wants to construct the minimal number of towers from the bars. Help Vasya to use the bars in the best way possible.",
"input": "",
"output": "```python\nfrom collections import defaultdict\r\n\r\n\r\nn=int(input())\r\na=list(map(int,input().split()))\r\nd=defaultdict(int)\r\nfor i in a:\r\n d[i]+=1\r\ndata,l=0,0\r\nfor i in d:\r\n data=max(data,i*d[i])\r\n l+=1\r\nprint(data,l)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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:\n\n1. Each domino completely covers two squares.\n\n2. No two dominoes overlap.\n\n3. Each domino lies entirely inside the board. It is allowed to touch the edges of the board.\n\nFind the maximum number of dominoes, which can be placed under these restrictions.",
"input": "",
"output": "```python\narea = [int(x) for x in input().split(\" \")]\narea = (area[0] * area[1]) - (area[0] * area[1] % 2)\nprint(area // 2)\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Unfortunately, Vasya can only sum pairs of integers (*a*, *b*), such that for any decimal place at least one number has digit 0 in this place. For example, Vasya can sum numbers 505 and 50, but he cannot sum 1 and 4.\n\nVasya has a set of *k* distinct non-negative integers *d*1,<=*d*2,<=...,<=*d**k*.\n\nVasya wants to choose some integers from this set so that he could sum any two chosen numbers. What maximal number of integers can he choose in the required manner?",
"input": "",
"output": "```python\nfrom collections import defaultdict\r\nn = int(input())\r\narr = [int(x) for x in input().split()]\r\nans = []\r\nd = defaultdict(bool)\r\nfor i in arr:\r\n if(i % 100 == 0 and not d[100]):\r\n d[100] = True\r\n ans.append(i)\r\n elif(i % 10 == 0 and not d[10]):\r\n d[10] = True\r\n ans.append(i)\r\n elif(i == 0):\r\n ans.append(i)\r\nif(d[10]):\r\n for i in arr:\r\n if('0' not in str(i) and len(str(i)) == 1):\r\n ans.append(i)\r\n break\r\nelse:\r\n for i in arr:\r\n if('0' not in str(i)):\r\n ans.append(i)\r\n break\r\nprint(len(ans))\r\nprint(*ans)\r\n\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "There is a right triangle with legs of length *a* and *b*. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.",
"input": "",
"output": "```python\nimport sys\r\ninput = sys.stdin.readline\r\n\r\n\r\ndef f(x):\r\n s = set()\r\n for i in range(1, x):\r\n y = (x**2 - i**2)**0.5\r\n if y == int(y):\r\n s.add((i, int(y)))\r\n return s\r\n\r\n\r\na, b = map(int, input().split())\r\nd = f(a)\r\nq = f(b)\r\nfor i1, i2 in d:\r\n for i3, i4 in q:\r\n if i1*i4 == i2*i3:\r\n print('YES')\r\n print(0, 0)\r\n print(-i1, i2)\r\n print(i4, i3)\r\n exit()\r\nprint('NO')\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "wHAT DO WE NEED cAPS LOCK FOR?\n\nCaps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage. \n\nLet's consider that a word has been typed with the Caps lock key accidentally switched on, if: \n - either it only contains uppercase letters; - or all letters except for the first one are uppercase. \nIn this case we should automatically change the case of all letters. For example, the case of the letters that form words \"hELLO\", \"HTTP\", \"z\" should be changed.\n\nWrite a program that applies the rule mentioned above. If the rule cannot be applied, the program should leave the word unchanged.",
"input": "",
"output": "```python\nss=\"aeiou\"\ns=input()\nnum=0\nfor i in range(0,len(s)):\n if s[i] in ss:\n num=i\naa=s[0:num+1]+'ntry'\nprint (aa.capitalize ())\n\n \t\t \t\t \t\t \t \t \t \t\t \t \t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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. \n\nPolycarp 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.\n\nYou are given an encoding *s* of some word, your task is to decode it.",
"input": "",
"output": "```python\nn=int(input())\r\ns=input()\r\na=list(s)\r\nif len(a)%2!=0:\r\n p=\"\"\r\n f=\"\"\r\n for i in range(len(s)):\r\n if i%2==0:\r\n p+=a[i]\r\n else:\r\n f+=a[i]\r\n print(f[::-1]+p)\r\nelse:\r\n p=\"\"\r\n f=\"\"\r\n for i in range(len(s)):\r\n if i%2==0:\r\n f+=a[i]\r\n else:\r\n p+=a[i]\r\n print(f[::-1]+p)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are given string *s* consists of opening and closing brackets of four kinds <>, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >.\n\nThe following definition of a regular bracket sequence is well-known, so you can be familiar with it.\n\nLet's define a regular bracket sequence (RBS). Empty string is RBS. Let *s*1 and *s*2 be a RBS then the strings <*s*1>*s*2, {*s*1}*s*2, [*s*1]*s*2, (*s*1)*s*2 are also RBS.\n\nFor example the string \"[[(){}]<>]\" is RBS, but the strings \"[)()\" and \"][()()\" are not.\n\nDetermine the least number of replaces to make the string *s* RBS.",
"input": "",
"output": "```python\nS = input()\r\n\r\ndef is_open(x):\r\n return x == '<' or x == '{' or x == '[' or x == '('\r\n\r\ndef is_match(x, y):\r\n if x == '<':\r\n return y == '>'\r\n elif x == '{':\r\n return y == '}'\r\n elif x == '[':\r\n return y == ']'\r\n else:\r\n return y == ')'\r\n \r\n\r\nopen_cnt = 0\r\nclose_cnt = 0\r\n\r\nstack = []\r\nfor s in S:\r\n if not is_open(s):\r\n if len(stack) > 0 and is_open(stack[-1]) and is_match(stack[-1], s):\r\n stack.pop()\r\n open_cnt-= 1\r\n else:\r\n close_cnt+= 1\r\n stack.append(s)\r\n else:\r\n open_cnt+= 1\r\n stack.append(s)\r\n \r\nprint(stack)\r\n \r\nif(open_cnt == close_cnt):\r\n print(open_cnt)\r\nelse:\r\n print('Impossible')\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Sometimes some words like \"localization\" or \"internationalization\" are so long that writing them many times in one text is quite tiresome.\n\nLet's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.\n\nThis abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.\n\nThus, \"localization\" will be spelt as \"l10n\", and \"internationalization» will be spelt as \"i18n\".\n\nYou are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.",
"input": "",
"output": "```python\nn = int (input())\r\nfor i in range (n):\r\n word = input()\r\n if len (word) <= 10:\r\n print (word)\r\n else:\r\n print (word[0] + str (len (word) - 2) + word[len(word) - 1])\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.\n\nThe toy consists of *n* parts and *m* ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part *i* as *v**i*. The child spend *v**f*1<=+<=*v**f*2<=+<=...<=+<=*v**f**k* energy for removing part *i* where *f*1,<=*f*2,<=...,<=*f**k* are the parts that are directly connected to the *i*-th and haven't been removed.\n\nHelp the child to find out, what is the minimum total energy he should spend to remove all *n* parts.",
"input": "",
"output": "```python\nn, m = map(int, input().split())\r\nf = [int(x) for x in input().split()]\r\nans = 0\r\nfor i in range(m):\r\n a, b = map(int, input().split())\r\n ans += min(f[a - 1], f[b - 1])\r\nprint(ans)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "There were *n* groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team.\n\nThe coach decided to form teams of exactly three people for this training. Determine the maximum number of teams of three people he can form. It is possible that he can't use all groups to form teams. For groups of two, either both students should write the contest, or both should not. If two students from a group of two will write the contest, they should be in the same team.",
"input": "",
"output": "```python\nn=int(input())\r\na=list(map(int,input().split()))\r\nif 1 not in a:\r\n print(\"0\")\r\nelif 2 not in a:\r\n print(n//3)\r\nelse:\r\n x=a.count(1)\r\n y=a.count(2)\r\n if y>=x:\r\n print(x)\r\n else:\r\n print(x + ((x-y)//3))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vanya walks late at night along a straight street of length *l*, lit by *n* lanterns. Consider the coordinate system with the beginning of the street corresponding to the point 0, and its end corresponding to the point *l*. Then the *i*-th lantern is at the point *a**i*. The lantern lights all points of the street that are at the distance of at most *d* from it, where *d* is some positive number, common for all lanterns. \n\nVanya wonders: what is the minimum light radius *d* should the lanterns have to light the whole street?",
"input": "",
"output": "```python\nn,l = map(int, input().split())\r\nlntr = list(map(int,input().split()))\r\nlntr.sort()\r\nmaxi = 0\r\n\r\nfor i in range(n-1):\r\n maxi = max(maxi,lntr[i+1]-lntr[i])\r\nres = max([maxi/2, lntr[0]-0, l-lntr[n-1]])\r\nprint(float(res))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.\n\nAs for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:\n - There are *n* knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to *n*. - The tournament consisted of *m* fights, in the *i*-th fight the knights that were still in the game with numbers at least *l**i* and at most *r**i* have fought for the right to continue taking part in the tournament. - After the *i*-th fight among all participants of the fight only one knight won — the knight number *x**i*, he continued participating in the tournament. Other knights left the tournament. - The winner of the last (the *m*-th) fight (the knight number *x**m*) became the winner of the tournament. \nYou fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number *b* was conquered by the knight number *a*, if there was a fight with both of these knights present and the winner was the knight number *a*.\n\nWrite the code that calculates for each knight, the name of the knight that beat him.",
"input": "",
"output": "```python\ndef update(v,l,r,src,p_src,kl,kr):\r\n if(l>r or la[v]==-1):\r\n return\r\n if(kl==kr):\r\n la[v]=src\r\n visited[kl]=src\r\n return\r\n else:\r\n km=(kl+kr)//2\r\n update(2*v,l,min(r,km),src,p_src,kl,km)\r\n update(2*v+1,max(km+1,l),r,src,p_src,km+1,kr)\r\n if(la[2*v]>-2 and la[2*v+1]>-2):\r\n la[v]=-1\r\n visited[p_src]=src\r\n\r\n\r\nn,m=map(int,input().split())\r\ni=1\r\nwhile(2**i 1:\r\n print(\"LEFT\")\r\n k -= 1\r\n print(\"\\nRIGHT\\n\".join((\"PRINT \" + c) for c in s))\r\nelse:\r\n while k < n:\r\n print(\"RIGHT\")\r\n k += 1\r\n print(\"\\nLEFT\\n\".join((\"PRINT \" + c) for c in reversed(s)))\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "After celebrating the midcourse the students of one of the faculties of the Berland State University decided to conduct a vote for the best photo. They published the photos in the social network and agreed on the rules to choose a winner: the photo which gets most likes wins. If multiple photoes get most likes, the winner is the photo that gets this number first.\n\nHelp guys determine the winner photo by the records of likes.",
"input": "",
"output": "```python\ndef run(n, arr):\n photos = []\n top = dict(id=arr.pop(0), likes=1)\n\n for id in arr:\n found = False\n for photo in photos:\n if photo['id'] == id:\n found = True\n photo['likes'] += 1\n if photo['likes'] > top['likes']:\n top = photo\n break\n if not found:\n photos.append(dict(id=id, likes=1))\n\n return top['id']\n\n\ndef read_data():\n n = int(input())\n arr = [int(x) for x in input().split(\" \")]\n return n, arr\n\n\nn, arr = read_data()\n\nprint(run(n, arr))\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Sengoku still remembers the mysterious \"colourful meteoroids\" she discovered with Lala-chan when they were little. In particular, one of the nights impressed her deeply, giving her the illusion that all her fancies would be realized.\n\nOn that night, Sengoku constructed a permutation *p*1,<=*p*2,<=...,<=*p**n* of integers from 1 to *n* inclusive, with each integer representing a colour, wishing for the colours to see in the coming meteor outburst. Two incredible outbursts then arrived, each with *n* meteorids, colours of which being integer sequences *a*1,<=*a*2,<=...,<=*a**n* and *b*1,<=*b*2,<=...,<=*b**n* respectively. Meteoroids' colours were also between 1 and *n* inclusive, and the two sequences were not identical, that is, at least one *i* (1<=≤<=*i*<=≤<=*n*) exists, such that *a**i*<=≠<=*b**i* holds.\n\nWell, she almost had it all — each of the sequences *a* and *b* matched exactly *n*<=-<=1 elements in Sengoku's permutation. In other words, there is exactly one *i* (1<=≤<=*i*<=≤<=*n*) such that *a**i*<=≠<=*p**i*, and exactly one *j* (1<=≤<=*j*<=≤<=*n*) such that *b**j*<=≠<=*p**j*.\n\nFor now, Sengoku is able to recover the actual colour sequences *a* and *b* through astronomical records, but her wishes have been long forgotten. You are to reconstruct any possible permutation Sengoku could have had on that night.",
"input": "",
"output": "```python\nn = int(input())\r\nai = list(map(int,input().split()))\r\nbi = list(map(int,input().split()))\r\nci = [0]*n\r\nfor i in range(n):\r\n ci[i] = ai[i]\r\nnums = [0]*n\r\nind = [0]*2\r\nj = 0\r\nnum = 0\r\nfor i in range(n):\r\n nums[ai[i]-1] += 1\r\nfor i in range(n):\r\n if nums[ai[i]-1] == 2:\r\n ind[j] = i\r\n j += 1\r\n if nums[i] == 0:\r\n num = i+1 \r\n \r\nci[ind[0]] = num\r\ndif = 0\r\ndif2 = 0\r\nfor i in range(n):\r\n if ci[i] != bi[i]:\r\n dif += 1\r\n if ci[i] != ai[i]:\r\n dif2 += 1\r\nif dif != 1 or dif2 != 1:\r\n ci[ind[0]] = ai[ind[0]]\r\n ci[ind[1]] = num\r\nfor i in range(n):\r\n print(ci[i],end=\" \")\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.\n\nThe rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. \n\nSometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.\n\nYour task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.",
"input": "",
"output": "```python\nimport sys\r\ninput=sys.stdin.readline\r\nm=1000000007\r\n\r\n#------------------------------------#\r\n\r\nfor _ in range(int(input())):\r\n cell=input().strip()\r\n if cell[0]==\"R\":\r\n #convert to AA format\r\n secindex=cell.index(\"C\")\r\n number1=int(cell[1:secindex])\r\n number2=int(cell[secindex+1:])-1\r\n column=\"\"\r\n while(number2>0):\r\n column+=chr(ord(\"A\")+number2%26)\r\n number2=number2//26-1\r\n print(column[::-1],number1,sep=\"\")\r\n else:\r\n i=0\r\n column=0\r\n while(not cell[i].isdigit()):\r\n column=column*26+ord(cell[i])-ord(\"A\")+1\r\n i+=1\r\n print(\"R\"+cell[i:]+\"C\"+str(column))\r\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Iahub is very proud of his recent discovery, propagating trees. Right now, he invented a new tree, called xor-tree. After this new revolutionary discovery, he invented a game for kids which uses xor-trees.\n\nThe game is played on a tree having *n* nodes, numbered from 1 to *n*. Each node *i* has an initial value *init**i*, which is either 0 or 1. The root of the tree is node 1.\n\nOne can perform several (possibly, zero) operations on the tree during the game. The only available type of operation is to pick a node *x*. Right after someone has picked node *x*, the value of node *x* flips, the values of sons of *x* remain the same, the values of sons of sons of *x* flips, the values of sons of sons of sons of *x* remain the same and so on.\n\nThe goal of the game is to get each node *i* to have value *goal**i*, which can also be only 0 or 1. You need to reach the goal of the game by using minimum number of operations.",
"input": "",
"output": "```python\nn=int(input())\r\nfrom collections import defaultdict\r\ngraph=defaultdict(list)\r\nfor i in range(n-1):\r\n u,v=[int(i) for i in input().split()]\r\n graph[u].append(v)\r\n graph[v].append(u)\r\n\r\ncurr=[int(i) for i in input().split()]\r\ngoal=[int(i) for i in input().split()]\r\n\r\nops=[]\r\ndef dfs(parent,ver,odd,even,lev):\r\n par=lev%2\r\n temp=curr[ver-1]\r\n changed=0\r\n if par and odd%2:\r\n temp=curr[ver-1]^1\r\n if par==0 and even%2:\r\n temp=curr[ver-1]^1\r\n #print(curr[ver-1],goal[ver-1])\r\n if temp!=goal[ver-1]:\r\n ops.append(ver)\r\n changed=1\r\n \r\n\r\n for ne in graph[ver]:\r\n if ne!=parent:\r\n if changed:\r\n if lev%2:\r\n dfs(ver,ne,odd+1,even,lev+1)\r\n else:\r\n dfs(ver,ne,odd,even+1,lev+1)\r\n else:\r\n dfs(ver,ne,odd,even,lev+1)\r\n\r\ndfs(-1,1,0,0,0)\r\nprint(len(ops))\r\nfor i in ops:\r\n print(i)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Mahmoud has an array *a* consisting of *n* integers. He asked Ehab to find another array *b* of the same length such that:\n - *b* is lexicographically greater than or equal to *a*. - *b**i*<=≥<=2. - *b* is pairwise coprime: for every 1<=≤<=*i*<=<<=*j*<=≤<=*n*, *b**i* and *b**j* are coprime, i. e. *GCD*(*b**i*,<=*b**j*)<==<=1, where *GCD*(*w*,<=*z*) is the greatest common divisor of *w* and *z*. \nEhab wants to choose a special array so he wants the lexicographically minimal array between all the variants. Can you find it?\n\nAn array *x* is lexicographically greater than an array *y* if there exists an index *i* such than *x**i*<=><=*y**i* and *x**j*<==<=*y**j* for all 1<=≤<=*j*<=<<=*i*. An array *x* is equal to an array *y* if *x**i*<==<=*y**i* for all 1<=≤<=*i*<=≤<=*n*.",
"input": "",
"output": "```python\nprint(\"Even\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Bachgold problem is very easy to formulate. Given a positive integer *n* represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.\n\nRecall that integer *k* is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and *k*.",
"input": "",
"output": "```python\ndef isprime(n):\r\n for n in range(n,100001):\r\n s=int(n**(0.5))\r\n f=1\r\n for j in range(2,s+1):\r\n if(n%j==0):\r\n f=0\r\n break\r\n if(f==1):\r\n return(n)\r\n\r\nprint(isprime(20))\r\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A company has *n* employees numbered from 1 to *n*. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee *A* is said to be the superior of another employee *B* if at least one of the following is true:\n - Employee *A* is the immediate manager of employee *B* - Employee *B* has an immediate manager employee *C* such that employee *A* is the superior of employee *C*. \nThe company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.\n\nToday the company is going to arrange a party. This involves dividing all *n* employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees *A* and *B* such that *A* is the superior of *B*.\n\nWhat is the minimum number of groups that must be formed?",
"input": "",
"output": "```python\ndic = dict()\nnum = int(input())\ncount = 0\ncheck = list()\nfor n in range(1, num + 1):\n employee = n\n manager = int(input())\n if manager in dic:\n dic[manager].append(employee)\n else:\n dic[manager] = list()\n dic[manager].append(employee)\ncheck = dic[-1]\nsize = len(check)\nwhile size > 0:\n for i in range(size):\n employee = check.pop()\n if employee in dic:\n for elem in dic[employee]:\n check.append(elem)\n size = len(check)\n count += 1\nprint(count)\n\n\n\n\n\n\t \t \t\t \t \t \t\t\t \t \t\t \t \t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Mikhail walks on a 2D plane. He can go either up or right. You are given a sequence of Mikhail's moves. He thinks that this sequence is too long and he wants to make it as short as possible.\n\nIn the given sequence moving up is described by character U and moving right is described by character R. Mikhail can replace any pair of consecutive moves RU or UR with a diagonal move (described as character D). After that, he can go on and do some other replacements, until there is no pair of consecutive moves RU or UR left.\n\nYour problem is to print the minimum possible length of the sequence of moves after the replacements.",
"input": "",
"output": "```python\nn-int(input())\r\nx=input().lower()\r\ni-0\r\nwhile i < len(x) -1:\r\nif x[i]+x[i+1] in ('ur', 'ru'):\r\n i=i+2\r\n n=n-1\r\nelse:\r\n i=i+1\r\nprint (n)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Translator's note: in Russia's most widespread grading system, there are four grades: 5, 4, 3, 2, the higher the better, roughly corresponding to A, B, C and F respectively in American grading system.\n\nThe term is coming to an end and students start thinking about their grades. Today, a professor told his students that the grades for his course would be given out automatically — he would calculate the simple average (arithmetic mean) of all grades given out for lab works this term and round to the nearest integer. The rounding would be done in favour of the student — $4.5$ would be rounded up to $5$ (as in example 3), but $4.4$ would be rounded down to $4$.\n\nThis does not bode well for Vasya who didn't think those lab works would influence anything, so he may receive a grade worse than $5$ (maybe even the dreaded $2$). However, the professor allowed him to redo some of his works of Vasya's choosing to increase his average grade. Vasya wants to redo as as few lab works as possible in order to get $5$ for the course. Of course, Vasya will get $5$ for the lab works he chooses to redo.\n\nHelp Vasya — calculate the minimum amount of lab works Vasya has to redo.",
"input": "",
"output": "```python\nn=int(input())\r\na=list(map(int,input().split()))\r\nk=sum(a)\r\nav=k/n\r\nc=0\r\nif(av<4.5):\r\n a.sort()\r\n s=int(n*4.5)-k\r\n if(n%2!=0):\r\n s+=1\r\n q=0\r\n for i in range(n):\r\n if(q>=s):\r\n break\r\n else:\r\n q+=5-a[i]\r\n c+=1\r\nprint(c)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they are not under its influence.\n\nHe has names of *n* people who possessed the diary in order. You need to tell, for each person, if he/she possessed the diary at some point before or not.\n\nFormally, for a name *s**i* in the *i*-th line, output \"YES\" (without quotes) if there exists an index *j* such that *s**i*<==<=*s**j* and *j*<=<<=*i*, otherwise, output \"NO\" (without quotes).",
"input": "",
"output": "```python\nn=int(input())\r\nlista=[]\r\nfor i in range(n):\r\n\tnam=input()\r\n\tif nam in lista:\r\n\t\tprint(\"YES\")\r\n\telse:\r\n\t\tlista.append(nam)\r\n\t\tprint(\"NO\")\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Sereja has an array *a*, consisting of *n* integers *a*1, *a*2, ..., *a**n*. The boy cannot sit and do nothing, he decided to study an array. Sereja took a piece of paper and wrote out *m* integers *l*1,<=*l*2,<=...,<=*l**m* (1<=≤<=*l**i*<=≤<=*n*). For each number *l**i* he wants to know how many distinct numbers are staying on the positions *l**i*, *l**i*<=+<=1, ..., *n*. Formally, he want to find the number of distinct numbers among *a**l**i*,<=*a**l**i*<=+<=1,<=...,<=*a**n*.?\n\nSereja wrote out the necessary array elements but the array was so large and the boy was so pressed for time. Help him, find the answer for the described question for each *l**i*.",
"input": "",
"output": "```python\n#采用预处理策略,避免每一次都遍历一遍列表\r\nn,m = map(int,input().split())\r\nline = list(map(int,input().split()))\r\ndistinct_nums = []\r\nvisited = [0]*100001 #用于标记每一个数字是否被访问过\r\ndistinct = 0\r\nfor i in range(n-1,-1,-1):\r\n if visited[line[i]] == 0:\r\n distinct += 1\r\n distinct_nums.append(distinct)\r\n visited[line[i]] = 1\r\n else:\r\n distinct_nums.append(distinct)\r\n\r\nfor i in range(m):\r\n l = int(input())\r\n print(distinct_nums[l-1])\r\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Indian summer is such a beautiful time of the year! A girl named Alyona is walking in the forest and picking a bouquet from fallen leaves. Alyona is very choosy — she doesn't take a leaf if it matches the color and the species of the tree of one of the leaves she already has. Find out how many leaves Alyona has picked.",
"input": "",
"output": "```python\nlis=[]\nfor _ in range(int(input())):\n a,b=map(str,input().split())\n lis.append([a,b])\nans = []\nfor i in range(len(lis)):\n if lis[i] in ans:\n pass\n else:\n ans.append(lis[i])\nprint(len(ans))\n\n \t\t \t\t\t\t \t \t \t \t\t\t\t\t\t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "New Year is coming in Line World! In this world, there are *n* cells numbered by integers from 1 to *n*, as a 1<=×<=*n* board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.\n\nSo, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of *n*<=-<=1 positive integers *a*1,<=*a*2,<=...,<=*a**n*<=-<=1. For every integer *i* where 1<=≤<=*i*<=≤<=*n*<=-<=1 the condition 1<=≤<=*a**i*<=≤<=*n*<=-<=*i* holds. Next, he made *n*<=-<=1 portals, numbered by integers from 1 to *n*<=-<=1. The *i*-th (1<=≤<=*i*<=≤<=*n*<=-<=1) portal connects cell *i* and cell (*i*<=+<=*a**i*), and one can travel from cell *i* to cell (*i*<=+<=*a**i*) using the *i*-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (*i*<=+<=*a**i*) to cell *i* using the *i*-th portal. It is easy to see that because of condition 1<=≤<=*a**i*<=≤<=*n*<=-<=*i* one can't leave the Line World using portals.\n\nCurrently, I am standing at cell 1, and I want to go to cell *t*. However, I don't know whether it is possible to go there. Please determine whether I can go to cell *t* by only using the construted transportation system.",
"input": "",
"output": "```python\nl=(input().split())\r\nm=[int(l[0]),int(l[1])]\r\nn=input().split()\r\np=[]\r\na=0\r\nfor i in range(len(n)):\r\n p=p+[n[i]]\r\nfor j in range(len(n)):\r\n a=a+p[j]\r\n if a==l[1]:\r\n print('YES')\r\n break\r\n elif a>l[1]:\r\n print('NO')\r\n break\r\n\t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Professor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest. \n\nIn total, *n* students will attend, and before the start, every one of them has some positive integer rating. Students are indexed from 1 to *n*. Let's denote the rating of *i*-th student as *a**i*. After the contest ends, every student will end up with some positive integer position. GukiZ expects that his students will take places according to their ratings. \n\nHe thinks that each student will take place equal to . In particular, if student *A* has rating strictly lower then student *B*, *A* will get the strictly better position than *B*, and if two students have equal ratings, they will share the same position. \n\nGukiZ would like you to reconstruct the results by following his expectations. Help him and determine the position after the end of the contest for each of his students if everything goes as expected.",
"input": "",
"output": "```python\nstudents = int(input())\nratings = list(map(int, input().split(' ')))\ndifferent_ratings = list(reversed(sorted(set(ratings))))\nrankings = {}\n\nfor i in range(len(different_ratings)):\n if i == 0:\n rankings[different_ratings[i]] = 1\n else:\n rankings[different_ratings[i]] = rankings[different_ratings[i - 1]] + ratings.count(different_ratings[i - 1])\n\npositions = []\n\nfor rating in ratings:\n positions.append(rankings[rating])\n\nprint(*positions)\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "The input contains two integers *a*1,<=*a*2 (0<=≤<=*a**i*<=≤<=109), separated by a single space.\n\nOutput a single integer.",
"input": "",
"output": "```python\nn=input().split()\nc=int(n[1])\na=[]\nb=[]\nl=\"\"\no=\"\"\nd=[]\nfor i in n[1]:\n\ta.append(int(i))\na.reverse()\nfor i in n[0]:\n\tb.append(i)\nif len(n[0]) < len(n[1]):\n\tb.insert(0,'0')\nfor i in range (len(a)):\n\tl+= str(a[i])\n\to+= str(b[i])\np = int(l)\nq = int(o)\nprint(p+q)\n\t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You're given a row with $n$ chairs. We call a seating of people \"maximal\" if the two following conditions hold:\n 1. There are no neighbors adjacent to anyone seated. 1. It's impossible to seat one more person without violating the first rule. \nThe seating is given as a string consisting of zeros and ones ($0$ means that the corresponding seat is empty, $1$ — occupied). The goal is to determine whether this seating is \"maximal\".\n\nNote that the first and last seats are not adjacent (if $n \\ne 2$).",
"input": "",
"output": "```python\nn=input()\r\nl='0'+input()+'0'\r\nprint('No' if '000' in l or '11' in l else 'Yes')\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with *n* room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (*n*<=-<=1)-th room to the *n*-th room. Thus, you can go to room *x* only from room *x*<=-<=1.\n\nThe potato pie is located in the *n*-th room and Vitaly needs to go there. \n\nEach pair of consecutive rooms has a door between them. In order to go to room *x* from room *x*<=-<=1, you need to open the door between the rooms with the corresponding key. \n\nIn total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type *t* can open the door of type *T* if and only if *t* and *T* are the same letter, written in different cases. For example, key f can open door F.\n\nEach of the first *n*<=-<=1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.\n\nVitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room *n*.\n\nGiven the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room *n*, which has a delicious potato pie. Write a program that will help Vitaly find out this number.",
"input": "",
"output": "```python\nn=int(input())\ns=list(input())\n\nkeys=[0]*26\ncount=0\nfor i in range(0, (len(s)//2)):\n key = s[i*2]\n door = s[i*2+1]\n keys[ord(key)-97] += 1\n if (keys[ord(door)-65] > 0):\n keys[ord(door)-65] -= 1\n else:\n count+=1\nprint(count)\n\t \t \t \t\t \t \t\t \t\t\t \t\t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs.\n\nCatacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages are built on different depths they do not intersect each other. Every minute Petya arbitrary chooses a passage from the room he is currently in and then reaches the room on the other end of the passage in exactly one minute. When he enters a room at minute *i*, he makes a note in his logbook with number *t**i*: \n - If Petya has visited this room before, he writes down the minute he was in this room last time; - Otherwise, Petya writes down an arbitrary non-negative integer strictly less than current minute *i*. \nInitially, Petya was in one of the rooms at minute 0, he didn't write down number *t*0.\n\nAt some point during his wandering Petya got tired, threw out his logbook and went home. Vasya found his logbook and now he is curious: what is the minimum possible number of rooms in Paris catacombs according to Petya's logbook?",
"input": "",
"output": "```python\nn = int(input())\r\nt = [int(x) for x in input().split()]\r\nans = 0\r\nistime = [0] * (2 * 10 ** 5 + 13)\r\nistime[0] = 1\r\nfor i in range(n):\r\n if istime[t[i]] > 0:\r\n istime[t[i]] -= 1\r\n else:\r\n ans += 1\r\n istime[i + 1] += 1\r\nprint(ans + 1)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Arkady and Kirill visited an exhibition of rare coins. The coins were located in a row and enumerated from left to right from 1 to *k*, each coin either was laid with its obverse (front) side up, or with its reverse (back) side up.\n\nArkady and Kirill made some photos of the coins, each photo contained a segment of neighboring coins. Akrady is interested in obverses, so on each photo made by him there is at least one coin with obverse side up. On the contrary, Kirill is interested in reverses, so on each photo made by him there is at least one coin with its reverse side up.\n\nThe photos are lost now, but Arkady and Kirill still remember the bounds of the segments of coins each photo contained. Given this information, compute the remainder of division by 109<=+<=7 of the number of ways to choose the upper side of each coin in such a way, that on each Arkady's photo there is at least one coin with obverse side up, and on each Kirill's photo there is at least one coin with reverse side up.",
"input": "",
"output": "```python\nprint(\"_RANDOM_GUESS_1692552615.5669065\")# 1692552615.566924\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.\n\nAccording to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.\n\nVasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to *n*) and ending with the *n*-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the *n*-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.\n\nTo finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to *n*, and generated *m* queries of the form: find element with value *b**i* in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.\n\nBut the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.",
"input": "",
"output": "```python\nn1=int(input())\r\nl1=list(map(int,input().split()))\r\nn2=int(input())\r\nl2=list(map(int,input().split()))\r\ns1=0\r\ns2=0\r\nd={}\r\nfor i in range(len(l1)):\r\n d[l1[i]]=i\r\nfor i in range(len(l2)):\r\n if l2[i] in d:\r\n s1+=d[l2[i]]+1\r\n s2+=n1-d[l2[i]]\r\nprint(s1,end=\" \")\r\nprint(s2)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Fox Ciel has a board with *n* rows and *n* columns, there is one integer in each cell.\n\nIt's known that *n* is an odd number, so let's introduce . Fox Ciel can do the following operation many times: she choose a sub-board with size *x* rows and *x* columns, then all numbers in it will be multiplied by -1.\n\nReturn the maximal sum of numbers in the board that she can get by these operations.",
"input": "",
"output": "```python\nn = int(input())\r\n\r\nm = []\r\nfor _ in range(n):\r\n m.append(list(map(int, input().split())))\r\n m[-1].append(0)\r\nm.append([0]*(n+1))\r\nx = (n+1)//2\r\nf = [0,0]\r\n\r\ndef flip(v,k):\r\n return -v if k > 0 else v\r\n\r\nsol = int(-1e9)\r\nfor s in range(1<>i&1) + flip(m[i+x][j+x],(s>>i&1 ^ s>>(x-1)&1) ^ k)\r\n if j == x - 1:\r\n f[k] += flip(sum, s>>i & 1)\r\n elif i == x - 1:\r\n f[k] += flip(sum,k)\r\n else:\r\n f[k] += max(sum, -sum)\r\n current_sol += (max(f[0],f[1]) if j != x-1 else f[s>>(x-1)])\r\n sol = max(sol, current_sol)\r\n\r\n\r\nprint(sol)\r\n\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "One day Vasya painted a Cartesian coordinate system on a piece of paper and marked some set of points (*x*1,<=*y*1),<=(*x*2,<=*y*2),<=...,<=(*x**n*,<=*y**n*). Let's define neighbors for some fixed point from the given set (*x*,<=*y*): \n - point (*x*',<=*y*') is (*x*,<=*y*)'s right neighbor, if *x*'<=><=*x* and *y*'<==<=*y* - point (*x*',<=*y*') is (*x*,<=*y*)'s left neighbor, if *x*'<=<<=*x* and *y*'<==<=*y* - point (*x*',<=*y*') is (*x*,<=*y*)'s lower neighbor, if *x*'<==<=*x* and *y*'<=<<=*y* - point (*x*',<=*y*') is (*x*,<=*y*)'s upper neighbor, if *x*'<==<=*x* and *y*'<=><=*y* \nWe'll consider point (*x*,<=*y*) from the given set supercentral, if it has at least one upper, at least one lower, at least one left and at least one right neighbor among this set's points.\n\nVasya marked quite many points on the paper. Analyzing the picture manually is rather a challenge, so Vasya asked you to help him. Your task is to find the number of supercentral points in the given set.",
"input": "",
"output": "```python\ncount = int(input())\r\npoints = []\r\nfor i in range(count):\r\n point = tuple(input().split())\r\n points.append(point)\r\n\r\nanswer = 0\r\n\r\nfor (x, y) in points:\r\n left = False\r\n right = False\r\n up = False\r\n low = False\r\n for (x1, y1) in points:\r\n if x1 > x and y1 == y:\r\n right = True\r\n if x1 < x and y1 == y:\r\n left = True\r\n if x1 == x and y1 > y:\r\n up = True\r\n if x1 == x and y1 < y:\r\n low = True\r\n \r\n if left and right and up and low:\r\n answer += 1\r\n\r\nprint(answer)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.\n\nA tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (*u*,<=*v*) that belongs to the graph, *u* and *v* belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.\n\nDr. Evil gave Mahmoud and Ehab a tree consisting of *n* nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?\n\nA loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .",
"input": "",
"output": "```python\nn = int(input())\r\ng = [[] for i in range(n+1)]\r\nfor _ in range(n-1):\r\n u, v = map(int, input().split())\r\n g[u].append(v)\r\n g[v].append(u)\r\n \r\nvisited = [False for _ in range(n+1)]\r\ndef dfs(node, prev):\r\n if prev:\r\n visited[node] = 1\r\n else:\r\n visited[node] = 0\r\n for w in g[node]:\r\n if not visited[w]:\r\n dfs(w, 1 - prev)\r\n \r\ndfs(1, 0)\r\nc = [0, 0]\r\nfor visit in visited:\r\n if visit == 1:\r\n c[1] += 1\r\n else:\r\n c[0] += 1\r\n \r\nprint(c[0]*c[1]-n+1)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "In Aramic language words can only represent objects.\n\nWords in Aramic have special properties: \n - A word is a root if it does not contain the same letter more than once. - A root and all its permutations represent the same object. - The root $x$ of a word $y$ is the word that contains all letters that appear in $y$ in a way that each letter appears once. For example, the root of \"aaaa\", \"aa\", \"aaa\" is \"a\", the root of \"aabb\", \"bab\", \"baabb\", \"ab\" is \"ab\". - Any word in Aramic represents the same object as its root. \nYou have an ancient script in Aramic. What is the number of different objects mentioned in the script?",
"input": "",
"output": "```python\nd=set()\r\ninput()\r\nfor i in input().split():\r\n x=set()\r\n for j in i: x.add(j)\r\n d.add(''.join(sorted(x)))\r\nprint(len(d))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Not so long ago the Codecraft-17 contest was held on Codeforces. The top 25 participants, and additionally random 25 participants out of those who got into top 500, will receive a Codeforces T-shirt.\n\nUnfortunately, you didn't manage to get into top 25, but you got into top 500, taking place *p*.\n\nNow the elimination round of 8VC Venture Cup 2017 is being held. It has been announced that the Codecraft-17 T-shirt winners will be chosen as follows. Let *s* be the number of points of the winner of the elimination round of 8VC Venture Cup 2017. Then the following pseudocode will be executed: \n\nHere \"div\" is the integer division operator, \"mod\" is the modulo (the remainder of division) operator.\n\nAs the result of pseudocode execution, 25 integers between 26 and 500, inclusive, will be printed. These will be the numbers of places of the participants who get the Codecraft-17 T-shirts. It is guaranteed that the 25 printed integers will be pairwise distinct for any value of *s*.\n\nYou're in the lead of the elimination round of 8VC Venture Cup 2017, having *x* points. You believe that having at least *y* points in the current round will be enough for victory.\n\nTo change your final score, you can make any number of successful and unsuccessful hacks. A successful hack brings you 100 points, an unsuccessful one takes 50 points from you. It's difficult to do successful hacks, though.\n\nYou want to win the current round and, at the same time, ensure getting a Codecraft-17 T-shirt. What is the smallest number of successful hacks you have to do to achieve that?",
"input": "",
"output": "```python\np, x, y = map(int, input().split())\r\n\r\ndef shirtpicking(s, test):\r\n i = (s // 50) % 475\r\n res = []\r\n for t in range(25):\r\n i = (i * 96 + 42) % 475\r\n res.append(i+26)\r\n\r\n if test in res:\r\n return True\r\n else:\r\n return False\r\n\r\nif x >= y:\r\n for x1 in range((x - y) // 50 + 1):\r\n if shirtpicking(x - x1 * 50, p):\r\n print(0)\r\n exit()\r\n\r\nans = 0\r\n\r\ns = x\r\nints = 0\r\n\r\nwhile ans == 0:\r\n\r\n s += 50\r\n\r\n ints += 1\r\n if shirtpicking(s, p):\r\n print((ints + 1) // 2)\r\n exit()\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. \n\nUCDHP stores some secret information about meteors as an *n*<=×<=*m* table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries:\n - The query to swap two table rows; - The query to swap two table columns; - The query to obtain a secret number in a particular table cell. \nAs the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.",
"input": "",
"output": "```python\nimport sys\ninput = sys.stdin.readline\nn ,m ,k = map(int ,input().split())\nrow ,col ,Data = [], [],[]\nfor i in range(n):\n row.append(i)\n a = list(input().split())\n Data.append(a)\nfor i in range(m):\n col.append(i)\nfor _ in range(k):\n s ,x ,y = input().split()\n x , y = int(x) ,int(y)\n if s == 'g':\n print(Data[row[x-1]][col[y-1]])\n elif s == 'r':\n tmp = row[x-1]\n row[x-1] = row[y-1]\n row[y-1] = tmp\n else :\n tmp = col[x-1]\n col[x-1] = col[y-1]\n col[y-1] = col[x-1]\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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*<=<<=*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. \n\nHelp the children and tell them how to form the line.",
"input": "",
"output": "```python\nfile=open(\"input.txt\",'r');c=open(\"output.txt\",'w')\na,b=map(int,file.readline().split())\nc.write(['BG'*b+'B'*(a-b),'GB'*a+'G'*(b-a)][a list[2] or list[1] + list[2] > list[3]:\n print(\"TRIANGLE\")\nelif list[0] + list[1] == list[2] or list[1] + list[2] == list[3]:\n print(\"SEGMENT\")\nelse:\n print(\"IMPOSSIBLE\")\n\n \t\t \t\t \t \t \t\t \t \t \t\t \t\t\t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "The year of 2012 is coming...\n\nAccording to an ancient choradrican legend in this very year, in 2012, Diablo and his brothers Mephisto and Baal will escape from hell, and innumerable hordes of demons will enslave the human world. But seven brave heroes have already gathered on the top of a mountain Arreat to protect us mere mortals from the effect of this terrible evil.\n\nThe seven great heroes are: amazon Anka, barbarian Chapay, sorceress Cleo, druid Troll, necromancer Dracul, paladin Snowy and a professional hit girl Hexadecimal. Heroes already know how much experience will be given for each of the three megabosses: *a* for Mephisto, *b* for Diablo and *c* for Baal.\n\nHere's the problem: heroes are as much as seven and megabosses are only three! Then our heroes decided to split into three teams, where each team will go to destroy their own megaboss. Each team member will receive a of experience, rounded down, where *x* will be the amount of experience for the killed megaboss and *y* — the number of people in the team.\n\nHeroes do not want to hurt each other's feelings, so they want to split into teams so that the difference between the hero who received the maximum number of experience and the hero who received the minimum number of experience were minimal. Since there can be several divisions into teams, then you need to find the one in which the total amount of liking in teams were maximum.\n\nIt is known that some heroes like others. But if hero *p* likes hero *q*, this does not mean that the hero *q* likes hero *p*. No hero likes himself.\n\nThe total amount of liking in teams is the amount of ordered pairs (*p*,<=*q*), such that heroes *p* and *q* are in the same group, and hero *p* likes hero *q* (but it is not important if hero *q* likes hero *p*). In case of heroes *p* and *q* likes each other and they are in the same group, this pair should be counted twice, as (*p*,<=*q*) and (*q*,<=*p*).\n\nA team can consist even of a single hero, but it is important that every megaboss was destroyed. All heroes must be involved in the campaign against evil. None of the heroes can be in more than one team.\n\nIt is guaranteed that every hero is able to destroy any megaboss alone.",
"input": "",
"output": "```python\nimport math\nimport itertools\n\nif __name__ == '__main__':\n N = int(input())\n likes = [input() for i in range(N)]\n likes = [line.split() for line in likes]\n likes = [(words[0], words[2]) for words in likes]\n a, b, c = (float(val) for val in input().split())\n\n min_diff = max(a, b, c)\n possible_groups = []\n for i in range(1, 7 - 1):\n for j in range(1, 7 - i):\n a_e = math.floor(a / i)\n b_e = math.floor(b / j)\n c_e = math.floor(c / (7 - i - j))\n diff = max(a_e, b_e, c_e) - min(a_e, b_e, c_e)\n if diff < min_diff:\n min_diff = diff\n possible_groups = [(i, j)]\n elif diff == min_diff:\n possible_groups.append((i, j))\n max_likes = 0\n for order in itertools.permutations(['Anka', 'Chapay', 'Cleo', 'Troll', 'Dracul', 'Snowy', 'Hexadecimal']):\n for i, j in possible_groups:\n likes_count = 0\n seta = set(order[:i])\n setb = set(order[i:(i + j)])\n setc = set(order[(i + j):])\n for p, q in likes:\n if p in seta and q in seta:\n likes_count += 1 \n if p in setb and q in setb:\n likes_count += 1 \n if p in setc and q in setc:\n likes_count += 1 \n max_likes = max(max_likes, likes_count)\n print(f'{min_diff} {max_likes}')\n\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are given a rectangular cake, represented as an *r*<=×<=*c* grid. Each cell either has an evil strawberry, or is empty. For example, a 3<=×<=4 cake may look as follows:\n\nThe cakeminator is going to eat the cake! Each time he eats, he chooses a row or a column that does not contain any evil strawberries and contains at least one cake cell that has not been eaten before, and eats all the cake cells there. He may decide to eat any number of times.\n\nPlease output the maximum number of cake cells that the cakeminator can eat.",
"input": "",
"output": "```python\na,b=list(map(int,input().split()))\r\nr=0\r\ng=0\r\nh=0\r\nl=[]\r\nfor i in range(a):\r\n s=input()\r\n if \"S\" in s:\r\n r+=s.count(\"S\")\r\n l.append(list(s))\r\n h+=1\r\n else:\r\n l.append(list(s))\r\n g+=1\r\nif h!=0 and g!=0:\r\n \r\n print(b*r) \r\nelif r==(a*b) :\r\n print(0)\r\nelif g==a:\r\n print(a*b) \r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nThere 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.\n\nYou 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.",
"input": "",
"output": "```python\nhs = []\r\nass = []\r\nfor _ in range(int(input())):\r\n h, a = map(int, input().split())\r\n hs.append(h)\r\n ass.append(a)\r\ncount = 0\r\nfor c in hs:\r\n for g in ass:\r\n if c== g:\r\n count+=1\r\n else:\r\n pass\r\nprint(count)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A company has *n* employees numbered from 1 to *n*. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee *A* is said to be the superior of another employee *B* if at least one of the following is true:\n - Employee *A* is the immediate manager of employee *B* - Employee *B* has an immediate manager employee *C* such that employee *A* is the superior of employee *C*. \nThe company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.\n\nToday the company is going to arrange a party. This involves dividing all *n* employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees *A* and *B* such that *A* is the superior of *B*.\n\nWhat is the minimum number of groups that must be formed?",
"input": "",
"output": "```python\n# https://codeforces.com/problemset/problem/115/A\r\n\r\nimport sys\r\n\r\n\r\ninp = tuple(int(line) for line in sys.stdin)\r\nhave_parent, have_child = set(), set()\r\n\r\nflag = -1\r\nfor i in range(1, len(inp)):\r\n if inp[i] == -1:\r\n continue\r\n else:\r\n have_parent.add(i)\r\n if i in have_child:\r\n flag = 3\r\n break\r\n\r\n have_child.add(inp[i])\r\n if inp[i] in have_parent:\r\n flag = 3\r\n break\r\n \r\nif not have_parent and not have_child:\r\n print(1)\r\nelif flag == 3:\r\n print(3)\r\nelse:\r\n print(2)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Phone number in Berland is a sequence of *n* digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.",
"input": "",
"output": "```python\n\r\nn = int(input())\r\ns = input()\r\n\r\nwhile (len(s) > 4):\r\n print (s[0:2], end='-')\r\n s = s[2:]\r\n\r\nif (len(s) <=3):\r\n print (s)\r\nelse:\r\n print (s[0:2], s[2:4], sep='-')\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Pasha has many hamsters and he makes them work out. Today, *n* hamsters (*n* is even) came to work out. The hamsters lined up and each hamster either sat down or stood up.\n\nFor another exercise, Pasha needs exactly hamsters to stand up and the other hamsters to sit down. In one minute, Pasha can make some hamster ether sit down or stand up. How many minutes will he need to get what he wants if he acts optimally well?",
"input": "",
"output": "```python\nn = int(input())\na = raw_input().strip()\n\n\nup = 0\n\n\nfor i in a:\n if i == 'X':\n up +=1\n\ndiff = (n // 2) - up\n\nprint(abs(diff))\n\nif diff >= 0:\n print(a.replace('x', 'X', diff))\nelse:\n print(a.replace('X', 'x', abs(diff)))\n\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Fox Ciel and her friends are in a dancing room. There are *n* boys and *m* girls here, and they never danced before. There will be some songs, during each song, there must be exactly one boy and one girl are dancing. Besides, there is a special rule:\n - either the boy in the dancing pair must dance for the first time (so, he didn't dance with anyone before); - or the girl in the dancing pair must dance for the first time. \nHelp Fox Ciel to make a schedule that they can dance as many songs as possible.",
"input": "",
"output": "```python\nx,y=map(int,input().split())\r\nz,x1,y1=[],[],[]\r\nfor i in range(1,x+1):\r\n\tfor j in range(1,y+1):\r\n\t\tif (i not in x1) or (j not in y1):\r\n\t\t\tx1.append(i)\r\n\t\t\ty1.append(j)\r\n\t\t\tz.append((i,j))\r\nprint(len(z))\r\nfor i in z:print(*i)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Let's denote as the number of bits set ('1' bits) in the binary representation of the non-negative integer *x*.\n\nYou are given multiple queries consisting of pairs of integers *l* and *r*. For each query, find the *x*, such that *l*<=≤<=*x*<=≤<=*r*, and is maximum possible. If there are multiple such numbers find the smallest of them.",
"input": "",
"output": "```python\nimport math\r\n\r\nn = int(input())\r\n\r\nfor _ in range(n):\r\n l, r = tuple(map(int, input().split()))\r\n t = int(math.log2(r + 1))\r\n if 2**t - 1 >= l and 2 ** t - 1 <= r:\r\n print(2 ** t - 1)\r\n else:\r\n print(r)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You have *m*<==<=*n*·*k* wooden staves. The *i*-th stave has length *a**i*. You have to assemble *n* barrels consisting of *k* staves each, you can use any *k* staves to construct a barrel. Each stave must belong to exactly one barrel.\n\nLet volume *v**j* of barrel *j* be equal to the length of the minimal stave in it.\n\nYou want to assemble exactly *n* barrels with the maximal total sum of volumes. But you have to make them equal enough, so a difference between volumes of any pair of the resulting barrels must not exceed *l*, i.e. |*v**x*<=-<=*v**y*|<=≤<=*l* for any 1<=≤<=*x*<=≤<=*n* and 1<=≤<=*y*<=≤<=*n*.\n\nPrint maximal total sum of volumes of equal enough barrels or 0 if it's impossible to satisfy the condition above.",
"input": "",
"output": "```python\nfrom bisect import bisect_right\r\n\r\n\r\ndef bad():\r\n print(0)\r\n exit()\r\n\r\n\r\nn, k, l_ = map(int, input().split())\r\na = sorted(list(map(int, input().split())))\r\n\r\nif n == 1:\r\n print(min(a))\r\n exit()\r\n\r\nif a[1] - a[0] > l_:\r\n bad()\r\n\r\nb = bisect_right(a, a[0] + l_)\r\n\r\nif b < n:\r\n bad()\r\n\r\nto_sum = [0]\r\n\r\nif n == 2:\r\n print(a[0] + a[n // 2])\r\n exit()\r\n\r\nto_sum += [min(k * i, b - n + i) for i in range(1, n)]\r\n\r\nprint(sum(a[i] for i in to_sum))\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nYour 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.",
"input": "",
"output": "```python\nn = int(input())\r\nl = [i for i in range(1, n+1) if i%2!=0]+[i for i in range(1, n+1) if i%2==0]\r\nfor i in range(n):\r\n try:\r\n if l[i]+1 == l[i+1] or l[i]-1 == l[i+1]:\r\n l.remove(l[i+1])\r\n except IndexError:\r\n break\r\nprint(len(l))\r\nprint(*l)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Stepan has a very big positive integer.\n\nLet's consider all cyclic shifts of Stepan's integer (if we look at his integer like at a string) which are also integers (i.e. they do not have leading zeros). Let's call such shifts as good shifts. For example, for the integer 10203 the good shifts are the integer itself 10203 and integers 20310 and 31020.\n\nStepan wants to know the minimum remainder of the division by the given number *m* among all good shifts. Your task is to determine the minimum remainder of the division by *m*.",
"input": "",
"output": "```python\ns = input()\nm = int(input())\nn = len(s)\ns = s + s\npot = []\npot.append(1)\nfor i in range(1, 200000):\n\tpot.append((pot[i - 1] * 10) % m)\ncur = 0\nmn = 1000000000\nfor i in range(0, 2 * n - 1):\n\tcur = (cur * 10 + ord(s[i]) - ord('0')) % m\n\tif i >= n:\n\t\tcur = (cur - (pot[n] * (ord(s[i]) - ord('0'))) % m + m) % m\n\tif i >= n - 1 and s[i - (n - 1)] != '0':\n\t\tmn = min(mn, cur)\nprint(mn)\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Hands that shed innocent blood!\n\nThere are *n* guilty people in a line, the *i*-th of them holds a claw with length *L**i*. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the *i*-th person kills the *j*-th person if and only if *j*<=<<=*i* and *j*<=≥<=*i*<=-<=*L**i*.\n\nYou are given lengths of the claws. You need to find the total number of alive people after the bell rings.",
"input": "",
"output": "```python\ntest = 1\r\n#test = int(input())\r\nfor _ in range(test):\r\n n = int(input())\r\n l = list(map(int,input().split()))\r\n x = 1\r\n k = n-1 - l[n-1]\r\n ind = n-2\r\n while ind >= 0:\r\n if k > ind:\r\n x+=1\r\n k = min(k,ind-l[ind])\r\n ind-=1\r\n print(x)\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Mr Keks is a typical white-collar in Byteland.\n\nHe has a bookshelf in his office with some books on it, each book has an integer positive price.\n\nMr Keks defines the value of a shelf as the sum of books prices on it. \n\nMiraculously, Mr Keks was promoted and now he is moving into a new office.\n\nHe learned that in the new office he will have not a single bookshelf, but exactly $k$ bookshelves. He decided that the beauty of the $k$ shelves is the [bitwise AND](https://en.wikipedia.org/wiki/Bitwise_operation#AND) of the values of all the shelves.\n\nHe also decided that he won't spend time on reordering the books, so he will place several first books on the first shelf, several next books on the next shelf and so on. Of course, he will place at least one book on each shelf. This way he will put all his books on $k$ shelves in such a way that the beauty of the shelves is as large as possible. Compute this maximum possible beauty.",
"input": "",
"output": "```python\n#!/usr/bin/python3.7\n\nimport sys\n\n\nn, k = [int(x) for x in input().split()]\na = [int(x) for x in input().split()]\n\ncur = 0\n\ndef is_submask(n, mask):\n return (n & mask) == mask\n\ndef f(mask):\n s = [[False for j in range(n)] for i in range(n)]\n for l in range(n):\n cur = 0\n for r in range(l, n):\n cur += a[r]\n s[l][r] = is_submask(cur, mask)\n dp = [[False for j in range(n)] for i in range(k)]\n dp[0] = s[0][:]\n for k1 in range(1, k):\n for r in range(n):\n for l in range(1, r + 1):\n dp[k1][r] |= dp[k1 - 1][l - 1] & s[l][r]\n return dp[k - 1][n - 1]\n\ncur = 0\nfor i in range(50, -1, -1):\n if f(cur + 2 ** i):\n cur += 2 ** i\nprint(cur)\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "In this task you need to process a set of stock exchange orders and use them to create order book.\n\nAn order is an instruction of some participant to buy or sell stocks on stock exchange. The order number *i* has price *p**i*, direction *d**i* — buy or sell, and integer *q**i*. This means that the participant is ready to buy or sell *q**i* stocks at price *p**i* for one stock. A value *q**i* is also known as a volume of an order.\n\nAll orders with the same price *p* and direction *d* are merged into one aggregated order with price *p* and direction *d*. The volume of such order is a sum of volumes of the initial orders.\n\nAn order book is a list of aggregated orders, the first part of which contains sell orders sorted by price in descending order, the second contains buy orders also sorted by price in descending order.\n\nAn order book of depth *s* contains *s* best aggregated orders for each direction. A buy order is better if it has higher price and a sell order is better if it has lower price. If there are less than *s* aggregated orders for some direction then all of them will be in the final order book.\n\nYou are given *n* stock exhange orders. Your task is to print order book of depth *s* for these orders.",
"input": "",
"output": "```python\nn, s = list(map(int, input().split()))\r\nB = []\r\nS = []\r\nfor i in range(n):\r\n st = list(input().split())\r\n st[1], st[2] = int(st[1]), int(st[2])\r\n if st[0] == 'B':\r\n B.append(st)\r\n else:\r\n S.append(st)\r\nB.sort()\r\nS.sort()\r\ni = 0\r\nwhile i < len(B) - 1:\r\n if B[i][1] == B[i + 1][1]:\r\n B[i][2] += B[i + 1][2]\r\n del(B[i + 1])\r\n else:\r\n i += 1\r\ni = 0\r\nwhile i < len(S) - 1:\r\n if S[i][1] == S[i + 1][1]:\r\n S[i][2] += S[i + 1][2]\r\n del(S[i + 1])\r\n else:\r\n i += 1\r\nB.reverse()\r\nfor i in range(min(s, len(S))):\r\n print(*S[i])\r\nfor i in range(min(s, len(B))):\r\n print(*B[i])\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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. \n\nA sequence *a*1, *a*2, ..., *a**n*, consisting of *n* integers, is Hungry if and only if: \n - Its elements are in increasing order. That is an inequality *a**i*<=<<=*a**j* holds for any two indices *i*,<=*j* (*i*<=<<=*j*). - For any two indices *i* and *j* (*i*<=<<=*j*), *a**j* must not be divisible by *a**i*. \nIahub is in trouble, so he asks you for help. Find a Hungry sequence with *n* elements.",
"input": "",
"output": "```python\nfrom queue import PriorityQueue\r\n\r\n\r\ndef isPrime(n):\r\n if(n==1 or n==0):\r\n return False\r\n for i in range(2,int(n**(1/2))+1):\r\n if(n%i==0):\r\n return False\r\n \r\n return True\r\n\r\ncount = int(input())\r\ns = ''\r\nfor i in range(1, 100000000):\r\n if count == 0:\r\n break\r\n if(isPrime(i)):\r\n s = s+ str(i) + ' '\r\n count -= 1\r\n\r\nprint(s.strip())\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Fox Ciel has *n* boxes in her room. They have the same size and weight, but they might have different strength. The *i*-th box can hold at most *x**i* boxes on its top (we'll call *x**i* the strength of the box). \n\nSince all the boxes have the same size, Ciel cannot put more than one box directly on the top of some box. For example, imagine Ciel has three boxes: the first has strength 2, the second has strength 1 and the third has strength 1. She cannot put the second and the third box simultaneously directly on the top of the first one. But she can put the second box directly on the top of the first one, and then the third box directly on the top of the second one. We will call such a construction of boxes a pile.\n\nFox Ciel wants to construct piles from all the boxes. Each pile will contain some boxes from top to bottom, and there cannot be more than *x**i* boxes on the top of *i*-th box. What is the minimal number of piles she needs to construct?",
"input": "",
"output": "```python\nn = int(input())\r\na = list(map(int,input().split()))\r\na.sort()\r\ns=[]\r\n\r\nfor i in range(n):\r\n s.sort(reverse = True)\r\n for j in range(len(s)):\r\n if i >= s[j]:\r\n s[j] += 1\r\n break\r\n else:\r\n s.append(1)\r\n\r\nprint(len(s))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point *x*(*x*<=><=0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order to get to his friend's house.",
"input": "",
"output": "```python\npos = int(input())\r\nif pos % 5 == 0:\r\n steps = int(pos/5)\r\n print(steps)\r\nelse:\r\n min = int(pos/5)\r\n stepss = min+1\r\n print(stepss)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You've got an array *a*, consisting of *n* integers: *a*1,<=*a*2,<=...,<=*a**n*. Your task is to find a minimal by inclusion segment [*l*,<=*r*] (1<=≤<=*l*<=≤<=*r*<=≤<=*n*) such, that among numbers *a**l*,<= *a**l*<=+<=1,<= ...,<= *a**r* there are exactly *k* distinct numbers.\n\nSegment [*l*,<=*r*] (1<=≤<=*l*<=≤<=*r*<=≤<=*n*; *l*,<=*r* are integers) of length *m*<==<=*r*<=-<=*l*<=+<=1, satisfying the given property, is called minimal by inclusion, if there is no segment [*x*,<=*y*] satisfying the property and less then *m* in length, such that 1<=≤<=*l*<=≤<=*x*<=≤<=*y*<=≤<=*r*<=≤<=*n*. Note that the segment [*l*,<=*r*] doesn't have to be minimal in length among all segments, satisfying the given property.",
"input": "",
"output": "```python\nn, k = map(int, input().split())\r\na = [0] + list(map(int, input().split()))\r\nfreq = [0] * (100001)\r\ndist = 0\r\nfor i in range(1, n+1):\r\n if freq[a[i]] == 0:\r\n dist += 1\r\n freq[a[i]] += 1\r\nl = 1 \r\nr = n\r\n\r\nif dist < k:\r\n print(-1, -1)\r\nelse:\r\n while dist >= k:\r\n freq[a[r]] -= 1\r\n if freq[a[r]] == 0:\r\n dist -= 1\r\n r -= 1\r\n r += 1\r\n dist += 1\r\n\r\n while dist >= k:\r\n freq[a[l]] -= 1\r\n if freq[a[l]] == 0:\r\n dist -= 1\r\n l += 1\r\n l -= 1\r\n print(l, r)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A dice is a cube, its faces contain distinct integers from 1 to 6 as black points. The sum of numbers at the opposite dice faces always equals 7. Please note that there are only two dice (these dices are mirror of each other) that satisfy the given constraints (both of them are shown on the picture on the left).\n\nAlice and Bob play dice. Alice has built a tower from *n* dice. We know that in this tower the adjacent dice contact with faces with distinct numbers. Bob wants to uniquely identify the numbers written on the faces of all dice, from which the tower is built. Unfortunately, Bob is looking at the tower from the face, and so he does not see all the numbers on the faces. Bob sees the number on the top of the tower and the numbers on the two adjacent sides (on the right side of the picture shown what Bob sees).\n\nHelp Bob, tell whether it is possible to uniquely identify the numbers on the faces of all the dice in the tower, or not.",
"input": "",
"output": "```python\nn = int(input())\nx = int(input())\nfaces = []\ndefault = {1,2,3,4,5,6}\nfor i in range(n):\n raw = set(map(int, input().split()))\n impr = set()\n for v in raw:\n impr.add(v)\n impr.add(7-v)\n if i == 0:\n impr.add(x)\n faces.append(default - impr)\n\ni = 1\nif n == 1:\n print(\"YES\")\n exit()\nfaces[1] = faces[1] - faces[0]\nif len(faces[1]) == 2:\n print(\"NO\")\n exit()\n\ni = 2\nwhile i < n:\n exc = faces[i] - faces[i-1]\n if len(exc) == 0:\n print(\"NO\")\n exit()\n i += 1\n \n \nprint(\"YES\")\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corresponding lowercase letter. Help Petya perform the comparison.",
"input": "",
"output": "```python\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Oct 5 23:07:21 2023\r\n\r\n@author: risha\r\n\"\"\"\r\n\r\ns1=list(input().lower())\r\ns2=list(input().lower())\r\nc=0\r\nfor i in range(len(s1)):\r\n if s1[i]==s2[i]:\r\n c=1\r\n else:\r\n if s1[i]s2[i]:\r\n print(\"1\")\r\n c=0\r\n break\r\nif c==1:\r\n print(0)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Dr. Evil kidnapped Mahmoud and Ehab in the evil land because of their performance in the Evil Olympiad in Informatics (EOI). He decided to give them some problems to let them go.\n\nDr. Evil is interested in sets, He has a set of *n* integers. Dr. Evil calls a set of integers evil if the MEX of it is exactly *x*. the MEX of a set of integers is the minimum non-negative integer that doesn't exist in it. For example, the MEX of the set {0,<=2,<=4} is 1 and the MEX of the set {1,<=2,<=3} is 0 .\n\nDr. Evil is going to make his set evil. To do this he can perform some operations. During each operation he can add some non-negative integer to his set or erase some element from it. What is the minimal number of operations Dr. Evil has to perform to make his set evil?",
"input": "",
"output": "```python\nn, m = map(int,input().split())\r\nl = list(map(int,input().split()))\r\nc = 0\r\nfor i in l :\r\n if i < m :\r\n c = c + 1\r\nif m in l :\r\n print(abs(m - c) + 1 )\r\nelse:\r\n print(abs(m - c) )\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Mr. Funt now lives in a country with a very specific tax laws. The total income of mr. Funt during this year is equal to *n* (*n*<=≥<=2) burles and the amount of tax he has to pay is calculated as the maximum divisor of *n* (not equal to *n*, of course). For example, if *n*<==<=6 then Funt has to pay 3 burles, while for *n*<==<=25 he needs to pay 5 and if *n*<==<=2 he pays only 1 burle.\n\nAs mr. Funt is a very opportunistic person he wants to cheat a bit. In particular, he wants to split the initial *n* in several parts *n*1<=+<=*n*2<=+<=...<=+<=*n**k*<==<=*n* (here *k* is arbitrary, even *k*<==<=1 is allowed) and pay the taxes for each part separately. He can't make some part equal to 1 because it will reveal him. So, the condition *n**i*<=≥<=2 should hold for all *i* from 1 to *k*.\n\nOstap Bender wonders, how many money Funt has to pay (i.e. minimal) if he chooses and optimal way to split *n* in parts.",
"input": "",
"output": "```python\nfrom sys import exit\r\nn=int(input())\r\ni=2\r\nwhile i*i<=n:\r\n if n%i==0:\r\n if n%2==0:\r\n print(2)\r\n else:\r\n print(3)\r\n exit()\r\n i+=1\r\nprint(1)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You've got a string *s*<==<=*s*1*s*2... *s*|*s*| of length |*s*|, consisting of lowercase English letters. There also are *q* queries, each query is described by two integers *l**i*,<=*r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=|*s*|). The answer to the query is the number of substrings of string *s*[*l**i*... *r**i*], which are palindromes.\n\nString *s*[*l*... *r*]<==<=*s**l**s**l*<=+<=1... *s**r* (1<=≤<=*l*<=≤<=*r*<=≤<=|*s*|) is a substring of string *s*<==<=*s*1*s*2... *s*|*s*|.\n\nString *t* is called a palindrome, if it reads the same from left to right and from right to left. Formally, if *t*<==<=*t*1*t*2... *t*|*t*|<==<=*t*|*t*|*t*|*t*|<=-<=1... *t*1.",
"input": "",
"output": "```python\nfrom array import array\r\nfrom sys import stdin ,stdout ,setrecursionlimit\r\nfrom threading import stack_size , Thread\r\nsetrecursionlimit(2**31-1)\r\ninput=stdin.readline\r\ndef print(*args, end='\\n', sep=' ') -> None:\r\n stdout.write(sep.join(map(str, args)) + end)\r\n\r\n\r\ndef palindrome(lef , righ):\r\n while (lef<=righ):\r\n if (st[lef]!=st[righ]):return 0 \r\n lef+=1 \r\n righ-=1\r\n return 1 \r\n \r\n\r\ndef dp(ind ,last):\r\n if ind==lenth:return \r\n if (last,ind) in mem :return\r\n mem[(last,ind)]=palindrome(last , ind)\r\n dp(ind+1,ind+1)\r\n if ind!=lenth-1:\r\n dp(ind+1 , last )\r\n\r\n\r\nst=input().strip() ; lenth=len(st) ; mem={}\r\n\r\n\r\ndef solve():\r\n dp(0,0) \r\n for i in range(lenth):\r\n for j in range(i,lenth):\r\n if j==i :continue\r\n mem[(i,j)]+=mem[(i,j-1 )]\r\n \r\n for i in range(lenth):\r\n for j in range(1,i+1):\r\n mem[(j,i)]+=mem[(j-1,i)]\r\n for _ in range(int(input())):\r\n l,r=map(int,input().split())\r\n l-=1 ; r-=1 \r\n if (l==0): print(mem[(r,r)])\r\n else: print(mem[(r,r)]-mem[(l-1,r)])\r\n\r\nstack_size(10**8) \r\nThread(target=solve).start()\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Alena has successfully passed the entrance exams to the university and is now looking forward to start studying.\n\nOne two-hour lesson at the Russian university is traditionally called a pair, it lasts for two academic hours (an academic hour is equal to 45 minutes).\n\nThe University works in such a way that every day it holds exactly *n* lessons. Depending on the schedule of a particular group of students, on a given day, some pairs may actually contain classes, but some may be empty (such pairs are called breaks).\n\nThe official website of the university has already published the schedule for tomorrow for Alena's group. Thus, for each of the *n* pairs she knows if there will be a class at that time or not.\n\nAlena's House is far from the university, so if there are breaks, she doesn't always go home. Alena has time to go home only if the break consists of at least two free pairs in a row, otherwise she waits for the next pair at the university.\n\nOf course, Alena does not want to be sleepy during pairs, so she will sleep as long as possible, and will only come to the first pair that is presented in her schedule. Similarly, if there are no more pairs, then Alena immediately goes home.\n\nAlena appreciates the time spent at home, so she always goes home when it is possible, and returns to the university only at the beginning of the next pair. Help Alena determine for how many pairs she will stay at the university. Note that during some pairs Alena may be at the university waiting for the upcoming pair.",
"input": "",
"output": "```python\nn = int(input(''))\r\nclasses = input('').split(' ')\r\n\r\n#stay = '1 0 1'\r\n\r\ncount = 0\r\nfor j in range(n-2):\r\n if((classes[j] == '1') and (classes[j+1] == '0') and (classes[j+2] == '1')):\r\n count = count + 1\r\n\r\nprint (count + classes.count('1'))\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Only *T* milliseconds left before the start of well-known online programming contest Codehorses Round 2017.\n\nPolycarp needs to download B++ compiler to take part in the contest. The size of the file is *f* bytes.\n\nPolycarp's internet tariff allows to download data at the rate of one byte per *t*0 milliseconds. This tariff is already prepaid, and its use does not incur any expense for Polycarp. In addition, the Internet service provider offers two additional packages:\n - download *a*1 bytes at the rate of one byte per *t*1 milliseconds, paying *p*1 burles for the package; - download *a*2 bytes at the rate of one byte per *t*2 milliseconds, paying *p*2 burles for the package. \nPolycarp can buy any package many times. When buying a package, its price (*p*1 or *p*2) is prepaid before usage. Once a package is bought it replaces the regular tariff until package data limit is completely used. After a package is consumed Polycarp can immediately buy a new package or switch to the regular tariff without loosing any time. While a package is in use Polycarp can't buy another package or switch back to the regular internet tariff.\n\nFind the minimum amount of money Polycarp has to spend to download an *f* bytes file no more than in *T* milliseconds.\n\nNote that because of technical reasons Polycarp can download only integer number of bytes using regular tariff and both packages. I.e. in each of three downloading modes the number of downloaded bytes will be integer. It means that Polycarp can't download a byte partially using the regular tariff or/and both packages.",
"input": "",
"output": "```python\nf, T, t0 = map(int, input().split())\r\na1, t1, p1= map(int, input().split())\r\na2, t2, p2= map(int, input().split())\r\n \r\ndef check(x, y):\r\n\tglobal f,T,t0,a1,t1,p1,a2,t2,p2\r\n\tz = f - x*a1-y*a2\r\n\ttemp = x*a1*t1 + y*a2*t2 + z*t0\r\n\tif temp<=T:\r\n\t\treturn p1*x + p2*y\r\n\treturn 1000000000000000004\r\n \r\n\r\nk = min(t0,min(t1,t2))\r\nif(f*k>T):\r\n print(-1)\r\nelif f*t0 <= T:\r\n print(0)\r\nelse:\r\n u1 = a1*t1 - a1*t0\r\n u2 = a2*t2 - a2*t0\r\n j = T - t0*f\r\n val = 1000000000000000004\r\n if(u1>=0):\r\n s = j\r\n if(s%u2==0):\r\n s//=u2\r\n val= min(val,check(0, s))\r\n else:\r\n s//=u2\r\n val= min(val,check(0, s))\r\n s+=1\r\n val= min(val,check(0, s))\r\n \r\n elif(u2>=0):\r\n s = j\r\n if(s%u1==0):\r\n s//=u1\r\n val= min(val,check(s, 0))\r\n else:\r\n s//=u1\r\n val= min(val,check(s, 0))\r\n s+=1\r\n val= min(val,check(s, 0))\r\n else:\r\n for x in range(0, 10000001):\r\n\t s = j - x*u1\r\n\t if(s%u2==0):\r\n\t s//=u2\r\n\t else:\r\n\t s//=u2\r\n\t s+=1\r\n\t if(s<0):\r\n\t break\r\n\t val= min(val,check(x, s))\r\n\t \r\n for x in range(0, 10000001):\r\n\t s = j - x*u2\r\n\t if(s%u1==0):\r\n\t s/=u1\r\n\t else:\r\n\t s//=u1\r\n\t s+=1\r\n\t if(s<0):\r\n\t break\r\n\t val= min(val,check(s,x))\r\n\t \r\n if(val==1000000000000000004):\r\n print(-1)\r\n else:\r\n \tprint(val)\r\n\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Kolya is going to make fresh orange juice. He has *n* oranges of sizes *a*1,<=*a*2,<=...,<=*a**n*. Kolya will put them in the juicer in the fixed order, starting with orange of size *a*1, then orange of size *a*2 and so on. To be put in the juicer the orange must have size not exceeding *b*, so if Kolya sees an orange that is strictly greater he throws it away and continues with the next one.\n\nThe juicer has a special section to collect waste. It overflows if Kolya squeezes oranges of the total size strictly greater than *d*. When it happens Kolya empties the waste section (even if there are no more oranges) and continues to squeeze the juice. How many times will he have to empty the waste section?",
"input": "",
"output": "```python\nn,b,d = map(int,input().split())\r\ns = list(map(int,input().split()))\r\nv = 0\r\not = 0\r\nfor i in range(n):\r\n if s[i] <= b:\r\n v += s[i]\r\n if v > d:\r\n ot += 1\r\n v = 0\r\nif v > d:\r\n ot += 1\r\nprint(ot)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "We consider a positive integer perfect, if and only if the sum of its digits is exactly $10$. Given a positive integer $k$, your task is to find the $k$-th smallest perfect positive integer.",
"input": "",
"output": "```python\ndef truee():\r\n l=sum(map(int,str(j)))\r\n if l==10:\r\n return 1\r\n return 0\r\nn=int(input())\r\nj=19\r\nk=1\r\nwhile k!=n:\r\n j+=9\r\n if truee()==1:\r\n k+=1\r\nprint(j)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Mr. Kitayuta has just bought an undirected graph consisting of *n* vertices and *m* edges. The vertices of the graph are numbered from 1 to *n*. Each edge, namely edge *i*, has a color *c**i*, connecting vertex *a**i* and *b**i*.\n\nMr. Kitayuta wants you to process the following *q* queries.\n\nIn the *i*-th query, he gives you two integers — *u**i* and *v**i*.\n\nFind the number of the colors that satisfy the following condition: the edges of that color connect vertex *u**i* and vertex *v**i* directly or indirectly.",
"input": "",
"output": "```python\nfrom collections import defaultdict\r\n\r\ndef dfs(adjlist, start, visited, color):\r\n if start in visited:\r\n return\r\n \r\n for (v,c) in adjlist[start]:\r\n if c == color:\r\n visited.add(start)\r\n visited.add(v)\r\n dfs(adjlist, v, visited, color)\r\n \r\nif __name__ =='__main__':\r\n n,m = map(int, input().split())\r\n adjlist = defaultdict(list)\r\n all_color = set()\r\n for i in range(0,m):\r\n tmp = list(map(int, input().split()))\r\n adjlist[tmp[0]].append((tmp[1],tmp[2]))\r\n adjlist[tmp[1]].append((tmp[0],tmp[2]))\r\n all_color.add(tmp[2])\r\n num_queries = int(input())\r\n queries = []\r\n for i in range(0,num_queries):\r\n queries.append(list(map(int, input().split())))\r\n \r\n color_map = {}\r\n for c in all_color:\r\n visited = set()\r\n for src in range(1,n+1):\r\n dfs(adjlist, src, visited, c)\r\n color_map[c] = visited\r\n \r\n for q in queries:\r\n count = 0\r\n for c in all_color:\r\n if q[0] in color_map[c] and q[1] in color_map[c]:\r\n count += 1\r\n print(count)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Dwarfs have planted a very interesting plant, which is a triangle directed \"upwards\". This plant has an amusing feature. After one year a triangle plant directed \"upwards\" divides into four triangle plants: three of them will point \"upwards\" and one will point \"downwards\". After another year, each triangle plant divides into four triangle plants: three of them will be directed in the same direction as the parent plant, and one of them will be directed in the opposite direction. Then each year the process repeats. The figure below illustrates this process.\n\nHelp the dwarfs find out how many triangle plants that point \"upwards\" will be in *n* years.",
"input": "",
"output": "```python\nn = int(input())\r\n\r\nmod = 10**9 +7\r\n\r\ndef power_2_k(k):\r\n if k == 0:\r\n return 1\r\n if k % 2 == 0:\r\n lower = power_2_k(k // 2)\r\n return (lower * lower) % mod\r\n else:\r\n k -= 1\r\n lower = power_2_k(k // 2)\r\n return (((lower * lower) % mod) * 2) % mod\r\n\r\np = power_2_k(n)\r\nprint((p * (p + 1) // 2) % mod)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Lolek and Bolek are about to travel abroad by plane. The local airport has a special \"Choose Your Plane\" offer. The offer's conditions are as follows:\n - it is up to a passenger to choose a plane to fly on; - if the chosen plane has *x* (*x*<=><=0) empty seats at the given moment, then the ticket for such a plane costs *x* zlotys (units of Polish currency). \nThe only ticket office of the airport already has a queue of *n* passengers in front of it. Lolek and Bolek have not stood in the queue yet, but they are already wondering what is the maximum and the minimum number of zlotys the airport administration can earn if all *n* passengers buy tickets according to the conditions of this offer?\n\nThe passengers buy tickets in turn, the first person in the queue goes first, then goes the second one, and so on up to *n*-th person.",
"input": "",
"output": "```python\nn, m = map(int, input().split())\r\n\r\nseats = sorted([int(x) for x in input().split()])\r\nseatsc = [s for s in seats]\r\nif n >= sum(seats):\r\n sm = sum([(x * (x + 1)) // 2 for x in seats])\r\n print(sm, sm)\r\nelse:\r\n pc = 0\r\n mncost = 0\r\n mxcost = 0\r\n while pc < n:\r\n ind = seats.index(max(seats))\r\n mxcost += seats[ind]\r\n seats[ind] -= 1\r\n pc += 1\r\n pc = 0\r\n while pc < n:\r\n ind = seatsc.index(min(seatsc))\r\n mncost += seatsc[ind]\r\n seatsc[ind] -= 1\r\n if seatsc[ind] == 0:\r\n seatsc.pop(ind)\r\n pc += 1\r\n print(mxcost,mncost)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "The prison of your city has *n* prisoners. As the prison can't accommodate all of them, the city mayor has decided to transfer *c* of the prisoners to a prison located in another city.\n\nFor this reason, he made the *n* prisoners to stand in a line, with a number written on their chests. The number is the severity of the crime he/she has committed. The greater the number, the more severe his/her crime was.\n\nThen, the mayor told you to choose the *c* prisoners, who will be transferred to the other prison. He also imposed two conditions. They are,\n - The chosen *c* prisoners has to form a contiguous segment of prisoners. - Any of the chosen prisoner's crime level should not be greater then *t*. Because, that will make the prisoner a severe criminal and the mayor doesn't want to take the risk of his running away during the transfer. \nFind the number of ways you can choose the *c* prisoners.",
"input": "",
"output": "```python\nn=list(map(int,input().split()))\r\nk=list(map(int,input().split()))\r\nc2=0\r\nway=0\r\nfor i in k:\r\n if i<=n[1]:\r\n c2+=1\r\n else:\r\n c2=0\r\n if c2>n[2]:\r\n way+=1\r\nprint(way)\r\n\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Recently, Pari and Arya did some research about NP-Hard problems and they found the minimum vertex cover problem very interesting.\n\nSuppose the graph *G* is given. Subset *A* of its vertices is called a vertex cover of this graph, if for each edge *uv* there is at least one endpoint of it in this set, i.e. or (or both).\n\nPari and Arya have won a great undirected graph as an award in a team contest. Now they have to split it in two parts, but both of them want their parts of the graph to be a vertex cover.\n\nThey have agreed to give you their graph and you need to find two disjoint subsets of its vertices *A* and *B*, such that both *A* and *B* are vertex cover or claim it's impossible. Each vertex should be given to no more than one of the friends (or you can even keep it for yourself).",
"input": "",
"output": "```python\nnVertices, nEdges = map(int, input().split())\r\ng = [[] for _ in range(nVertices)]\r\nedges = []\r\nfor _ in range(nEdges):\r\n u, v = map(lambda x: int(x) - 1, input().split())\r\n g[u].append(v)\r\n g[v].append(u)\r\n edges.append((u, v))\r\n\r\ndef dfs(v, m):\r\n mark[v] = m\r\n for to in g[v]:\r\n if not mark[to]:\r\n dfs(to, m ^ 1)\r\n\r\nmark = [None] * nVertices\r\nfor v in range(nVertices):\r\n if not mark[v]:\r\n dfs(v, 0)\r\ncnt1 = cnt2 = 0\r\nfor u, v in edges:\r\n cnt1 += mark[u] == 0 or mark[v] == 0\r\n cnt2 += mark[u] == 1 or mark[v] == 1\r\nif cnt1 != nEdges or cnt2 != nEdges:\r\n print(-1)\r\nelse:\r\n ret = []\r\n ret.append('%d\\n' % mark.count(0))\r\n vertices = []\r\n for v in range(nVertices):\r\n if mark[v] == 0:\r\n vertices.append(v + 1)\r\n ret.append('%s\\n' % ' '.join(map(str, vertices)))\r\n ret.append('%d\\n' % mark.count(1))\r\n vertices = []\r\n for v in range(nVertices):\r\n if mark[v] == 1:\r\n vertices.append(v + 1)\r\n ret.append('%s\\n' % ' '.join(map(str, vertices)))\r\n print(''.join(ret))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.\n\nGiven two strings *a* and *b*, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other.\n\nA subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings \"ac\", \"bc\", \"abc\" and \"a\" are subsequences of string \"abc\" while strings \"abbc\" and \"acb\" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.",
"input": "",
"output": "```python\na=input()\r\nb=input()\r\nif any(i not in iter(a) for i in b): print(max(len(b),len(a)))\r\nelse: print(-1)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nBy 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.\n\nFor example, the general considers the sequence of heights (4, 3, 4, 2, 1, 1) correct and the sequence (4, 3, 1, 2, 2) wrong.\n\nWithin 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.",
"input": "",
"output": "```python\nn = int(input())\r\nheights = list(map(int, input().split()))\r\n\r\nposition_max = -1\r\nposition_min = -1\r\n\r\n# Find the positions of maximum and minimum heights\r\nfor i in range(n):\r\n if heights[i] == max(heights):\r\n position_max = i\r\n if heights[i] == min(heights):\r\n position_min = i\r\n\r\n# Calculate the minimum number of swaps needed\r\nif position_max > position_min:\r\n min_swaps = position_max + (n - 1 - position_min) - 1\r\nelse:\r\n min_swaps = position_max + (n - 1 - position_min)\r\n\r\nprint(min_swaps)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Little Petya often travels to his grandmother in the countryside. The grandmother has a large garden, which can be represented as a rectangle 1<=×<=*n* in size, when viewed from above. This rectangle is divided into *n* equal square sections. The garden is very unusual as each of the square sections possesses its own fixed height and due to the newest irrigation system we can create artificial rain above each section.\n\nCreating artificial rain is an expensive operation. That's why we limit ourselves to creating the artificial rain only above one section. At that, the water from each watered section will flow into its neighbouring sections if their height does not exceed the height of the section. That is, for example, the garden can be represented by a 1<=×<=5 rectangle, where the section heights are equal to 4, 2, 3, 3, 2. Then if we create an artificial rain over any of the sections with the height of 3, the water will flow over all the sections, except the ones with the height of 4. See the illustration of this example at the picture:\n\nAs Petya is keen on programming, he decided to find such a section that if we create artificial rain above it, the number of watered sections will be maximal. Help him.",
"input": "",
"output": "```python\n\r\n\r\nn = int(input())\r\narr = list(map(int, input().split()))\r\n\r\n\r\ndef rain(arr,n, index):\r\n counter = 1\r\n lindex = index - 1\r\n rindex = index + 1 \r\n currentL = arr[index]\r\n currentR = arr[index]\r\n while(lindex >= 0):\r\n \r\n if arr[lindex] <= currentL:\r\n counter += 1\r\n currentL = arr[lindex]\r\n lindex -= 1\r\n \r\n else:\r\n break\r\n \r\n \r\n while(rindex < n):\r\n if arr[rindex] <= currentR:\r\n counter += 1\r\n currentR = arr[rindex]\r\n rindex += 1 \r\n \r\n\r\n else:\r\n break\r\n\r\n \r\n return counter \r\n \r\n \r\nmax_rain = rain(arr,n, 0)\r\nfor i in range(1,n):\r\n r = rain(arr,n, i) \r\n if r > max_rain:\r\n max_rain = r\r\n \r\nprint(max_rain)\r\n \r\n \r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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*.\n\nUnfortunately, he doesn't know any such table. Your task is to help him to find at least one of them.",
"input": "",
"output": "```python\na,b=input().split()\r\na=int(a)\r\nb=int(b)\r\nl=[]\r\nfor i in range(a):\r\n if i!=0:\r\n print(*l)\r\n l=[]\r\n for j in range(a):\r\n if j==0:l.append(b)\r\n else:l.append(0)\r\nprint(*l)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Two polar bears Menshykov and Uslada from the St.Petersburg zoo and elephant Horace from the Kiev zoo got six sticks to play with and assess the animals' creativity. Menshykov, Uslada and Horace decided to make either an elephant or a bear from those sticks. They can make an animal from sticks in the following way: \n - Four sticks represent the animal's legs, these sticks should have the same length. - Two remaining sticks represent the animal's head and body. The bear's head stick must be shorter than the body stick. The elephant, however, has a long trunk, so his head stick must be as long as the body stick. Note that there are no limits on the relations between the leg sticks and the head and body sticks. \nYour task is to find out which animal can be made from the given stick set. The zoo keeper wants the sticks back after the game, so they must never be broken, even bears understand it.",
"input": "",
"output": "```python\nssticks = list()\r\nssticks[:] = map(int,input().split(' '))\r\nssticks.sort()\r\nssdict = dict()\r\nfor i in ssticks:\r\n ssdict[i] = 0\r\nfor i in ssticks:\r\n ssdict[i] += 1\r\nssticks = []\r\nfor k in ssdict:\r\n ssticks.append(ssdict[k])\r\n \r\nif ssticks.count(4) > 0:\r\n if ssticks.count(2) > 0:\r\n print('Elephant')\r\n else:\r\n print('Bear')\r\nelse: print('Alien')\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vasya has a sequence of cubes and exactly one integer is written on each cube. Vasya exhibited all his cubes in a row. So the sequence of numbers written on the cubes in the order from the left to the right equals to *a*1,<=*a*2,<=...,<=*a**n*.\n\nWhile Vasya was walking, his little brother Stepan played with Vasya's cubes and changed their order, so now the sequence of numbers written on the cubes became equal to *b*1,<=*b*2,<=...,<=*b**n*. \n\nStepan said that he swapped only cubes which where on the positions between *l* and *r*, inclusive, and did not remove or add any other cubes (i. e. he said that he reordered cubes between positions *l* and *r*, inclusive, in some way).\n\nYour task is to determine if it is possible that Stepan said the truth, or it is guaranteed that Stepan deceived his brother.",
"input": "",
"output": "```python\nimport sys\r\nn,l,r=map(int,input().split())\r\na=list(map(int,input().split()))\r\nb=list(map(int,input().split()))\r\nfor il in range(0,l):\r\n for ir in range(r,n):\r\n if a[il]==b[il] and a[ir]==b[ir]:\r\n print('TRUTH')\r\n exit()\r\n else:\r\n print('LIE')\r\n exit()\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Pashmak decided to give Parmida a pair of flowers from the garden. There are *n* flowers in the garden and the *i*-th of them has a beauty number *b**i*. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty difference is maximal possible!\n\nYour task is to write a program which calculates two things:\n 1. The maximum beauty difference of flowers that Pashmak can give to Parmida. 1. The number of ways that Pashmak can pick the flowers. Two ways are considered different if and only if there is at least one flower that is chosen in the first way and not chosen in the second way.",
"input": "",
"output": "```python\nfrom collections import Counter\r\n\r\nn=int(input())\r\nb=list(map(int,input().split()))\r\ncnt=Counter(b)\r\nlst=list(cnt)\r\nl,r=lst[0],lst[-1]\r\nprint(cnt[r]-cnt[l],cnt[r]*cnt[l])\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.",
"input": "",
"output": "```python\nn=int(input())\r\na=list(map(int,input().split(' ')))\r\nfor i in range(n):\r\n if a[0]%2!=a[1]%2 and a[0]%2!=a[2]%2:\r\n print('0')\r\n break\r\n if a[i]%2!=a[i+1]%2 and a[i]%2!=a[i-1]%2:\r\n print(i+1)\r\n break\r\n\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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! \n\nMore 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*<=><=*c*, then everything on the screen disappears and after that the word you have typed appears on the screen.\n\nFor 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.\n\nYou're given the times when ZS the Coder typed the words. Determine how many words remain on the screen after he finished typing everything.",
"input": "",
"output": "```python\nq=[int(a)for a in input().split()]\r\nw=[int(a)for a in input().split()]\r\ne=1\r\nif q[0]>1:\r\n for r in range(1,len(w)):\r\n if w[r]-w[r-1]>q[1]:\r\n e=1\r\n else:\r\n e+=1\r\n print(e)\r\nelse:\r\n print(1)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Kolya has a string *s* of length *n* consisting of lowercase and uppercase Latin letters and digits.\n\nHe wants to rearrange the symbols in *s* and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, such as madam or racecar.\n\nYour task is to help Kolya and determine the minimum number of palindromes of equal lengths to cut *s* into, if it is allowed to rearrange letters in *s* before cuttings.",
"input": "",
"output": "```python\nmp,a,p={},[],[]\r\nn=int(input())\r\nfor i in input():\r\n if i in mp:mp[i]+=1\r\n else:mp[i]=1\r\nodd=0\r\nfor i in mp:\r\n if mp[i]&1:\r\n a.append(i)\r\n mp[i]-=1\r\n odd+=1\r\n if mp[i]:\r\n p.append(i)\r\nm=max(1,odd)\r\nfor i in range(m,n+1):\r\n if not n%i:\r\n d=n//i\r\n if odd and not d&1:continue\r\n print(i)\r\n for K in range(i-m):\r\n a.append(p[-1])\r\n if mp[p[-1]]>1:mp[p[-1]]-=1\r\n else:p.pop()\r\n for k in range(i):\r\n s=''\r\n for j in range(d//2):\r\n s+=p[-1]\r\n mp[p[-1]]-=2\r\n if not mp[p[-1]]:p.pop()\r\n if odd:print(s+a.pop()+s[::-1],end=' ')\r\n else:print(s+s[::-1],end=' ')\r\n exit()\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer.\n\nAt 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).\n\nIf 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.\n\nKay 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.",
"input": "",
"output": "```python\nn,x=list(map(int, input().split()))\r\ndistress=0\r\nfor i in range(n):\r\n query=input().split()\r\n if query[0]=='+':\r\n x+=int(query[1])\r\n else:\r\n if x>=int(query[1]):\r\n x-=int(query[1])\r\n else:\r\n distress+=1\r\nprint(x, distress)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A simple recommendation system would recommend a user things liked by a certain number of their friends. In this problem you will implement part of such a system.\n\nYou are given user's friends' opinions about a list of items. You are also given a threshold *T* — the minimal number of \"likes\" necessary for an item to be recommended to the user.\n\nOutput the number of items in the list liked by at least *T* of user's friends.",
"input": "",
"output": "```python\n\r\nn, m, t = map(int,raw_input().strip().split())\r\nx = []\r\nfor i in xrange(n):\r\n x.append(raw_input().strip())\r\nprint sum([sum([x[i][j] == 'Y' for i in xrange(n)]) >= t for j in xrange(m)])\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Pig is visiting a friend.\n\nPig's house is located at point 0, and his friend's house is located at point *m* on an axis.\n\nPig can use teleports to move along the axis.\n\nTo 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.\n\nFormally, 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.\n\nDetermine if Pig can visit the friend using teleports only, or he should use his car.",
"input": "",
"output": "```python\n\r\n\r\nn, m = map(int, input().split())\r\na = []\r\n\r\nfor i in range(m):\r\n\ta.append(False)\r\na[0] = True\r\n\r\nfor _ in range(n):\r\n\tx, y = map(int, input().split())\r\n\tfor i in range(x,y):\r\n\t\ta[i] = True\r\n\r\n\r\nif False in a:\r\n\tprint(\"NO\")\r\nelse:\r\n\tprint(\"YES\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Nian is a monster which lives deep in the oceans. Once a year, it shows up on the land, devouring livestock and even people. In order to keep the monster away, people fill their villages with red colour, light, and cracking noise, all of which frighten the monster out of coming.\n\nLittle Tommy has *n* lanterns and Big Banban has *m* lanterns. Tommy's lanterns have brightness *a*1,<=*a*2,<=...,<=*a**n*, and Banban's have brightness *b*1,<=*b*2,<=...,<=*b**m* respectively.\n\nTommy intends to hide one of his lanterns, then Banban picks one of Tommy's non-hidden lanterns and one of his own lanterns to form a pair. The pair's brightness will be the product of the brightness of two lanterns.\n\nTommy wants to make the product as small as possible, while Banban tries to make it as large as possible.\n\nYou are asked to find the brightness of the chosen pair if both of them choose optimally.",
"input": "",
"output": "```python\ni,j=map(int,input().split())\r\nli=list(map(int,input().split()))\r\nli.sort()\r\nlj=list(map(int,input().split()))\r\nlj.sort()\r\nprint(li[i-2]*lj[j-1])\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Once Bob needed to find the second order statistics of a sequence of integer numbers. Lets choose each number from the sequence exactly once and sort them. The value on the second position is the second order statistics of the given sequence. In other words it is the smallest element strictly greater than the minimum. Help Bob solve this problem.",
"input": "",
"output": "```python\n#rOkY\r\n#FuCk\r\n\r\n################################## kOpAl #####################################\r\n\r\nt=int(input())\r\nl=list(map(int,input().split()))\r\nl.sort()\r\nx=list(dict.fromkeys(l))\r\n\r\nif(len(x)>1):\r\n print(x[1])\r\nelse:\r\n print('NO')\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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). \n\nYour task is to determine by the given *a*, *b* and *n* who wins the game.",
"input": "",
"output": "```python\na, b, n = map(int, input().split())\r\na1 = a\r\nb1 = b\r\nn1 = n\r\ncount = 0\r\nc = 0\r\nwhile c != n:\r\n d = n1 - c\r\n while d > 0:\r\n a, d = d, a % d\r\n c += a\r\n a = a1\r\n b = b1\r\n a, b = b, a\r\n count += 1\r\nif count % 2 == 0:\r\n print(1)\r\nelse:\r\n print(0)\r\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point *x*(*x*<=><=0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order to get to his friend's house.",
"input": "",
"output": "```python\nimport sys\r\ndef I(): return int(sys.stdin.readline().rstrip())\r\ndef LI(): return list(map(int, sys.stdin.readline().rstrip().split()))\r\ndef MI(): return map(int, sys.stdin.readline().rstrip().split())\r\ndef SI(): return sys.stdin.readline().rstrip()\r\n\r\n\r\ndef main():\r\n n = I()\r\n count = 0\r\n while n > 0:\r\n if n > 5:\r\n count += 1\r\n n -= 5\r\n else:\r\n count += 1\r\n n -= n\r\n print(count)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Petya has got 2*n* cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2*n*. We'll denote the number that is written on a card with number *i*, as *a**i*. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that.",
"input": "",
"output": "```python\nimport re\r\nimport sys\r\nexit=sys.exit\r\nfrom bisect import bisect_left as bsl,bisect_right as bsr\r\nfrom collections import Counter,defaultdict as ddict,deque\r\nfrom functools import lru_cache\r\ncache=lru_cache(None)\r\nfrom heapq import *\r\nfrom itertools import *\r\nfrom math import inf\r\nfrom pprint import pprint as pp\r\nenum=enumerate\r\nri=lambda:int(rln())\r\nris=lambda:list(map(int,rfs()))\r\nrln=sys.stdin.readline\r\nrl=lambda:rln().rstrip('\\n')\r\nrfs=lambda:rln().split()\r\ncat=''.join\r\ncatn='\\n'.join\r\nmod=1000000007\r\nd4=[(0,-1),(1,0),(0,1),(-1,0)]\r\nd8=[(-1,-1),(0,-1),(1,-1),(-1,0),(1,0),(-1,1),(0,1),(1,1)]\r\n########################################################################\r\n\r\nn=ri()\r\na=ris()\r\nd=ddict(set)\r\nfor i in range(2*n):\r\n d[a[i]].add(i)\r\nans=[]\r\nfor x in d:\r\n if len(d[x])%2:\r\n print(-1)\r\n exit()\r\n while d[x]:\r\n j=d[x].pop()\r\n i=d[x].pop()\r\n ans.append((i,j))\r\nfor i,j in ans:\r\n print(1+i,1+j)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A median in an array with the length of *n* is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2,<=6,<=1,<=2,<=3) is the number 2, and a median of array (0,<=96,<=17,<=23) — the number 17.\n\nWe define an expression as the integer part of dividing number *a* by number *b*.\n\nOne day Vasya showed Petya an array consisting of *n* integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals *x*. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to *x*.\n\nPetya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. \n\nWhile Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.",
"input": "",
"output": "```python\n\"\"\"\nModule which implements the search of the minimum number of elements to be inserted\nin order to make the given number the median of this array.\n\"\"\"\ndef min_num(positions: list, length: int, count: int):\n \"\"\"\n Return the minimum number of elements.\n \"\"\"\n result = count\n if ((length+1) // 2 - 1) in positions:\n return result\n if positions[-1] < ((length+1) // 2 - 1):\n while positions[-1] != ((length+1) // 2 - 1):\n result += 1\n positions[-1] += 1\n length += 1\n if positions[0] > ((length+1) // 2 - 1):\n while positions[0] != ((length+1) // 2 - 1):\n result += 1\n length += 1\n return result\n\nif __name__ == \"__main__\":\n settings = [int(x) for x in input().split(\" \")]\n array = [int(x) for x in input().split(\" \")]\n count = 0\n if settings[1] not in array:\n array.append(settings[1])\n count += 1\n settings[0] += 1\n array.sort()\n positions = []\n for i in range(len(array)):\n if array[i] == settings[1]:\n positions.append(i)\n print(min_num(positions, settings[0], count))\n\t \t\t \t \t\t\t\t \t \t\t\t \t\t\t \t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Kefa decided to make some money doing business on the Internet for exactly *n* days. He knows that on the *i*-th day (1<=≤<=*i*<=≤<=*n*) he makes *a**i* money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence *a**i*. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.\n\nHelp Kefa cope with this task!",
"input": "",
"output": "```python\nn=int(input())\r\n\r\nsub=[]\r\nseq=list (map (int , input().split()))\r\n\r\ns=1\r\nfor i in range(1,len(seq)):\r\n if seq[i]>=seq[i-1]:\r\n s=s+1\r\n else:\r\n sub.append(s)\r\n s=1\r\n sub.append(s)\r\nprint(max(sub))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Recently Adaltik discovered japanese crosswords. Japanese crossword is a picture, represented as a table sized *a*<=×<=*b* squares, and each square is colored white or black. There are integers to the left of the rows and to the top of the columns, encrypting the corresponding row or column. The number of integers represents how many groups of black squares there are in corresponding row or column, and the integers themselves represents the number of consecutive black squares in corresponding group (you can find more detailed explanation in Wikipedia [https://en.wikipedia.org/wiki/Japanese_crossword](https://en.wikipedia.org/wiki/Japanese_crossword)).\n\nAdaltik decided that the general case of japanese crossword is too complicated and drew a row consisting of *n* squares (e.g. japanese crossword sized 1<=×<=*n*), which he wants to encrypt in the same way as in japanese crossword.\n\nHelp Adaltik find the numbers encrypting the row he drew.",
"input": "",
"output": "```python\ninput()\r\nx = input().split('W')\r\ny= [len(i) for i in x if len(i)>0]\r\nprint(len(y))\r\nprint(*y)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You have an array *a* consisting of *n* integers. Each integer from 1 to *n* appears exactly once in this array.\n\nFor some indices *i* (1<=≤<=*i*<=≤<=*n*<=-<=1) it is possible to swap *i*-th element with (*i*<=+<=1)-th, for other indices it is not possible. You may perform any number of swapping operations any order. There is no limit on the number of times you swap *i*-th element with (*i*<=+<=1)-th (if the position is not forbidden).\n\nCan you make this array sorted in ascending order performing some sequence of swapping operations?",
"input": "",
"output": "```python\nR = lambda:map(int,input().split())\r\nn = int(input())\r\nC = list(R())\r\ns = input()\r\ntt = 0\r\nfor i in range(n - 1):\r\n\tif C[i] > C[i + 1]:\r\n\t\tif s[i] == '0':\r\n\t\t\tprint(\"no\")\r\n\t\t\ttt = 1\r\n\t\t\tbreak\r\n\t\telse: \r\n\t\t\tt = i\r\n\t\t\twhile t >= 0 and C[t] > C[t + 1] and s[t] == '1':\r\n\t\t\t\tC[t + 1], C[t] = C[t], C[t + 1]\r\n\t\t\t\tt -= 1\r\n\t\t\tif C[t] > C[t + 1]:\r\n\t\t\t\tprint(\"no\")\r\n\t\t\t\ttt = 1\r\n\t\t\t\tbreak\r\nf = [i for i in range(1,n + 1)]\r\nif tt == 0:\r\n if f == C:\r\n print(\"yes\")\r\n else:\r\n print(\"no\")\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.",
"input": "",
"output": "```python\nn1=(input(\"Enter a word : \"))\nu=0\nl=0\nfor i in n1:\n if 65<=ord(i)<=90:\n u+=1\n else:\n l+=1\nif u>l:\n print(n1.upper())\nelse:\n print(n1.lower()) \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Recently, Vladimir got bad mark in algebra again. To avoid such unpleasant events in future he decided to train his arithmetic skills. He wrote four integer numbers *a*, *b*, *c*, *d* on the blackboard. During each of the next three minutes he took two numbers from the blackboard (not necessarily adjacent) and replaced them with their sum or their product. In the end he got one number. Unfortunately, due to the awful memory he forgot that number, but he remembers four original numbers, sequence of the operations and his surprise because of the very small result. Help Vladimir remember the forgotten number: find the smallest number that can be obtained from the original numbers by the given sequence of operations.",
"input": "",
"output": "```python\nimport itertools\r\nimport math\r\nimport time\r\nfrom builtins import input, range\r\nfrom math import gcd as gcd\r\nimport sys\r\nimport queue\r\nimport itertools\r\nimport collections\r\nfrom heapq import heappop, heappush\r\nimport random\r\nimport os\r\nfrom random import randint\r\nimport decimal\r\n\r\n# from sys import stdin, stdout\r\n# input, print = stdin.readline, stdout.write\r\n\r\ndecimal.getcontext().prec = 18\r\n\r\n\r\ndef solve():\r\n def rec(op, arr):\r\n mn = 1 << 60\r\n for f in range(len(arr)):\r\n for s in range(f + 1, len(arr)):\r\n if len(arr) == 2:\r\n if op == \"+\":\r\n return arr[f] + arr[s]\r\n else:\r\n return arr[f] * arr[s]\r\n\r\n new_arr = arr * 1\r\n new_arr.remove(arr[f])\r\n new_arr.remove(arr[s])\r\n\r\n if op == \"+\":\r\n new_arr.append(arr[f] + arr[s])\r\n else:\r\n new_arr.append(arr[f] * arr[s])\r\n\r\n mn = min(mn, rec(ops[4 - len(arr) + 1], new_arr))\r\n\r\n return mn\r\n\r\n a = list(map(int, input().split()))\r\n ops = list(map(str, input().split()))\r\n\r\n print(rec(ops[0], a))\r\n\r\n\r\nif __name__ == '__main__':\r\n multi_test = 0\r\n\r\n if multi_test == 1:\r\n t = int(sys.stdin.readline())\r\n for _ in range(t):\r\n solve()\r\n else:\r\n solve()\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "DZY loves chemistry, and he enjoys mixing chemicals.\n\nDZY has *n* chemicals, and *m* pairs of them will react. He wants to pour these chemicals into a test tube, and he needs to pour them in one by one, in any order. \n\nLet's consider the danger of a test tube. Danger of an empty test tube is 1. And every time when DZY pours a chemical, if there are already one or more chemicals in the test tube that can react with it, the danger of the test tube will be multiplied by 2. Otherwise the danger remains as it is.\n\nFind the maximum possible danger after pouring all the chemicals one by one in optimal order.",
"input": "",
"output": "```python\ndef get(Array, Item):\r\n if Array[Item] == Item: return Item\r\n Array[Item] = get(Array, Array[Item]);\r\n return Array[Item]\r\n\r\nn ,m = map(int , input().split(' '))\r\nchem = [i for i in range(1+n)]\r\nans = 0\r\nrank = [1]*(n+1)\r\nfor _ in range(m):\r\n a, b = map(int , input().split(' '))\r\n chem[get(chem , a)] = get(chem , b)\r\nrec = [0]*(n+1)\r\nfor x in chem:\r\n rec[get(chem ,x)]+= 1\r\nfor x in rec:\r\n if x > 1:\r\n ans+=(x-1)\r\nprint(2**ans)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vasya has a beautiful garden where wonderful fruit trees grow and yield fantastic harvest every year. But lately thieves started to sneak into the garden at nights and steal the fruit too often. Vasya can’t spend the nights in the garden and guard the fruit because there’s no house in the garden! Vasya had been saving in for some time and finally he decided to build the house. The rest is simple: he should choose in which part of the garden to build the house. In the evening he sat at his table and drew the garden’s plan. On the plan the garden is represented as a rectangular checkered field *n*<=×<=*m* in size divided into squares whose side length is 1. In some squares Vasya marked the trees growing there (one shouldn’t plant the trees too close to each other that’s why one square contains no more than one tree). Vasya wants to find a rectangular land lot *a*<=×<=*b* squares in size to build a house on, at that the land lot border should go along the lines of the grid that separates the squares. All the trees that grow on the building lot will have to be chopped off. Vasya loves his garden very much, so help him choose the building land lot location so that the number of chopped trees would be as little as possible.",
"input": "",
"output": "```python\ndef calc_trees(cont: list, start_row: int, start_col: int, area_h, area_w) -> int:\r\n trees = 0\r\n for i in range(start_row, start_row + area_h):\r\n for j in range(start_col, start_col + area_w):\r\n trees += cont[i][j]\r\n\r\n\r\nn, m = [int(item) for item in input().split(' ')]\r\ncont = []\r\nfor i in range(n):\r\n # subArr = [int(item) for item in input().split(' ')]\r\n # cont.append(subArr)\r\n cont.append([int(item) for item in input().split(' ')])\r\n\r\na, b = [int(item) for item in input().split(' ')]\r\n\r\n# print(f'cont => {cont}')\r\nans = n * m\r\nfor i in range(n):\r\n for j in range(m):\r\n if i <= n - a and j <= m - b:\r\n temp = calc_trees(cont, i, j, a, b)\r\n if ans > temp:\r\n ans = temp\r\n if i <= n - b and j <= m - a:\r\n temp = calc_trees(cont, i, j, b, a)\r\n if ans > temp:\r\n ans = temp\r\nprint(ans)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A tennis tournament with *n* participants is running. The participants are playing by an olympic system, so the winners move on and the losers drop out.\n\nThe tournament takes place in the following way (below, *m* is the number of the participants of the current round):\n - let *k* be the maximal power of the number 2 such that *k*<=≤<=*m*, - *k* participants compete in the current round and a half of them passes to the next round, the other *m*<=-<=*k* participants pass to the next round directly, - when only one participant remains, the tournament finishes. \nEach match requires *b* bottles of water for each participant and one bottle for the judge. Besides *p* towels are given to each participant for the whole tournament.\n\nFind the number of bottles and towels needed for the tournament.\n\nNote that it's a tennis tournament so in each match two participants compete (one of them will win and the other will lose).",
"input": "",
"output": "```python\nn,b,p = [int(c) for c in input().split()]\n\n\nprint((n-1)*(2*b+1), n*p)\n\n\t \t\t\t\t\t \t\t \t \t\t \t \t \t\t \t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Hag is a very talented person. He has always had an artist inside him but his father forced him to study mechanical engineering.\n\nYesterday he spent all of his time cutting a giant piece of wood trying to make it look like a goose. Anyway, his dad found out that he was doing arts rather than studying mechanics and other boring subjects. He confronted Hag with the fact that he is a spoiled son that does not care about his future, and if he continues to do arts he will cut his 25 Lira monthly allowance.\n\nHag is trying to prove to his dad that the wooden piece is a project for mechanics subject. He also told his dad that the wooden piece is a strictly convex polygon with $n$ vertices.\n\nHag brought two pins and pinned the polygon with them in the $1$-st and $2$-nd vertices to the wall. His dad has $q$ queries to Hag of two types. \n - $1$ $f$ $t$: pull a pin from the vertex $f$, wait for the wooden polygon to rotate under the gravity force (if it will rotate) and stabilize. And then put the pin in vertex $t$. - $2$ $v$: answer what are the coordinates of the vertex $v$. \nPlease help Hag to answer his father's queries.\n\nYou can assume that the wood that forms the polygon has uniform density and the polygon has a positive thickness, same in all points. After every query of the 1-st type Hag's dad tries to move the polygon a bit and watches it stabilize again.",
"input": "",
"output": "```python\n#!/usr/bin/env python3\n\n\nfrom math import hypot\n\n[n, q] = map(int, input().strip().split())\nxys = [tuple(map(int, input().strip().split())) for _ in range(n)]\nqis = [tuple(map(int, input().strip().split())) for _ in range(q)]\n\ndxys = [(xys[(i + 1) % n][0] - xys[i][0], xys[(i + 1) % n][1] - xys[i][1]) for i in range(n)]\n\nS = 3 * sum((x*dy - y*dx) for (x, y), (dx, dy) in zip(xys, dxys))\nSx = sum((dx + 2*x) * (x*dy - y*dx) for (x, y), (dx, dy) in zip(xys, dxys))\nSy = sum((dy + 2*y) * (x*dy - y*dx) for (x, y), (dx, dy) in zip(xys, dxys))\n#Sy = sum((2*dx*dy + 3*x*dx + 3*x*dy + 6*x*y)*dy for (x, y), (dx, dy) in zip(xys, dxys))\nfor p in [2, 3]:\n\twhile S % p == Sx % p == Sy % p == 0:\n\t\tS //= p\n\t\tSx //= p\n\t\tSy //= p\n\nxyms = [(S*x - Sx, S*y - Sy) for x, y in xys]\nhs = [hypot(x, y) for x, y in xyms]\n\ndef to_coord(x, y):\n\treturn (x + Sx) / S, (y + Sy) / S\n\nhangs = (0, 1)\nhang_on = None\ncx, cy = 0.0, 0.0\n\n# hang on u\ndef get_v(v):\n\tif hang_on is None:\n\t\treturn xyms[v]\n\telse:\n\t\tux, uy = xyms[hang_on]\n\t\tvx, vy = xyms[v]\n\t\th = hs[hang_on]\n\t\treturn ((uy * vx - ux * vy) / h, (ux * vx + uy * vy) / h)\n\n#def ss(v1, v2):\n#\treturn tuple(vi + vj for vi, vj in zip(v1, v2))\n\n#def disp():\n#\tprint ('hangs on', hang_on, 'of', hangs)\n#\tprint ('center', to_coord(cx, cy))\n#\tprint ({i: to_coord(*ss(get_v(i), (cx, cy))) for i in range(n)})\n\t\n#disp()\nfor qi in qis:\n\tif qi[0] == 1:\n\t\t_, f, t = qi # 1-indexation\n\t\ts = hangs[1 - hangs.index(f - 1)]\n\t\tdx, dy = get_v(s)\n\t\tcx += dx\n\t\tcy += dy - hs[s]\n\t\thang_on = s\n\t\thangs = (s, t - 1)\n#\t\tprint ('{} --> {}'.format(f - 1, t - 1))\n#\t\tdisp()\n\telse:\n\t\t_, v = qi # 1-indexation\n\t\tdx, dy = get_v(v - 1)\n\t\tprint (*to_coord(cx + dx, cy + dy))\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "We call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, \"aabba\" is good, because after the merging step it will become \"aba\".\n\nGiven a string, you have to find two values:\n 1. the number of good substrings of even length; 1. the number of good substrings of odd length.",
"input": "",
"output": "```python\ns=input()\r\nans_odd=0\r\nans_even=0\r\ncnt_odd=[0,0]\r\ncnt_even=[0,0]\r\nfor i in range(len(s)):\r\n id=ord(s[i])-ord(\"a\")\r\n ans_odd+=1\r\n if i%2==0:\r\n ans_even+=cnt_odd[id]\r\n ans_odd+=cnt_even[id]\r\n cnt_even[id]+=1\r\n else:\r\n ans_odd+=cnt_odd[id]\r\n ans_even+=cnt_even[id]\r\n cnt_odd[id]+=1\r\nprint(ans_even,ans_odd)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "One day the Codeforces round author sat exams. He had *n* exams and he needed to get an integer from 2 to 5 for each exam. He will have to re-sit each failed exam, i.e. the exam that gets mark 2. \n\nThe author would need to spend too much time and effort to make the sum of his marks strictly more than *k*. That could have spoilt the Codeforces round. On the other hand, if the sum of his marks is strictly less than *k*, the author's mum won't be pleased at all. \n\nThe Codeforces authors are very smart and they always get the mark they choose themselves. Also, the Codeforces authors just hate re-sitting exams. \n\nHelp the author and find the minimum number of exams he will have to re-sit if he passes the exams in the way that makes the sum of marks for all *n* exams equal exactly *k*.",
"input": "",
"output": "```python\nn, k = map(int, input().split())\n\nresult = 51\n\n\ndef dfs(remain_exams: int, slate: list):\n global result\n if remain_exams == 0:\n if sum(slate) == k:\n num_2 = len([score for score in slate if score == 2])\n if num_2 < result:\n result = num_2\n else:\n for i in range(2, 6):\n slate.append(i)\n dfs(remain_exams - 1, slate)\n slate.pop()\n\n\ndfs(n, [])\nprint(result)\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Your friend has *n* cards.\n\nYou know that each card has a lowercase English letter on one side and a digit on the other.\n\nCurrently, your friend has laid out the cards on a table so only one side of each card is visible.\n\nYou would like to know if the following statement is true for cards that your friend owns: \"If a card has a vowel on one side, then it has an even digit on the other side.\" More specifically, a vowel is one of 'a', 'e', 'i', 'o' or 'u', and even digit is one of '0', '2', '4', '6' or '8'.\n\nFor example, if a card has 'a' on one side, and '6' on the other side, then this statement is true for it. Also, the statement is true, for example, for a card with 'b' and '4', and for a card with 'b' and '3' (since the letter is not a vowel). The statement is false, for example, for card with 'e' and '5'. You are interested if the statement is true for all cards. In particular, if no card has a vowel, the statement is true.\n\nTo determine this, you can flip over some cards to reveal the other side. You would like to know what is the minimum number of cards you need to flip in the worst case in order to verify that the statement is true.",
"input": "",
"output": "```python\nneeds_flipping = ['a', 'e', 'i', 'o', 'u', '1', '3', '5', '7', '9']\r\n \r\ndef flip(s):\r\n flip_count = 0\r\n for letter in s:\r\n if letter in needs_flipping:\r\n flip_count += 1\r\n return flip_count\r\n \r\nprint(flip(input()))\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Valera had two bags of potatoes, the first of these bags contains *x* (*x*<=≥<=1) potatoes, and the second — *y* (*y*<=≥<=1) potatoes. Valera — very scattered boy, so the first bag of potatoes (it contains *x* potatoes) Valera lost. Valera remembers that the total amount of potatoes (*x*<=+<=*y*) in the two bags, firstly, was not gerater than *n*, and, secondly, was divisible by *k*.\n\nHelp Valera to determine how many potatoes could be in the first bag. Print all such possible numbers in ascending order.",
"input": "",
"output": "```python\ndef solver(y, k, n):\r\n x = n - y\r\n\r\n ans = []\r\n for i in range(0,x):\r\n if (y+i+1) % k == 0:\r\n ans.append(str(i+1))\r\n\r\n return '-1' if ans == [] else ' '.join(ans)\r\n \r\n\r\nif __name__ == \"__main__\":\r\n y, k, n = map(int, input().split(\" \"))\r\n print(solver(y, k, n))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Natasha is planning an expedition to Mars for $n$ people. One of the important tasks is to provide food for each participant.\n\nThe warehouse has $m$ daily food packages. Each package has some food type $a_i$.\n\nEach participant must eat exactly one food package each day. Due to extreme loads, each participant must eat the same food type throughout the expedition. Different participants may eat different (or the same) types of food.\n\nFormally, for each participant $j$ Natasha should select his food type $b_j$ and each day $j$-th participant will eat one food package of type $b_j$. The values $b_j$ for different participants may be different.\n\nWhat is the maximum possible number of days the expedition can last, following the requirements above?",
"input": "",
"output": "```python\n\r\ndef get_longest(left_num, cur_depth, max_depth):\r\n if(cur_depth == max_depth):\r\n if left_num == 0:\r\n return 9999999\r\n else:\r\n return int(food_dict[sorted_food_key[max_depth - 1]] / left_num)\r\n else:\r\n cur_long = 0\r\n for i in range(0, left_num + 1):\r\n if i == 0:\r\n this_food_alive = 9999999\r\n else:\r\n this_food_alive = int(food_dict[sorted_food_key[cur_depth - 1]] / i)\r\n next_food_alive = get_longest(left_num - i, cur_depth + 1, max_depth)\r\n min_val = min(next_food_alive, this_food_alive)\r\n cur_long = max(min_val, cur_long)\r\n return cur_long\r\n \r\n \r\n\r\n\r\n\r\n\r\ninput_list = list(map(int, input().split()))\r\nfoods = list(map(int, input().split()))\r\n\r\nparticip_count = input_list[0]\r\npackage_count = input_list[1]\r\n\r\nif package_count < particip_count:\r\n print(0)\r\nelse:\r\n food_dict = dict()\r\n for food in foods:\r\n if food in food_dict:\r\n food_dict[food] = food_dict[food] + 1\r\n else:\r\n food_dict[food] = 1\r\n\r\n sorted_food_key = sorted(food_dict, key=lambda food: food_dict[food], reverse=True)\r\n\r\n if particip_count < len(sorted_food_key):\r\n sorted_food_key = sorted_food_key[:particip_count]\r\n elif particip_count > len(sorted_food_key):\r\n key_offset = 1\r\n while particip_count > len(food_dict):\r\n food_dict[999 + key_offset] = 0\r\n key_offset = key_offset + 1\r\n sorted_food_key = sorted(food_dict, key=lambda food: food_dict[food], reverse=True)\r\n else:\r\n key_offset = 1\r\n\r\n print(get_longest(particip_count, 1, particip_count));\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Our old friend Alexey has finally entered the University of City N — the Berland capital. Alexey expected his father to get him a place to live in but his father said it was high time for Alexey to practice some financial independence. So, Alexey is living in a dorm. \n\nThe dorm has exactly one straight dryer — a 100 centimeter long rope to hang clothes on. The dryer has got a coordinate system installed: the leftmost end of the dryer has coordinate 0, and the opposite end has coordinate 100. Overall, the university has *n* students. Dean's office allows *i*-th student to use the segment (*l**i*,<=*r**i*) of the dryer. However, the dean's office actions are contradictory and now one part of the dryer can belong to multiple students!\n\nAlexey don't like when someone touch his clothes. That's why he want make it impossible to someone clothes touch his ones. So Alexey wonders: what is the total length of the parts of the dryer that he may use in a such way that clothes of the others (*n*<=-<=1) students aren't drying there. Help him! Note that Alexey, as the most respected student, has number 1.",
"input": "",
"output": "```python\nimport numpy as np\n\nnum_of_student = int(input())\nsush = list()\n\nfor i in range(0, num_of_student):\n inp = input()\n inp_spl = inp.split(\" \")\n sush.append(int(inp_spl[0]))\n sush.append(int(inp_spl[1]))\n\none_range = np.zeros((np.max(sush)+1,))\n\nfor i in range(0, num_of_student*2, 2):\n one_range[sush[i]:sush[i+1]] = i+1\n\ncount = 0\nfor i in one_range:\n if i == 1:\n count += 1\n\nprint(count)\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Permutation *p* is an ordered set of integers *p*1,<=<=*p*2,<=<=...,<=<=*p**n*, consisting of *n* distinct positive integers, each of them doesn't exceed *n*. We'll denote the *i*-th element of permutation *p* as *p**i*. We'll call number *n* the size or the length of permutation *p*1,<=<=*p*2,<=<=...,<=<=*p**n*.\n\nYou have a sequence of integers *a*1,<=*a*2,<=...,<=*a**n*. In one move, you are allowed to decrease or increase any number by one. Count the minimum number of moves, needed to build a permutation from this sequence.",
"input": "",
"output": "```python\nt = int(input())\r\nres = 0\r\ns = sorted(list(map(int, input().split())))\r\nfor i in range(0, t):\r\n res+=abs(i+1 - s[i])\r\nprint(res)\r\n\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You may have heard of the pie rule before. It states that if two people wish to fairly share a slice of pie, one person should cut the slice in half, and the other person should choose who gets which slice. Alice and Bob have many slices of pie, and rather than cutting the slices in half, each individual slice will be eaten by just one person.\n\nThe way Alice and Bob decide who eats each slice is as follows. First, the order in which the pies are to be handed out is decided. There is a special token called the \"decider\" token, initially held by Bob. Until all the pie is handed out, whoever has the decider token will give the next slice of pie to one of the participants, and the decider token to the other participant. They continue until no slices of pie are left.\n\nAll of the slices are of excellent quality, so each participant obviously wants to maximize the total amount of pie they get to eat. Assuming both players make their decisions optimally, how much pie will each participant receive?",
"input": "",
"output": "```python\n\n\nimport sys\n\ncache = {}\n\ndef max_possible(pie_slices, current_slice):\n\n if current_slice in cache:\n return cache[current_slice]\n\n if len(pie_slices) - 1 == current_slice:\n return pie_slices[current_slice]\n\n opp = pie_slices[current_slice]\n for cs in range(current_slice + 1, len(pie_slices)):\n c1 = max_possible(pie_slices, cs)\n if opp > c1:\n return opp\n\n opp += pie_slices[cs]\n\n return pie_slices[current_slice] + sum(pie_slices[current_slice + 1:]) - max_possible(pie_slices, current_slice + 1)\n\ndef main():\n n = int(sys.stdin.readline().strip())\n\n pie_slices = [int(tok) for tok in sys.stdin.readline().strip().split()]\n\n b = max_possible(pie_slices, 0)\n print(sum(pie_slices) - b, b)\n\n\n\n\n\n\n\n\nif __name__ == '__main__':\n main()\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "There is a fence in front of Polycarpus's home. The fence consists of *n* planks of the same width which go one after another from left to right. The height of the *i*-th plank is *h**i* meters, distinct planks can have distinct heights.\n\nPolycarpus has bought a posh piano and is thinking about how to get it into the house. In order to carry out his plan, he needs to take exactly *k* consecutive planks from the fence. Higher planks are harder to tear off the fence, so Polycarpus wants to find such *k* consecutive planks that the sum of their heights is minimal possible.\n\nWrite the program that finds the indexes of *k* consecutive planks with minimal total height. Pay attention, the fence is not around Polycarpus's home, it is in front of home (in other words, the fence isn't cyclic).",
"input": "",
"output": "```python\nn,k=map(int,input().split())\r\nh=list(map(int,input().split()))\r\nj_min=sum(h[0:k])\r\nj=0\r\nfor i in range(1,n-k):\r\n p=j_min-h[i-1]+h[i+k]\r\n if p15:\r\n print(now+15)\r\n sys.exit(0)\r\n else:\r\n now=i\r\nprint(90)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.\n\nA little later they found a string *s*, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring *t* of the string *s*.\n\nPrefix supposed that the substring *t* is the beginning of the string *s*; Suffix supposed that the substring *t* should be the end of the string *s*; and Obelix supposed that *t* should be located somewhere inside the string *s*, that is, *t* is neither its beginning, nor its end.\n\nAsterix chose the substring *t* so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring *t* aloud, the temple doors opened. \n\nYou know the string *s*. Find the substring *t* or determine that such substring does not exist and all that's been written above is just a nice legend.",
"input": "",
"output": "```python\n\r\nfrom sys import stdin, stdout\r\n\r\ns=stdin.readline()\r\ns=s[:-1]\r\nl=len(s)\r\nans,p,pp=set(),set(),set()\r\nd=0\r\nfor i in range(l-1,0,-1):\r\n\tif s[:i]==s[-i:]:\r\n\t\tans=s[:i]\r\n\t\tx=len(ans)\r\n\t\tfor j in range(1,l-x):\r\n\t\t\tif s[j:j+x] in ans:\r\n\t\t\t\tstdout.write(str(s[j:j+x]))\r\n\t\t\t\td=1\r\n\t\t\t\tbreak\r\n\tif d:\r\n\t\tbreak\r\nif not d:\r\n\tstdout.write(\"Just a legend\")\r\n\r\n\t\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "An *n*<=×<=*n* table *a* is defined as follows:\n - The first row and the first column contain ones, that is: *a**i*,<=1<==<=*a*1,<=*i*<==<=1 for all *i*<==<=1,<=2,<=...,<=*n*. - Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the remaining elements are defined by the formula *a**i*,<=*j*<==<=*a**i*<=-<=1,<=*j*<=+<=*a**i*,<=*j*<=-<=1. \nThese conditions define all the values in the table.\n\nYou are given a number *n*. You need to determine the maximum value in the *n*<=×<=*n* table defined by the rules above.",
"input": "",
"output": "```python\ndef m(n):\r\n a=[[0]*n]*n\r\n a[0]=[1]*n\r\n for i in range(n):a[i][0]=1\r\n for i in range(1, n):\r\n for u in range(1, n):\r\n a[i][u]=a[i-1][u]+a[i][u-1]\r\n print(a[n-1][n-1])\r\nn=int(input())\r\nif n==1: print(1)\r\nelse: m(n)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "So, the New Year holidays are over. Santa Claus and his colleagues can take a rest and have guests at last. When two \"New Year and Christmas Men\" meet, thear assistants cut out of cardboard the letters from the guest's name and the host's name in honor of this event. Then the hung the letters above the main entrance. One night, when everyone went to bed, someone took all the letters of our characters' names. Then he may have shuffled the letters and put them in one pile in front of the door.\n\nThe next morning it was impossible to find the culprit who had made the disorder. But everybody wondered whether it is possible to restore the names of the host and his guests from the letters lying at the door? That is, we need to verify that there are no extra letters, and that nobody will need to cut more letters.\n\nHelp the \"New Year and Christmas Men\" and their friends to cope with this problem. You are given both inscriptions that hung over the front door the previous night, and a pile of letters that were found at the front door next morning.",
"input": "",
"output": "```python\nword1=input()\r\nword2=input()\r\ntotal=input()\r\narr1=[]\r\narr2=[]\r\ntot=[]\r\nfor x,let in enumerate(word1):\r\n arr1.append(let)\r\nfor x,let in enumerate(word2):\r\n arr2.append(let)\r\n\r\nfor x,let in enumerate(total):\r\n tot.append(let)\r\n\r\n\r\narr1.extend(arr2)\r\narr1.sort()\r\ntot.sort()\r\n\r\nif arr1 == tot:\r\n print(\"YES\")\r\nelse:\r\n print(\"NO\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Okabe needs to renovate the Future Gadget Laboratory after he tried doing some crazy experiments! The lab is represented as an *n* by *n* square grid of integers. A good lab is defined as a lab in which every number not equal to 1 can be expressed as the sum of a number in the same row and a number in the same column. In other words, for every *x*,<=*y* such that 1<=≤<=*x*,<=*y*<=≤<=*n* and *a**x*,<=*y*<=≠<=1, there should exist two indices *s* and *t* so that *a**x*,<=*y*<==<=*a**x*,<=*s*<=+<=*a**t*,<=*y*, where *a**i*,<=*j* denotes the integer in *i*-th row and *j*-th column.\n\nHelp Okabe determine whether a given lab is good!",
"input": "",
"output": "```python\ndef r():\r\n return list(map(int, input().split()))\r\nn = int(input())\r\nmatr = [r() for i in range(n)]\r\nans = True\r\ncolumns = list(map(set,zip(*matr)))\r\nfor row in matr:\r\n\tans &= all(x == 1 or any(x - a in row for a in col) for x, col in zip(row, columns))\r\nprint(\"Yes\" if ans else \"No\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "We know that lucky digits are digits 4 and 7, however Vasya's got another favorite digit 0 and he assumes it also is lucky! Lucky numbers are such non-negative integers whose decimal record only contains lucky digits. For example, numbers 0,<=47,<=7074 are lucky, but 1,<=7377,<=895,<= -7 are not.\n\nVasya has *t* important positive integers he needs to remember. Vasya is quite superstitious and he wants to remember lucky numbers only, so he is asking you for each important number to represent it as a sum of exactly six lucky numbers (Vasya just can't remember more numbers). Then Vasya can just remember these six numbers and calculate the important number at any moment.\n\nFor each of *t* important integers represent it as the sum of six lucky numbers or state that this is impossible.",
"input": "",
"output": "```python\nprint(\"_RANDOM_GUESS_1691495004.1477993\")# 1691495004.1478186\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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*<=<<=*y*) from the set, such that *y*<==<=*x*·*k*.\n\nYou're given a set of *n* distinct positive integers. Your task is to find the size of it's largest *k*-multiple free subset.",
"input": "",
"output": "```python\ndef main():\n n, k = map(int, input().split())\n l = list(map(int, input().split()))\n s = set(l)\n for p in l:\n s.discard(p * k)\n print(len(s))\n\n\nif __name__ == '__main__':\n main()\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Lenny is playing a game on a 3<=×<=3 grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be switched off, if it was switched off then it will be switched on.\n\nLenny has spent some time playing with the grid and by now he has pressed each light a certain number of times. Given the number of times each light is pressed, you have to print the current state of each light.",
"input": "",
"output": "```python\ninp=[]\r\nout=[[True,True,True],[True,True,True],[True,True,True]]\r\n\r\nfor i in range(3):\r\n inp.append(list(map(int,input().split())))\r\n \r\nfor i in range(3):\r\n for j in range(3):\r\n if inp[i][j]%2==0:\r\n inp[i][j]=0\r\n else:\r\n inp[i][j]=1\r\nfor i in range(3):\r\n for j in range(3):\r\n k=out\r\n if inp[i][j]==1:\r\n out[i][j]=(not out[i][j])\r\n if i-1>=0:\r\n out[i-1][j]=(not out[i-1][j])\r\n if i+1<3:\r\n out[i+1][j]=(not out[i+1][j])\r\n if j-1>=0:\r\n out[i][j-1]=(not out[i][j-1])\r\n if j+1<3:\r\n out[i][j+1]=(not out[i][j+1])\r\nfor i in range(3):\r\n for j in range(3):\r\n if out[i][j]==True:\r\n out[i][j]=str(1)\r\n else:\r\n out[i][j]=str(0)\r\nprint(''.join(out[0]))\r\nprint(''.join(out[1]))\r\nprint(''.join(out[2]))\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a \"plus\") and negative (a \"minus\"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.\n\nMike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own.\n\nMike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.",
"input": "",
"output": "```python\ngroups = 0 \r\nlast = '00'\r\nfor i in range(int(input())):\r\n new = input()\r\n if new != last:\r\n groups +=1\r\n last = new\r\n \r\n \r\nprint(groups)\r\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are *n* lines in that description each of which described one goal. Every goal was marked with the name of the team that had scored it. Help Vasya, learn the name of the team that won the finals. It is guaranteed that the match did not end in a tie.",
"input": "",
"output": "```python\nfrom collections import Counter\r\n\r\nn = int(input())\r\n\r\nlst=[]\r\n\r\nfor i in range(n):\r\n lst.append(input())\r\n\r\nc = Counter(lst)\r\nwinner = c.most_common(1)\r\n\r\nprint(winner[0][0])\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Given an array *a*1,<=*a*2,<=...,<=*a**n* of *n* integers, find the largest number in the array that is not a perfect square.\n\nA number *x* is said to be a perfect square if there exists an integer *y* such that *x*<==<=*y*2.",
"input": "",
"output": "```python\nimport math\r\nn = int(input())\r\narr = list(map(int,filter(None,input().split(' '))))\r\narr = sorted(arr,reverse=True)\r\nnum = -1\r\nfor a in arr:\r\n sq = math.sqrt(a)\r\n if sq-math.floor(sq)==0:\r\n continue\r\n else:\r\n num = a\r\n break\r\nprint(num)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vasily the bear has a favorite rectangle, it has one vertex at point (0,<=0), and the opposite vertex at point (*x*,<=*y*). Of course, the sides of Vasya's favorite rectangle are parallel to the coordinate axes. \n\nVasya also loves triangles, if the triangles have one vertex at point *B*<==<=(0,<=0). That's why today he asks you to find two points *A*<==<=(*x*1,<=*y*1) and *C*<==<=(*x*2,<=*y*2), such that the following conditions hold:\n - the coordinates of points: *x*1, *x*2, *y*1, *y*2 are integers. Besides, the following inequation holds: *x*1<=<<=*x*2; - the triangle formed by point *A*, *B* and *C* is rectangular and isosceles ( is right); - all points of the favorite rectangle are located inside or on the border of triangle *ABC*; - the area of triangle *ABC* is as small as possible. \nHelp the bear, find the required points. It is not so hard to proof that these points are unique.",
"input": "",
"output": "```python\ndef main():\r\n x, y = list(map(int, input().split()))\r\n if x >= 0 and y >= 0:\r\n x1, x2, y1, y2 = 0, x+y, x+y, 0\r\n elif x <= 0 and y >= 0:\r\n x1, x2, y1, y2 = x-y, 0, 0, -(x-y)\r\n elif x <= 0 and y <= 0:\r\n x1, x2, y1, y2 = x+y, 0, 0, x+y\r\n elif x >= 0 and y <= 0:\r\n x1, x2, y1, y2 = 0, x - y, -(x-y), 0\r\n print(x1, y1, x2, y2)\r\n\r\nif __name__ == \"__main__\":\r\n main()\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Another programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place.\n\nYou know the rules of comparing the results of two given teams very well. Let's say that team *a* solved *p**a* problems with total penalty time *t**a* and team *b* solved *p**b* problems with total penalty time *t**b*. Team *a* gets a higher place than team *b* in the end, if it either solved more problems on the contest, or solved the same number of problems but in less total time. In other words, team *a* gets a higher place than team *b* in the final results' table if either *p**a*<=><=*p**b*, or *p**a*<==<=*p**b* and *t**a*<=<<=*t**b*. \n\nIt is considered that the teams that solve the same number of problems with the same penalty time share all corresponding places. More formally, let's say there is a group of *x* teams that solved the same number of problems with the same penalty time. Let's also say that *y* teams performed better than the teams from this group. In this case all teams from the group share places *y*<=+<=1, *y*<=+<=2, ..., *y*<=+<=*x*. The teams that performed worse than the teams from this group, get their places in the results table starting from the *y*<=+<=*x*<=+<=1-th place.\n\nYour task is to count what number of teams from the given list shared the *k*-th place.",
"input": "",
"output": "```python\nnk = list(map(int ,input().split()))\r\nn = nk[0]\r\nk = nk[1]\r\narr = []\r\nsolved = []\r\npts = []\r\nfor i in range(n):\r\n x = list(map(int, input().split()))\r\n arr.append(x)\r\nfor i in range(len(arr)):\r\n minval = i\r\n for j in range(i+1, len(arr)):\r\n if arr[minval][0] < arr[j][0]:\r\n minval = j\r\n elif arr[minval][0] == arr[j][0]:\r\n if arr[minval][1] < arr[j][1]:\r\n minval = j\r\n\r\n temp = arr[i]\r\n arr[i] = arr[minval]\r\n arr[minval] = temp\r\n\r\nkth = arr[k]\r\nprint(arr.count(kth))\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Little Vasya has received a young builder’s kit. The kit consists of several wooden bars, the lengths of all of them are known. The bars can be put one on the top of the other if their lengths are the same.\n\nVasya wants to construct the minimal number of towers from the bars. Help Vasya to use the bars in the best way possible.",
"input": "",
"output": "```python\nn = int(input())\r\nnums = list(map(int,input().split()))\r\ndiff = set(nums)\r\n\r\nres1 = max(nums.count(i) for i in diff)\r\nres2 = len(diff)\r\n\r\nprint(res1,res2)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "For some time the program of rounding numbers that had been developed by the Codeforces participants during one of the previous rounds, helped the citizens of Far Far Away to convert numbers into a more easily readable format. However, as time went by, the economy of the Far Far Away developed and the scale of operations grew. So the King ordered to found the Bank of Far Far Away and very soon even the rounding didn't help to quickly determine even the order of the numbers involved in operations. Besides, rounding a number to an integer wasn't very convenient as a bank needed to operate with all numbers with accuracy of up to 0.01, and not up to an integer.\n\nThe King issued yet another order: to introduce financial format to represent numbers denoting amounts of money. The formal rules of storing a number in the financial format are as follows: \n - A number contains the integer part and the fractional part. The two parts are separated with a character \".\" (decimal point). - To make digits in the integer part of a number easier to read, they are split into groups of three digits, starting from the least significant ones. The groups are separated with the character \",\" (comma). For example, if the integer part of a number equals 12345678, then it will be stored in the financial format as 12,345,678 - In the financial format a number's fractional part should contain exactly two digits. So, if the initial number (the number that is converted into the financial format) contains less than two digits in the fractional part (or contains no digits at all), it is complemented with zeros until its length equals 2. If the fractional part contains more than two digits, the extra digits are simply discarded (they are not rounded: see sample tests). - When a number is stored in the financial format, the minus sign is not written. Instead, if the initial number had the minus sign, the result is written in round brackets. - Please keep in mind that the bank of Far Far Away operates using an exotic foreign currency — snakes ($), that's why right before the number in the financial format we should put the sign \"$\". If the number should be written in the brackets, then the snake sign should also be inside the brackets. \nFor example, by the above given rules number 2012 will be stored in the financial format as \"$2,012.00\" and number -12345678.9 will be stored as \"($12,345,678.90)\".\n\nThe merchants of Far Far Away visited you again and expressed much hope that you supply them with the program that can convert arbitrary numbers to the financial format. Can you help them?",
"input": "",
"output": "```python\n\r\ns=input().strip()\r\na=[]\r\nif s[0]=='-':\r\n p='($'\r\n s=s[1:]\r\nelse:\r\n p='$'\r\nj=0\r\nt='.'\r\nn=len(s)\r\nwhile j<(n):\r\n if s[j]=='.':\r\n t=t+s[j+1]\r\n if j+2=0:\r\n a.append(',')\r\n u=0\r\n else:\r\n a.append(s[k])\r\na=p+''.join(a[::-1])+t\r\nif a[0]=='(':\r\n a=a+')'\r\nprint(a)\r\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw.\n\nThe first player wrote number *a*, the second player wrote number *b*. How many ways to throw a dice are there, at which the first player wins, or there is a draw, or the second player wins?",
"input": "",
"output": "```python\ndef get(f): return f(input().strip())\ndef gets(f): return [*map(f, input().split())]\n\n\na, b = gets(int)\ni = a + b >> 1\nif a + b & 1:\n print(i, 0, 6 - i)\nelse:\n print(i - 1, 1, 6 - i)\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word.\n\nHongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character of the word to the beginning of the word. He calls this a cyclic shift. He can apply cyclic shift many times. For example, consecutively applying cyclic shift operation to the word \"abracadabra\" Hongcow will get words \"aabracadabr\", \"raabracadab\" and so on.\n\nHongcow is now wondering how many distinct words he can generate by doing the cyclic shift arbitrarily many times. The initial string is also counted.",
"input": "",
"output": "```python\ns = input().strip()\r\nn = len(s)\r\n\r\n# Generate all possible cyclic shifts\r\nshifts = [s[i:] + s[:i] for i in range(n)]\r\n\r\n# Add shifts to a set to remove duplicates\r\ndistinct_shifts = set(shifts)\r\n\r\n# Return the size of the set as the answer\r\nprint(len(distinct_shifts))\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has *n* students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times.\n\nThe head of the SSU OPTC is recently gathering teams to participate in the world championship. Each team must consist of exactly three people, at that, any person cannot be a member of two or more teams. What maximum number of teams can the head make if he wants each team to participate in the world championship with the same members at least *k* times?",
"input": "",
"output": "```python\n\r\nn, k = map(int, input().split())\r\na = list(map(int, input().split()))\r\n\r\ncount = 0\r\nresult = 0\r\nfor i in a:\r\n if i == 0:\r\n count += 1\r\n if count == k:\r\n count = 0\r\n result += 1\r\nif count != 0:\r\n result += 1\r\nprint(result)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Formula One championship consists of series of races called Grand Prix. After every race drivers receive points according to their final position. Only the top 10 drivers receive points in the following order 25, 18, 15, 12, 10, 8, 6, 4, 2, 1. At the conclusion of the championship the driver with most points is the champion. If there is a tie, champion is the one with most wins (i.e. first places). If a tie still exists, it is chosen the one with most second places, and so on, until there are no more place to use for compare.\n\n Last year another scoring system was proposed but rejected. In it the champion is the one with most wins. If there is tie, champion is the one with most points. If a tie still exists it is proceeded the same way as in the original scoring system, that is comparing number of second, third, forth, and so on, places.\n\nYou are given the result of all races during the season and you are to determine the champion according to both scoring systems. It is guaranteed, that both systems will produce unique champion.",
"input": "",
"output": "```python\nN=int(input())\r\n# S={\"name\":[0,0,0,......],}\r\nsoc=[25,18,15,12,10,8,6,4,2,1]\r\nS={}\r\nfor i in range(N):\r\n\tn=int(input())\r\n\tfor y in range(n):\r\n\t\tif y<10:\r\n\t\t\ts=input()\r\n\t\t\tif s in S:\r\n\t\t\t\tS[s][0]+=soc[y]\r\n\t\t\t\tS[s][y+1]+=1\r\n\t\t\telse:\r\n\t\t\t\tS[s]=[soc[y],0,0,0,0,0,0,0,0,0,0]\r\n\t\t\t\tS[s][y+1]+=1\r\n#print(S)\r\n###A\r\nmas=[0]\r\nm=0\r\nfor i in S:\r\n\t#print(type(S[i][0]))\r\n\tif S[i][0]>m:\r\n\t\tmas=[0]\r\n\t\tm=S[i][0]\r\n\t\tmas[0]=i\r\n\telif S[i][0]==m:\r\n\t\tmas.append(i)\r\n#print(mas,m)\r\nif len(mas)>1:\r\n\tzz=1\r\n\tn=0\r\n\tM=[0]\r\n\twhile n==0:\r\n\t\tmaxx=0\r\n\t\tfor i in range(len(mas)):\r\n\t\t\tt=S[mas[i]][zz]\r\n\t\t\tif t>maxx and t!=0:\r\n\t\t\t\tM=[0]\r\n\t\t\t\tmaxx=t\r\n\t\t\t\tM[0]=(mas[i])\r\n\t\t\telif t==maxx and t!=0:\r\n\t\t\t\tM.append(mas[i])\r\n\t\tzz=zz+1\r\n\t\tif len(M)==1:\r\n\t\t\tbreak\r\n\tprint(M[0]) \t\t\r\nelse:\r\n\tprint(mas[0])\r\n####B\r\n\r\nmas=[0]\r\nm=0\r\nfor i in S:\r\n\tif S[i][1]>m:\r\n\t\tmas=[0]\r\n\t\tm=S[i][1]\r\n\t\tmas[0]=i\r\n\telif S[i][0]==m:\r\n\t\tmas.append(i)\r\nif len(mas)>1:\r\n\tmas1=[0]\r\n\tm1=0\r\n\tfor i in range(len(mas)):\r\n\t#print(type(S[i][0]))\r\n\t\tif S[mas[i]][0]>m:\r\n\t\t\tmas1=[0]\r\n\t\t\tm1=S[mas[i]][0]\r\n\t\t\tmas1[0]=mas[i]\r\n\t\telif S[mas[i]][0]==m1:\r\n\t\t\tmas1.append(mas[i])\t\r\n\tif len(mas1)>1:\r\n\t\tzz=2\r\n\t\tn=0\r\n\t\tM=[0]\r\n\t\twhile n==0:\r\n\t\t\tmaxx=0\r\n\t\t\tfor i in range(len(mas)):\r\n\t\t\t\tt=S[mas[i]][zz]\r\n\t\t\t\tif t>maxx and t!=0:\r\n\t\t\t\t\tM=[0]\r\n\t\t\t\t\tmaxx=t\r\n\t\t\t\t\tM[0]=(mas[i])\r\n\t\t\t\telif t==maxx and t!=0:\r\n\t\t\t\t\tM.append(mas[i])\r\n\t\t\tzz=zz+1\r\n\t\t\tif len(M)==1:\r\n\t\t\t\tbreak\r\n\t\tprint(M[0]) \r\n\telse:\r\n\t\tprint(mas1[0])\r\nelse:\r\n\tprint(mas[0])\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "One day Vasya the Hipster decided to count how many socks he had. It turned out that he had *a* red socks and *b* blue socks.\n\nAccording to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot.\n\nEvery day Vasya puts on new socks in the morning and throws them away before going to bed as he doesn't want to wash them.\n\nVasya wonders, what is the maximum number of days when he can dress fashionable and wear different socks, and after that, for how many days he can then wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.\n\nCan you help him?",
"input": "",
"output": "```python\nn,k=map(int,input().split())\r\nprint(min(n,k),abs(n-k)//2)\r\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vasya has got two number: *a* and *b*. However, Vasya finds number *a* too short. So he decided to repeat the operation of lengthening number *a* *n* times.\n\nOne operation of lengthening a number means adding exactly one digit to the number (in the decimal notation) to the right provided that the resulting number is divisible by Vasya's number *b*. If it is impossible to obtain the number which is divisible by *b*, then the lengthening operation cannot be performed.\n\nYour task is to help Vasya and print the number he can get after applying the lengthening operation to number *a* *n* times.",
"input": "",
"output": "```python\na,b,n=input().split(\" \")\r\nno_iterations={\r\n 0:[a]\r\n}\r\ndigits=[str(x) for x in range(10)]\r\nfound=False\r\nfor i in range(1,int(n)+1):\r\n new_iterations=[]\r\n for x in no_iterations[i-1]:\r\n for y in digits:\r\n if i==int(n):\r\n if int(x+y)%int(b)==0 and found==False:\r\n print(x+y)\r\n found=True\r\n else:\r\n new_iterations.append(x+y)\r\n no_iterations[i]=new_iterations\r\nif found==False:\r\n print(-1)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Little X has *n* distinct integers: *p*1,<=*p*2,<=...,<=*p**n*. He wants to divide all of them into two sets *A* and *B*. The following two conditions must be satisfied:\n - If number *x* belongs to set *A*, then number *a*<=-<=*x* must also belong to set *A*. - If number *x* belongs to set *B*, then number *b*<=-<=*x* must also belong to set *B*. \nHelp Little X divide the numbers into two sets or determine that it's impossible.",
"input": "",
"output": "```python\nimport sys\nsys.setrecursionlimit(1000000)\n\nset_a = 0\nset_b = 10**9 + 1\n\ndef find_set(u):\n if u not in parent:\n parent[u] = u\n parent[u] = u if parent[u] == u else find_set(parent[u])\n return parent[u]\n\ndef union(u, v):\n up = find_set(u)\n vp = find_set(v)\n parent[up] = vp\n\n\"\"\"\n4 5 7\n2 3 5 4\n\"\"\"\nparent = dict() # range 0 to 10**9 + 1\nparent[0] = 0\nparent[10**9 + 1] = 10**9 + 1\nn, a, b = map(int, input().split())\np = list(map(int, input().split()))\nset_p = set()\nfor i in range(n):\n set_p.add(p[i])\n\nans = [-1] * (n)\nno = False\n\nfor i in range(n):\n if a - p[i] in set_p and b - p[i] in set_p: # in both set\n union(a - p[i], p[i])\n union(b - p[i], p[i])\n elif a - p[i] in set_p and b - p[i] not in set_p: #only in set a\n union(a - p[i], set_a)\n union(p[i], set_a)\n elif b - p[i] in set_p and a - p[i] not in set_p: #only in set a\n union(b - p[i], set_b)\n union(p[i], set_b)\n else:\n no = True\n\nif no:\n print(\"NO\")\nelse:\n print('YES')\n for idx in p:\n if find_set(idx) == 0 :\n print('0', end = ' ')\n else:\n print('1', end = ' ')\n\n\t\t \t\t \t\t \t\t\t \t \t\t \t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "As the guys fried the radio station facilities, the school principal gave them tasks as a punishment. Dustin's task was to add comments to nginx configuration for school's website. The school has *n* servers. Each server has a name and an ip (names aren't necessarily unique, but ips are). Dustin knows the ip and name of each server. For simplicity, we'll assume that an nginx command is of form \"command ip;\" where command is a string consisting of English lowercase letter only, and ip is the ip of one of school servers.\n\nEach ip is of form \"a.b.c.d\" where *a*, *b*, *c* and *d* are non-negative integers less than or equal to 255 (with no leading zeros). The nginx configuration file Dustin has to add comments to has *m* commands. Nobody ever memorizes the ips of servers, so to understand the configuration better, Dustin has to comment the name of server that the ip belongs to at the end of each line (after each command). More formally, if a line is \"command ip;\" Dustin has to replace it with \"command ip; #name\" where name is the name of the server with ip equal to ip.\n\nDustin doesn't know anything about nginx, so he panicked again and his friends asked you to do his task for him.",
"input": "",
"output": "```python\nm,n=input().split(' ')\r\nIP={}\r\nfor i in range(int(m)):\r\n x,y=input().split(' ')\r\n IP[y]=x\r\nfor i in range(int(n)):\r\n s,r=input().split(' ')\r\n f=s+' '+r+' #'+IP[r[:-1]]\r\n print(f)\r\n\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Is it rated?\n\nHere it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.\n\nAnother Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.\n\nIt's known that if at least one participant's rating has changed, then the round was rated for sure.\n\nIt's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.\n\nIn this problem, you should not make any other assumptions about the rating system.\n\nDetermine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.",
"input": "",
"output": "```python\nn=int(input())\r\nl=0\r\nr=0\r\nll=[]\r\nll1=[]\r\nfor i in range(n):\r\n \r\n a=input().split(\" \")\r\n l+=int(a[0])\r\n r+=int(a[1])\r\n ll.append(list(map(int,a)))\r\nll1=list(ll)\r\nflag=0\r\nif(l!=r):\r\n print(\"rated\")\r\nelse:\r\n ll.sort(reverse=True)\r\n for j in range(n):\r\n #print(ll[j],ll1[j])\r\n if(ll[j]==ll1[j]):\r\n flag=1\r\n else:\r\n flag=0\r\n break\r\n if(flag==0):\r\n print(\"unrated\")\r\n else:\r\n print(\"maybe\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "One day Vasya painted a Cartesian coordinate system on a piece of paper and marked some set of points (*x*1,<=*y*1),<=(*x*2,<=*y*2),<=...,<=(*x**n*,<=*y**n*). Let's define neighbors for some fixed point from the given set (*x*,<=*y*): \n - point (*x*',<=*y*') is (*x*,<=*y*)'s right neighbor, if *x*'<=><=*x* and *y*'<==<=*y* - point (*x*',<=*y*') is (*x*,<=*y*)'s left neighbor, if *x*'<=<<=*x* and *y*'<==<=*y* - point (*x*',<=*y*') is (*x*,<=*y*)'s lower neighbor, if *x*'<==<=*x* and *y*'<=<<=*y* - point (*x*',<=*y*') is (*x*,<=*y*)'s upper neighbor, if *x*'<==<=*x* and *y*'<=><=*y* \nWe'll consider point (*x*,<=*y*) from the given set supercentral, if it has at least one upper, at least one lower, at least one left and at least one right neighbor among this set's points.\n\nVasya marked quite many points on the paper. Analyzing the picture manually is rather a challenge, so Vasya asked you to help him. Your task is to find the number of supercentral points in the given set.",
"input": "",
"output": "```python\ndef process(A):\r\n d_x = {}\r\n d_y = {}\r\n for x,y in A:\r\n if x not in d_x:\r\n d_x[x] = [y, y]\r\n else:\r\n d_x[x][0] = min(d_x[x][0], y)\r\n d_x[x][1] = max(d_x[x][1], y)\r\n if y not in d_y:\r\n d_y[y] = [x, x]\r\n else:\r\n d_y[y][0] = min(d_y[y][0], x)\r\n d_y[y][1] = max(d_y[y][1], x)\r\n answer = 0\r\n for x, y in A:\r\n if d_x[x][0] < y < d_x[x][1]:\r\n if d_y[y][0] < x < d_y[y][1]:\r\n answer+=1\r\n return answer\r\n\r\nn = int(input())\r\nA = []\r\nfor i in range(n):\r\n x, y = [int(x) for x in input().split()]\r\n A.append([x, y])\r\nprint(process(A))\r\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink \"Beecola\", which can be bought in *n* different shops in the city. It's known that the price of one bottle in the shop *i* is equal to *x**i* coins.\n\nVasiliy plans to buy his favorite drink for *q* consecutive days. He knows, that on the *i*-th day he will be able to spent *m**i* coins. Now, for each of the days he want to know in how many different shops he can buy a bottle of \"Beecola\".",
"input": "",
"output": "```python\nfrom bisect import *\n\nN = int(input())\na = sorted(list(map(int, input().split())))\nQ = int(input())\nfor _ in range(Q):\n budget = int(input())\n print(bisect_right(a, budget))\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If there are at least 7 players of some team standing one after another, then the situation is considered dangerous. For example, the situation 00100110111111101 is dangerous and 11110111011101 is not. You are given the current situation. Determine whether it is dangerous or not.",
"input": "",
"output": "```python\nplayers = input()\r\nif \"1\" * 7 in players or \"0\" * 7 in players:\r\n print(\"YES\")\r\nelse:\r\n print(\"NO\")\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nBy 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.\n\nFor example, the general considers the sequence of heights (4, 3, 4, 2, 1, 1) correct and the sequence (4, 3, 1, 2, 2) wrong.\n\nWithin 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.",
"input": "",
"output": "```python\nimport sys\r\nnum = int(sys.stdin.readline().strip())\r\nlst = sys.stdin.readline().strip().split()\r\n# print(lst)\r\nlst1 = map(int, lst)\r\nmp = list(lst1)\r\n# print(mp)\r\nmaxi = max(mp)\r\nmini = min(mp)\r\n# print(maxi)\r\n# print(mini)\r\nmaxi_inx = []\r\nmini_inx = []\r\nfor i in range(len(mp)):\r\n if mp[i] == maxi:\r\n maxi_inx.append(i)\r\n if mp[i] == mini:\r\n mini_inx.append(i)\r\n# print(maxi_inx)\r\n# print(mini_inx)\r\nif min(maxi_inx) < max(mini_inx):\r\n summ = min(maxi_inx) + len(lst) - (max(mini_inx) + 1)\r\n print(summ)\r\nelse:\r\n summ = min(maxi_inx) + len(lst) - (max(mini_inx) + 1) - 1\r\n print(summ)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "There are *n* students living in the campus. Every morning all students wake up at the same time and go to wash. There are *m* rooms with wash basins. The *i*-th of these rooms contains *a**i* wash basins. Every student independently select one the rooms with equal probability and goes to it. After all students selected their rooms, students in each room divide into queues by the number of wash basins so that the size of the largest queue is the least possible. Calculate the expected value of the size of the largest queue among all rooms.",
"input": "",
"output": "```python\nimport functools,math,itertools,time\nu=functools.lru_cache(maxsize=None)\nn,m=map(int,input().split())\ns=[*map(int,input().split())]\nt=u(lambda x:1 if x<2 else x*t(x-1))\nc=u(lambda r,n:t(n)/t(r)/t(n-r))\np=u(lambda n,k:n**k)\nw=u(lambda n,k:math.ceil(n/k))\nr=u(lambda k,n:max(k,n))\nh=u(lambda i,j,l:c(l,i)*p(j-1,i-l)/p(j,i))\n\nfor i,j in itertools.product(range(1,n+1),range(1,m+1)):\n for l in range(i+1):\n h(i,j,l)\n@u\ndef d(i,j,k):\n if j:\n q=0\n for l in range(i + 1):\n q+=h(i,j,l)*d(i-l,j-1,r(k,w(l,s[j-1])))\n return q\n return k\nprint(d(n,m,0))\n\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Johnny has a younger sister Anne, who is very clever and smart. As she came home from the kindergarten, she told his brother about the task that her kindergartener asked her to solve. The task was just to construct a triangle out of four sticks of different colours. Naturally, one of the sticks is extra. It is not allowed to break the sticks or use their partial length. Anne has perfectly solved this task, now she is asking Johnny to do the same.\n\nThe boy answered that he would cope with it without any difficulty. However, after a while he found out that different tricky things can occur. It can happen that it is impossible to construct a triangle of a positive area, but it is possible to construct a degenerate triangle. It can be so, that it is impossible to construct a degenerate triangle even. As Johnny is very lazy, he does not want to consider such a big amount of cases, he asks you to help him.",
"input": "",
"output": "```python\nl=list(map(int,input().split()))\r\nl.sort(reverse=True)\r\na=l[0]\r\nb=l[1]\r\nc=l[2]\r\nd=l[3]\r\n\r\nif(b+c>a or b+d>a or c+d>a or c+d>b):\r\n print(\"TRIANGLE\")\r\nelif(b+c==a or b+d==a or c+d==a or c+d==b):\r\n print(\"SEGMENT\")\r\nelse: \r\n print(\"IMPOSSIBLE\")\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Allen has a LOT of money. He has $n$ dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are $1$, $5$, $10$, $20$, $100$. What is the minimum number of bills Allen could receive after withdrawing his entire balance?",
"input": "",
"output": "```python\n# https://codeforces.com/problemset/problem/996/A\r\n\r\ndef main():\r\n n = int(input())\r\n sum = 0\r\n bills = [100, 20, 10, 5, 1]\r\n for i in bills:\r\n sum += n // i\r\n n %= i\r\n print(sum)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "There is a fence in front of Polycarpus's home. The fence consists of *n* planks of the same width which go one after another from left to right. The height of the *i*-th plank is *h**i* meters, distinct planks can have distinct heights.\n\nPolycarpus has bought a posh piano and is thinking about how to get it into the house. In order to carry out his plan, he needs to take exactly *k* consecutive planks from the fence. Higher planks are harder to tear off the fence, so Polycarpus wants to find such *k* consecutive planks that the sum of their heights is minimal possible.\n\nWrite the program that finds the indexes of *k* consecutive planks with minimal total height. Pay attention, the fence is not around Polycarpus's home, it is in front of home (in other words, the fence isn't cyclic).",
"input": "",
"output": "```python\n\nplanksAmount, k = map(int, input().split())\n\nplanksHeight = list(map(int, input().split()))\n\n\nplanksHeight.sort()\n\nif len(planksAmount) == 1:\n print(1)\nelse:\n \n print(sum(planksHeight[:k]))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "All cities of Lineland are located on the *Ox* coordinate axis. Thus, each city is associated with its position *x**i* — a coordinate on the *Ox* axis. No two cities are located at a single point.\n\nLineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another city (because if they live in the same city, then it is easier to drop in).\n\nStrange but true, the cost of sending the letter is exactly equal to the distance between the sender's city and the recipient's city.\n\nFor each city calculate two values *min**i* and *max**i*, where *min**i* is the minimum cost of sending a letter from the *i*-th city to some other city, and *max**i* is the the maximum cost of sending a letter from the *i*-th city to some other city",
"input": "",
"output": "```python\nn = int(input()) # number of cities\r\nx = list(map(int, input().split())) # list of city coordinates\r\n\r\nmini = [0]*n\r\nmaxi = [0]*n\r\n\r\n# calculate mini values\r\nfor i in range(n):\r\n if i == 0:\r\n mini[i] = x[1] - x[0]\r\n elif i == n-1:\r\n mini[i] = x[n-1] - x[n-2]\r\n else:\r\n mini[i] = min(x[i]-x[i-1], x[i+1]-x[i])\r\n\r\n# calculate maxi values\r\nfor i in range(n):\r\n maxi[i] = max(x[i]-x[0], x[n-1]-x[i])\r\n\r\n# print mini and maxi values\r\nfor i in range(n):\r\n print(mini[i], maxi[i])\r\n\r\nThis code first reads the input values, calculates the mini and maxi values using the algorithm discussed above, and then prints these values in the required format. The output will consist of n lines, where the i-th line contains the mini and maxi values for the i-th city separated by a space.\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Nikolay has *a* lemons, *b* apples and *c* pears. He decided to cook a compote. According to the recipe the fruits should be in the ratio 1:<=2:<=4. It means that for each lemon in the compote should be exactly 2 apples and exactly 4 pears. You can't crumble up, break up or cut these fruits into pieces. These fruits — lemons, apples and pears — should be put in the compote as whole fruits.\n\nYour task is to determine the maximum total number of lemons, apples and pears from which Nikolay can cook the compote. It is possible that Nikolay can't use any fruits, in this case print 0.",
"input": "",
"output": "```python\na = int(input())\r\nb = int(input())\r\nc = int(input())\r\n\r\nif (b < 2*a):\r\n # Constraint is b, rather than a\r\n if (c < 2*b):\r\n # Constraint is c, not a or b \r\n a = c//4\r\n b = 2*a \r\n c = 2*b \r\n else: \r\n # c >= 2b, so constraint is b, not a or c \r\n a = b//2 \r\n b = 2*a \r\n c = 2*b \r\nelse: \r\n # b >= 2a, constraint is a, rather than b \r\n if (c < 4*a):\r\n # Constraint is c, not a or b \r\n a = c//4\r\n b = 2*a \r\n c = 2*b \r\n else:\r\n # c >= 4a, so constraint is a, not b or c \r\n a = a \r\n b = 2*a \r\n c = 2*b \r\n \r\nprint(a+b+c)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Two friends are on the coordinate axis *Ox* in points with integer coordinates. One of them is in the point *x*1<==<=*a*, another one is in the point *x*2<==<=*b*. \n\nEach of the friends can move by one along the line in any direction unlimited number of times. When a friend moves, the tiredness of a friend changes according to the following rules: the first move increases the tiredness by 1, the second move increases the tiredness by 2, the third — by 3 and so on. For example, if a friend moves first to the left, then to the right (returning to the same point), and then again to the left his tiredness becomes equal to 1<=+<=2<=+<=3<==<=6.\n\nThe friends want to meet in a integer point. Determine the minimum total tiredness they should gain, if they meet in the same point.",
"input": "",
"output": "```python\na = int(input())\r\nb = int(input())\r\nb, a = max(a, b), min(a, b)\r\nif (b - a) % 2 == 0:\r\n print((1 + (b - a) // 2) * (b - a) // 2) \r\nelse:\r\n print((1 + (b - a + 1) // 2) * ((b - a + 1) // 2) // 2 + (1 + (b - a - 1) // 2) * ((b - a - 1) // 2) // 2)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.",
"input": "",
"output": "```python\nn=input()\r\nc=0\r\nfor i in n:\r\n if i.isupper():\r\n c=c+1\r\n \r\nif c>len(n)//2:\r\n n=n.upper()\r\nelse:\r\n n=n.lower()\r\n \r\nprint(n)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Polycarpus has a ribbon, its length is *n*. He wants to cut the ribbon in a way that fulfils the following two conditions: \n - After the cutting each ribbon piece should have length *a*, *b* or *c*. - After the cutting the number of ribbon pieces should be maximum. \nHelp Polycarpus and find the number of ribbon pieces after the required cutting.",
"input": "",
"output": "```python\n# https://codeforces.com/problemset/problem/189/A\n\nfrom functools import lru_cache\nimport sys\nsys.setrecursionlimit(4000)\n\ndef helper() -> int:\n n, a, b, c = [int(s) for s in input().split(\" \")]\n a, b, c = sorted([a, b, c])\n\n dp = [0] * n\n dp[-a] = 1\n dp[-b] = 1\n dp[-c] = 1\n\n for i in range(len(dp) - 1, -1, -1):\n for value in [a,b,c]:\n if i + value < len(dp) and dp[i + value] > 0:\n dp[i] = max(dp[i], 1 + dp[i + value])\n\n return dp[0]\n\nprint(helper())\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Sean is trying to save a large file to a USB flash drive. He has *n* USB flash drives with capacities equal to *a*1,<=*a*2,<=...,<=*a**n* megabytes. The file size is equal to *m* megabytes. \n\nFind the minimum number of USB flash drives needed to write Sean's file, if he can split the file between drives.",
"input": "",
"output": "```python\nn = int(input())\r\nfile_size = int(input())\r\nflash_size = [int(input()) for i in range(n)]\r\nflash_size.sort(reverse=True)\r\ni = 0\r\ns = 0\r\nwhile i < n:\r\n s += flash_size[i]\r\n i += 1\r\n if s >= file_size:\r\n break\r\nprint(i)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "ZS the Coder and Chris the Baboon are travelling to Udayland! To get there, they have to get on the special IOI bus. The IOI bus has *n* rows of seats. There are 4 seats in each row, and the seats are separated into pairs by a walkway. When ZS and Chris came, some places in the bus was already occupied.\n\nZS and Chris are good friends. They insist to get a pair of neighbouring empty seats. Two seats are considered neighbouring if they are in the same row and in the same pair. Given the configuration of the bus, can you help ZS and Chris determine where they should sit?",
"input": "",
"output": "```python\nn=int(input())\r\nli_st=[]\r\nfor i in range(0,n-1):\r\n m=input()\r\n li_st.append(m)\r\nans = \"NO\"\r\nfor i in range(0,n-1):\r\n m = li_st[i]\r\n if ans==\"NO\":\r\n for j in range(0,4):\r\n if m[j]==m[j+1] and m[j]=='O':\r\n m=m.replace(\"OO\",\"++\")\r\n ans = \"YES\"\r\n break\r\n li_st[i] = m\r\nprint(ans)\r\nif ans==\"YES\":\r\n for x in (li_st):\r\n print(x)\r\n\r\n \r\n \r\n \r\n \r\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vanya and his friends are walking along the fence of height *h* and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed *h*. If the height of some person is greater than *h* he can bend down and then he surely won't be noticed by the guard. The height of the *i*-th person is equal to *a**i*.\n\nConsider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?",
"input": "",
"output": "```python\ns=input()\r\nt=s.split()\r\nn=int(t[0])\r\nh=int(t[1])\r\ns=input()\r\nt=s.split()\r\nw=0\r\nfor i in t:\r\n if int(i)>h:\r\n w+=2\r\n else:\r\n w+=1\r\nprint(w)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Gennady is one of the best child dentists in Berland. Today *n* children got an appointment with him, they lined up in front of his office.\n\nAll children love to cry loudly at the reception at the dentist. We enumerate the children with integers from 1 to *n* in the order they go in the line. Every child is associated with the value of his cofidence *p**i*. The children take turns one after another to come into the office; each time the child that is the first in the line goes to the doctor.\n\nWhile Gennady treats the teeth of the *i*-th child, the child is crying with the volume of *v**i*. At that the confidence of the first child in the line is reduced by the amount of *v**i*, the second one — by value *v**i*<=-<=1, and so on. The children in the queue after the *v**i*-th child almost do not hear the crying, so their confidence remains unchanged.\n\nIf at any point in time the confidence of the *j*-th child is less than zero, he begins to cry with the volume of *d**j* and leaves the line, running towards the exit, without going to the doctor's office. At this the confidence of all the children after the *j*-th one in the line is reduced by the amount of *d**j*.\n\nAll these events occur immediately one after the other in some order. Some cries may lead to other cries, causing a chain reaction. Once in the hallway it is quiet, the child, who is first in the line, goes into the doctor's office.\n\nHelp Gennady the Dentist to determine the numbers of kids, whose teeth he will cure. Print their numbers in the chronological order.",
"input": "",
"output": "```python\nn = int(input())\r\nlist_child = []\r\nlist_output = []\r\nfor i in range(n):\r\n s = [int(j) for j in input().split()]\r\n list_child.append([s[0],s[1],s[2],i+1])\r\nt = 0\r\nwhile t < n:\r\n if list_child[t][2] >= 0:\r\n for i in range(list_child[t][0]):\r\n if t+i < n-1:\r\n list_child[t+i+1][2] -= list_child[t][0]-i\r\n list_output.append(list_child[t][3])\r\n elif t < n-1:\r\n for j in range(t+1,n):\r\n list_child[j][2] -= list_child[t][1]\r\n t += 1\r\nprint (len(list_output))\r\nfor i in range(len(list_output)-1):\r\n print (list_output[i],end=' ')\r\nprint (list_output[len(list_output)-1])\r\n \r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Eugeny has array *a*<==<=*a*1,<=*a*2,<=...,<=*a**n*, consisting of *n* integers. Each integer *a**i* equals to -1, or to 1. Also, he has *m* queries:\n - Query number *i* is given as a pair of integers *l**i*, *r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*). - The response to the query will be integer 1, if the elements of array *a* can be rearranged so as the sum *a**l**i*<=+<=*a**l**i*<=+<=1<=+<=...<=+<=*a**r**i*<==<=0, otherwise the response to the query will be integer 0. \nHelp Eugeny, answer all his queries.",
"input": "",
"output": "```python\nn , m = map(int,input().split())\r\narr = input().split()\r\nx = arr.count('1')\r\ny = n - x\r\nans = ''\r\nfor j in range(m):\r\n l , r = map(int,input().split())\r\n if (r - l + 1) % 2 == 0 and min(x , y) >= (r - l + 1)//2 :\r\n ans += '1\\n'\r\n else:\r\n ans += '0\\n'\r\nprint(ans)\r\n\r\n\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Small, but very brave, mouse Brain was not accepted to summer school of young villains. He was upset and decided to postpone his plans of taking over the world, but to become a photographer instead.\n\nAs you may know, the coolest photos are on the film (because you can specify the hashtag #film for such).\n\nBrain took a lot of colourful pictures on colored and black-and-white film. Then he developed and translated it into a digital form. But now, color and black-and-white photos are in one folder, and to sort them, one needs to spend more than one hour!\n\nAs soon as Brain is a photographer not programmer now, he asks you to help him determine for a single photo whether it is colored or black-and-white.\n\nPhoto can be represented as a matrix sized *n*<=×<=*m*, and each element of the matrix stores a symbol indicating corresponding pixel color. There are only 6 colors: \n - 'C' (cyan)- 'M' (magenta)- 'Y' (yellow)- 'W' (white)- 'G' (grey)- 'B' (black) \nThe photo is considered black-and-white if it has only white, black and grey pixels in it. If there are any of cyan, magenta or yellow pixels in the photo then it is considered colored.",
"input": "",
"output": "```python\n#!/usr/bin/env python3\n# coding:utf-8\n\nif __name__ == \"__main__\":\n n, m = [int(item) for item in input().split()]\n for i in n:\n arr = input().split()\n if \"C\" in arr or \"Y\" in arr or \"M\" in arr:\n print(\"#Color\")\n exit(0)\n print(\"#Black&White\")\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with *n* room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (*n*<=-<=1)-th room to the *n*-th room. Thus, you can go to room *x* only from room *x*<=-<=1.\n\nThe potato pie is located in the *n*-th room and Vitaly needs to go there. \n\nEach pair of consecutive rooms has a door between them. In order to go to room *x* from room *x*<=-<=1, you need to open the door between the rooms with the corresponding key. \n\nIn total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type *t* can open the door of type *T* if and only if *t* and *T* are the same letter, written in different cases. For example, key f can open door F.\n\nEach of the first *n*<=-<=1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.\n\nVitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room *n*.\n\nGiven the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room *n*, which has a delicious potato pie. Write a program that will help Vitaly find out this number.",
"input": "",
"output": "```python\nn = int(input())\r\np = []\r\na = list(input())\r\nsum = 0\r\nfor i in range(len(a)):\r\n if i % 2 == 0:\r\n p.append((chr(ord(a[i]) - 32)))\r\n else:\r\n if a[i] in p:\r\n p.remove(a[i])\r\n else:\r\n sum += 1\r\nprint(sum)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A + B is often used as an example of the easiest problem possible to show some contest platform. However, some scientists have observed that sometimes this problem is not so easy to get accepted. Want to try?",
"input": "",
"output": "```python\na, b = map(int,input().split(\" \"))\r\nprint(str(a+b))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Iahub isn't well prepared on geometry problems, but he heard that this year there will be a lot of geometry problems on the IOI selection camp. Scared, Iahub locked himself in the basement and started thinking of new problems of this kind. One of them is the following.\n\nIahub wants to draw *n* distinct points and *m* segments on the *OX* axis. He can draw each point with either red or blue. The drawing is good if and only if the following requirement is met: for each segment [*l**i*,<=*r**i*] consider all the red points belong to it (*r**i* points), and all the blue points belong to it (*b**i* points); each segment *i* should satisfy the inequality |*r**i*<=-<=*b**i*|<=≤<=1.\n\nIahub thinks that point *x* belongs to segment [*l*,<=*r*], if inequality *l*<=≤<=*x*<=≤<=*r* holds.\n\nIahub gives to you all coordinates of points and segments. Please, help him to find any good drawing.",
"input": "",
"output": "```python\n#input\r\nn,m=map(int,input().split())\r\nxlist=[int(x) for x in input().split()]\r\nfor i in range(m):\r\n\tsegment=[int(x) for x in input().split()]\r\n\r\n#variables\r\ncolor=''\r\n\r\n#main\r\nfor i in range(n):\r\n\tif i%2==0:\r\n\t\tcolor+='0 '\r\n\telse:\r\n\t\tcolor+='1 '\r\n\r\nprint(color)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house.\n\nKarlsson's gaze immediately fell on *n* wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find.\n\nAnd now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open.\n\nKarlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds *t*, in which he is able to bring all the cupboard doors in the required position.\n\nYour task is to write a program that will determine the required number of seconds *t*.",
"input": "",
"output": "```python\nfrom sys import stdin,stdout\nfrom math import gcd,sqrt,floor,ceil\n# Fast I/O\ninput = stdin.readline\nprint = stdout.write\n\ndef list_inp(x):return list(map(x,input().split()))\ndef map_inp(x):return map(x,input().split())\n\ndef lcm(a,b): return (a*b)/gcd(a,b)\n\ndef solve(x):\n return x[len(x)//2]-x[(len(x)-1)//2]+1\nt = int(input())\ncnt = 0\nfor _ in range(t):\n a,b = map_inp(int)\n if a == b:\n continue\n elif a == 0 and b == 1:\n cnt+=1\nprint(cnt)\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Luke Skywalker gave Chewbacca an integer number *x*. Chewbacca isn't good at numbers but he loves inverting digits in them. Inverting digit *t* means replacing it with digit 9<=-<=*t*. \n\nHelp Chewbacca to transform the initial number *x* to the minimum possible positive number by inverting some (possibly, zero) digits. The decimal representation of the final number shouldn't start with a zero.",
"input": "",
"output": "```python\nimport sys, threading\r\nimport math\r\nfrom math import log2,floor\r\nimport heapq\r\nfrom collections import defaultdict,deque\r\ninput = sys.stdin.readline\r\n \r\n############ ---- Input Functions ---- ############\r\ndef inp():\r\n return(int(input()))\r\ndef inlt():\r\n return(list(map(int,input().split())))\r\ndef insr():\r\n s = input()\r\n return(list(s[:len(s) - 1]))\r\ndef invr():\r\n return(map(int,input().split()))\r\nn = str(inp())\r\ns = \"\"\r\nfor i in range(len(n)):\r\n if 9 - int(n[i]) < int(n[i]):\r\n if 9 - int(n[i]) == 0 and len(s) == 0:\r\n s += n[i]\r\n else:\r\n s += str(9 - int(n[i]))\r\n else:\r\n s += n[i]\r\nprint(int(s))\r\n# def main(): \r\n# threading.stack_size(1 << 27)\r\n# sys.setrecursionlimit(1 << 30)\r\n# main_thread = threading.Thread(target=main)\r\n# main_thread.start()\r\n# main_thread.join()\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Petya and Vasya are playing a game. Petya's got *n* non-transparent glasses, standing in a row. The glasses' positions are indexed with integers from 1 to *n* from left to right. Note that the positions are indexed but the glasses are not.\n\nFirst Petya puts a marble under the glass in position *s*. Then he performs some (possibly zero) shuffling operations. One shuffling operation means moving the glass from the first position to position *p*1, the glass from the second position to position *p*2 and so on. That is, a glass goes from position *i* to position *p**i*. Consider all glasses are moving simultaneously during one shuffling operation. When the glasses are shuffled, the marble doesn't travel from one glass to another: it moves together with the glass it was initially been put in.\n\nAfter all shuffling operations Petya shows Vasya that the ball has moved to position *t*. Vasya's task is to say what minimum number of shuffling operations Petya has performed or determine that Petya has made a mistake and the marble could not have got from position *s* to position *t*.",
"input": "",
"output": "```python\n#B. Find Marble\r\nn,s,t = map(int,input().split())\r\np = list(map(int,input().split()))\r\na = list(range(1,n+1))\r\nm = a[s-1]\r\nx = 0\r\nif s == t:\r\n print(0)\r\nelse:\r\n while True:\r\n tmp = [0]*n\r\n for i in range(n):\r\n tmp[p[i]-1] = a[i]\r\n x += 1\r\n if tmp[t-1] == m:\r\n print(x)\r\n break\r\n elif tmp[s-1] == m:\r\n print(-1)\r\n break\r\n a = tmp\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.\n\nAssuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus.",
"input": "",
"output": "```python\nfrom sys import stdin\nfrom collections import Counter,defaultdict,deque\nimport sys\nimport math\nimport os\nimport operator\nimport random\nfrom fractions import Fraction\nimport functools\nimport bisect\nimport itertools\nfrom heapq import *\nimport copy\n\n\nans = []\nfor _ in range(int(input())):\n ans.append(input())\nans = ans[::-1]\nvisit = set()\nfor i in ans:\n if i not in visit:\n print(i)\n visit.add(i)\n\n\n'''\nn = int(input())\narr = list(map(int,input().split()))\ndp = [[0 for i in range(11)] for j in range(n+2)]\nprint(dp)\ndp[1][arr[1]] = 1\nfor i in range(1,n):\n for j in range(10):\n dp[i+1][(j+arr[i+1])%10]+=dp[i][j]\n dp[i+1][(j*arr[i+1])%10]+=dp[i][j]\nfor i in range(10):\n print(dp[n][i])\n\n\n\ndef error(n):\n return (n - int(n))<1\n\na = [5,4,3,2,1]\nk = 300\nleft,right = 0,k\nmid = (left + right) / 2\nwhile left<=right:\n square = (mid*mid)\n if int(square) == k and error(square) == True:\n print(mid)\n break\n elif square <= k:\n left = mid\n else:\n right = mid\n mid = (left + right) / 2\n'''\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Natasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the string — concatenation of letters, which correspond to the stages.\n\nThere are $n$ stages available. The rocket must contain exactly $k$ of them. Stages in the rocket should be ordered by their weight. So, after the stage with some letter can go only stage with a letter, which is at least two positions after in the alphabet (skipping one letter in between, or even more). For example, after letter 'c' can't go letters 'a', 'b', 'c' and 'd', but can go letters 'e', 'f', ..., 'z'.\n\nFor the rocket to fly as far as possible, its weight should be minimal. The weight of the rocket is equal to the sum of the weights of its stages. The weight of the stage is the number of its letter in the alphabet. For example, the stage 'a 'weighs one ton,' b 'weighs two tons, and' z' — $26$ tons.\n\nBuild the rocket with the minimal weight or determine, that it is impossible to build a rocket at all. Each stage can be used at most once.",
"input": "",
"output": "```python\nimport sys\r\nimport math\r\n\r\n\r\ndef scan(input_type='int'):\r\n return list(map(int, sys.stdin.readline().strip().split()))\r\n\r\n\r\ndef solution():\r\n # for _ in range(int(input())):\r\n n, k = scan()\r\n s = input()\r\n a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',\r\n 'w', 'x', 'y', 'z']\r\n c = {}\r\n for i in range(26):\r\n c[a[i]] = i+1\r\n b = [i for i in s]\r\n b.sort()\r\n s = 1000000000\r\n for i in range(n):\r\n e = k\r\n j = i+1\r\n w = c[b[i]]\r\n q = b[i]\r\n p = 0\r\n while e > 1 and j < n:\r\n if c[b[j]] - c[q[p]] > 2:\r\n w += c[b[j]]\r\n q += b[j]\r\n p += 1\r\n e -= 1\r\n j += 1\r\n if e == 1:\r\n s = min(s, w)\r\n break\r\n if s == 1000000000:\r\n print(-1)\r\n else:\r\n print(s)\r\n\r\n\r\nif __name__ == '__main__':\r\n solution()\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.\n\nThe rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. \n\nSometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.\n\nYour task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.",
"input": "",
"output": "```python\nt = int(input())\r\nl = []\r\nfor i in range(t):\r\n m = input()\r\n l.append(m)\r\nfor i in range(len(l) , 0 , -1):\r\n print(l[i-1])\r\n \r\n \r\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "One day *n* cells of some array decided to play the following game. Initially each cell contains a number which is equal to it's ordinal number (starting from 1). Also each cell determined it's favourite number. On it's move *i*-th cell can exchange it's value with the value of some other *j*-th cell, if |*i*<=-<=*j*|<==<=*d**i*, where *d**i* is a favourite number of *i*-th cell. Cells make moves in any order, the number of moves is unlimited.\n\nThe favourite number of each cell will be given to you. You will also be given a permutation of numbers from 1 to *n*. You are to determine whether the game could move to this state.",
"input": "",
"output": "```python\nfrom __future__ import division\r\nfrom sys import stdin, stdout\r\nfrom queue import PriorityQueue\r\nfrom heapq import *\r\nfrom collections import deque, defaultdict, Counter\r\nfrom bitarray import bitarray\r\ninput_int = lambda: int(stdin.readline())\r\ninput_1D_int = lambda: [int(x) for x in stdin.readline().split()]\r\ninput_2D_int = lambda n: [input_1D_int() for _ in range(n)]\r\ninput_string = lambda: stdin.readline().strip()\r\ninput_1D_string = lambda: [str(x) for x in stdin.readline().split()]\r\ninput_2D_string = lambda n: [input_1D_string() for _ in range(n)]\r\npr = lambda args, sep: stdout.write(sep.join(map(str, args)) + '\\n')\r\nchars, oo = 'abcdefghijklmnopqrstuvwxyz', int(1000000000000000000)\r\nclass DSU:\r\n def __init__(self, n):\r\n self.groupSize = [0] * (n + 1)\r\n self.parent = [0] * (n + 1)\r\n self.rank = [0] * (n + 1)\r\n self.mx = [0] * (n + 1)\r\n self.mn = [0] * (n + 1)\r\n for i in range(n + 1):\r\n self.parent[i] = i\r\n self.mx[i] = self.mn[i] = i\r\n self.groupSize[i] = 1\r\n self.rank[i] = 0\r\n def make_set(self, u):\r\n self.parent[u] = u\r\n self.groupSize[u] = 1\r\n def find_set(self, x):\r\n if self.parent[x] == x: return x\r\n self.parent[x] = self.find_set(self.parent[x])\r\n return self.parent[x]\r\n def union_set(self, u, v):\r\n leader1 = self.find_set(u)\r\n leader2 = self.find_set(v)\r\n if leader1 == leader2: return\r\n if self.groupSize[leader1] < self.groupSize[leader2]:\r\n leader1, leader2 = leader2, leader1\r\n self.parent[leader2] = leader1\r\n self.groupSize[leader1] += self.groupSize[leader2]\r\n if self.rank[leader1] == self.rank[leader2]:\r\n self.rank[leader1] += 1\r\n self.mx[leader1] = max(self.mx[leader1], self.mx[leader2])\r\n self.mn[leader1] = min(self.mn[leader1], self.mn[leader2])\r\n def samegroup(self, u, v):\r\n leader1 = self.find_set(u)\r\n leader2 = self.find_set(v)\r\n return leader1 == leader2\r\n def sizeGroup(self, u):\r\n leader = self.find_set(u)\r\n return self.groupSize[leader]\r\n def get_max(self, u):\r\n return self.mx[self.find_set(u)]\r\n def get_min(self, u):\r\n return self.mn[self.find_set(u)]\r\nn = input_int()\r\na = input_1D_int()\r\nb = input_1D_int()\r\ndsu = DSU(n + 10)\r\nfor i in range(0, n):\r\n r = (i + 1) + b[i]\r\n l = (i + 1) - b[i]\r\n if r > 0 and r <= n:dsu.union_set(r, i + 1)\r\n if l <= n and l > 0:dsu.union_set(l, i + 1)\r\nfor i in range(0, n):\r\n if dsu.find_set(a[i]) != dsu.find_set(i + 1):\r\n print(\"NO\")\r\n exit()\r\nprint(\"YES\")\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "wHAT DO WE NEED cAPS LOCK FOR?\n\nCaps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage. \n\nLet's consider that a word has been typed with the Caps lock key accidentally switched on, if: \n - either it only contains uppercase letters; - or all letters except for the first one are uppercase. \nIn this case we should automatically change the case of all letters. For example, the case of the letters that form words \"hELLO\", \"HTTP\", \"z\" should be changed.\n\nWrite a program that applies the rule mentioned above. If the rule cannot be applied, the program should leave the word unchanged.",
"input": "",
"output": "```python\ns = input()\r\ns1 = ''\r\n\r\nif s.isupper():\r\n s1 += s[0]\r\n s= s[1:].lower()\r\n s1 += s\r\n print(s1)\r\nelif s[0] >= 'a' and s[0] <= 'z':\r\n s1 += s[0]\r\n s1 = s1.upper()\r\n if s[1:].isupper():\r\n s = s[1:].lower()\r\n s1 += s\r\n print(s1)\r\nelse:\r\n print(s)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Two friends are on the coordinate axis *Ox* in points with integer coordinates. One of them is in the point *x*1<==<=*a*, another one is in the point *x*2<==<=*b*. \n\nEach of the friends can move by one along the line in any direction unlimited number of times. When a friend moves, the tiredness of a friend changes according to the following rules: the first move increases the tiredness by 1, the second move increases the tiredness by 2, the third — by 3 and so on. For example, if a friend moves first to the left, then to the right (returning to the same point), and then again to the left his tiredness becomes equal to 1<=+<=2<=+<=3<==<=6.\n\nThe friends want to meet in a integer point. Determine the minimum total tiredness they should gain, if they meet in the same point.",
"input": "",
"output": "```python\na = int(input())\r\nb = int(input())\r\nc = abs(a - b)\r\nans = 0\r\nfor i in range(c // 2 + 1):\r\n ans += 2 * i\r\nif c % 2 == 1:\r\n ans += i + 1\r\nprint(ans)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter *c* DZY knows its value *w**c*. For each special string *s*<==<=*s*1*s*2... *s*|*s*| (|*s*| is the length of the string) he represents its value with a function *f*(*s*), where \n\nNow DZY has a string *s*. He wants to insert *k* lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get?",
"input": "",
"output": "```python\nn = input()\r\nk = int(input())\r\na = list(map(int , input().split()))\r\ns = 0\r\nfor i in range(len(n)):\r\n s+=(a[ord(n[i])-97])*(i+1)\r\nx = max(a)\r\nj = len(n)+1\r\nfor i in range(k):\r\n s+=j*x\r\n j+=1\r\nprint(s)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Caisa solved the problem with the sugar and now he is on the way back to home. \n\nCaisa is playing a mobile game during his path. There are (*n*<=+<=1) pylons numbered from 0 to *n* in this game. The pylon with number 0 has zero height, the pylon with number *i* (*i*<=><=0) has height *h**i*. The goal of the game is to reach *n*-th pylon, and the only move the player can do is to jump from the current pylon (let's denote its number as *k*) to the next one (its number will be *k*<=+<=1). When the player have made such a move, its energy increases by *h**k*<=-<=*h**k*<=+<=1 (if this value is negative the player loses energy). The player must have non-negative amount of energy at any moment of the time. \n\nInitially Caisa stand at 0 pylon and has 0 energy. The game provides a special opportunity: one can pay a single dollar and increase the height of anyone pylon by one. Caisa may use that opportunity several times, but he doesn't want to spend too much money. What is the minimal amount of money he must paid to reach the goal of the game?",
"input": "",
"output": "```python\ndef ii(): return int(input())\r\ndef mi(): return map(int,input().split())\r\ndef li(): return list(mi())\r\ndef main():\r\n n=ii()\r\n v=li()\r\n c=0\r\n ans=v[0]\r\n for i in range(0,n-1):\r\n c+=v[i]-v[i+1]\r\n if(c<=0):\r\n ans+=(-c)\r\n c=0\r\n print(ans) \r\n \r\nif __name__ == \"__main__\":\r\n main() \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Let's call a number *k*-good if it contains all digits not exceeding *k* (0,<=...,<=*k*). You've got a number *k* and an array *a* containing *n* numbers. Find out how many *k*-good numbers are in *a* (count each number every time it occurs in array *a*).",
"input": "",
"output": "```python\nn,k=map(int,input().split())\r\nc=0\r\nfor i in range (n):\r\n a = input()\r\n m = 0\r\n for j in range (k+7):\r\n if str(j) in a:\r\n m = m+1\r\n if m == k+1:\r\n c=c+1\r\nprint(c)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are given a rectangular cake, represented as an *r*<=×<=*c* grid. Each cell either has an evil strawberry, or is empty. For example, a 3<=×<=4 cake may look as follows:\n\nThe cakeminator is going to eat the cake! Each time he eats, he chooses a row or a column that does not contain any evil strawberries and contains at least one cake cell that has not been eaten before, and eats all the cake cells there. He may decide to eat any number of times.\n\nPlease output the maximum number of cake cells that the cakeminator can eat.",
"input": "",
"output": "```python\nr, c = map(int, input().split())\ncake = []\ncc = [True for i in range(c)]\ncr = [True for i in range(r)]\nt = 0\nfor i in range(r):\n cake.append(input())\nfor row in range(r):\n for col in range(c):\n if cake[row][col] == 'S': \n cc[col] = False\n cr[row] = False\n \nfor i in range(r):\n for j in range(c):\n if cc[j] or cr[i]:\n t += 1\nprint(t)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Calculate the minimum number of characters you need to change in the string *s*, so that it contains at least *k* different letters, or print that it is impossible.\n\nString *s* consists only of lowercase Latin letters, and it is allowed to change characters only to lowercase Latin letters too.",
"input": "",
"output": "```python\na = input()\r\nb = int(input())\r\nif len(a) >= b and b - len(set(list(a))) <= 0 and len(set(list(a))) < 26:\r\n if b - len(set(list(a))) > 0:\r\n print(b - len(set(list(a))))\r\n else:\r\n print(0)\r\nelse:\r\n print(\"impossible\")\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Once Bob got to a sale of old TV sets. There were *n* TV sets at that sale. TV set with index *i* costs *a**i* bellars. Some TV sets have a negative price — their owners are ready to pay Bob if he buys their useless apparatus. Bob can «buy» any TV sets he wants. Though he's very strong, Bob can carry at most *m* TV sets, and he has no desire to go to the sale for the second time. Please, help Bob find out the maximum sum of money that he can earn.",
"input": "",
"output": "```python\nn,m=map(int,input().split())\r\nli=list(map(int,input().split()))\r\nli.sort()\r\nt=0\r\nfor x in range(m):\r\n if li[x]<0:\r\n t+=-li[x]\r\n else:\r\n t-=li[x]\r\nprint(t)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "An African crossword is a rectangular table *n*<=×<=*m* in size. Each cell of the table contains exactly one letter. This table (it is also referred to as grid) contains some encrypted word that needs to be decoded.\n\nTo solve the crossword you should cross out all repeated letters in rows and columns. In other words, a letter should only be crossed out if and only if the corresponding column or row contains at least one more letter that is exactly the same. Besides, all such letters are crossed out simultaneously.\n\nWhen all repeated letters have been crossed out, we should write the remaining letters in a string. The letters that occupy a higher position follow before the letters that occupy a lower position. If the letters are located in one row, then the letter to the left goes first. The resulting word is the answer to the problem.\n\nYou are suggested to solve an African crossword and print the word encrypted there.",
"input": "",
"output": "```python\nfrom collections import defaultdict\r\ndef main():\r\n n, m = map(int, input().split())\r\n matrix = []\r\n \r\n for i in range(n):\r\n matrix.append(input())\r\n \r\n row_freq = defaultdict(dict)\r\n col_freq = defaultdict(dict)\r\n \r\n for i in range(n):\r\n for j in range(m):\r\n letter = matrix[i][j]\r\n if letter not in row_freq[i]:\r\n row_freq[i][letter] = 0\r\n \r\n if letter not in col_freq[j]:\r\n col_freq[j][letter] = 0\r\n row_freq[i][letter] += 1\r\n col_freq[j][letter] += 1\r\n \r\n encrypted = []\r\n for i in range(n):\r\n for j in range(m):\r\n letter = matrix[i][j]\r\n if row_freq[i][letter] == 1 and col_freq[j][letter] == 1:\r\n encrypted.append(letter)\r\n \r\n print(''.join(encrypted))\r\n \r\nmain()\r\n \r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "So, the New Year holidays are over. Santa Claus and his colleagues can take a rest and have guests at last. When two \"New Year and Christmas Men\" meet, thear assistants cut out of cardboard the letters from the guest's name and the host's name in honor of this event. Then the hung the letters above the main entrance. One night, when everyone went to bed, someone took all the letters of our characters' names. Then he may have shuffled the letters and put them in one pile in front of the door.\n\nThe next morning it was impossible to find the culprit who had made the disorder. But everybody wondered whether it is possible to restore the names of the host and his guests from the letters lying at the door? That is, we need to verify that there are no extra letters, and that nobody will need to cut more letters.\n\nHelp the \"New Year and Christmas Men\" and their friends to cope with this problem. You are given both inscriptions that hung over the front door the previous night, and a pile of letters that were found at the front door next morning.",
"input": "",
"output": "```python\ns1 = input()\r\ns2 = input()\r\ns3 = input()\r\ns11 = s1+s2\r\ndef checking(s1,s2):\r\n count1 = {}\r\n count2 = {}\r\n for char in s1:\r\n count1[char] = count1.get(char,0) + 1\r\n\r\n for char in s2:\r\n count2[char] = count2.get(char,0) +1\r\n\r\n if count2 == count1:\r\n print('YES')\r\n else:\r\n print(\"NO\")\r\n\r\n\r\nchecking(s11,s3)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.\n\nPetya has a number consisting of *n* digits without leading zeroes. He represented it as an array of digits without leading zeroes. Let's call it *d*. The numeration starts with 1, starting from the most significant digit. Petya wants to perform the following operation *k* times: find the minimum *x* (1<=≤<=*x*<=<<=*n*) such that *d**x*<==<=4 and *d**x*<=+<=1<==<=7, if *x* is odd, then to assign *d**x*<==<=*d**x*<=+<=1<==<=4, otherwise to assign *d**x*<==<=*d**x*<=+<=1<==<=7. Note that if no *x* was found, then the operation counts as completed and the array doesn't change at all.\n\nYou are given the initial number as an array of digits and the number *k*. Help Petya find the result of completing *k* operations.",
"input": "",
"output": "```python\nn,k = map(int,input().split())\narr = list(input())\n\nwhile k>0:\n flag=True\n for i in range(n-1):\n if arr[i]=='4' and arr[i+1]=='7':\n if (i+1)%2==1:\n arr[i]='4'\n arr[i+1]='4'\n else:\n arr[i]='7'\n arr[i+1]='7'\n flag=False\n break\n if flag:\n break\n k-=1\nprint (''.join(arr))\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Sergey is testing a next-generation processor. Instead of bytes the processor works with memory cells consisting of *n* bits. These bits are numbered from 1 to *n*. An integer is stored in the cell in the following way: the least significant bit is stored in the first bit of the cell, the next significant bit is stored in the second bit, and so on; the most significant bit is stored in the *n*-th bit.\n\nNow Sergey wants to test the following instruction: \"add 1 to the value of the cell\". As a result of the instruction, the integer that is written in the cell must be increased by one; if some of the most significant bits of the resulting number do not fit into the cell, they must be discarded.\n\nSergey wrote certain values of the bits in the cell and is going to add one to its value. How many bits of the cell will change after the operation?",
"input": "",
"output": "```python\n\n\nn = int(input())\nc = input()[::-1]\nnc = format(int(c, 2)+1, f\"0{len(c)}b\")[::-1]\n\no = 0\n\nprint(nc)\nfor cb, ncb in zip(c, nc):\n if cb != ncb:\n o += 1\n\nprint(o)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vanya and his friends are walking along the fence of height *h* and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed *h*. If the height of some person is greater than *h* he can bend down and then he surely won't be noticed by the guard. The height of the *i*-th person is equal to *a**i*.\n\nConsider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?",
"input": "",
"output": "```python\na,b=map(int,input().split())\r\nc=list(map(int,input().split()))\r\nl=0\r\nfor i in range(a):\r\n if b>=c[i]:\r\n l=l+1\r\n else:\r\n l=l+(c[i]//b)\r\nprint(l)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Dima and his friends have been playing hide and seek at Dima's place all night. As a result, Dima's place got messy. In the morning they decided that they need to clean the place.\n\nTo decide who exactly would clean the apartment, the friends want to play a counting-out game. First, all the guys stand in a circle, and then each of them shows some number of fingers on one hand (one to five), and then the boys count in a circle, starting from Dima, the number of people, respective to the total number of fingers shown. The person on who the countdown stops will clean the apartment.\n\nFor example, if Dima and one of his friends played hide and seek, and 7 fingers were shown during the counting-out, then Dima would clean the place. If there were 2 or say, 8 fingers shown, then his friend would clean the place.\n\nDima knows how many fingers each of his friends will show during the counting-out. Now he is interested in the number of ways to show some number of fingers on one hand (one to five), so that he did not have to clean the place. Help Dima.",
"input": "",
"output": "```python\nn = int(input())\r\nl = [int(i) for i in input().split()]\r\ntotal = n+1\r\ns = sum(l)\r\nans = 0\r\nfor i in range(5):\r\n s+=1\r\n if(s%(n+1)==1):\r\n pass\r\n else:\r\n ans+=1\r\n \r\nprint(ans)\r\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A newspaper is published in Walrusland. Its heading is *s*1, it consists of lowercase Latin letters. Fangy the little walrus wants to buy several such newspapers, cut out their headings, glue them one to another in order to get one big string. After that walrus erase several letters from this string in order to get a new word *s*2. It is considered that when Fangy erases some letter, there's no whitespace formed instead of the letter. That is, the string remains unbroken and it still only consists of lowercase Latin letters.\n\nFor example, the heading is \"abc\". If we take two such headings and glue them one to the other one, we get \"abcabc\". If we erase the letters on positions 1 and 5, we get a word \"bcac\".\n\nWhich least number of newspaper headings *s*1 will Fangy need to glue them, erase several letters and get word *s*2?",
"input": "",
"output": "```python\nfrom math import *\r\nfrom sys import stdin, stdout, setrecursionlimit\r\nfrom bisect import *\r\nfrom collections import *\r\ninput = lambda: stdin.readline().strip()\r\nprint = stdout.write\r\n\r\ns1=input()\r\ns2=input()\r\n\r\nal=defaultdict(list)\r\ncount=1;index=0;count=0\r\n\r\nfor i in range(len(s1)):\r\n al[s1[i]].append(i)\r\n\r\nfor i in range(len(s2)):\r\n if(len(al[s2[i]])==0):\r\n print(str(-1))\r\n exit()\r\n\r\nfor i in range(len(s2)):\r\n\r\n r=bisect_left(al[s2[i]],index)\r\n if(r==len(al[s2[i]])):\r\n count+=1\r\n index=al[s2[i]][0]+1\r\n else:\r\n index=al[s2[i]][r]+1\r\n\r\nprint(str(count))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "\"QAQ\" is a word to denote an expression of crying. Imagine \"Q\" as eyes with tears and \"A\" as a mouth.\n\nNow Diamond has given Bort a string consisting of only uppercase English letters of length *n*. There is a great number of \"QAQ\" in the string (Diamond is so cute!).\n\nBort wants to know how many subsequences \"QAQ\" are in the string Diamond has given. Note that the letters \"QAQ\" don't have to be consecutive, but the order of letters should be exact.",
"input": "",
"output": "```python\nimport math\r\ncnt=0\r\nst=\"\"\r\nfrom itertools import combinations \r\ndef powerset(string):\r\n global cnt\r\n for i in range(0,len(string)+1):\r\n for element in combinations(string,i):\r\n if(''.join(element)==\"QAQ\"):\r\n cnt+=1\r\ndef powerSet(arr, n) :\r\n global cnt\r\n global st\r\n opsize = math.pow(2, n)\r\n for counter in range( 1, (int)(opsize)) :\r\n st=\"\"\r\n for j in range(0, n) : \r\n if (counter & (1< len(word) - count_caps:\r\n for i in range(len(word)):\r\n char = word[i].upper()\r\n word[i] = char\r\nelse:\r\n for i in range(len(word)):\r\n char = word[i].lower()\r\n word[i] = char\r\n\r\nword = ''.join(word)\r\nprint(word)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Luke Skywalker gave Chewbacca an integer number *x*. Chewbacca isn't good at numbers but he loves inverting digits in them. Inverting digit *t* means replacing it with digit 9<=-<=*t*. \n\nHelp Chewbacca to transform the initial number *x* to the minimum possible positive number by inverting some (possibly, zero) digits. The decimal representation of the final number shouldn't start with a zero.",
"input": "",
"output": "```python\nn=int(input())\r\nres=0\r\narr=[int(x) for x in str(n)]\r\nfor i in range(0,len(arr)-1):\r\n if(i==0 and arr[i]==9):\r\n continue\r\n elif(arr[i]>=5):\r\n arr[i]=9-arr[i]\r\nfor i in range(0,len(arr)):\r\n res=res+(10**(len(arr)-1-i))*arr[i]\r\nprint(res)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are given an array *a*1,<=*a*2,<=...,<=*a**n* consisting of *n* integers, and an integer *k*. You have to split the array into exactly *k* non-empty subsegments. You'll then compute the minimum integer on each subsegment, and take the maximum integer over the *k* obtained minimums. What is the maximum possible integer you can get?\n\nDefinitions of subsegment and array splitting are given in notes.",
"input": "",
"output": "```python\nn,k=map(int,input().split())\nip=list(map(int,input().split()))\na=max(ip)\nb=min(ip)\nif k==1:\n print(b)\nelif k>2:\n print(a)\nelse:\n if ip[0]==a or ip[-1]==a:\n print(a)\n else:\n if ip[0]>ip[-1]:\n print(max(ip[0], min(ip[1:])))\n else:\n print(max(ip[-1], min(ip[:-1])))\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "In a Berland's zoo there is an enclosure with camels. It is known that camels like to spit. Bob watched these interesting animals for the whole day and registered in his notepad where each animal spitted. Now he wants to know if in the zoo there are two camels, which spitted at each other. Help him to solve this task.\n\nThe trajectory of a camel's spit is an arc, i.e. if the camel in position *x* spits *d* meters right, he can hit only the camel in position *x*<=+<=*d*, if such a camel exists.",
"input": "",
"output": "```python\nn = int(input())\r\na = 0\r\nm = []\r\nfor i in range(n):\r\n x, d = map(int, input().split())\r\n\r\n a = x + d\r\n m.append(a)\r\n if m.count(d) == True:\r\n print('YES')\r\n else:\r\n print('NO')\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "At the children's day, the child came to Picks's house, and messed his house up. Picks was angry at him. A lot of important things were lost, in particular the favorite set of Picks.\n\nFortunately, Picks remembers something about his set *S*:\n - its elements were distinct integers from 1 to *limit*; - the value of was equal to *sum*; here *lowbit*(*x*) equals 2*k* where *k* is the position of the first one in the binary representation of *x*. For example, *lowbit*(100102)<==<=102,<=*lowbit*(100012)<==<=12,<=*lowbit*(100002)<==<=100002 (binary representation). \nCan you help Picks and find any set *S*, that satisfies all the above conditions?",
"input": "",
"output": "```python\ns,t = map(int,input().split())\r\nc = {}\r\nfor i in range(1,t+1):\r\n l = 0\r\n tmp = i\r\n while tmp%2==0:\r\n tmp /= 2\r\n l += 1\r\n if l in c:\r\n c[l] += 1\r\n else:\r\n c[l] = 1\r\n\r\nb = bin(s)[2:][::-1]\r\n\r\nused = {}\r\nfor i in range(len(b)):\r\n if b[i] == '1':\r\n if i in c and c[i] > 0:\r\n c[i] -= 1\r\n if i in used:\r\n used[i] += 1\r\n else:\r\n used[i] = 1\r\n else:\r\n sm = 0\r\n for j in range(i):\r\n if j in c and c[j] > 0:\r\n sm += c[j]*(2**j)\r\n if sm < 2**i:\r\n print(-1)\r\n break\r\n else:\r\n sm = 0\r\n for j in range(i-1,-1,-1):\r\n if j in c and c[j] > 0:\r\n if sm+c[j]*(2**j) == 2**i:\r\n if j in used:\r\n used[j] += c[j]\r\n else:\r\n used[j] = c[j]\r\n c[j] = 0\r\n sm += c[j]*(2**j)\r\n break\r\n elif sm+c[j]*(2**j)<2**i:\r\n if j in used:\r\n used[j] += c[j]\r\n else:\r\n used[j] = c[j]\r\n c[j] = 0\r\n sm += c[j]*(2**j)\r\n else:\r\n d = (2**i-sm)//(2**j)\r\n if j in used:\r\n used[j] += d\r\n else:\r\n used[j] = d\r\n c[j] -= d\r\n sm += d*(2**j)\r\nelse:\r\n lst = []\r\n nonz = sum([used[i] for i in used])\r\n for i in range(1,t+1):\r\n if nonz == 0:\r\n break\r\n l = 0\r\n tmp = i\r\n while tmp%2==0:\r\n tmp /= 2\r\n l += 1\r\n if l in used and used[l] >0:\r\n used[l] -= 1\r\n nonz -= 1\r\n lst.append(i) \r\n print(len(lst))\r\n print(*lst)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word *s*. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word \"hello\". For example, if Vasya types the word \"ahhellllloou\", it will be considered that he said hello, and if he types \"hlelo\", it will be considered that Vasya got misunderstood and he didn't manage to say hello. Determine whether Vasya managed to say hello by the given word *s*.",
"input": "",
"output": "```python\ns = input()\r\ncheck = False\r\nwhile s.count(\"h\") > 1:\r\n s = s.replace(\"h\", \"\",1) \r\nwhile s.count(\"h\") == 1:\r\n for i in s:\r\n if i == \"h\":\r\n a , b = s.split(i)\r\n s = b\r\n if s[0] == \"e\":\r\n while s.count(\"e\") > 1:\r\n s = s.replace(\"e\", \"\",1) \r\n while s.count(\"e\") == 1:\r\n for i in s:\r\n if i == \"e\":\r\n a , b = s.split(i)\r\n s = b\r\n if s[0] == \"l\" and s[1] == \"l\" :\r\n while s.count(\"l\") > 1:\r\n s = s.replace(\"l\", \"\",1) \r\n while s.count(\"l\") == 1:\r\n for i in s:\r\n if i == \"l\":\r\n a , b = s.split(i)\r\n s = b \r\n if s[0] == \"o\" :\r\n while s.count(\"o\") > 1:\r\n s = s.replace(\"o\", \"\",1) \r\n while s.count(\"o\") == 1:\r\n for i in s:\r\n if i == \"o\":\r\n a , b = s.split(i)\r\n s = b\r\n check = True\r\nif check:\r\n print(\"YES\")\r\nelse:\r\n print(\"NO\") \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "The last stage of Football World Cup is played using the play-off system.\n\nThere are *n* teams left in this stage, they are enumerated from 1 to *n*. Several rounds are held, in each round the remaining teams are sorted in the order of their ids, then the first in this order plays with the second, the third — with the fourth, the fifth — with the sixth, and so on. It is guaranteed that in each round there is even number of teams. The winner of each game advances to the next round, the loser is eliminated from the tournament, there are no draws. In the last round there is the only game with two remaining teams: the round is called the Final, the winner is called the champion, and the tournament is over.\n\nArkady wants his two favorite teams to play in the Final. Unfortunately, the team ids are already determined, and it may happen that it is impossible for teams to meet in the Final, because they are to meet in some earlier stage, if they are strong enough. Determine, in which round the teams with ids *a* and *b* can meet.",
"input": "",
"output": "```python\nn, a, b = map(int, input().split())\r\nans = 0\r\na -= 1\r\nb -= 1\r\nwhile n > 2:\r\n n //= 2\r\n a //= 2\r\n b //= 2\r\n ans += 1\r\n if a == b:\r\n print(ans)\r\n break\r\nelse:\r\n print(\"Final!\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.\n\nMarmot brought Mole *n* ordered piles of worms such that *i*-th pile contains *a**i* worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to *a*1, worms in second pile are labeled with numbers *a*1<=+<=1 to *a*1<=+<=*a*2 and so on. See the example for a better understanding.\n\nMole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.\n\nPoor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.",
"input": "",
"output": "```python\ndef solucion(num_W, label_j_W):\r\n lista_int = []\r\n valor = 0\r\n lista_2 = []\r\n for i in range(len(num_W)):\r\n lista_int.append(valor+num_W[i])\r\n valor += num_W[i]\r\n label_j_W_2 = sorted(label_j_W)\r\n for i in range(len(label_j_W_2)):\r\n contador = lista_int[0]\r\n for j in range(len(lista_int)):\r\n if label_j_W_2[i] <= contador:\r\n lista_2.append(j+1)\r\n break\r\n else:\r\n if j+1 < len(lista_int):\r\n contador = lista_int[j+1]\r\n else:\r\n break\r\n for i in range(len(lista_2)):\r\n if label_j_W[i] != label_j_W_2[i]:\r\n print(lista_2[label_j_W_2.index(label_j_W[i])])\r\n else:\r\n print(lista_2[i])\r\ndef main():\r\n '''Funcion principal'''\r\n input()\r\n num_W = [int(x) for x in input().split()]\r\n input()\r\n label_j_W = [int(x) for x in input().split()]\r\n solucion(num_W, label_j_W)\r\n\r\nmain()\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Little boy Petya loves stairs very much. But he is bored from simple going up and down them — he loves jumping over several stairs at a time. As he stands on some stair, he can either jump to the next one or jump over one or two stairs at a time. But some stairs are too dirty and Petya doesn't want to step on them.\n\nNow Petya is on the first stair of the staircase, consisting of *n* stairs. He also knows the numbers of the dirty stairs of this staircase. Help Petya find out if he can jump through the entire staircase and reach the last stair number *n* without touching a dirty stair once.\n\nOne has to note that anyway Petya should step on the first and last stairs, so if the first or the last stair is dirty, then Petya cannot choose a path with clean steps only.",
"input": "",
"output": "```python\nn,m=map(int,input().split())\r\nx=list(map(int,input().split()))\r\nif n in x:\r\n print(\"NO\")\r\nelse:\r\n for i in range(1,len(x)):\r\n if x[i]-x[i-1]>3:\r\n print(\"NO\")\r\n break\r\n else:\r\n print(\"YES\")\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Two positive integers *a* and *b* have a sum of *s* and a bitwise XOR of *x*. How many possible values are there for the ordered pair (*a*,<=*b*)?",
"input": "",
"output": "```python\nfor _ in range(1):\r\n add,xor_n=map(int,input().split())\r\n if add < xor_n:\r\n print(0)\r\n continue\r\n d=add-xor_n\r\n if d % 2==1:\r\n print(0)\r\n continue\r\n d//=2\r\n xor=bin(xor_n).replace(\"0b\",\"\")\r\n sub=0\r\n if xor_n & d==0:\r\n if add==xor_n:\r\n sub=2\r\n print(2**xor.count('1')-sub)\r\n else:\r\n print(0)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "An African crossword is a rectangular table *n*<=×<=*m* in size. Each cell of the table contains exactly one letter. This table (it is also referred to as grid) contains some encrypted word that needs to be decoded.\n\nTo solve the crossword you should cross out all repeated letters in rows and columns. In other words, a letter should only be crossed out if and only if the corresponding column or row contains at least one more letter that is exactly the same. Besides, all such letters are crossed out simultaneously.\n\nWhen all repeated letters have been crossed out, we should write the remaining letters in a string. The letters that occupy a higher position follow before the letters that occupy a lower position. If the letters are located in one row, then the letter to the left goes first. The resulting word is the answer to the problem.\n\nYou are suggested to solve an African crossword and print the word encrypted there.",
"input": "",
"output": "```python\nn,m=map(int,input().split()) ; arr=[]\r\nfor i in range(n):\r\n x=input()\r\n arr.append(x)\r\nfor h in range(n):\r\n for i in range(m):\r\n c=0\r\n let=arr[h][i]\r\n if let.isalpha():\r\n for j in range(h+1,n):\r\n if arr[j][i]==let:\r\n arr[j]=arr[j].replace(let,\"0\") ; c+=1\r\n if c>0:\r\n arr[h]=arr[h].replace(let,\"0\")\r\n\r\n \r\n \r\n \r\ns=\"\" \r\nfor i in range(n):\r\n for j in range(m):\r\n let=arr[i][j]\r\n if let.isalpha():\r\n if arr[i].count(let)>1:\r\n arr[i]=arr[i].replace(let,'0')\r\n else:\r\n s+=let\r\nprint(s)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "The winner of the card game popular in Berland \"Berlogging\" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line \"name score\", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to *m*) at the end of the game, than wins the one of them who scored at least *m* points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points.",
"input": "",
"output": "```python\nimport sys\r\n\r\n\r\ndef parse_line(line):\r\n line = line.strip().split()\r\n name = line[0]\r\n score = int(line[1])\r\n return name, score\r\n\r\n\r\ndef update_scores(name, score, scores, winner):\r\n if name not in scores:\r\n scores[name] = score\r\n else:\r\n scores[name] += score\r\n if winner == '':\r\n winner = name\r\n else:\r\n if scores[name] > scores[winner]:\r\n winner = name\r\n return winner\r\n\r\n\r\nlines = sys.stdin.readlines()\r\nrounds = int(lines[0].strip())\r\n\r\n\r\nscores = {}\r\nwinner = ''\r\nfor round in range(1, rounds+1):\r\n name, score = parse_line(lines[round])\r\n winner = update_scores(name, score, scores, winner)\r\n\r\n\r\nprint(winner)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Lenny is playing a game on a 3<=×<=3 grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be switched off, if it was switched off then it will be switched on.\n\nLenny has spent some time playing with the grid and by now he has pressed each light a certain number of times. Given the number of times each light is pressed, you have to print the current state of each light.",
"input": "",
"output": "```python\nn = int(input())\ndef dd(n):\n if len(str(n)) != len(set(list(str(n)))):\n return False\n else:\n return True\nn += 1\nwhile not dd(n):\n n += 1\n\nprint(n)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are given two arrays *A* and *B* consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose *k* numbers in array *A* and choose *m* numbers in array *B* so that any number chosen in the first array is strictly less than any number chosen in the second array.",
"input": "",
"output": "```python\nfrom sys import stdin\r\n_input = stdin.readline\r\n_int = int\r\ncount, cnt = [_int(i) for i in _input().split()]\r\nk, m = [_int(i) for i in _input().split()]\r\na = [_int(i) for i in _input().split()]\r\nb = [_int(i) for i in _input().split()]\r\na = a[k-1]\r\nb = b[cnt - m]\r\nif a < b:\r\n print('YES')\r\nelse:\r\n print('NO')\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her *n* students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often oddly shaped, interlocking and tessellating pieces).\n\nThe shop assistant told the teacher that there are *m* puzzles in the shop, but they might differ in difficulty and size. Specifically, the first jigsaw puzzle consists of *f*1 pieces, the second one consists of *f*2 pieces and so on.\n\nMs. Manana doesn't want to upset the children, so she decided that the difference between the numbers of pieces in her presents must be as small as possible. Let *A* be the number of pieces in the largest puzzle that the teacher buys and *B* be the number of pieces in the smallest such puzzle. She wants to choose such *n* puzzles that *A*<=-<=*B* is minimum possible. Help the teacher and find the least possible value of *A*<=-<=*B*.",
"input": "",
"output": "```python\nn,m=map(int,input().split())\r\nf=list(map(int,input().split()))\r\nf.sort()\r\nleast=f[n-1]-f[0]\r\nfor i in range(1,m-n+1):\r\n dif=f[i+n-1]-f[i]\r\n if dif2:\r\n print('NO')\r\n else:\r\n if ans==2 or ans==4:\r\n print('YES')\r\n else:\r\n print('NO')\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\"\n\nCould you pass the interview in the machine vision company in IT City?",
"input": "",
"output": "```python\na=input()\r\nb=5**int(a)\r\nlasttwodigit=b%100\r\nprint(lasttwodigit)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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*.\n\nAs Petya is older, he wants to take the chores with complexity larger than some value *x* (*h**i*<=><=*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*).\n\nIn how many ways can they choose an integer *x* so that Petya got exactly *a* chores and Vasya got exactly *b* chores?",
"input": "",
"output": "```python\n# Wadea #\r\n\r\nn,a,b=map(int ,input().split())\r\narr=list(map(int ,input().split()))\r\narr.sort()\r\nk=arr[b-1]\r\ng=arr[b]\r\nprint(int(abs(k-g)))\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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:\n\n1. Each domino completely covers two squares.\n\n2. No two dominoes overlap.\n\n3. Each domino lies entirely inside the board. It is allowed to touch the edges of the board.\n\nFind the maximum number of dominoes, which can be placed under these restrictions.",
"input": "",
"output": "```python\nN,M = input().split()\r\nprint(int(N)*int(M)//2)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vasya, or Mr. Vasily Petrov is a dean of a department in a local university. After the winter exams he got his hands on a group's gradebook.\n\nOverall the group has *n* students. They received marks for *m* subjects. Each student got a mark from 1 to 9 (inclusive) for each subject.\n\nLet's consider a student the best at some subject, if there is no student who got a higher mark for this subject. Let's consider a student successful, if there exists a subject he is the best at.\n\nYour task is to find the number of successful students in the group.",
"input": "",
"output": "```python\nn,m = map(int,input().split())\r\nll = []\r\nl = [0] * m\r\nfor i in range(n):\r\n ll.append(input().strip())\r\n for j in range(m):\r\n l[j] = max(l[j],int(ll[-1][j]))\r\nans = 0\r\nfor i in ll:\r\n for j in range(m):\r\n if int(i[j]) == l[j]:\r\n ans += 1\r\n break\r\nprint(ans)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "So, the New Year holidays are over. Santa Claus and his colleagues can take a rest and have guests at last. When two \"New Year and Christmas Men\" meet, thear assistants cut out of cardboard the letters from the guest's name and the host's name in honor of this event. Then the hung the letters above the main entrance. One night, when everyone went to bed, someone took all the letters of our characters' names. Then he may have shuffled the letters and put them in one pile in front of the door.\n\nThe next morning it was impossible to find the culprit who had made the disorder. But everybody wondered whether it is possible to restore the names of the host and his guests from the letters lying at the door? That is, we need to verify that there are no extra letters, and that nobody will need to cut more letters.\n\nHelp the \"New Year and Christmas Men\" and their friends to cope with this problem. You are given both inscriptions that hung over the front door the previous night, and a pile of letters that were found at the front door next morning.",
"input": "",
"output": "```python\na=input()\r\na=list(a)\r\nb=input()\r\nb=list(b)\r\nc=input()\r\nl=list(c)\r\nfor i in a:\r\n if i in l:\r\n l.remove(i)\r\n a.remove(i)\r\nfor i in b:\r\n if i in l:\r\n l.remove(i)\r\n b.remove(i)\r\nprint('YES' if len(l)==0 and len(a)==0 and len(b)==0 else 'NO')\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Once Bob got to a sale of old TV sets. There were *n* TV sets at that sale. TV set with index *i* costs *a**i* bellars. Some TV sets have a negative price — their owners are ready to pay Bob if he buys their useless apparatus. Bob can «buy» any TV sets he wants. Though he's very strong, Bob can carry at most *m* TV sets, and he has no desire to go to the sale for the second time. Please, help Bob find out the maximum sum of money that he can earn.",
"input": "",
"output": "```python\n# -*- coding: utf-8 -*-\n\"\"\"Codeforce\n\nAutomatically generated by Colaboratory.\n\nOriginal file is located at\n https://colab.research.google.com/drive/1vkqd1IDYYeIi4VIH6yqQEhbS4qcGMzLO\n\"\"\"\n\nn , m = map(int , input().split())\ntv_price = list(map(int , input().split()))\ntv_price = sorted(tv_price)\n\n\nearning = 0\n\nfor i in range(m):\n if tv_price[i] < 0:\n earning += tv_price[i]\n else:\n break\n\nprint(earning)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array *a* consisting of *n* distinct integers.\n\nUnfortunately, the size of *a* is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question correctly: is it possible to sort the array *a* (in increasing order) by reversing exactly one segment of *a*? See definitions of segment and reversing in the notes.",
"input": "",
"output": "```python\nn=int(input())\r\nA=input().split()\r\nN={}\r\nfor x in range(n):\r\n N[int(A[x])]=x\r\nM=sorted(N.items())\r\nP=[]\r\nQ=[]\r\nfor x in range(n):\r\n if x!=M[x][1]:\r\n P.append(M[x][1])\r\n Q.append(x)\r\nif P==sorted(Q, reverse=True):\r\n print('yes')\r\nelse:\r\n print('no')\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Little boy Petya loves stairs very much. But he is bored from simple going up and down them — he loves jumping over several stairs at a time. As he stands on some stair, he can either jump to the next one or jump over one or two stairs at a time. But some stairs are too dirty and Petya doesn't want to step on them.\n\nNow Petya is on the first stair of the staircase, consisting of *n* stairs. He also knows the numbers of the dirty stairs of this staircase. Help Petya find out if he can jump through the entire staircase and reach the last stair number *n* without touching a dirty stair once.\n\nOne has to note that anyway Petya should step on the first and last stairs, so if the first or the last stair is dirty, then Petya cannot choose a path with clean steps only.",
"input": "",
"output": "```python\nn, m=map (int, input ().split ())\r\nl=[]\r\nif m>0:\r\n\tk=list(map (int, input ().split ()))\r\n\tl=k\r\nif (1 in l) or (n in l):\r\n\tprint ('NO')\r\nelif m==0:\r\n\tprint ('YES' ) \r\nelse:\r\n\tl.sort() \r\n\tflag =0\r\n\tfor i in range(m-2):\r\n\t\tif l[i+1]-l[i] ==1 and l[i+2]-l[i+1] ==1:\r\n\t\t\tflag=1\r\n\t\t\tbreak\r\n\tif flag ==1:\r\n\t\tprint ('NO')\r\n\telse:\r\n\t\tprint ('YES')\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Ted has a pineapple. This pineapple is able to bark like a bulldog! At time *t* (in seconds) it barks for the first time. Then every *s* seconds after it, it barks twice with 1 second interval. Thus it barks at times *t*, *t*<=+<=*s*, *t*<=+<=*s*<=+<=1, *t*<=+<=2*s*, *t*<=+<=2*s*<=+<=1, etc.\n\nBarney woke up in the morning and wants to eat the pineapple, but he can't eat it when it's barking. Barney plans to eat it at time *x* (in seconds), so he asked you to tell him if it's gonna bark at that time.",
"input": "",
"output": "```python\nt,s,x=map(int,input().split())\r\ni=1\r\nwhile i= 6:\r\n print(6)\r\n else:\r\n print(5)\r\nelif m in lst2:\r\n if d == 1:\r\n print(4)\r\n else:\r\n print(5)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Olga came to visit the twins Anna and Maria and saw that they have many cookies. The cookies are distributed into bags. As there are many cookies, Olga decided that it's no big deal if she steals a bag. However, she doesn't want the sisters to quarrel because of nothing when they divide the cookies. That's why Olga wants to steal a bag with cookies so that the number of cookies in the remaining bags was even, that is, so that Anna and Maria could evenly divide it into two (even 0 remaining cookies will do, just as any other even number). How many ways there are to steal exactly one cookie bag so that the total number of cookies in the remaining bags was even?",
"input": "",
"output": "```python\nn=int(input())\na=list(map(int,input().split()))\nk=sum(a)%2\nc=0\nfor i in range(n):\n if a[i]%2==k:\n c+=1\nprint(c)\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "As it's the first of April, Heidi is suspecting that the news she reads today are fake, and she does not want to look silly in front of all the contestants. She knows that a newspiece is fake if it contains heidi as a subsequence. Help Heidi assess whether the given piece is true, but please be discreet about it...",
"input": "",
"output": "```python\nx = input()\nif (\"h\" in x):\n if (\"e\" in x):\n if (\"i\" in x):\n if (\"d\" in x):\n if (\"i\" in x):\n print (\"YES\")\nelse:\n print (\"NO\")\n \t \t \t\t\t \t\t \t \t\t \t\t \t \t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "The following problem is well-known: given integers *n* and *m*, calculate\n\nwhere 2*n*<==<=2·2·...·2 (*n* factors), and denotes the remainder of division of *x* by *y*.\n\nYou are asked to solve the \"reverse\" problem. Given integers *n* and *m*, calculate",
"input": "",
"output": "```python\nn = int(input())\r\nm = int(input())\r\n\r\nif m == 1:\r\n print(1)\r\nelse:\r\n x = str(bin(m))\r\n print(int(x[-n:],2))\r\n\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vasya plays the sleuth with his friends. The rules of the game are as follows: those who play for the first time, that is Vasya is the sleuth, he should investigate a \"crime\" and find out what is happening. He can ask any questions whatsoever that can be answered with \"Yes\" or \"No\". All the rest agree beforehand to answer the questions like that: if the question’s last letter is a vowel, they answer \"Yes\" and if the last letter is a consonant, they answer \"No\". Of course, the sleuth knows nothing about it and his task is to understand that.\n\nUnfortunately, Vasya is not very smart. After 5 hours of endless stupid questions everybody except Vasya got bored. That’s why Vasya’s friends ask you to write a program that would give answers instead of them.\n\nThe English alphabet vowels are: A, E, I, O, U, Y\n\nThe English alphabet consonants are: B, C, D, F, G, H, J, K, L, M, N, P, Q, R, S, T, V, W, X, Z",
"input": "",
"output": "```python\ns = input()\r\nc = len(s)-1\r\n \r\nif (s[c].isalpha()):\r\n\tif (s[c].upper()=='A' or s[c].upper()=='E' or s[c].upper()=='I' or s[c].upper()=='O' or s[c].upper()=='U' or s[c].upper()=='Y'):\r\n\t\tprint(\"YES\")\r\n\t\texit()\r\n\telse:\r\n\t\tprint(\"NO\")\r\n\t\texit()\r\nelse:\r\n\tif (s[c-1].upper()=='A' or s[c-1].upper()=='E' or s[c-1].upper()=='I' or s[c-1].upper()=='O' or s[c-1].upper()=='U'or s[c-1].upper()=='Y'):\r\n\t\tprint(\"YES\")\r\n\t\texit()\r\n\telse:\r\n\t\tprint(\"NO\")\r\n\t\texit()\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Winnie-the-Pooh likes honey very much! That is why he decided to visit his friends. Winnie has got three best friends: Rabbit, Owl and Eeyore, each of them lives in his own house. There are winding paths between each pair of houses. The length of a path between Rabbit's and Owl's houses is *a* meters, between Rabbit's and Eeyore's house is *b* meters, between Owl's and Eeyore's house is *c* meters.\n\nFor enjoying his life and singing merry songs Winnie-the-Pooh should have a meal *n* times a day. Now he is in the Rabbit's house and has a meal for the first time. Each time when in the friend's house where Winnie is now the supply of honey is about to end, Winnie leaves that house. If Winnie has not had a meal the required amount of times, he comes out from the house and goes to someone else of his two friends. For this he chooses one of two adjacent paths, arrives to the house on the other end and visits his friend. You may assume that when Winnie is eating in one of his friend's house, the supply of honey in other friend's houses recover (most probably, they go to the supply store).\n\nWinnie-the-Pooh does not like physical activity. He wants to have a meal *n* times, traveling minimum possible distance. Help him to find this distance.",
"input": "",
"output": "```python\nfrom sys import stdin, stdout\r\nfrom functools import reduce\r\n\r\ndef main():\r\n n=int(stdin.readline().strip())-1\r\n a=int(stdin.readline().strip())\r\n b=int(stdin.readline().strip())\r\n c=int(stdin.readline().strip())\r\n if n<=0: return 0\r\n x=min(a, min(b, c))\r\n if x==a or x==b: return x*n\r\n else: return min(a,b)+c*n-1\r\n\r\nstdout.write(str(main()))\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him.\n\nOne day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For each contest where this coder participated, he wrote out a single non-negative number — the number of points his favorite coder earned in the contest. Vasya wrote out the points for the contest in the order, in which the contests run (naturally, no two contests ran simultaneously).\n\nVasya considers a coder's performance in a contest amazing in two situations: he can break either his best or his worst performance record. First, it is amazing if during the contest the coder earns strictly more points that he earned on each past contest. Second, it is amazing if during the contest the coder earns strictly less points that he earned on each past contest. A coder's first contest isn't considered amazing. Now he wants to count the number of amazing performances the coder had throughout his whole history of participating in contests. But the list of earned points turned out long and Vasya can't code... That's why he asks you to help him.",
"input": "",
"output": "```python\nn = int(input())\na = [int(x) for x in input().split()]\nans = 0\nmn = mx = a[0]\nfor x in a:\n if x > mx:\n ans += 1\n mx = x\n if x < mn:\n ans += 1\n mn = x\nprint(ans)\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has *n* students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times.\n\nThe head of the SSU OPTC is recently gathering teams to participate in the world championship. Each team must consist of exactly three people, at that, any person cannot be a member of two or more teams. What maximum number of teams can the head make if he wants each team to participate in the world championship with the same members at least *k* times?",
"input": "",
"output": "```python\nn, k = map(int, input().split())\r\narr= list(map(int, input().split()))\r\n\r\ncount = 0\r\n\r\nfor i in arr:\r\n if 5-i >= k:\r\n count += 1\r\n\r\nans= count // 3\r\n\r\nprint(ans)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.\n\nPetya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find out if the given number *n* is almost lucky.",
"input": "",
"output": "```python\ns=input()\r\nc=0\r\nfor i in s:\r\n if i=='4' or i=='7':\r\n c+=1\r\nl=[4,7,47,74,447,444,474,744,747,774,477]\r\nd=0\r\nfor j in l:\r\n if int(s)>j:\r\n if int(s)%j==0:\r\n d+=1\r\nif d!=0 or c==len(s):\r\n print('YES')\r\nelse:\r\n print('NO')\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. \"Piece of cake\" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.",
"input": "",
"output": "```python\na=int(input())\r\nb=[]\r\nfor i in range(a):\r\n b.append(list(map(int,input().split(\" \")[:3])))\r\nr=0\r\nfor j in range(len(b)):\r\n r=r+sum(b[j])\r\nif(r==0):\r\n print(\"YES\")\r\nelse:\r\n print(\"NO\")\r\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Theatre Square in the capital city of Berland has a rectangular shape with the size *n*<=×<=*m* meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size *a*<=×<=*a*.\n\nWhat is the least number of flagstones needed to pave the Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square.",
"input": "",
"output": "```python\nimport math\r\nm,n,a=map(int,input().split())\r\nx=math.ceil(m/a)\r\ny=math.ceil(n/a)\r\nif x>1 and y>1:\r\n t=x+y\r\nif x<=1 and y<=1:\r\n t=1\r\nif x>1 and y<=1:\r\n t=x\r\nif x<=1 and y>1:\r\n t=y\r\nprint(t)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nNow 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.\n\nPearlo 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.",
"input": "",
"output": "```python\na=input()\r\nb=input()\r\nc=input()\r\na=list(a)\r\nb=list(b)\r\nc=list(c)\r\nif c[::-1]==a:\r\n print(\"YES\")\r\nelif b[0]==b[2]:\r\n print(\"YES\")\r\nelse:\r\n print(\"NO\")\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "One spring day on his way to university Lesha found an array *A*. Lesha likes to split arrays into several parts. This time Lesha decided to split the array *A* into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array *A*.\n\nLesha is tired now so he asked you to split the array. Help Lesha!",
"input": "",
"output": "```python\n#For fast I/O\r\nimport sys\r\ninput = lambda: sys.stdin.readline().strip()\r\n\r\nn = int(input())\r\nl = [int(i) for i in input().split()]\r\n\r\ns = sum(l)\r\nif s != 0:\r\n\tprint('YES')\r\n\tprint(1)\r\n\tprint(1,n)\r\nelse:\r\n\tpossible = False\r\n\r\n\tfor i in range(n):\r\n\t\tif l[i] != 0:\r\n\t\t\tpossible = True\r\n\t\t\tprint('YES')\r\n\t\t\tprint(2)\r\n\t\t\tprint(1,i+1)\r\n\t\t\tprint(i+2,n)\r\n\t\t\tbreak\r\n\r\n\tif not possible:\r\n\t\tprint('NO')\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Petya is preparing for IQ test and he has noticed that there many problems like: you are given a sequence, find the next number. Now Petya can solve only problems with arithmetic or geometric progressions.\n\nArithmetic progression is a sequence *a*1, *a*1<=+<=*d*, *a*1<=+<=2*d*, ..., *a*1<=+<=(*n*<=-<=1)*d*, where *a*1 and *d* are any numbers.\n\nGeometric progression is a sequence *b*1, *b*2<==<=*b*1*q*, ..., *b**n*<==<=*b**n*<=-<=1*q*, where *b*1<=≠<=0, *q*<=≠<=0, *q*<=≠<=1. \n\nHelp Petya and write a program to determine if the given sequence is arithmetic or geometric. Also it should found the next number. If the sequence is neither arithmetic nor geometric, print 42 (he thinks it is impossible to find better answer). You should also print 42 if the next element of progression is not integer. So answer is always integer.",
"input": "",
"output": "```python\nnumbers = list(map(int,input().split()))\r\narithmetic_prog = numbers[1] - numbers[0]\r\ngeometric_prog = numbers[1] / numbers[0]\r\n\r\nif numbers[3]-numbers[2] == arithmetic_prog and numbers[2]-numbers[1] == arithmetic_prog:\r\n print(int(numbers[-1]+arithmetic_prog))\r\nelif numbers[3]/numbers[2] == geometric_prog and numbers[2]/numbers[1] == geometric_prog:\r\n print(int(numbers[-1]*geometric_prog))\r\nelse:\r\n print(42)\r\n \r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A soldier wants to buy *w* bananas in the shop. He has to pay *k* dollars for the first banana, 2*k* dollars for the second one and so on (in other words, he has to pay *i*·*k* dollars for the *i*-th banana). \n\nHe has *n* dollars. How many dollars does he have to borrow from his friend soldier to buy *w* bananas?",
"input": "",
"output": "```python\nk,n,w=map(int,input().split())\nsum=0\ntc=0\nfor i in range(w+1):\n sum=sum+i\ntc=sum*k\nprint(tc-n) \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Some days ago, I learned the concept of LCM (least common multiple). I've played with it for several times and I want to make a big number with it.\n\nBut I also don't want to use many numbers, so I'll choose three positive integers (they don't have to be distinct) which are not greater than *n*. Can you help me to find the maximum possible least common multiple of these three integers?",
"input": "",
"output": "```python\nfrom math import gcd\r\n\r\nn = int(input())\r\n\r\nif n <= 3:\r\n print([0, 1, 2, 6][n])\r\n exit()\r\n\r\nprint(\r\n max(\r\n n * (n-1) * (n-2) // gcd(n, n-2),\r\n (n-1) * (n-2) * (n-3) // gcd(n-1, n-3)\r\n )\r\n)\r\n\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You helped Dima to have a great weekend, but it's time to work. Naturally, Dima, as all other men who have girlfriends, does everything wrong.\n\nInna and Dima are now in one room. Inna tells Dima off for everything he does in her presence. After Inna tells him off for something, she goes to another room, walks there in circles muttering about how useless her sweetheart is. During that time Dima has time to peacefully complete *k*<=-<=1 tasks. Then Inna returns and tells Dima off for the next task he does in her presence and goes to another room again. It continues until Dima is through with his tasks.\n\nOverall, Dima has *n* tasks to do, each task has a unique number from 1 to *n*. Dima loves order, so he does tasks consecutively, starting from some task. For example, if Dima has 6 tasks to do in total, then, if he starts from the 5-th task, the order is like that: first Dima does the 5-th task, then the 6-th one, then the 1-st one, then the 2-nd one, then the 3-rd one, then the 4-th one.\n\nInna tells Dima off (only lovingly and appropriately!) so often and systematically that he's very well learned the power with which she tells him off for each task. Help Dima choose the first task so that in total he gets told off with as little power as possible.",
"input": "",
"output": "```python\ndef read():\r\n n, k = list(map(int, input().split()))\r\n powers = list(map(int, input().split()))\r\n return n, k, powers\r\n\r\n\r\ndef get_min_power(n, k, powers):\r\n start_task = 0\r\n mins = []\r\n for i in range(k):\r\n s = 0\r\n for j in range(i, n, k):\r\n s += powers[j]\r\n mins.append(s)\r\n task = min(mins)\r\n return mins.index(task) + 1\r\n\r\ndef main():\r\n n, k, powers = read()\r\n print(get_min_power(n, k, powers))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "An *n*<=×<=*n* table *a* is defined as follows:\n - The first row and the first column contain ones, that is: *a**i*,<=1<==<=*a*1,<=*i*<==<=1 for all *i*<==<=1,<=2,<=...,<=*n*. - Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the remaining elements are defined by the formula *a**i*,<=*j*<==<=*a**i*<=-<=1,<=*j*<=+<=*a**i*,<=*j*<=-<=1. \nThese conditions define all the values in the table.\n\nYou are given a number *n*. You need to determine the maximum value in the *n*<=×<=*n* table defined by the rules above.",
"input": "",
"output": "```python\nn = int(input())\r\nx = [0,1,2,6,20,70,252,924,3432,12870,48620]\r\nprint(x[n])\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A bracket sequence is a string, containing only characters \"(\", \")\", \"[\" and \"]\".\n\nA correct bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters \"1\" and \"+\" between the original characters of the sequence. For example, bracket sequences \"()[]\", \"([])\" are correct (the resulting expressions are: \"(1)+[1]\", \"([1+1]+1)\"), and \"](\" and \"[\" are not. The empty string is a correct bracket sequence by definition.\n\nA substring *s*[*l*... *r*] (1<=≤<=*l*<=≤<=*r*<=≤<=|*s*|) of string *s*<==<=*s*1*s*2... *s*|*s*| (where |*s*| is the length of string *s*) is the string *s**l**s**l*<=+<=1... *s**r*. The empty string is a substring of any string by definition.\n\nYou are given a bracket sequence, not necessarily correct. Find its substring which is a correct bracket sequence and contains as many opening square brackets «[» as possible.",
"input": "",
"output": "```python\n'''input\n((()))([]\n'''\nfrom sys import stdin\n\n\ndef check_valid(string):\n\tstack = []\n\tfor i in string:\n\t\tif i in ['(', '[']:\n\t\t\tstack.append(i)\n\t\telif i == ')':\n\t\t\tif len(stack) > 0:\n\t\t\t\tif stack[-1] == '(':\n\t\t\t\t\tstack.pop()\n\t\t\t\t\tcontinue\n\t\t\treturn False\n\t\telif i == ']':\n\t\t\tif len(stack) > 0:\n\t\t\t\tif stack[-1] == '[':\n\t\t\t\t\tstack.pop()\n\t\t\t\t\tcontinue\n\t\t\treturn False\n \n\treturn len(stack) == 0\n \n\ndef merge(index):\n\t# refining\n\taux = []\n\tif len(index) > 0:\n\t\tstart = index[0][0]\n\t\tend = index[0][1]\n\t\tfor i in range(1, len(index)):\n\t\t\ts, e = index[i]\n\t\t\tif e <= end:\n\t\t\t\tpass\n\t\t\telif s >= end:\n\t\t\t\taux.append([start, end])\n\t\t\t\tstart, end = s, e\n\t\taux.append([start, end])\n\tindex = aux\n\n\n\n\n\t# acutal merging\n\taux = []\n\tif len(index) > 0:\n\t\taux = [index[0]]\n\t\tfor i in range(1, len(index)):\n\t\t\tif index[i][0] == aux[-1][1] + 1:\n\t\t\t\taux[-1][1] = index[i][1]\n\t\t\telse:\n\t\t\t\tif check_valid(string[aux[-1][1] + 1: index[i][0]]):\n\t\t\t\t\taux[-1][1] = index[i][1]\n\t\t\t\telse:\n\t\t\t\t\taux.append(index[i])\n\treturn aux\n \n\n# main starts\nstring = stdin.readline().strip()\nstack = []\nindex = []\nstart = -1\nend = -1\nfor i in range(len(string)):\n\tif string[i] == '(':\n\t\tstack.append(i)\n\telif string[i] == '[':\n\t\tstack.append(i)\n\n\telif string[i] == ')':\n\t\tif len(stack) > 0 and string[stack[-1]] == '(':\n\t\t\tindex.append([stack[-1], i])\n\t\t\tstack.pop()\n\t\telse:\n\t\t\tstack = []\n\telif string[i] == ']':\n\t\tif len(stack) > 0 and string[stack[-1]] == '[':\n\t\t\tindex.append([stack[-1], i])\n\t\t\tstack.pop()\t\n\t\telse:\n\t\t\tstack = []\n\nindex.sort(key = lambda x:(x[0], x[1]))\n\n\nindex = merge(index)\ndiff = 0\nans = [-1, -1]\nfor i in index:\n\tstart, end = i\n\tc = string[start: end + 1].count('[')\n\tif diff < c :\n\t\tans = [start, end + 1]\n\t\tdiff = c\n\n\nprint(diff)\nprint(string[ans[0]: ans[1]])\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are given the current time in 24-hour format hh:mm. Find and print the time after *a* minutes.\n\nNote that you should find only the time after *a* minutes, see the examples to clarify the problem statement.\n\nYou can read more about 24-hour format here [https://en.wikipedia.org/wiki/24-hour_clock](https://en.wikipedia.org/wiki/24-hour_clock).",
"input": "",
"output": "```python\nl1 = [int(x) for x in input().split(\":\")]\r\nn = int(input())\r\nfinal = l1[0]*60+l1[1]+n\r\ntotal = 24*60\r\nthing = final%total\r\nprint(str(int(thing/60))+str(\":\")+str(thing%60))\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Kitahara Haruki has bought *n* apples for Touma Kazusa and Ogiso Setsuna. Now he wants to divide all the apples between the friends.\n\nEach apple weights 100 grams or 200 grams. Of course Kitahara Haruki doesn't want to offend any of his friend. Therefore the total weight of the apples given to Touma Kazusa must be equal to the total weight of the apples given to Ogiso Setsuna.\n\nBut unfortunately Kitahara Haruki doesn't have a knife right now, so he cannot split any apple into some parts. Please, tell him: is it possible to divide all the apples in a fair way between his friends?",
"input": "",
"output": "```python\nx = int(input())\r\nfrom collections import Counter\r\ny = map(int,input().split())\r\ny = Counter(y)\r\n# print(y)\r\ns = y[100]+y[200]*2\r\n# print(s)\r\nif s%2:\r\n print(\"NO\")\r\nelse:\r\n print(\"YES\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are given two integers $a$ and $b$. Moreover, you are given a sequence $s_0, s_1, \\dots, s_{n}$. All values in $s$ are integers $1$ or $-1$. It's known that sequence is $k$-periodic and $k$ divides $n+1$. In other words, for each $k \\leq i \\leq n$ it's satisfied that $s_{i} = s_{i - k}$.\n\nFind out the non-negative remainder of division of $\\sum \\limits_{i=0}^{n} s_{i} a^{n - i} b^{i}$ by $10^{9} + 9$.\n\nNote that the modulo is unusual!",
"input": "",
"output": "```python\nn, a, b, k = map(int,input().split())\r\ns = input()\r\n\r\ni = 0\r\nsu = []\r\n\r\nfor i in range(k):\r\n t = 0\r\n if s[i] == '+':\r\n for j in range(n // k + 1):\r\n if 0 <= n-k*j-i <= n:\r\n t += pow(a, n-k*j-i, 10**9+9)*pow(b, k*j+i, 10**9+9)\r\n else:\r\n for j in range(n // k + 1):\r\n if 0 <= n-k*j-i <= n:\r\n t -= pow(a, n-k*j-i, 10**9+9)*pow(b, k*j+i, 10**9+9)\r\n su.append(t)\r\n\r\nprint(sum(su) % (10**9+9))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Fox Ciel saw a large field while she was on a bus. The field was a *n*<=×<=*m* rectangle divided into 1<=×<=1 cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes. \n\nAfter seeing the field carefully, Ciel found that the crop plants of each cell were planted in following procedure:\n - Assume that the rows are numbered 1 to *n* from top to bottom and the columns are numbered 1 to *m* from left to right, and a cell in row *i* and column *j* is represented as (*i*,<=*j*). - First, each field is either cultivated or waste. Crop plants will be planted in the cultivated cells in the order of (1,<=1)<=→<=...<=→<=(1,<=*m*)<=→<=(2,<=1)<=→<=...<=→<=(2,<=*m*)<=→<=...<=→<=(*n*,<=1)<=→<=...<=→<=(*n*,<=*m*). Waste cells will be ignored. - Crop plants (either carrots or kiwis or grapes) will be planted in each cell one after another cyclically. Carrots will be planted in the first cell, then kiwis in the second one, grapes in the third one, carrots in the forth one, kiwis in the fifth one, and so on. \nThe following figure will show you the example of this procedure. Here, a white square represents a cultivated cell, and a black square represents a waste cell.\n\nNow she is wondering how to determine the crop plants in some certain cells.",
"input": "",
"output": "```python\n\r\ndef mi():\r\n\treturn map(int, input().split())\r\nn,m,k,t = mi()\r\nwasterowscount = [0]*(n+1)\r\nd = {0:'Carrots',1:'Kiwis',2:'Grapes'}\r\n\r\nwaste = [[]]*(n+1)\r\ndef fun(x,y):\r\n\tglobal waste\r\n\tif y in waste[x]:\r\n\t\tprint ('Waste')\r\n\t\treturn 0\r\n\tcur = (((x-1)*m-wasterowscount[x-1]))\r\n\tcur+=(y)\r\n\tfor i in range(wasterowscount[x]-wasterowscount[x-1]):\r\n\t\tif waste[x][i]countU:\r\n \r\n print(T.lower())\r\nif countLmaximum):\r\n maximum=col\r\n \r\n\r\nprint(maximum)\r\n\r\n\r\n\r\n\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are given a connected weighted undirected graph without any loops and multiple edges. \n\nLet us remind you that a graph's spanning tree is defined as an acyclic connected subgraph of the given graph that includes all of the graph's vertexes. The weight of a tree is defined as the sum of weights of the edges that the given tree contains. The minimum spanning tree (MST) of a graph is defined as the graph's spanning tree having the minimum possible weight. For any connected graph obviously exists the minimum spanning tree, but in the general case, a graph's minimum spanning tree is not unique.\n\nYour task is to determine the following for each edge of the given graph: whether it is either included in any MST, or included at least in one MST, or not included in any MST.",
"input": "",
"output": "```python\nN = 100010\r\nn, m = map(int, input().split())\r\n\r\nx = [0] * (N)\r\ny = [0] * (N)\r\nz = [0] * (N)\r\np = [0] * (N)\r\nans = [0] * (N)\r\nf = [False] * (N)\r\nh = [0] * (N)\r\npe = [0] * (N)\r\nd = [0] * (N)\r\nv = [[] for _ in range(N)]\r\n\r\n# Função para comparar arestas com base em seus pesos (z)\r\ndef cmp(i, j):\r\n return z[i] < z[j]\r\n\r\n# Função para encontrar o representante de um conjunto\r\ndef par(x):\r\n while pe[x]:\r\n x = pe[x]\r\n return x\r\n\r\n# Função para unir dois conjuntos\r\ndef uni(x, y):\r\n x = par(x)\r\n y = par(y)\r\n v[x].clear()\r\n v[y].clear()\r\n f[x] = False\r\n f[y] = False\r\n if x == y:\r\n return\r\n if h[x] > h[y]:\r\n pe[y] = x\r\n else:\r\n pe[x] = y\r\n if h[x] == h[y]:\r\n h[y] += 1\r\n\r\n# Função para adicionar uma aresta ao grafo\r\ndef add_edge(x, y, i):\r\n if x == y:\r\n return\r\n ans[i] = 1\r\n v[x].append((y, i))\r\n v[y].append((x, i))\r\n\r\n# Função de busca em profundidade (DFS)\r\ndef dfs(c, g, h):\r\n f[c] = True\r\n d[c] = h\r\n for i in v[c]:\r\n if not f[i[0]]:\r\n dfs(i[0], i[1], h + 1)\r\n d[c] = min(d[c], d[i[0]])\r\n elif i[1] != g:\r\n d[c] = min(d[c], d[i[0]])\r\n if d[c] == h:\r\n ans[g] = 2\r\n\r\n# Leitura das informações das arestas\r\nfor i in range(1, m + 1):\r\n x[i], y[i], z[i] = map(int, input().split())\r\n p[i] = i\r\n\r\n# Ordena as arestas com base em seus pesos\r\np.sort(key=lambda i: z[i])\r\n\r\ni = 1\r\nwhile i <= m:\r\n j = i\r\n while j <= m and z[p[j]] == z[p[i]]:\r\n add_edge(par(x[p[j]]), par(y[p[j]]), p[j])\r\n j += 1\r\n j = i\r\n while j <= m and z[p[j]] == z[p[i]]:\r\n k = par(x[p[j]])\r\n if not f[k]:\r\n dfs(k, 0, 0)\r\n j += 1\r\n j = i\r\n while j <= m and z[p[j]] == z[p[i]]:\r\n uni(x[p[j]], y[p[j]])\r\n j += 1\r\n i = j\r\n\r\n# Imprime o tipo de conectividade para cada aresta\r\nfor i in range(1, m + 1):\r\n if ans[i] == 0:\r\n print(\"none\")\r\n elif ans[i] == 1:\r\n print(\"at least one\")\r\n else:\r\n print(\"any\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Unlike Knights of a Round Table, Knights of a Polygonal Table deprived of nobility and happy to kill each other. But each knight has some power and a knight can kill another knight if and only if his power is greater than the power of victim. However, even such a knight will torment his conscience, so he can kill no more than $k$ other knights. Also, each knight has some number of coins. After a kill, a knight can pick up all victim's coins.\n\nNow each knight ponders: how many coins he can have if only he kills other knights?\n\nYou should answer this question for each knight.",
"input": "",
"output": "```python\nimport heapq\n\nif __name__ == '__main__':\n rd = lambda: map(int, input().split())\n n, k = rd()\n a = sorted(zip(rd(), rd(), range(n)))\n\n minH = []\n total = 0\n ans = [0] * n\n for i in range(len(a)):\n if len(minH) >= k + 1:\n (coins, index) = heapq.heappop(minH)\n total -= coins\n\n heapq.heappush(minH, (a[i][1], i))\n\n total += a[i][1]\n ans[a[i][2]] = total\n\n\n\n print(*ans)\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A tourist hiked along the mountain range. The hike lasted for *n* days, during each day the tourist noted height above the sea level. On the *i*-th day height was equal to some integer *h**i*. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. for all *i*'s from 1 to *n*<=-<=1 the inequality |*h**i*<=-<=*h**i*<=+<=1|<=≤<=1 holds.\n\nAt the end of the route the tourist rafted down a mountain river and some notes in the journal were washed away. Moreover, the numbers in the notes could have been distorted. Now the tourist wonders what could be the maximum height during his hike. Help him restore the maximum possible value of the maximum height throughout the hike or determine that the notes were so much distorted that they do not represent any possible height values that meet limits |*h**i*<=-<=*h**i*<=+<=1|<=≤<=1.",
"input": "",
"output": "```python\nn,m = map(int,input().split())\r\nl = []\r\nfor i in range(m):\r\n l.append(list(map(int,input().split())))\r\nans = max(l[0][1]+l[0][0],l[-1][1]+n-l[-1][0])\r\nfor i in range(m-1):\r\n if abs(l[i][1]-l[i+1][1]) > abs(l[i][0]-l[i+1][0]):\r\n ans = 'IMPOSSIBLE'\r\n break\r\n if l[i][1] > l[i+1][1]:\r\n ans = max(ans,l[i][1]+(-(l[i][1]-l[i+1][1])+(l[i+1][0]-l[i][0]))//2)\r\n else:\r\n ans = max(ans,l[i][1]+(-(l[i][1]-l[i+1][1])+(l[i+1][0]-l[i][0]))//2)\r\nprint(ans)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Sean is trying to save a large file to a USB flash drive. He has *n* USB flash drives with capacities equal to *a*1,<=*a*2,<=...,<=*a**n* megabytes. The file size is equal to *m* megabytes. \n\nFind the minimum number of USB flash drives needed to write Sean's file, if he can split the file between drives.",
"input": "",
"output": "```python\nn=int(input())\r\nm=int(input())\r\ncount=0\r\nc=[]\r\nfor i in range(n):\r\n a = int(input())\r\n c.append(a)\r\nc.sort(reverse=True)\r\nif sum(c)=m:\r\n coumt=0\r\n break\r\n s=c[i]+c[i+1]\r\n if s=m:\r\n count+=1\r\n break\r\n\r\nprint(count+1)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.\n\nSince the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length.",
"input": "",
"output": "```python\ndef get_letters(word):\n letters = set(word)\n return ''.join(sorted(letters))\n\n\ndef main():\n n = int(input())\n words = [input() for _ in range(n)]\n\n two_letter_maps = {}\n single_letter_maps = {}\n for word in words:\n letters = get_letters(word)\n if len(letters) == 2:\n increase_count(letters, two_letter_maps, len(word))\n elif len(letters) == 1:\n increase_count(letters, single_letter_maps, len(word))\n\n for pairs in two_letter_maps:\n for letter in pairs:\n two_letter_maps[pairs] += get_count(letter, single_letter_maps)\n\n double_count = get_max(two_letter_maps)\n single_count = get_max(single_letter_maps)\n\n count = max(double_count, single_count)\n print(count)\n\n\ndef get_count(key, dictionary):\n if key not in dictionary:\n return 0\n return dictionary[key]\n\n\ndef get_max(dictionary):\n if len(dictionary) == 0:\n return 0\n return max(dictionary.values())\n\n\ndef increase_count(key, dictionary, value):\n if key not in dictionary:\n dictionary[key] = 0\n dictionary[key] += value\n\n\nif __name__ == '__main__':\n main()\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "The input contains a single integer *a* (0<=≤<=*a*<=≤<=35).\n\nOutput a single integer.",
"input": "",
"output": "```python\nn = (int)(input());\r\nprint(2 ** n);\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Linear Kingdom has exactly one tram line. It has *n* stops, numbered from 1 to *n* in the order of tram's movement. At the *i*-th stop *a**i* passengers exit the tram, while *b**i* passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it becomes empty.\n\nYour task is to calculate the tram's minimum capacity such that the number of people inside the tram at any time never exceeds this capacity. Note that at each stop all exiting passengers exit before any entering passenger enters the tram.",
"input": "",
"output": "```python\nn=int(input())\r\nc=0\r\nm=0\r\nwhile(n):\r\n\ta,b=map(int,input().split())\r\n\tc=c-a+b\r\n\tm=max(m,c)\r\n\tn-=1\r\nprint(m)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "These days Arkady works as an air traffic controller at a large airport. He controls a runway which is usually used for landings only. Thus, he has a schedule of planes that are landing in the nearest future, each landing lasts $1$ minute.\n\nHe was asked to insert one takeoff in the schedule. The takeoff takes $1$ minute itself, but for safety reasons there should be a time space between the takeoff and any landing of at least $s$ minutes from both sides.\n\nFind the earliest time when Arkady can insert the takeoff.",
"input": "",
"output": "```python\nn,s = map(int,input().split())\r\na = []\r\nfor i in range(n):\r\n\th , m = map(int,input().split())\r\n\ta.append((h*60)+m)\r\n\r\ntime = a[n-1]+s+1\r\nfor i in range(n-1):\r\n\tdif = a[i+1] - a[i]\r\n\tif(dif > s*2+1):\r\n\t\ttime = a[i]+s+1\r\n\t\tbreak\r\n\r\nh = int(time/60)\r\nm = time%60\r\n\r\nprint(\"{} {}\".format(h,m))\r\n\r\n\r\n\r\n\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A sequence of non-negative integers *a*1,<=*a*2,<=...,<=*a**n* of length *n* is called a wool sequence if and only if there exists two integers *l* and *r* (1<=≤<=*l*<=≤<=*r*<=≤<=*n*) such that . In other words each wool sequence contains a subsequence of consecutive elements with xor equal to 0.\n\nThe expression means applying the operation of a bitwise xor to numbers *x* and *y*. The given operation exists in all modern programming languages, for example, in languages C++ and Java it is marked as \"^\", in Pascal — as \"xor\".\n\nIn this problem you are asked to compute the number of sequences made of *n* integers from 0 to 2*m*<=-<=1 that are not a wool sequence. You should print this number modulo 1000000009 (109<=+<=9).",
"input": "",
"output": "```python\nx = input()\r\ni = 3\r\ny = \"\"\r\nwhile (i < len(x)-3):\r\n if (x[i]==\"W\" and x[i+1]==\"U\" and x[i+2]==\"P\"):\r\n y = y + \" \"\r\n i += 3\r\n else:\r\n y = y + x[i]\r\n i += 1\r\nprint(y)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A large banner with word CODEFORCES was ordered for the 1000-th onsite round of Codeforcesω that takes place on the Miami beach. Unfortunately, the company that made the banner mixed up two orders and delivered somebody else's banner that contains someone else's word. The word on the banner consists only of upper-case English letters.\n\nThere is very little time to correct the mistake. All that we can manage to do is to cut out some substring from the banner, i.e. several consecutive letters. After that all the resulting parts of the banner will be glued into a single piece (if the beginning or the end of the original banner was cut out, only one part remains); it is not allowed change the relative order of parts of the banner (i.e. after a substring is cut, several first and last letters are left, it is allowed only to glue the last letters to the right of the first letters). Thus, for example, for example, you can cut a substring out from string 'TEMPLATE' and get string 'TEMPLE' (if you cut out string AT), 'PLATE' (if you cut out TEM), 'T' (if you cut out EMPLATE), etc.\n\nHelp the organizers of the round determine whether it is possible to cut out of the banner some substring in such a way that the remaining parts formed word CODEFORCES.",
"input": "",
"output": "```python\na = input()\r\nc = 'CODEFORCES'\r\nif len(a)<10:print('NO')\r\nelse:\r\n t = 0\r\n for i in range(10):\r\n if a[i] == c[i]:\r\n t+=1\r\n for i in range(10):\r\n if a[(-1)*(i+1)] == c[(-1)*(i+1)]:t+=1\r\n print('YES' if t>=10 else 'NO')\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "In this problem we consider a special type of an auction, which is called the second-price auction. As in regular auction *n* bidders place a bid which is price a bidder ready to pay. The auction is closed, that is, each bidder secretly informs the organizer of the auction price he is willing to pay. After that, the auction winner is the participant who offered the highest price. However, he pay not the price he offers, but the highest price among the offers of other participants (hence the name: the second-price auction).\n\nWrite a program that reads prices offered by bidders and finds the winner and the price he will pay. Consider that all of the offered prices are different.",
"input": "",
"output": "```python\nnums=int(input())\r\na=list(map(int, input().split()))\r\n\r\nm=a[0];mi=0 #m=Largest bid; mi=index of largest bid\r\nn=0\t#Second largest number\r\n\r\nfor i in range(1, nums):\r\n\tif a[i]>=m:\r\n\t\tn=m #Second largest bacomes equal to the previous largest one\r\n\t\tm=a[i] #New largest number\r\n\t\tmi=i #index of the largest bid\r\n\telse:\r\n\t\tif a[i]>=n:\r\n\t\t\tn=a[i] #Second largest number changes if there exists a number between 'n' and 'm'\r\nprint(mi+1, n)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Polycarp takes part in a math show. He is given *n* tasks, each consists of *k* subtasks, numbered 1 through *k*. It takes him *t**j* minutes to solve the *j*-th subtask of any task. Thus, time required to solve a subtask depends only on its index, but not on the task itself. Polycarp can solve subtasks in any order.\n\nBy solving subtask of arbitrary problem he earns one point. Thus, the number of points for task is equal to the number of solved subtasks in it. Moreover, if Polycarp completely solves the task (solves all *k* of its subtasks), he recieves one extra point. Thus, total number of points he recieves for the complete solution of the task is *k*<=+<=1.\n\nPolycarp has *M* minutes of time. What is the maximum number of points he can earn?",
"input": "",
"output": "```python\ndef I(): return(list(map(int,input().split())))\r\ndef sieve(n):\r\n\ta=[1]*n\r\n\tfor i in range(2,n):\r\n\t if a[i]:\r\n\t for j in range(i*i,n,i):\r\n\t a[j]=0\r\n\treturn a\r\n\r\n\r\n\r\n\r\nn,k,m=I()\r\narr=I()\r\narr.sort()\r\npts=0\r\nf=0\r\nfor i in range(k-2):\r\n\tcurrm=m\r\n\tpts+=min(n,currm//arr[i])\r\n\r\n\tm-=min(currm//arr[i],n)*arr[i]\r\n\tif m<=0:\r\n\t\tf=1\r\n\t\tbreak\r\n# print(m)\r\nif f or m=n:\r\n\t\t\tpts+=(m//arr[-1])*2\r\n\tprint(pts)\r\n\r\n\r\n\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Kefa decided to make some money doing business on the Internet for exactly *n* days. He knows that on the *i*-th day (1<=≤<=*i*<=≤<=*n*) he makes *a**i* money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence *a**i*. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.\n\nHelp Kefa cope with this task!",
"input": "",
"output": "```python\nn=int(input())\r\nm=list(map(int,input().split()))\r\nc1=1\r\nc2=1\r\nfor i in range(0,n-1):\r\n if m[i]<=m[i+1]:\r\n #print(m[i],m[i+1])\r\n c2 +=1\r\n elif m[i]>m[i+1]:\r\n if c2>c1:\r\n c1=c2\r\n c2=1\r\nif c2 > c1:\r\n c1 = c2\r\nprint(c1)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Once again Tavas started eating coffee mix without water! Keione told him that it smells awful, but he didn't stop doing that. That's why Keione told his smart friend, SaDDas to punish him! SaDDas took Tavas' headphones and told him: \"If you solve the following problem, I'll return it to you.\"\n\nThe problem is: \n\nYou are given a lucky number *n*. Lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.\n\nIf we sort all lucky numbers in increasing order, what's the 1-based index of *n*? \n\nTavas is not as smart as SaDDas, so he asked you to do him a favor and solve this problem so he can have his headphones back.",
"input": "",
"output": "```python\nd = {'4':1 ,'7':2}\r\nres =0\r\nfor i in input():\r\n res = res * 2 + d[i]\r\n #print(res)\r\nprint(res)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.\n\nUnfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky digits in it is a lucky number. He wonders whether number *n* is a nearly lucky number.",
"input": "",
"output": "```python\ndef main():\r\n\r\n inp = input()\r\n\r\n IL = len(inp)\r\n\r\n if IL == 7 or IL == 4:\r\n print(\"YES\")\r\n\r\n else:\r\n print(\"NO\")\r\n \r\n \r\n\r\nmain()\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "The array *a* with *n* integers is given. Let's call the sequence of one or more consecutive elements in *a* segment. Also let's call the segment k-good if it contains no more than *k* different values.\n\nFind any longest k-good segment.\n\nAs the 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.",
"input": "",
"output": "```python\nfrom collections import Counter\r\nn,k=map(int,input().split())\r\narr=list(map(int,input().split()))\r\nc=Counter()\r\ncount=0\r\nans=[-1,-1]\r\nl=0\r\nfor r,el in enumerate(arr):\r\n c[el]+=1\r\n if c[el]==1:\r\n count+=1\r\n while count>k:\r\n c[arr[l]]-=1\r\n if c[arr[l]]==0:\r\n count-=1\r\n l+=1\r\n if r-l+1>=ans[-1]-ans[0]+1:\r\n ans=[l+1,r+1]\r\n \r\nprint(*ans)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Ann has recently started commuting by subway. We know that a one ride subway ticket costs *a* rubles. Besides, Ann found out that she can buy a special ticket for *m* rides (she can buy it several times). It costs *b* rubles. Ann did the math; she will need to use subway *n* times. Help Ann, tell her what is the minimum sum of money she will have to spend to make *n* rides?",
"input": "",
"output": "```python\nn, m, a, b = map(int,input().split())\r\nq=int(((n/m)//1))\r\np=n-(q*m)\r\nprint((q*b)+(p*a))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase \"how are you\" he can type \"hhoow aaaare yyoouu\". \n\nPolycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! \n\nHelp Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result.",
"input": "",
"output": "```python\n# Wadea #\r\n\r\nn = str(input())\r\nr = \"\"\r\nfor i in n:\r\n if n.count(i) > 1:\r\n pass\r\n else:\r\n r += i\r\nif len(r) == 0:\r\n print(n[0])\r\nelse:\r\n print(r)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vasya lives in a round building, whose entrances are numbered sequentially by integers from 1 to *n*. Entrance *n* and entrance 1 are adjacent.\n\nToday Vasya got bored and decided to take a walk in the yard. Vasya lives in entrance *a* and he decided that during his walk he will move around the house *b* entrances in the direction of increasing numbers (in this order entrance *n* should be followed by entrance 1). The negative value of *b* corresponds to moving |*b*| entrances in the order of decreasing numbers (in this order entrance 1 is followed by entrance *n*). If *b*<==<=0, then Vasya prefers to walk beside his entrance.\n\nHelp Vasya to determine the number of the entrance, near which he will be at the end of his walk.",
"input": "",
"output": "```python\nimport math\ndef solve(n,a,b):\n \n if b< 0:\n res=(n-(-1*b%n))+a\n else: \n res = b%n + a\n return res if res < n else res-n\n\ndef main() :\n arr = list(map(int, input().split(' ')))\n # arr = []\n # for _ in range(3):\n # arr.append(input())\n print(solve(*arr))\nmain()\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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:\n - 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). \nNow Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.\n\nPolycarp 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.\n\nAs Polycarp has no time, he is asking for your help in solving this problem.",
"input": "",
"output": "```python\nimport sys\n\nserverTraffic = 0\nactiveUsers = 0\n\nfor line in sys.stdin:\n if line[0] == '+':\n activeUsers += 1\n elif line[0] == '-':\n activeUsers -= 1\n else:\n #serverTraffic += (activeUsers - 1) * (len(line) - line.find(':') - 1)\n serverTraffic += activeUsers * (len(line) - line.find(':') - 2)\n\nprint(serverTraffic)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Manao is trying to open a rather challenging lock. The lock has *n* buttons on it and to open it, you should press the buttons in a certain order to open the lock. When you push some button, it either stays pressed into the lock (that means that you've guessed correctly and pushed the button that goes next in the sequence), or all pressed buttons return to the initial position. When all buttons are pressed into the lock at once, the lock opens.\n\nConsider an example with three buttons. Let's say that the opening sequence is: {2, 3, 1}. If you first press buttons 1 or 3, the buttons unpress immediately. If you first press button 2, it stays pressed. If you press 1 after 2, all buttons unpress. If you press 3 after 2, buttons 3 and 2 stay pressed. As soon as you've got two pressed buttons, you only need to press button 1 to open the lock.\n\nManao doesn't know the opening sequence. But he is really smart and he is going to act in the optimal way. Calculate the number of times he's got to push a button in order to open the lock in the worst-case scenario.",
"input": "",
"output": "```python\na=int(input())\r\ncount=0\r\nj=1\r\narr=[]\r\nfor i in range(a-1):\r\n count=count+j\r\n j=j+1\r\n arr.append(count)\r\nprint(sum(arr)+a)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Misha and Vanya have played several table tennis sets. Each set consists of several serves, each serve is won by one of the players, he receives one point and the loser receives nothing. Once one of the players scores exactly *k* points, the score is reset and a new set begins.\n\nAcross all the sets Misha scored *a* points in total, and Vanya scored *b* points. Given this information, determine the maximum number of sets they could have played, or that the situation is impossible.\n\nNote that the game consisted of several complete sets.",
"input": "",
"output": "```python\nk,a,b=map(int,input().split())\r\nif (a%k==0 or b%k==0) and (a!=0 and b!=0):\r\n print(a//k+b//k)\r\nelse:\r\n print(-1)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vitaly has an array of *n* distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: \n 1. The product of all numbers in the first set is less than zero (<=<<=0). 1. The product of all numbers in the second set is greater than zero (<=><=0). 1. The product of all numbers in the third set is equal to zero. 1. Each number from the initial array must occur in exactly one set. \nHelp Vitaly. Divide the given array.",
"input": "",
"output": "```python\n# -*- coding: utf-8 -*-\n\nN = int(input())\na = []\nfor _ in range(N):\n _a = int(input())\n a.append(_a)\na.sort()\n\nprint('ce pula mea de runtime error iti trebuie')\n \t\t \t\t \t \t \t\t\t\t \t \t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "For a positive integer *n* let's define a function *f*:\n\n*f*(*n*)<==<=<=-<=1<=+<=2<=-<=3<=+<=..<=+<=(<=-<=1)*n**n* \n\nYour task is to calculate *f*(*n*) for a given integer *n*.",
"input": "",
"output": "```python\nn=int(input())\r\nc=0\r\nk=0\r\nfor i in range(n+1):\r\n if i>0:\r\n if i%2!=0:\r\n c-=i\r\n else:\r\n k+=i\r\n\r\nprint(c+k)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vasya's bicycle chain drive consists of two parts: *n* stars are attached to the pedal axle, *m* stars are attached to the rear wheel axle. The chain helps to rotate the rear wheel by transmitting the pedal rotation.\n\nWe know that the *i*-th star on the pedal axle has *a**i* (0<=<<=*a*1<=<<=*a*2<=<<=...<=<<=*a**n*) teeth, and the *j*-th star on the rear wheel axle has *b**j* (0<=<<=*b*1<=<<=*b*2<=<<=...<=<<=*b**m*) teeth. Any pair (*i*,<=*j*) (1<=≤<=*i*<=≤<=*n*; 1<=≤<=*j*<=≤<=*m*) is called a gear and sets the indexes of stars to which the chain is currently attached. Gear (*i*,<=*j*) has a gear ratio, equal to the value .\n\nSince Vasya likes integers, he wants to find such gears (*i*,<=*j*), that their ratios are integers. On the other hand, Vasya likes fast driving, so among all \"integer\" gears (*i*,<=*j*) he wants to choose a gear with the maximum ratio. Help him to find the number of such gears.\n\nIn the problem, fraction denotes division in real numbers, that is, no rounding is performed.",
"input": "",
"output": "```python\nn=int(input())\r\nlist1=list(map(int,input().split()))\r\nm=int(input())\r\nlist2=list(map(int,input().split()))\r\nmax1=0\r\nfor i in list2:\r\n for j in list1:\r\n if i%j==0 and (i//j)>max1:\r\n max1=(i//j)\r\nc=0 \r\nfor i in list2:\r\n for j in list1:\r\n if i%j==0 and i//j==max1:\r\n c=c+1\r\nprint(c) \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A robber has attempted to rob a bank but failed to complete his task. However, he had managed to open all the safes.\n\nOleg the bank client loves money (who doesn't), and decides to take advantage of this failed robbery and steal some money from the safes. There are many safes arranged in a line, where the *i*-th safe from the left is called safe *i*. There are *n* banknotes left in all the safes in total. The *i*-th banknote is in safe *x**i*. Oleg is now at safe *a*. There are two security guards, one of which guards the safe *b* such that *b*<=<<=*a*, i.e. the first guard is to the left of Oleg. The other guard guards the safe *c* so that *c*<=><=*a*, i.e. he is to the right of Oleg.\n\nThe two guards are very lazy, so they do not move. In every second, Oleg can either take all the banknotes from the current safe or move to any of the neighboring safes. However, he cannot visit any safe that is guarded by security guards at any time, becaues he might be charged for stealing. Determine the maximum amount of banknotes Oleg can gather.",
"input": "",
"output": "```python\n######################################################\ndef convert_inp_to_int():\n return [int(x) for x in input().strip().split()]\n#######################################################\ndef get_position(flag,n,notes_at,pos):\n\tif(flag):\n\t\ti=0 \n\t\twhile(ipos):\n\t\t\t\treturn (i-1)\n\t\t\ti+=1\t\n\t\treturn (i-1)\n\telse:\n\t\ti=0 \n\t\twhile(i=pos):\n\t\t\t\treturn (i-1)\n\t\t\ti+=1\t\n\t\treturn (i-1)\t\t\n####################################################\nabc=convert_inp_to_int()\na=abc[0]\nb=abc[1]\nc=abc[2]\nn=convert_inp_to_int()[0]\nnotes_at=convert_inp_to_int()\nnotes_at.sort()\n#print(notes_at)\noleg_pos=get_position(0,n,notes_at,a) \ng1_pos=get_position(1,n,notes_at,b)\ng2_pos=get_position(0,n,notes_at,c)\ng1_pos+=1\nprint(oleg_pos,g1_pos,g2_pos)\nif(g1_pos k*b or n < k*a:\r\n print(\"No solution\")\r\n exit()\r\nr = n % k\r\ni, j = 0, n//k\r\nwhile i < n:\r\n if r:\r\n r -= 1\r\n print(s[i:i+j+1])\r\n i += j\r\n i += 1\r\n else:\r\n print(s[i:i+j+1])\r\n i += j\r\n i += 1\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A big company decided to launch a new series of rectangular displays, and decided that the display must have exactly *n* pixels. \n\nYour task is to determine the size of the rectangular display — the number of lines (rows) of pixels *a* and the number of columns of pixels *b*, so that:\n - there are exactly *n* pixels on the display; - the number of rows does not exceed the number of columns, it means *a*<=≤<=*b*; - the difference *b*<=-<=*a* is as small as possible.",
"input": "",
"output": "```python\nn = int(input())\r\na = 1\r\nans = 10**18\r\nwhile a*a <= n:\r\n if n%a == 0:\r\n b = n//a\r\n if b-a < ans:\r\n ans = b-a\r\n ans_a = a\r\n a+=1\r\nprint(ans_a, n//ans_a)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with *n* room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (*n*<=-<=1)-th room to the *n*-th room. Thus, you can go to room *x* only from room *x*<=-<=1.\n\nThe potato pie is located in the *n*-th room and Vitaly needs to go there. \n\nEach pair of consecutive rooms has a door between them. In order to go to room *x* from room *x*<=-<=1, you need to open the door between the rooms with the corresponding key. \n\nIn total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type *t* can open the door of type *T* if and only if *t* and *T* are the same letter, written in different cases. For example, key f can open door F.\n\nEach of the first *n*<=-<=1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.\n\nVitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room *n*.\n\nGiven the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room *n*, which has a delicious potato pie. Write a program that will help Vitaly find out this number.",
"input": "",
"output": "```python\nn = int(input())\n\nword = input()\nisKey = True\nkeys = []\nbuy = 0\n\nfor pos in range(len(word)):\n \n if(isKey):\n keys.append(word[pos].upper())\n isKey = False\n else:\n isKey = True\n if (word[pos] not in keys):\n buy += 1\n else:\n keys.remove(word[pos])\n\nprint(buy)\n \t \t \t \t \t\t \t\t \t\t \t \t\t \t\t \t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vanya walks late at night along a straight street of length *l*, lit by *n* lanterns. Consider the coordinate system with the beginning of the street corresponding to the point 0, and its end corresponding to the point *l*. Then the *i*-th lantern is at the point *a**i*. The lantern lights all points of the street that are at the distance of at most *d* from it, where *d* is some positive number, common for all lanterns. \n\nVanya wonders: what is the minimum light radius *d* should the lanterns have to light the whole street?",
"input": "",
"output": "```python\nl = input()\r\nl = l.split()\r\nl[0] = int(l[0])\r\nl[1] = int(l[1])\r\n\r\nl1 = input()\r\nl1 = l1.split()\r\nfor i in range(len(l1)):\r\n l1[i] = int(l1[i])\r\n\r\nl1.sort()\r\n\r\nd = float(\"inf\")\r\n\r\nfor j in range(len(l1)-1):\r\n d = min(d, abs(l1[i+1] - l1[i]))\r\n\r\nprint(d)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Two players play a game.\n\nInitially there are $n$ integers $a_1, a_2, \\ldots, a_n$ written on the board. Each turn a player selects one number and erases it from the board. This continues until there is only one number left on the board, i. e. $n - 1$ turns are made. The first player makes the first move, then players alternate turns.\n\nThe first player wants to minimize the last number that would be left on the board, while the second player wants to maximize it.\n\nYou want to know what number will be left on the board after $n - 1$ turns if both players make optimal moves.",
"input": "",
"output": "```python\nn = int(input())\ni = (n // 2) - (n % 2 == 0)\nprint(list(sorted(map(int, input().split())))[i])\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A triangular number is the number of dots in an equilateral triangle uniformly filled with dots. For example, three dots can be arranged in a triangle; thus three is a triangular number. The *n*-th triangular number is the number of dots in a triangle with *n* dots on a side. . You can learn more about these numbers from Wikipedia (http://en.wikipedia.org/wiki/Triangular_number).\n\nYour task is to find out if a given integer is a triangular number.",
"input": "",
"output": "```python\nsum = 0\r\ni = 0\r\nans = \"NO\"\r\nt = int(input())\r\nwhile sum <= t:\r\n i += 1\r\n sum += i\r\n if sum == t:\r\n ans = \"YES\"\r\nprint(ans)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called \"Black Square\" on his super cool touchscreen phone.\n\nIn this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules of the game, Jury must use this second to touch the corresponding strip to make the square go away. As Jury is both smart and lazy, he counted that he wastes exactly *a**i* calories on touching the *i*-th strip.\n\nYou've got a string *s*, describing the process of the game and numbers *a*1,<=*a*2,<=*a*3,<=*a*4. Calculate how many calories Jury needs to destroy all the squares?",
"input": "",
"output": "```python\n# SOLUTION 1\r\n# a,b,c,d = map(int,input().split())\r\n# s = input()\r\n# print(s.count(\"1\")*a+s.count(\"2\")*b+s.count(\"3\")*c+s.count(\"4\")*d)\r\n\r\n# SOLUTION 2\r\n# a,b,c,d = map(int,input().split())\r\n# sum = 0\r\n# for w in input():\r\n# if w == \"1\":\r\n# sum += a\r\n# elif w == \"2\":\r\n# sum += b\r\n# elif w == \"3\":\r\n# sum += c\r\n# else :\r\n# sum += d\r\n# print(sum)\r\n\r\n\r\n#SOLUTION 3\r\nl = list(map(int,input().split()))\r\nsum = 0\r\nfor w in input():\r\n sum += l[int(w)-1]\r\nprint(sum)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "There exists an island called Arpa’s land, some beautiful girls live there, as ugly ones do.\n\nMehrdad 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*. \n\nMehrdad has become quite confused and wants you to help him. Please help, although it's a naive cheat.",
"input": "",
"output": "```python\nn=int(input())\r\np=1\r\nfor i in range(n):\r\n p=p*1378\r\nplist=list(str(p))\r\nprint(plist[-1])\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "The Little Elephant very much loves sums on intervals.\n\nThis time he has a pair of integers *l* and *r* (*l*<=≤<=*r*). The Little Elephant has to find the number of such integers *x* (*l*<=≤<=*x*<=≤<=*r*), that the first digit of integer *x* equals the last one (in decimal notation). For example, such numbers as 101, 477474 or 9 will be included in the answer and 47, 253 or 1020 will not.\n\nHelp him and count the number of described numbers *x* for a given pair *l* and *r*.",
"input": "",
"output": "```python\narr=list(map(int,input().split()))\r\nans=0\r\nfor i in range(arr[0],arr[1]+1):\r\n if(i%10==i//(10**math.log10(i)):\r\n ans+=1\r\nprint(ans)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "The Little Elephant loves Ukraine very much. Most of all he loves town Rozdol (ukr. \"Rozdil\").\n\nHowever, Rozdil is dangerous to settle, so the Little Elephant wants to go to some other town. The Little Elephant doesn't like to spend much time on travelling, so for his journey he will choose a town that needs minimum time to travel to. If there are multiple such cities, then the Little Elephant won't go anywhere.\n\nFor each town except for Rozdil you know the time needed to travel to this town. Find the town the Little Elephant will go to or print \"Still Rozdil\", if he stays in Rozdil.",
"input": "",
"output": "```python\nn = int(input())\r\nl = list(map(int, input().split()))\r\nl1 = l.copy()\r\nl1.sort()\r\nif l1[0]==l1[1]:\r\n print(\"Still Rozdil\")\r\nelse:\r\n mini = l1[0]\r\n index = 0\r\n for i in range(len(l)):\r\n if l[i] == mini:\r\n index = i\r\n break\r\n print(index+1)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are at a water bowling training. There are *l* people who play with their left hand, *r* people, who play with their right hand, and *a* ambidexters, who can play with left or right hand.\n\nThe coach decided to form a team of even number of players, exactly half of the players should play with their right hand, and exactly half of the players should play with their left hand. One player should use only on of his hands.\n\nAmbidexters play as well with their right hand as with their left hand. In the team, an ambidexter can play with their left hand, or with their right hand.\n\nPlease find the maximum possible size of the team, where equal number of players use their left and right hands, respectively.",
"input": "",
"output": "```python\nfrom math import *\r\na,b,c=map(int,input().split())\r\np=min(a,b)\r\nk=max(a,b)\r\ns=k-p\r\nif s>=c:\r\n ans=2*(p+c)\r\nelse:\r\n ans=2*(k+(c-s)//2)\r\nprint(ans)\r\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are given string *s*. Your task is to determine if the given string *s* contains two non-overlapping substrings \"AB\" and \"BA\" (the substrings can go in any order).",
"input": "",
"output": "```python\ns = input()\r\nyes = False\r\nleftMostAB = -1\r\nleftMostBA = -1\r\nrightMostAB = -1\r\nrightMostBA = -1\r\nfor i in range(len(s)-1):\r\n if s[i:i+2] == \"AB\":\r\n leftMostAB = i\r\n if s[i:i+2] == \"BA\":\r\n leftMostBA = i\r\n\r\nfor i in range(len(s)-2,-1,-1):\r\n if s[i:i+2] == \"AB\":\r\n rightMostAB = i\r\n if s[i:i+2] == \"BA\":\r\n rightMostBA = i\r\nif leftMostAB+1 < rightMostBA or leftMostBA+1 < rightMostAB:\r\n print(\"YES\")\r\nelse:\r\n print(\"NO\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "There is a fence in front of Polycarpus's home. The fence consists of *n* planks of the same width which go one after another from left to right. The height of the *i*-th plank is *h**i* meters, distinct planks can have distinct heights.\n\nPolycarpus has bought a posh piano and is thinking about how to get it into the house. In order to carry out his plan, he needs to take exactly *k* consecutive planks from the fence. Higher planks are harder to tear off the fence, so Polycarpus wants to find such *k* consecutive planks that the sum of their heights is minimal possible.\n\nWrite the program that finds the indexes of *k* consecutive planks with minimal total height. Pay attention, the fence is not around Polycarpus's home, it is in front of home (in other words, the fence isn't cyclic).",
"input": "",
"output": "```python\nn, k = [int(i) for i in input().split()]\r\nh = [int(i) for i in input().split()]\r\nsum_min = sum(h)\r\nj = 0\r\nfor curr_j in range(n-k):\r\n print(curr_j)\r\n if sum(h[curr_j:curr_j+k]) < sum_min:\r\n sum_min = sum(h[curr_j:curr_j+k])\r\n j = curr_j\r\nprint(j+1)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not enough time to assign tanks into teams and the whole game will collapse!\n\nThere are exactly *n* distinct countries in the world and the *i*-th country added *a**i* tanks to the game. As the developers of the game are perfectionists, the number of tanks from each country is beautiful. A beautiful number, according to the developers, is such number that its decimal representation consists only of digits '1' and '0', moreover it contains at most one digit '1'. However, due to complaints from players, some number of tanks of one country was removed from the game, hence the number of tanks of this country may not remain beautiful.\n\nYour task is to write the program that solves exactly the same problem in order to verify Gena's code correctness. Just in case.",
"input": "",
"output": "```python\nn = int(input())\r\nl = input().split(\" \")\r\nans = 1\r\nfor i in l:\r\n ans = ans * int(i)\r\n\r\nprint(ans)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are given a sequence *a* consisting of *n* integers. You may partition this sequence into two sequences *b* and *c* in such a way that every element belongs exactly to one of these sequences. \n\nLet *B* be the sum of elements belonging to *b*, and *C* be the sum of elements belonging to *c* (if some of these sequences is empty, then its sum is 0). What is the maximum possible value of *B*<=-<=*C*?",
"input": "",
"output": "```python\n#-------------Program--------------\r\n#----Kuzlyaev-Nikita-Codeforces----\r\n#-------------Training-------------\r\n#----------------------------------\r\n\r\nn=int(input())\r\na=list(map(int,input().split()))\r\nb=0;c=0\r\nfor i in range(n):\r\n if a[i]<0:c-=a[i]\r\n else:\r\n b+=a[i]\r\nprint(b-c)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "High school student Vasya got a string of length *n* as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.\n\nVasya can change no more than *k* characters of the original string. What is the maximum beauty of the string he can achieve?",
"input": "",
"output": "```python\nA. Vasya and String\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of *n* vertices. For each vertex *v* from 0 to *n*<=-<=1 he wrote down two integers, *degree**v* and *s**v*, were the first integer is the number of vertices adjacent to vertex *v*, and the second integer is the XOR sum of the numbers of vertices adjacent to *v* (if there were no adjacent vertices, he wrote down 0). \n\nNext day Misha couldn't remember what graph he initially had. Misha has values *degree**v* and *s**v* left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.",
"input": "",
"output": "```python\nfrom collections import deque\r\nn = int(input())\r\nprocess = deque()\r\nvs = []\r\nfor i in range(n):\r\n d, s = map(int, input().split())\r\n if d == 1:\r\n process.append(i)\r\n vs.append((d, s))\r\nedges = []\r\nwhile process:\r\n a = process.popleft()\r\n d, s = vs[a]\r\n if d == 0:\r\n continue\r\n dd, ss = vs[s]\r\n vs[s] = (dd - 1, ss ^ a)\r\n if dd == 2:\r\n process.append(s)\r\n edges.append((a, s))\r\nprint(len(edges))\r\nfor a, b in edges:\r\n print(a,b)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones.\n\nOnce he thought about a string of length *n* consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and the other contains 1, then we are allowed to remove these two digits from the string, obtaining a string of length *n*<=-<=2 as a result.\n\nNow Andreid thinks about what is the minimum length of the string that can remain after applying the described operation several times (possibly, zero)? Help him to calculate this number.",
"input": "",
"output": "```python\nimport re\r\n\r\nn = int(input())\r\nstring = input()\r\nis_match = re.findall(r'01|10', string)\r\nmatcheo = string\r\nwhile is_match:\r\n matcheo = re.sub(r'01|10', '', matcheo)\r\n is_match = re.findall(r'01|10', matcheo)\r\n\r\nprint(0) if not matcheo else print(len(matcheo))\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Vasya has *n* pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every *m*-th day (at days with numbers *m*,<=2*m*,<=3*m*,<=...) mom buys a pair of socks to Vasya. She does it late in the evening, so that Vasya cannot put on a new pair of socks before the next day. How many consecutive days pass until Vasya runs out of socks?",
"input": "",
"output": "```python\na, b = map(int,input().split())\r\nc = 0\r\nd = a\r\n\r\nfor i in range(0, a):\r\n if i % b == 0:\r\n a = a + 1\r\nprint(int(d + a//b))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "So, the Berland is at war with its eternal enemy Flatland again, and Vasya, an accountant, was assigned to fulfil his duty to the nation. \n\nRight now the situation in Berland is dismal — their both cities are surrounded! The armies of flatlanders stand on the borders of circles, the circles' centers are in the surrounded cities. At any moment all points of the flatland ring can begin to move quickly in the direction of the city — that's the strategy the flatlanders usually follow when they besiege cities.\n\nThe berlanders are sure that they can repel the enemy's attack if they learn the exact time the attack starts. For that they need to construct a radar that would register any movement at the distance of at most *r* from it. Thus, we can install a radar at such point, that at least one point of the enemy ring will be in its detecting range (that is, at a distance of at most *r*). Then the radar can immediately inform about the enemy's attack. \n\nDue to the newest technologies, we can place a radar at any point without any problems. But the problem is that the berlanders have the time to make only one radar. Besides, the larger the detection radius (*r*) is, the more the radar costs.\n\nThat's why Vasya's task (that is, your task) is to find the minimum possible detection radius for the radar. In other words, your task is to find the minimum radius *r* (*r*<=≥<=0) such, that a radar with radius *r* can be installed at some point and it can register the start of the movements of both flatland rings from that point. \n\nIn this problem you can consider the cities as material points, the attacking enemy rings - as circles with centers in the cities, the radar's detection range — as a disk (including the border) with the center at the point where the radar is placed.",
"input": "",
"output": "```python\nimport math\r\n\r\n\r\nclass Point:\r\n def __init__(self, x, y):\r\n self.x = x\r\n self.y = y\r\n\r\n def __sub__(self, other):\r\n return Point(self.x - other.x, self.y - other.y)\r\n\r\n def distance(self, other):\r\n dx = abs(self.x - other.x)\r\n dy = abs(self.y - other.y)\r\n return math.hypot(dx, dy)\r\n\r\n\r\ndef float_eq(a, b):\r\n return abs(a - b) < 1e-9\r\n\r\n\r\ndef main():\r\n ax, ay, ar = map(int, input().split())\r\n bx, by, br = map(int, input().split())\r\n point_a = Point(ax, ay)\r\n point_b = Point(bx, by)\r\n\r\n p_dist = point_a.distance(point_b)\r\n r_sum = ar + br\r\n\r\n if float_eq(p_dist, r_sum):\r\n return print(0)\r\n if p_dist > r_sum:\r\n return print((p_dist - r_sum) / 2)\r\n if p_dist > ar:\r\n return print(0)\r\n print(abs(ar - br) / 2)\r\n\r\n\r\nmain()\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are *n* lines in that description each of which described one goal. Every goal was marked with the name of the team that had scored it. Help Vasya, learn the name of the team that won the finals. It is guaranteed that the match did not end in a tie.",
"input": "",
"output": "```python\nt=int(input())\r\nd=[]\r\nfor i in range(t):\r\n n=input()\r\n d.append(n)\r\n k=d[0]\r\n for i in range(len(d)):\r\n if(d.count(d[i])>d.count(k)):\r\n k=i \r\nprint(k)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.",
"input": "",
"output": "```python\nstr = input()\nlower, upper = 0, 0\nfor i in range(len(str)):\n if (str[i].isupper()): \n upper += 1\n else:\n lower += 1\n\nif (lower < upper):\n print(str.upper())\nelse:\n print(str.lower())\n\t \t \t\t \t\t\t\t\t\t\t\t \t\t\t\t \t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "One industrial factory is reforming working plan. The director suggested to set a mythical detail production norm. If at the beginning of the day there were *x* details in the factory storage, then by the end of the day the factory has to produce (remainder after dividing *x* by *m*) more details. Unfortunately, no customer has ever bought any mythical detail, so all the details produced stay on the factory. \n\nThe board of directors are worried that the production by the given plan may eventually stop (that means that there will be а moment when the current number of details on the factory is divisible by *m*). \n\nGiven the number of details *a* on the first day and number *m* check if the production stops at some moment.",
"input": "",
"output": "```python\na,m = map(int,input().split())\r\ns = set()\r\nflag = 0\r\nwhile 1:\r\n if a>m:\r\n a %= m\r\n if a in s:\r\n break\r\n s.add(a)\r\n a *= 2\r\n if a==m:\r\n flag = 1\r\n break\r\nif flag:\r\n print(\"Yes\")\r\nelse:\r\n print(\"No\")\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are given two positive integer numbers *a* and *b*. Permute (change order) of the digits of *a* to construct maximal number not exceeding *b*. No number in input and/or output can start with the digit 0.\n\nIt is allowed to leave *a* as it is.",
"input": "",
"output": "```python\na=input()\nb=input()\nna=len(a)\nnb=len(b)\nif(nal[j]:\n\t\t\t\tans1+=l[j]\n\t\t\t\tl.pop(j)\n\t\t\t\tflag=1\n\t\t\t\tbreak\n\t\tif(flag==1):\n\t\t\tbreak\n\tans1+=\"\".join(l)\n\tflag=0\n\tfor i in b:\n\t\tfor j in range(len(l2)):\n\t\t\tif i>l2[j]:\n\t\t\t\tans2+=l2[j]\n\t\t\t\tl2.pop(j)\n\t\t\t\tflag=1\n\t\t\t\tbreak\n\t\tif(flag==1):\n\t\t\tbreak\n\tans2+=\"\".join(l2)\n\tif(int(ans1)<=int(b)):\n\t\tprint(ans1)\n\telse:\n\t\tprint(ans2)\n \t\t\t \t\t\t \t\t \t \t\t\t\t\t \t\t\t \t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Tonio has a keyboard with only two letters, \"V\" and \"K\".\n\nOne day, he has typed out a string *s* with only these two letters. He really likes it when the string \"VK\" appears, so he wishes to change at most one letter in the string (or do no changes) to maximize the number of occurrences of that string. Compute the maximum number of times \"VK\" can appear as a substring (i. e. a letter \"K\" right after a letter \"V\") in the resulting string.",
"input": "",
"output": "```python\nimport sys\r\nimport math\r\nimport collections\r\nimport heapq\r\ninput=sys.stdin.readline\r\ns=input()\r\nn=len(s)-1\r\nc=s.count('VK')\r\nfor i in range(n):\r\n if(s[i]=='V'):\r\n s1=s[:i]+'K'+s[i+1:]\r\n else:\r\n s1=s[:i]+'V'+s[i+1:]\r\n c=max(c,s1.count('VK'))\r\nprint(c)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "One day the Codeforces round author sat exams. He had *n* exams and he needed to get an integer from 2 to 5 for each exam. He will have to re-sit each failed exam, i.e. the exam that gets mark 2. \n\nThe author would need to spend too much time and effort to make the sum of his marks strictly more than *k*. That could have spoilt the Codeforces round. On the other hand, if the sum of his marks is strictly less than *k*, the author's mum won't be pleased at all. \n\nThe Codeforces authors are very smart and they always get the mark they choose themselves. Also, the Codeforces authors just hate re-sitting exams. \n\nHelp the author and find the minimum number of exams he will have to re-sit if he passes the exams in the way that makes the sum of marks for all *n* exams equal exactly *k*.",
"input": "",
"output": "```python\nl=list(input())\r\ncount=0\r\nans=0\r\nfor i in range(len(l)):\r\n if count==0:\r\n count+=1\r\n print(ans,1)\r\n if 0< count<5 and l[i]==l[i-1]:\r\n count+=1\r\n print(ans,2)\r\n if 0< count<5 and l[i]!=l[i-1]:\r\n ans+=1\r\n count=1\r\n print(ans,3)\r\n if count==5:\r\n ans+=1\r\n count=1\r\n print(ans,4)\r\nprint(ans+1) \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "The Little Elephant loves chess very much. \n\nOne day the Little Elephant and his friend decided to play chess. They've got the chess pieces but the board is a problem. They've got an 8<=×<=8 checkered board, each square is painted either black or white. The Little Elephant and his friend know that a proper chessboard doesn't have any side-adjacent cells with the same color and the upper left cell is white. To play chess, they want to make the board they have a proper chessboard. For that the friends can choose any row of the board and cyclically shift the cells of the chosen row, that is, put the last (rightmost) square on the first place in the row and shift the others one position to the right. You can run the described operation multiple times (or not run it at all).\n\nFor example, if the first line of the board looks like that \"BBBBBBWW\" (the white cells of the line are marked with character \"W\", the black cells are marked with character \"B\"), then after one cyclic shift it will look like that \"WBBBBBBW\".\n\nHelp the Little Elephant and his friend to find out whether they can use any number of the described operations to turn the board they have into a proper chessboard.",
"input": "",
"output": "```python\nbad = False\nfor i in range(8):\n row = input().strip()\n if row not in ('WBWBWBWB', 'BWBWBWBW'):\n bad = True\n\nif bad:\n print('NO')\nelse:\n print('YES')\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Kevin Sun has just finished competing in Codeforces Round #334! The round was 120 minutes long and featured five problems with maximum point values of 500, 1000, 1500, 2000, and 2500, respectively. Despite the challenging tasks, Kevin was uncowed and bulldozed through all of them, distinguishing himself from the herd as the best cowmputer scientist in all of Bovinia. Kevin knows his submission time for each problem, the number of wrong submissions that he made on each problem, and his total numbers of successful and unsuccessful hacks. Because Codeforces scoring is complicated, Kevin wants you to write a program to compute his final score.\n\nCodeforces scores are computed as follows: If the maximum point value of a problem is *x*, and Kevin submitted correctly at minute *m* but made *w* wrong submissions, then his score on that problem is . His total score is equal to the sum of his scores for each problem. In addition, Kevin's total score gets increased by 100 points for each successful hack, but gets decreased by 50 points for each unsuccessful hack.\n\nAll arithmetic operations are performed with absolute precision and no rounding. It is guaranteed that Kevin's final score is an integer.",
"input": "",
"output": "```python\nm = [int(i) for i in input().split(\" \")]\r\nw = [int(i) for i in input().split(\" \")]\r\nhs, hu = [int(i) for i in input().split(\" \")]\r\nscore = 0\r\nfor i in range(5):\r\n score += max(0.3 * 500 * (i+1), (1 - m[i]/250) * (500 * (i+1)) - 50 * w[i])\r\nscore += 100 * hs\r\nscore -= 50 * hu\r\nprint(int(score))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Mikhail walks on a 2D plane. He can go either up or right. You are given a sequence of Mikhail's moves. He thinks that this sequence is too long and he wants to make it as short as possible.\n\nIn the given sequence moving up is described by character U and moving right is described by character R. Mikhail can replace any pair of consecutive moves RU or UR with a diagonal move (described as character D). After that, he can go on and do some other replacements, until there is no pair of consecutive moves RU or UR left.\n\nYour problem is to print the minimum possible length of the sequence of moves after the replacements.",
"input": "",
"output": "```python\nn = input()\r\ns= len(n)\r\nj =n.count('RU' and 'UR')\r\nprint((s-(j*2))+j-1)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are given a tetrahedron. Let's mark its vertices with letters *A*, *B*, *C* and *D* correspondingly.\n\nAn ant is standing in the vertex *D* of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place.\n\nYou do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertex *D* to itself in exactly *n* steps. In other words, you are asked to find out the number of different cyclic paths with the length of *n* from vertex *D* to itself. As the number can be quite large, you should print it modulo 1000000007 (109<=+<=7).",
"input": "",
"output": "```python\nn=int(input())\r\nm=1000000007\r\nf=0\r\ng=1\r\nfor i in range(1,n):\r\n t=f+0\r\n f=(3*g)%m\r\n g=(2*g+t)%m\r\nprint(f)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "An *n*<=×<=*n* table *a* is defined as follows:\n - The first row and the first column contain ones, that is: *a**i*,<=1<==<=*a*1,<=*i*<==<=1 for all *i*<==<=1,<=2,<=...,<=*n*. - Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the remaining elements are defined by the formula *a**i*,<=*j*<==<=*a**i*<=-<=1,<=*j*<=+<=*a**i*,<=*j*<=-<=1. \nThese conditions define all the values in the table.\n\nYou are given a number *n*. You need to determine the maximum value in the *n*<=×<=*n* table defined by the rules above.",
"input": "",
"output": "```python\nn=int(input())\r\narr=[1,5,15,35,70,126,210,230,395]\r\nprint(arr[n-1])\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "After finishing eating her bun, Alyona came up with two integers *n* and *m*. She decided to write down two columns of integers — the first column containing integers from 1 to *n* and the second containing integers from 1 to *m*. Now the girl wants to count how many pairs of integers she can choose, one from the first column and the other from the second column, such that their sum is divisible by 5.\n\nFormally, Alyona wants to count the number of pairs of integers (*x*,<=*y*) such that 1<=≤<=*x*<=≤<=*n*, 1<=≤<=*y*<=≤<=*m* and equals 0.\n\nAs usual, Alyona has some troubles and asks you to help.",
"input": "",
"output": "```python\nimport sys\n\nn, m = map(int, sys.stdin.readline().split())\nres = (n // 5) * (m // 5) * 5\nres += (n // 5) * (m % 5)\nres += (m // 5) * (n % 5)\nfor i in range(1, (n % 5) + 1):\n for j in range(1, (m % 5) + 1):\n if (i + j) % 5 == 0:\n res += 1\nprint(res)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are given $n$ strings. Each string consists of lowercase English letters. Rearrange (reorder) the given strings in such a way that for every string, all strings that are placed before it are its substrings.\n\nString $a$ is a substring of string $b$ if it is possible to choose several consecutive letters in $b$ in such a way that they form $a$. For example, string \"for\" is contained as a substring in strings \"codeforces\", \"for\" and \"therefore\", but is not contained as a substring in strings \"four\", \"fofo\" and \"rof\".",
"input": "",
"output": "```python\nimport sys\r\ninput = sys.stdin.readline\r\n\r\ng = sorted([input()[:-1] for _ in range(int(input()))], key=len)\r\n\r\nfor i in g[:-1]:\r\n if i not in g[-1]:\r\n print(\"NO\")\r\n break\r\nelse:\r\n print(\"YES\")\r\n for i in g:\r\n print(i)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You're given a string of lower-case Latin letters. Your task is to find the length of its longest substring that can be met in the string at least twice. These occurrences can overlap (see sample test 2).",
"input": "",
"output": "```python\ns = input()\r\n\r\nmc = -1\r\n\r\nfor i in range(len(s)):\r\n\tfor j in range(i+1, len(s)):\r\n\t\tcu = 0\r\n\t\tfor cu in range(len(s)-max(i, j)):\r\n\t\t\tif s[i+cu] == s[j+cu]:\r\n\t\t\t\tmc = max(mc, cu)\r\n\t\t\telse:\r\n\t\t\t\tbreak\r\n\t\t\r\n\r\nprint(mc + 1)\r\n\t\t\t\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Pasha has a wooden stick of some positive integer length *n*. He wants to perform exactly three cuts to get four parts of the stick. Each part must have some positive integer length and the sum of these lengths will obviously be *n*. \n\nPasha likes rectangles but hates squares, so he wonders, how many ways are there to split a stick into four parts so that it's possible to form a rectangle using these parts, but is impossible to form a square.\n\nYour task is to help Pasha and count the number of such ways. Two ways to cut the stick are considered distinct if there exists some integer *x*, such that the number of parts of length *x* in the first way differ from the number of parts of length *x* in the second way.",
"input": "",
"output": "```python\nn=int(input())\r\nans=0\r\nfor i in range(1,n//2+1):\r\n i1=i\r\n i2=n//2-i\r\n if(i1>1)\r\nprint(mn if mn < 99**99 else~ 0)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "*n* participants of the competition were split into *m* teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends.\n\nYour task is to write a program that will find the minimum and the maximum number of pairs of friends that could have formed by the end of the competition.",
"input": "",
"output": "```python\nfrom math import comb\r\n\r\na,b = list(map(int,input().split()))\r\n\r\nif b == 1:\r\n print((comb(a,2)),comb(a,2))\r\nelse:\r\n m = a-b+1\r\n if m%2:\r\n mx = comb(m-1,2) + 1\r\n else:\r\n mx = comb(m,2)\r\n \r\n p = a//b\r\n q = a%b\r\n \r\n mn = (b-q)*comb(p,2) + q*(comb(p+1,2))\r\n \r\n print(mn,mx)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "*n* participants of the competition were split into *m* teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends.\n\nYour task is to write a program that will find the minimum and the maximum number of pairs of friends that could have formed by the end of the competition.",
"input": "",
"output": "```python\nimport math\n\nn, m = map(int, input().split())\nteams = [0] * m\n\nf = n // m\n\nfor i in range(m):\n teams[i] += f\n\nif n % m > 0:\n teams[0] += 1\n\nansMin = 0\nfor i in teams:\n ansMin += math.comb(i, 2)\n\nansMax = math.comb(n-(m-1), 2)\n\nprint(ansMin, ansMax)\n\t \t \t\t \t \t \t \t \t\t\t \t \t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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:\n\n1. Each domino completely covers two squares.\n\n2. No two dominoes overlap.\n\n3. Each domino lies entirely inside the board. It is allowed to touch the edges of the board.\n\nFind the maximum number of dominoes, which can be placed under these restrictions.",
"input": "",
"output": "```python\nboard = input().split(\" \")\r\nm = int(board[0])\r\nn = int(board[1])\r\narea = m * n\r\n\r\nprint(area // 2)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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. \n\nValue 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.",
"input": "",
"output": "```python\nn,p,q,r=map(int,input().split())\r\narr=list(map(int,input().strip().split()))\r\npi,qj,rk= -1000000001,-1000000001,-1000000001\r\nfor i in range(n):\r\n x=arr[i]\r\n pi=max(pi,x*p)\r\n qj=max(qj,x*q)\r\n rk=max(rk,x*r)\r\nprint(pi+qj+rk)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Luba thinks about watering her garden. The garden can be represented as a segment of length *k*. Luba has got *n* buckets, the *i*-th bucket allows her to water some continuous subsegment of garden of length exactly *a**i* each hour. Luba can't water any parts of the garden that were already watered, also she can't water the ground outside the garden.\n\nLuba has to choose one of the buckets in order to water the garden as fast as possible (as mentioned above, each hour she will water some continuous subsegment of length *a**i* if she chooses the *i*-th bucket). Help her to determine the minimum number of hours she has to spend watering the garden. It is guaranteed that Luba can always choose a bucket so it is possible water the garden.\n\nSee the examples for better understanding.",
"input": "",
"output": "```python\ns = list(map(int,input().split()))\r\nlist_of_lengths = list(map(int,input().split()))\r\na = []\r\nfor j in list_of_lengths:\r\n if(s[1]%j ==0):\r\n a.append(int(s[1]//j));\r\nprint(min(a))\r\n \r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be. \n\nIn order to make sure that he's right and restore the correct order of keys, Santa typed his favorite patter looking only to his keyboard.\n\nYou are given the Santa's favorite patter and the string he actually typed. Determine which pairs of keys could be mixed. Each key must occur in pairs at most once.",
"input": "",
"output": "```python\nimport sys\r\nread = lambda: sys.stdin.readline().strip()\r\nreadi = lambda: map(int, read().split())\r\nfrom collections import *\r\n\r\noriginal = read()\r\noutput = read()\r\n\r\nmapping = dict()\r\nfor i in range(len(original)):\r\n key = original[i]\r\n val = output[i]\r\n\r\n if key in mapping:\r\n if mapping[key] != val:\r\n print(-1)\r\n break\r\n if val in mapping:\r\n if mapping[val] != key:\r\n print(-1)\r\n break\r\n\r\n if key != val:\r\n mapping[key] = val\r\n mapping[val] = key\r\nelse:\r\n n = len(mapping)//2\r\n print(n)\r\n keys = list(mapping.keys())\r\n for key in keys:\r\n if key in mapping:\r\n print(key, mapping[key])\r\n mapping.pop(mapping[key])\r\n mapping.pop(key)\r\n\r\n\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Allen has a LOT of money. He has $n$ dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are $1$, $5$, $10$, $20$, $100$. What is the minimum number of bills Allen could receive after withdrawing his entire balance?",
"input": "",
"output": "```python\nn = int(input())\r\ncount = n // 100 + (n % 100) // 20 + (n % 20) // 10 + (n % 10) // 5 + (n % 5)\r\nprint(count)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Sergey is testing a next-generation processor. Instead of bytes the processor works with memory cells consisting of *n* bits. These bits are numbered from 1 to *n*. An integer is stored in the cell in the following way: the least significant bit is stored in the first bit of the cell, the next significant bit is stored in the second bit, and so on; the most significant bit is stored in the *n*-th bit.\n\nNow Sergey wants to test the following instruction: \"add 1 to the value of the cell\". As a result of the instruction, the integer that is written in the cell must be increased by one; if some of the most significant bits of the resulting number do not fit into the cell, they must be discarded.\n\nSergey wrote certain values of the bits in the cell and is going to add one to its value. How many bits of the cell will change after the operation?",
"input": "",
"output": "```python\nn = int(input())\nbits = input()\n\ncounter = 1\ni = 0\nwhile i < n-1 and bits[i] == '1':\n counter += 1\n i += 1\n\nprint(counter)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.\n\nA tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (*u*,<=*v*) that belongs to the graph, *u* and *v* belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.\n\nDr. Evil gave Mahmoud and Ehab a tree consisting of *n* nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?\n\nA loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .",
"input": "",
"output": "```python\nimport bisect\nimport math\nfrom collections import deque\nimport heapq\nimport functools\nfrom queue import Queue\n\nmod = 998244353 \nN = 200005\n\ndef mul(a, b):\n\treturn (a*b)%mod\n\ndef add(a, b):\n\treturn (a+b) if (a+b=0) else (a-b)+mod\n\ndef powr(a, b):\n\tans = 1\n\twhile b>0:\n\t\tif b & 1:\n\t\t\tans=mul(ans,a)\n\t\ta = mul(a,a) \n\t\tb//=2\n\treturn ans\n\ndef inv(n):\n\treturn powr(n, mod-2)\n\ndef factlist():\n\tfact = [1]\n\tfor i in range(1, N):\n\t\tfact.append(mul(fact[i-1],i))\n\treturn fact\n\ndef invfactlist(fact):\n\tinvfact=[0]*N\n\tinvfact[0]=1\n\tinvfact[N-1]= inv(fact[N-1])\n\tfor i in range(N-2, 0, -1):\n\t\tinvfact[i]= mul(invfact[i+1],(i+1))\n\t\n\treturn invfact\n\ndef rot(S):\n\treturn list(zip(*S[::-1]))\n\ndef gcd(a, b):\n\tif b==0:\n\t\treturn a\n\treturn gcd(b, a%b)\n\ndef generate():\n\tans = [0]\n\twhile ans[-1]<1000000000:\n\t\tans.append(1+ans[-1]*2)\n\treturn ans\n\n\n\ndef main():\n\tn=int(input())\n\tg=[[]*n for _ in range(n)]\n\tfor i in range(n-1):\n\t u,v=map(int,input().split())\n\t g[u-1].append(v-1)\n\t g[v-1].append(u-1)\n\tqueue=Queue()\n\td=[-1]*n\n\tfor i in range(n):\n\t if(d[i]==-1):\n\t d[i]=0\n\t queue.put(i)\n\t while(not queue.empty()):\n\t u=queue.get()\n\t for v in g[u]:\n\t if(d[v]==-1):\n\t d[v]=1-d[u]\n\t queue.put(v)\n\tl=d.count(0)\n\tr=n-l\n\tprint(l*r-(n-1))\n\n\nif __name__ == \"__main__\":\n main()\n \n\t\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.\n\nOne 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.\n\nIn 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.\n\nShapur 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.\n\nNow you are going to take part in Shapur's contest. See if you are faster and more accurate.",
"input": "",
"output": "```python\n# cook your dish here\r\nn=input()\r\ns=input()\r\nres = ''\r\nfor i in range(len(n)):\r\n res += str(int(s[i])^int(n[i]))\r\nprint(res)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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.",
"input": "",
"output": "```python\nimport itertools\r\n\r\nn = int(input())\r\nif n < 3:\r\n print(0)\r\n exit(0)\r\npos = [list(tuple(map(int,input().split())))for _ in range(n)]\r\nmax = 0\r\nfor ss in itertools.combinations(pos, 3):\r\n area = ss[0][0]*(ss[1][1]-ss[2][1]) + ss[1][0]*(ss[2][1]-ss[0][1]) + ss[2][0]*(ss[0][1]-ss[1][1])\r\n if area == 1:\r\n max = max + 1\r\nprint(max)\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Sometimes some words like \"localization\" or \"internationalization\" are so long that writing them many times in one text is quite tiresome.\n\nLet's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.\n\nThis abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.\n\nThus, \"localization\" will be spelt as \"l10n\", and \"internationalization» will be spelt as \"i18n\".\n\nYou are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.",
"input": "",
"output": "```python\n#刘乐天 2300012105 生命科学学院\r\ni=int(input())\r\nfor i in range(0,i):\r\n a=input()\r\n b=len(a)-2\r\n if b>8:\r\n print(a[0]+str(b)+a[-1])\r\n else:\r\n print(a)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "It's New Year's Eve soon, so Ivan decided it's high time he started setting the table. Ivan has bought two cakes and cut them into pieces: the first cake has been cut into *a* pieces, and the second one — into *b* pieces.\n\nIvan knows that there will be *n* people at the celebration (including himself), so Ivan has set *n* plates for the cakes. Now he is thinking about how to distribute the cakes between the plates. Ivan wants to do it in such a way that all following conditions are met:\n 1. Each piece of each cake is put on some plate; 1. Each plate contains at least one piece of cake; 1. No plate contains pieces of both cakes. \nTo make his guests happy, Ivan wants to distribute the cakes in such a way that the minimum number of pieces on the plate is maximized. Formally, Ivan wants to know the maximum possible number *x* such that he can distribute the cakes according to the aforementioned conditions, and each plate will contain at least *x* pieces of cake.\n\nHelp Ivan to calculate this number *x*!",
"input": "",
"output": "```python\nfrom math import floor\r\n\r\ninputs = input().split(' ')\r\n\r\nn = int(inputs[0])\r\na = int(inputs[1])\r\nb = int(inputs[2])\r\n\r\ncur_max = floor((a + b) / n)\r\n\r\nwhile True:\r\n for i in range(n):\r\n if cur_max * i <= a and cur_max * (n-i) <= b:\r\n print(cur_max)\r\n exit()\r\n cur_max -= 1\r\nprint(1)\r\n \r\n \r\n\r\n\r\n\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "On the way to Rio de Janeiro Ostap kills time playing with a grasshopper he took with him in a special box. Ostap builds a line of length *n* such that some cells of this line are empty and some contain obstacles. Then, he places his grasshopper to one of the empty cells and a small insect in another empty cell. The grasshopper wants to eat the insect.\n\nOstap knows that grasshopper is able to jump to any empty cell that is exactly *k* cells away from the current (to the left or to the right). Note that it doesn't matter whether intermediate cells are empty or not as the grasshopper makes a jump over them. For example, if *k*<==<=1 the grasshopper can jump to a neighboring cell only, and if *k*<==<=2 the grasshopper can jump over a single cell.\n\nYour goal is to determine whether there is a sequence of jumps such that grasshopper will get from his initial position to the cell with an insect.",
"input": "",
"output": "```python\nn, k = [int(x) for x in input().split()]\r\ns = input()\r\nti = s.index('T')\r\ngi = s.index('G')\r\nd = abs(gi - ti)\r\nr = d % k\r\nif r!= 0:\r\n print(\"NO\")\r\nelse:\r\n if ti < gi:\r\n ti, gi = gi, ti\r\n bad = False\r\n for i in range(gi + k, ti, k):\r\n if s[i] == '#':\r\n bad = True\r\n break\r\n if bad:\r\n print(\"NO\")\r\n else:\r\n print(\"YES\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "This is yet another problem dealing with regular bracket sequences.\n\nWe should remind you that a bracket sequence is called regular, if by inserting «+» and «1» into it we can get a correct mathematical expression. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not. \n\nYou are given a string of «(» and «)» characters. You are to find its longest substring that is a regular bracket sequence. You are to find the number of such substrings as well.",
"input": "",
"output": "```python\ns = input()\r\nstack = []\r\nans = 0\r\nc = 0\r\nc1 = 0\r\nfor i in range(len(s)):\r\n if s[i] == \"(\":\r\n stack.append(s[i])\r\n c+=1\r\n else:\r\n if len(stack) == 0:\r\n pass\r\n else:\r\n p = stack.pop()\r\n if len(stack) == 0:\r\n if ans < (2*c):\r\n ans = (2*c)\r\n c1 = 1\r\n elif ans == (2*c):\r\n ans = (2*c)\r\n c1+=1\r\n c=0\r\nif ans == 0:\r\n print(ans,1)\r\nelse:\r\n print(ans,c1)\r\n \n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.\n\nA little later they found a string *s*, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring *t* of the string *s*.\n\nPrefix supposed that the substring *t* is the beginning of the string *s*; Suffix supposed that the substring *t* should be the end of the string *s*; and Obelix supposed that *t* should be located somewhere inside the string *s*, that is, *t* is neither its beginning, nor its end.\n\nAsterix chose the substring *t* so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring *t* aloud, the temple doors opened. \n\nYou know the string *s*. Find the substring *t* or determine that such substring does not exist and all that's been written above is just a nice legend.",
"input": "",
"output": "```python\ns=input()\r\nb=True\r\nfor x in range(1,len(s)):\r\n\ti=s[:len(s)-x]\r\n\te=s[x:]\r\n\tif(i==e and i in s[1:-1]):\r\n\t\tprint(i)\r\n\t\tb=False\r\n\t\tbreak\r\nif(b):\r\n\tprint(\"Just a legend\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Buses run between the cities *A* and *B*, the first one is at 05:00 AM and the last one departs not later than at 11:59 PM. A bus from the city *A* departs every *a* minutes and arrives to the city *B* in a *t**a* minutes, and a bus from the city *B* departs every *b* minutes and arrives to the city *A* in a *t**b* minutes.\n\nThe driver Simion wants to make his job diverse, so he counts the buses going towards him. Simion doesn't count the buses he meet at the start and finish.\n\nYou know the time when Simion departed from the city *A* to the city *B*. Calculate the number of buses Simion will meet to be sure in his counting.",
"input": "",
"output": "```python\na, ta = map(int, input().split())\nb, tb = map(int, input().split())\nh, m = map(int, input().split(':'))\ntime = h * 60 + m\nbasetime = 300\n\n\nif time - basetime >= tb:\n ans = (ta + tb) // b\n if ta == tb:\n ans -= 1\nelse:\n ans = (time - basetime + ta) // b\n\n\nprint(ans)\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Masha really loves algebra. On the last lesson, her strict teacher Dvastan gave she new exercise.\n\nYou are given geometric progression *b* defined by two integers *b*1 and *q*. Remind that a geometric progression is a sequence of integers *b*1,<=*b*2,<=*b*3,<=..., where for each *i*<=><=1 the respective term satisfies the condition *b**i*<==<=*b**i*<=-<=1·*q*, where *q* is called the common ratio of the progression. Progressions in Uzhlyandia are unusual: both *b*1 and *q* can equal 0. Also, Dvastan gave Masha *m* \"bad\" integers *a*1,<=*a*2,<=...,<=*a**m*, and an integer *l*.\n\nMasha writes all progression terms one by one onto the board (including repetitive) while condition |*b**i*|<=≤<=*l* is satisfied (|*x*| means absolute value of *x*). There is an exception: if a term equals one of the \"bad\" integers, Masha skips it (doesn't write onto the board) and moves forward to the next term.\n\nBut the lesson is going to end soon, so Masha has to calculate how many integers will be written on the board. In order not to get into depression, Masha asked you for help: help her calculate how many numbers she will write, or print \"inf\" in case she needs to write infinitely many integers.",
"input": "",
"output": "```python\nimport math\r\n\r\nb, q, l, m = list(map(int,input().split(\" \")))\r\na = set(map(int,input().split(\" \")))\r\n\r\nif q == 1:\r\n if b in a:\r\n ans = 0\r\n else:\r\n ans = \"inf\"\r\nelif q == -1:\r\n if b in a and -b in a:\r\n ans = 0\r\n else:\r\n ans = \"inf\"\r\nelse:\r\n # Finite progression\r\n # b_n = b_1*q^(n-1): |b_n| <= l -> |b_1*q^(n-1)| <= l\r\n # (log(l)-log(|b_1|))/ log(q) + 1 >= n\r\n max_num = int((math.log(l) - math.log(abs(b))) / math.log(q) + 1)\r\n \r\n # a/b == 0 mod (q)\r\n bad_count = sum(map(lambda x: x <= l and (math.log(x/b)/math.log(q)) % 1 == 0, a))\r\n # print(bad_count)\r\n ans = max_num - bad_count\r\n\r\n\r\n\r\n\r\nprint(ans)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "There are *n* walruses standing in a queue in an airport. They are numbered starting from the queue's tail: the 1-st walrus stands at the end of the queue and the *n*-th walrus stands at the beginning of the queue. The *i*-th walrus has the age equal to *a**i*.\n\nThe *i*-th walrus becomes displeased if there's a younger walrus standing in front of him, that is, if exists such *j* (*i*<=<<=*j*), that *a**i*<=><=*a**j*. The displeasure of the *i*-th walrus is equal to the number of walruses between him and the furthest walrus ahead of him, which is younger than the *i*-th one. That is, the further that young walrus stands from him, the stronger the displeasure is.\n\nThe airport manager asked you to count for each of *n* walruses in the queue his displeasure.",
"input": "",
"output": "```python\nn = int(input())\r\nl = list(map(int,input().split()))\r\nfor i in range(len(l)-1):\r\n if l[i] > l[i+1]:\r\n j = i\r\n c = 0\r\n while l[i] > l[j+1]:\r\n c += 1\r\n if j+1 == len(l) - 1:\r\n break\r\n j += 1\r\n print(c-1,end=\" \")\r\n else:\r\n print(\"-1 \",end=\"\")\r\nprint(-1)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Berland Football Cup starts really soon! Commentators from all over the world come to the event.\n\nOrganizers have already built $n$ commentary boxes. $m$ regional delegations will come to the Cup. Every delegation should get the same number of the commentary boxes. If any box is left unoccupied then the delegations will be upset. So each box should be occupied by exactly one delegation.\n\nIf $n$ is not divisible by $m$, it is impossible to distribute the boxes to the delegations at the moment.\n\nOrganizers can build a new commentary box paying $a$ burles and demolish a commentary box paying $b$ burles. They can both build and demolish boxes arbitrary number of times (each time paying a corresponding fee). It is allowed to demolish all the existing boxes.\n\nWhat is the minimal amount of burles organizers should pay to satisfy all the delegations (i.e. to make the number of the boxes be divisible by $m$)?",
"input": "",
"output": "```python\na,b,c,d=map(int,input().split())\r\nif a//b==0:print(0)\r\nelif b>a:\r\n k=abs((b-a)*c);l=abs(a*d)\r\n if kb:\r\n k=(b-(a%b))*c;l=(a%b)*d\r\n if k0:\r\n store+=i\r\n if store>0:\r\n if i<0:\r\n store-=1\r\n else:\r\n c+=1\r\nprint(c)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "There are several days left before the fiftieth birthday of a famous Berland's writer Berlbury. In this connection the local library decided to make an exposition of the works of this famous science-fiction writer. It was decided as well that it is necessary to include into the exposition only those books that were published during a particular time period. It is obvious that if the books differ much in size, the visitors will not like it. That was why the organizers came to the opinion, that the difference between the highest and the lowest books in the exposition should be not more than *k* millimeters.\n\nThe library has *n* volumes of books by Berlbury, arranged in chronological order of their appearance. The height of each book in millimeters is know, it is *h**i*. As Berlbury is highly respected in the city, the organizers want to include into the exposition as many books as possible, and to find out what periods of his creative work they will manage to cover. You are asked to help the organizers cope with this hard task.",
"input": "",
"output": "```python\n################################################################################\r\nn,k=map(int, input().split())\r\nh=list(map(int, input().split()))\r\n\r\n# n=3\r\n# k=3\r\n# h=[14,12,10]\r\n\r\n# n=4\r\n# k=5\r\n# h=[8,19,10,13]\r\n################################################################################\r\nmax_a=0\r\n\r\ni1=0\r\nmincup=h[0]\r\nmaxcup=h[0]\r\nfor i in range(1,n):\r\n if h[i]maxcup:\r\n maxcup=h[i]\r\n\r\n while maxcup-mincup>k and i1!=i:\r\n if mincup==h[i1]:\r\n mincup=min(h[i1+1:i+1])\r\n if maxcup==h[i1]:\r\n maxcup=max(h[i1+1:i+1])\r\n i1+=1\r\n\r\n if i-i1+1>max_a:\r\n max_a=i-i1+1\r\n\r\ni1=0\r\nmincup=h[0]\r\nmaxcup=h[0]\r\nout=[]\r\nfor i in range(1,n):\r\n if h[i]maxcup:\r\n maxcup=h[i]\r\n\r\n while maxcup-mincup>k and i1!=i:\r\n if mincup==h[i1]:\r\n mincup=min(h[i1+1:i+1])\r\n if maxcup==h[i1]:\r\n maxcup=max(h[i1+1:i+1])\r\n i1+=1\r\n\r\n if i-i1+1==max_a:\r\n out.append([i1+1,i+1])\r\n\r\nprint(max_a,len(out))\r\nfor out1 in out:\r\n print(out1[0],out1[1])\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A and B are preparing themselves for programming contests.\n\nB loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.\n\nInitially, the compiler displayed *n* compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix some mistake and then another one mistake.\n\nHowever, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared — the compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, compilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change.\n\nCan you help B find out exactly what two errors he corrected?",
"input": "",
"output": "```python\nt=int(input())\r\na=list(map(int,input().split()))\r\nb=list(map(int,input().split()))\r\nc=list(map(int,input().split()))\r\nsumm1=sum(a)\r\nsumm2=sum(b)\r\nsumm3=sum(c)\r\nprint(summ1-summ2)\r\nprint(summ2-summ3)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "For a given positive integer *n* denote its *k*-rounding as the minimum positive integer *x*, such that *x* ends with *k* or more zeros in base 10 and is divisible by *n*.\n\nFor example, 4-rounding of 375 is 375·80<==<=30000. 30000 is the minimum integer such that it ends with 4 or more zeros and is divisible by 375.\n\nWrite a program that will perform the *k*-rounding of *n*.",
"input": "",
"output": "```python\n\r\nfrom math import gcd\r\n\r\n\r\ndef lcm(x, y):\r\n ans = (x*y)//gcd(x, y)\r\n return ans\r\n\r\n\r\nn, k = (map(int, input().split()))\r\nif k == 0:\r\n print(n)\r\nelse:\r\n z = 10**k\r\n print(lcm(n, z))\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not enough time to assign tanks into teams and the whole game will collapse!\n\nThere are exactly *n* distinct countries in the world and the *i*-th country added *a**i* tanks to the game. As the developers of the game are perfectionists, the number of tanks from each country is beautiful. A beautiful number, according to the developers, is such number that its decimal representation consists only of digits '1' and '0', moreover it contains at most one digit '1'. However, due to complaints from players, some number of tanks of one country was removed from the game, hence the number of tanks of this country may not remain beautiful.\n\nYour task is to write the program that solves exactly the same problem in order to verify Gena's code correctness. Just in case.",
"input": "",
"output": "```python\n'''input\n3\n5 10 1\n'''\nn = int(input())\np = 1\nfor x in map(int, input().split()):\n\tp *= x\nprint(p)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm:\n - if the last digit of the number is non-zero, she decreases the number by one; - if the last digit of the number is zero, she divides the number by 10 (i.e. removes the last digit). \nYou are given an integer number $n$. Tanya will subtract one from it $k$ times. Your task is to print the result after all $k$ subtractions.\n\nIt is guaranteed that the result will be positive integer number.",
"input": "",
"output": "```python\nm,n=map(int,input().split())\r\nfor i in range(n):\r\n if(m%10!=0):\r\n m=m-1\r\n else:\r\n m=m//10\r\nprint(m)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You found a mysterious function *f*. The function takes two strings *s*1 and *s*2. These strings must consist only of lowercase English letters, and must be the same length.\n\nThe output of the function *f* is another string of the same length. The *i*-th character of the output is equal to the minimum of the *i*-th character of *s*1 and the *i*-th character of *s*2.\n\nFor example, *f*(\"ab\", \"ba\") = \"aa\", and *f*(\"nzwzl\", \"zizez\") = \"niwel\".\n\nYou found two strings *x* and *y* of the same length and consisting of only lowercase English letters. Find any string *z* such that *f*(*x*,<=*z*)<==<=*y*, or print -1 if no such string *z* exists.",
"input": "",
"output": "```python\na=input()\r\nb=input()\r\nfor i in range(len(a)):\r\n if b[i]>a[i]:\r\n print(-1)\r\n exit(0)\r\nprint(b)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. \"Piece of cake\" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.",
"input": "",
"output": "```python\nn=int(input())\r\na=b=c=0\r\nfor i in range(n):\r\n s=list(map(int,input().split()))\r\n a+=s[0]\r\n b+=s[1]\r\n c+=s[2]\r\nif a==b==c==0:\r\n print('YES')\r\nelse:\r\n print('NO')\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Mike is the president of country What-The-Fatherland. There are *n* bears living in this country besides Mike. All of them are standing in a line and they are numbered from 1 to *n* from left to right. *i*-th bear is exactly *a**i* feet high. \n\nA group of bears is a non-empty contiguous segment of the line. The size of a group is the number of bears in that group. The strength of a group is the minimum height of the bear in that group.\n\nMike is a curious to know for each *x* such that 1<=≤<=*x*<=≤<=*n* the maximum strength among all groups of size *x*.",
"input": "",
"output": "```python\ndef strength(bears):\r\n return (max(min(bears[displacement:displacement + group_size]) for displacement in range(len(bears) - group_size + 1)) for group_size in range(1, len(bears) + 1))\r\nuseless = input()\r\nbears = input().split(' ')\r\nfor i in strength(bears):\r\n print(i, end = ' ')\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Allen has a LOT of money. He has $n$ dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are $1$, $5$, $10$, $20$, $100$. What is the minimum number of bills Allen could receive after withdrawing his entire balance?",
"input": "",
"output": "```python\nimport math \r\n\r\ndef lotto(money):\r\n\tbills = 0\r\n\twhile money != 0:\r\n\t\tbills += math.floor(money/100) \r\n\t\tmoney %= 100\r\n\t\tbills += math.floor(money/20)\r\n\t\tmoney %= 20\r\n\t\tbills += math.floor(money/10)\r\n\t\tmoney %= 10\r\n\t\tbills += math.floor(money/5)\r\n\t\tmoney %= 5\r\n\t\tbills += math.floor(money/1)\r\n\t\tmoney %= 1\r\n\treturn bills\r\n\r\nprint(lotto(int(input())))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Imagine that there is a group of three friends: A, B and С. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The debts still mean the same but the total sum of the debts now equals 20 rubles.\n\nThis task is a generalisation of a described example. Imagine that your group of friends has *n* people and you know the debts between the people. Optimize the given debts without changing their meaning. In other words, finally for each friend the difference between the total money he should give and the total money he should take must be the same. Print the minimum sum of all debts in the optimal rearrangement of the debts. See the notes to the test samples to better understand the problem.",
"input": "",
"output": "```python\nn,m=map(int,input().split())\r\nd=dict()\r\n\r\nfor i in range(0,m):\r\n a,b,c=map(int,input().split())\r\n if a in d:\r\n d[a]=d[a]+c\r\n else:\r\n d[a]=c\r\n if b in d:\r\n d[b]=d[b]-c\r\n else:\r\n d[b]=-c\r\n\r\n\r\nprint(abs(sum([i for i in d.values() if i<0])))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "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?",
"input": "",
"output": "```python\ni = int(input())\na = 0\nwhile i >= 10:\n a += 1\n i = sum(int(x) for x in str(i))\nprint(a)\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are given a string *s* consisting of |*s*| small english letters.\n\nIn one move you can replace any character of this string to the next character in alphabetical order (a will be replaced with b, s will be replaced with t, etc.). You cannot replace letter z with any other letter.\n\nYour target is to make some number of moves (not necessary minimal) to get string abcdefghijklmnopqrstuvwxyz (english alphabet) as a subsequence. Subsequence of the string is the string that is obtained by deleting characters at some positions. You need to print the string that will be obtained from the given string and will be contain english alphabet as a subsequence or say that it is impossible.",
"input": "",
"output": "```python\nimport string\r\nalf = string.ascii_lowercase\r\ncount = 0\r\ns = list(input())\r\nfor i, el in enumerate(s):\r\n if alf.index(el) <= count:\r\n s[i] = alf[count]\r\n print(''.join(s))\r\n count += 1\r\n if count == 26:\r\n print(''.join(s))\r\n exit(0)\r\nprint(-1)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "In this problem you have to simulate the workflow of one-thread server. There are *n* queries to process, the *i*-th will be received at moment *t**i* and needs to be processed for *d**i* units of time. All *t**i* are guaranteed to be distinct.\n\nWhen a query appears server may react in three possible ways: \n 1. If server is free and query queue is empty, then server immediately starts to process this query. 1. If server is busy and there are less than *b* queries in the queue, then new query is added to the end of the queue. 1. If server is busy and there are already *b* queries pending in the queue, then new query is just rejected and will never be processed. \nAs soon as server finished to process some query, it picks new one from the queue (if it's not empty, of course). If a new query comes at some moment *x*, and the server finishes to process another query at exactly the same moment, we consider that first query is picked from the queue and only then new query appears.\n\nFor each query find the moment when the server will finish to process it or print -1 if this query will be rejected.",
"input": "",
"output": "```python\n#include \r\n#include \r\ntypedef long long ll;\r\ntypedef unsigned long long ull;\r\n#define clr(ma) memset(ma,-1,sizeof ma)\r\n#define inf 30000000;\r\n#define vi vector\r\n#define pi pair\r\n#define T2 pair\r\n#define mk make_pair\r\n#define getBit(m,i) ((m&(1<::iterator\r\n#define itr2 map >::iterator\r\n#define id(k) scanf(\"%9lf\",&k)\r\n#define fi(ss) freopen (ss,\"r\",stdin)\r\n#define fo(ss) freopen (ss,\"w\",stdout)\r\n#define clean(vis) memset(vis,0,sizeof vis)\r\nusing namespace std;\r\nint t [200000+10];\r\nint d[200000+10];\r\nint n,b;\r\nint state;\r\nint pos;\r\nqueue q;\r\nll res[200000+10];\r\nll ct;\r\nint main(){\r\n in2(n,b);\r\n for(int i=0;i=n)break;\r\n if (q.empty()){\r\n res[pos]=t[pos]+d[pos];\r\n ct=t[pos]+d[pos];\r\n pos++;\r\n }\r\n else{\r\n int v=q.front();\r\n q.pop();\r\n res[v]=ct+d[v];\r\n if (pos=1:\r\n print(\"NO\")\r\n quit()\r\n if p>=1:\r\n print(\"NO\")\r\n quit()\r\n elif h[i]>h[i+1]:\r\n p+=1\r\n elif h[i]==h[i+1]:\r\n s+=1\r\n if p>=1:\r\n print(\"NO\")\r\n quit()\r\nprint(\"YES\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "There are *n* cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers *a*1,<=*a*2,<=...,<=*a**n*. All coordinates are pairwise distinct.\n\nIt is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates.\n\nIt is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. \n\nYour task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance.",
"input": "",
"output": "```python\nn = int(input())\r\nls = list(map(int, input().split()))\r\nls.sort()\r\nk=[]\r\nfor x in range(len(ls)-1):\r\n k.append(ls[x+1] - ls[x])\r\nprint (min(k), k.count(min(k)))\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are given a tetrahedron. Let's mark its vertices with letters *A*, *B*, *C* and *D* correspondingly.\n\nAn ant is standing in the vertex *D* of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place.\n\nYou do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertex *D* to itself in exactly *n* steps. In other words, you are asked to find out the number of different cyclic paths with the length of *n* from vertex *D* to itself. As the number can be quite large, you should print it modulo 1000000007 (109<=+<=7).",
"input": "",
"output": "```python\nimport sys\r\nimport math\r\nfrom collections import Counter\r\ninput = sys.stdin.readline\r\nN = 1000000007\r\n#use input().strip() \r\n\r\ndef multiply(a, b):\r\n\tmul = [[0 for x in range(2)]\r\n\t\t\tfor y in range(2)]\r\n\tfor i in range(2):\r\n\t\tfor j in range(2):\r\n\t\t\tfor k in range(2):\r\n\t\t\t\tmul[i][j] += a[i][k] * b[k][j]\r\n\r\n\tfor i in range(2):\r\n\t\tfor j in range(2):\r\n\t\t\ta[i][j] = mul[i][j]\r\n\treturn a\r\n\r\n\r\ndef power(F, n):\r\n\tM = [[2, 3], [1, 0]]\r\n\tif (n == 1):\r\n\t\treturn F[0][0]\r\n\tpower(F, int(n / 2))\r\n\tF = multiply(F, F)\r\n\tif (n % 2 != 0):\r\n\t\tF = multiply(F, M)\r\n\treturn F[0][0]\r\n\r\nn = int(input().strip())\r\nif n == 1:\r\n print(0)\r\nelif n == 2:\r\n print(3)\r\nelse:\r\n a = [[2, 3], [1, 0]]\r\n x = power(a, n - 2)\r\n print((x * 3) % N)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are given two lists of non-zero digits.\n\nLet's call an integer pretty if its (base 10) representation has at least one digit from the first list and at least one digit from the second list. What is the smallest positive pretty integer?",
"input": "",
"output": "```python\nx,y = input().split()\n\nx = int(x)\ny = int(y)\n\no = list(map(int, input().split()))\np = list(map(int, input().split()))\n\no.sort()\np.sort()\n\na = len(o)\nb = len(p)\n\ni = 0\nj = 0\n\nwhile(i < a):\n while(j < b):\n if(o[i] == p[j]):\n print(o[i])\n break\n\n else:\n j = j+1\n\n i = i+1\n\n\nif(o[0] > p[0]):\n e = (p[0] * 10)+o[0]\n print(e)\n\nelse:\n e = (o[0] * 10)+ p[0]\n print(e)\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not.\n\nThe next prime number after *x* is the smallest prime number greater than *x*. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that there is exactly one next prime number after each number. So 5 is not the next prime number for 2.\n\nOne cold April morning Panoramix predicted that soon Kakofonix will break free from his straitjacket, and this will be a black day for the residents of the Gallic countryside.\n\nPanoramix's prophecy tells that if some day Asterix and Obelix beat exactly *x* Roman soldiers, where *x* is a prime number, and next day they beat exactly *y* Roman soldiers, where *y* is the next prime number after *x*, then it's time to wait for Armageddon, for nothing can shut Kakofonix up while he sings his infernal song.\n\nYesterday the Gauls beat *n* Roman soldiers and it turned out that the number *n* was prime! Today their victims were a troop of *m* Romans (*m*<=><=*n*). Determine whether the Gauls should wait for the black day after today's victory of Asterix and Obelix?",
"input": "",
"output": "```python\ndef isPrime(n):\r\n \r\n # Corner case\r\n if (n <= 1):\r\n return False\r\n \r\n # Check from 2 to n-1\r\n for i in range(2, n):\r\n if (n % i == 0):\r\n return False\r\n \r\n return True\r\na=[int(i) for i in input().split()]\r\nprimes=[]\r\nfor i in range(a[0],a[1]+1):\r\n primes.append(isPrime(i))\r\nif sum(primes)==2:\r\n print(\"YES\")\r\nelse:\r\n print(\"NO\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Polycarp watched TV-show where *k* jury members one by one rated a participant by adding him a certain number of points (may be negative, i. e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the *i*-th jury member gave *a**i* points.\n\nPolycarp does not remember how many points the participant had before this *k* marks were given, but he remembers that among the scores announced after each of the *k* judges rated the participant there were *n* (*n*<=≤<=*k*) values *b*1,<=*b*2,<=...,<=*b**n* (it is guaranteed that all values *b**j* are distinct). It is possible that Polycarp remembers not all of the scores announced, i. e. *n*<=<<=*k*. Note that the initial score wasn't announced.\n\nYour task is to determine the number of options for the score the participant could have before the judges rated the participant.",
"input": "",
"output": "```python\n# Jury Marks\r\n\r\nk, n = list(map(int, input().split(' ')))\r\njury_marks = list(map(int, input().split(' ')))\r\npoly_marks = list(map(int, input().split(' ')))\r\npotential = set()\r\ncurrent = poly_marks[0]\r\n\r\nfor mark in jury_marks:\r\n current += -1 * mark\r\n potential.add(current)\r\n\r\ncount = 0\r\n\r\nfor num in potential:\r\n all_vals = set()\r\n current = num\r\n for mark in jury_marks:\r\n current += mark\r\n all_vals.add(current)\r\n # print(all_vals, poly_marks)\r\n for mark in poly_marks:\r\n if not mark in all_vals:\r\n break\r\n else:\r\n count += 1\r\nprint(count)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "There are *n* servers in a laboratory, each of them can perform tasks. Each server has a unique id — integer from 1 to *n*.\n\nIt is known that during the day *q* tasks will come, the *i*-th of them is characterized with three integers: *t**i* — the moment in seconds in which the task will come, *k**i* — the number of servers needed to perform it, and *d**i* — the time needed to perform this task in seconds. All *t**i* are distinct.\n\nTo perform the *i*-th task you need *k**i* servers which are unoccupied in the second *t**i*. After the servers begin to perform the task, each of them will be busy over the next *d**i* seconds. Thus, they will be busy in seconds *t**i*,<=*t**i*<=+<=1,<=...,<=*t**i*<=+<=*d**i*<=-<=1. For performing the task, *k**i* servers with the smallest ids will be chosen from all the unoccupied servers. If in the second *t**i* there are not enough unoccupied servers, the task is ignored.\n\nWrite the program that determines which tasks will be performed and which will be ignored.",
"input": "",
"output": "```python\ndef main():\r\n n, k = map(int, input().split())\r\n ser = [0] * n\r\n for i in range(k):\r\n t, ki, v = map(int, input().split())\r\n ans = 0\r\n for el in ser:\r\n if el < t:\r\n ans += 1\r\n if ans > ki: break\r\n if ans >= ki:\r\n ans = 0\r\n j = 0\r\n while ki > 0:\r\n if ser[j] < t:\r\n ser[j] = t + v - 1\r\n ki -= 1\r\n ans += (j+1)\r\n j += 1\r\n print(ans)\r\n else:\r\n print(-1)\r\n ans = 0\r\n return 0\r\nmain()\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "You are given two positive integer numbers *a* and *b*. Permute (change order) of the digits of *a* to construct maximal number not exceeding *b*. No number in input and/or output can start with the digit 0.\n\nIt is allowed to leave *a* as it is.",
"input": "",
"output": "```python\na = sorted(input())\r\nb = int(input())\r\na = a[::-1]\r\np = \"\"\r\nwhile a:\r\n\tfor i, z in enumerate(a):\r\n\t\tn = p + a[i] + \"\".join(sorted(a[:i]+a[i+1:]))\r\n\t\tif int(n)<=b:\r\n\t\t\tp += z\r\n\t\t\ta.pop(i)\r\n\t\t\tbreak\r\nprint(p)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "A new Berland businessman Vitaly is going to open a household appliances' store. All he's got to do now is to hire the staff.\n\nThe store will work seven days a week, but not around the clock. Every day at least *k* people must work in the store.\n\nBerland has a law that determines the order of working days and non-working days. Namely, each employee must work for exactly *n* consecutive days, then rest for exactly *m* days, then work for *n* more days and rest for *m* more, and so on. Vitaly doesn't want to break the law. Fortunately, there is a loophole: the law comes into force on the day when the employee is hired. For example, if an employee is hired on day *x*, then he should work on days [*x*,<=*x*<=+<=1,<=...,<=*x*<=+<=*n*<=-<=1], [*x*<=+<=*m*<=+<=*n*,<=*x*<=+<=*m*<=+<=*n*<=+<=1,<=...,<=*x*<=+<=*m*<=+<=2*n*<=-<=1], and so on. Day *x* can be chosen arbitrarily by Vitaly.\n\nThere is one more thing: the key to the store. Berland law prohibits making copies of keys, so there is only one key. Vitaly is planning to entrust the key to the store employees. At the same time on each day the key must be with an employee who works that day — otherwise on this day no one can get inside the store. During the day the key holder can give the key to another employee, if he also works that day. The key will handed to the first hired employee at his first working day.\n\nEach employee has to be paid salary. Therefore, Vitaly wants to hire as few employees as possible provided that the store can operate normally on each day from 1 to infinity. In other words, on each day with index from 1 to infinity, the store must have at least *k* working employees, and one of the working employees should have the key to the store.\n\nHelp Vitaly and determine the minimum required number of employees, as well as days on which they should be hired.",
"input": "",
"output": "```python\nn,m,k = map(int,input().split())\n\n\nans = [1 for i in range(k)]\n\ntransition = True\nfor i in range(n-1, n+m):\n\n if transition: \n if ans[-k]+n == i+1:\n ans.append(i)\n if k > 1:\n transition = False\n else: \n if ans[-k]+n == i:\n ans.extend([i]*(max(1, k-1)))\n transition = True\n \nprint(*ans)\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Recently *n* students from city S moved to city P to attend a programming camp.\n\nThey moved there by train. In the evening, all students in the train decided that they want to drink some tea. Of course, no two people can use the same teapot simultaneously, so the students had to form a queue to get their tea.\n\n*i*-th student comes to the end of the queue at the beginning of *l**i*-th second. If there are multiple students coming to the queue in the same moment, then the student with greater index comes after the student with lesser index. Students in the queue behave as follows: if there is nobody in the queue before the student, then he uses the teapot for exactly one second and leaves the queue with his tea; otherwise the student waits for the people before him to get their tea. If at the beginning of *r**i*-th second student *i* still cannot get his tea (there is someone before him in the queue), then he leaves the queue without getting any tea. \n\nFor each student determine the second he will use the teapot and get his tea (if he actually gets it).",
"input": "",
"output": "```python\nimport sys\r\ninput = sys.stdin.readline\r\n\r\nfor _ in range(int(input())):\r\n n = int(input())\r\n g = [list(map(int, input().split())) for _ in range(n)]\r\n\r\n d = []\r\n c = 1\r\n x = 0\r\n for i in range(n):\r\n if g[i][0] - x >= c:\r\n d.append(g[i][0])\r\n c = g[i][0] + 1\r\n else:\r\n c += 1\r\n if g[i][1] <= c:\r\n d.append(0)\r\n else:\r\n d.append(g[i][0]+c-x)\r\n c -= 1\r\n x = g[i][0]\r\n print(*d)\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Let quasi-palindromic number be such number that adding some leading zeros (possible none) to it produces a palindromic string. \n\nString *t* is called a palindrome, if it reads the same from left to right and from right to left.\n\nFor example, numbers 131 and 2010200 are quasi-palindromic, they can be transformed to strings \"131\" and \"002010200\", respectively, which are palindromes.\n\nYou are given some integer number *x*. Check if it's a quasi-palindromic number.",
"input": "",
"output": "```python\na=input()\r\ni=len(a)-1\r\nwhile(a[i]=='0'):i-=1\r\nif a[:i+1]==a[len(a)-i+1::-1]:print(\"YES\")\r\nelse:print(\"NO\")\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Sometimes one has to spell email addresses over the phone. Then one usually pronounces a dot as dot, an at sign as at. As a result, we get something like vasyaatgmaildotcom. Your task is to transform it into a proper email address ([[email protected]](/cdn-cgi/l/email-protection)). \n\nIt is known that a proper email address contains only such symbols as . @ and lower-case Latin letters, doesn't start with and doesn't end with a dot. Also, a proper email address doesn't start with and doesn't end with an at sign. Moreover, an email address contains exactly one such symbol as @, yet may contain any number (possible, zero) of dots. \n\nYou have to carry out a series of replacements so that the length of the result was as short as possible and it was a proper email address. If the lengths are equal, you should print the lexicographically minimal result. \n\nOverall, two variants of replacement are possible: dot can be replaced by a dot, at can be replaced by an at.",
"input": "",
"output": "```python\nemail = input()\n\n\nidx_at = email.index(\"at\")\nidx_dot = email.index(\"dot\")\n\n\nprint(email[0:idx_at] + \"@\" + email[idx_at+2:idx_dot] + \".\" + email[idx_dot+3:len(email)])\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "One day Kefa found *n* baloons. For convenience, we denote color of *i*-th baloon as *s**i* — lowercase letter of the Latin alphabet. Also Kefa has *k* friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. Help Kefa to find out, can he give out all his baloons, such that no one of his friens will be upset — print «YES», if he can, and «NO», otherwise. Note, that Kefa's friend will not upset, if he doesn't get baloons at all.",
"input": "",
"output": "```python\nballons, friends = map(int, input().split())\r\ncolor = input()\r\nlencolor = len(color)\r\nx = 0\r\ncount = [0] * 26 # букв всего 26б значит и индекс не мсжет быть болше 26\r\n# tkcb кол-во одного цвета больше чем друзейб кто-то получит два одного цвета\r\nfor i in color:\r\n nomer = ord(i) - 97\r\n count[nomer] += 1 # индексы плюсуются\r\nfor i in range(26):\r\n if count[i] > friends:\r\n # print(chr(i + 97), count[i])\r\n # elif count[i] > friends:\r\n x += 1\r\nif x > 0:\r\n print('NO')\r\nelse:\r\n print('YES')\r\n\n```"
},
{
"source": "MatrixStudio/Codeforces-Python-Submissions",
"instruction": "Once upon a time a child got a test consisting of multiple-choice questions as homework. A multiple-choice question consists of four choices: A, B, C and D. Each choice has a description, and the child should find out the only one that is correct.\n\nFortunately the child knows how to solve such complicated test. The child will follow the algorithm:\n - If there is some choice whose description at least twice shorter than all other descriptions, or at least twice longer than all other descriptions, then the child thinks the choice is great. - If there is exactly one great choice then the child chooses it. Otherwise the child chooses C (the child think it is the luckiest choice). \nYou are given a multiple-choice questions, can you predict child's choose?",
"input": "",
"output": "```python\na=input()\r\nb=input()\r\nc=input()\r\nd=input()\r\nif((len(a)-2)>=(len(b)-2)*2 and (len(a)-2)>=(len(c)-2)*2 and (len(a)-2)>=(len(d)-2)*2):\r\n print(\"A\")\r\nelif((len(b)-2)>=(len(a)-2)*2 and (len(b)-2)>=(len(c)-2)*2 and (len(b)-2)>=(len(d)-2)*2):\r\n print(\"B\")\r\nelif((len(d)-2)>=(len(b)-2)*2 and (len(d)-2)>=(len(c)-2)*2 and (len(d)-2)>=(len(a)-2)*2):\r\n print(\"D\") \r\nelif((len(a)-2)*2