source
stringclasses
3 values
instruction
stringlengths
23
3.97k
input
stringclasses
1 value
output
stringlengths
1
3.75k
MatrixStudio/Codeforces-Python-Submissions
The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has *n* students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times. The head of the SSU OPTC is recently gathering teams to participate in the world championship. Each team must consist of exactly three people, at that, any person cannot be a member of two or more teams. What maximum number of teams can the head make if he wants each team to participate in the world championship with the same members at least *k* times?
```python ######################################################################## "#######################################################################" ######################################################################## "Author = Fasih_ur_Rehman" #| <>"" <>"" <>"" <>"" <>"" <>"" <>"" <>"" <>"" #### "| <>"" <>"" <>"" <>"" <>"" <>"" <>"" <>"" <>"" ####" #| <> <> <> <> <> <> <> <> <> #### "_________ ____ _____ ___ __ __ " #| \ / \/ / \ |\ \ | \ | \ #### "| β–“β–“β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–“ /β–“β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ\ β–“β–“β–“β–“β–“β–“\| | β–ˆβ–ˆβ–ˆ | β–ˆβ–ˆ | β–ˆβ–ˆ ####" #| β–“β–“_____ β–“β–“__| β–“β–“ β–ˆβ–ˆ___\β–ˆβ–ˆ| | β–“β–“β–“ | β–“β–“__| β–“β–“ #### "| β–ˆβ–ˆ \ β–“β–“ β–“β–“ \β–ˆβ–ˆ \ | β–ˆβ–ˆβ–ˆ | β–“β–“ β–“β–“ ####" #| β–“β–“β–“β–ˆβ–ˆβ–ˆβ–ˆβ–“ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ \β–“β–“β–“β–“β–“β–“\ | β–“β–“β–“ | β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ #### "| β–ˆβ–ˆ β–“β–“ | β–“β–“ \__| β–ˆβ–ˆ| | β–ˆβ–ˆβ–ˆ | β–“β–“ | β–“β–“ ####" #| β–“β–“ β–“β–“ | β–“β–“ \β–ˆβ–ˆ β–ˆβ–ˆ| | β–“β–“β–“ | β–“β–“ | β–“β–“ #### "\_β–ˆβ–ˆ β–ˆβ–ˆ \β–ˆβ–ˆ \β–“β–“β–“β–“β–“β–“/ \_β–ˆβ–ˆβ–ˆ \_β–ˆβ–ˆ \_β–ˆβ–ˆ ####" #| <>"" <>"" <>"" <>"" <>"" <>"" <>"" <>"" <>"" #### "| <>"" <>"" <>"" <>"" <>"" <>"" <>"" <>"" <>"" ####" #| <> <> <> <> <> <> <> <> <> #### "#######################################################################" ######################################################################## "#######################################################################" a,b = map(int,input().split()) x = list(map(int,input().split())) c = 0 for i in range(a): if 5-x[i]>=b: c+=1 print(c//3) ```
MatrixStudio/Codeforces-Python-Submissions
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed *w* kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem. Pete and Billy are great fans of even numbers, that's why they want to divide the watermelon in such a way that each of the two parts weighs even number of kilos, at the same time it is not obligatory that the parts are equal. The boys are extremely tired and want to start their meal as soon as possible, that's why you should help them and find out, if they can divide the watermelon in the way they want. For sure, each of them should get a part of positive weight.
```python def watermelon(w): if w%2 == 0 and w >= 1 and w <= 100: return("YES") else: return("NO") w = int(input()) print(watermelon(w)) ```
MatrixStudio/Codeforces-Python-Submissions
Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone. In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules of the game, Jury must use this second to touch the corresponding strip to make the square go away. As Jury is both smart and lazy, he counted that he wastes exactly *a**i* calories on touching the *i*-th strip. You've got a string *s*, describing the process of the game and numbers *a*1,<=*a*2,<=*a*3,<=*a*4. Calculate how many calories Jury needs to destroy all the squares?
```python strips = list(map(int, input().split())) seconds = list(map(int, input())) result = sum([strips[i - 1] for i in seconds]) print(result) ```
MatrixStudio/Codeforces-Python-Submissions
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. Grisha 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. Right 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.
```python ο»Ώusing System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _1 { class Program { static void Main(string[] args) { string S = Console.ReadLine(); string[] Mas = S.Split(' '); Int64[] mas = { 0, 0 }; mas[0] = Int64.Parse(Mas[0]); mas[1] = Int64.Parse(Mas[1]); S = Console.ReadLine(); String[] Mas2 = S.Split(' '); Int64[] cnt = { 0, 0, 0 }; for (Int64 i = 0; i < 3; i++) cnt[i] = Int64.Parse(Mas2[i]); Int64[] req = { 0, 0 }; req[0] += 2 * cnt[0] + cnt[1]; req[1] += 3 * cnt[2] + cnt[1]; Int64 ans = req[0] - mas[0] + req[1] - mas[1]; Console.WriteLine(ans); } } } ```
MatrixStudio/Codeforces-Python-Submissions
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." The problem is: You 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. If we sort all lucky numbers in increasing order, what's the 1-based index of *n*? Tavas 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.
```python # Tavas and Saddas lucky = input() satuan = 0 count = 0 total = 0 for x in range(len(lucky)): count = 2**satuan if lucky[x]=='7': count*=2 total+=count satuan+=1 print(total) ```
MatrixStudio/Codeforces-Python-Submissions
The circle line of the Berland subway has *n* stations. We know the distances between all pairs of neighboring stations: - *d*1 is the distance between the 1-st and the 2-nd station;- *d*2 is the distance between the 2-nd and the 3-rd station;...- *d**n*<=-<=1 is the distance between the *n*<=-<=1-th and the *n*-th station;- *d**n* is the distance between the *n*-th and the 1-st station. The trains go along the circle line in both directions. Find the shortest distance between stations with numbers *s* and *t*.
```python n = int(input()) a = list(map(int, input().split())) s, t = map(int, input().split()) if s > t: s, t = t, s sum1 = sum(a[s - 1: t - 1]) if sum1 < sum(a) - sum1: print(sum1) else: print(sum(a) - sum1) ```
MatrixStudio/Codeforces-Python-Submissions
Fox Ciel starts to learn programming. The first task is drawing a fox! However, that turns out to be too hard for a beginner, so she decides to draw a snake instead. A snake is a pattern on a *n* by *m* table. Denote *c*-th cell of *r*-th row as (*r*,<=*c*). The tail of the snake is located at (1,<=1), then it's body extends to (1,<=*m*), then goes down 2 rows to (3,<=*m*), then goes left to (3,<=1) and so on. Your task is to draw this snake for Fox Ciel: the empty cells should be represented as dot characters ('.') and the snake cells should be filled with number signs ('#'). Consider sample tests in order to understand the snake pattern.
```python n,m=map(int,input().split()) dot="."*(m-1) flag=0 flag1=0 for i in range(n): if flag==0: print("#"*m) flag=1 else: if flag1==0: print(dot,end="") print("#") flag1=1 flag=0 else: print("#",end="") print(dot) flag1=0 flag=0 ```
MatrixStudio/Codeforces-Python-Submissions
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. Ostap 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. Your 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.
```python import sys n, k = (int(i) for i in sys.stdin.readline().split()) seq = sys.stdin.readline().split()[0] G, T = 0, 0 for i, char in enumerate(seq): if char == 'G': G = i if char == 'T': T = i start = min(G, T) end = max(G, T) while start < end: if seq[start] == '#': print("NO") break start += k if start == end: print("YES") print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Santa Claus is the first who came to the Christmas Olympiad, and he is going to be the first to take his place at a desk! In the classroom there are *n* lanes of *m* desks each, and there are two working places at each of the desks. The lanes are numbered from 1 to *n* from the left to the right, the desks in a lane are numbered from 1 to *m* starting from the blackboard. Note that the lanes go perpendicularly to the blackboard, not along it (see picture). The organizers numbered all the working places from 1 to 2*nm*. The places are numbered by lanes (i.Β e. all the places of the first lane go first, then all the places of the second lane, and so on), in a lane the places are numbered starting from the nearest to the blackboard (i.Β e. from the first desk in the lane), at each desk, the place on the left is numbered before the place on the right. Santa Clause knows that his place has number *k*. Help him to determine at which lane at which desk he should sit, and whether his place is on the left or on the right!
```python import math n,m,k=map(int,input().split()) s=n*2*m l=math.ceil((k/(2*m))) c=k-(l-1)*2*m r=math.ceil(c/(2)) if k%2==0: print(l,r,"R") else: print(l,r,"L") ```
MatrixStudio/Codeforces-Python-Submissions
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... Today 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. Help 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.
```python n=int(input()) lst=list(map(int,input().split())) s=0 lst.sort(reverse=True) for i in range(len(lst)): s=s+lst[i] if s>=n: print(i+1) break ```
MatrixStudio/Codeforces-Python-Submissions
Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number *n*. How many times can Gerald put a spell on it until the number becomes one-digit?
```python print(int(input()%9) ```
MatrixStudio/Codeforces-Python-Submissions
ZS the Coder is playing a game. There is a number displayed on the screen and there are two buttons, '<=+<=' (plus) and '' (square root). Initially, the number 2 is displayed on the screen. There are *n*<=+<=1 levels in the game and ZS the Coder start at the level 1. When ZS the Coder is at level *k*, he can : 1. Press the '<=+<=' button. This increases the number on the screen by exactly *k*. So, if the number on the screen was *x*, it becomes *x*<=+<=*k*.1. Press the '' button. Let the number on the screen be *x*. After pressing this button, the number becomes . After that, ZS the Coder levels up, so his current level becomes *k*<=+<=1. This button can only be pressed when *x* is a perfect square, i.e. *x*<==<=*m*2 for some positive integer *m*. Additionally, after each move, if ZS the Coder is at level *k*, and the number on the screen is *m*, then *m* must be a multiple of *k*. Note that this condition is only checked after performing the press. For example, if ZS the Coder is at level 4 and current number is 100, he presses the '' button and the number turns into 10. Note that at this moment, 10 is not divisible by 4, but this press is still valid, because after it, ZS the Coder is at level 5, and 10 is divisible by 5. ZS the Coder needs your help in beating the gameΒ β€” he wants to reach level *n*<=+<=1. In other words, he needs to press the '' button *n* times. Help him determine the number of times he should press the '<=+<=' button before pressing the '' button at each level. Please note that ZS the Coder wants to find just any sequence of presses allowing him to reach level *n*<=+<=1, but not necessarily a sequence minimizing the number of presses.
```python ###### ### ####### ####### ## # ##### ### ##### # # # # # # # # # # # # # ### # # # # # # # # # # # # # ### ###### ######### # # # # # # ######### # ###### ######### # # # # # # ######### # # # # # # # # # # # #### # # # # # # # # # # ## # # # # # ###### # # ####### ####### # # ##### # # # # # from __future__ import print_function # for PyPy2 from itertools import permutations as perm # from fractions import Fraction from collections import * from sys import stdin from bisect import * from heapq import * from math import * g = lambda : stdin.readline().strip() gl = lambda : g().split() gil = lambda : [int(var) for var in gl()] gfl = lambda : [float(var) for var in gl()] gcl = lambda : list(g()) gbs = lambda : [int(var) for var in g()] mod = int(1e9)+7 inf = float("inf") n, = gil() n = int(1e5) ans = [] m = 2 for k in range(1, n+1): i = k*((k+1)**2) - (m//k) print(m) m = k*(k+1) ```
MatrixStudio/Codeforces-Python-Submissions
Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks. Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off. You know that there will be *n* interesting minutes *t*1,<=*t*2,<=...,<=*t**n*. Your task is to calculate for how many minutes Limak will watch the game.
```python n = int(input()) t = map(int, input().split()) m = 0 for i in t: if i - m > 15: m += 15 else: m = i print(m) ```
MatrixStudio/Codeforces-Python-Submissions
In this problem you are to calculate the sum of all integers from 1 to *n*, but you should take all powers of two with minus in the sum. For example, for *n*<==<=4 the sum is equal to <=-<=1<=-<=2<=+<=3<=-<=4<==<=<=-<=4, because 1, 2 and 4 are 20, 21 and 22 respectively. Calculate the answer for *t* values of *n*.
```python minus = set() i = 1 while i < 10 ** 10: minus.add(i) i *= 2 for _ in range(int(input())): n = int(input()) _sum = 0 for i in range(1, n + 1): if i % 10000 == 0: print(f"i: {i}") if i in minus: _sum -= i else: _sum += i print(_sum) ```
MatrixStudio/Codeforces-Python-Submissions
There is a system of *n* vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to *n*, in the order from the highest to the lowest, the volume of the *i*-th vessel is *a**i* liters. Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the *i*-th vessel goes to the (*i*<=+<=1)-th one. The liquid that overflows from the *n*-th vessel spills on the floor. Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: 1. Add *x**i* liters of water to the *p**i*-th vessel; 1. Print the number of liters of water in the *k**i*-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.
```python import sys input = sys.stdin.readline if __name__ == '__main__': n = int(input()) maxvol = list(map(int, input().split())) nxt = list(range(n + 2)) vol = [0] * n def addwater(i, water): if i >= n or water == 0: return vol[i] += water if vol[i] >= maxvol[i]: water, vol[i] = vol[i] - maxvol[i], maxvol[i] toadd = i + 1 while toadd != nxt[toadd]: toadd = nxt[toadd] nxt[i] = toadd addwater(toadd, water) m = int(input()) for i in range(m): f = list(map(int, input().split())) if len(f) == 3: addwater(f[1] - 1, f[2]) if len(f) == 2: print(vol[f[1] - 1]) ```
MatrixStudio/Codeforces-Python-Submissions
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. Help Yaroslav.
```python n = int(input()) b = dict() for x in list(map(int, input().split())): if x not in b.keys(): b[x] = 1 else: b[x] += 1 if any(b[x] > (n + 1) / 2 for x in b.keys()): print('NO') else: print('YES') ```
MatrixStudio/Codeforces-Python-Submissions
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word *s*. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if Vasya types the word "ahhellllloou", it will be considered that he said hello, and if he types "hlelo", it will be considered that Vasya got misunderstood and he didn't manage to say hello. Determine whether Vasya managed to say hello by the given word *s*.
```python s=input() target='hello' tmp=0 for i in target: tmp=s.find(i,tmp+1) if tmp==-1: print('NO') break else: print('YES') ```
MatrixStudio/Codeforces-Python-Submissions
"To curtain off the moonlight should be hardly possible; the shades present its mellow beauty and restful nature." Intonates Mino. "See? The clouds are coming." Kanno gazes into the distance. "That can't be better," Mino turns to Kanno. The sky can be seen as a one-dimensional axis. The moon is at the origin whose coordinate is $0$. There are $n$ clouds floating in the sky. Each cloud has the same length $l$. The $i$-th initially covers the range of $(x_i, x_i + l)$ (endpoints excluded). Initially, it moves at a velocity of $v_i$, which equals either $1$ or $-1$. Furthermore, no pair of clouds intersect initially, that is, for all $1 \leq i \lt j \leq n$, $\lvert x_i - x_j \rvert \geq l$. With a wind velocity of $w$, the velocity of the $i$-th cloud becomes $v_i + w$. That is, its coordinate increases by $v_i + w$ during each unit of time. Note that the wind can be strong and clouds can change their direction. You are to help Mino count the number of pairs $(i, j)$ ($i &lt; j$), such that with a proper choice of wind velocity $w$ not exceeding $w_\mathrm{max}$ in absolute value (possibly negative and/or fractional), the $i$-th and $j$-th clouds both cover the moon at the same future moment. This $w$ doesn't need to be the same across different pairs.
```python # -*- coding: utf-8 -*- """ @Project : CodeForces @File : 4.py @Time : 2018/6/11 23:01 @Author : Koushiro """ def find_bigger(num): for j in range(len(b_wind)): if b_wind[j] >= num: break return len(b_wind) - j if __name__ == "__main__": n, l, w_max = map(int, input().split()) a_wind = [] b_wind = [] for i in range(n): x, y = map(int, input().split()) if y == 1: a_wind.append(x) else: b_wind.append(x) b_wind.sort() result = 0 for i in range(len(a_wind)): if a_wind[i] < 0: left = a_wind[i] + (-2 * a_wind[i] - l) / (w_max + 1) result += find_bigger(left) else: if (w_max!=1): right = a_wind[i] + (2 * a_wind[i] + l) / (w_max -1) result += find_bigger(right) print(result) ```
MatrixStudio/Codeforces-Python-Submissions
Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced programmer. Actually he is not a programmer at all. So he wasn't able to solve them. That's why he asked you to help him with these tasks. One of these tasks is the following. A sequence of *l* integers *b*1,<=*b*2,<=...,<=*b**l* (1<=≀<=*b*1<=≀<=*b*2<=≀<=...<=≀<=*b**l*<=≀<=*n*) is called good if each number divides (without a remainder) by the next number in the sequence. More formally for all *i* (1<=≀<=*i*<=≀<=*l*<=-<=1). Given *n* and *k* find the number of good sequences of length *k*. As the answer can be rather large print it modulo 1000000007 (109<=+<=7).
```python n, k = list(map(int, input().split())) s = [] for i in range(1, n+1): s.append(i) tot = 0 dp = dict() def combo(c, s, ci, k, dp): # print(c, ci) if len(c) == k: # print(c) global tot tot += 1 return for i in range(ci, len(s)): if len(c) == 0: c.append(s[i]) combo(c,s,i,k, dp) del c[-1] elif s[i] % c[-1] == 0: c.append(s[i]) key = (len(c), c[-1]) if key in dp: tot += dp[key] else: combo(c,s,i,k, dp) del c[-1] else: return combo([], s, 0, k, dp) print(tot) ```
MatrixStudio/Codeforces-Python-Submissions
You are locked in a room with a door that has a keypad with 10 keys corresponding to digits from 0 to 9. To escape from the room, you need to enter a correct code. You also have a sequence of digits. Some keys on the keypad have fingerprints. You believe the correct code is the longest not necessarily contiguous subsequence of the sequence you have that only contains digits with fingerprints on the corresponding keys. Find such code.
```python n, m = map(int, input().split()) x = list(map(int, input().split())) y = list(map(int, input().split())) for i in x: for j in y: if j in x: if i == j: print(j,end = " ") break ```
MatrixStudio/Codeforces-Python-Submissions
Hands that shed innocent blood! There are *n* guilty people in a line, the *i*-th of them holds a claw with length *L**i*. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the *i*-th person kills the *j*-th person if and only if *j*<=&lt;<=*i* and *j*<=β‰₯<=*i*<=-<=*L**i*. You are given lengths of the claws. You need to find the total number of alive people after the bell rings.
```python n = int(input()) L = list(map(int, input().split())) r = -1 dead = 0 for i in range(1, n): c = i - L[i] ln = i - max(c, 0) dead += i - max(i - ln, r + 1) if ln > 0: r = i - 1 print(n - dead) ```
MatrixStudio/Codeforces-Python-Submissions
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. In 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. Help Vitya find out if a word $s$ is Berlanese.
```python vowels = "aiueo" s = input() for i in range(len(s)): if s[i] not in vowels + 'n' and s[i + 1] not in vowels: print("NO") exit() print("YES") ```
MatrixStudio/Codeforces-Python-Submissions
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. Consider 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. Manao 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.
```python import sys input = sys.stdin.readline ################ ---- Input Functions ---- ################ def integer_input(): return(int(input())) def integer_list_input(): return list(map(int, input().split())) def string_input(): string_with_newline = input() return string_with_newline[:len(string_with_newline) - 1] def multiple_integers_input(): return map(int, input().split()) ################ ---- Solution ---- ################ def minimum_presses(buttons): left, right, presses = buttons - 1, 1, 0 while left > 0: presses += left * right left += 1 right -= 1 presses += buttons return presses # 2 # 1 2 => 2 * 1 + 1 * 2 => 1 * 1 + 1 * 2 = 1 + 2 = 3 # 3 # 1 2 3 => 3 * 1 + 2 * 2 + 1 * 3 => 2 * 1 + 1 * 2 + 1 * 3 = 7 # 4 # 1 2 3 4: (4 * 1) + (3 * (1+1)) + (2 * (2+1)) + (1 * (3+1)) = 3*1 + 2*2 + 1*3 + 1*4 print(minimum_presses(integer_input())) ```
MatrixStudio/Codeforces-Python-Submissions
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: - 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. Your 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.
```python l = list(map(int, input().split())) ok=True for i in range(6): if l.count(l[i])>=4: ok = False f=l[i] if ok: print("Alien") else: for i in range(4): l.pop(l.index(f)) print(["Bear", "Elephant"][l[0]==l[1]]) ```
MatrixStudio/Codeforces-Python-Submissions
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. Vanya wants to know how many digits he will have to write down as he labels the books.
```python n=int(input()) s=len(str(n)) print(s*n + s - int('1'*s)) ```
MatrixStudio/Codeforces-Python-Submissions
Kuriyama Mirai has killed many monsters and got many (namely *n*) stones. She numbers the stones from 1 to *n*. The cost of the *i*-th stone is *v**i*. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions: 1. She will tell you two numbers, *l* and *r*Β (1<=≀<=*l*<=≀<=*r*<=≀<=*n*), and you should tell her . 1. Let *u**i* be the cost of the *i*-th cheapest stone (the cost that will be on the *i*-th place if we arrange all the stone costs in non-decreasing order). This time she will tell you two numbers, *l* and *r*Β (1<=≀<=*l*<=≀<=*r*<=≀<=*n*), and you should tell her . For every question you should give the correct answer, or Kuriyama Mirai will say "fuyukai desu" and then become unhappy.
```python input() s = input() s1 = list(map(int, s.split())) s2 = sorted(s1) for i in range(1, len(s1)): s1[i] += s1[i - 1] s2[i] += s2[i - 1] for _ in range(int(input())): case, left, right = map(int, input().split()) if case == 1: print(s1[right - 1] - s1[left - 2] if left - 2 >= 0 else s1[right - 1]) else: print(s2[right - 1] - s2[left - 2] if left - 2 >= 0 else s2[right - 1]) ```
MatrixStudio/Codeforces-Python-Submissions
Professor GukiZ makes a new robot. The robot are in the point with coordinates (*x*1,<=*y*1) and should go to the point (*x*2,<=*y*2). In a single step the robot can change any of its coordinates (maybe both of them) by one (decrease or increase). So the robot can move in one of the 8 directions. Find the minimal number of steps the robot should make to get the finish position.
```python def solve(): x1, y1 = map(int, input().split()) x2, y2 = map(int, input().split()) print(max(abs(x1 - x2), abs(y1 - y2))) if __name__ == "__main__": solve() ```
MatrixStudio/Codeforces-Python-Submissions
Tonio has a keyboard with only two letters, "V" and "K". One 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.
```python s=input() c=s.count('VK') if(s=='VV'): c=1 if('VVV' in s or 'KKK' in s): c=c+1 print(c) ```
MatrixStudio/Codeforces-Python-Submissions
Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number *a* and Antisimon receives number *b*. They also have a heap of *n* stones. The players take turns to make a move and Simon starts. During a move a player should take from the heap the number of stones equal to the greatest common divisor of the fixed number he has received and the number of stones left in the heap. A player loses when he cannot take the required number of stones (i. e. the heap has strictly less stones left than one needs to take). Your task is to determine by the given *a*, *b* and *n* who wins the game.
```python import math n,a,b=map(int,input().split()) i=0 while(n>0): if i==0: n-=math.gcd(n,a) i=1-i elif i==1: n-=math.gcd(n,b) i=1-i print(1-i) ```
MatrixStudio/Codeforces-Python-Submissions
Walking through the streets of Marshmallow City, Slastyona have spotted some merchants selling a kind of useless toy which is very popular nowadays – caramel spinner! Wanting to join the craze, she has immediately bought the strange contraption. Spinners in Sweetland have the form of V-shaped pieces of caramel. Each spinner can, well, spin around an invisible magic axis. At a specific point in time, a spinner can take 4 positions shown below (each one rotated 90 degrees relative to the previous, with the fourth one followed by the first one): After the spinner was spun, it starts its rotation, which is described by a following algorithm: the spinner maintains its position for a second then majestically switches to the next position in clockwise or counter-clockwise order, depending on the direction the spinner was spun in. Slastyona managed to have spinner rotating for exactly *n* seconds. Being fascinated by elegance of the process, she completely forgot the direction the spinner was spun in! Lucky for her, she managed to recall the starting position, and wants to deduct the direction given the information she knows. Help her do this.
```python s,e=map(str,input().split()) n=int(input()) def clk(st,n,lis): sti=lis.index(st) n=n-n//5 p=4-sti if(n<=p): return(lis[sti+n]) else: n=n-p return(lis[n]) def aclk(st,n,lis): sti=lis.index(st)+1 n=n-n//5 if(n<=sti): return(lis[sti-n]) else: n=n-sti return(lis[-n]) lis=['v', '<', '^' ,'>' ,'v'] ck=clk(s,n,lis) ack=aclk(s,n,lis) if(ck==e): print('cw') elif(ack==e): print('ccw') else: print('undefined') ```
MatrixStudio/Codeforces-Python-Submissions
Sereja and Dima play a game. The rules of the game are very simple. The players have *n* cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The game ends when there is no more cards. The player who has the maximum sum of numbers on his cards by the end of the game, wins. Sereja and Dima are being greedy. Each of them chooses the card with the larger number during his move. Inna is a friend of Sereja and Dima. She knows which strategy the guys are using, so she wants to determine the final score, given the initial state of the game. Help her.
```python user = int(input()) card_val = [int(x) for x in input().split()] S_1 = 0 D_1 = 0 i = 0 k = 0 while len(card_val) != 0: if k % 2 == 0: if card_val[i] > card_val[len(card_val)-1-i]: S_1 += card_val[i] del card_val[i] k += 1 else: S_1 += card_val[len(card_val)-1-i] del card_val[len(card_val)-1-i] k += 1 else: if card_val[i] > card_val[len(card_val) - 1-i]: D_1 += card_val[i] del card_val[i] k += 1 else: D_1 += card_val[len(card_val) - 1-i] del card_val[len(card_val) - 1 - i] k +=1 print(S_1,D_1) ```
MatrixStudio/Codeforces-Python-Submissions
Dreamoon wants to climb up a stair of *n* steps. He can climb 1 or 2 steps at each move. Dreamoon wants the number of moves to be a multiple of an integer *m*. What is the minimal number of moves making him climb to the top of the stairs that satisfies his condition?
```python n,m=map(int,input().split()) t=(n+1)//2 s=(t-1)//m*m+m print([s,-1][s>n]) ```
MatrixStudio/Codeforces-Python-Submissions
The World Programming Olympics Medal is a metal disk, consisting of two parts: the first part is a ring with outer radius of *r*1 cm, inner radius of *r*2 cm, (0<=&lt;<=*r*2<=&lt;<=*r*1) made of metal with density *p*1 g/cm3. The second part is an inner disk with radius *r*2 cm, it is made of metal with density *p*2 g/cm3. The disk is nested inside the ring. The Olympic jury decided that *r*1 will take one of possible values of *x*1,<=*x*2,<=...,<=*x**n*. It is up to jury to decide which particular value *r*1 will take. Similarly, the Olympic jury decided that *p*1 will take one of possible value of *y*1,<=*y*2,<=...,<=*y**m*, and *p*2 will take a value from list *z*1,<=*z*2,<=...,<=*z**k*. According to most ancient traditions the ratio between the outer ring mass *m**out* and the inner disk mass *m**in* must equal , where *A*,<=*B* are constants taken from ancient books. Now, to start making medals, the jury needs to take values for *r*1, *p*1, *p*2 and calculate the suitable value of *r*2. The jury wants to choose the value that would maximize radius *r*2. Help the jury find the sought value of *r*2. Value *r*2 doesn't have to be an integer. Medal has a uniform thickness throughout the area, the thickness of the inner disk is the same as the thickness of the outer ring.
```python r1 = list(map(int , input().split())) n = r1.pop(0) r1.sort() r = r1[-1] p1 = list(map(int , input().split())) m = p1.pop(0) p1.sort() a = p1[-1] p2 = list(map(int , input().split())) k = p2.pop(0) p2.sort() b = p2[0] A , B = map(int , input().split()) B *= (a/b) import math print(r*(math.sqrt(B/(A + B)))) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At that as little as possible letters should be changed in the word. For example, the word HoUse must be replaced with house, and the word ViP β€” with VIP. If a word contains an equal number of uppercase and lowercase letters, you should replace all the letters with lowercase ones. For example, maTRIx should be replaced by matrix. Your task is to use the given method on one given word.
```python s = input() low = 0 high = 0 for c in s: if ord(c) >= ord('a'): low += 1 else: high += 1 if max(low, high) == low: print(s.lower()) else: print(s.upper()) ```
MatrixStudio/Codeforces-Python-Submissions
Two players play a game. Initially 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. The first player wants to minimize the last number that would be left on the board, while the second player wants to maximize it. You want to know what number will be left on the board after $n - 1$ turns if both players make optimal moves.
```python n=int(input()) a=list(map(int,input().split())) a.sort() x=sum(a) print((x//2)-1) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya decided to write an anonymous letter cutting the letters out of a newspaper heading. He knows heading *s*1 and text *s*2 that he wants to send. Vasya can use every single heading letter no more than once. Vasya doesn't have to cut the spaces out of the heading β€” he just leaves some blank space to mark them. Help him; find out if he will manage to compose the needed text.
```python s1=input() s2=input() l1=[] l2=[] ans=True for i in list(set(list(s2))): l1.append(s1.count(i)) l2.append(s2.count(i)) for x,y in zip(l1,l2): if x<y: ans=False break if ans is False: print("NO") else: print("YES") ```
MatrixStudio/Codeforces-Python-Submissions
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*. What 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.
```python n, m, a = map(int, input().split()) if n % a != 0: nn = n // a + 1 else: nn = n // a if m % a != 0: mm = m // a + 1 else: mm = m // a print(nn * mm) ```
MatrixStudio/Codeforces-Python-Submissions
Some days ago, I learned the concept of LCM (least common multiple). I've played with it for several times and I want to make a big number with it. But I also don't want to use many numbers, so I'll choose three positive integers (they don't have to be distinct) which are not greater than *n*. Can you help me to find the maximum possible least common multiple of these three integers?
```python n = int(input()) a = n b = max(1, n-1) c = max(1, n-2) print(a*b*c) ```
MatrixStudio/Codeforces-Python-Submissions
Little Petya is learning to play chess. He has already learned how to move a king, a rook and a bishop. Let us remind you the rules of moving chess pieces. A chessboard is 64 square fields organized into an 8<=Γ—<=8 table. A field is represented by a pair of integers (*r*,<=*c*) β€” the number of the row and the number of the column (in a classical game the columns are traditionally indexed by letters). Each chess piece takes up exactly one field. To make a move is to move a chess piece, the pieces move by the following rules: - A rook moves any number of fields horizontally or vertically. - A bishop moves any number of fields diagonally. - A king moves one field in any direction β€” horizontally, vertically or diagonally. Petya is thinking about the following problem: what minimum number of moves is needed for each of these pieces to move from field (*r*1,<=*c*1) to field (*r*2,<=*c*2)? At that, we assume that there are no more pieces besides this one on the board. Help him solve this problem.
```python r1, c1, r2, c2 = map(int, input().split()) if c1 != c2 and r1 != r2: torre = 2 else: torre = 1 if (r1 + c1) % 2 == (r2 + c2) % 2: bispo = 1 else: bispo = 0 rei = max(abs(c1 - c2),abs(r1 - r2)) print(torre, bispo, rei) ```
MatrixStudio/Codeforces-Python-Submissions
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*. Consider 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?
```python n,h = map(int,input().split(" ")) a = input().split(" ") maxw = 0; for i in range(n): if (int(a[i])>h): maxw +=2; else: maxw+=1; print(maxw) ```
MatrixStudio/Codeforces-Python-Submissions
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" β€” thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.
```python sum1=0 for _ in range(int(input())): n=list(map(int, input().split())) sum1=sum1+sum(n) if sum1==0: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word. Note, that during capitalization all the letters except the first one remains unchanged.
```python s = input() s = list(s) s[0] = s[0].upper() print("".join(map(str, s))) ```
MatrixStudio/Codeforces-Python-Submissions
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: - 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. She repeats this process until there is only one card left. What are the possible colors for the final card?
```python mod = 1000000007 ii = lambda : int(input()) si = lambda : input() dgl = lambda : list(map(int, input())) f = lambda : map(int, input().split()) il = lambda : list(map(int, input().split())) ls = lambda : list(input()) d=[0, 0, 0] dt={0:'B',1:'G',2:'R'} n=ii() s=si() for i in s: if i=='B':d[0]+=1 elif i=='G':d[1]+=1 else:d[2]+=1 c0=d.count(0) c1=d.count(1) if c0==2: print(dt[d.index(max(d))]) elif c0==1 and c1==1: for i in range(3): if d[i]==1 or d[i]==0: print(dt[i],end='') elif c1==2 and c0==1: print(dt[d.index(0)]) else: print('BGR') ```
MatrixStudio/Codeforces-Python-Submissions
Nowadays all circuses in Berland have a round arena with diameter 13 meters, but in the past things were different. In Ancient Berland arenas in circuses were shaped as a regular (equiangular) polygon, the size and the number of angles could vary from one circus to another. In each corner of the arena there was a special pillar, and the rope strung between the pillars marked the arena edges. Recently the scientists from Berland have discovered the remains of the ancient circus arena. They found only three pillars, the others were destroyed by the time. You are given the coordinates of these three pillars. Find out what is the smallest area that the arena could have.
```python T=[] for _ in range(3): a=tuple(map(int,input().split())) T.append(a) if T[0][0]==T[1][0]: if T[0][0]!=T[1][0]: D=abs((T[0][1]-T[1][1])/(T[0][0]-T[1][0])) else: D=abs(T[0][1]-T[1][1]) elif T[0][0]==T[2][0]: if T[0][0]!=T[2][0]: D=abs((T[0][1]-T[2][1])/(T[0][0]-T[2][0])) else: D=abs(T[0][1]-T[2][1]) else: if T[1][0]!=T[2][0]: D=abs((T[1][1]-T[2][1])/(T[1][0]-T[2][0])) else: D=abs(T[1][1]-T[2][1]) print(D*D) ```
MatrixStudio/Codeforces-Python-Submissions
Little Alyona is celebrating Happy Birthday! Her mother has an array of *n* flowers. Each flower has some mood, the mood of *i*-th flower is *a**i*. The mood can be positive, zero or negative. Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose several of the subarrays suggested by her mother. After that, each of the flowers will add to the girl's happiness its mood multiplied by the number of chosen subarrays the flower is in. For example, consider the case when the mother has 5 flowers, and their moods are equal to 1,<=<=-<=2,<=1,<=3,<=<=-<=4. Suppose the mother suggested subarrays (1,<=<=-<=2), (3,<=<=-<=4), (1,<=3), (1,<=<=-<=2,<=1,<=3). Then if the girl chooses the third and the fourth subarrays then: - the first flower adds 1Β·1<==<=1 to the girl's happiness, because he is in one of chosen subarrays, - the second flower adds (<=-<=2)Β·1<==<=<=-<=2, because he is in one of chosen subarrays, - the third flower adds 1Β·2<==<=2, because he is in two of chosen subarrays, - the fourth flower adds 3Β·2<==<=6, because he is in two of chosen subarrays, - the fifth flower adds (<=-<=4)Β·0<==<=0, because he is in no chosen subarrays. Thus, in total 1<=+<=(<=-<=2)<=+<=2<=+<=6<=+<=0<==<=7 is added to the girl's happiness. Alyona wants to choose such subarrays from those suggested by the mother that the value added to her happiness would be as large as possible. Help her do this! Alyona can choose any number of the subarrays, even 0 or all suggested by her mother.
```python from sys import stdin from collections import deque,Counter,defaultdict,OrderedDict import sys import math,os import operator import random from fractions import Fraction import functools import bisect import itertools from heapq import * import time import copy n,m = map(int,input().split()) arr = list(map(int,input().split())) chosen = [] for _ in range(m): a,b = map(int,input().split()) if sum(arr[a-1:b])>0: chosen.append([a,b]) ans = 0 for i in range(n): count = 0 for a,b in chosen: if i in range(a-1,b): count+=1 ans+=arr[i]*count print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
This problem's actual name, "Lexicographically Largest Palindromic Subsequence" is too long to fit into the page headline. You are given string *s* consisting of lowercase English letters only. Find its lexicographically largest palindromic subsequence. We'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<=&lt;<=*p*2<=&lt;<=...<=&lt;<=*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". String *x* = *x*1*x*2... *x*|*x*| is lexicographically larger than string *y* = *y*1*y*2... *y*|*y*| if either |*x*| &gt; |*y*| and *x*1<==<=*y*1, *x*2<==<=*y*2, ...,<=*x*|*y*|<==<=*y*|*y*|, or there exists such number *r* (*r*<=&lt;<=|*x*|, *r*<=&lt;<=|*y*|) that *x*1<==<=*y*1, *x*2<==<=*y*2, ..., *x**r*<==<=*y**r* and *x**r*<=<=+<=<=1<=&gt;<=*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". String *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".
```python l=input() l=list(l) l.sort() k=l.count(l[-1]) for i in range(k): print(l[-1],end="") ```
MatrixStudio/Codeforces-Python-Submissions
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. Arkady 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. What is the minimum number of holes Arkady should block to make at least $B$ liters of water flow out of the first hole?
```python n, a, b = map(int, input().split()) lst = list(map(int, input().split())) S = sum(lst) s = lst.pop(0) lst = sorted(lst) i = 0 f = True if a*s/S>b: ans = 0 f = False else: while i<=n: S = sum(lst) if a*s/(S+s)>=b: ans = i f = False break i+=1 if lst:lst.pop(0) if f: ans = n-1 print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
You are given array consisting of *n* integers. Your task is to find the maximum length of an increasing subarray of the given array. A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray strictly greater than previous.
```python n=int(input()) lis=list(map(int,input().split())) count=1 maxm=1 for i in range(n-1): if lis[i]<lis[i+1]: count+=1 else: count=1 maxm=max(maxm,count) print(maxm) ```
MatrixStudio/Codeforces-Python-Submissions
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?
```python a = None b = None a = input() b = input() print(a+b) ```
MatrixStudio/Codeforces-Python-Submissions
Hideo Kojima has just quit his job at Konami. Now he is going to find a new place to work. Despite being such a well-known person, he still needs a CV to apply for a job. During all his career Hideo has produced *n* games. Some of them were successful, some were not. Hideo wants to remove several of them (possibly zero) from his CV to make a better impression on employers. As a result there should be no unsuccessful game which comes right after successful one in his CV. More formally, you are given an array *s*1,<=*s*2,<=...,<=*s**n* of zeros and ones. Zero corresponds to an unsuccessful game, one β€” to a successful one. Games are given in order they were produced, and Hideo can't swap these values. He should remove some elements from this array in such a way that no zero comes right after one. Besides that, Hideo still wants to mention as much games in his CV as possible. Help this genius of a man determine the maximum number of games he can leave in his CV.
```python import sys #sys.stdin = open('input.in', 'r') #sys.stdout = open('output.out', 'w') n = int(input()) s = input().split() count = 0 for i in range(len(s) - 1): if s[i] == '1' and s[i + 1] == '0': count += 1 print(len(s) - count) ```
MatrixStudio/Codeforces-Python-Submissions
A tree is a connected graph that doesn't contain any cycles. The distance between two vertices of a tree is the length (in edges) of the shortest path between these vertices. You are given a tree with *n* vertices and a positive number *k*. Find the number of distinct pairs of the vertices which have a distance of exactly *k* between them. Note that pairs (*v*, *u*) and (*u*, *v*) are considered to be the same pair.
```python MAX = 50002 adj = [[] for i in range(MAX)] dp = [[0 for i in range(503)] for j in range(MAX)] k = 0 def dfs(at, parent): dx = [0 for i in range(k + 1)] for i in adj[at]: if i == parent: continue dfs(i, at) dp[at] [k] = dp[at] [k] + dp[i] [k] for j in range(0, k + 1): dp[at] [k] = dp[at] [k] + dx[j] * dp[i] [k - (1 + j)] if j > 0: dp[at] [j] = dp[at] [j] + dp[i] [j - 1] dx[j] = dx[j] + dp[j] [j - 1] n, k = map(int, input( ).split( )) for i in range(1, n): u, v = map(int, input( ).split( )) adj[u].append(v) adj[v].append(u) dp[i] [0] = 1 dp[n] [0] = 1 dfs(1, -1) print(dp[1] [k]) ```
MatrixStudio/Codeforces-Python-Submissions
Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity. There are *n* columns of toy cubes in the box arranged in a line. The *i*-th column contains *a**i* cubes. At first, the gravity in the box is pulling the cubes downwards. When Chris switches the gravity, it begins to pull all the cubes to the right side of the box. The figure shows the initial and final configurations of the cubes in the box: the cubes that have changed their position are highlighted with orange. Given the initial configuration of the toy cubes in the box, find the amounts of cubes in each of the *n* columns after the gravity switch!
```python st = int(input()) lst = list(map(int, input().split())) print(*sorted(lst)) ```
MatrixStudio/Codeforces-Python-Submissions
One day Polycarp published a funny picture in a social network making a poll about the color of his handle. Many of his friends started reposting Polycarp's joke to their news feed. Some of them reposted the reposts and so on. These events are given as a sequence of strings "name1 reposted name2", where name1 is the 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. Polycarp measures the popularity of the joke as the length of the largest repost chain. Print the popularity of Polycarp's joke.
```python d={'polycarp':1} for _ in range(int(input())):a,b,c=input().lower().split();d[a]=d[c]+1 print(max(d.values())) ```
MatrixStudio/Codeforces-Python-Submissions
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc. However, it's easy to make a mistake during the Β«translationΒ». Vasya translated word *s* from Berlandish into Birlandish as *t*. Help him: find out if he translated the word correctly.
```python from numpy import * import numpy as np str1 = input() str2 = input() s1 = list(str1) s2 = list(str2) ar1 = np.asarray(s1) ar2 = np.asarray(s2) ar2 = ar2[::-1] if (np.shape(ar1)== np.shape(ar2)): if all(ar1 == ar2): print ("YES") else: print ("NO") else: print ("NO") ```
MatrixStudio/Codeforces-Python-Submissions
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. The 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! Alexey 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.
```python n=int(input()) l=[] for i in range(n): l.append(list(map(int,input().split()))) r=list(range(l[0][0],l[0][1]+1)) count=0 for i in range(1,n): if(l[i][0] in r and l[i][1] in r): if(l[i][1]==l[i][0]+1): count-=1 else: r=r[:r.index(l[i][0])+1]+r[r.index(l[i][1]):] elif(l[i][0] in r): f=0 for j in range(l[i][1],r[len(r)-1],1): if(j in r): f=1 temp=j break if(f==0): r=r[:r.index(l[i][0])+1] else: r=r[:r.index(l[i][0])+1]+r[r.index(temp):] elif(l[i][1] in r): f=0 for j in range(l[i][0],r[0],-1): if(j in r): f=1 temp=j break if(f==0): r=r[r.index(l[i][1]):] else: r=r[:r.index(temp)+1]+r[r.index(l[i][1]):] elif(l[i][0]<r[0] and l[i][1]>r[len(r)-1]): print(0) exit(0) for i in range(len(r)-1): if(r[i+1]==r[i]+1): count+=1 print(count) ```
MatrixStudio/Codeforces-Python-Submissions
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. The 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. All 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?
```python n = int(input()) pie = list(map(int, input().split())) d = [0,0] th = 1 tr = 0 for i in range(0,n): if(i==n-1): if((d[tr]+pie[i])<d[th]): d[tr]+=pie[i] else: d[th]+=pie[i] elif( (i<n-2) and ((d[th]+pie[i]+pie[i+2]) > (d[tr]+pie[i+1])) ): d[th]+=pie[i] th,tr = tr,th elif(pie[i+1]<pie[i]): d[th]+=pie[i] th,tr = tr,th else: d[tr]+=pie[i] print(d[0], " ", d[1]) ```
MatrixStudio/Codeforces-Python-Submissions
To stay woke and attentive during classes, Karen needs some coffee! Karen, a coffee aficionado, wants to know the optimal temperature for brewing the perfect cup of coffee. Indeed, she has spent some time reading several recipe books, including the universally acclaimed "The Art of the Covfefe". She knows *n* coffee recipes. The *i*-th recipe suggests that coffee should be brewed between *l**i* and *r**i* degrees, inclusive, to achieve the optimal taste. Karen thinks that a temperature is admissible if at least *k* recipes recommend it. Karen has a rather fickle mind, and so she asks *q* questions. In each question, given that she only wants to prepare coffee with a temperature between *a* and *b*, inclusive, can you tell her how many admissible integer temperatures fall within the range?
```python import math as mt import sys,string input=sys.stdin.readline import random from collections import deque,defaultdict L=lambda : list(map(int,input().split())) Ls=lambda : list(input().split()) M=lambda : map(int,input().split()) I=lambda :int(input()) n,k,q=M() # Does range update def update(D, l, r, x): D[l] += x D[r + 1] -= x # Prints updated Array def printArray(A, D): for i in range(0 , len(A)): if (i == 0): A[i] = D[i] else: A[i] = D[i] + A[i - 1] A=[0]*200100 D=[0]*200101 for i in range(n): a,b=M() update(D,a,b,1) printArray(A,D) x=[0] for i in range(len(A)): if(A[i]>=k): x.append(x[-1]+1) else: x.append(x[-1]) x.append(x[-1]) for i in range(q): a,b=M() print(x[b+1]-x[a],) ```
MatrixStudio/Codeforces-Python-Submissions
Vadim is really keen on travelling. Recently he heard about kayaking activity near his town and became very excited about it, so he joined a party of kayakers. Now the party is ready to start its journey, but firstly they have to choose kayaks. There are 2Β·*n* people in the group (including Vadim), and they have exactly *n*<=-<=1 tandem kayaks (each of which, obviously, can carry two people) and 2 single kayaks. *i*-th person's weight is *w**i*, and weight is an important matter in kayaking β€” if the difference between the weights of two people that sit in the same tandem kayak is too large, then it can crash. And, of course, people want to distribute their seats in kayaks in order to minimize the chances that kayaks will crash. Formally, the instability of a single kayak is always 0, and the instability of a tandem kayak is the absolute difference between weights of the people that are in this kayak. Instability of the whole journey is the total instability of all kayaks. Help the party to determine minimum possible total instability!
```python n = input() weights = [] for i in range(n*2): weights.append(input()) instability = 0 weights.sort() tandem_weights = weights[0:-2] for i in range(1,(n*2)-2): instability += tandem_weights[i] - tandem_weights[i-1] print(instability) ```
MatrixStudio/Codeforces-Python-Submissions
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. Polycarpus 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. Write 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).
```python n, k = map(int, input().split()) l = list(map(int, input().split())) ans = list() for i in range(n-k+1): ans.append(sum(l[i:i+k])) print(ans.index(min(ans)) + 1) ```
MatrixStudio/Codeforces-Python-Submissions
Do you like summer? Residents of Berland do. They especially love eating ice cream in the hot summer. So this summer day a large queue of *n* Berland residents lined up in front of the ice cream stall. We know that each of them has a certain amount of berland dollars with them. The residents of Berland are nice people, so each person agrees to swap places with the person right behind him for just 1 dollar. More formally, if person *a* stands just behind person *b*, then person *a* can pay person *b* 1 dollar, then *a* and *b* get swapped. Of course, if person *a* has zero dollars, he can not swap places with person *b*. Residents of Berland are strange people. In particular, they get upset when there is someone with a strictly smaller sum of money in the line in front of them. Can you help the residents of Berland form such order in the line so that they were all happy? A happy resident is the one who stands first in the line or the one in front of who another resident stands with not less number of dollars. Note that the people of Berland are people of honor and they agree to swap places only in the manner described above.
```python n= int(input()) a = list(map(int,input().split())) i = len(a) - 1 c1 = 0 while (c1 == 0): i = len(a) - 1 while (i >= 1): if (abs(a[i] - a[i-1]) == 1): c1 = -1 break if (a[i-1] > a[i]): a[i] = a[i] + 1 a[i-1] = a[i-1] - 1 a[i],a[i-1] = a[i-1],a[i] i = i - 1 j = len(a) - 1 s = 0 while (j > 0): if (a[j-1] > a[j]): s = s + 1 j = j - 1 if (c1 == -1): print(':(') c1 = -1 break elif (s == 0): print(*a) c1 = -1 break else: c1 = 0 ```
MatrixStudio/Codeforces-Python-Submissions
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.
```python def solve(): a, b = map(int, input().split()) li1 = [] for i in range(b): c, d = map(int, input().split()) li1.append((d,c)) li1.sort(reverse=True) t = 0 ans = 0 for i in range(b-1): cd = li1[i] if a>cd[1]: a-=cd[1] ans = ans+cd[1]*cd[0] else: ans = ans+a*cd[0] a=0 print(ans) if __name__ == "__main__": solve() ```
MatrixStudio/Codeforces-Python-Submissions
In the evening, after the contest Ilya was bored, and he really felt like maximizing. He remembered that he had a set of *n* sticks and an instrument. Each stick is characterized by its length *l**i*. Ilya decided to make a rectangle from the sticks. And due to his whim, he decided to make rectangles in such a way that maximizes their total area. Each stick is used in making at most one rectangle, it is possible that some of sticks remain unused. Bending sticks is not allowed. Sticks with lengths *a*1, *a*2, *a*3 and *a*4 can make a rectangle if the following properties are observed: - *a*1<=≀<=*a*2<=≀<=*a*3<=≀<=*a*4 - *a*1<==<=*a*2 - *a*3<==<=*a*4 A rectangle can be made of sticks with lengths of, for example, 3Β 3Β 3Β 3 or 2Β 2Β 4Β 4. A rectangle cannot be made of, for example, sticks 5Β 5Β 5Β 7. Ilya also has an instrument which can reduce the length of the sticks. The sticks are made of a special material, so the length of each stick can be reduced by at most one. For example, a stick with length 5 can either stay at this length or be transformed into a stick of length 4. You have to answer the question β€” what maximum total area of the rectangles can Ilya get with a file if makes rectangles from the available sticks?
```python n=int(input()) d=set(map(int,input().split())) w=list(d) if(len(w)==1): print(w[0]*w[0]) if(len(w)==2): print(w[0]*w[1]) elif(len(w)==3):print(0) else: mi=min(w) w.pop(w.index(mi)) mj=min(w) w.pop(w.index(mj)) mk=min(w) print(mi*mk) ```
MatrixStudio/Codeforces-Python-Submissions
Where do odds begin, and where do they end? Where does hope emerge, and will they ever break? Given an integer sequence *a*1,<=*a*2,<=...,<=*a**n* of length *n*. Decide whether it is possible to divide it into an odd number of non-empty subsegments, the each of which has an odd length and begins and ends with odd numbers. A subsegment is a contiguous slice of the whole sequence. For example, {3,<=4,<=5} and {1} are subsegments of sequence {1,<=2,<=3,<=4,<=5,<=6}, while {1,<=2,<=4} and {7} are not.
```python leng = input() arr = input() leng = int(leng) arr = list(map(int, arr.split(' '))) if leng % 2 == 0: print("No") elif arr[0] % 2 == 0 or arr[-1] % 2 == 0: print("No") else: print("Yes") ```
MatrixStudio/Codeforces-Python-Submissions
One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality of the first laptop is higher (strictly greater) than the quality of the second laptop. Please, check the guess of Alex. You are given descriptions of *n* laptops. Determine whether two described above laptops exist.
```python x=int(input()) n=False for i in range(x): a,b=[int(x) for x in input().split()] if a<b: n=True if not n: print('Poor Alex') else: print('Happy Alex') ```
MatrixStudio/Codeforces-Python-Submissions
ZS the Coder is coding on a crazy computer. If you don't type in a word for a *c* consecutive seconds, everything you typed disappear! More formally, if you typed a word at second *a* and then the next word at second *b*, then if *b*<=-<=*a*<=≀<=*c*, just the new word is appended to other words on the screen. If *b*<=-<=*a*<=&gt;<=*c*, then everything on the screen disappears and after that the word you have typed appears on the screen. For example, if *c*<==<=5 and you typed words at seconds 1,<=3,<=8,<=14,<=19,<=20 then at the second 8 there will be 3 words on the screen. After that, everything disappears at the second 13 because nothing was typed. At the seconds 14 and 19 another two words are typed, and finally, at the second 20, one more word is typed, and a total of 3 words remain on the screen. You're given the times when ZS the Coder typed the words. Determine how many words remain on the screen after he finished typing everything.
```python n,c = list(map(int,input().split())) t = list(map(int,input().split())) r = 1 for i in range(1,n): if t[i]-t[i-1] <= c: r += 1 else: r = 1 print(r) ```
MatrixStudio/Codeforces-Python-Submissions
Greatest common divisor *GCD*(*a*,<=*b*) of two positive integers *a* and *b* is equal to the biggest integer *d* such that both integers *a* and *b* are divisible by *d*. There are many efficient algorithms to find greatest common divisor *GCD*(*a*,<=*b*), for example, Euclid algorithm. Formally, find the biggest 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!
```python (a, b) = map(int, input().split(' ')) def gcd(a, b): if a == 0: return b return gcd(b % a, a) print(gcd(a, b)) ```
MatrixStudio/Codeforces-Python-Submissions
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. Ostap 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. Your 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.
```python def solve(s, k): g = s.index("G") t = s.index("T") if abs(g - t) % k != 0: return "NO" start = g fin = t + 1 if g > t: k = -k fin -= 2 for i in range(start, fin, k): if s[i] == "T": return "YES" elif s[i] == "#": return "NO" return "NO" def main(): n, k = map(int, input().split()) print(solve(input(), k)) main() ```
MatrixStudio/Codeforces-Python-Submissions
The recent All-Berland Olympiad in Informatics featured *n* participants with each scoring a certain amount of points. As the head of the programming committee, you are to determine the set of participants to be awarded with diplomas with respect to the following criteria: - At least one participant should get a diploma. - None of those with score equal to zero should get awarded. - When someone is awarded, all participants with score not less than his score should also be awarded. Determine the number of ways to choose a subset of participants that will receive the diplomas.
```python n = int(input()) a = list(map(int, input().rstrip().split(" "))) a.sort() a = list(set(a)) if a[0]==0: a.pop(0) print(len(a)) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word *s*. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if Vasya types the word "ahhellllloou", it will be considered that he said hello, and if he types "hlelo", it will be considered that Vasya got misunderstood and he didn't manage to say hello. Determine whether Vasya managed to say hello by the given word *s*.
```python s = input() h = s.find('h') e = s.find('e', h + 1) l = s.find('l', e + 1) l2 = s.find('l', l + 1) o = s.find('o', l2 + 1) a = h < e < l < l2 < o b = (h + 1) * e * l * l2 * o b1 = b < 0 print('YES' * a + 'NO' * b1) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya lives in a round building, whose entrances are numbered sequentially by integers from 1 to *n*. Entrance *n* and entrance 1 are adjacent. Today 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. Help Vasya to determine the number of the entrance, near which he will be at the end of his walk.
```python #include <iostream> using namespace std; int main() { long long n,o,i,sigma,k=0; cin>>n; i=n; sigma=0; if(n>0) { while(i>0) { i--; k++; sigma=sigma+k; } o=1+sigma*6; } else if(n==0) { o=1; } cout<<o; return 0; } ```
MatrixStudio/Codeforces-Python-Submissions
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. In 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. Help Vitya find out if a word $s$ is Berlanese.
```python s = input() if ( s[-1]!='a' and s[-1]!='e' and s[-1]!='i' and s[-1]!='o' and s[-1]!='u' and s[-1]!='n'): print('NO') elif (s[-1]=='a' or s[-1]=='e' or s[-1]=='i' or s[-1]=='o' or s[-1]=='u' or s[-1] == 'n' ): print('YES') else: for i in range(0,len(s)-1): if (s[i]=='a' or s[i]=='e' or s[i]=='i' or s[i]=='o' or s[i]=='u' or s[i] == 'n' ): if ( s[i+1]=='a' or s[i+1]=='e' or s[i+1]=='i' or s[i+1]=='o' or s[i+1]=='u' or s[i+1]=='n'): print('YES') elif ( s[i+1]!='a' and s[i+1]!='e' and s[i+1]!='i' and s[i+1]!='o' and s[i+1]!='u'): print('YES') if ( s[i]!='a' and s[i]!='e' and s[i]!='i' and s[i]!='o' and s[i]!='u' and s[i] != 'n'): if ( s[i+1]!='a' and s[i+1]!='e' and s[i+1]!='i' and s[i+1]!='o' and s[i+1]!='u'): # print(s[i]) # print(s[i+1]) print('NO') break ```
MatrixStudio/Codeforces-Python-Submissions
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth. Now 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!). Bort 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.
```python k = 0 q = 0 a = 0 for i in input(): if i == 'A': a += q elif i == 'Q': k += a q += 1 print(k) ```
MatrixStudio/Codeforces-Python-Submissions
For a positive integer *n* let's define a function *f*: *f*(*n*)<==<=<=-<=1<=+<=2<=-<=3<=+<=..<=+<=(<=-<=1)*n**n* Your task is to calculate *f*(*n*) for a given integer *n*.
```python n=int(input()) c=0 for i in range(1,n+1,2): c+=-1*i for i in range(2,n+1,2): c+=i print(c) ```
MatrixStudio/Codeforces-Python-Submissions
You are given a rectangular board of *M*<=Γ—<=*N* squares. Also you are given an unlimited number of standard domino pieces of 2<=Γ—<=1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions: 1. Each domino completely covers two squares. 2. No two dominoes overlap. 3. Each domino lies entirely inside the board. It is allowed to touch the edges of the board. Find the maximum number of dominoes, which can be placed under these restrictions.
```python m,n=map(int,input().split()) r=m*n/2 r=int(r) print(r) ```
MatrixStudio/Codeforces-Python-Submissions
Eleven wants to choose a new name for herself. As a bunch of geeks, her friends suggested an algorithm to choose a name for her. Eleven wants her name to have exactly *n* characters. Her friend suggested that her name should only consist of uppercase and lowercase letters 'O'. More precisely, they suggested that the *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 - *f*1<==<=1, - *f*2<==<=1, - *f**n*<==<=*f**n*<=-<=2<=+<=*f**n*<=-<=1 (*n*<=&gt;<=2). As her friends are too young to know what Fibonacci sequence is, they asked you to help Eleven determine her new name.
```python n = int(input()) a = 1 b = 1 result = 'O' for i in range(2, n+1): if i == a + b: result += 'O' x = b b += a a = x else: result += 'o' print(result) ```
MatrixStudio/Codeforces-Python-Submissions
Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number *a* and Antisimon receives number *b*. They also have a heap of *n* stones. The players take turns to make a move and Simon starts. During a move a player should take from the heap the number of stones equal to the greatest common divisor of the fixed number he has received and the number of stones left in the heap. A player loses when he cannot take the required number of stones (i. e. the heap has strictly less stones left than one needs to take). Your task is to determine by the given *a*, *b* and *n* who wins the game.
```python def gcd(a,b): large=1 for i in range(1,min(a,b)+1): if(a%i==0 and b%i==0): large=i return large a,b,n=map(int,input().split()) while(True): if(gcd(a,n)<=n): n-=gcd(a,n) else: print("1") exit() if(gcd(b,n)<=n): n-=gcd(b,n) else: print("0") exit() ```
MatrixStudio/Codeforces-Python-Submissions
In some game by Playrix it takes *t* minutes for an oven to bake *k* carrot cakes, all cakes are ready at the same moment *t* minutes after they started baking. Arkady needs at least *n* cakes to complete a task, but he currently don't have any. However, he has infinitely many ingredients and one oven. Moreover, Arkady can build one more similar oven to make the process faster, it would take *d* minutes to build the oven. While the new oven is being built, only old one can bake cakes, after the new oven is built, both ovens bake simultaneously. Arkady can't build more than one oven. Determine if it is reasonable to build the second oven, i.e. will it decrease the minimum time needed to get *n* cakes or not. If the time needed with the second oven is the same as with one oven, then it is unreasonable.
```python n, t, k, d = map(int,input().split()) not_build = (n / k) * t build = d + (not_build / 2) # print(not_build) # print(build) if(build < not_build): print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality of the first laptop is higher (strictly greater) than the quality of the second laptop. Please, check the guess of Alex. You are given descriptions of *n* laptops. Determine whether two described above laptops exist.
```python n = int(input()) z,x=0,0 for i in range(n): p=input().split() if z == 0: z = p[:] if x == 0: x = p[:] else: z = min(z,p,key=lambda a: int(a[0])) x = max(x,p,key=lambda a: int(a[1])) if int(z[0]) < int(x[0]) and int(z[1]) > int(x[1]): print("Happy Alex") else: print("Poor Alex") ```
MatrixStudio/Codeforces-Python-Submissions
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. To 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?
```python import sys n, k, l, c, d, p, nl, np = map(int, sys.stdin.readline().split()) a = k*l b = c*d print(min(p//np, a//nl, b) // n) ```
MatrixStudio/Codeforces-Python-Submissions
Polycarpus is the director of a large corporation. There are *n* secretaries working for the corporation, each of them corresponds via the famous Spyke VoIP system during the day. We know that when two people call each other via Spyke, the Spyke network assigns a unique ID to this call, a positive integer session number. One day Polycarpus wondered which secretaries are talking via the Spyke and which are not. For each secretary, he wrote out either the session number of his call or a 0 if this secretary wasn't talking via Spyke at that moment. Help Polycarpus analyze these data and find out the number of pairs of secretaries that are talking. If Polycarpus has made a mistake in the data and the described situation could not have taken place, say so. Note that the secretaries can correspond via Spyke not only with each other, but also with the people from other places. Also, Spyke conferences aren't permitted β€” that is, one call connects exactly two people.
```python n=int(input()) l=list(map(int,input().split())) ans=0 repeat={} for i in l: if i in repeat: repeat[i]+=1 if repeat[1]>2: ans=-1 break else: ans+=1 else: repeat[i]=1 print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
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. Across 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. Note that the game consisted of several complete sets.
```python k, a, b = list(map(int, input().split())) if a + b < k: print(-1) else: print( (a + b) // k ) ```
MatrixStudio/Codeforces-Python-Submissions
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. In 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. He 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. GukiZ 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.
```python # coding=utf-8 if __name__ == '__main__': n = int(input()) line = str(input()).split() line = [int(it) for it in line] refer = line.copy() refer.sort(reverse=True) value = list() for i in range(n): value.append(str(refer.index(line[i]) + 1)) print(' '.join(value)) ```
MatrixStudio/Codeforces-Python-Submissions
Natasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the stringΒ β€” concatenation of letters, which correspond to the stages. There are $n$ stages available. The rocket must contain exactly $k$ of them. Stages in the rocket should be ordered by their weight. So, after the stage with some letter can go only stage with a letter, which is at least two positions after in the alphabet (skipping one letter in between, or even more). For example, after letter 'c' can't go letters 'a', 'b', 'c' and 'd', but can go letters 'e', 'f', ..., 'z'. For the rocket to fly as far as possible, its weight should be minimal. The weight of the rocket is equal to the sum of the weights of its stages. The weight of the stage is the number of its letter in the alphabet. For example, the stage 'a 'weighs one ton,' b 'weighs two tons, and' z'Β β€” $26$ tons. Build the rocket with the minimal weight or determine, that it is impossible to build a rocket at all. Each stage can be used at most once.
```python def algo(chaine, num): trier = sorted(chaine) liste = [ord(a)-96 for a in trier] somme = sum(liste) if (num > len(liste)): return -1 c = 0 for k in range(len(liste)-1): if (liste[k] < liste[k+1]): c = c+1 if(c < num): return -1 for i in range(len(liste)-num): n = 1 count = liste[i] j = 1 while(j<num+1): if liste[i+j]<=liste[i]+1 or liste[i+j]<=liste[i+j-1]+1: print("from if2") j = j+1 continue print(liste[i+j]) count = count+liste[i+j] n = n+1 j = j+1 #print(count) print(count) print("========") if count < somme and n == num: print("from if3") somme = count print("azazazaz") return somme n = int(input()) while n != 0: s = input() ans = algo(s) print(ans) n -=1 ```
MatrixStudio/Codeforces-Python-Submissions
HQ9+ is a joke programming language which has only four one-character instructions: - "H" prints "Hello, World!",- "Q" prints the source code of the program itself,- "9" prints the lyrics of "99 Bottles of Beer" song, - "+" increments the value stored in the internal accumulator. Instructions "H" and "Q" are case-sensitive and must be uppercase. The characters of the program which are not instructions are ignored. You are given a program written in HQ9+. You have to figure out whether executing this program will produce any output.
```python s = input() st = 'HQ9' count = 0 for i in s: if (i in st): count += 1 if (count > 0): print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
You can not just take the file and send it. When Polycarp trying to send a file in the social network "Codehorses", he encountered an unexpected problem. If the name of the file contains three or more "x" (lowercase Latin letters "x") in a row, the system considers that the file content does not correspond to the social network topic. In this case, the file is not sent and an error message is displayed. Determine the minimum number of characters to remove from the file name so after that the name does not contain "xxx" as a substring. Print 0 if the file name does not initially contain a forbidden substring "xxx". You can delete characters in arbitrary positions (not necessarily consecutive). If you delete a character, then the length of a string is reduced by $1$. For example, if you delete the character in the position $2$ from the string "exxxii", then the resulting string is "exxii".
```python n = int(input()) s = input() segs = [] seg=[-1,-1] for i in range(len(s)): if(s[i] == 'x'): if(seg[0] == -1): seg[0] = i seg[1] = i else: seg[-1] = i else: if(seg[0] != -1): segs.append(seg) seg = [-1,-1] if(seg[0] != -1): segs.append(seg) ans = 0 for i in segs: l = i[1] - i[0] + 1 if(l >= 3): ans += l - 2 print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
A famous Berland's painter Kalevitch likes to shock the public. One of his last obsessions is chess. For more than a thousand years people have been playing this old game on uninteresting, monotonous boards. Kalevitch decided to put an end to this tradition and to introduce a new attitude to chessboards. As before, the chessboard is a square-checkered board with the squares arranged in a 8<=Γ—<=8 grid, each square is painted black or white. Kalevitch suggests that chessboards should be painted in the following manner: there should be chosen a horizontal or a vertical line of 8 squares (i.e. a row or a column), and painted black. Initially the whole chessboard is white, and it can be painted in the above described way one or more times. It is allowed to paint a square many times, but after the first time it does not change its colour any more and remains black. Kalevitch paints chessboards neatly, and it is impossible to judge by an individual square if it was painted with a vertical or a horizontal stroke. Kalevitch hopes that such chessboards will gain popularity, and he will be commissioned to paint chessboards, which will help him ensure a comfortable old age. The clients will inform him what chessboard they want to have, and the painter will paint a white chessboard meeting the client's requirements. It goes without saying that in such business one should economize on everything β€” for each commission he wants to know the minimum amount of strokes that he has to paint to fulfill the client's needs. You are asked to help Kalevitch with this task.
```python def main(): row = [False] * 8 col = [False] * 8 for r in range(8): s = input() for c in range(8): if s[c] == 'W': row[r] = True col[c] = True answer = 16 - sum(row) - sum(col) if answer == 16: answer = 8 print(answer) if __name__ == "__main__": main() ```
MatrixStudio/Codeforces-Python-Submissions
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. Little 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?
```python x = int(input()) p = list(map(int,input().split())) q = list(map(int,input().split())) p.pop(0) q.pop(0) r = p+q m = list(range(1,x+1)) sum = 0 for a in m : if a in r: sum+=1 if sum == x: print("I become the guy.") else: print("Oh, my keyboard!") ```
MatrixStudio/Codeforces-Python-Submissions
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: - 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. All five kinds of polyhedrons are shown on the picture below: Anton 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!
```python n=int(input()) t_f=0 for i in range(n): p=input() if p=="Tetrahedron": t_f+=4 elif p=="Cube": t_f+=6 elif p=="Octahedron": t_f+=8 elif p=="Dodecahedron": t_f+=12 elif p=="Icosahedron": t_f+=20 print(t_f) ```
MatrixStudio/Codeforces-Python-Submissions
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. Lenny 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.
```python mat = [[int(x) for x in input().split()] for y in range(3)] a=[[0 for x in range(3)] for y in range(3)] for i in range(3) : for j in range(3) : while mat[i][j]>0 : for ii in range(0,3) : a[ii][j]=a[ii][j]+1 #print(a) for jj in range(0,3) : a[i][jj]=a[i][jj]+1 mat[i][j]=mat[i][j]-1 #print(a) ans=[[0 for x in range(3)] for y in range(3)] for i in range(3) : for j in range(3) : print(1 if a[i][j]%2==0 else 0,end="") print() ```
MatrixStudio/Codeforces-Python-Submissions
Santa Claus has *n* candies, he dreams to give them as gifts to children. What 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.
```python f = int(input()) data = dict() data[1] = [{1}] data[2] = [{2}] data[3] = [{1, 2}] for c in range(4, f+1): t = data[c-1] n = list() for i in t: if 1 in i: for z in i: if sum(i - {z} | {z+1}) == c: n.append(i - {z} | {z+1}) else: n.append(i | {1}) l = max([len(x) for x in n]) b = set() for z in n: if len(z) == l: b.add(tuple(z)) data[c] = [list(map(lambda x: set(x), b))[0]] l = len(data[f][0]) s = ' '.join(map(str, list(data[f][0]))) print(f'{l}\n{s}') ```
MatrixStudio/Codeforces-Python-Submissions
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). He has *n* dollars. How many dollars does he have to borrow from his friend soldier to buy *w* bananas?
```python k, n, w = map(int, input().split()) total = int(w * (w + 1) / 2) if ans := (total * k - n) > 0 : print(ans) else : print(0) ```
MatrixStudio/Codeforces-Python-Submissions
In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of *n* bumpers. The bumpers are numbered with integers from 1 to *n* from left to right. There are two types of bumpers. They are denoted by the characters '&lt;' and '&gt;'. When the ball hits the bumper at position *i* it goes one position to the right (to the position *i*<=+<=1) if the type of this bumper is '&gt;', or one position to the left (to *i*<=-<=1) if the type of the bumper at position *i* is '&lt;'. If there is no such position, in other words if *i*<=-<=1<=&lt;<=1 or *i*<=+<=1<=&gt;<=*n*, the ball falls from the game field. Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position.
```python import os os.system("cls") ```
MatrixStudio/Codeforces-Python-Submissions
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.
```python import collections n = int(input()) d = collections.defaultdict(lambda: [0, 0]) max = None for i in range(n): info = input().split(" ") if max is None: max = info[0] d[info[0]][0] += int(info[1]) d[info[0]][1] = i if d[info[0]][0] > d[max][0]: max = info[0] print(max) ```
MatrixStudio/Codeforces-Python-Submissions
Tonight is brain dinner night and all zombies will gather together to scarf down some delicious brains. The artful Heidi plans to crash the party, incognito, disguised as one of them. Her objective is to get away with at least one brain, so she can analyze the zombies' mindset back home and gain a strategic advantage. They will be *N* guests tonight: *N*<=-<=1 real zombies and a fake one, our Heidi. The living-dead love hierarchies as much as they love brains: each one has a unique rank in the range 1 to *N*<=-<=1, and Heidi, who still appears slightly different from the others, is attributed the highest rank, *N*. Tonight there will be a chest with brains on display and every attendee sees how many there are. These will then be split among the attendees according to the following procedure: The zombie of the highest rank makes a suggestion on who gets how many brains (every brain is an indivisible entity). A vote follows. If at least half of the attendees accept the offer, the brains are shared in the suggested way and the feast begins. But if majority is not reached, then the highest-ranked zombie is killed, and the next zombie in hierarchy has to make a suggestion. If he is killed too, then the third highest-ranked makes one, etc. (It's enough to have exactly half of the votes – in case of a tie, the vote of the highest-ranked alive zombie counts twice, and he will of course vote in favor of his own suggestion in order to stay alive.) You should know that zombies are very greedy and sly, and they know this too – basically all zombie brains are alike. Consequently, a zombie will never accept an offer which is suboptimal for him. That is, if an offer is not strictly better than a potential later offer, he will vote against it. And make no mistake: while zombies may normally seem rather dull, tonight their intellects are perfect. Each zombie's priorities for tonight are, in descending order: 1. survive the event (they experienced death already once and know it is no fun), 1. get as many brains as possible. Heidi goes first and must make an offer which at least half of the attendees will accept, and which allocates at least one brain for Heidi herself. What is the smallest number of brains that have to be in the chest for this to be possible?
```python n = int(input()) if n%2==1: print(n//2+1) else: print(n//2) ```
MatrixStudio/Codeforces-Python-Submissions
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*. But 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.
```python n=int(input()) if n==1: print(-1) else: a="" while n>0: a=a+str(n) a=a+" " n=n-1 print(a) ```
MatrixStudio/Codeforces-Python-Submissions
The programming competition season has already started and it's time to train for ICPC. Sereja coaches his teams for a number of year and he knows that to get ready for the training session it's not enough to prepare only problems and editorial. As the training sessions lasts for several hours, teams become hungry. Thus, Sereja orders a number of pizzas so they can eat right after the end of the competition. Teams plan to train for *n* times during *n* consecutive days. During the training session Sereja orders exactly one pizza for each team that is present this day. He already knows that there will be *a**i* teams on the *i*-th day. There are two types of discounts in Sereja's favourite pizzeria. The first discount works if one buys two pizzas at one day, while the second is a coupon that allows to buy one pizza during two consecutive days (two pizzas in total). As Sereja orders really a lot of pizza at this place, he is the golden client and can use the unlimited number of discounts and coupons of any type at any days. Sereja wants to order exactly *a**i* pizzas on the *i*-th day while using only discounts and coupons. Note, that he will never buy more pizzas than he need for this particular day. Help him determine, whether he can buy the proper amount of pizzas each day if he is allowed to use only coupons and discounts. Note, that it's also prohibited to have any active coupons after the end of the day *n*.
```python input() p=0 for x in map(int, input().split()): p=1<<20 if x<p else p^x&1 print('NO' if p>0 else 'YES') ```
MatrixStudio/Codeforces-Python-Submissions
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second. One day in 230 AD Shapur was trying to find out if any one can possibly do calculations faster than him. As a result he made a very great contest and asked every one to come and take part. In his contest he gave the contestants many different pairs of numbers. Each number is made from digits 0 or 1. The contestants should write a new number corresponding to the given pair of numbers. The rule is simple: The *i*-th digit of the answer is 1 if and only if the *i*-th digit of the two given numbers differ. In the other case the *i*-th digit of the answer is 0. Shapur made many numbers and first tried his own speed. He saw that he can perform these operations on numbers of length ∞ (length of a number is number of digits in it) in a glance! He always gives correct answers so he expects the contestants to give correct answers, too. He is a good fellow so he won't give anyone very big numbers and he always gives one person numbers of same length. Now you are going to take part in Shapur's contest. See if you are faster and more accurate.
```python a=input() b=input() aa=[] bb=[] t=0 for c in a: aa.append(c) for d in b: bb.append(d) while True: if aa[t]==bb[t]: t+=1 print(0,end='') else: t+=1 print(1,end='') if t>=len(a): break ```
MatrixStudio/Codeforces-Python-Submissions
Special Agent Smart Beaver works in a secret research department of ABBYY. He's been working there for a long time and is satisfied with his job, as it allows him to eat out in the best restaurants and order the most expensive and exotic wood types there. The content special agent has got an important task: to get the latest research by British scientists on the English Language. These developments are encoded and stored in a large safe. The Beaver's teeth are strong enough, so the authorities assured that upon arriving at the place the beaver won't have any problems with opening the safe. And he finishes his aspen sprig and leaves for this important task. Of course, the Beaver arrived at the location without any problems, but alas. He can't open the safe with his strong and big teeth. At this point, the Smart Beaver get a call from the headquarters and learns that opening the safe with the teeth is not necessary, as a reliable source has sent the following information: the safe code consists of digits and has no leading zeroes. There also is a special hint, which can be used to open the safe. The hint is string *s* with the following structure: - if *s**i* = "?", then the digit that goes *i*-th in the safe code can be anything (between 0 to 9, inclusively); - if *s**i* is a digit (between 0 to 9, inclusively), then it means that there is digit *s**i* on position *i* in code; - if the string contains letters from "A" to "J", then all positions with the same letters must contain the same digits and the positions with distinct letters must contain distinct digits. - The length of the safe code coincides with the length of the hint. For example, hint "?JGJ9" has such matching safe code variants: "51919", "55959", "12329", "93539" and so on, and has wrong variants such as: "56669", "00111", "03539" and "13666". After receiving such information, the authorities change the plan and ask the special agents to work quietly and gently and not to try to open the safe by mechanical means, and try to find the password using the given hint. At a special agent school the Smart Beaver was the fastest in his platoon finding codes for such safes, but now he is not in that shape: the years take their toll ... Help him to determine the number of possible variants of the code to the safe, matching the given hint. After receiving this information, and knowing his own speed of entering codes, the Smart Beaver will be able to determine whether he will have time for tonight's show "Beavers are on the trail" on his favorite TV channel, or he should work for a sleepless night...
```python S = input() chSet = set() numQ = 0 for s in S: if ord(s) >= 65 and ord(s) <= 74: chSet.add(s) elif s == '?': numQ += 1 if len(chSet) != 0: cur = 1 for i in range(10, max(10 - len(chSet), 0), -1): cur *= i if S[0] not in chSet: print(cur * pow(10, numQ)) else: cur = cur * 9 // 10 print(cur * pow(10, numQ)) else: print(pow(10, numQ)) ```
MatrixStudio/Codeforces-Python-Submissions
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: - 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. Your 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.
```python from collections import Counter def solved(dic): chan = 0 if len(list(dic.values())) == 3: for k,v in dic.items(): if v == 4: chan = k if chan != 0: return 'Bear' elif len(list(dic.values())) == 2: for k,v in dic.items(): if v == 4: chan = k if chan != 0: return 'Elephant' else: return 'Alien' if __name__ == '__main__': lst = list(map(int,input().split())) dic = Counter(lst) print(solved(dic)) ```
MatrixStudio/Codeforces-Python-Submissions
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.
```python import math def compute(l, n): l2 = math.ceil(n / l) return 2 * l + 2 * l2 n = int(input()) best = 9999999999 for i in range(1, n): best = min(best, compute(i, n)) print(best) ```