problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word. Hongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character ...
3
s = input() a = set() for i in range(len(s)): a.add(s) s = s[-1] + s[:-1] print(len(a))
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
3
n=int(input()) for i in range(n): word=input() ans=word if len(word)>10: ans=word[0]+str(len(word)-2)+word[-1] print(ans)
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
n, k = [int(x) for x in input().split(' ')] for i in range(k): if n % 10 == 0: n /= 10 else: n -= 1 print(int(n))
For given two segments s1 and s2, print "1" if they are intersect, "0" otherwise. s1 is formed by end points p0 and p1, and s2 is formed by end points p2 and p3. Constraints * 1 ≤ q ≤ 1000 * -10000 ≤ xpi, ypi ≤ 10000 * p0 ≠ p1 and p2 ≠ p3. Input The entire input looks like: q (the number of queries) 1st query 2n...
3
from typing import Tuple def cross(a: Tuple[int, int], b: Tuple[int, int]) -> float: return float(a[0] * b[1] - a[1] * b[0]) if __name__ == "__main__": q = int(input()) for _ in range(q): x_p0, y_p0, x_p1, y_p1, x_p2, y_p2, x_p3, y_p3 = map(lambda x: int(x), ...
A magic island Geraldion, where Gerald lives, has its own currency system. It uses banknotes of several values. But the problem is, the system is not perfect and sometimes it happens that Geraldionians cannot express a certain sum of money with any set of banknotes. Of course, they can use any number of banknotes of ea...
3
n = int(input()) notes = input().split(' ') available_nums = set() for i in range (n): available_nums.add(notes[i]) if '1' in notes: print(-1) else: print(1)
There is a cave. The cave has N rooms and M passages. The rooms are numbered 1 to N, and the passages are numbered 1 to M. Passage i connects Room A_i and Room B_i bidirectionally. One can travel between any two rooms by traversing passages. Room 1 is a special room with an entrance from the outside. It is dark in th...
3
N, M = map(int, input().split()) node =[[] for _ in range(N)] for _ in range(M): x, y = map(int, input().split()) node[x-1].append(y-1) node[y-1].append(x-1) ct = [-1]*N i = 0 stack = [] ct[0] = 0 stack.append(0) while len(stack) != 0: v = stack.pop(0) for e in node[v]: if ct[e] == -1: ct[e] = v ...
A string is called a KEYENCE string when it can be changed to `keyence` by removing its contiguous substring (possibly empty) only once. Given a string S consisting of lowercase English letters, determine if S is a KEYENCE string. Constraints * The length of S is between 7 and 100 (inclusive). * S consists of lowerc...
3
s=input() x=len(s)-7 for i in range(7): if s[:i]+s[x+i:] == "keyence": print("YES") break else: print("NO")
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 * t = int(input()) rA = [] for z in range(t): n = int(input()) a, b, c = [int(i) for i in input().split()] bob = [i for i in input()] cr, rp, cs = 0, 0, 0 cr = bob.count('R') cp = bob.count('P') cs = bob.count('S') dR = b - cr dP = c - cp dS = a - cs s = 0 ...
Codeforces user' handle color depends on his rating — it is red if his rating is greater or equal to 2400; it is orange if his rating is less than 2400 but greater or equal to 2200, etc. Each time participant takes part in a rated contest, his rating is changed depending on his performance. Anton wants the color of hi...
1
n = input() l = [] sl = [] for i in range(n): sl = raw_input().split(" ") sl[1] = int(sl[1]) sl[2] = int(sl[2]) l.append(sl) sl = [] flag = 0 for i in range(n): if l[i][1]<l[i][2] and l[i][1]>=2400: flag = 1 if flag: print "YES" else: print "NO"
Little Petya was given this problem for homework: You are given function <image> (here <image> represents the operation of taking the remainder). His task is to count the number of integers x in range [a;b] with property f(x) = x. It is a pity that Petya forgot the order in which the remainders should be taken and wr...
1
I=lambda:map(int, raw_input().split()) import itertools p = I() a = list(itertools.permutations([p[0],p[1],p[2],p[3]])) def isOk(n): cnt = 0 for x in a: z = n for y in x: z = z % y if z == n: cnt += 1 if cnt >= 7: return True return False ans = 0 for x in xrang...
Ringo is giving a present to Snuke. Ringo has found out that Snuke loves yakiniku (a Japanese term meaning grilled meat. yaki: grilled, niku: meat). He supposes that Snuke likes grilled things starting with `YAKI` in Japanese, and does not like other things. You are given a string S representing the Japanese name of ...
1
s = (raw_input()) if s.startswith('YAKI'): print "Yes" else: print "No"
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...
3
# URL: http://codeforces.com/problemset/problem/579/A def parse_input() -> int: return int(input()) def solve(n: int) -> int: return bin(n)[2:].count('1') if __name__ == '__main__': print(solve(parse_input()))
Numbers 1, 2, 3, ... n (each integer from 1 to n once) are written on a board. In one operation you can erase any two numbers a and b from the board and write one integer (a + b)/(2) rounded up instead. You should perform the given operation n - 1 times and make the resulting number that will be left on the board as s...
3
t=int(input()) for i in range(t): n = int(input()) a = [] for j in range(1, n+1): a.append(j) print(2) print(a.pop(n-1), end=' ') print(a.pop(n-3)) a.append(n-1) for k in range(n-2): x1 = a.pop() x2 = a.pop() print(x1, end=' ') print(x2) a...
Colonel has n badges. He wants to give one badge to every of his n soldiers. Each badge has a coolness factor, which shows how much it's owner reached. Coolness factor can be increased by one for the cost of one coin. For every pair of soldiers one of them should get a badge with strictly higher factor than the secon...
1
n = int(raw_input()) badges = map(int, raw_input().split()) badges.sort() count = 0 aux = [] obj = {} for i in badges: obj[i] = 'a' for i in xrange(len(badges) - 1): if badges[i] == badges[i+1]: aux.append((badges[i], i)) for i in aux: a = i[0] while obj.get(a) == 'a': count += 1 a += 1 badges[i[1]] = a ob...
Nash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the n× n board. Rows and columns of this board are numbered from 1 to n. The cell on the intersection of the r-th row and c-th...
3
from collections import deque n = int(input()) d = [[0] * n for _ in range(n)] for r in range(n): nums = list(map(int, input().split())) i = 0 while i + 1 < 2 * n: d[r][i // 2] = (nums[i], nums[i + 1]) i += 2 result = [[None] * n for _ in range(n)] def bfs(rs, cs, val): queue = deque(...
You are given a string s consisting of n lowercase Latin letters. You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation. String s = s_1 s_2 ... s_n is lexicograp...
3
N=int(input()) S=input() tam=len(S) S+=chr(ord(S[tam-1])+1) for pos in range(tam): if S[pos]>S[pos+1]: break ans=S[0:pos]+S[pos+1:tam] print(ans)
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc....
3
str1 = input() str2 = list(map(str, input())) str2.reverse() if str1 == ''.join(str2): print("YES") else: print("NO")
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had a red socks and b blue socks. According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot. Every day Vasya puts on new socks in the morning and ...
3
inp=input().split() a=int(inp[0]) b=int(inp[1]) fash=0 c=True while c==True: if a==0 or b==0: break a=a-1 b=b-1 fash+=1 total=a+b print(fash,(total//2))
Three friends are going to meet each other. Initially, the first friend stays at the position x = a, the second friend stays at the position x = b and the third friend stays at the position x = c on the coordinate axis Ox. In one minute each friend independently from other friends can change the position x by 1 to the...
3
from sys import stdin read = stdin.readline def main(): cases = int(read()) for case in range(cases): nums = list(map(int, read().strip().split())) x = sum(nums)/3 for i in range(len(nums)): num = nums[i] if abs((num+1)-x) < abs(num-x): nums[i] += 1 ...
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
ans=0 for i in range(1,6): m=list(input().split()) if '1'in m: a=i for j in range(len(m)): if m[j]=='0': ans+=1 else: break j=abs(ans-2) i=abs(a-3) if a!=3: k=j+i else: k=j if k>0: print(k) else: print(-k)
Polycarp and his friends want to visit a new restaurant. The restaurant has n tables arranged along a straight line. People are already sitting at some tables. The tables are numbered from 1 to n in the order from left to right. The state of the restaurant is described by a string of length n which contains characters ...
3
for _ in range(int(input())): n,k=list(map(int,input().split())) s=input() if s=="0"*n: c=0 for i in range(0,n,k+1): c+=1 print(c) continue ind=[i for i in range(n) if s[i]=="1"] c=0 for i in range(len(ind)-1): nex=ind[i+1] for j i...
You are given three positive integers n, a and b. You have to construct a string s of length n consisting of lowercase Latin letters such that each substring of length a has exactly b distinct letters. It is guaranteed that the answer exists. You have to answer t independent test cases. Recall that the substring s[l ...
3
t = int(input()) str = 'abcdefghijklmnopqrstuvwxyz' while t: n, a, b = map(int, input().split()) res='' while n>0: if n>b: k = b else: k = n res += str[0:k:1] n-=b print(res) t-=1
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had a red socks and b blue socks. According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot. Every day Vasya puts on new socks in the morning and ...
3
a, b = map(int, input().split()) z = min(a, b) v = (max(a, b) - z) // 2 print(z, v)
A bracket sequence is a string that is one of the following: 1. An empty string; 2. The concatenation of `(`, A, and `)` in this order, for some bracket sequence A ; 3. The concatenation of A and B in this order, for some non-empty bracket sequences A and B / Given are N strings S_i. Can a bracket sequence be forme...
3
n = int(input()) plus_bracket = [] minus_bracket = [] for _ in range(n): mini = 0 cur = 0 for bracket in input(): if bracket == '(': cur += 1 else: cur -= 1 if cur < mini: mini = cur if cur > 0: plus_bracket.append([-mini, cur]) else: minus_bracket.append([cur - mini, -c...
You are given a non-decreasing array of non-negative integers a_1, a_2, …, a_n. Also you are given a positive integer k. You want to find m non-decreasing arrays of non-negative integers b_1, b_2, …, b_m, such that: * The size of b_i is equal to n for all 1 ≤ i ≤ m. * For all 1 ≤ j ≤ n, a_j = b_{1, j} + b_{2, j}...
3
for _ in range(int(input())): n,k=map(int,input().split()) l=sorted(set(map(int,input().split()))) if len(l)>1 and k==1:print(-1);continue if k>=len(l):print(1);continue print(-((1-len(l))//(k-1)))
In the final of CODE FESTIVAL in some year, there are N participants. The height and power of Participant i is H_i and P_i, respectively. Ringo is hosting a game of stacking zabuton (cushions). The participants will line up in a row in some order, and they will in turn try to add zabuton to the stack of zabuton. Init...
3
N = int(input()) HP = [tuple(map(int,input().split())) for _ in range(N)] HP.sort(key=lambda x: sum(x)) INF = float('inf') dp = [0] maxj = 0 for i,(h,p) in enumerate(HP): dp2 = [INF] * (maxj + 2) for j in range(maxj,-1,-1): dp2[j] = min(dp2[j], dp[j]) if dp[j] <= h: dp2[j+1] = min(dp2[j+1], dp[j] + p) if j...
Easy and hard versions are actually different problems, so we advise you to read both statements carefully. You are given a weighted rooted tree, vertex 1 is the root of this tree. Also, each edge has its own cost. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A paren...
3
import os import sys from io import BytesIO, IOBase # region fastio 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 file.mode self.write = self.buffer.wri...
There are two sisters Alice and Betty. You have n candies. You want to distribute these n candies between two sisters in such a way that: * Alice will get a (a > 0) candies; * Betty will get b (b > 0) candies; * each sister will get some integer number of candies; * Alice will get a greater amount of candie...
3
t = int(input()) for i in range(t): n = int(input()) print(n//2 if n%2 == 1 else n//2-1)
Polycarpus has a ribbon, its length is n. He wants to cut the ribbon in a way that fulfils the following two conditions: * After the cutting each ribbon piece should have length a, b or c. * After the cutting the number of ribbon pieces should be maximum. Help Polycarpus and find the number of ribbon pieces ...
3
n, a, b, c = map(int, input().split()) arr = sorted([a, b, c]) res = -1 for i in range(n//arr[0], -1, -1): for j in range((n-i*arr[0])//arr[1], -1, -1): if (n-i*arr[0]-j*arr[1])%arr[2]==0: k = (n-i*arr[0]-j*arr[1]) // arr[2] res = max(res, i+j+k) break print(res)
Vadim and Roman like discussing challenging problems with each other. One day Vadim told his friend following problem: Given N points on a plane. Each point p is defined by it's two integer coordinates — px and py. The distance between points a and b is min(|ax - bx|, |ay - by|). You should choose a starting point and...
1
def f(N): a = 0 for i in range(1,N+1): a = a^i return a for i in range(input()): N = input() print f(N) for _ in range(N): k = raw_input().split()
A permutation is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as pi. We'll call number n the size of permutation p1, p2, ..., pn. Nickolas adores permutations. He likes some permutations more than the o...
3
n=int(input()) if(n%2!=0): print(-1) else: for i in range(1,n+1): if(i%2!=0): print(i+1,i,end=" ")
You are given a string s consisting of exactly n characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings. Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string ...
3
def ia(): n=input().split() return list(map(int,n)) def ic(): return list(input()) def ii(): return int(input()) n=int(ii()) k=int(n/3) s=ic() from collections import Counter d=Counter(s) a=d['0'] b=d['1'] c=d['2'] if(a==k and b==k and c==k): print(''.join(s)) else: if(c<k): if(b>k):...
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 m,n,a = [int(x) for x in input().split()] l=math.ceil(m/a) k=math.ceil(n/a) print(l*k)
T is playing a game with his friend, HL. There are n piles of stones, the i-th pile initially has a_i stones. T and HL will take alternating turns, with T going first. In each turn, a player chooses a non-empty pile and then removes a single stone from it. However, one cannot choose a pile that has been chosen in th...
3
import sys T = int(sys.stdin.readline().strip()) for t in range (0, T): n = int(sys.stdin.readline().strip()) a = list(map(int, sys.stdin.readline().strip().split())) if max(a) > sum(a) / 2: print('T') elif sum(a) % 2 == 1: print('T') else: print('HL')
Write a program which solve a simultaneous equation: ax + by = c dx + ey = f The program should print x and y for given a, b, c, d, e and f (-1,000 ≤ a, b, c, d, e, f ≤ 1,000). You can suppose that given equation has a unique solution. Input The input consists of several data sets, 1 line for each data set. In a ...
3
def Cramer(coef): deno = coef[0]*coef[4] - coef[1]*coef[3] return [(coef[2]*coef[4] - coef[1]*coef[5]) / deno, (coef[0]*coef[5] - coef[2]*coef[3]) / deno] while True: try: coeflist = [float(item) for item in input().split()] ans1, ans2 = Cramer(coeflist) if abs(ans1) < 1e-4: ans1 = 0.0 if abs(ans2) < 1e-...
Recently, you found a bot to play "Rock paper scissors" with. Unfortunately, the bot uses quite a simple algorithm to play: he has a string s = s_1 s_2 ... s_{n} of length n where each letter is either R, S or P. While initializing, the bot is choosing a starting index pos (1 ≤ pos ≤ n), and then it can play any numbe...
3
t=int(input()) while(t): z=input() n=len(z) r,s,p=0,0,0 for i in range(n): if z[i]=="R": r+=1 if z[i]=="P": p+=1 if z[i]=="S": s+=1 if r>=s and r>=p: for i in range(n): print("P",end="") elif p>=s and p>=r: f...
You are given a huge decimal number consisting of n digits. It is guaranteed that this number has no leading zeros. Each digit of this number is either 0 or 1. You may perform several (possibly zero) operations with this number. During each operation you are allowed to change any digit of your number; you may change 0...
3
def get_num(): return int(input()) def print_arr(arr: list): for val in arr: print(val) def read_num_list(): num_str = input() return [int(v) for v in num_str.split(' ')] n, x, y = read_num_list() s = input() wanted_str = '1' + ('0' * y) wanted_str = ('0' * (x - y - 1)) + wanted_str s_trunc = s[n-x:] an...
Alice and Bob play a game. They have a binary string s (a string such that each character in it is either 0 or 1). Alice moves first, then Bob, then Alice again, and so on. During their move, the player can choose any number (not less than one) of consecutive equal characters in s and delete them. For example, if the...
3
import sys input = sys.stdin.readline t=int(input()) for tests in range(t): S=input().strip()+"0" L=[] NOW=0 for s in S: if s=="0": L.append(NOW) NOW=0 else: NOW+=1 L.sort(reverse=True) ANS=0 for i in range(0,len(L),2): ANS+=L...
HQ9+ is a joke programming language which has only four one-character instructions: * "H" prints "Hello, World!", * "Q" prints the source code of the program itself, * "9" prints the lyrics of "99 Bottles of Beer" song, * "+" increments the value stored in the internal accumulator. Instructions "H" and "Q"...
3
a=input() A=['H','Q','9'] j=0 for i in A: if i in a: j=1 if j==1: print('YES') else: print('NO')
The only difference between easy and hard versions is constraints. If you write a solution in Python, then prefer to send it in PyPy to speed up execution time. A session has begun at Beland State University. Many students are taking exams. Polygraph Poligrafovich is going to examine a group of n students. Students ...
3
import sys, os, io def rs(): return sys.stdin.readline().rstrip() def ri(): return int(sys.stdin.readline()) def ria(): return list(map(int, sys.stdin.readline().split())) def ws(s): sys.stdout.write(s + '\n') def wi(n): sys.stdout.write(str(n) + '\n') def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n') ...
One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning: a1, a2, ..., an → an, a1, a2, ..., an - 1. Help Twi...
3
n = list(map(int, input().split()))[0] a = list(map(int, input().split())) flag = 0 for i in range(1,n): if a[i] < a[i-1]: flag = i ans = True for i in range (flag+1,n-1): if a[i+1] < a[i] : ans = False for i in range (flag-1) : if a[i+1] < a[i] : ans = False if flag != 0 and a[n-1] > a[0] : ans = False ...
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line. Unfortunately, from time to ti...
1
comma_str = raw_input()[1:-1] if not comma_str or comma_str.isspace(): print 0 else: print len(set(map(str.strip, comma_str.split(','))))
One day, as Sherlock Holmes was tracking down one very important criminal, he found a wonderful painting on the wall. This wall could be represented as a plane. The painting had several concentric circles that divided the wall into several parts. Some parts were painted red and all the other were painted blue. Besides,...
3
a = int(input()) s = sorted(list(map(int,input().split()))) d = 0 f = 1 if (a % 2 != 0): s.append(0) s.reverse() sum1 = 0 while d < a : sum1 +=s[d]**2*3.141592 -s[f]**2*3.141592 d +=2 f +=2 print (abs(sum1))
Each evening after the dinner the SIS's students gather together to play the game of Sport Mafia. For the tournament, Alya puts candies into the box, which will serve as a prize for a winner. To do that, she performs n actions. The first action performed is to put a single candy into the box. For each of the remainin...
3
a,b=map(int,input().split()) if b==(a*(a+1))//2:print(0) else: c=0 for x in range(a): c+=x+1 if c-(a-x-1)==b:break print(a-x-1)
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y). Valera wants to place...
3
n,m,k=map(int,input().split()) curx,cury=1,1 flag=1 def construct(lim): cnt=0 global curx,cury,flag while cnt<lim: cnt+=1 if curx>n or cury>m: break if flag!=0: print(curx,cury,end=' ') cury+=1 if cury>m: flag=0 ...
The chef is preparing a birthday cake for one of his guests, and his decided to write the age of the guest in candles on the cake. There are 10 types of candles, one for each of the digits '0' through '9'. The chef has forgotten the age of the guest, however, so doesn't know whether he has enough candles of the right t...
1
t=int(raw_input()) #dict={'0':0,'1':0,'2':0,'3':0,'4':0,'5':0,'6':0,'7':0,'8':0,'9':0} for i in range(0,t): list=map(lambda x:int(x),raw_input().split()) m=min(list) for i in range(0,10): if list[i]==m: if i==0: for j in range(0,10): if list[j]==list[i] and i!=j: ...
Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yy...
3
if __name__ == '__main__': s, r = list(input()), [] for c in s: if r and c == r[-1]:r.pop() else:r.append(c) print("".join(r))
We have a grid with H horizontal rows and W vertical columns. Let (i,j) denote the square at the i-th row from the top and the j-th column from the left. The square (i, j) has two numbers A_{ij} and B_{ij} written on it. First, for each square, Takahashi paints one of the written numbers red and the other blue. Then...
3
def main(): H, W = map(int, input().split()) N = 80 * (H+W) // 2 A = [list(map(int, input().split())) for _ in range(H)] B = [list(map(int, input().split())) for _ in range(H)] dp = [[set() for _ in range(W+1)] for _ in range(2)] dp[0][1].add(0) def ltN(x): return x <= N for i in range(H...
A bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not. The teacher gave Dmitry's class a very strange task — she asked every student...
3
n = int(input()) s = input() c1 = s.count("(") c2 = s.count(")") if c1 != c2: print(-1) else: need = [0] * n cnt = 0 for i in range(n): if cnt < 0: need[i] = 1 if s[i] == "(": cnt += 1 elif s[i] == ")": cnt -= 1 else: print(...
Olesya loves numbers consisting of n digits, and Rodion only likes numbers that are divisible by t. Find some number that satisfies both of them. Your task is: given the n and t print an integer strictly larger than zero consisting of n digits that is divisible by t. If such number doesn't exist, print - 1. Input T...
3
n, t = map(int, input().split()) if t == 10: if n == 1: print(-1) else: print('1' * (n-1) + '0') else: print(str(t) * n)
Edogawa Conan got tired of solving cases, and invited his friend, Professor Agasa, over. They decided to play a game of cards. Conan has n cards, and the i-th card has a number ai written on it. They take turns playing, starting with Conan. In each turn, the player chooses a card and removes it. Also, he removes all c...
3
n = int(input()) a = list(map(int, input().split())) a.sort() a.append(-1) d2 = True x = 1 if n == 1: d2 = False for i in range(1, n + 1): if a[i] == a[i - 1]: x += 1 else: if x % 2 != 0: d2 = False x = 1 if not d2: print('Conan') else: print('Agasa')
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy...
3
m = int(input()) g = 0 a = 0 b = 0 for i in range (m): l=list(map(int, input().strip().split(" "))) g = g+l[0] a = a+l[1] b = b+l[2] if (g == 0 and a == 0 and b == 0): print("YES") else: print("NO")
You are given an undirected unweighted graph consisting of n vertices and m edges (which represents the map of Bertown) and the array of prices p of length m. It is guaranteed that there is a path between each pair of vertices (districts). Mike has planned a trip from the vertex (district) a to the vertex (district) b...
3
import io import os from collections import Counter, defaultdict, deque def bfs(source, graph): q = deque([source]) dist = {source: 0} while q: node = q.popleft() d = dist[node] for nbr in graph[node]: if nbr not in dist: dist[nbr] = d + 1 ...
n participants of the competition were split into m teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends. Your task is to write a program that will find the minimum and the maximum number of pairs of friends that could ha...
3
n, m = map(int, input().split()) if n == m: print("{} {}".format(0, 0)) exit() # ans1 def nc2(n): return n * (n - 1) // 2 ans1 = nc2(n - m + 1) # ans2 if n % m == 0: if n // m >= 2: ans2 = nc2(n // m) * m else: ans2 = 0 else: ans2 = nc2(n // m + 1) * (n % m) if n // m...
Vasya has become interested in wrestling. In wrestling wrestlers use techniques for which they are awarded points by judges. The wrestler who gets the most points wins. When the numbers of points of both wrestlers are equal, the wrestler whose sequence of points is lexicographically greater, wins. If the sequences of...
3
n = int(input()) import queue as queue points1 = 0 points2 = 0 lexical = True lexical_winning = -1 q1 = queue.Queue() q2 = queue.Queue() winner = -1 last = -1 for i in range(n): num = int(input()) last = num if num > 0: points1 += num if lexical: if q1.qsize() > 0: ...
Sasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table M with n rows and n columns such that M_{ij}=a_i ⋅ a_j where a_1, ..., a_n is some sequence of positive integers. Of course, the girl decided to take it to school with her. But while she was having lunch, hoolig...
3
#!/usr/bin/pypy3 from math import sqrt n = int(input()) l0 = [int(n) for n in input().split()] l1 = [int(n) for n in input().split()] v = int(sqrt(l0[1]*l0[2]*l1[2])) #a0*a1*a2 a0=v//l1[2] a1=l1[0]//a0 print(a0,a1,end=" ") for i in range(2,n): na = int(input().split()[0]) print(na//a0,end=" ")
Nikolay got a string s of even length n, which consists only of lowercase Latin letters 'a' and 'b'. Its positions are numbered from 1 to n. He wants to modify his string so that every its prefix of even length has an equal amount of letters 'a' and 'b'. To achieve that, Nikolay can perform the following operation arb...
3
x = int(input()) arr = list(input()) count = 0 ans = [] for i in range(0,x-1,2): temp =arr[i]+arr[i+1] if temp=='ab' or temp=='ba': ans.append(temp) elif temp=='bb' or temp=='aa': ans.append('ab') count+=1 print(count) print("".join(ans))
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
t = int(input()) for i in range(t): s = input() if len(s) > 10: print(f"{s[0]}{len(s)-2}{s[-1]}") else: print(s)
The student council is preparing for the relay race at the sports festival. The council consists of n members. They will run one after the other in the race, the speed of member i is s_i. The discrepancy d_i of the i-th stage is the difference between the maximum and the minimum running speed among the first i members...
3
#fi = open("task3.txt") #def input(): # return fi.readline() n = int(input()) s = [int(x) for x in input().split()] s.sort() dp = [0 for _ in range(n)] for l in range(1,n): dp_new = [0 for _ in range(n-l)] for i in range(n-l): dp_new[i] = min(dp[i],dp[i+1])+s[i+l]-s[i] dp = dp_new print(dp[0])
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second. One day in 230 AD Shapur was trying to find out if any one can possibly do...
1
a=str(raw_input()) b=str(raw_input()) x="" if(len(a)==len(b)): for i in range (len(a)): if(a[i]==b[i]): x=x+"0" else: x=x+"1" print(x)
Mountaineers Mr. Takahashi and Mr. Aoki recently trekked across a certain famous mountain range. The mountain range consists of N mountains, extending from west to east in a straight line as Mt. 1, Mt. 2, ..., Mt. N. Mr. Takahashi traversed the range from the west and Mr. Aoki from the east. The height of Mt. i is h_i...
3
n = int(input()) t = list(map(int, input().split(' '))) a = list(map(int, input().split(' '))) result = 1 for i in range(n): h_max, h_min = min(t[i], a[i])+1, 1 if i != n-1: if a[i] > a[i+1]: h_min = a[i] else: h_min = a[n-1] if i != 0: if t[i-1] < t[i]: ...
E869120 found a chest which is likely to contain treasure. However, the chest is locked. In order to open it, he needs to enter a string S consisting of lowercase English letters. He also found a string S', which turns out to be the string S with some of its letters (possibly all or none) replaced with `?`. One more t...
3
S = input() t = input() n = len(S) m = len(t) for i in range(n-m, -1, -1): t_ = S[i:i+m] for j in range(m+1): if j == m: print((S[:i] + t + S[i+m:]).replace('?', 'a')) exit() if t_[j] == '?': continue elif t_[j] != t[j]: break print('UNRESTORABLE')
A class of students wrote a multiple-choice test. There are n students in the class. The test had m questions, each of them had 5 possible answers (A, B, C, D or E). There is exactly one correct answer for each question. The correct answer for question i worth a_i points. Incorrect answers are graded with zero points....
3
n, m = map(int, input().split()) x = [[0] * 26 for _ in range(m)] for _ in range(n): s = input() for i in range(m): x[i][ord(s[i]) - ord('A')] += 1 a = list(map(int, input().split())) ans = 0 for i in range(m): ans += max(x[i]) * a[i] print(ans)
Tokitsukaze is one of the characters in the game "Kantai Collection". In this game, every character has a common attribute — health points, shortened to HP. In general, different values of HP are grouped into 4 categories: * Category A if HP is in the form of (4 n + 1), that is, when divided by 4, the remainder is ...
3
r=int(input()) if r % 4 == 2: print("1 B") elif r % 4 == 1: print("0 A") elif r % 4 == 0: print("1 A") else: print("2 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());m=0 for _ in range(n): l=list(map(int,input().split()));c=0 for i in l: if i==1: c+=1 if c>=2: m+=1 print(m)
Chef develops his own computer program for playing chess. He is at the very beginning. At first he needs to write the module that will receive moves written by the players and analyze it. The module will receive a string and it should report at first whether this string represents the correct pair of cells on the chess...
1
from sys import stdin for trial in xrange(int(stdin.readline())): s = raw_input() if len(s)==5: L=[ord(s[0])-96,ord(s[3])-96,ord(s[1])-48,ord(s[4])-48] if s[2]=='-' and all((i>0 and i<9) for i in L): print "Yes" if (abs(L[0]-L[1])*abs(L[2]-L[3])==2) else "No" continue ...
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
# -*- coding: utf-8 -*- """ Created on Mon Jun 8 18:56:36 2020 @author: Paras """ w = int(input()) if w%2==0 and w>=4: print("YES") else: print("NO")
We will create an artwork by painting black some squares in a white square grid with 10^9 rows and N columns. The current plan is as follows: for the i-th column from the left, we will paint the H_i bottommost squares and will not paint the other squares in that column. Before starting to work, you can choose at most K...
3
n,K = map(int,input().split()) a = [0]+list(map(int,input().split()))+[0] INF = float("inf") n += 1 dp = [[[INF for i in range(K+1)] for j in range(n+1)] for k in range(n+1)] dp[0][0][0] = 0 mx = 0 for i in range(1,n+1): x = a[i] for j in range(i): for k in range(1,min(K,i)+1): dp[i][j][k] = dp[i-1][j][k-...
You are given an array a of length n. You are also given a set of distinct positions p_1, p_2, ..., p_m, where 1 ≤ p_i < n. The position p_i means that you can swap elements a[p_i] and a[p_i + 1]. You can apply this operation any number of times for each of the given positions. Your task is to determine if it is poss...
1
t = int(input()) while t: t-=1 se = False n,m = map(int, raw_input().split()) arr = map(int, raw_input().split()) p = map(int, raw_input().split()) arrs = sorted(arr) p.sort() i,j=0,0 while i<len(arr) and j<len(p): if p[j] == i+1: temp = j while j+1<le...
Pulkit is really good at maths. Recently, he came to know about a problem on matrices. Amazed by the problem he got, he asked Ashish the same problem. Ashish also being good at maths solved the problem within 5 minutes. Now, its your time to solve the problem. You will be given n*m binary matrix. You need to tell if i...
1
num_cases = int(raw_input().rstrip("\n")) for count in range(num_cases): n, m = map(int, raw_input().rstrip("\n").split(" ")) rows = [] cet = set() for itr in range(n): row = raw_input().rstrip("\n") rows.append(row) cet.add(row) if len(cet) == n: found = False ...
Rabbits and cats are competing. The rules are as follows. First, each of the two animals wrote n2 integers on a piece of paper in a square with n rows and n columns, and drew one card at a time. Shuffle two cards and draw them one by one alternately. Each time a card is drawn, the two will mark it if the same number a...
1
#!/usr/bin/env python from collections import deque import itertools as it import sys sys.setrecursionlimit(1000000) n, u, v, m = map(int, raw_input().split()) m1 = {} m2 = {} for i in range(n): lst_ = map(int, raw_input().split()) for j in range(n): if n == 1: l = [0] else: ...
Despite his bad reputation, Captain Flint is a friendly person (at least, friendly to animals). Now Captain Flint is searching worthy sailors to join his new crew (solely for peaceful purposes). A sailor is considered as worthy if he can solve Flint's task. Recently, out of blue Captain Flint has been interested in ma...
3
n = int(input()) for i in range(n): num = int(input()) if num <= 30: print("NO") else: print("YES") difference = num - 30 if difference == 6 or difference == 10 or difference == 14: print(6, 10, 15, num-31) else: print(6, 10, 14, num-30)
After the mysterious disappearance of Ashish, his two favourite disciples Ishika and Hriday, were each left with one half of a secret message. These messages can each be represented by a permutation of size n. Let's call them a and b. Note that a permutation of n elements is a sequence of numbers a_1, a_2, …, a_n, in ...
3
from collections import Counter n = int(input()) a = {} b = {} match = [] c = 0 for i in [int(i) for i in input().split()]: a[i] = c c += 1 c = 0 for i in [int(i) for i in input().split()]: b[i] = c c += 1 for i in range(1, n+1): match.append((b.get(i) - a.get(i) + n) % n) occu = Counter(match)...
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
# ✪ H4WK3yE乡 # Mayank Chaudhary # ABES EC , Ghaziabad # ///==========Libraries, Constants and Functions=============/// import sys from bisect import bisect_left,bisect_right from collections import deque,Counter from math import gcd,sqrt,factorial,ceil,log10 from itertools import permutations inf = float("inf") mod = ...
This problem's actual name, "Lexicographically Largest Palindromic Subsequence" is too long to fit into the page headline. You are given string s consisting of lowercase English letters only. Find its lexicographically largest palindromic subsequence. We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk (1 ≤ ...
3
s=sorted(input()) print(s[len(s)-1]*s.count(s[len(s)-1]))
Vova, the Ultimate Thule new shaman, wants to build a pipeline. As there are exactly n houses in Ultimate Thule, Vova wants the city to have exactly n pipes, each such pipe should be connected to the water supply. A pipe can be connected to the water supply if there's water flowing out of it. Initially Vova has only on...
1
n, k = map(int, raw_input().split()) def f(m): return k*(k-1)/2-(k-m)*(k-m-1)/2+1 if f(k - 1) < n: print -1 else: l, h = 0, k - 1 while l < h: m = (l + h) / 2 if f(m) < n: l = m + 1 else: h = m print l
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." — an excerpt from contest rules. A total of n participants took part in the contest (n ≥ k), and you already know their scores. Calculate how many ...
3
n,k=map(int,input().split()) l=list(map(int,input().split())) s=[] for i in range(n): if(l[i]==0): break if(l[i]>l[k-1] or l[i]==l[k-1]): s.append(l[i]) else: pass print(len(s))
Find the minimum area of a square land on which you can place two identical rectangular a × b houses. The sides of the houses should be parallel to the sides of the desired square land. Formally, * You are given two identical rectangles with side lengths a and b (1 ≤ a, b ≤ 100) — positive integers (you are given ...
3
for _ in range(int(input())): a,b=map(int,input().split()) x=2*min(a,b) y=max(a,b) print(max(x,y)**2)
Write a program which reads an integer $S$ [second] and converts it to $h:m:s$ where $h$, $m$, $s$ denote hours, minutes (less than 60) and seconds (less than 60) respectively. Constraints * $0 \leq S \leq 86400$ Input An integer $S$ is given in a line. Output Print $h$, $m$ and $s$ separated by ':'. You do not n...
3
data = int(input()) print(data//3600, (data//60)%60, data%60, sep = ":")
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
n = int(input()) li = list(map(int,input().split()))[:n] li.sort() mypart = 0 count=0 sumoflist = sum(li) for i in range(len(li)-1,-1,-1): if sumoflist-mypart >= mypart: mypart += li[i] count+=1 print(count)
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If...
3
n = input() if "0"*7 in n or '1'*7 in n: print("YES") else: print("NO")
Calendars in widespread use today include the Gregorian calendar, which is the de facto international standard, and is used almost everywhere in the world for civil purposes. The Gregorian reform modified the Julian calendar's scheme of leap years as follows: Every year that is exactly divisible by four is a leap year...
1
import datetime y1,m1,d1 = map(int, raw_input().split(":")) y2,m2,d2 = map(int, raw_input().split(":")) print abs(datetime.date(y1,m1,d1)-datetime.date(y2,m2,d2)).days
Write a program which identifies the number of combinations of three integers which satisfy the following conditions: * You should select three distinct integers from 1 to n. * A total sum of the three integers is x. For example, there are two combinations for n = 5 and x = 9. * 1 + 3 + 5 = 9 * 2 + 3 + 4 = 9 Note...
1
import sys p = sys.stdin.readlines() r = 0 for i in p: n,x = map(int,i.split()) if n==0 and x==0: break else: for a in range(1,n+1): for b in range(1,n+1): if a==b: break else: for c in range(1,n+1): if a==c or b==c: break elif a+b+c==x: r+=1 print r r = r*0
You are given n strings a_1, a_2, …, a_n: all of them have the same length m. The strings consist of lowercase English letters. Find any string s of length m such that each of the given n strings differs from s in at most one position. Formally, for each given string a_i, there is no more than one position j such that...
3
from sys import stdin, stdout # case 1: 2 char diff # abac # zbab # zbac or abab # case 2: 1 char diff # abac # zbac # ?bac # brutal # O(26*M^2*N) def spy_string(a, n, m): ca = list(a[0]) for i in range(m): org = ca[i] for j in range(26): ca[i] = chr(ord('a') + j) f...
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()) g = list(map(int, input().split())) ans = [0 for i in range(n)] for i in range(n): ans[g[i]-1] = i+1 print(*ans)
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()) a=[] b=[] tot=0 for i in range(n): h,g=map(int,input().split()) a.append(h) b.append(g) for x in a: tot+=b.count(x) print(tot)
Takahashi is a member of a programming competition site, ButCoder. Each member of ButCoder is assigned two values: Inner Rating and Displayed Rating. The Displayed Rating of a member is equal to their Inner Rating if the member has participated in 10 or more contests. Otherwise, the Displayed Rating will be their Inn...
3
N, R = map(int, input().split()) if N>10: N=10 print(R+(100*(10-N)))
Vanya walks late at night along a straight street of length l, lit by n lanterns. Consider the coordinate system with the beginning of the street corresponding to the point 0, and its end corresponding to the point l. Then the i-th lantern is at the point ai. The lantern lights all points of the street that are at the ...
3
n,l=[int(j) for j in input().split()] a=[int(j) for j in input().split()] a.sort() md=0 for i in range(1,n): d=a[i]-a[i-1] if d>md: md=d if md/2>a[0] and md/2>l-a[n-1]: print(md/2) elif a[0]>md/2 and a[0]>l-a[n-1]: print(a[0]) else: print(l-a[n-1])
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 read_line_sum(): return sum([int(x) for x in input().split(' ')]) n = int(input()) count = 0 for i in range(n): if read_line_sum() >= 2: count += 1 print(count)
M-kun is a brilliant air traffic controller. On the display of his radar, there are N airplanes numbered 1, 2, ..., N, all flying at the same altitude. Each of the airplanes flies at a constant speed of 0.1 per second in a constant direction. The current coordinates of the airplane numbered i are (X_i, Y_i), and the d...
3
# coding: utf-8 # Your code here! import sys read = sys.stdin.read readline = sys.stdin.readline n, = map(int, readline().split()) M = 2*10**5+2 Uy = {} Dy = {} Rx = {} Lx = {} d1U = {} # 右上、x+y UR d1R = {} # 右上、x+y UR d2U = {} # 左上、x-y UL d2L = {} # 左上、x-y UL d3L = {} # 左下、x+y LD d3D = {} # 左下、x+y LD d4D = {} # 右下、...
You are given two integers x and y. You can perform two types of operations: 1. Pay a dollars and increase or decrease any of these integers by 1. For example, if x = 0 and y = 7 there are four possible outcomes after this operation: * x = 0, y = 6; * x = 0, y = 8; * x = -1, y = 7; * x = 1, y = ...
3
a=int(input()) for i in range(0,a): x,y=map(int,input().split()) a,b=map(int,input().split()) minn=min(x,y) if(b>2*a): print(x*a+y*a) else: print(a*(abs(y-x))+b*minn)
You are given two strings s and t. In a single move, you can choose any of two strings and delete the first (that is, the leftmost) character. After a move, the length of the string decreases by 1. You can't choose a string if it is empty. For example: * by applying a move to the string "where", the result is the s...
3
s1=input() s2=input() s1=list(s1) s2=list(s2) n=min(len(s1),len(s2)) z=0 count=0 for i in range(n): if s1[len(s1)-1-i]==s2[len(s2)-1-i]: count+=1 else: break if z==0: print(len(s1)+len(s2)-2*count)
Snuke has decided to play with a six-sided die. Each of its six sides shows an integer 1 through 6, and two numbers on opposite sides always add up to 7. Snuke will first put the die on the table with an arbitrary side facing upward, then repeatedly perform the following operation: * Operation: Rotate the die 90° tow...
3
x = int(input()) print(x // 11 * 2 + (x % 11 - 1) // 6 + 1)
A sequence of non-negative integers a1, a2, ..., an of length n is called a wool sequence if and only if there exists two integers l and r (1 ≤ l ≤ r ≤ n) such that <image>. In other words each wool sequence contains a subsequence of consecutive elements with xor equal to 0. The expression <image> means applying the o...
3
n, m = map(int, input().split()) mod = 10 ** 9 + 9 s, ans = pow(2, m, mod) - 1, 1 for i in range(n): ans = ans * (s - i) % mod; print (ans)
There are n monsters standing in a row numbered from 1 to n. The i-th monster has h_i health points (hp). You have your attack power equal to a hp and your opponent has his attack power equal to b hp. You and your opponent are fighting these monsters. Firstly, you and your opponent go to the first monster and fight it...
3
str = input() spl = str.split(' ') n = int(spl[0]) a = int(spl[1]) b = int(spl[2]) k = int(spl[3]) str = input() spl = str.split(' ') h = [0] * n for i in range(n): h[i] = int(spl[i]) h[i] %= (a + b) if(h[i] == 0): h[i] = a + b h[i] -= 1 h[i] = h[i] // a h.sort() ans = 0 for i in range...
Polycarpus likes studying at school a lot and he is always diligent about his homework. Polycarpus has never had any problems with natural sciences as his great-great-grandfather was the great physicist Seinstein. On the other hand though, Polycarpus has never had an easy time with history. Everybody knows that the Wo...
1
def f(n): s = [map(int, raw_input().split()) for _ in xrange(n)] s.sort(key=lambda x: (x[0], x[1])) count = 0 last = s[0][1] for i in xrange(1, n): if s[i][1] < last: count += 1 else: last = s[i][1] return count print f(int(raw_input()))
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
3
n=int(input("")) ans=[] for i in range(n): s=input("") l=[] for i in s: l.append(i) if len(l)>10: x=l[0]+str(len(l)-2)+l[-1] ans.append(x) else: x=s ans.append(x) for i in ans: print(i)
Someday, Drazil wanted to go on date with Varda. Drazil and Varda live on Cartesian plane. Drazil's home is located in point (0, 0) and Varda's home is located in point (a, b). In each step, he can move in a unit distance in horizontal or vertical direction. In other words, from position (x, y) he can go to positions (...
1
import math a,b,s=raw_input('').strip().split() a=int(a) b=int(b) s=int(s) if s<abs(a)+abs(b): print 'No' else: if(s-abs(a)-abs(b))%2==0: print 'Yes' else: print 'No'
You got a box with a combination lock. The lock has a display showing n digits. There are two buttons on the box, each button changes digits on the display. You have quickly discovered that the first button adds 1 to all the digits (all digits 9 become digits 0), and the second button shifts all the digits on the displ...
3
n = int(input()) s = [int(x) for x in input()] print("".join(map(str, min([[(x + 10 - s[j]) % 10 for x in (s[j:] + s[:j])] for j in range(n)]))))
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
i = int(input()) if i < 0 : x = str(-i) else: x = str(i) l = [] for j in x : l.append(j) if l.count('4')+l.count('7') == 4 or l.count('4')+l.count('7') == 7 : print("YES") else : print("NO")