problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
A bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not. The teacher gave Dmitry's class a very strange task — she asked every student...
3
import sys input = sys.stdin.readline def main(): N = int(input()) S = input().strip() x = S.count("(") y = S.count(")") if x != y: print(-1) return score = 0 ans = 0 cnt = 0 for s in S: cnt += 1 if s == ')': if score - 1 == 0: ...
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
line = int(input()) min_num = 0 for i in range(5, 0, -1): min_num += line//i line %= i print(min_num)
You have a long stick, consisting of m segments enumerated from 1 to m. Each segment is 1 centimeter long. Sadly, some segments are broken and need to be repaired. You have an infinitely long repair tape. You want to cut some pieces from the tape and use them to cover all of the broken segments. To be precise, a piece...
3
n, m, k = [int(t) for t in input().split(' ')] b = [int(t) for t in input().split(' ')] general = n // k rest = n % k INF = 2*m+1 delta = [None] * n for i in range(n): delta[i] = (i, b[i] - b[i-1] if i > 0 else INF) delta.sort(reverse=True, key=lambda x: x[1]) starts = [t[0] for t in delta][:k] starts.sort() s...
There are n students in the first grade of Nlogonia high school. The principal wishes to split the students into two classrooms (each student must be in exactly one of the classrooms). Two distinct students whose name starts with the same letter will be chatty if they are put in the same classroom (because they must ha...
3
a = [0] * 26 for i in range(int(input())): a[ord(input()[0]) - 97] += 1 ans = 0 for v in a: if v == 3: ans += 1 elif v > 3: ans += v // 2 * (v // 2 - 1) // 2 w = v - v // 2; ans += w * (w - 1) // 2 print(ans)
ZS the Coder and Chris the Baboon are travelling to Udayland! To get there, they have to get on the special IOI bus. The IOI bus has n rows of seats. There are 4 seats in each row, and the seats are separated into pairs by a walkway. When ZS and Chris came, some places in the bus was already occupied. ZS and Chris are...
3
n=int(input()) a=[] b=[] s1=[] for i in range(0,n): s=str(input()) a.append(s) f=0 for i in range(0,n): if('OO' in a[i] and f!=1): f=1 s=a[i].split('|') k=s.index('OO') if(k==0): s1.append('++') s1.append('|') s1.append(s[1]) else: ...
Young boy Artem tries to paint a picture, and he asks his mother Medina to help him. Medina is very busy, that's why she asked for your help. Artem wants to paint an n × m board. Each cell of the board should be colored in white or black. Lets B be the number of black cells that have at least one white neighbor adja...
3
t = int(input()) ans = [] for g in range(t): n, m = map(int, input().split()) a = [['B' for i in range(m)] for j in range(n)] if n == 1: a[0][1] = 'W' elif m == 1: a[1][0] = 'W' else: a[n-1][m - 1] = 'W' ans.append(a) for j in ans: for i in j: print(''.join(ma...
After the mysterious disappearance of Ashish, his two favourite disciples Ishika and Hriday, were each left with one half of a secret message. These messages can each be represented by a permutation of size n. Let's call them a and b. Note that a permutation of n elements is a sequence of numbers a_1, a_2, …, a_n, in ...
3
from collections import defaultdict n=int(input()) l=[[-1,-1] for i in range(n)] l1=list(map(int,input().split())) l2=list(map(int,input().split())) for i in range(n): l[l1[i]-1][0]=(i+1) l[l2[i]-1][1]=(i+1) #print(l) for i in range(n): a,b=l[i][0],l[i][1] if l[i][0]<l[i][1]: l[i][0]=-1*(n-b+a)...
Little Dormi received a histogram with n bars of height a_1, a_2, …, a_n for Christmas. However, the more he played with his new histogram, the more he realized its imperfections, so today he wanted to modify it to his liking. To modify the histogram, Little Dormi is able to perform the following operation an arbitrar...
3
for _ in range(int(input())): n=int(input()) a=[0]+list(map(int,input().split()))+[0] n+=2 c=0 for i in range(1,n-1): if a[i]>a[i-1] and a[i]>a[i+1]: p=max(a[i-1],a[i+1]) c+=a[i]-p a[i]=p for i in range(1,n): c+=abs(a[i]-a[i-1]) print(c) ...
After Fox Ciel got off a bus, she found that the bus she was on was a wrong bus and she lost her way in a strange town. However, she fortunately met her friend Beaver Taro and asked which way to go to her castle. Taro's response to her was a string s, and she tried to remember the string s correctly. However, Ciel fee...
3
# import functools # # # class Automaton: # def __init__(self, start, ends, transitions): # self.start = start # self.ends = set(ends) # self.transitions = transitions # [dict] # # def next_states(self, states, char): # states = functools.reduce(set.union, (self.transitions[stat...
You have a playlist consisting of n songs. The i-th song is characterized by two numbers t_i and b_i — its length and beauty respectively. The pleasure of listening to set of songs is equal to the total length of the songs in the set multiplied by the minimum beauty among them. For example, the pleasure of listening to...
3
'''input 3 2 1 100 5 5 100000 1 ''' from sys import stdin, stdout import math import heapq # main starts n, k = list(map(int, stdin.readline().split())) playlist = [] for _ in range(n): playlist.append(list(map(int, stdin.readline().split()))) playlist = sorted(playlist, key = lambda x: x[1], reverse = True) #print(...
You've been in love with Coronavirus-chan for a long time, but you didn't know where she lived until now. And just now you found out that she lives in a faraway place called Naha. You immediately decided to take a vacation and visit Coronavirus-chan. Your vacation lasts exactly x days and that's the exact number of d...
3
def right_m(me, num): k = min(me, num) return k * (k + 1) // 2 def left_m(me, num): k = me if me <= num: return k * (k + 1) // 2 l = me - num return k * (k + 1) // 2 - l * (l + 1) // 2 def ans(lm, rm, num): if num <= lm: return left_m(lm, num) ans = right_m(rm, num) n...
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 pla...
1
#CF2A import sys lines = [] for line in sys.stdin: lines.append(line) lines = lines[1:] result = {} for line in lines: name,score = line.split() score = int(score) if result.has_key(name): result[name] += score else: result[name] = score maxscore = max(result.values()) winners = [n f...
You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4⋅ LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D. You believe that only some part of the ...
3
N, M = map(int, input().split()) S1 = input() S2 = input() ans = 0 dp = [[0 for i in range(M + 1)] for j in range(N + 1)] for i in range(N): for j in range(M): v = max( 0, max( dp[i + 1][j] - 1, dp[i][j + 1] - 1, ) ) if S...
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory. George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living...
3
r=0 for i in range(int(input())): n,m=map(int,input().split()) if m>=n+2: r=r+1 print(r)
Anna is a girl so brave that she is loved by everyone in the city and citizens love her cookies. She is planning to hold a party with cookies. Now she has a vanilla cookies and b chocolate cookies for the party. She invited n guests of the first type and m guests of the second type to the party. They will come to the ...
3
t = int(input()) for i in range(t): a, b, n, m = map(int, input().split()) ans = 'Yes' if min(a, b) < m: ans = 'No' elif a + b < n + m: ans = 'No' print(ans)
Unary is a minimalistic Brainfuck dialect in which programs are written using only one token. Brainfuck programs use 8 commands: "+", "-", "[", "]", "<", ">", "." and "," (their meaning is not important for the purposes of this problem). Unary programs are created from Brainfuck programs using the following algorithm...
3
d={">":'1000', "<":'1001', "+":'1010', "-":'1011', ".":'1100', ",":'1101', "[":'1110', "]":'1111'} s=input() l=[] for i in s: l.append(d[i]) a="".join(l) ans=int(a,2) print(ans%1000003)
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
3
n=int(input()) for i in range(n): s=input() if len(s)>10: s=s[0]+str(len(s)-2)+s[len(s)-1] print(s,sep="\0")
You've been in love with Coronavirus-chan for a long time, but you didn't know where she lived until now. And just now you found out that she lives in a faraway place called Naha. You immediately decided to take a vacation and visit Coronavirus-chan. Your vacation lasts exactly x days and that's the exact number of d...
3
from math import * from sys import stdin,stdout input=stdin.buffer.readline n,x=[int(x) for x in input().split()] d=[int(x) for x in input().split()] s=sum(d) mul=x//s x=x%s n1=n a=[] for i in range(n1): a.append([d[i],(d[i]*(d[i]+1))//2]) a=a+a # print(a) # print(x) l=0 r=0 m=0 total=0 days=0 a.reverse() n=len(a) ...
A permutation of length n 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). Consider a permutation p of length ...
3
class BigMod(object): __mod = None def __init__(self, mod = 1000000007): self.__mod = mod def big_mod(self, base, pw): if pw == 0: return 1 r = self.big_mod(base, pw//2) r = (r * r) % self.__mod if pw % 2 : r = (base * r) % self.__mod ...
To quickly hire highly skilled specialists one of the new IT City companies made an unprecedented move. Every employee was granted a car, and an employee can choose one of four different car makes. The parking lot before the office consists of one line of (2n - 2) parking spaces. Unfortunately the total number of cars...
3
n = int(input()) N = 2*n-2 ans = 0; for i in range(n): l_cnt = i r_cnt = N - i - n if r_cnt < 0: break m = 4 p = int(l_cnt > 0) + int(r_cnt > 0) m *= 3 ** p l_cnt = max(0, l_cnt - 1) r_cnt = max(0, r_cnt - 1) p = l_cnt + r_cnt; m *= 4 ** p; ans += m print(ans)
There is a knight - the chess piece - at the origin (0, 0) of a two-dimensional grid. When the knight is at the square (i, j), it can be moved to either (i+1,j+2) or (i+2, j+1). In how many ways can the knight reach the square (X, Y)? Find the number of ways modulo 10^9 + 7. Constraints * 1 \leq X \leq 10^6 * 1 \l...
3
inp=list(map(int,input().split())) x=inp[0] y=inp[1] if (x+y)%3!=0: print (0) else: flag=0 z=(x+y)//3 n=x-z m=y-z if m<0 or n<0: print (0) flag=1 else: arr=[1] v=pow(10,9)+7 for i in range(1,m+n+1): arr.append((arr[-1]*i)%v) a=arr[m+n] b=(arr[m]*arr[n])%v print ((a*po...
For strings s and t, we will say that s and t are prefix-free when neither is a prefix of the other. Let L be a positive integer. A set of strings S is a good string set when the following conditions hold true: * Each string in S has a length between 1 and L (inclusive) and consists of the characters `0` and `1`. * A...
3
import sys readline = sys.stdin.readline class Node: def __init__(self, sigma, depth): self.end = False self.child = [None] * sigma self.depth = depth def __setitem__(self, i, x): self.child[i] = x def __getitem__(self, i): return self.child[i] class Trie(): def...
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 vi. 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...
3
n = int(input()) ar = list(map(int, input().split())) q = int(input()) sr = sorted(ar) ps1 = [0] * (n + 1) ps2 = [0] * (n + 1) for i in range(1, n + 1): ps1[i] = ps1[i - 1] + ar[i - 1] ps2[i] = ps2[i - 1] + sr[i - 1] for i in range(q): t, l, r = map(int, input().split()) if t == 1: print(ps1[r]...
Someone gave Alyona an array containing n positive integers a1, a2, ..., an. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not ...
3
x=int(input()) l=list(map(int, input().split(' '))) l.sort() a=1 for i in l: if i>=a: a+=1 print(a)
A teacher decides to give toffees to his students. He asks n students to stand in a queue. Since the teacher is very partial, he follows the following rule to distribute toffees. He looks at the first two students and gives more toffees to the student having higher marks than the other one. If they have the same marks...
1
n = input() s = raw_input() a = [1]*n for j in xrange(n): for i in xrange(n-1): if s[i]=='L': if a[i]<=a[i+1]: a[i]=a[i+1]+1 elif s[i]=='R': if a[i]>=a[i+1]: a[i+1]=a[i]+1 elif s[i]=='=' and a[i]!=a[i+1]:...
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a. Namely, it takes several iterations to calculate value v. At the first iteration, Xeni...
3
# template begins ##################################### from io import BytesIO, IOBase import sys import math import os import heapq from collections import defaultdict, deque from math import ceil from bisect import bisect_left, bisect_left from time import perf_counter # region fastio BUFSIZE = 8192 class FastIO...
Noora is a student of one famous high school. It's her final year in school — she is going to study in university next year. However, she has to get an «A» graduation certificate in order to apply to a prestigious one. In school, where Noora is studying, teachers are putting down marks to the online class register, wh...
1
a = [int(i) for i in str(raw_input()).split(" ")] b = [int(i) for i in str(raw_input()).split(" ")] sum = 0 for num in b: sum += num if ((2*a[1]-1)*a[0] - 2*sum)>=0: print(((2*a[1]-1)*a[0] - 2*sum)) else: print(0)
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...
1
s = raw_input() count = [0]*5 tags = ["h","e","l","l","o"] idx=0 for i in s: if i==tags[idx]: count[idx]+=1 idx+=1 if idx==5: break if list(set(count))[0]==1: print "YES" else: print "NO"
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
s = input() if (s.find("1111111") >= 0) or (s.find("0000000") >= 0): print("YES") else: print("NO")
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...
3
s=input() t=input() n=len(s) ans='' for i in range(n): ans+=str(int(s[i])^int(t[i])) print(ans)
You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the integers from 1 through N. You would like to sort this sequence in ascending order by repeating the following operation: * Choose an element in the sequence and move it to the beginning or the end of the sequence. Find the minimum number of op...
3
#!usr/bin/env python3 n = int(input()) p = [int(input()) for i in range(n)] f = [0]*(n+1) m = [n-1]*(n+1) for i in p: if f[i-1]: m[i] = m[i-1]-1 f[i] = 1 print(min(m))
On a random day, Neko found n treasure chests and m keys. The i-th chest has an integer a_i written on it and the j-th key has an integer b_j on it. Neko knows those chests contain the powerful mysterious green Grapes, thus Neko wants to open as many treasure chests as possible. The j-th key can be used to unlock the ...
3
n,m = map(int,input().split()) A =list(map(int, input().split(' ')[:n])) B =list(map(int, input().split(' ')[:m])) Aev = Bev = 0 for i in A: if(i%2==0): Aev+=1 for i in B: if(i%2==0): Bev+=1 print(min(Aev,abs(Bev-m))+min(abs(Aev-n),Bev))
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation. The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe...
3
a=input() l=list(a) one=0 two=0 three=0 s=[] for i in range(0,len(l),2): if(l[i]=='1'): one+=1 elif(l[i]=='2'): two+=1 elif(l[i]=='3'): three+=1 for p in range(one): s.append('1') if(two!=0 or three!=0): s.append('+') else: if(p<one-1): s.appen...
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
[m,n]=list(map(int,input().split())) print((m*n)//2)
Tokitsukaze is one of the characters in the game "Kantai Collection". In this game, every character has a common attribute — health points, shortened to HP. In general, different values of HP are grouped into 4 categories: * Category A if HP is in the form of (4 n + 1), that is, when divided by 4, the remainder is ...
3
n=int(input()) if n%4==1: print("0 A") elif n%4==0: print("1 A") elif n%4==2: print("1 B") else: print("2 A")
PolandBall is playing a game with EnemyBall. The rules are simple. Players have to say words in turns. You cannot say a word which was already said. PolandBall starts. The Ball which can't say a new word loses. You're given two lists of words familiar to PolandBall and EnemyBall. Can you determine who wins the game, i...
1
n, m = map(int, raw_input().split()) poland = set() enemy = set() commons = set() for i in xrange(n): poland.add(raw_input()) for j in xrange(m): s = raw_input() enemy.add(s) if s in poland: commons.add(s) poland_extra = len(commons) % 2 print 'YES' if n + poland_extra - m > 0 else 'NO'
In AtCoder, a person who has participated in a contest receives a color, which corresponds to the person's rating as follows: * Rating 1-399 : gray * Rating 400-799 : brown * Rating 800-1199 : green * Rating 1200-1599 : cyan * Rating 1600-1999 : blue * Rating 2000-2399 : yellow * Rating 2400-2799 : orange * Rating 280...
3
n = int(input()) A = [int(i) for i in input().split()] B = set() crown = 0 for a in A: if a // 400 >= 8: crown += 1 else: B.add(a // 400) print(max(1, len(B)), len(B) + crown)
Eugeny has array a = a1, a2, ..., an, consisting of n integers. Each integer ai equals to -1, or to 1. Also, he has m queries: * Query number i is given as a pair of integers li, ri (1 ≤ li ≤ ri ≤ n). * The response to the query will be integer 1, if the elements of array a can be rearranged so as the sum ali + a...
1
def main(): line = raw_input().split() n = int(line[0]) m = int(line[1]) a = map(int,raw_input().split()) pos = 0 neg = 0 for i in xrange(len(a)): if a[i] > 0: pos += 1 else: neg += 1 while m > 0: tmp = raw_input().split() #print ...
"Night gathers, and now my watch begins. It shall not end until my death. I shall take no wife, hold no lands, father no children. I shall wear no crowns and win no glory. I shall live and die at my post. I am the sword in the darkness. I am the watcher on the walls. I am the shield that guards the realms of men. I ple...
1
'''input 3 1 2 5 ''' input1 = int(raw_input().strip()) input2 = map(int, raw_input().split()) input2.sort() count = 0 for num in input2: if num > input2[0] and num < input2[len(input2) - 1]: # print input2[len(input2) - 1] count += 1 print count output = count
Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock. <image> The combination lock is represented by n rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has t...
3
if __name__ == '__main__': input() l = [] for tmp in input().strip('\n\r\t '): l.append(int(tmp)) c = 0 for i, tmp in enumerate(input().strip('\n\r\t ')): ss = int(tmp) c += min(abs(ss - l[i]), min(ss, l[i]) + 10 - max(ss, l[i])) print(c)
You are given three integers x, y and n. Your task is to find the maximum integer k such that 0 ≤ k ≤ n that k mod x = y, where mod is modulo operation. Many programming languages use percent operator % to implement it. In other words, with given x, y and n you need to find the maximum possible integer from 0 to n tha...
3
#code t=int(input()) for i in range(t): x,y,n=[int(x) for x in input().split()] p=(n-y)//x print(p*x+y)
Internet search engines, such as Google, automatically sort and categorize web pages around the world to create a huge database. It also parses the search keywords entered by the user and creates an inquiry statement for database search. In each case, complicated processing is performed to realize efficient search, bu...
3
import re print(*[x for x in re.split(r'\s|"|,|\.',input())if 2<len(x)<7])
Snuke lives on an infinite two-dimensional plane. He is going on an N-day trip. At the beginning of Day 1, he is at home. His plan is described in a string S of length N. On Day i(1 ≦ i ≦ N), he will travel a positive distance in the following direction: * North if the i-th letter of S is `N` * West if the i-th letter...
1
a = raw_input() n, w, s, e = -1, -1, -1, -1 for i in a: if i == "S": s = 1 if i == "W": w = 1 if i == "E": e = 1 if i == "N": n = 1 if w * e > 0 and n * s > 0: print "Yes" else: print "No"
Iahub got bored, so he invented a game to be played on paper. He writes n integers a1, a2, ..., an. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices i and j (1 ≤ i ≤ j ≤ n) and flips all values ak for which their positions are in range [i, j] (that is i ≤ k ≤ j)...
3
n=int(input()) binary=list(map(int,input().split())) single1=binary.count(1) if single1==len(binary): print(single1-1) else : s=[] for i in binary: if i==1: s.append(-1) else: s.append(1) sum1=0 sum2=-2000 for i in s: sum1+=i if sum1<0: ...
Alice guesses the strings that Bob made for her. At first, Bob came up with the secret string a consisting of lowercase English letters. The string a has a length of 2 or more characters. Then, from string a he builds a new string b and offers Alice the string b so that she can guess the string a. Bob builds b from a...
3
for _ in range(int(input())): s = input() print(s[0], end = '') for i in range(1, len(s), 2): print(s[i], end = '') print()
Snuke has a calculator. It has a display and two buttons. Initially, the display shows an integer x. Snuke wants to change this value into another integer y, by pressing the following two buttons some number of times in arbitrary order: * Button A: When pressed, the value on the display is incremented by 1. * Button ...
3
x,y = map(int,input().split()) ans = 0 if x*y < 0: ans += 1 elif (x>0 and y==0) or (x==0 and y<0): ans += 1 elif y < x: ans += 2 ans += abs(abs(x)-abs(y)) print(ans)
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 ...
1
draf=raw_input().split() n = int(draf[0]) a = int(draf[1]) b = int(draf[2]) m = n - a if m > b+1: m = b+1 print m
You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'. You ...
3
s = input().split(';') l = [] for i in s: l+=i.split(',') a = '' b = '' int for word in l: flag = True for sym in word: if not sym in ['0','1','2','3','4','5','6','7','8','9']: flag = False break if len(word) > 1 and word[0] == '0': flag = False if flag and...
You are given a sequence a_1, a_2, ..., a_n consisting of n non-zero integers (i.e. a_i ≠ 0). You have to calculate two following values: 1. the number of pairs of indices (l, r) (l ≤ r) such that a_l ⋅ a_{l + 1} ... a_{r - 1} ⋅ a_r is negative; 2. the number of pairs of indices (l, r) (l ≤ r) such that a_l ⋅ a...
1
n = input() x, y = 1, 0 for i in map(int, raw_input().split()): if i < 0: x, y = y, x x += 1 print x * y, n * (n + 1) / 2 - x * y
This is the easy version of the problem. The difference between the versions is in the number of possible operations that can be made. You can make hacks if and only if you solved both versions of the problem. You are given a binary table of size n × m. This table consists of symbols 0 and 1. You can make such operat...
3
num_test = int(input()) def solve(): n, m = map(int, input().split()) bList = [[0] * (m+1)] for i in range(n): bList.append( [0] + list(input()) ) ansNum = 0 ansList = [] for i in range(1, n+1): for j in range(1, m+1): if bList[i][j] == '0': continue ...
Nauuo is a girl who loves playing chess. One day she invented a game by herself which needs n chess pieces to play on a m× m chessboard. The rows and columns are numbered from 1 to m. We denote a cell on the intersection of the r-th row and c-th column as (r,c). The game's goal is to place n chess pieces numbered fro...
3
import sys input = sys.stdin.readline n = int(input()) ans = int(n/2) + 1 print(ans) i, j = 1, 1 m = n while m > 0: print(i, j) if i == ans: j += 1 else: i += 1 m -= 1
Today, Osama gave Fadi an integer X, and Fadi was wondering about the minimum possible value of max(a, b) such that LCM(a, b) equals X. Both a and b should be positive integers. LCM(a, b) is the smallest positive integer that is divisible by both a and b. For example, LCM(6, 8) = 24, LCM(4, 12) = 12, LCM(2, 3) = 6. O...
1
import math m={} # A function to print all prime factors of # a given number n def primeFactors(n): # Print the number of two's that divide n while n % 2 == 0: if 2 not in m: m[2]=1 else: m[2]+=1 n = n / 2 # n must be odd at t...
You are given an array a_1, a_2, ... , a_n, which is sorted in non-decreasing order (a_i ≤ a_{i + 1}). Find three indices i, j, k such that 1 ≤ i < j < k ≤ n and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to a_i, a_j and a_k (for example it is possible to...
3
# [int(s) for s in input().split()] # int(input()) # input() T = int(input()) for t in range(1,T+1): N = int(input()) A = [int(s) for s in input().split()] if A[0] + A[1] <= A[-1]: print(1,2,N) else: print(-1)
Vasya used to be an accountant before the war began and he is one of the few who knows how to operate a computer, so he was assigned as the programmer. We all know that programs often store sets of integers. For example, if we have a problem about a weighted directed graph, its edge can be represented by three integer...
3
import sys sys.stdin.readline() ans='' stk=[1] for word in sys.stdin.readline().strip().split(' '): if not stk: stk=1 break stk[-1]-=1 ans+=','+word if word[0]=='p': stk.append(2) ans+='<' while stk and stk[-1]==0: stk.pop() ans+='>' if stk: print('Error occurred') else: print(ans....
In recent years John has very successfully settled at his new job at the office. But John doesn't like to idly sit around while his code is compiling, so he immediately found himself an interesting distraction. The point of his distraction was to maintain a water level in the water cooler used by other zebras. <image>...
3
def solve(k, l, r, t, x, y): k -= l r -= l if r >= x+y-1: if y < x: if k+y > r: k -= x return t-1 <= int(k//(x-y)) return t <= int(k//(x-y)) return True if y < x: if k+y > r: if k-x < 0: retu...
A binary string is a string where each character is either 0 or 1. Two binary strings a and b of equal length are similar, if they have the same character in some position (there exists an integer i such that a_i = b_i). For example: * 10010 and 01111 are similar (they have the same character in position 4); * 10...
3
for _ in range(int(input())): n = int(input()) s = list(input()) c = s[n - 1] for i in range(n): print(c, end = '') print()
«One dragon. Two dragon. Three dragon», — the princess was counting. She had trouble falling asleep, and she got bored of counting lambs when she was nine. However, just counting dragons was boring as well, so she entertained herself at best she could. Tonight she imagined that all dragons were here to steal her, and ...
3
a = [] for _ in range(4): a.append(int(input())) d = int(input()) kil = 0 for i in range(1, d+1): for j in range(4): if i % a[j] == 0: kil+=1 break print(kil)
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 Bi...
3
w=int(input()) par=w%2 if par== 0 and w>2 : print("YES") else: print("NO")
Dawid has four bags of candies. The i-th of them contains a_i candies. Also, Dawid has two friends. He wants to give each bag to one of his two friends. Is it possible to distribute the bags in such a way that each friend receives the same amount of candies in total? Note, that you can't keep bags for yourself or thro...
3
A = list(map(int,input().split())) def check(a): a.sort() s = sum(a) if a[0] + a[3] == a[2] + a [1]: return "YES" for i in range(len(a)): if a[i] == s - a[i]: return 'YES' return "NO" print(check(A))
Recall that string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly zero or all) characters. For example, for the string a="wowwo", the following strings are subsequences: "wowwo", "wowo", "oo", "wow", "", and others, but the following are not subsequences: "owoo", "owwwo", ...
3
s = input() n = len(s) w = n*[0] ow = n*[0] wow = n*[0] w[n-1] = 0 for i in range(n-2, -1, -1): w[i] = w[i+1] if s[i] == 'v' and s[i+1] == 'v': w[i] += 1 ow[n-1] = 0; for i in range(n-2, -1, -1): ow[i] = ow[i+1] if s[i] == 'o': ow[i] += w[i] wow[n-1] = 0; for i in range(n-2, -1, ...
Hongcow likes solving puzzles. One day, Hongcow finds two identical puzzle pieces, with the instructions "make a rectangle" next to them. The pieces can be described by an n by m grid of characters, where the character 'X' denotes a part of the puzzle and '.' denotes an empty part of the grid. It is guaranteed that th...
1
from itertools import * n,m = map(int, raw_input().split()) r = [] for _ in xrange(n): r.append(raw_input().strip()) minx = min(i for i,j in product(xrange(n),xrange(m)) if r[i][j] == 'X') maxx = max(i for i,j in product(xrange(n),xrange(m)) if r[i][j] == 'X') miny = min(j for i,j in product(xrange(n),xrange(m)) if ...
There is a beautiful garden of stones in Innopolis. Its most beautiful place is the n piles with stones numbered from 1 to n. EJOI participants have visited this place twice. When they first visited it, the number of stones in piles was x_1, x_2, …, x_n, correspondingly. One of the participants wrote down this sequ...
3
# import sys # sys.stdin=open("input.in","r") n=int(input()) a=list(map(int,input().split())) b=list(map(int,input().split())) l=[] for i in range(n): c=b[i]-a[i] l.append(c) if sum(l)<=0: print("YES") else: print("NO")
Vadim loves decorating the Christmas tree, so he got a beautiful garland as a present. It consists of n light bulbs in a single row. Each bulb has a number from 1 to n (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland....
3
n=int(input()) s=list(map(int,input().split())) dp=[[[float("INF"),float("INF")]for i in range(n//2+1)]for i in range(n+1)] dp[0][0]=[0,0] for i in range(1,n+1): if s[i-1]==0: for j in range(1,n//2+1): dp[i][j][0]=min(dp[i-1][j-1][0],dp[i-1][j-1][1]+1) for j in range(n//2+1): ...
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 ...
3
n = int(input()) x = list(map(int, input().split())) y = list(map(int, input().split())) x.pop(0) y.pop(0) myset = set(x + y) if n == len(myset): print("I become the guy.") else: print("Oh, my keyboard!")
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...
3
s = input() if s.find('h') == -1: print('NO') elif s.find('e', s.find('h')) == -1: print('NO') else: b = s.find('e', s.find('h')) if s.find('l', b) == -1: print('NO') else: c = s.find('l', b) + 1 if s.find('l', c) == -1: print('NO') else: d = ...
You are given two integers n and m (m < n). Consider a convex regular polygon of n vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length). <image> Examples of convex regular polygons Your task is to say if it is poss...
3
# -*- coding: utf-8 -*- """ Created on Thu Oct 1 23:47:08 2020 @author: SAIGANESH """ t=int(input()) for _ in range(t): n,m=input().split() if(int(n)<3): print("NO") else: if(int(n)%int(m)==0): print("YES") else: print("NO")
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 ai cubes. At first, the gravity in the box is pulling...
3
#using selection sort instead of gravity sort def minim(arr,starts,end): minim = starts for i in range(starts,end): if arr[i]<arr[minim]: minim=i return minim; def selection_sort(arra): for i in range(0,len(arra)): min_index = minim(arra,i,len(arra)) temp = arra[i] arra[i]=arra[min_index] arra[min_ind...
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob. Right now, Limak and Bob weigh a and b respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight. Limak eats a lot and his weight is tripled after every year, while Bob's weight...
3
inpu = input().split() a = int(inpu[0]) # limak's weight b = int(inpu[1]) # bob's weight years = 0 while a <= b: a *= 3 b *= 2 years += 1 else: print(years)
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
1
import string n = int(raw_input().rstrip('\n')) i = 0 while i < n: s = raw_input().rstrip('\n') if len(s) <= 10: print s else: print s[0] + str(len(s)-2) + s[-1] i+=1
This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved. Pikachu is a cute and friendly pokémon living in the wild pikachu herd. But it has become known recently that infamous team R...
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(...
One day the Codeforces round author sat exams. He had n exams and he needed to get an integer from 2 to 5 for each exam. He will have to re-sit each failed exam, i.e. the exam that gets mark 2. The author would need to spend too much time and effort to make the sum of his marks strictly more than k. That could have s...
3
n,k=map(int,input().split()) if 3*n<k: print("0") else: print(3*n-k)
Vanya is doing his maths homework. He has an expression of form <image>, where x1, x2, ..., xn are digits from 1 to 9, and sign <image> represents either a plus '+' or the multiplication sign '*'. Vanya needs to add one pair of brackets in this expression so that to maximize the value of the resulting expression. Inpu...
1
def main(): s = raw_input() t = [] t.append(-1) for i, p in enumerate(s): if p == '*': t.append(i) t.append(len(s)) res = eval(s) for i in xrange(len(t)): for j in xrange(i + 1, len(t)): x, y = t[i], t[j] ns = s[:x + 1] + '(' + s[x + 1:y] +...
Fast Forwarding Mr. Anderson frequently rents video tapes of his favorite classic films. Watching the films so many times, he has learned the precise start times of his favorite scenes in all such films. He now wants to find how to wind the tape to watch his favorite scene as quickly as possible on his video player. ...
3
#!/usr/bin/env python3 t = int(input()) count = 0 speed = 1 margin = 0 while t > 0: t -= speed count += 1 if margin + speed * 3 <= t: speed *= 3 margin += speed elif t < margin: margin -= speed speed /= 3 print(count)
Limak and Radewoosh are going to compete against each other in the upcoming algorithmic contest. They are equally skilled but they won't solve problems in the same order. There will be n problems. The i-th problem has initial score pi and it takes exactly ti minutes to solve it. Problems are sorted by difficulty — it'...
3
n, c = map(int, input().split()) p = list(map(int, input().split())) t = list(map(int, input().split())) p_l, p_t = 0,0 for i in range(n): p_l += max(0, p[i] - c * sum(t[:i+1])) p_t += max(0, p[n - i - 1] - c * sum(t[n-i-1:])) if p_l > p_t: print('Limak') elif p_l == p_t: print('Tie') else: print('...
Wabbit is trying to move a box containing food for the rest of the zoo in the coordinate plane from the point (x_1,y_1) to the point (x_2,y_2). He has a rope, which he can use to pull the box. He can only pull the box if he stands exactly 1 unit away from the box in the direction of one of two coordinate axes. He will...
3
#--------- nhập t ---------# for i in range(int(input())): #------ nhập toa độ x1, y2, x2, y2 ------# x1, y1, x2, y2 = map(int, input().split()) # tạo biến answer # ans = 0 # nếu đường cần kéo là đường thẳng # if x1 == x2: ans = abs(y1 - y2) elif y1 == y2: ans = abs(x1 - x2) # khi đầu x1, y1 và x2, y2 là đư...
zscoder loves simple strings! A string t is called simple if every pair of adjacent characters are distinct. For example ab, aba, zscoder are simple whereas aa, add are not simple. zscoder is given a string s. He wants to change a minimum number of characters so that the string s becomes simple. Help him with this tas...
3
alf = 'abcdefghijklmnopqrstuvwxyz' st = input() st = ' '.join(st) st = st.split() if len(st) == 1: print(*st) else: for i in range(1, len(st) - 1): if st[i] == st[i - 1]: for j in alf: if j != st[i - 1] and j != st[i + 1]: st[i] = j bre...
Vasiliy spent his vacation in a sanatorium, came back and found that he completely forgot details of his vacation! Every day there was a breakfast, a dinner and a supper in a dining room of the sanatorium (of course, in this order). The only thing that Vasiliy has now is a card from the dining room contaning notes ho...
3
a = [*map(int, input().split())] print(sum([max(0, max(a) - i - 1) for i in a]))
Recently you have received two positive integer numbers x and y. You forgot them, but you remembered a shuffled list containing all divisors of x (including 1 and x) and all divisors of y (including 1 and y). If d is a divisor of both numbers x and y at the same time, there are two occurrences of d in the list. For ex...
3
def divList(n): if (n == 1): return [1] l = [1, n] for i in range(2, n // 2 + 1): if (n % i == 0): l.append(i) return l n = int(input()) l = input().split() l = [int(i) for i in l] if (n == 2): print(l[0], l[1]) exit() l.sort() x = l[len(l) - 1] xDiv = divList(x) for ...
Polycarpus is an amateur businessman. Recently he was surprised to find out that the market for paper scissors is completely free! Without further ado, Polycarpus decided to start producing and selling such scissors. Polycaprus calculated that the optimal celling price for such scissors would be p bourles. However, he...
1
p, d = map(int, raw_input().split()) i = 1 while True: r = i * ((p + 1) / i) - 1 if r >= p - d: ret = r else: break i *= 10 print ret
++++++++[>+>++>+++>++++>+++++>++++++>+++++++>++++++++>+++++++++>++++++++++>+ ++++++++++>++++++++++++>+++++++++++++>++++++++++++++>+++++++++++++++>+++++++ +++++++++<<<<<<<<<<<<<<<<-]>>>>>>>>>>.<<<<<<<<<<>>>>>>>>>>>>>>++.--<<<<<<<<< <<<<<>>>>>>>>>>>>>+.-<<<<<<<<<<<<<>>>>>>>>>>>>>>--.++<<<<<<<<<<<<<...
3
cnt = 0 for i in oct(int(input())): if i == '1': cnt += 1 print(cnt)
Peter Parker wants to play a game with Dr. Octopus. The game is about cycles. Cycle is a sequence of vertices, such that first one is connected with the second, second is connected with third and so on, while the last one is connected with the first one again. Cycle may consist of a single isolated vertex. Initially t...
3
n = int(input().strip()) cycles = map(int, input().strip().split()) n_steps = 0 for c in cycles: n_steps += c - 1 print(int(not(n_steps % 2)) + 1)
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
3
n = int(input().strip()) for _ in range(n): w = str(input().strip()) l = len(w) if l>10: w = w[0]+str(l-2)+w[-1] print(w)
Phoenix has a string s consisting of lowercase Latin letters. He wants to distribute all the letters of his string into k non-empty strings a_1, a_2, ..., a_k such that every letter of s goes to exactly one of the strings a_i. The strings a_i do not need to be substrings of s. Phoenix can distribute letters of s and re...
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...
Polycarp has created his own training plan to prepare for the programming contests. He will train for n days, all days are numbered from 1 to n, beginning from the first. On the i-th day Polycarp will necessarily solve a_i problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first...
3
n=int(input()) l=list(map(int,input().split())) s=sum(l) s=s/2 c=0 for i in range(n): c=c+l[i] if(c>=s): print(i+1) break
Some natural number was written on the board. Its sum of digits was not less than k. But you were distracted a bit, and someone changed this number to n, replacing some digits with others. It's known that the length of the number didn't change. You have to find the minimum number of digits in which these two numbers c...
3
from sys import stdin, stdout k = int(stdin.readline().strip()) N = [int(x) for x in stdin.readline().strip()] current, change, size = 0, 0, len(N) for i in N: current += i if current >= k: stdout.write("0") else: N.sort() for i in range(size): if current < k: if N[i] != 9: ...
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network. Bu...
3
t=input() set1=set() for i in range(len(t)): set1.add(t[i]) if len(set1)%2==0: print("CHAT WITH HER!") else: print("IGNORE HIM!")
Pashmak has fallen in love with an attractive girl called Parmida since one year ago... Today, Pashmak set up a meeting with his partner in a romantic garden. Unfortunately, Pashmak has forgotten where the garden is. But he remembers that the garden looks like a square with sides parallel to the coordinate axes. He al...
3
x1,y1,x2,y2=input().split() x1=int(x1) x2=int(x2) y2=int(y2) y1=int(y1) x3=0 y3=0 x4=0 y4=0 sz=abs(x2-x1) sy=abs(y2-y1) sx=max(sz,sy) if sz==sy: x3=x1 y3=y2 x4=x2 y4=y1 #print("1") print(x3,y3,x4,y4,sep=' ') elif x1==x2: x3=x1+sy y3=y1 x4=x2+sy y4=y2 #print("2") print(x...
Finished her homework, Nastya decided to play computer games. Passing levels one by one, Nastya eventually faced a problem. Her mission is to leave a room, where a lot of monsters live, as quickly as possible. There are n manholes in the room which are situated on one line, but, unfortunately, all the manholes are clo...
3
n,k=map(int,input().split()) ans,pos=0,0 pos=min(k-1,abs(n-k)) print(3*n+pos)
A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k 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? Input The first lin...
3
amount=0 k,n,w=list(int(x) for x in input().split()) for i in range(w+1): amount+=(i*k) if(amount<=n): print(0) else: print(amount-n)
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
3
N = int(input()) for _ in range(N): S = input() if len(S) < 11: print(S) else: print(S[0]+str((len(S)-2))+S[len(S)-1])
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...
1
import sys from collections import deque as dq range = xrange input = raw_input h,w,P = [int(x) for x in input().split()] S = [int(x) for x in input().split()] board = [] for b in sys.stdin.read(): for c in b: if c=='.': board.append(-1) elif c=='#': board.append(-2) ...
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits. Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has on...
3
n=int(input()) for i in range(n+1,9013): a=list(str(i)) b=set(a) if(len(a)==len(b)): print(i) break
Two players decided to play one interesting card game. There is a deck of n cards, with values from 1 to n. The values of cards are pairwise different (this means that no two different cards have equal values). At the beginning of the game, the deck is completely distributed between players such that each player has a...
3
t = int(input()) for _ in range(t): n, a, b = input().split() x = input().split() y = input().split() if n in x: print('YES') else: print('NO')
Zibi is a competitive programming coach. There are n competitors who want to be prepared well. The training contests are quite unusual – there are two people in a team, two problems, and each competitor will code exactly one of them. Of course, people in one team will code different problems. Rules of scoring also are...
3
from sys import stdin from operator import add from itertools import repeat def main(): n, m = map(int, stdin.readline().split()) inp = list(map(int, stdin.read().split(), repeat(10, 2*n+2*m))) xys = inp[:2*n] exc = list(map(add, inp[2*n:], repeat(-1))) a = list(range(n)) a.sort(key=lambda i: ...
You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges. The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i. Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b...
3
n, m = map(int, input().split()) abc = [list(map(int, input().split())) for _ in range(m)] edge = set() INF = float('inf') cost = [[INF]*n for _ in range(n)] for i in range(n): cost[i][i] = 0 for a, b, c in abc: a, b = a-1, b-1 cost[a][b] = c cost[b][a] = c edge.add((a, b, c)) for k in range(n): ...
Pushok the dog has been chasing Imp for a few hours already. <image> Fortunately, Imp knows that Pushok is afraid of a robot vacuum cleaner. While moving, the robot generates a string t consisting of letters 's' and 'h', that produces a lot of noise. We define noise of string t as the number of occurrences of strin...
3
def key(x): s = x.count('s') return s/len(x) def sh_produce(x): x = str(x) sh = [0 for j in range(len(x))] if x[-1] == 'h': sh[-1] = 1 for i in range(len(x)-2, -1, -1): if x[i] == 'h': sh[i] = sh[i+1] + 1 else: sh[i] = sh[i+1] sh_num = 0 ...
This problem is actually a subproblem of problem G from the same contest. There are n candies in a candy box. The type of the i-th candy is a_i (1 ≤ a_i ≤ n). You have to prepare a gift using some of these candies with the following restriction: the numbers of candies of each type presented in a gift should be all di...
3
def make(list): dic={} n=len(list) for i in range(n): if list[i] in dic: dic[list[i]]+=1 else: dic[list[i]]=1 l=[] for i in dic: l.append(dic[i]) l.sort() s=0 prev=n+1 for i in range(len(l)-1,-1,-1): if l[i]<prev: s+...
You are given an integer n. In one move, you can either multiply n by two or divide n by 6 (if it is divisible by 6 without the remainder). Your task is to find the minimum number of moves needed to obtain 1 from n or determine if it's impossible to do that. You have to answer t independent test cases. Input The fi...
3
def solve(n): cnt=0 if n==1: return 0 while True: if n >= 6 and n%6==0: n = n//6 cnt+=1 if n == 1: return cnt elif n == 6: return cnt+1 elif n < 6 : n*=2 cnt+=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
str1 = str(input()).lower() str2 = str(input()).lower() if str1 < str2: print(-1) elif str2 < str1: print(1) elif str1 == str2: print(0)
In the beginning, Takahashi has A cookies, and Aoki has B cookies. They will perform the following operation alternately, starting from Takahashi: * If the number of cookies in his hand is odd, eat one of those cookies; if the number is even, do nothing. Then, give one-half of the cookies in his hand to the other pers...
3
*a,k=map(int,input().split()) for i in range(k): a[1-i%2]+=a[i%2]//2 a[i%2]=(a[i%2]-a[i%2]%2)//2 print(*a)