problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
You are given an integer sequence of length N. The i-th term in the sequence is a_i. In one operation, you can select a term and either increment or decrement it by one. At least how many operations are necessary to satisfy the following conditions? * For every i (1≤i≤n), the sum of the terms from the 1-st through i-...
3
n = int(input()) A = [int(i) for i in input().split()] def f(A, op, acc = 0, cnt = 0): for i in range(n): acc += A[i] if i % 2 == 0 and op * acc <= 0: cnt += - op * acc + 1 acc = op if i % 2 == 1and op * acc >= 0: cnt += op * acc...
Takahashi has two positive integers A and B. It is known that A plus B equals N. Find the minimum possible value of "the sum of the digits of A" plus "the sum of the digits of B" (in base 10). Constraints * 2 ≤ N ≤ 10^5 * N is an integer. Input Input is given from Standard Input in the following format: N Outp...
3
n=int(input()) nl=[] for i in range(5): nl.append(int((n/10**(4-i))%10)) if sum(nl)>1: print(sum(nl)) else: print(10)
A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (x < y) from the set, such that y = x·k. You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-mu...
1
''' Created on 2013-5-2 URL : http://codeforces.com/contest/275/problem/C @author: zhxfl ''' n, k = map(int, raw_input().split()); r = sorted(map(int, raw_input().split())); Set = set(); for j in range(n): Set.add(r[j]); if k > 1 and r[j] % k == 0 and ((r[j] / k) in Set): Set.remove(r[j]); #prin...
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
import io import os #input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline n = int(input()) for i in range(n): word = input() lenght = len(word) if lenght > 10: print(word[0] + str(lenght - 2) + word[lenght-1]) else: print(word)
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d...
3
a=input() b=[] for i in range(len(a)): b.extend(a[i]) if '4' not in b and '7' not in b: print('NO') elif b.count('4')+b.count('7')==4 or b.count('4')+b.count('7')==7: print('YES') else: print('NO')
AtCoDeer the deer found two rectangles lying on the table, each with height 1 and width W. If we consider the surface of the desk as a two-dimensional plane, the first rectangle covers the vertical range of [0,1] and the horizontal range of [a,a+W], and the second rectangle covers the vertical range of [1,2] and the ho...
3
a,b,c=map(int,input().split()) print(max(0,c-b-a)if c>b else max(0,b-c-a))
For a given array a consisting of n integers and a given integer m find if it is possible to reorder elements of the array a in such a way that ∑_{i=1}^{n}{∑_{j=i}^{n}{(a_j)/(j)}} equals m? It is forbidden to delete elements as well as insert new elements. Please note that no rounding occurs during division, for exampl...
3
import sys input = sys.stdin.readline for _ in range(int(input())): n, m = map(int, input().split()) print("YES" if sum(map(int, input().split())) == m else "NO")
You are given a text consisting of n lines. Each line contains some space-separated words, consisting of lowercase English letters. We define a syllable as a string that contains exactly one vowel and any arbitrary number (possibly none) of consonants. In English alphabet following letters are considered to be vowels:...
3
n = int(input()) pattern = list(map(int, input().split())) data = [] for i in range(n): data.append(input()) vowels = ['a', 'e', 'i', 'o', 'u', 'y'] trigger = True for i in range(n): count = 0 for ch in data[i]: if ch in vowels: count += 1 if count != pattern[i]: trigger = False break if trigger: print('Y...
AtCoDeer the deer has N cards with positive integers written on them. The number on the i-th card (1≤i≤N) is a_i. Because he loves big numbers, he calls a subset of the cards good when the sum of the numbers written on the cards in the subset, is K or greater. Then, for each card i, he judges whether it is unnecessary...
3
def I(): return int(input()) def MI(): return map(int, input().split()) def LI(): return list(map(int, input().split())) def main(): N,K=MI() a=LI()#下位の連続するn枚が不要なはず a.sort() for i in range(N):#K以上ならば必要 if a[i]>=K: a=a[:i] break N=len(a) ...
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
n=int(input()) l=[] count=0 s=0 for i in range(n): p, v, t=[int(x) for x in input().split()] str1=str(p)+str(v)+str(t) l.append(str1) for i1 in l: if int(i1[0])==1: count+=1 if int(i1[1])==1: count+=1 if int(i1[2])==1: count+=1 if count>=2: s+=1 count=0 pr...
Let LCM(x, y) be the minimum positive integer that is divisible by both x and y. For example, LCM(13, 37) = 481, LCM(9, 6) = 18. You are given two integers l and r. Find two integers x and y such that l ≤ x < y ≤ r and l ≤ LCM(x, y) ≤ r. Input The first line contains one integer t (1 ≤ t ≤ 10000) — the number of tes...
3
import sys input=sys.stdin.readline T=int(input()) for _ in range(T): n,m=map(int,input().split()) if (m>=2*n): print(n,2*n) else: print(-1,-1)
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
st = input().split('+') st.sort() l = '+'.join(st) print(l)
Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw. The first player wrote number a, the second player wrote number b. How many ways ...
3
a, b = map(int, input().split()) awin, draw, bwin = 0,0,0 for i in range(1, 7): if abs(a-i) < abs(b-i): awin +=1 elif abs(a-i) == abs(b-i): draw += 1 else: bwin += 1 print(awin, draw, bwin)
The brave Knight came to the King and asked permission to marry the princess. The King knew that the Knight was brave, but he also wanted to know if he was smart enough. So he asked him to solve the following task. There is a permutation p_i of numbers from 1 to 2n. You can make two types of operations. 1. Swap p_...
3
import sys import math from math import factorial, inf, gcd from heapq import * from functools import * from itertools import * from collections import * from typing import * from bisect import * import random sys.setrecursionlimit(10**5) def rarray(): return [int(i) for i in input().split()] def is_sorted(a): ...
Let quasi-palindromic number be such number that adding some leading zeros (possible none) to it produces a palindromic string. String t is called a palindrome, if it reads the same from left to right and from right to left. For example, numbers 131 and 2010200 are quasi-palindromic, they can be transformed to strin...
1
n=int (raw_input()) finalNum=n div10=True while div10==True: if finalNum%10==0: finalNum/=10 else: div10=False finalNum=str(finalNum) i=-len(finalNum) f=-1 toPrint='YES' while i <=f and toPrint=='YES' : if finalNum[i] != finalNum[f]: toPrint='NO' i+=1 f-=1 print toPri...
Takahashi is organizing a party. At the party, each guest will receive one or more snack pieces. Takahashi predicts that the number of guests at this party will be A or B. Find the minimum number of pieces that can be evenly distributed to the guests in both of the cases predicted. We assume that a piece cannot be ...
3
import math a,b=map(int,input().split());print((a*b)//math.gcd(a,b))
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
x=int(input()) y=int(x % 2) if x==2: print ("NO") elif y==0: print ("YES") else: print ("NO")
Kuroni has n daughters. As gifts for them, he bought n necklaces and n bracelets: * the i-th necklace has a brightness a_i, where all the a_i are pairwise distinct (i.e. all a_i are different), * the i-th bracelet has a brightness b_i, where all the b_i are pairwise distinct (i.e. all b_i are different). Kuro...
3
t = int(input()) for _ in range(t): n = int(input()) a = map(int, input().split()) b = map(int, input().split()) a_sort = sorted(a) b_sort = sorted(b) for i in range(n): print(a_sort[i], end=' ') print() for i in range(n): print(b_sort[i], end=' ')
A word or a sentence in some language is called a pangram if all the characters of the alphabet of this language appear in it at least once. Pangrams are often used to demonstrate fonts in printing or test the output devices. You are given a string consisting of lowercase and uppercase Latin letters. Check whether thi...
3
import sys from functools import lru_cache, cmp_to_key from heapq import merge, heapify, heappop, heappush, nlargest, nsmallest, _heapify_max, _heapreplace_max from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf, log from collections import defaultdict as dd, deque, Counter as c from itertools import co...
Consider writing each of the integers from 1 to N \times M in a grid with N rows and M columns, without duplicates. Takahashi thinks it is not fun enough, and he will write the numbers under the following conditions: * The largest among the values in the i-th row (1 \leq i \leq N) is A_i. * The largest among the value...
3
N, M = map(int, input().split()) a_list = tuple(map(int, input().split())) b_list = tuple(map(int, input().split())) mod = 10 ** 9 + 7 # 同じもの含んでいたらアウト a_set = set(a_list) b_set = set(b_list) if len(a_set) < N or len(b_set) < M: print(0) exit() # 大きいものから順にみていく a_list = sorted(a_list, reverse=True) b_list = sor...
Many students live in a dormitory. A dormitory is a whole new world of funny amusements and possibilities but it does have its drawbacks. There is only one shower and there are multiple students who wish to have a shower in the morning. That's why every morning there is a line of five people in front of the dormitory...
3
import itertools def queue_joy(g, p): return (g[p[0]][p[1]] + g[p[1]][p[0]] + g[p[1]][p[2]] + g[p[2]][p[1]] + (g[p[2]][p[3]] + g[p[3]][p[2]]) * 2 + (g[p[3]][p[4]] + g[p[4]][p[3]]) * 2) g = list(list(map(int, input().split())) for _ in range(5)) print(max([queue_joy(g, p) for ...
Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to th...
3
a = [int(s) for s in input().split()] print(4-len(set(a)))
There is a directed graph with N vertices numbered 1 to N and M edges. The i-th edge is directed from Vertex A_i to Vertex B_i, and there are C_i coins placed along that edge. Additionally, there is a button on Vertex N. We will play a game on this graph. You start the game on Vertex 1 with zero coins, and head for V...
3
n, m, p = map(int, input().split()) edge = [] for _ in range(m): a, b, c = map(int, input().split()) edge.append([a-1, b-1, -c]) d = [float("inf") for _ in range(n)] d[0] = 0 # check = [0 for _ in range(n)] for i in range(n*2): for now, next, weight in edge: if d[next] > d[now] + weight + p: ...
There are N dishes of cuisine placed in front of Takahashi and Aoki. For convenience, we call these dishes Dish 1, Dish 2, ..., Dish N. When Takahashi eats Dish i, he earns A_i points of happiness; when Aoki eats Dish i, she earns B_i points of happiness. Starting from Takahashi, they alternately choose one dish and ...
3
n = int(input()) l = [list(map(int, input().split())) for _ in range(n)] l.sort(key=lambda x:x[0]+x[1], reverse=True) ans = 0 for i in range(n): if i % 2: ans -= l[i][1] else: ans += l[i][0] print(ans)
You got a job as a marketer in a pet shop, and your current task is to boost sales of cat food. One of the strategies is to sell cans of food in packs with discounts. Suppose you decided to sell packs with a cans in a pack with a discount and some customer wants to buy x cans of cat food. Then he follows a greedy str...
3
# -*- coding: utf-8 -*- """ Created on Tue Oct 27 10:38:41 2020 @author: sanat """ numCases = int(input()) results = [] for i in range(0, numCases): l, r = map(int,input().split()) if (r < 2 * l): results.append("YES") else: results.append("NO") for i in results: print(i)
By 2312 there were n Large Hadron Colliders in the inhabited part of the universe. Each of them corresponded to a single natural number from 1 to n. However, scientists did not know what activating several colliders simultaneously could cause, so the colliders were deactivated. In 2312 there was a startling discovery:...
1
n, m = map(int, raw_input().split()) act = [0] * (n + 1) mark = [False] * (n + 1) crib = [[] for _ in range(n + 1)] crib[1] = [1] for i in range(2, n + 1): if len(crib[i]) == 0: for j in range(i, n + 1, i): crib[j].append(i) for _ in range(m): k, ind = raw_input().split() ind = int(i...
Fedya studies in a gymnasium. Fedya's maths hometask is to calculate the following expression: (1n + 2n + 3n + 4n) mod 5 for given value of n. Fedya managed to complete the task. Can you? Note that given number n can be extremely large (e.g. it can exceed any integer type of your programming language). Input The si...
1
from __future__ import division s = raw_input() mod2 = int(s[-1]) % 2 mod4 = int(s[-2:]) % 4 twos = (1, 2, 4, 3) threes = (1,3,4,2) fours = (1, 4) result = 1 + twos[mod4] + threes[mod4] + fours[mod2] print result % 5
Let's call a number k-good if it contains all digits not exceeding k (0, ..., k). You've got a number k and an array a containing n numbers. Find out how many k-good numbers are in a (count each number every time it occurs in array a). Input The first line contains integers n and k (1 ≤ n ≤ 100, 0 ≤ k ≤ 9). The i-th ...
3
n,k=map(int,input().split()) l=[] for i in range(n): l.append(input()) l1=list(set(l)) s=0 for i in l1: c=0 for j in range(k+1): if i.count(str(j))==0: c=1 break if not c: s+=l.count(i) print(s)
You are both a shop keeper and a shop assistant at a small nearby shop. You have n goods, the i-th good costs a_i coins. You got tired of remembering the price of each product when customers ask for it, thus you decided to simplify your life. More precisely you decided to set the same price for all n goods you have. ...
3
V=[] for _ in range(int(input())): l=int(input()) q=sum(map(int,input().split())) V.append(-(-q//l)) print(*V,sep = "\n")
Let's define the following recurrence: $$$a_{n+1} = a_{n} + minDigit(a_{n}) ⋅ maxDigit(a_{n}).$$$ Here minDigit(x) and maxDigit(x) are the minimal and maximal digits in the decimal representation of x without leading zeroes. For examples refer to notes. Your task is calculate a_{K} for given a_{1} and K. Input The ...
3
def solve(a1, k): for _ in range(k-1): lstA = [int(x) for x in str(a1)] if lstA.count(0) > 0: return a1 a1 = a1 + (max(lstA) * min(lstA)) return a1 t = int(input()) for i in range(t): a1, k = [int(x) for x in input().split()] print(solve(a1, k))
In Chelyabinsk lives a much respected businessman Nikita with a strange nickname "Boss". Once Nikita decided to go with his friend Alex to the Summer Biathlon World Cup. Nikita, as a very important person, received a token which allows to place bets on each section no more than on one competitor. To begin with friends...
1
#! /usr/bin/python __author__="Guillermo Candia Huerta" __date__ ="$22-03-2011 11:47:42 AM$" import sys def resolver(input, n): r = [] for i in range(0, n): r.append(0) t = sys.maxint for v in input: if v[0] <= i+1 and i+1 <= v[1]: if v[2] < t: ...
You are given a string s consisting of lowercase English letters and a number k. Let's call a string consisting of lowercase English letters beautiful if the number of occurrences of each letter in that string is divisible by k. You are asked to find the lexicographically smallest beautiful string of length n, which is...
3
import collections import string import math import copy import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in fil...
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: * Employee A is the immediate manag...
3
#take input n = int(input()) superierList = [] for i in range(n): superierList.append(int(input())) # print(superierList) orderList = [1]*n leafList = [0]*n for i in range(n): thisSup = superierList[i] thisOrder = orderList[i] if(thisSup != -1): if(thisOrder == 1): leafList[i] = 1 ...
You are given an array a consisting of n integers. You can perform the following operations arbitrary number of times (possibly, zero): 1. Choose a pair of indices (i, j) such that |i-j|=1 (indices i and j are adjacent) and set a_i := a_i + |a_i - a_j|; 2. Choose a pair of indices (i, j) such that |i-j|=1 (indice...
3
from collections import Counter n = int(input()) a = list(map(int, input().split())) m = -1 maxInd = -1 c = Counter(a) cur = c.most_common(1)[0][0] curInd = a.index(cur) prev = curInd+1 res = [] for i in range(curInd+1, len(a)): if a[i]>cur: res.append([2, i+1, prev]) elif a[i]<cur: res.appe...
What joy! Petya's parents went on a business trip for the whole year and the playful kid is left all by himself. Petya got absolutely happy. He jumped on the bed and threw pillows all day long, until... Today Petya opened the cupboard and found a scary note there. His parents had left him with duties: he should water...
3
n=int(input()) l=list(map(int,input().split())) l.sort() s,count=0,0 j=sum(l) if j<n:print(-1) else: j=True for x in range(11,-1,-1): if s>=n: print(count) j=False break else: s+=l[x] count+=1 if j!=False:print(count)
You are given a string s consisting of lowercase Latin letters "a", "b" and "c" and question marks "?". Let the number of question marks in the string s be k. Let's replace each question mark with one of the letters "a", "b" and "c". Here we can obtain all 3^{k} possible strings consisting only of letters "a", "b" and...
3
import sys input = sys.stdin.readline def getInts(): return [int(s) for s in input().split()] def getInt(): return int(input()) def getStrs(): return [s for s in input().split()] def getStr(): return input().strip() def listStr(): return list(input().strip()) import collections as col """ ""...
We have N dice arranged in a line from left to right. The i-th die from the left shows p_i numbers from 1 to p_i with equal probability when thrown. We will choose K adjacent dice, throw each of them independently, and compute the sum of the numbers shown. Find the maximum possible value of the expected value of this ...
3
n,k=map(int,input().split()) p=list(map(int,input().split())) li=[sum(p[0:k])] for i in range(n-k): li.append(li[i]-p[i]+p[i+k]) print((max(li)+k)/2)
You are given a rectangular board of M × N squares. Also you are given an unlimited number of standard domino pieces of 2 × 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions: 1. Each domino completely covers two squa...
3
m, n = map(int, input().split()) print((m * n) // 2)
There are n employees in Alternative Cake Manufacturing (ACM). They are now voting on some very important question and the leading world media are trying to predict the outcome of the vote. Each of the employees belongs to one of two fractions: depublicans or remocrats, and these two fractions have opposite opinions o...
1
n=input() s=raw_input() d,r=[],[] for i in range(n): if 'D'==s[i]: d+=[i] else: r+=[i] i,j=0,0 while i<len(d) and j<len(r): if d[i]<r[j]: d+=[n+d[i]] i+=1 j+=1 else: r+=[n+r[j]] j+=1 i+=1 print 'D' if i<len(d) else 'R'
You are a lover of bacteria. You want to raise some bacteria in a box. Initially, the box is empty. Each morning, you can put any number of bacteria into the box. And each night, every bacterium in the box will split into two bacteria. You hope to see exactly x bacteria in the box at some moment. What is the minimu...
1
n=input() m=0 while n: x=n%2 m+=x n/=2 print m
You have n gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The i-th gift consists of a_i candies and b_i oranges. During one move, you can choose some gift 1 ≤ i ≤ n and do one of the following operations: * eat exactly...
3
for _ in range(int(input())): n=int(input()) a=list(map(int, input().split())) b=list(map(int, input().split())) s=0 candy=min(a) orange=min(b) for i in range(n): s+=max(a[i]-candy,b[i]-orange) print(s)
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
def prob4A(): i = int(input()) print(('NO', 'YES')[not(i % 2) and (i > 2)]) prob4A()
Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not. Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindro...
3
#Codeforces : Lovely Palindrome n=input() print(n+n[::-1])
Theatre Square in the capital city of Berland has a rectangular shape with the size n × m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a × a. What is the least number of flagstones needed to pave the Square? It'...
3
import math n,m,a = list(map(int, input().split())) width = (m / a) width = math.ceil(width) height = (n / a) height = math.ceil(height) res = width * height print(res)
Let's say string s has period k if s_i = s_{i + k} for all i from 1 to |s| - k (|s| means length of string s) and k is the minimum positive integer with this property. Some examples of a period: for s="0101" the period is k=2, for s="0000" the period is k=1, for s="010" the period is k=2, for s="0011" the period is k=...
3
from math import ceil for _ in range(int(input())): s = input() n = len(s) if len(set(s)) == 1: print(s) else: ans = '10'*n print(ans[:2*n])
Sasha and Dima want to buy two n-tier cakes. Each cake should consist of n different tiers: from the size of 1 to the size of n. Tiers should go in order from the smallest to the biggest (from top to bottom). They live on the same street, there are 2 ⋅ n houses in a row from left to right. Each house has a pastry shop...
1
n=int(input()) l=list(map(int,raw_input().split())) d={} q=[(0,0)] p=[(0,0)] for i in xrange(len(l)): key=l[i] if key not in d: d[key]=1 q.append((l[i],i)) else: p.append((l[i],i)) q.sort() p.sort() ans=0 for i in xrange(len(q)-1): u=abs(q[i][1]-q[i+1][1]) ans+=u for i in xra...
There are N squares aligned in a row. The i-th square from the left contains an integer a_i. Initially, all the squares are white. Snuke will perform the following operation some number of times: * Select K consecutive squares. Then, paint all of them white, or paint all of them black. Here, the colors of the squares...
3
N,K = map(int,input().split()) a = list(map(int,input().split())) psum = 0 for i in a: if i > 0: psum += i nsum = 0 for i in range(K): nsum += a[i] if a[i] > 0: psum -= a[i] ans = max( psum + nsum , psum ) for i in range(N - K): nsum -= a[i] if a[i] > 0: psum += a[...
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm: * if the last digit of the number is non-zero, she decreases the number by one; * if the last digit of the number is ze...
3
s = input() s = s.split(' ') n = int(s[0]) k = int(s[1]) i = 0 while i < k: if n % 10 == 0: n = n / 10 else: n -= 1 i+= 1 n = int(n) 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...
3
k = 10**9 x, y = divmod(-int(input()), k) print(0, 0, 1, k, -x, y)
Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game. Rules of the game are very simple: at first number of rounds n is defined. I...
3
n = int(input()) sx = 0 sy = 0 for i in range(0, n): x,y=map(int,input().split()) sx+= x>y sx -= x<y if sx>0: print('Mishka') else: print('Chris' if sx<0 else "Friendship is magic!^^")
You are given a string s consisting of n lowercase Latin letters. Polycarp wants to remove exactly k characters (k ≤ n) from the string s. Polycarp uses the following algorithm k times: * if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; * if th...
3
from collections import defaultdict from re import sub n, k = [int(inp) for inp in input().split()] s = input() alphabet = 'abcdefghijklmnopqrstuvwxyz' mapping = defaultdict(int) for char in s: mapping[char] += 1 for char in alphabet: if k <= 0: break tmp = min(k, mapping[char]) k -= tmp if ...
You are given two positive integers n and k. Print the k-th positive integer that is not divisible by n. For example, if n=3, and k=7, then all numbers that are not divisible by 3 are: 1, 2, 4, 5, 7, 8, 10, 11, 13 .... The 7-th number among them is 10. Input The first line contains an integer t (1 ≤ t ≤ 1000) — the ...
3
t = int(input()) elem = [] res = [] for i in range(t): elem.append(list(map(int, input().split()))) for n, k in elem: m = n - 1 s, o = k // m, k % m if k % (n - 1) != 0: res = s * n + o else: res = s * n - 1 print(res)
You are given two lists of segments [al_1, ar_1], [al_2, ar_2], ..., [al_n, ar_n] and [bl_1, br_1], [bl_2, br_2], ..., [bl_n, br_n]. Initially, all segments [al_i, ar_i] are equal to [l_1, r_1] and all segments [bl_i, br_i] are equal to [l_2, r_2]. In one step, you can choose one segment (either from the first or fro...
3
import sys input = sys.stdin.readline t = int(input()) for _ in range(t): n, k = map(int, input().split()) l1, r1 = map(int, input().split()) l2, r2 = map(int, input().split()) intersect_length = min(r1, r2) - max(l1, l2) length = max(r1, r2) - min(l1, l2) ans = 0 cost = 0 if inte...
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
n = int(input()) k = 0 for _ in range(n): p, q = map(int, input().split()) if p + 2 <= q: k += 1 print(k)
DZY has a hash table with p buckets, numbered from 0 to p - 1. He wants to insert n numbers, in the order they are given, into the hash table. For the i-th number xi, DZY will put it into the bucket numbered h(xi), where h(x) is the hash function. In this problem we will assume, that h(x) = x mod p. Operation a mod b d...
3
def main_function(): p, n = [int(i) for i in input().split(" ")] hash_table = [0 for i in range(p)] korea = False japan = 0 for i in range(1, n + 1): b = int(input()) if hash_table[b % p] == 1: korea = True japan = i break else: ...
Bash wants to become a Pokemon master one day. Although he liked a lot of Pokemon, he has always been fascinated by Bulbasaur the most. Soon, things started getting serious and his fascination turned into an obsession. Since he is too young to go out and catch Bulbasaur, he came up with his own way of catching a Bulbas...
1
def main(): string = str(raw_input()) s = "Bulbasaur" freq = {} for l in s: freq[l] = 0 for letter in string: if letter in freq.keys(): freq[letter]+=1 freq["u"]/=2 freq["a"]/=2 values = freq.values() print min(values) if __name__ == '__main__': main...
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...
3
a, b = [int(i) for i in input().split()] path = [b] error = False while b > a: if b % 2 == 0: b = b // 2 else: if str(b)[-1] == '1': b = (b - 1) // 10 else: error = True break path.append(b) if b == a and not error: print("YES") print(len...
You are given an equation: Ax2 + Bx + C = 0. Your task is to find the number of distinct roots of the equation and print all of them in ascending order. Input The first line contains three integer numbers A, B and C ( - 105 ≤ A, B, C ≤ 105). Any coefficient may be equal to 0. Output In case of infinite root cou...
3
a,b,c = [int(x) for x in input().split()] if a == 0 and b == 0 and c == 0: print(-1) elif a == 0: if b == 0: print(0) else: print(1) print(-c/b) else: disc = b**2 - 4*a*c denom = 2*a if disc == 0: print(1) print(-b/denom) elif disc < 0: print(...
One day Sasha visited the farmer 2D and his famous magnetic farm. On this farm, the crop grows due to the influence of a special magnetic field. Maintaining of the magnetic field is provided by n machines, and the power of the i-th machine is a_i. This year 2D decided to cultivate a new culture, but what exactly he d...
3
n = int(input()) a = list(sorted([int(x) for x in input().split()])) mmm = 0 for i in range(1, n): for j in range(2, a[i] - 1): if a[i] % j == 0: mmm = max(mmm, (j - 1) * (a[i] // j) - j * a[0] + a[0]) print(sum(a) - mmm)
Your company was appointed to lay new asphalt on the highway of length n. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing. Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are ...
3
import math t = int(input()) for test in range(t): [n, g, b] = [int(x) for x in input().split(' ')] d = math.ceil(n / 2) res = d q = d // g r = d % g if r != 0: res += b * q else: if b >= g: res += b * (q - 1) else: res = n print(max(res, ...
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Let next(x) be the minimum lucky number which is larger than or equals x. Petya is interested what i...
3
def lucky_gen(): current = ['4'] while True: yield int(''.join(current)) for i in range(len(current)-1, -1, -1): if current[i] == '4': current[i] = '7' break else: current[i] = '4' if i == 0: ...
The Little Elephant loves Ukraine very much. Most of all he loves town Rozdol (ukr. "Rozdil"). However, Rozdil is dangerous to settle, so the Little Elephant wants to go to some other town. The Little Elephant doesn't like to spend much time on travelling, so for his journey he will choose a town that needs minimum ti...
3
n=int(input()) A=list(map(int,input().split())) if(len(A)==1): print(1) else: X=sorted(A) if(X[0]==X[1]): print("Still Rozdil") else: print(A.index(X[0])+1)
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it: * deletes all the vowels, * inserts a character "." before each consonant, * repl...
3
a=input().lower() b='aeiouy' c=[] for i in a: if i not in b: c.append('.') c.append(i) print("".join(c))
Innokentiy decides to change the password in the social net "Contact!", but he is too lazy to invent a new password by himself. That is why he needs your help. Innokentiy decides that new password should satisfy the following conditions: * the length of the password must be equal to n, * the password should con...
3
import sys n,k = input().split() n=int(n) k=int(k) s="" x=k for i in range(n): if k>0: s=s+chr(97+i) k-=1 else: for j in range(x): s=s+chr(97+j) j+=1 if len(s)==n: print(s) sys.exit() print(s)
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
a=int(input()) b=list(map(int,input().split())) isEasy = True for i in b: if i==1: isEasy = False break if isEasy: print('EASY') else: print('HARD')
Little X has met the following problem recently. Let's define f(x) as the sum of digits in decimal representation of number x (for example, f(1234) = 1 + 2 + 3 + 4). You are to calculate <image> Of course Little X has solved this problem quickly, has locked it, and then has tried to hack others. He has seen the foll...
1
a = input() s = 10**17 p = (45 * 18 * s + 1) % a print (1 + (a - p)), (s * 10 + (a - p))
You are at a water bowling training. There are l people who play with their left hand, r people, who play with their right hand, and a ambidexters, who can play with left or right hand. The coach decided to form a team of even number of players, exactly half of the players should play with their right hand, and exactl...
3
l,f,a = map(int,input().split()) m = min(l,f) M = max(l,f) if m + a >= M: rem = (a- M + m)//2 team = M + rem else: team = m + a print (2*team)
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()) X=N+1 if(N%2==0): print(X//2) else: print((X//2)*(-1))
Once upon a time, Oolimry saw a suffix array. He wondered how many strings can produce this suffix array. More formally, given a suffix array of length n and having an alphabet size k, count the number of strings that produce such a suffix array. Let s be a string of length n. Then the i-th suffix of s is the subst...
1
from collections import Counter, defaultdict, deque import bisect from sys import stdin, stdout from itertools import permutations import math import timeit import random def inp(force_list=False): re = map(int, raw_input().split()) if len(re) == 1 and not force_list: return re[0] return re def in...
Allen wants to enter a fan zone that occupies a round square and has n entrances. There already is a queue of a_i people in front of the i-th entrance. Each entrance allows one person from its queue to enter the fan zone in one minute. Allen uses the following strategy to enter the fan zone: * Initially he stands...
3
n = int(input()) i = 0 ans = 1000000000000000000 for x in map(int, input().split()): if i >= x: ans = i + 1 break tmp = ((x - i) // n) + 1 if (x - i) % n else ((x - i) // n) t = tmp * n + i + 1 ans = ans if ans < t else t i += 1 ans %= n if ans == 0: ans = n print(ans) ...
Katie, Kuro and Shiro are best friends. They have known each other since kindergarten. That's why they often share everything with each other and work together on some very hard problems. Today is Shiro's birthday. She really loves pizza so she wants to invite her friends to the pizza restaurant near her house to cele...
3
n=int(input()) if(n%2==0 and n!=0): print(n+1) else: print ((n+1)//2)
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
x=int(input("")) #number of word list1=[] for i in range(x): word=input("") list1.append(word) for i in list1: y=len(i) if y > 10: z = i.split() for n in z: print(n[0]+str(y-2)+n[-1]) else: print(i)
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
n = int(input()) r = 0 while n>0: r += 1 if n>5: n -= 5 else: break print(r)
You received a notebook which is called Death Note. This notebook has infinite number of pages. A rule is written on the last page (huh) of this notebook. It says: "You have to write names in this notebook during n consecutive days. During the i-th day you have to write exactly a_i names.". You got scared (of course yo...
3
n, m = map(int, input().split()) a = list(map(int, input().split())) left = m for x in a: turn = 0 if x < left: left -= x else: x -= left turn = 1 + x // m left = m - x % m print(turn, end= ' ') print()
After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum nu...
3
n = int(input()) p = [0, 0, 0, 0, 0] for v in map(int, input().split()): p[v] += 1 ans = p[4] x = min(p[3], p[1]) p[3] -= x p[1] -= x ans += x + p[3] ans += int(p[2] / 2) p[2] %= 2 ans += p[2] ans += int((max(0, p[1] - p[2] * 2) + 3) / 4) print(ans)
You are locked in a room with a door that has a keypad with 10 keys corresponding to digits from 0 to 9. To escape from the room, you need to enter a correct code. You also have a sequence of digits. Some keys on the keypad have fingerprints. You believe the correct code is the longest not necessarily contiguous subse...
3
n = [int(i) for i in input().split()] l = [int(i) for i in input().split()] l1 = [int(i) for i in input().split()] ans="" for i in l: if i in l1: ans += str(i)+" " print(ans)
You are given a string s of length n, which consists only of the first k letters of the Latin alphabet. All letters in string s are uppercase. A subsequence of string s is a string that can be derived from s by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD...
3
n, k = map(int, input().split()) s = input() upper = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")[:k] d = dict() for u in upper: d[u] = 0 for l in s: d[l] += 1 print(min(d.values()) * k)
Let's call a list of positive integers a_0, a_1, ..., a_{n-1} a power sequence if there is a positive integer c, so that for every 0 ≤ i ≤ n-1 then a_i = c^i. Given a list of n positive integers a_0, a_1, ..., a_{n-1}, you are allowed to: * Reorder the list (i.e. pick a permutation p of \{0,1,...,n - 1\} and change...
3
import sys import math,bisect sys.setrecursionlimit(10 ** 5) from collections import defaultdict from itertools import groupby,accumulate from heapq import heapify,heappop,heappush from collections import deque,Counter,OrderedDict def I(): return int(sys.stdin.readline()) def neo(): return map(int, sys.stdin.readline()...
Vasily the Programmer loves romance, so this year he decided to illuminate his room with candles. Vasily has a candles.When Vasily lights up a new candle, it first burns for an hour and then it goes out. Vasily is smart, so he can make b went out candles into a new candle. As a result, this new candle can be used like...
3
n = list(map(int, input().strip().split())) h =0 p =n[0] while(p!=0): h = h+1 p = p-1 if(h%n[1] == 0): p =p+1 print(h)
The numbers of all offices in the new building of the Tax Office of IT City will have lucky numbers. Lucky number is a number that consists of digits 7 and 8 only. Find the maximum number of offices in the new building of the Tax Office given that a door-plate can hold a number not longer than n digits. Input The on...
3
ans=0 for i in range(1,int(input())+1): x=2**i ans+=x print(ans)
You are given two integers A and B. Find the largest value among A+B, A-B and A \times B. Constraints * -1000 \leq A,B \leq 1000 * All values in input are integers. Input Input is given from Standard Input in the following format: A B Output Print the largest value among A+B, A-B and A \times B. Examples Inp...
3
# A a, b = map(int, input().split()) print(max(a+b, a-b, a*b))
You are given a string s consisting of n lowercase Latin letters. Let's define a substring as a contiguous subsegment of a string. For example, "acab" is a substring of "abacaba" (it starts in position 3 and ends in position 6), but "aa" or "d" aren't substrings of this string. So the substring of the string s from po...
3
def main(): n = int(input()) s = input() for i in range(1,n): if(s[i]<s[i-1]): print("YES") print(str(i)+' '+str(i+1)) return print("NO") return main()
A permutation of length n is an array p=[p_1,p_2,...,p_n], which contains every integer from 1 to n (inclusive) and, moreover, each number appears exactly once. For example, p=[3,1,4,2,5] is a permutation of length 5. For a given number n (n ≥ 2), find a permutation p in which absolute difference (that is, the absolut...
3
import bisect import os from collections import Counter import bisect from collections import defaultdict import math import random import heapq as hq from math import sqrt import sys from functools import reduce, cmp_to_key from collections import deque import threading from itertools import combinations from io impor...
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,B,K=map(int,input().split(' ')) l=[A,B] for i in range(K): p=l[i%2] l[i%2] = (p-(p%2))/2 l[(i+1)%2] += (p-(p%2))/2 print(' '.join([str(int(x)) for x in l]))
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
n = int(input()) a = list(map(int,input().strip().split(' '))) maxi = 0 mini = n r = min(a) l = max(a) i = n-1 flag1 = 0 flag2 = 0 while i >= 0: if r in a[i:n] and flag1 == 0: flag1 = 1 maxi = i - a[i:n].index(r) if l in a[0:n-i] and flag2 == 0: mini = a[0:n-i].index(l) flag2 = 1...
Given is a string S consisting of `L` and `R`. Let N be the length of S. There are N squares arranged from left to right, and the i-th character of S from the left is written on the i-th square from the left. The character written on the leftmost square is always `R`, and the character written on the rightmost square...
3
s = input() res = [0] * len(s) cnt = 0 for i in range(len(s)): if s[i] == "R": cnt += 1 else: res[i-1] += (cnt+1)//2 res[i] += cnt//2 cnt = 0 cnt = 0 for i in range(1, len(s)+1): if s[-i] == "L": cnt += 1 else: res[-i] += cnt//2 res[-i+1] += (cnt+1...
Recently Vova found n candy wrappers. He remembers that he bought x candies during the first day, 2x candies during the second day, 4x candies during the third day, ..., 2^{k-1} x candies during the k-th day. But there is an issue: Vova remembers neither x nor k but he is sure that x and k are positive integers and k >...
3
n=int(input()) for i in range(n): a=int(input()) k=2 j=0 while(True): m=2**k if(a%(m-1)==0): break k=k+1 print(a//(m-1))
Takahashi will do a tap dance. The dance is described by a string S where each character is `L`, `R`, `U`, or `D`. These characters indicate the positions on which Takahashi should step. He will follow these instructions one by one in order, starting with the first character. S is said to be easily playable if and onl...
3
s = input() print("Yes" if s[::2].count("L") + s[1::2].count("R") == 0 else "No")
You are given a permutation p_1, p_2, ..., p_n. Recall that sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once. Find three indices i, j and k such that: * 1 ≤ i < j < k ≤ n; * p_i < p_j and p_j > p_k. Or say that there are no such indices. Input The first lin...
3
a=int(input()) for i in range(0,a): n=a=int(input('')) l=list(map(int,input().split())) f=False for i in range(1,n-1): if l[i]>l[i-1] and l[i]>l[i+1]: f=True break if f: i+=1 print("YES") print(i-1,i,i+1) else: print("NO")
You are given a positive number x. Find the smallest positive integer number that has the sum of digits equal to x and all digits are distinct (unique). Input The first line contains a single positive integer t (1 ≤ t ≤ 50) — the number of test cases in the test. Then t test cases follow. Each test case consists of ...
3
""" pppppppppppppppppppp ppppp ppppppppppppppppppp ppppppp ppppppppppppppppppppp pppppppp pppppppppppppppppppppp pppppppppppppppppppppppppppppppp pppppppppppppppppppp...
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the...
3
line=input().split() n=int(line[0]) h=int(line[1]) s=input() data=[int(a) for a in s.split()] i=0 w=0 while i<len(data): if data[i]<=h: w=w+1 i=i+1 else: w=w+2 i=i+1 print(w)
You are given a string s and should process m queries. Each query is described by two 1-based indices li, ri and integer ki. It means that you should cyclically shift the substring s[li... ri] ki times. The queries should be processed one after another in the order they are given. One operation of a cyclic shift (rota...
1
s = raw_input() m = int(raw_input()) def shift(l, r, k): global s length = (r-l+1) modulo = k % length res = s[r-modulo:r] + s[l-1:r-modulo] s = s[:l-1] + res + s[r:] for i in xrange(m): l, r, k = map(int, raw_input().split()) shift(l, r, k) print s
[The Duck song](https://www.youtube.com/watch?v=MtN1YnoL46Q) For simplicity, we'll assume that there are only three types of grapes: green grapes, purple grapes and black grapes. Andrew, Dmitry and Michal are all grapes' lovers, however their preferences of grapes are different. To make all of them happy, the followi...
3
x,y,z=[int(j) for j in input().split(' ')] a,b,c=[int(j) for j in input().split(' ')] t=a+b+c k=0 if a<x: k=-1 else: t-=x if t-c<y: k=-1 t-=y if(t<z): k=-1 if k!=-1: print("YES") else: print("NO")
Vasya thinks that lucky tickets are the tickets whose numbers are divisible by 3. He gathered quite a large collection of such tickets but one day his younger brother Leonid was having a sulk and decided to destroy the collection. First he tore every ticket exactly in two, but he didn’t think it was enough and Leonid a...
3
n = int(input()) l = map(int, input().split()) resto0, resto1, resto2 = 0, 0, 0 for i in l: resto = i % 3 if resto == 0: resto0 += 1 elif resto == 1: resto1 += 1 else: resto2 += 1 r = int(resto0 / 2) r += (resto1 if resto1 < resto2 else resto2) print(r) # 1490050692425
You are given two integers a and b. In one move, you can choose some integer k from 1 to 10 and add it to a or subtract it from a. In other words, you choose an integer k ∈ [1; 10] and perform a := a + k or a := a - k. You may use different values of k in different moves. Your task is to find the minimum number of mo...
3
t=int(input()) for i in range(t): a,b=input().split() a=int(a) b=int(b) if(a==b): print("0") else: diff=abs(a-b) if(a<b): temp=a a=b b=temp ct=0 i=10 while(diff!=0 and i>=1): if(diff>=i): ...
Let's call a string a phone number if it has length 11 and fits the pattern "8xxxxxxxxxx", where each "x" is replaced by a digit. For example, "80123456789" and "80000000000" are phone numbers, while "8012345678" and "79000000000" are not. You have n cards with digits, and you want to use them to make as many phone n...
3
n = int(input()) m = input() f = m.count('8',0,len(m)) if 11*f < n: print(f) else: print(n // 11)
Takahashi, who is A years old, is riding a Ferris wheel. It costs B yen (B is an even number) to ride the Ferris wheel if you are 13 years old or older, but children between 6 and 12 years old (inclusive) can ride it for half the cost, and children who are 5 years old or younger are free of charge. (Yen is the currenc...
3
a,b=map(int,input().split()) print(b if 12<a else b//2 if 5<a else 0)
You've got a 5 × 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix: 1....
3
a = [[i for i in input().split()] for _ in range(5)] for i in range(5): for j in range(5): if a[i][j] == '1': print(abs(i-2) + abs(j-2)) break
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the oppo...
3
n = int(input("")) mag = [] mis_c = 0 for i in range(n): s = input("") mag.append(s) if (i>0 and mag[i-1]!=s): mis_c +=1 print (mis_c+1)
Today at the lesson of mathematics, Petya learns about the digital root. The digital root of a non-negative integer is the single digit value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-d...
3
n=int(input()) for i in range(n): a=input() a=a.split() print(int(a[1])+9*(int(a[0])-1))