problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
A and B are preparing themselves for programming contests. B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code. Initially, the compiler displayed n compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix s...
3
n=int(input()) a=[int(i) for i in input().split()] b=[int(i) for i in input().split()] c=[int(i) for i in input().split()] a.sort() b.sort() c.sort() def Binarysearch(s,key): low=0 high=len(s)-1 while(high>=low): mid=(low+high)//2 if key<s[mid]: high=mid-1 elif key==s[mid...
Bessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However, Bessie is sure that there is a secret message hidden inside. The text is a string s of lowercase Latin letters. She considers a string t as hidden in string s if t exists as a subsequence of s whose indices form an arithmetic pr...
3
from collections import Counter from collections import defaultdict best = [[0 for i in range(256)] for j in range(256)] cnt = [0] * 256 s = input() n = len(s) count = Counter(s) cnt[ord(s[0])] = 1 ans = max(list(count.values())) for i in range(1, n): i1 = ord(s[i]) for j in range(ord('a'), ord('z')+1): ...
Takahashi received otoshidama (New Year's money gifts) from N of his relatives. You are given N values x_1, x_2, ..., x_N and N strings u_1, u_2, ..., u_N as input. Each string u_i is either `JPY` or `BTC`, and x_i and u_i represent the content of the otoshidama from the i-th relative. For example, if x_1 = `10000` a...
3
ans = 0 for i in range(int(input())): x,u = input().split() if u == "BTC":ans += float(x)*3.8e5 else:ans += int(x) print(ans)
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 squa...
3
a, b = [int(i) for i in input().split()] reszta = a%2 cale = int(a/2) count = 0 count = b * cale + reszta * int(b/2) print(count)
Petya has an array a consisting of n integers. He wants to remove duplicate (equal) elements. Petya wants to leave only the rightmost entry (occurrence) for each element of the array. The relative order of the remaining unique elements should not be changed. Input The first line contains a single integer n (1 ≤ n ≤ ...
3
# ANSHUL GAUTAM # IIIT-D T = int(input()) l = list(map(int, input().split())) L = [] r = l[::-1] for i in r: if(i not in L): L.append(i) R = L[::-1] print(len(R)) print(*R)
Let's denote a function <image> You are given an array a consisting of n integers. You have to calculate the sum of d(ai, aj) over all pairs (i, j) such that 1 ≤ i ≤ j ≤ n. Input The first line contains one integer n (1 ≤ n ≤ 200000) — the number of elements in a. The second line contains n integers a1, a2, ..., ...
3
n = int(input()) a = input().split() a = [int(x) for x in a] cnt = {} for i in range(n): cnt[a[i]] = 0 cnt[a[i]+1] = 0 cnt[a[i]-1] = 0 ans = 0 res = 0 for i in range(n): ans = ans + (i-cnt[a[i]]-cnt[a[i]+1]-cnt[a[i]-1])*a[i] ans = ans - (res-cnt[a[i]-1]*(a[i]-1)-cnt[a[i]]*a[i]-cnt[a[i]+1]*(a[i]+1))...
Petr stands in line of n people, but he doesn't know exactly which position he occupies. He can say that there are no less than a people standing in front of him and no more than b people standing behind him. Find the number of different positions Petr can occupy. Input The only line contains three integers n, a and ...
3
import math, os, sys import string, re from itertools import * from collections import Counter from operator import mul def inputint(): return int(input()) def inputarray(func=int): return map(func, input().split()) def inputarray2(n, func=int): for _ in range(n): yield func(input()) n, a, b = ...
Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first n. He writes down the followin...
3
n, k = map(int, input().split()) if n % 2 == 0: a = n // 2 elif n % 2 != 0: a = n // 2 + 1 if k <= a: x = (k - 1) * 2 + 1 elif k > a: x = (k - a) * 2 print(x)
You are given a string s consisting of n lowercase Latin letters. You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation. String s = s_1 s_2 ... s_n is lexicograp...
3
n = int(input()) s = input() i = next((i for i in range(n-1) if s[i] > s[i+1]), n-1) print(s[:i] + s[i+1:])
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr...
3
import math #line = input() word1 = input().lower() word2 = input().lower() #n = int(line.split(' ')[0]) #m = int(line.split(' ')[1]) #tabela = [None] * n count =0 stevec=0 while stevec < len(word1): if word1[stevec] != word2[stevec]: if ord(word1[stevec]) < ord(word2[stevec]): count = -1 ...
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 swit...
1
# coding =utf-8 I = lambda:map(int,raw_input().split()) a = [] b = [] x = [1,-1,0,0,0] y = [0,0,1,-1,0] for i in range(3): a.append(I()) for i in range(3): for j in range(3): sum =0 for k in range(5): if i+x[k]>=0 and i+x[k]<=2 and j+y[k]>=0 and j+y[k]<=2: sum+=a[i+x[k]][j+y[k]] b.append((sum+1)%2) print...
In this problem, we use the 24-hour clock. Takahashi gets up exactly at the time H_1 : M_1 and goes to bed exactly at the time H_2 : M_2. (See Sample Inputs below for clarity.) He has decided to study for K consecutive minutes while he is up. What is the length of the period in which he can start studying? Constraint...
3
a,b,c,d,e=map(int,input().split()) x=60*a+b y=60*c+d print((y-x)-e)
Let's denote a function <image> You are given an array a consisting of n integers. You have to calculate the sum of d(ai, aj) over all pairs (i, j) such that 1 ≤ i ≤ j ≤ n. Input The first line contains one integer n (1 ≤ n ≤ 200000) — the number of elements in a. The second line contains n integers a1, a2, ..., ...
3
n = int(input()) a = list(map(int, input().split())) bad = 0 for i in range(1, n): bad += a[i] - a[0] Sum = bad for i in range(1, n): bad -= (a[i] - a[i - 1]) * (n - i) Sum += bad maP = dict() for i in range(n): if a[i] in maP: maP[a[i]] += 1 else: maP[a[i]] = 1 for j in range(-1, 2, 2): ...
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 squa...
3
#ygioughh m,n=map(int,input().split()) print((m*n)//2)
Today, Mezo is playing a game. Zoma, a character in that game, is initially at position x = 0. Mezo starts sending n commands to Zoma. There are two possible commands: * 'L' (Left) sets the position x: =x - 1; * 'R' (Right) sets the position x: =x + 1. Unfortunately, Mezo's controller malfunctions sometimes. ...
3
import io, sys, atexit, os import math as ma from sys import exit from decimal import Decimal as dec from itertools import permutations from itertools import combinations def li(): return list(map(int, sys.stdin.readline().split())) def num(): return map(int, sys.stdin.readline().split()) def nu(): re...
For the multiset of positive integers s=\\{s_1,s_2,...,s_k\}, define the Greatest Common Divisor (GCD) and Least Common Multiple (LCM) of s as follow: * \gcd(s) is the maximum positive integer x, such that all integers in s are divisible on x. * lcm(s) is the minimum positive integer x, that divisible on all integ...
3
from math import gcd, sqrt from itertools import takewhile from functools import reduce def ri(): return int(input()) def ria(): return list(map(int, input().split())) def lcm(a, b): return a * b // gcd(a, b) def gcd_n(*args): return reduce(gcd, args) def odd_numbers(start=3): while True: yi...
You're given an integer n. For every integer i from 2 to n, assign a positive integer a_i such that the following conditions hold: * For any pair of integers (i,j), if i and j are coprime, a_i ≠ a_j. * The maximal value of all a_i should be minimized (that is, as small as possible). A pair of integers is call...
3
def SieveOfEratosthenes(n): prime = [0 for i in range(n+1)] p = 2 count = 1 while (p * p <= n): if (prime[p] == 0): prime[p] = count count += 1 for i in range(p * p, n+1, p): prime[i] = prime[p] p += 1 for p in range(2, n): ...
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." — an excerpt from contest rules. A total of n participants took part in the contest (n ≥ k), and you already know their scores. Calculate how many ...
3
n, k = map(int, input().split()) scores = list(map(int, input().split())) ans = 0 for s in scores: ans += (s > 0) and (s >= scores[k - 1]) print(ans)
Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it ...
3
n=int(input()) ls=[] lss=[] for i in range(n): a,b=[int(y) for y in input().split()] ls.append(a) lss.append(b) maxy=0 a=0 for i in range(n): a+=(-ls[i]+lss[i]) if a>maxy: maxy=a print(maxy)
You have n students under your control and you have to compose exactly two teams consisting of some subset of your students. Each student had his own skill, the i-th student skill is denoted by an integer a_i (different students can have the same skills). So, about the teams. Firstly, these two teams should have the s...
3
for i in range(int(input())): n=int(input()) arr=list(map(int,input().split())) d={} maxcount=0 for i in range(len(arr)): if arr[i] in d.keys(): d[arr[i]]+=1 else: d[arr[i]]=1 maxcount=max(maxcount,d[arr[i]]) diff=len(d) # print(maxcount,diff) ...
Peter likes to travel by train. He likes it so much that on the train he falls asleep. Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour. The boy start...
1
atob = str(raw_input()) a = str(raw_input()) b = str(raw_input()) rev = atob[::-1] forw = False back = False if (atob.find(a)+len(a)-1) < atob.rfind(b) and atob.find(a) != -1: forw = True if (rev.find(a)+ len(a)-1) < rev.rfind(b) and rev.find(b) != -1: back = True if forw and back: print "both" elif forw:...
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr...
3
str1 = input().lower() str2 = input().lower() if str1 < str2: print('-1') elif str1 > str2: print('1') else: print('0')
The Smart Beaver from ABBYY plans a space travel on an ultramodern spaceship. During the voyage he plans to visit n planets. For planet i ai is the maximum number of suitcases that an alien tourist is allowed to bring to the planet, and bi is the number of citizens on the planet. The Smart Beaver is going to bring som...
3
I=lambda:map(int,input().split()) n,c=I() a,b=[],[] for _ in range(n):x,y=I();a.append(x);b.append(y) if max(a)==0:print([0,-1][n==c]);exit() def f(x): r=0 for i in range(n): r+=1+a[i]*x//b[i] if r>c:break return r l=-1 r=10**18 while l<r-1: m=(l+r)//2 if f(m)<c:l=m else:r=m L=r l=-1 r=10**18 while l<r-1: m=...
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If...
3
def bfs(x,c): if a[x] ==c: a[x] = ' ' num[ord(c)-48]+=1 if x+1<=len(a)-1: bfs(x+1,c) if x-1>=0:bfs(x-1,c) return 0 a=[] s= input() boo = True num =[0,0] for i in range(len(s)): a.append(s[i]) b = a for i in range(len(s)): if s[i] == '0': bfs(i,'0') if num[0]>=...
Let's denote a function <image> You are given an array a consisting of n integers. You have to calculate the sum of d(ai, aj) over all pairs (i, j) such that 1 ≤ i ≤ j ≤ n. Input The first line contains one integer n (1 ≤ n ≤ 200000) — the number of elements in a. The second line contains n integers a1, a2, ..., ...
3
n = int(input()) ssum = 0 fans = 0 mp = {0:0} a = list(map(int, input().strip().split()))[:n] def find(x): if mp.get(x): return mp[x] else: return 0 for i in range(n): if not mp.get(a[i]): mp[a[i]] = 0 mp[a[i]] += 1 fans += i * a[i] - ssum + find(a[i] + 1) - find(...
Let's call an undirected graph of n vertices p-interesting, if the following conditions fulfill: * the graph contains exactly 2n + p edges; * the graph doesn't contain self-loops and multiple edges; * for any integer k (1 ≤ k ≤ n), any subgraph consisting of k vertices contains at most 2k + p edges. A sub...
3
t = int(input()) for test in range(t): n,p = map(int,input().split()) s = "" for i in range(n): s+=str(i+1)+' '+str((i+1)%n+1)+'\n' s+=str(i+1)+' '+str((i+2)%n+1)+'\n' if p > 0: for i in range(n): for j in range(i+3,min(n,i-2+n)): s+=str(i+1)+' '+str(j...
Phoenix has n coins with weights 2^1, 2^2, ..., 2^n. He knows that n is even. He wants to split the coins into two piles such that each pile has exactly n/2 coins and the difference of weights between the two piles is minimized. Formally, let a denote the sum of weights in the first pile, and b denote the sum of weigh...
3
t = int(input()) for i in range(t): print(2 ** (int(input()) // 2 + 1) - 2)
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg...
3
import sys import math import bisect import itertools import random import re def solve(A, m): n = len(A) ans = 0 for i in range(n): if A[i] % m: return -1 ans += A[i] // m return ans def main(): n, m = map(int, input().split()) A = list(map(int, input().split())) ...
Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you? You are given a system of equations: <image> You should count, how many there are pai...
3
s,p=map(int,input().split()) x=range(32) print(sum(a*a+b-s==a+b*b-p==0 for a in x for b in x))
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like. Now let's imagine a typical morning in your family. You haven't w...
3
a=int(input()) l=list(map(int,input().split()))[:a] l.sort() b=0 c=0 n=0 for i in l: b+=i for i in l[::-1]: c+=i n+=1 if c>(b/2): break print(n)
As a token of his gratitude, Takahashi has decided to give his mother an integer sequence. The sequence A needs to satisfy the conditions below: * A consists of integers between X and Y (inclusive). * For each 1\leq i \leq |A|-1, A_{i+1} is a multiple of A_i and strictly greater than A_i. Find the maximum possible ...
3
X,Y=map(int, input().split()) c=0 a=X while a<=Y: c=c+1 a=a*2 print(c)
Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game. Rules of the game are very simple: at first number of rounds n is defined. I...
3
n = int(input()) winner = {1: 'Mishka', 2: 'Chris', 3: 'Friendship is magic!^^'} count = 0 for i in range(n): a, b = map(int, input().split()) if a-b > 0: count += 1 elif a-b < 0: count -= 1 if count > 0: print(winner[1]) elif count < 0: print(winner[2]) else: print(winner[3])
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point. Misha has a list of handle change requests. After completing the re...
3
class QuickFindUF: def __init__(self): self.parent = {} def connected(self, node1, node2): return self.root(node1) == self.root(node2) def root(self, node): if not node in self.parent.keys(): self.parent[node] = node return node while self.parent[no...
You are given two positive integers n (1 ≤ n ≤ 10^9) and k (1 ≤ k ≤ 100). Represent the number n as the sum of k positive integers of the same parity (have the same remainder when divided by 2). In other words, find a_1, a_2, …, a_k such that all a_i>0, n = a_1 + a_2 + … + a_k and either all a_i are even or all a_i ar...
3
t=int(input()) while(t>0): n,k=map(int,input().split()) if((n-k+1)%2!=0): if(n-k+1<=0): print('NO') else: print('YES') l=[1]*(k-1)+[n-k+1] print(*l) else: if((n-(k-1)*2)%2==0): if((n-(k-1)*2)<=0): print('NO')...
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings. Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, seco...
3
n=int(input()) a=1 msg="" while(a!=n): if(a%2==0): msg+="I love that " else: msg+="I hate that " a+=1 if(n%2==0): msg+="I love it" else: msg+="I hate it" print(msg)
Kilani is playing a game with his friends. This game can be represented as a grid of size n × m, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell). The game is played in rounds. In each round players expand turn by turn: firstly, t...
3
from collections import deque import math def add(x, y): return (x[0] + y[0], x[1] + y[1]) h, w, n = list(map(int, input().split())) speeds = list(map(int, input().split())) arr = [None] * h castles = [deque() for _ in range(n)] castles_count = [0] * n for i in range(h): arr[i] = list(input()) for j in ...
Write a program which reads three integers a, b and c, and prints "Yes" if a < b < c, otherwise "No". Constraints * 0 ≤ a, b, c ≤ 100 Input Three integers a, b and c separated by a single space are given in a line. Output Print "Yes" or "No" in a line. Examples Input 1 3 8 Output Yes Input 3 8 1 Output...
3
a ,b ,c = map(int,input().split());print(["No","Yes"][a < b< c])
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find ...
3
s=str(input()) l=list(s) flag=0 if ('0' not in l) and ('1' not in l) and ('2' not in l) and ('3' not in l)and ('5' not in l) and ('6' not in l) and ('8' not in l) and ('9' not in l) and (('4' in l) or ('7' in l)): flag=1 else: n=int(s) if n%4==0 or n%7==0 or n%47==0 or n%44==0 or n%74==0 or n%77==0 or n%447==0 or n%...
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated. The language is that peculiar as it has exactly one variable, called x. Also, there are two operations: * Operation ++ increases the value of variable x by 1. * Operation -- decreases the value of variable x by 1....
3
x=int(input()) result=0 for i in range(0,x): sentencia=input() result=result+sentencia.count("++") -sentencia.count("--") print (result)
In this problem, we use the 24-hour clock. Takahashi gets up exactly at the time H_1 : M_1 and goes to bed exactly at the time H_2 : M_2. (See Sample Inputs below for clarity.) He has decided to study for K consecutive minutes while he is up. What is the length of the period in which he can start studying? Constraint...
3
H,M,h,m,K = map(int,input().split()) a = h-H a = a*60 + (m-M) print(a-K)
There is a directed graph with N vertices and M edges. The i-th edge (1≤i≤M) points from vertex a_i to vertex b_i, and has a weight c_i. We will play the following single-player game using this graph and a piece. Initially, the piece is placed at vertex 1, and the score of the player is set to 0. The player can move t...
3
INF = -float("inf") def Bellmanford(n, edges): dp = [INF] * n dp[0] = 0 for i in range(n): # たかだかn-1回ループ n回目でまだ更新できたら負閉路がある for u, v, c in edges: if dp[u] != INF and dp[u] + c > dp[v]: dp[v] = dp[u] + c if i == n-1 and v == n-1: retu...
Allen has a LOT of money. He has n dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are 1, 5, 10, 20, 100. What is the minimum number of bills Allen could receive after withdrawing his entire balance? Input The first...
3
n = int(input()) den = [100, 20, 10, 5, 1] i = 0 bills = 0 while n > 0: t = n // den[i] if t > 0: bills += t n %= den[i] i += 1 #print(n) print(bills)
Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on. The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call ver...
3
import sys input = sys.stdin.readline from collections import deque class Graph(object): """docstring for Graph""" def __init__(self,n,d): # Number of nodes and d is True if directed self.n = n self.graph = [[] for i in range(n)] self.parent = [-1 for i in range(n)] self.directed = d def addEdge(self,x,y...
The king's birthday dinner was attended by k guests. The dinner was quite a success: every person has eaten several dishes (though the number of dishes was the same for every person) and every dish was served alongside with a new set of kitchen utensils. All types of utensils in the kingdom are numbered from 1 to 100....
3
from collections import Counter n,k = map(int,input().split(' ')) utensils = Counter(input().split(' ')) max_utensils = max(list(map(int,list(utensils.values())))) min_dishes = int(max_utensils / k) if max_utensils % k == 0 else int(max_utensils / k) + 1 print(min_dishes*k*len(utensils)-n)
Write a program which prints $n$-th fibonacci number for a given integer $n$. The $n$-th fibonacci number is defined by the following recursive formula: \begin{equation*} fib(n)= \left \\{ \begin{array}{ll} 1 & (n = 0) \\\ 1 & (n = 1) \\\ fib(n - 1) + fib(n - 2) & \\\ \end{array} \right. \end{equation*} Constraints ...
3
n = int(input()) fib = [1]*(n+1) for i in range(2,n+1): fib[i] = fib[i-1]+fib[i-2] print(fib[n])
Write a program which reads a word W and a text T, and prints the number of word W which appears in text T T consists of string Ti separated by space characters and newlines. Count the number of Ti which equals to W. The word and text are case insensitive. Constraints * The length of W ≤ 10 * W consists of lower cas...
3
import sys w = input() text = sys.stdin.read() print(text.lower().split().count(w))
While walking down the street Vanya saw a label "Hide&Seek". Because he is a programmer, he used & as a bitwise AND for these two words represented as a integers in base 64 and got new word. Now Vanya thinks of some string s and wants to know the number of pairs of words of length |s| (length of s), such that their bit...
3
def main(): s = input() number = '' ans = 1 for c in s: if c >= '0' and c <= '9': number = bin(int(c))[2:] elif c >= 'A' and c <= 'Z': number = bin(ord(c) - 55)[2:] elif c >= 'a' and c <= 'z': number = bin(ord(c) - 61)[2:] elif c == '-': number = bin(62)[2:] else: number = bin(63)[2:] if len(number) ...
You are policeman and you are playing a game with Slavik. The game is turn-based and each turn consists of two phases. During the first phase you make your move and during the second phase Slavik makes his move. There are n doors, the i-th door initially has durability equal to a_i. During your move you can try to br...
3
n,x,y=map(int,input().split()) arr=list(map(int,input().split())) if(x-y>0): print(n) else: arr.sort() count=0 for i in arr: if(i<=x): count+=1 else: break if(count%2==0): print(count//2) else: print((count//2) +1)
On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k pe...
3
#!/usr/bin/python3 import sys sys.setrecursionlimit(10 ** 9) def bscheck(n, l, v1, v2, k, t): while True: if k > n: k = n if n == 0: return True if l / v2 > t: return False # v2 * tx + v1 * (t - tx) = l # (v2 - v1) * tx = l - v1 * t ...
You are given a string S consisting of lowercase English letters. We will write down this string, starting a new line after every w letters. Print the string obtained by concatenating the letters at the beginnings of these lines from top to bottom. Constraints * 1 \leq w \leq |S| \leq 1000 * S consists of lowercase E...
3
s = input() w = int(input()) print(''.join(s[::w]))
Two players play a game. Initially there are n integers a_1, a_2, …, 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 t...
3
n=int(input()) l=list(map(int,input().split())) l.sort() if n%2!=0: print(l[int(n/2)]) else: print(l[int(n/2-1)])
Valentin participates in a show called "Shockers". The rules are quite easy: jury selects one letter which Valentin doesn't know. He should make a small speech, but every time he pronounces a word that contains the selected letter, he receives an electric shock. He can make guesses which letter is selected, but for eac...
3
import sys #f = open('input', 'r') f = sys.stdin n = int(f.readline()) cset = set(chr(ord('a')+i) for i in range(26)) found = False res = 0 for _ in range(n): action, word = f.readline().split() if action == '!': if found: res += 1 cset &= set(word) elif action == '.': cset -= set(word) else:...
Takahashi is a user of a site that hosts programming contests. When a user competes in a contest, the rating of the user (not necessarily an integer) changes according to the performance of the user, as follows: * Let the current rating of the user be a. * Suppose that the performance of the user in the contest is b. ...
3
r,g=map(int,open(0).read().split()) print(g*2-r)
Let's define a function f(x) (x is a positive integer) as follows: write all digits of the decimal representation of x backwards, then get rid of the leading zeroes. For example, f(321) = 123, f(120) = 21, f(1000000) = 1, f(111) = 111. Let's define another function g(x) = (x)/(f(f(x))) (x is a positive integer as well...
3
testcases = int(input()) for testcase in range(testcases): n = input() print(len(n))
A string s of length n can be encrypted by the following algorithm: * iterate over all divisors of n in decreasing order (i.e. from n to 1), * for each divisor d, reverse the substring s[1 ... d] (i.e. the substring which starts at position 1 and ends at position d). For example, the above algorithm applied t...
3
size = 0 def decrypt(s: str): divList = [] div = 2 while div*div <= size: if size%div == 0: div1 = int(size/div) divList.append(div) if div!=div1: divList.append(div1) div += 1 divList.append(size) divList.sort() #print(divLi...
"Hey, it's homework time" — thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him. The sequence of n integers is calle...
3
import math import sys import collections # imgur.com/Pkt7iIf.png def getdict(n): d = {} if type(n) is list: for i in n: if i in d: d[i] += 1 else: d[i] = 1 else: for i in range(n): t = ii() if t in d: ...
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If...
3
#k,p=map(str,input().split()) ##print(f'{k}\n{p}') ##j=(list(sorted(k))) ##b=(list(sorted(p))) ##print(j) ##print(b) #print(min(list(sorted(k)),list(sorted(p)))) k = input() if 7 * '1' in k: print('YES') elif 7 * '0' in k: print('YES') else: print('NO')
When preparing a tournament, Codeforces coordinators try treir best to make the first problem as easy as possible. This time the coordinator had chosen some problem and asked n people about their opinions. Each person answered whether this problem is easy or hard. If at least one of these n people has answered that th...
3
input() print('EASY' if set(input().split())=={'0'} else 'HARD')
Vova had a pretty weird sleeping schedule. There are h hours in a day. Vova will sleep exactly n times. The i-th time he will sleep exactly after a_i hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is 0). Each time Vova sleeps exactly one day (in...
3
from collections import defaultdict IA = lambda: map(int,input().split()) n,h,l,r=IA() a=list(IA()) def judge(x): if x<=r and x>=l: return 1 return 0 dp=[[int(-1) for _ in range(h)] for _ in range(n+1)] dp[0][0]=0 for i in range(0,n): for j in range(0,h): if dp[i][j]>=0: ...
There are N stones arranged in a row. The i-th stone from the left is painted in the color C_i. Snuke will perform the following operation zero or more times: * Choose two stones painted in the same color. Repaint all the stones between them, with the color of the chosen stones. Find the number of possible final s...
3
import sys N = int(input()) C = [0] n = N for i in range(1, n + 1): c = int(sys.stdin.readline()) if c == C[-1]: N -= 1 else: C.append(c) dp = [0] * (N + 2) dp[0] = 1 dp[1] = 1 cumsum = [0] * (2 * (10 ** 5) + 2) cumsum[C[1]] = 1 for i in range(2, N+1): dp[i] = dp[i - 1] + cumsum[C[i]] ...
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them. Input The first line contains integ...
3
n = int(input()) s = input() o = 0; for i in range(len(s)-1): if s[i] == s[i+1]: o+=1 print(o)
On a two-dimensional plane, there are N red points and N blue points. The coordinates of the i-th red point are (a_i, b_i), and the coordinates of the i-th blue point are (c_i, d_i). A red point and a blue point can form a friendly pair when, the x-coordinate of the red point is smaller than that of the blue point, an...
3
n = int(input()) red = [list(map(int, input().split())) for _ in range(n)] blue = [list(map(int, input().split())) for _ in range(n)] blue.sort() res = 0 for bx, by in blue: dist = -1 for rx, ry in red: if rx < bx and dist < ry < by: dist = ry mx, my = rx, ry if dist >...
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the ...
3
import itertools import math import os import sys eps = 1e-8 coord = [[]] + [list(map(int, input().split())) for _ in range(8)] idx = list(range(1, 9)) def perpendicular(v1, v2): return sum([x * y for (x, y) in zip(v1, v2)]) < eps def all_perpendicular(vs): return all([perpendicular(vs[i], vs[(i+1)%4]) for...
Recall that the permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). A sequence a is a subsegment of a...
3
import math n,m=map(int,input().split()) count=0 fac=[1] for i in range(1,n+1): fac.append(fac[-1]*i%m) for length in range(n): times=n-length length+=1 p=fac[length] number=n-length+1 q=fac[number] count+=((times*p*q)%m) print(count%m)
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi). They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan consider...
3
if __name__=='__main__': n = int(input()) gx,gy,c= {},{},0 tup = {} for i in range(n): x,y= (input().split(' ')) if x in gx and y not in gy: c += gx[x] gx[x]+=1 gy[y]=1 tup[(x,y)]=1 elif x not in gx and y in gy: c += gy[...
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d...
3
s=input() c=0 for i in s: if i=='7'or i=='4': c+=1 if c==4 or c==7: print("YES") else: print("NO")
For a finite set of integers X, let f(X)=\max X - \min X. Given are N integers A_1,...,A_N. We will choose K of them and let S be the set of the integers chosen. If we distinguish elements with different indices even when their values are the same, there are {}_N C_K ways to make this choice. Find the sum of f(S) ove...
3
MOD = 10**9+7 N, K = map(int, input().split()) A = list(map(int, input().split())) A.sort() f = [1] for i in range(10**5): f.append(f[-1] * (i+1) % MOD) def nCr(n, r, mod=MOD): return f[n] * pow(f[r], mod-2, mod) * pow(f[n-r], mod-2, mod) % mod ans = 0 for i in range(N-K+1): ans += (A[-1-i] - A[i]) * nC...
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point x(x > 0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order ...
3
x=int(input()) print(x//5 if x%5==0 else x//5+1)
Santa has to send presents to the kids. He has a large stack of n presents, numbered from 1 to n; the topmost present has number a_1, the next present is a_2, and so on; the bottom present has number a_n. All numbers are distinct. Santa has a list of m distinct presents he has to send: b_1, b_2, ..., b_m. He will send...
3
kl = int(input()) for l in range(kl): n, m = [int(i) for i in input().split()] ind = [0 for i in range(0, n + 1)] a = [0 for i in range(n)] sc = 1 for i in input().split(): i = int(i) ind[i] = sc sc += 1 mm = 0 ssc = 0 scp = 0 for i in input().split(): ...
Ivan plays an old action game called Heretic. He's stuck on one of the final levels of this game, so he needs some help with killing the monsters. The main part of the level is a large corridor (so large and narrow that it can be represented as an infinite coordinate line). The corridor is divided into two parts; let'...
3
R=lambda:map(int,input().split()) q,=R() a=[] for _ in[0]*q:n,r=R();a+=sum(x-k*r>0for k,x in enumerate(sorted(set(R()))[::-1])), print(' '.join(map(str,a)))
[3R2 as DJ Mashiro - Happiness Breeze](https://open.spotify.com/track/2qGqK8GRS65Wlf20qUBEak) [Ice - DJ Mashiro is dead or alive](https://soundcloud.com/iceloki/dj-mashiro-is-dead-or-alive) NEKO#ΦωΦ has just got a new maze game on her PC! The game's main puzzle is a maze, in the forms of a 2 × n rectangle grid. NEKO...
3
n, q = [int(i) for i in input().split()] field = [0] * n bol = True count = 0 count2 = 0 for t in range(q): r, c = [int(i) for i in input().split()] r -= 1 c -= 1 if field[c] == 3: count -= 1 if c > 0: if ((field[c] | field[c - 1]) == 3): count2 -= 1 if c < n - 1:...
Chouti was doing a competitive programming competition. However, after having all the problems accepted, he got bored and decided to invent some small games. He came up with the following game. The player has a positive integer n. Initially the value of n equals to v and the player is able to do the following operatio...
3
n=int(input()) while n>1: start=n-1 if start<=1: break if n%start==0: start-=1 else: n-=start print(n)
You are given two positive integers n and k. Print the k-th positive integer that is not divisible by n. For example, if n=3, and k=7, then all numbers that are not divisible by 3 are: 1, 2, 4, 5, 7, 8, 10, 11, 13 .... The 7-th number among them is 10. Input The first line contains an integer t (1 ≤ t ≤ 1000) — the ...
3
t = int(input()) results = [] for i in range(t): n, k = [int(x) for x in input().strip().split(' ')] if n > k: results.append(k) continue loop = n - 1 how_many_loops = k // loop res = n*how_many_loops + k % loop if k % loop == 0: res -= 1 # import code # code.in...
One day, the Grasshopper was jumping on the lawn and found a piece of paper with a string. Grasshopper became interested what is the minimum jump ability he should have in order to be able to reach the far end of the string, jumping only on vowels of the English alphabet. Jump ability is the maximum possible length of ...
3
print(max([len(i)+1 for i in input().replace("A","-").replace("E","-").replace("I","-").replace("O","-").replace("U","-").replace("Y","-").split("-")]))
At a break Vanya came to the class and saw an array of n k-bit integers a_1, a_2, …, a_n on the board. An integer x is called a k-bit integer if 0 ≤ x ≤ 2^k - 1. Of course, Vanya was not able to resist and started changing the numbers written on the board. To ensure that no one will note anything, Vanya allowed himse...
1
n,k=map(int,raw_input().split()) lst=map(int,raw_input().split()) from functools import * def mycmp(a,b): if p[a]<p[b]: return -1 else: return 1 s=0 f=[0] for i in range(0,n): s=s^lst[i] f.append(s) from collections import * ck=Counter(f) ans=(n*(n+1))/2 val=pow(2,k)-1 for i in ck: v...
Vanya walks late at night along a straight street of length l, lit by n lanterns. Consider the coordinate system with the beginning of the street corresponding to the point 0, and its end corresponding to the point l. Then the i-th lantern is at the point ai. The lantern lights all points of the street that are at the ...
3
#!/usr/bin/env python n, l = map(int, input().strip().split()) a = map(int, input().strip().split()) a = sorted(a) prev = a[0] if len(a) else 0 total = 0 if (prev > total): total = prev for lamp in a[1:]: if ((lamp - prev) / 2 > total): total = (lamp - prev) / 2 prev = lamp if (l - prev > tota...
There are n bags with candies, initially the i-th bag contains i candies. You want all the bags to contain an equal amount of candies in the end. To achieve this, you will: * Choose m such that 1 ≤ m ≤ 1000 * Perform m operations. In the j-th operation, you will pick one bag and add j candies to all bags apart ...
3
import sys import math from collections import defaultdict,Counter # input=sys.stdin.readline # def print(x): # sys.stdout.write(str(x)+"\n") # sys.stdout=open("CP1/output.txt",'w') # sys.stdin=open("CP1/input.txt",'r') # mod=pow(10,9)+7 t=int(input()) for i in range(t): n=int(input()) print(n) print(*list(ra...
Bob has a string s consisting of lowercase English letters. He defines s' to be the string after removing all "a" characters from s (keeping all other characters in the same order). He then generates a new string t by concatenating s and s'. In other words, t=s+s' (look at notes for an example). You are given a string...
3
t = input() a = t.count('a') l2 = (len(t)-a)//2 l1 = len(t)-l2 if t[:l1].replace('a','') == t[l1:]: print(t[:l1]) else: print(':(')
John Smith knows that his son, Thomas Smith, is among the best students in his class and even in his school. After the students of the school took the exams in English, German, Math, and History, a table of results was formed. There are n students, each of them has a unique id (from 1 to n). Thomas's id is 1. Every st...
3
n = int(input()) lst = [] for i in range(n): a = list(map(int,input().split())) lst.append(a) a = sum(lst[0]) cnt = 1 for i in range(1, len(lst)): if a < sum(lst[i]): cnt = cnt + 1 print(cnt)
One Sunday Petr went to a bookshop and bought a new book on sports programming. The book had exactly n pages. Petr decided to start reading it starting from the next day, that is, from Monday. Petr's got a very tight schedule and for each day of the week he knows how many pages he will be able to read on that day. Som...
3
__copyright__ = '' __author__ = 'Son-Huy TRAN' __email__ = "sonhuytran@gmail.com" __doc__ = '' __version__ = '1.0' def find_last_day(n_page: int, reading_schedule: list) -> int: sum_schedule = sum(reading_schedule) n_page %= sum_schedule if n_page % sum_schedule == 0: i = 6 while reading...
In Berland it is the holiday of equality. In honor of the holiday the king decided to equalize the welfare of all citizens in Berland by the expense of the state treasury. Totally in Berland there are n citizens, the welfare of each of them is estimated as the integer in ai burles (burle is the currency in Berland). ...
1
#http://codeforces.com/contest/758/problem/A [n]=map(int,raw_input().split()) welfare=map(int,raw_input().split()) if n>=1 and n<=100 and all(item>=0 for item in welfare) and all(item<=1000000 for item in welfare) and len(welfare)==n: if (sum(welfare)==0): print 0 else: k=0 for item in welfare: ...
A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it! You are given integers n,k. Construct a grid A with size n × n consisting of integers 0 and 1. The very important condition should be satisfied: the sum of all elements in the grid is exactly k. In other words, the number of 1 in the gr...
3
import os import sys from io import BytesIO, IOBase def main(): t = int(input()) for _ in range (t): n,k = map(int, input().split()) M = [[0]*n for i in range (n)] rem = k%n R = list() C = [0]*n for i in range (rem): R.append (1 + k//n) ...
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them. Input The first line contains integ...
1
n = int(raw_input()) s = raw_input() r = 0 for i in range(1, n): if s[i] == s[i - 1]: r = r + 1 print(r)
Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers a, b, c on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting e...
3
a = int(input()) b = int(input()) c = int(input()) d = a+b+c e = a*b*c f = a+b*c g = a*b+c h = (a+b)*c i = a*(b+c) print(max([d,e,f,g,h,i]))
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If...
1
import sys import copy s = sys.stdin.readline()[:-1] def check(s): for i in xrange(0, len(s)): cnt = 0 j = i while j < len(s) and s[i] == s[j]: cnt += 1 j += 1 if cnt >= 7: return True else: continue return False if ch...
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 squa...
3
a = [int(s) for s in input().split()] r = a[0]*a[1] r = int(r) n = 0 n= int(n) while r > 1: r -= 2 n += 1 print(n)
There are n people sitting in a circle, numbered from 1 to n in the order in which they are seated. That is, for all i from 1 to n-1, the people with id i and i+1 are adjacent. People with id n and 1 are adjacent as well. The person with id 1 initially has a ball. He picks a positive integer k at most n, and passes th...
1
def factorize(n): # o(sqr(n)) c, ans = 1, [] while (c * c < n): if n % c == 0: ans.extend([period_sum(1, c, n // c), period_sum(1, n // c, c)]) c += 1 if c * c == n: ans.append(period_sum(1, c, n // c)) print(' '.join(map(str, sorted(ans)))) sum_mn = lambda m, n:...
You are given two integers l and r, where l < r. We will add 1 to l until the result is equal to r. Thus, there will be exactly r-l additions performed. For each such addition, let's look at the number of digits that will be changed after it. For example: * if l=909, then adding one will result in 910 and 2 digits...
3
for _ in range(int(input())): oneee=64656 l,r=map(int,input().split()) dxds=3545 t=r zsfv=6435 ans=0 segdvz=5844 a1=[0]*(len(str(t))) tdgssge=True z=str(l)[::-1] for i in range(len(str(l))): drgdrg=False a1[-(i+1)]=int(z[i]) sef=354 a2=[int(i) for i i...
Sasha and Kolya decided to get drunk with Coke, again. This time they have k types of Coke. i-th type is characterised by its carbon dioxide concentration <image>. Today, on the party in honour of Sergiy of Vancouver they decided to prepare a glass of Coke with carbon dioxide concentration <image>. The drink should als...
3
from collections import deque n, k = map(int, input().split()) d = set(int(x)-n for x in input().split()) q = deque() q.append(0) visited = {i : False for i in range(-1000, 1001)} dist = {i : 0 for i in range(-1000, 1001)} ans = -1 visited[0] = True found = False while q: u = q.popleft() fo...
We have a permutation p = {p_1,\ p_2,\ ...,\ p_n} of {1,\ 2,\ ...,\ n}. Print the number of elements p_i (1 < i < n) that satisfy the following condition: * p_i is the second smallest number among the three numbers p_{i - 1}, p_i, and p_{i + 1}. Constraints * All values in input are integers. * 3 \leq n \leq 20 * p...
3
n=int(input()) p=[int(i) for i in input().split()] ans=0 for i in range(n-2): a,b,c=p[i:i+3] if a<b<c or a>b>c: ans+=1 print(ans)
There exists an island called Arpa’s land, some beautiful girls live there, as ugly ones do. Mehrdad wants to become minister of Arpa’s land. Arpa has prepared an exam. Exam has only one question, given n, print the last digit of 1378n. <image> Mehrdad has become quite confused and wants you to help him. Please hel...
3
n = int(input()) r = pow(1378 , n , 10) print(int(r))
You're given an array b of length n. Let's define another array a, also of length n, for which a_i = 2^{b_i} (1 ≤ i ≤ n). Valerii says that every two non-intersecting subarrays of a have different sums of elements. You want to determine if he is wrong. More formally, you need to determine if there exist four integers...
1
import sys if sys.subversion[0] == "PyPy": import io, atexit sys.stdout = io.BytesIO() atexit.register(lambda: sys.__stdout__.write(sys.stdout.getvalue())) sys.stdin = io.BytesIO(sys.stdin.read()) input = lambda: sys.stdin.readline().rstrip() RS = raw_input RI = lambda x=int: map(x,RS().split(...
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≤ i ≤ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is it...
3
num = int(input()) l = list(int(s) for s in input().split()) count = 1 max = 1 for i in range(num - 1): if l[i] <= l[i + 1]: count += 1 else: count = 1 if count > max: max = count print(max) # _______________________________ #< Welp! Fuck it, I did my best. > # ---------------------...
You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Find the length of the shortest cycle in this graph or determine th...
1
from collections import Counter, defaultdict from sys import stdin, stdout import sys sys.setrecursionlimit(1000000) raw_input = stdin.readline d=defaultdict(set) n=input() l=map(int,raw_input().split()) p=1 c=0 while p<=10**18: temp=0 val=[] for i in xrange(n): if p&l[i]: temp+=1 ...
Sergey is testing a next-generation processor. Instead of bytes the processor works with memory cells consisting of n bits. These bits are numbered from 1 to n. An integer is stored in the cell in the following way: the least significant bit is stored in the first bit of the cell, the next significant bit is stored in ...
3
#----Kuzlyaev-Nikita-Codeforces----- #------------02.04.2020------------- alph="abcdefghijklmnopqrstuvwxyz" #----------------------------------- n=int(input()) s=str(input()) E=0;d=[] for i in range(n):d.append(int(s[i])) d.append(0);d[0]+=1 for i in range(n): if d[i]>1: d[i]=0;d[i+1]+=1 E+=1 ...
You are given positive integers A and B. If A is a divisor of B, print A + B; otherwise, print B - A. Constraints * All values in input are integers. * 1 \leq A \leq B \leq 20 Input Input is given from Standard Input in the following format: A B Output If A is a divisor of B, print A + B; otherwise, print B -...
3
a=[int(i) for i in input().split()] print(a[0]+a[1] if a[1]%a[0]==0 else a[1]-a[0])
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...
3
s = input() + 'd' n = len(s) glas = set(('a', 'o', 'u', 'i', 'e')) f = True for i in range(n - 1): if s[i] in glas or s[i] == 'n': continue if s[i + 1] not in glas: f = False if f: print('YES') else: print('NO')
There are n walruses standing in a queue in an airport. They are numbered starting from the queue's tail: the 1-st walrus stands at the end of the queue and the n-th walrus stands at the beginning of the queue. The i-th walrus has the age equal to ai. The i-th walrus becomes displeased if there's a younger walrus stan...
3
n=int(input()) a=list(map(int,input().split())) m=[0]*n for i in range(n-1,-1,-1): if(i==n-1): m[i]=a[i] else: m[i]=min(a[i],m[i+1]) res=[0 for i in range(n)] for i in range(n): left=i+1 right=n-1 ans=-1 while(left<=right): mid=left+(right-left)//2 if(m[mid]<a[i])...
You are given an array a consisting of n integers a_1, a_2, ... , a_n. In one operation you can choose two elements of the array and replace them with the element equal to their sum (it does not matter where you insert the new element). For example, from the array [2, 1, 4] you can obtain the following arrays: [3, 4],...
3
import math def merge_it_fun(my_list,n1): x_mod0 = 0; x_mod1 = 0; x_mod2 = 0; for x in my_list: if x%3==0: x_mod0+=1; elif x%3==1: x_mod1+=1; else: x_mod2+=1; print(x_mod0+min(x_mod1,x_mod2)+math.floor((abs(x_mod1-x_mod2))/3)) if __n...
The Little Elephant loves Ukraine very much. Most of all he loves town Rozdol (ukr. "Rozdil"). However, Rozdil is dangerous to settle, so the Little Elephant wants to go to some other town. The Little Elephant doesn't like to spend much time on travelling, so for his journey he will choose a town that needs minimum ti...
3
import functools n = int(input()) cities = [int(x) for x in input().split(" ")] min_n = 10000000000000 count_min = 0 min_i = -1 for i, city in enumerate(cities): if city < min_n: min_n = city count_min = 1 min_i = i elif city == min_n: count_min += 1 if count_min == 1: pr...