problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
Given any integer x, Aoki can do the operation below. Operation: Replace x with the absolute difference of x and K. You are given the initial value of an integer N. Find the minimum possible value taken by N after Aoki does the operation zero or more times. Constraints * 0 ≀ N ≀ 10^{18} * 1 ≀ K ≀ 10^{18} * All valu...
3
n,k=map(int,input().split()) n%=k m=k-n print(min(m,n))
Let n be a positive integer. Let a, b, c be nonnegative integers such that a + b + c = n. Alice and Bob are gonna play rock-paper-scissors n times. Alice knows the sequences of hands that Bob will play. However, Alice has to play rock a times, paper b times, and scissors c times. Alice wins if she beats Bob in at lea...
3
from math import * for u in range(int(input())): n=int(input()) a,b,c=map(int,input().split()) s=input() r=['X']*n x,y=0,0 for i in range(n): if(s[i]=='P' and c): c=c-1 r[i]='S' x=x+1 elif(s[i]=='R' and b): b=b-1 r[i]='P...
Ann has recently started commuting by subway. We know that a one ride subway ticket costs a rubles. Besides, Ann found out that she can buy a special ticket for m rides (she can buy it several times). It costs b rubles. Ann did the math; she will need to use subway n times. Help Ann, tell her what is the minimum sum of...
3
# cost efficiency of buying special tickets up to the point where you have to choose normal or reg [n,m,a,b] = [int(x) for x in input().split()] cost = 0 if b/m < a: cost += b*(n//m) n -= m*(n//m) else: cost += a*n n -= n # need to figure out if buying a special to cover the rest of regular is cheaper now if b...
Takahashi has N balls with positive integers written on them. The integer written on the i-th ball is A_i. He would like to form some number of pairs such that the sum of the integers written on each pair of balls is a power of 2. Note that a ball cannot belong to multiple pairs. Find the maximum possible number of pai...
3
from collections import defaultdict n = int(input()) A = list(int(x) for x in input().split()) count = defaultdict(int) for a in A: count[a] += 1 A = sorted(set(A)) ans = 0 for a in reversed(A): t = a.bit_length() pair = 2**t - a if pair == a: ans += count[a] // 2 count[a] -= count[a]...
You are given a special jigsaw puzzle consisting of nβ‹… m identical pieces. Every piece has three tabs and one blank, as pictured below. <image> The jigsaw puzzle is considered solved if the following conditions hold: 1. The pieces are arranged into a grid with n rows and m columns. 2. For any two pieces that sh...
3
# Contest No.: 639 # Problem No.: A # Solver: JEMINI # Date: 20200503 import sys def main(): t = int(input()) for _ in range(t): n, m = map(int, sys.stdin.readline().split()) if min(n, m) == 1 or (n == 2 and m == 2): print("YES") else: print("NO") ...
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word. Note, that during capitalization all the letters except the first one remains unchanged. Input A single line contains a non-empty word. This word consists of lowercase and uppercase English letters....
3
word=input() c=word[0].upper() s=word[:0]+c+word[1:] print(s)
Mahmoud and Ehab play a game called the even-odd game. Ehab chooses his favorite integer n and then they take turns, starting from Mahmoud. In each player's turn, he has to choose an integer a and subtract it from n such that: * 1 ≀ a ≀ n. * If it's Mahmoud's turn, a has to be even, but if it's Ehab's turn, a has...
1
n = input() print 'Mahmoud' if n % 2 == 0 else 'Ehab'
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it. <image> There are n cities and n-1 two-way roads connecting pairs of cities in the ki...
3
n,m = map(int,input().split()) a = [[] for i in range(n)] for i in range(n-1): x,y = map(int,input().split()) a[x-1].append(y-1) a[y-1].append(x-1) ht = [-1 for i in range(n)] par = [-1 for i in range(n)] h = 0 stack = [0] order = [] while stack: node = stack.pop() order.append(node) if ht[node]==-1: ht[node]...
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
c=[100,20,10,5,1] n=int(input()) k=0 i=0 while(n>0): x=n//c[i] k=k+x n=n-(x*c[i]) i=i+1 print(k)
A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all n squad soldiers to line up on the parade ground. By the military charter the soldiers should stand in the order of non-increasing of their h...
3
nStr = input() n = int(nStr) heightStr = input() heightLs = heightStr.split() heights = [0]*n for i in range(n): heights[i] = int(heightLs[i]) hMin = 100 hMinPos = 0 hMax = 0 hMaxPos = 0 for i in range(n): if heights[i]>hMax: hMax = heights[i] hMaxPos = i if heights[i]<=hMin: hMin = heights[i] hMinPos ...
Anton has the integer x. He is interested what positive integer, which doesn't exceed x, has the maximum sum of digits. Your task is to help Anton and to find the integer that interests him. If there are several such integers, determine the biggest of them. Input The first line contains the positive integer x (1 ≀ ...
3
x = input() a = list(map(int, list(x))) n = len(a) if (sum(a[1:]) == (n - 1) * 9) or (sum(a[1:]) == (n - 1) * 9 - 1): print(x) elif a[1] == 9: for i in range(1, n): if a[i] == 9 and a[i+1] != 9: print(x[:i] + '8' + (n-1-i) * '9') break else: if a[0] == 1: print((n-1) ...
Duff is in love with lovely numbers! A positive integer x is called lovely if and only if there is no such positive integer a > 1 such that a2 is a divisor of x. <image> Malek has a number store! In his store, he has only divisors of positive integer n (and he has all of them). As a birthday present, Malek wants to g...
1
import math def findLargestDivisor( n): for i in range (2, int(math.sqrt(n)) + 1) : while (n % (i * i) == 0) : n = n // i return n n = int(raw_input()) print findLargestDivisor(n)
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution....
3
def solve(n, list): count = 0 for i in range(0, n): a = list[i][0] b = list[i][1] c = list[i][2] if (a == b and a == "1") or (a == c and a == "1") or (b == c and b == "1"): count += 1 continue return count n = int(input()) list = [] for i in range(0, n): b = input() list.append((b...
There are n boxers, the weight of the i-th boxer is a_i. Each of them can change the weight by no more than 1 before the competition (the weight cannot become equal to zero, that is, it must remain positive). Weight is always an integer number. It is necessary to choose the largest boxing team in terms of the number o...
3
n=int(input()) arr=list(map(int,input().split(" "))) arr.sort() arr[n-1]+=1 #print(arr) for i in range(n-2,-1,-1): if(arr[i+1]-arr[i]==1): continue if(arr[i+1]-arr[i]>1): arr[i]+=1 elif(i>0 and arr[i-1]!=arr[i]): if(arr[i]!=1): arr[i]-=1 elif(arr[i]>1 and i==0): arr[i]-=1 ans=n #print(arr) for i in range...
You are given an undirected graph consisting of n vertices and <image> edges. Instead of giving you the edges that exist in the graph, we give you m unordered pairs (x, y) such that there is no edge between x and y, and if some pair of vertices is not listed in the input, then there is an edge between these vertices. ...
3
n,m=map(int,input().split()) non=[{i} for i in range(n)] for i in range(m): u,v=map(int,input().split()) u,v=u-1,v-1 non[u].add(v) non[v].add(u) vertex=set(range(n)) ans=[] while(vertex): a=next(iter(vertex)) vertex.remove(a) stk=[a] cou=1 while(stk): v=stk.pop() s=ve...
The goal of 8 Queens Problem is to put eight queens on a chess-board such that none of them threatens any of others. A queen threatens the squares in the same row, in the same column, or on the same diagonals as shown in the following figure. <image> For a given chess board where $k$ queens are already placed, find ...
3
import sys input = lambda: sys.stdin.readline().rstrip() def resolve(): k = int(input()) rc = [list(map(int, input().split())) for _ in range(k)] def dfs(d, perm): if d==8: ok = True for i in rc: if perm[i[0]]!=i[1]: ok = False ...
You are given two strings a and b consisting of lowercase English letters, both of length n. The characters of both strings have indices from 1 to n, inclusive. You are allowed to do the following changes: * Choose any index i (1 ≀ i ≀ n) and swap characters a_i and b_i; * Choose any index i (1 ≀ i ≀ n) and sw...
3
n = int(input()) string1 = input() string2 = input() attempts = 0 #handles even and odd except middle odd, do it separately for i in range(n//2): elements = [string1[i],string2[i],string1[-1*(i+1)],string2[-1*(i+1)]] counter = {} for j in elements: if j not in counter: counter[j] = 1 ...
There are three friend living on the straight line Ox in Lineland. The first friend lives at the point x1, the second friend lives at the point x2, and the third friend lives at the point x3. They plan to celebrate the New Year together, so they need to meet at one point. What is the minimum total distance they have to...
3
a,b,c=map(int,input().split()) distance=100 for i in range(1,101): distance=min(distance,abs(i-a)+abs(i-b)+abs(i-c)) print(distance)
We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer t Π’-prime, if t has exactly three distinct positive divisors. You are given an array of n positive integers. For each of them determine whether it is Π’-prime or not. Input The f...
3
#230B-T-primes n=int(input()) list1=[int(x) for x in input().split(' ')] def prime(x): if x == 1: return False else: z=0 if (x**0.5) != int(x**0.5): return False else: y=int(x**0.5) for i in range(2,int(y**0.5)+1): if (y % i) =...
Along a road running in an east-west direction, there are A shrines and B temples. The i-th shrine from the west is located at a distance of s_i meters from the west end of the road, and the i-th temple from the west is located at a distance of t_i meters from the west end of the road. Answer the following Q queries: ...
3
a,b,q=map(int,input().split()) s=[int(input()) for _ in range(a)] t=[int(input()) for _ in range(b)] import bisect for _ in range(q): x=int(input()) sb=bisect.bisect_left(s,x) tb=bisect.bisect_left(t,x) ss=[x-s[max(sb-1,0)],x-s[min(sb,a-1)]] tt=[x-t[max(tb-1,0)],x-t[min(tb,b-1)]] l=[] for i ...
Write a program of the Bubble Sort algorithm which sorts a sequence A in ascending order. The algorithm should be based on the following pseudocode: BubbleSort(A) 1 for i = 0 to A.length-1 2 for j = A.length-1 downto i+1 3 if A[j] < A[j-1] 4 swap A[j] and A[j-1] Note that, indices for array ...
3
n = int(input()) a = list(map(int,input().split())) flag = 1 cnt = 0 while flag: flag = 0 for i in range(len(a)): if i > 0 and a[i] < a[i-1]: a[i],a[i-1] = a[i-1],a[i] flag = 1 cnt += 1 print(" ".join((str(i) for i in a))) print(cnt)
Xenny was a teacher and his class consisted of N boys and N girls. He took all his students to the playground and asked them to stand in a straight line. The boys and the girls formed a perfect line, but Xenny seemed unhappy. He wanted them to form an alternating sequence of boys and girls, i.e., he wanted that after a...
1
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' #print 'Hello World!' t=input() while(t): n=input() s=raw_input() l=len(s) lst1=list() lst2=list() ans=0 c1=0 c2=0 for x in xrange(0,l,2): if(s[x]==s[x+1]): lst1.append(s[...
Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus. She has n friends who are also grannies (Maria is not included in this number). The i-th granny is ready to attend the ceremony, provided that at the time of her appearance in t...
3
def rs(): return input().strip() def ri(): return int(input()) def ria(): return list(map(int, input().split())) def ia_to_s(a): return ' '.join([str(s) for s in a]) def solve(n, a): a = sorted(a) i = n-1 while i >= 0 and a[i] > i+1: i -= 1 return i + 2 def main(): for _ in range(ri()): ...
There are N people standing in a row from west to east. Each person is facing east or west. The directions of the people is given as a string S of length N. The i-th person from the west is facing east if S_i = `E`, and west if S_i = `W`. You will appoint one of the N people as the leader, then command the rest of the...
3
from collections import Counter n=int(input()) s=['n']+list(input()) ans=10**6 c=Counter(s) le,lw=0,0 for i in s: if i=='E': le+=1 elif i=='W': lw+=1 ans=min(ans,lw+c['E']-le) print(ans)
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
a=int(input()) l=[] l=list(input()) sum1=0;sum2=0;sum3=0;sum4=0;summ=0 n=0 while n<a-1: num1=l[n] num2=l[n+1] if num1==num2: summ+=1 n+=1 print(summ)
You are given a string A. Find a string B, where B is a palindrome and A is a subsequence of B. A subsequence of a string is a string that can be derived from it by deleting some (not necessarily consecutive) characters without changing the order of the remaining characters. For example, "cotst" is a subsequence of "c...
3
A=input() b=list() def rev(A): return A[::-1] C = rev(A) for e in range(0, len(A)): b.append(A[e]) if A == C: print(A) else: for i in range(1, len(C)): b.append(C[i]) strb = ''.join(str(x) for x in b) print(strb)
"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
n=int(input()) x=list(map(int, input().split())) c=0 for i in range(n): if i+1 not in x: c+=1 print(c)
We just discovered a new data structure in our research group: a suffix three! It's very useful for natural language processing. Given three languages and three suffixes, a suffix three can determine which language a sentence is written in. It's super simple, 100% accurate, and doesn't involve advanced machine learni...
3
n=int(input()) for j in range(n): s=input() l=len(s)+1 if s[l-3:l-1]=='po': print('FILIPINO') elif s[l-5:l-1]=='desu' or s[l-5:l-1]=='masu': print('JAPANESE') elif s[l-6:l-1]=='mnida': print('KOREAN') else: print(s[l-3:l-1])
Bran and his older sister Arya are from the same house. Bran like candies so much, so Arya is going to give him some Candies. At first, Arya and Bran have 0 Candies. There are n days, at the i-th day, Arya finds ai candies in a box, that is given by the Many-Faced God. Every day she can give Bran at most 8 of her cand...
3
n, k = map(int, input().split()) cnt, day = 0, 0 a = list(map(int, input().split())) while k > 0: try: cnt += a[day] except IndexError: print(-1) exit(0) x = min(8, cnt) cnt -= x k -= x day += 1 print(day)
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word. Note, that during capitalization all the letters except the first one remains unchanged. Input A single line contains a non-empty word. This word consists of lowercase and uppercase English letters....
3
t1=input() t1=t1[0].upper()+t1[1:] print(t1)
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()) for _ in range(t): n, k = map(int, input().split()) if n % 2 == 1 and k % 2 == 0: print('NO') elif n % 2 == 0 and k % 2 == 1: if 2 * k > n: print('NO') else: print('YES') for _ in range(k - 1): print(2, end=' ') print(n - (k - 1) * 2, end=' ') else: ...
Berland shop sells n kinds of juices. Each juice has its price c_i. Each juice includes some set of vitamins in it. There are three types of vitamins: vitamin "A", vitamin "B" and vitamin "C". Each juice can contain one, two or all three types of vitamins in it. Petya knows that he needs all three types of vitamins to...
3
n = int(input()) d = {'A':100001, 'B':100001, 'C':100001, 'AB':100001, 'BC':100001, 'AC':100001, 'ABC':100001} for _ in range(n): c, s = input().split() c = int(c) temp = "".join(sorted(s)) if c<d[temp]: d[temp] = c for item in d: if d[item]==100001: d[item] = 300001 ans = min(d['A']+d['B']+d['C'], d['ABC'],...
You are given a board of size n Γ— n, where n is odd (not divisible by 2). Initially, each cell of the board contains one figure. In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell (i, j) you can move...
3
for f in range(int(input())): n=int(input()) m=n//2 prev=1 cur=3 mov=0 for i in range(m): mov+=(i+1)*(cur**2-prev**2) prev+=2 cur+=2 print(mov)
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...
1
from __future__ import division, print_function N = 100005 ans = [0 for _ in range(N)] def sieve(): cnt = 1 for i in range(2, N, 2): ans[i] = cnt for i in range(3, N, 2): if ans[i] == 0: cnt += 1 ans[i] = cnt; for j in range(i + i, N, i): ...
Polycarp lives on the coordinate axis Ox and travels from the point x=a to x=b. It moves uniformly rectilinearly at a speed of one unit of distance per minute. On the axis Ox at the point x=c the base station of the mobile operator is placed. It is known that the radius of its coverage is r. Thus, if Polycarp is at a ...
3
def count_min(c1,c2,c,d): count=0 if (c2 > c + d or c1 < c - d): count = 0 return count if (c1 <= c + d and c2 >= c - d): count = min elif (c1 <= c + d and c2 < c - d): count = c1 - (c - d) elif (c2 >= c - d and c1 > c + d): count = (c + d) - c2 elif (c2 <...
One day Alex was creating a contest about his friends, but accidentally deleted it. Fortunately, all the problems were saved, but now he needs to find them among other problems. But there are too many problems, to do it manually. Alex asks you to write a program, which will determine if a problem is from this contest ...
3
I = lambda: map(int, input().split()) L = [ "Danil", "Olya", "Slava", "Ann", "Nikita", ] s = str(input()) c = 0 for sub in L: c += s.count(sub) if c == 1: print("YES") else: print("NO")
Write a program which reads two integers a, b and an operator op, and then prints the value of a op b. The operator op is '+', '-', '*' or '/' (sum, difference, product or quotient). The division should truncate any fractional part. Constraints * 0 ≀ a, b ≀ 20000 * No divisions by zero are given. Input The input c...
3
ops = {'+': lambda a, b: a+b, '-': lambda a, b: a-b, '*': lambda a, b: a*b, '/': lambda a, b: int(a/b)} while True: a, op, b = input().split() if op not in ops.keys(): break print(ops[op](int(a),int(b)))
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
def main(): n = int(sys.stdin.readline()) coins = [int(x) for x in sys.stdin.readline().split()] coins.sort(reverse=True) total = sum(coins) cur = 0 count = 0 for coin in coins: if cur > total: break cur += coin total -= coin count += 1 sys.stdout.write(str(count)) if __name__ == '__main_...
The subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. You are given an integer n. You have to find a sequence s consisting of digits \{1, 3, 7\} such that it has exactly n subsequences equal to 1337. For example, seque...
3
# Los comentarios van dirigidos a una mejor del algoritmo # OJO: se asume que se halla leΓ­do antes el informe que queda adjunto con este archivo inputs = int(input()) # se lee la cantidad de casos pruebas a leer for i in range(inputs): n = int(input()) # se lee la cantidad de ocurrencias de "1337"...
Vasily has a number a, which he wants to turn into a number b. For this purpose, he can do two types of operations: * multiply the current number by 2 (that is, replace the number x by 2Β·x); * append the digit 1 to the right of current number (that is, replace the number x by 10Β·x + 1). You need to help Vasil...
1
a,b = map(int,raw_input().split()) nums = [a] answers = [] def dfs(nums): if(nums[-1]>b): return elif(nums[-1]==b): answers.append(nums) else: numsPlusOne = nums[::] numsPlusOne.append((nums[-1]*10)+1) dfs(numsPlusOne) numsTimesTwo = nums[::] numsTimes...
Yaroslav has an array that consists of n integers. In one second Yaroslav can swap two neighboring array elements. Now Yaroslav is wondering if he can obtain an array where any two neighboring elements would be distinct in a finite time. Help Yaroslav. Input The first line contains integer n (1 ≀ n ≀ 100) β€” the numb...
3
import math from collections import Counter n = int(input()) a = list(map(int, input().split())) cnt = Counter(a) ans = 1 for i in range(n): if cnt[a[i]] > math.ceil(n/2): ans = 0 break if (len(set(a)) > 1 or len(a) == 1) and ans == 1: print("YES") else: print("NO")
You are given a sequence of integers of length n and integer number k. You should print any integer number x in the range of [1; 10^9] (i.e. 1 ≀ x ≀ 10^9) such that exactly k elements of given sequence are less than or equal to x. Note that the sequence can contain equal elements. If there is no such x, print "-1" (w...
1
from __future__ import division, print_function import bisect import os import sys from io import BytesIO, IOBase def main(): pass # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() se...
An accordion is a string (yes, in the real world accordions are musical instruments, but let's forget about it for a while) which can be represented as a concatenation of: an opening bracket (ASCII code 091), a colon (ASCII code 058), some (possibly zero) vertical line characters (ASCII code 124), another colon, and a ...
3
def main(): buf = input() s = "" for _, c in enumerate(buf): if c == '[' or c == ']' or c == ':' or c == '|': s += c if len(s) < 4: print(-1) # impossible return idx_brl = None # [ idx_col = None # : idx_cor = None # : idx_brr = None # ] fo...
Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: 1. The product of all numbers in the first set is less than zero ( < 0). 2. The product of all numbers in the second set is greater than zero ( > 0). 3. The product of a...
3
n=int(input()) s=list(map(int,input().split())) a=[] b=[] c=[] for i in range(n): if s[i]<0: a.append(s[i]) elif s[i]>0: b.append(s[i]) else: c.append(s[i]) if len(a)%2==0: d=a.pop() c.append(d) if len(b)==0: e=a.pop() b.append(e) f=a.pop() b.append(f) print(len(a),*list(a)) print(len(b),*list(b)) print(...
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
MOD = 1000000007 ii = lambda : int(input()) si = lambda : input() dgl = lambda : list(map(int, input())) f = lambda : map(int, input().split()) il = lambda : list(map(int, input().split())) ls = lambda : list(input()) for _ in range(ii()): n,m=f() st=il() d=dict((st[i],i) for i in range(n)) gfts=il() ...
Serval is fighting with a monster. The health of the monster is H. In one attack, Serval can decrease the monster's health by A. There is no other way to decrease the monster's health. Serval wins when the monster's health becomes 0 or below. Find the number of attacks Serval needs to make before winning. Constrai...
3
H, A = map(int, input().split()) print(H//A + 1 if H%A else H//A)
You have a string s of length n consisting of only characters > and <. You may do some operations with this string, for each operation you have to choose some character that still remains in the string. If you choose a character >, the character that comes right after it is deleted (if the character you chose was the l...
3
for _ in range(int(input())): n, s = int(input()), input() a1, a2 = 0, 0 for ch in s: if ch == '>': break else: a1 += 1 for ch in reversed(s): if ch == '<': break else: a2 += 1 print(min(a1, a2))
You are given a string s consisting only of lowercase Latin letters. You can rearrange all letters of this string as you wish. Your task is to obtain a good string by rearranging the letters of the given string or report that it is impossible to do it. Let's call a string good if it is not a palindrome. Palindrome is...
3
import random def ispallindrome(s): f=True l=int(len(s)/2) for i in range(l): if s[i]!=s[i*(-1)-1]: f=False break return f def canbeconverted(s): fl = False if len(s) > 1: for ch in s: if s[0] != ch: fl = True ...
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
#******** weight=int(input()) #you cannot divide 2 or odd numbers into 2 even parts if(weight==2 or weight%2==1): print("NO") #otherwise, all even numbers except 2 can be divided into 2 even parts else: print("YES")
For a positive integer n let's define a function f: f(n) = - 1 + 2 - 3 + .. + ( - 1)nn Your task is to calculate f(n) for a given integer n. Input The single line contains the positive integer n (1 ≀ n ≀ 1015). Output Print f(n) in a single line. Examples Input 4 Output 2 Input 5 Output -3 Note f(4)...
3
n=int(input()) if n%2==0: s=n//2 else: s=(n-1)//2-n print(s)
The purpose of this problem is to verify whether the method you are using to read input data is sufficiently fast to handle problems branded with the enormous Input/Output warning. You are expected to be able to process at least 2.5MB of input data per second at runtime. Karan likes stickers. All his stickers are rect...
1
n=input() a=map(int,raw_input().split()) c=0 for i in xrange(n): if a[i]<300000000: c+=1 print c
A matrix of size n Γ— m is called nice, if all rows and columns of the matrix are palindromes. A sequence of integers (a_1, a_2, ... , a_k) is a palindrome, if for any integer i (1 ≀ i ≀ k) the equality a_i = a_{k - i + 1} holds. Sasha owns a matrix a of size n Γ— m. In one operation he can increase or decrease any numb...
3
for _ in range(int(input())): n, m = map(int, input().split()) data = [list(map(int, input().split())) for _ in range(n)] res = 0 for i in range(n//2): for k in range(m//2): t = sorted([data[i][k], data[i][m-1-k], data[n-1-i][k], data[n-1-i][m-1-k]]) res += t[3]+t[2]-t[1]...
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
n=int(input()) arr=[] x=0 arr=list(map(int,input().split(" "))) for i in range(n): if arr[i]==1: x=x+1 if x==0: print("EASY") else: print("HARD")
Bob is playing with 6-sided dice. A net of such standard cube is shown below. <image> He has an unlimited supply of these dice and wants to build a tower by stacking multiple dice on top of each other, while choosing the orientation of each dice. Then he counts the number of visible pips on the faces of the dice. Fo...
3
n=int(input()) arr=list(map(int,input().split())) for i in arr: if i<=14: print("NO") else: flg=False for j in range(1,7): if (i-j)%14==0: flg=True if flg: print("YES") else: print("NO")
Petya loves lucky numbers. Everybody knows that positive integers are lucky if their decimal representation doesn't contain digits other than 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Lucky number is super lucky if it's decimal representation contains equal amount of digits 4 and 7. Fo...
3
from itertools import product n = int(input()) l = [] for i in range(2, 11, 2): l = l + [int(''.join([str(y) for y in x])) for x in list(product([4,7], repeat=i)) if x.count(4) == i/2] for x in sorted(l): if x == n or x > n: print(x) exit(0) # Made By Mostafa_Khaled
Kolya got an integer array a_1, a_2, ..., a_n. The array can contain both positive and negative integers, but Kolya doesn't like 0, so the array doesn't contain any zeros. Kolya doesn't like that the sum of some subsegments of his array can be 0. The subsegment is some consecutive segment of elements of the array. Y...
3
n = int(input()) arr = list(map(int,input().strip().split()))[:n] from collections import defaultdict store = defaultdict(int) store[0] = True;sums = 0;count = 0; for i,num in enumerate(arr): sums += num if store[sums] == True: count+=1 store = defaultdict(int) store[0] = True ...
Over time, Alexey's mail box got littered with too many letters. Some of them are read, while others are unread. Alexey's mail program can either show a list of all letters or show the content of a single letter. As soon as the program shows the content of an unread letter, it becomes read letter (if the program shows...
3
'''input 2 0 0 ''' n = int(input()) l = "".join(input().split()) while "00" in l: l = l.replace("00", "0") l = l.replace("0", " ") print(len(l.strip()))
A sequence a_1, a_2, ..., a_n is called good if, for each element a_i, there exists an element a_j (i β‰  j) such that a_i+a_j is a power of two (that is, 2^d for some non-negative integer d). For example, the following sequences are good: * [5, 3, 11] (for example, for a_1=5 we can choose a_2=3. Note that their sum ...
3
""" 6 4 7 1 5 4 9 """ n = int(input()) a = sorted([int(x) for x in input().split()]) b = set([]) for p in range(32): s = 1 << p i, j = 0, n-1 while i < j: while i < j and a[i] + a[j] > s: j -= 1 if i < j and a[i] + a[j] == s: b.add(a[i]) b.add(a[j]) ...
Wilbur the pig is tinkering with arrays again. He has the array a1, a2, ..., an initially consisting of n zeros. At one step, he can choose any index i and either add 1 to all elements ai, ai + 1, ... , an or subtract 1 from all elements ai, ai + 1, ..., an. His goal is to end up with the array b1, b2, ..., bn. Of co...
1
n = input() l = map(int, raw_input().split()) amount = 0 adding = 0 for i in xrange(n): q = l[i] - adding adding += q amount += abs(q) print amount
We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer t Π’-prime, if t has exactly three distinct positive divisors. You are given an array of n positive integers. For each of them determine whether it is Π’-prime or not. Input The f...
3
import math as m n=10**6 arr=[1]*(n+1) arr[0]=-1 arr[1]=-1 for i in range(2,int(m.sqrt(n+1))+1): if arr[i]==1: for j in range(2*i,n+1,i): arr[j]=-1 mm=int(input()) num=list(map(int,input().split())) for i in num: if int(m.sqrt(i))==m.sqrt(i) and arr[int(m.sqrt(i))]==1: print('YES')...
A student of z-school found a kind of sorting called z-sort. The array a with n elements are z-sorted if two conditions hold: 1. ai β‰₯ ai - 1 for all even i, 2. ai ≀ ai - 1 for all odd i > 1. For example the arrays [1,2,1,2] and [1,1,1,1] are z-sorted while the array [1,2,3,4] isn’t z-sorted. Can you make the...
1
n=int(raw_input()) a=map(int,raw_input().split()) a.sort() res = range(n) idx=0 for i in range(0,n,2): res[i]=a[idx] idx+=1 idx=n-1 for i in range(1,n,2): res[i]=a[idx] idx-=1 for i in res: print i,
Programmer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the expose procedure. Unfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agreed...
3
first = True power = 1 a, b, c = input().split(sep=' ') a, b, c = int(a), int(b), int(c) while power <= b: if not first: print(' ', end='') if power >= a: print(power, end='') first = False power *= c if first: print(-1, end='') print('\n')
You are given two sequences a_1, a_2, ..., a_n and b_1, b_2, ..., b_n. Each element of both sequences is either 0, 1 or 2. The number of elements 0, 1, 2 in the sequence a is x_1, y_1, z_1 respectively, and the number of elements 0, 1, 2 in the sequence b is x_2, y_2, z_2 respectively. You can rearrange the elements i...
3
for _ in range(int(input())): x1,y1,z1=map(int,input().split()) x2,y2,z2=map(int,input().split()) cnt=0 if z1>0 and y2>0: if z1>=y2: cnt+=(2*y2) z1-=y2 y2=0 else: cnt+=(2*z1) y2-=z1 z1=0 if x1>0 and z2>0: ...
AtCoder Inc. has decided to lock the door of its office with a 3-digit PIN code. The company has an N-digit lucky number, S. Takahashi, the president, will erase N-3 digits from S and concatenate the remaining 3 digits without changing the order to set the PIN code. How many different PIN codes can he set this way? ...
3
N = int(input()) S = input() ans = 0 for i in range(1000): t = "{:0=3}".format(i) p = 0 for j in range(N): if S[j] == t[p]: p += 1 if p == 3: break if p == 3: ans += 1 print(ans)
Mike and Ann are sitting in the classroom. The lesson is boring, so they decided to play an interesting game. Fortunately, all they need to play this game is a string s and a number k (0 ≀ k < |s|). At the beginning of the game, players are given a substring of s with left border l and right border r, both equal to k ...
3
s=input().rstrip() s=[i for i in s] n=len(s) pos=[0]*(n) mini=s[0] print('Mike') for i in range(1,n): mini=min(mini,s[i]) if mini<s[i]: print('Ann') else: print('Mike')
When Petya went to school, he got interested in large numbers and what they were called in ancient times. For instance, he learned that the Russian word "tma" (which now means "too much to be counted") used to stand for a thousand and "tma tmyschaya" (which literally means "the tma of tmas") used to stand for a million...
3
from sys import * K = int(stdin.readline()) c = K L = int(stdin.readline()) f = False ind = 0 while K < L: K *= c ind += 1 if K == L: print("YES") print(ind) else: print("NO")
Luke Skywalker got locked up in a rubbish shredder between two presses. R2D2 is already working on his rescue, but Luke needs to stay alive as long as possible. For simplicity we will assume that everything happens on a straight line, the presses are initially at coordinates 0 and L, and they move towards each other wi...
3
#code import math d, l, v1, v2 = map(int, input().split(' ')) ans = ((l-d)*1.00000000000000000000000000)/(v1*1.00000000000000000000000+v2) print("%.20f" % abs(ans))
You and your n - 1 friends have found an array of integers a_1, a_2, ..., a_n. You have decided to share it in the following way: All n of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for h...
3
# Legends Always Come Up with Solution # Author: Manvir Singh import os from io import BytesIO, IOBase import sys from collections import defaultdict, deque, Counter from bisect import * from math import sqrt, pi, ceil, log, inf,gcd from itertools import permutations from copy import deepcopy from heapq import * def ...
Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. For example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. When a team plays as ...
3
n=int(input()) colors=[0]*n for i in range(n): colors[i]=list(map(int,input().split())) N=0 for i in range(n): for k in range(n): if colors[i][1]==colors[k][0]: N+=1 print(N)
Given is an integer S. Find a combination of six integers X_1,Y_1,X_2,Y_2,X_3, and Y_3 that satisfies all of the following conditions: * 0 \leq X_1,Y_1,X_2,Y_2,X_3,Y_3 \leq 10^9 * The area of the triangle in a two-dimensional plane whose vertices are (X_1,Y_1),(X_2,Y_2), and (X_3,Y_3) is S/2. We can prove that ther...
1
S = input() a = 10**9 d = (S+a-1)/a b = a*d-S c = 1 print 0, 0, a, b, c, d
You have an array a with length n, you can perform operations. Each operation is like this: choose two adjacent elements from a, say x and y, and replace one of them with gcd(x, y), where gcd denotes the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor). What is the minimum number of ope...
3
from math import gcd n = int(input()) arr = list(map(int, input().split())) cnt = arr.count(1) if cnt != 0: print(n - cnt) exit() dis = int(2e9) for i in range(len(arr)): g = arr[i] for j in range(i+1, len(arr)): g = gcd(g, arr[j]) if g == 1: dis = min(dis, j-i) print(-1 ...
Zookeeper is playing a game. In this game, Zookeeper must use bombs to bomb a string that consists of letters 'A' and 'B'. He can use bombs to bomb a substring which is either "AB" or "BB". When he bombs such a substring, the substring gets deleted from the string and the remaining parts of the string get concatenated....
3
import sys, os import heapq, functools, collections import math, random from collections import Counter, defaultdict # available on Google, not available on Codeforces # import numpy as np # import scipy def solve_(lst): # your solution here c = Counter(lst) if c["B"] == 0: return len(lst) ...
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below. There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each ...
3
# -*- coding: utf-8 -*- """ Created on Wed Jun 24 08:39:22 2020 @author: Harshal """ n=int(input()) trees=[] for _ in range(n): a,b=map(int,input().split()) trees.append([a,b]) occ=trees[0][0] ans=1 for i in range(1,n): cur=trees[i] if cur[0]-cur[1]>occ: ans+=1 occ=cur[0] ...
Ehab loves number theory, but for some reason he hates the number x. Given an array a, find the length of its longest subarray such that the sum of its elements isn't divisible by x, or determine that such subarray doesn't exist. An array a is a subarray of an array b if a can be obtained from b by deletion of several...
3
for ii in range(int(input())): n,k = map(int, input().split()) a= list(map(int, input().split())) s2 =[] if sum(a)%k!=0: print(n) continue for i in range(n): if (a[i] % k != 0): s2.append(i) if not s2: print(-1) else: x=n-max(s2) y=...
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
t=int(input()) for i in range(t): x,y,n=map(int,input().split()) k=n//x*x k+=y if k<=n: print(k) else: print(k-x)
You are a coach of a group consisting of n students. The i-th student has programming skill a_i. All students have distinct programming skills. You want to divide them into teams in such a way that: * No two students i and j such that |a_i - a_j| = 1 belong to the same team (i.e. skills of each pair of students in t...
3
t=int(input()) for _ in range(t): n=int(input()) x=list(map(int,input().split())) f=0 x.sort() for i in range(n-1): if x[i+1]-x[i]==1: f=1 break; if f==0: print(1) else: print(2)
Mahmoud has n line segments, the i-th of them has length ai. Ehab challenged him to use exactly 3 line segments to form a non-degenerate triangle. Mahmoud doesn't accept challenges unless he is sure he can win, so he asked you to tell him if he should accept the challenge. Given the lengths of the line segments, check ...
3
n=int(input()) a=list(map(int,input().split())) a.sort() flag=0 if n==3 and a[0]==1 and a[1]==328479 and a[2]==3245: print("LOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOL") for i in range(n-2): if (a[i]+a[i+1]>a[i+2]) and (a[i]<a[i+1]+a[i+2]) and (a[i+2]+a[i]>a[i+1]): print("YES") fla...
A number is ternary if it contains only digits 0, 1 and 2. For example, the following numbers are ternary: 1022, 11, 21, 2002. You are given a long ternary number x. The first (leftmost) digit of x is guaranteed to be 2, the other digits of x can be 0, 1 or 2. Let's define the ternary XOR operation βŠ™ of two ternary n...
3
t=int(input()) for _ in range(t): n=int(input()) x=input() a,b="","" bool=True for i in x: if i=="1": if bool: b+="1" a+="0" bool=False else: a+="1" b+="0" elif i=="0": b+='0' a+="0" else: if bool: b+="1" a+="1" else: b+="0" a+="2" print(a) print(b)
The only difference between easy and hard versions is constraints. There are n kids, each of them is reading a unique book. At the end of any day, the i-th kid will give his book to the p_i-th kid (in case of i = p_i the kid will give his book to himself). It is guaranteed that all values of p_i are distinct integers ...
3
import sys input = sys.stdin.buffer.readline class UnionFind(): def __init__(self, n): self.n = n self.root = [-1] * (n + 1) self.rnk = [0] * (n + 1) def Find_Root(self, x): if self.root[x] < 0: return x else: self.root[x] = self.Find_Root(self.root[x]) return self.root[x] ...
One day Polycarp published a funny picture in a social network making a poll about the color of his handle. Many of his friends started reposting Polycarp's joke to their news feed. Some of them reposted the reposts and so on. These events are given as a sequence of strings "name1 reposted name2", where name1 is the n...
3
n=int(input()) parents={'polycarp':1} for i in range(n): name1,name2=[i.lower() for i in input().split(' reposted ')] parents[name1]=parents[name2]+1 ans=max(parents.values()) print(ans)
You are given two integers n and m. You have to construct the array a of length n consisting of non-negative integers (i.e. integers greater than or equal to zero) such that the sum of elements of this array is exactly m and the value βˆ‘_{i=1}^{n-1} |a_i - a_{i+1}| is the maximum possible. Recall that |x| is the absolut...
3
t=int(input()) while(t>0): inp=list(map(int, input().split())) n=inp[0] m=inp[1] if(n==1): print(0) elif(n==2): print(m) else: print(2*m) t-=1
You are given two segments [l_1; r_1] and [l_2; r_2] on the x-axis. It is guaranteed that l_1 < r_1 and l_2 < r_2. Segments may intersect, overlap or even coincide with each other. <image> The example of two segments on the x-axis. Your problem is to find two integers a and b such that l_1 ≀ a ≀ r_1, l_2 ≀ b ≀ r_2 an...
3
import sys amount = int(input()) for i in range(amount): l1,r1,l2,r2 = [int(s) for s in input().split()] if l1 != r2: print(l1,r2) continue if l1 != l2: print(l1,l2) continue if r1 != l2: print(r1,l2) continue if r1 != r2: print(r1,r2) ...
The name of one small but proud corporation consists of n lowercase English letters. The Corporation has decided to try rebranding β€” an active marketing strategy, that includes a set of measures to change either the brand (both for the company and the goods it produces) or its components: the name, the logo, the slogan...
3
from collections import * d=defaultdict(list) n,m=map(int,input().split()) s=input() flag=0 flag2=0 temp,temp1=0,0 for i in range(m): x,y=input().strip().split(" ") if x in d.keys(): flag=1 for i in d.keys(): if d[i]==x: temp=i break else: ...
A has a string consisting of some number of lowercase English letters 'a'. He gives it to his friend B who appends some number of letters 'b' to the end of this string. Since both A and B like the characters 'a' and 'b', they have made sure that at this point, at least one 'a' and one 'b' exist in the string. B now gi...
3
import sys import itertools as it import math as mt import collections as cc input=sys.stdin.readline I=lambda:list(map(int,input().split())) s=list(input().strip()) n=len(s) c=cc.Counter(s) f=cc.defaultdict(int) tf=1 if len(set(s))<3: print("NO") else: for i in range(n): f[s[i]]+=1 if s[i]=='a': if f['b']...
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() ctr=0 w=0 o=0 t=0 for i in range(0,len(s)-1): if(s[i]=='v' and s[i+1]=='v'): w+=1 ctr+=t continue if(s[i]=='o'): o+=1 t+=w continue else: continue print(ctr)
Vasya lives in a round building, whose entrances are numbered sequentially by integers from 1 to n. Entrance n and entrance 1 are adjacent. Today Vasya got bored and decided to take a walk in the yard. Vasya lives in entrance a and he decided that during his walk he will move around the house b entrances in the direct...
1
n,a,b=map(int,raw_input().split()) if b==0: print a elif b>0: val = (a+(b%n))%n if val==0: print n else: print val else: b = n- abs(b) val = (a+(b%n))%n if val==0: print n else: print val
Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited n his friends there. If t...
3
n=int(input()) p=list(map(int, input().split())) d=p[:] for i in range(1,n+1): d[i-1]=p.index(i)+1 print(*d, end=' ')
You are given a sequence a consisting of n integers. Find the maximum possible value of <image> (integer remainder of ai divided by aj), where 1 ≀ i, j ≀ n and ai β‰₯ aj. Input The first line contains integer n β€” the length of the sequence (1 ≀ n ≀ 2Β·105). The second line contains n space-separated integers ai (1 ≀ a...
3
n = int(input()) a = list(set(map(int, input().split()))) inf = 2000001 prev = [0] * inf for i in a: prev[i] = i last = 0 for i in range(inf): if prev[i] == i: prev[i] = last last = i else: prev[i] = last res = 0 for i in a: for j in range(2 * i, inf, i): res = max(res, prev[j] % i) print(res)
Like any unknown mathematician, Yuri has favourite numbers: A, B, C, and D, where A ≀ B ≀ C ≀ D. Yuri also likes triangles and once he thought: how many non-degenerate triangles with integer sides x, y, and z exist, such that A ≀ x ≀ B ≀ y ≀ C ≀ z ≀ D holds? Yuri is preparing problems for a new contest now, so he is v...
3
from collections import defaultdict from math import log2,floor,sqrt from pprint import pprint from bisect import bisect_left,bisect_right mod=pow(10,9)+7 dict=defaultdict(int) def fun(a,b,c,d): z=list(range(c,d+1)) lis=list(range(a+b,b+c+1)) length=len(lis) numbers=[1]*length # print(lis) mina=...
Guy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon P which is defined by coordinates of its vertices. Define P(x,y) as a polygon obtained by translating P by vector \overrightarrow {(x,y)}. The picture below depicts an example of t...
3
from itertools import permutations def solve(): n = int(input()) if n & 1: print("NO") return points = [] for i in range(n): points.append(complex(*map(int, input().split()))) n = n // 2 for i in range(n - 1): if not check_pair(points[i], points[i + 1], points[i...
You are given an array a_1, a_2, ..., a_n, consisting of n positive integers. Initially you are standing at index 1 and have a score equal to a_1. You can perform two kinds of moves: 1. move right β€” go from your current index x to x+1 and add a_{x+1} to your score. This move can only be performed if x<n. 2. mo...
3
for _ in range(int(input())): n,k,z=map(int,input().split()) arr=list(map(int,input().split())) lmax=0 ans=0 s=0 for t in range(z+1): pos=k-2*t if pos<0: break s=0 lmax=0 for i in range(pos+1): if i<n-1: lmax=max(lma...
The Cybernetics Failures (CF) organisation made a prototype of a bomb technician robot. To find the possible problems it was decided to carry out a series of tests. At the beginning of each test the robot prototype will be placed in cell (x0, y0) of a rectangular squared field of size x Γ— y, after that a mine will be i...
3
COLOR_RED = '\033[1;31m' COLOR_RESET = '\033[1;m' m, n, x, y = map(int, input().split()) S = input() visited = set() visited.add((x, y)) cnt = 1 print('1 ', end='') for e in S[0:len(S) - 1]: if e == 'U' and x > 1: x -= 1 elif e == 'D' and x < m: x += 1 elif e == 'R' and y < n: ...
Jack decides to invite Emma out for a dinner. Jack is a modest student, he doesn't want to go to an expensive restaurant. Emma is a girl with high taste, she prefers elite places. Munhattan consists of n streets and m avenues. There is exactly one restaurant on the intersection of each street and avenue. The streets a...
1
n, m = map(int, raw_input().split()) j = [] for _ in range(n): n = list(map(int, raw_input().split())) j.append(min(n)) print max(j)
We have a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and b_i. For each k=1, ..., N, solve the problem below: * Consider writing a number on each vertex in the tree in the following manner: * First, write 1 on Vertex k. * Then, for each of the numbers 2, ..., N in this order, w...
3
from functools import * from itertools import * import sys sys.setrecursionlimit(10**6) input = sys.stdin.buffer.readline M = 10**9+7 N = int(input()) @lru_cache(maxsize=None) def mod_inv(x): return 1 if x == 1 else M // x * -mod_inv(M%x) % M Weight = [0]*(N+1) Size = [0]*(N+1) def calc_subtree(v): W, S = 1, 1 ...
If the strings are consecutive, you can replace the characters with a rule to shorten the string. For example, for the string AAAA, the expression @ 4A will compress one character. Create a program that restores the character string compressed by this rule to the original character string. However, it is assumed that t...
1
while 1: try: n=raw_input() ans='' f=t=0 for i in n: if i!='@' and f==0: ans+=i elif i=='@': f=1 elif f==1 and t==0: t=int(i) else: ans+=i*t f=0 ...
Find the number of palindromic numbers among the integers between A and B (inclusive). Here, a palindromic number is a positive integer whose string representation in base 10 (without leading zeros) reads the same forward and backward. Constraints * 10000 \leq A \leq B \leq 99999 * All input values are integers. Inp...
3
a, b = map(int, input().split()) c = 0 while a <= b: if str(a) == str(a)[::-1]: c += 1 a += 1 print(c)
You're given a list of n strings a1, a2, ..., an. You'd like to concatenate them together in some order such that the resulting string would be lexicographically smallest. Given the list of strings, output the lexicographically smallest concatenation. Input The first line contains integer n β€” the number of strings (...
3
from functools import cmp_to_key as cmptokey n=int(input()) s=[] for i in range(n): s+=[input()] s.sort(key=cmptokey(lambda x,y:1 if x+y>y+x else -1)) print(''.join(s))
Tonio has a keyboard with only two letters, "V" and "K". One day, he has typed out a string s with only these two letters. He really likes it when the string "VK" appears, so he wishes to change at most one letter in the string (or do no changes) to maximize the number of occurrences of that string. Compute the maximu...
3
s = input() c = s.count("VK") s = s.replace("VK","_") if s.count("VV") or s.count("KK"): c+=1 print (c)
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. Petya wonders eagerly what minimum lucky number has the sum of digits equal to n. Help him cope with...
3
from sys import * n=int(input()) for i in range((n//4)+1): res=n-4*i if res%7==0: j=res//7 print("4"*i+"7"*j) exit() print(-1)
You are given an integer number n. The following algorithm is applied to it: 1. if n = 0, then end algorithm; 2. find the smallest prime divisor d of n; 3. subtract d from n and go to step 1. Determine the number of subtrations the algorithm will make. Input The only line contains a single integer n (2 ≀...
3
from math import sqrt from math import floor def deli(a): sq = sqrt(a) sq = floor(sq) if a % 2 == 0: return 2 for i in range(3, sq + 1, 2): if a % i == 0: d = i return d return a n = int(input()) c = 0 while n > 0: b = deli(n) if b == 2: c ...