problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s. You have to answer t independent test cases. Input The first line of the input co...
3
n = int(input()) c = [] for i in range(n): a, b = [int(m) for m in input().split()] if a % b == 0: c.append(0) else: c.append(b - (a % b)) for item in c: print(item)
The only difference between easy and hard versions is constraints. 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 will take the exam one-by-one in order from 1-th to n-th. Rules of the exam are following: *...
3
n, m = list(map(int, input().split())) array = list(map(int, input().split())) res = [] def sumWithout(mas, indexes): res = 0 for i in range(len(mas)): if not (i in indexes): res += mas[i] return(res) def maxWithout(mas, indexes): res = -1 resInd = 0 for i in range(len(ma...
Kuriyama Mirai has killed many monsters and got many (namely n) stones. She numbers the stones from 1 to n. The cost of the i-th stone is vi. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions: 1. She will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should...
3
#------------------------template--------------------------# import os import sys from math import * from collections import * from bisect import * from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') BUFSIZE = 8192 class FastIO(IOBase): newl...
There are n cities and m bidirectional roads in Berland. The i-th road connects the cities x_i and y_i, and has the speed limit s_i. The road network allows everyone to get from any city to any other city. The Berland Transport Ministry is planning a road reform. First of all, maintaining all m roads is too costly, ...
3
from collections import defaultdict from math import ceil, sqrt, floor from heapq import heappush,heappop import sys inf = float("inf") class DisjointSet: def __init__(self, n): self.n = n self.par = [-1] * n self.nc = n def findParent(self, i): if self.par[i] == -1: return i #no parent yet else: v...
Tanya has n candies numbered from 1 to n. The i-th candy has the weight a_i. She plans to eat exactly n-1 candies and give the remaining candy to her dad. Tanya eats candies in order of increasing their numbers, exactly one candy per day. Your task is to find the number of such candies i (let's call these candies goo...
3
n=int(input('')) a=(list(map(int, input().split()))) b=0 c=0 d=0 e=0 l=0 for i in range(0,n): if i%2==0: b+=a[i] else: c+=a[i] for i in range(0,n): if i%2==0: f=d+c-e g=e+b-d-a[i] if f==g: l+=1 else: f=e+b-d g=d+c-e-a[i] if f==g: ...
Appleman and Toastman play a game. Initially Appleman gives one group of n numbers to the Toastman, then they start to complete the following tasks: * Each time Toastman gets a group of numbers, he sums up all the numbers and adds this sum to the score. Then he gives the group to the Appleman. * Each time Applema...
3
n = int(input()) inp = input().split() for i in range(n): inp[i] = int(inp[i]) inp = sorted(inp) ans = 0 for i in range(n): ans += inp[i] su = ans for i in range(n-1): ans += su su -= inp[i] print(ans)
After winning gold and silver in IOI 2014, Akshat and Malvika want to have some fun. Now they are playing a game on a grid made of n horizontal and m vertical sticks. An intersection point is any point on the grid which is formed by the intersection of one horizontal stick and one vertical stick. In the grid shown be...
1
m,n=map(int,raw_input().split()) if(m%2==0 and n%2==0): print "Malvika" elif(m%2!=0 and n%2!=0): print "Akshat" elif(m>n): if(n%2==0): print "Malvika" else: print "Akshat" else: if(m%2==0): print "Malvika" else: print "Akshat"
You are given an array of n integers: a_1, a_2, …, a_n. Your task is to find some non-zero integer d (-10^3 ≤ d ≤ 10^3) such that, after each number in the array is divided by d, the number of positive numbers that are presented in the array is greater than or equal to half of the array size (i.e., at least ⌈n/2⌉). Not...
3
''' Author : thekushalghosh ''' n = int(input()) a = list(map(int,input().split())) q = [i for i in a if i > 0] w = [i for i in a if i < 0] if len(q) >= (n + 1) // 2: print(1) elif len(w) >= (n + 1) // 2: print(-1) else: print(0)
Given is an integer sequence A_1, ..., A_N of length N. We will choose exactly \left\lfloor \frac{N}{2} \right\rfloor elements from this sequence so that no two adjacent elements are chosen. Find the maximum possible sum of the chosen elements. Here \lfloor x \rfloor denotes the greatest integer not greater than x. ...
3
N = int(input()) A = list(map(int, input().split())) inf = 10**18 x = N % 2 + 1 dp = [[-inf] * 4 for _ in range(N + 10)] dp[0][0] = 0 for i, a in enumerate(A): for j in range(x + 1): dp[i+1][j+1] = max(dp[i+1][j+1], dp[i][j]) now = dp[i][j] if (i + j) % 2 == 0: now += a ...
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word s. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if...
3
s = input() a=-1 for i in 'hello': a = s.find(i,a+1) if a==-1: break if a==-1: print('NO') else: print('YES')
Vasya's birthday is approaching and Lena decided to sew a patterned handkerchief to him as a present. Lena chose digits from 0 to n as the pattern. The digits will form a rhombus. The largest digit n should be located in the centre. The digits should decrease as they approach the edges. For example, for n = 5 the handk...
3
n=int(input("")) for i in range (n+1): for k in range (n-i): print(" ",end=" ") for k in range (i): print(k,end=" ") for k in range (i+1): if k==i: print(i-k,end="") else: print(i-k,end=" ") print("") for i in range (n-1,-1,-1): for k in r...
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....
1
def test(s,t): for i in range(len(s)): if s[i] != t[len(s)-1-i]: return "NO" return "YES" s = raw_input() t = raw_input() if len(s) == len(t): print test(s,t) else: print "NO"
Bessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically, he wants to get from (0,0) to (x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance betw...
3
for i in range(int(input())): a,b=list(map(int,input().split())) to=0 l=[] t=0 l=list(map(int,input().split())) d=max(l) if(b==d): to=1 elif(d>b): to=2 for vaibhav in l: ...
There are n kids, numbered from 1 to n, dancing in a circle around the Christmas tree. Let's enumerate them in a clockwise direction as p_1, p_2, ..., p_n (all these numbers are from 1 to n and are distinct, so p is a permutation). Let the next kid for a kid p_i be kid p_{i + 1} if i < n and p_1 otherwise. After the da...
3
n=int(input()) l=[] a,b=0,0 for i in range(n): s=list(map(int,input().split(" "))) a=int(s[0]) b=int(s[1]) l.append([a,b]) ans=[1] a,b=l[0][0],l[0][1] if b in l[a-1]: ans.append(a) ans.append(b) i=a j=b else: ans.append(b) ans.append(a) i=b j=a while len(ans)<n: for c...
Let's call a string good if and only if it consists of only two types of letters — 'a' and 'b' and every two consecutive letters are distinct. For example "baba" and "aba" are good strings and "abb" is a bad string. You have a strings "a", b strings "b" and c strings "ab". You want to choose some subset of these strin...
1
a,b,c = map(int,raw_input().split()) print c*2+2*min(a,b)+(1 if a<>b else 0)
You're given two arrays a[1 ... n] and b[1 ... n], both of the same length n. In order to perform a push operation, you have to choose three integers l, r, k satisfying 1 ≤ l ≤ r ≤ n and k > 0. Then, you will add k to elements a_l, a_{l+1}, …, a_r. For example, if a = [3, 7, 1, 4, 1, 2] and you choose (l = 3, r = 5, ...
3
for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) r = [b[i] - a[i] for i in range(n)] if any(value < 0 for value in r): print("NO") else: consecutive = False k = 0 for value in r: if ...
Takahashi has a string S consisting of lowercase English letters. Starting with this string, he will produce a new one in the procedure given as follows. The procedure consists of Q operations. In Operation i (1 \leq i \leq Q), an integer T_i is provided, which means the following: * If T_i = 1: reverse the string S...
3
s,_,*q=open(0) a=['',''] p=1 for q in q: p^=q<'2' a[(q<'2 2')^p]+=q[-2]*(q>'2') print(a[p^1][::-1]+s[:-1][::p or-1]+a[p])
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
s = input() numbers = [0, 0, 0] for c in s: if c == '1': numbers[0] += 1 elif c == '2': numbers[1] += 1 elif c == '3': numbers[2] += 1 ones = '+'.join('1' for _ in range(numbers[0])) twos = '+'.join('2' for _ in range(numbers[1])) threes = '+'.join('3' for _ in range(numbers[2])) wo...
Ann has recently started commuting by subway. We know that a one ride subway ticket costs a rubles. Besides, Ann found out that she can buy a special ticket for m rides (she can buy it several times). It costs b rubles. Ann did the math; she will need to use subway n times. Help Ann, tell her what is the minimum sum of...
3
n,m,a,b = tuple(map(int,input().split(" "))) if m*a >b: cost = min((n//m)*b+(n%m)*a,((n//m)+1)*(b)) else: cost = n*a print(cost)
Let us define a magic grid to be a square matrix of integers of size n × n, satisfying the following conditions. * All integers from 0 to (n^2 - 1) inclusive appear in the matrix exactly once. * [Bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of all elements in a row or a column must be the sa...
3
n = int(input()) t = [[0] * n for i in range(n)] last_even = 0 last_odd = 1 for j in range(n): for i in range(n): if j % 2 == 0: t[i][j] = last_even last_even += 2 else: t[i][j] = last_odd last_odd += 2 for r in t: print(' '.join(map(str, r)))
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition. Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character...
3
s='a'+input() r=0 for i in range(1,len(s)):t=ord(s[i]),ord(s[i-1]);a,b=min(t),max(t);r+=min(b-a,a+26-b) print(r)
Today Berland holds a lottery with a prize — a huge sum of money! There are k persons, who attend the lottery. Each of them will receive a unique integer from 1 to k. The organizers bought n balls to organize the lottery, each of them is painted some color, the colors are numbered from 1 to k. A ball of color c corresp...
1
n, k = map(int, raw_input().strip().split()) numbers = map(int, raw_input().strip().split()) freq = [0] * (n + 1) for it in numbers: freq[it] += 1 ans = 0 limit = n // k for it in freq: if it > limit: ans += it - limit print ans
Your math teacher gave you the following problem: There are n segments on the x-axis, [l_1; r_1], [l_2; r_2], …, [l_n; r_n]. The segment [l; r] includes the bounds, i.e. it is a set of such x that l ≤ x ≤ r. The length of the segment [l; r] is equal to r - l. Two segments [a; b] and [c; d] have a common point (inters...
3
t = int(input()) for i in range(t): n = int(input()) k = 0 s = 10**9 for j in range(n): l,r = map(int, input().split()) if l > k: k = l if r < s: s = r if k-s < 0: print(0) else: print(k-s)
The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her n students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often oddl...
3
n,p=map(int,input().split()) s=sorted(map(int,input().split())) m=s[n-1]-s[0] for i in range(p-n+1): m=min(m,s[i+n-1]-s[i]) print(m)
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth. Now Diamond has given Bort a string consisting of only uppercase English letters of length n. There is a great number of "QAQ" in the string (Diamond is so cute!). <image> illustration by 猫屋 https://twitter.com/nekoy...
3
a = input() s = 0 for i in range(len(a)): if a[i] == 'A': s += a[:i].count('Q') * a[i:].count('Q') print(s)
Polycarp knows that if the sum of the digits of a number is divisible by 3, then the number itself is divisible by 3. He assumes that the numbers, the sum of the digits of which is divisible by 4, are also somewhat interesting. Thus, he considers a positive integer n interesting if its sum of digits is divisible by 4. ...
3
n=int(input()) while 1: s=0 for i in str(n): s+=int(i) if s%4==0: print(n) break n+=1
There are three friend living on the straight line Ox in Lineland. The first friend lives at the point x1, the second friend lives at the point x2, and the third friend lives at the point x3. They plan to celebrate the New Year together, so they need to meet at one point. What is the minimum total distance they have to...
3
x1,x2,x3=list(map(int,input().strip().split(' '))) print(max(x1,x2,x3)-min(x1,x2,x3))
The School №0 of the capital of Berland has n children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value ti: * ti = 1, if the i-th child is good at programming, *...
3
t=int(input()) nums=list(map(int,input().split())) teams=[[],[],[]] i=0 while i<len(nums): x=nums[i] teams[x-1].append((i+1)) i=i+1 w=min([len(x) for x in teams]) print(w) i=0 while i<w: print(teams[0][i],teams[1][i],teams[2][i]) i=i+1
wHAT DO WE NEED cAPS LOCK FOR? Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage. Let's consider that a word has been typed with the Caps lock key accidentall...
3
string = input() string_len = len(string) if all(string[i].isupper() for i in range(1, len(string))) or string_len == 1: if string[0].islower(): print(string[0].upper() + string[1:].lower()) else: print(string[0].lower() + string[1:].lower()) else: print(string)
Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers. He wants to know how many subsequences of length three can be selected from a, so that they form a geometric p...
1
""" // Author : snape_here - Susanta Mukherjee """ from __future__ import division, print_function import os,sys from io import BytesIO, IOBase if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip def ii(): return int(...
As you could know there are no male planes nor female planes. However, each plane on Earth likes some other plane. There are n planes on Earth, numbered from 1 to n, and the plane with number i likes the plane with number fi, where 1 ≤ fi ≤ n and fi ≠ i. We call a love triangle a situation in which plane A likes plane...
1
N = int(raw_input()) L = map(int, raw_input().split()) for i in range(N): L[i] -= 1 b = False for i in range(N): if L[L[L[i]]] == i: b = True break if b : print "YES" else: print "NO"
Mr. Kitayuta has kindly given you a string s consisting of lowercase English letters. You are asked to insert exactly n lowercase English letters into s to make it a palindrome. (A palindrome is a string that reads the same forward and backward. For example, "noon", "testset" and "a" are all palindromes, while "test" a...
3
s = input() for i in range(26): for j in range(len(s)+1): s1 = s[:j]+chr(ord('a')+i)+s[j:] if s1[::-1] == s1: print (s1) exit(0) print ('NA')
You are given a string s. Each character is either 0 or 1. You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met. You may eras...
3
T= int(input()) result="" for t in range(T): counter=0 n=input() n=n.strip("0") for ch in range(len(n)-1): if n[ch]=="0": counter+=1 result+="\n"+str(counter) print(result.strip("\n"))
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
i = int(input()) b = i > 2 and i%2==0 if b: print('YES') else: print('NO')
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=input() nn=int(n) cont=0 cont2=0 for x in range(nn): cont = 0 a = list(map(int , input().split(' '))) for y in range(3): if(a[y]==1): cont+=1 if(cont>=2): cont2+=1 print(cont2)
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find ...
3
num = int(input()) count = 0 for i in str(num): if i == '4' or i == '7': count += 1 continue else: break if count == len(str(num)): print("YES") elif num % 4 == 0 or num % 7 == 0 or num % 47 == 0 or num % 74 == 0 or num % 44 == 0 or num % 77 == 0: print("YES") elif num % 444 == 0...
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
import sys import math t = int(input()) for _ in range(t): a, b, c = list(map(int, input().split())) maxL = min(a, b, c) maxR = max(a, b, c) maxR -= 1 maxL += 1 print(max(0, (maxR - maxL) * 2))
You are given a rectangular cake, represented as an r × c grid. Each cell either has an evil strawberry, or is empty. For example, a 3 × 4 cake may look as follows: <image> The cakeminator is going to eat the cake! Each time he eats, he chooses a row or a column that does not contain any evil strawberries and contain...
3
n,m=map(int,input().split());a=[] for i in range(n):a.append(list(input())) for i in range(n): ok=1 for j in range(m): if(a[i][j]=='S'):ok=0 if(ok): for j in range(m):a[i][j]='+' for j in range(m): ok=1 for i in range(n): if(a[i][j]=='S'):ok=0 if(ok): for i in ran...
Write a program of the Bubble Sort algorithm which sorts a sequence A in ascending order. The algorithm should be based on the following pseudocode: BubbleSort(A) 1 for i = 0 to A.length-1 2 for j = A.length-1 downto i+1 3 if A[j] < A[j-1] 4 swap A[j] and A[j-1] Note that, indices for array ...
3
N = int(input()) *A, = list(map(int, input().split())) flg = 1 cnt = 0 while flg: flg = 0 for j in range(N-1,0,-1): if A[j] < A[j-1]: v = A[j] A[j] = A[j - 1] A[j - 1] = v flg = 1 cnt += 1 print(*A) print(cnt)
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob. Right now, Limak and Bob weigh a and b respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight. Limak eats a lot and his weight is tripled after every year, while Bob's weight...
3
a,b = input().split() a = int(a) b = int(b) cnt = 1 while 1 : a = 3 * a b = 2 * b if a > b : print(cnt) break cnt = cnt + 1
You are given a string S consisting of uppercase English letters. Find the length of the longest ACGT string that is a substring (see Notes) of S. Here, a ACGT string is a string that contains no characters other than `A`, `C`, `G` and `T`. Constraints * S is a string of length between 1 and 10 (inclusive). * Each c...
3
import re result = re.findall('[ATCG]+',input(),re.S) if len(result)>0: print(max(list(map(len,result)))) else: print(0)
You are given an array a consisting of n integers. You have to find the length of the smallest (shortest) prefix of elements you need to erase from a to make it a good array. Recall that the prefix of the array a=[a_1, a_2, ..., a_n] is a subarray consisting several first elements: the prefix of the array a of length k...
3
for u in range(int(input())): n=int(input()) l=list(map(int,input().split())) if(l==sorted(l)): print(0) else: c=0 i=n-1 while(i>0): if(l[i]<=l[i-1]): i=i-1 c=c+1 else: break x=i i=x ...
Recently Anton found a box with digits in his room. There are k2 digits 2, k3 digits 3, k5 digits 5 and k6 digits 6. Anton's favorite integers are 32 and 256. He decided to compose this integers from digits he has. He wants to make the sum of these integers as large as possible. Help him solve this task! Each digit c...
3
a,b,c,d=map(int,input().split()) t=min(a,c,d) a=abs(a-t) count=t*256 a=min(a,b) print(count+a*32)
We have a sequence p = {p_1,\ p_2,\ ...,\ p_N} which is a permutation of {1,\ 2,\ ...,\ N}. You can perform the following operation at most once: choose integers i and j (1 \leq i < j \leq N), and swap p_i and p_j. Note that you can also choose not to perform it. Print `YES` if you can sort p in ascending order in th...
1
N=input() P=map(int, raw_input().split()) Q=sorted(P) cnt=0 for p,x in zip(P,Q): if p!=x: cnt+=1 if cnt<=2: print "YES" else: print "NO"
Two-gram is an ordered pair (i.e. string of length two) of capital Latin letters. For example, "AZ", "AA", "ZA" — three distinct two-grams. You are given a string s consisting of n capital Latin letters. Your task is to find any two-gram contained in the given string as a substring (i.e. two consecutive characters of ...
3
n = int(input()) s = input() d = {} for i in range(n - 1): t = s[i] + s[i + 1] if t in d: d[t] += 1 else: d[t] = 1 print(sorted(d, key=d.get)[-1])
Mr. A came to Aizu for sightseeing. You can overlook the Aizu Basin from the window of the hotel where you stayed. As I was looking at the scenery, I noticed a piece of the photo on the floor. Apparently I took the outside view from the window. "Which area did you take?" A asked, holding the photo so that the view outs...
3
while 1: N, M = map(int, input().split()) if N == 0: break W = [list(map(int, input().split())) for i in range(N)] P = [list(map(int, input().split())) for i in range(M)] P0 = [[0]*M for i in range(M)] ans = [] for t in range(4): P1 = [] for i in range(M): ...
The goal of 8 Queens Problem is to put eight queens on a chess-board such that none of them threatens any of others. A queen threatens the squares in the same row, in the same column, or on the same diagonals as shown in the following figure. <image> For a given chess board where $k$ queens are already placed, find ...
3
import sys from itertools import permutations sys.setrecursionlimit(10 ** 7) input = sys.stdin.readline f_inf = float('inf') mod = 10 ** 9 + 7 def resolve(): k = int(input()) RC = [list(map(int, input().split())) for _ in range(k)] res = [["."] * 8 for _ in range(8)] for pattern in permutations(list...
As shown in the following figure, there is a paper consisting of a grid structure where each cell is indicated by (x, y) coordinate system. We are going to put drops of ink on the paper. A drop comes in three different sizes: Large, Medium, and Small. From the point of fall, the ink sinks into surrounding cells as sho...
3
paper=[[0 for i in range(10)] for j in range(10)] while 1: try: x,y,s=map(int,input().split(",")) if s==1: r=[[-1,0],[1,0],[0,0],[0,-1],[0,1]] elif s==2: r=[[-1,-1],[-1,0],[-1,1],[0,-1],[0,0],[0,1],[1,-1],[1,0],[1,1]] elif s==3: r=[[-2,0],[-1,-1],[...
So the Beautiful Regional Contest (BeRC) has come to an end! n students took part in the contest. The final standings are already known: the participant in the i-th place solved p_i problems. Since the participants are primarily sorted by the number of solved problems, then p_1 ≥ p_2 ≥ ... ≥ p_n. Help the jury distrib...
3
for _ in range(int(input())): ln = int(input()) a = [int(x) for x in input().split()] my_g = my_s = my_b = -1 g = s = b = 0 for i in range(ln): if my_g == -1: my_g = a[i] if a[i] == my_g: g += 1 elif a[i] < my_g: if my_s == -1: ...
Everybody in Russia uses Gregorian calendar. In this calendar there are 31 days in January, 28 or 29 days in February (depending on whether the year is leap or not), 31 days in March, 30 days in April, 31 days in May, 30 in June, 31 in July, 31 in August, 30 in September, 31 in October, 30 in November, 31 in December. ...
3
import sys c1 = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] n = int(input()) a = [int(i) for i in input().split()] if a.count(29) >= 2: print('NO') sys.exit(0) eli...
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
n=input() count=0 for index,element in enumerate(n): if element== '7' or element =='4': count+=1 if count==7 or count==4: print("YES") else: print("NO")
Two friends are on the coordinate axis Ox in points with integer coordinates. One of them is in the point x1 = a, another one is in the point x2 = b. Each of the friends can move by one along the line in any direction unlimited number of times. When a friend moves, the tiredness of a friend changes according to the f...
1
a = input() b = input() a,b = min(a,b),max(a,b) c = (a+b)//2 a = c-a b = b-c print a*(a+1)/2 + b*(b+1)/2
Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpr...
3
a,b=map(int,input().split()) c=max(a,b) final=7-c if final==6: print(f"1/1") else: if final==1: print(f"1/6") elif final==2: print(f"1/3") elif final==3: print(f"1/2") elif final==4: print(f"2/3") elif final==5: print(f"5/6")
Polycarp loves ciphers. He has invented his own cipher called Right-Left. Right-Left cipher is used for strings. To encrypt the string s=s_{1}s_{2} ... s_{n} Polycarp uses the following algorithm: * he writes down s_1, * he appends the current word with s_2 (i.e. writes down s_2 to the right of the current resul...
3
t = list(input())#ncteho k = 1 st = "" if len(t) > 1: if len(t) % 2 == 0: for i in range((len(t)//2)-1, -1, -1): st += (t[i]+t[i+k]) #st += (t[i+k-1]) #print("i",i,"k",k) #print("t[",i,"] = ", t[i]) #print("t[",i+k,"] = ", t[(i+k)]) #p...
There are n banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if n > 1. No bank is a neighbour of itself. Vasya has an account in each bank. Its balance may be negative, meaning V...
3
def main(): from itertools import accumulate from collections import Counter print(int(input()) - Counter(accumulate(map(int, input().split()))).most_common()[0][1]) if __name__ == '__main__': main()
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
arr=list(map(int,input().rstrip().split(' '))) n=arr[0] m=arr[1] a=arr[2] count_n=0 count_m=0 if n%a == 0 : count_n=n//a else: count_n=(n//a)+1 if m%a == 0 : count_m=m//a else: count_m=(m//a)+1 print(count_n*count_m)
Pandey needs your help. As you know, he is on the quest to save the princess. After traveling for a number of days, he has finally reached the palace, but one last battle remains to be fought. However he has only one unit of energy left in him. To win the battle, he needs all the energy he can get. So he is searching f...
1
from pprint import pprint as pp def GI(): return int(raw_input()) def GIS(): return map(int, raw_input().split()) def main(): for t in xrange(GI()): ex = [1, 1] for _ in xrange(GI()): b = raw_input() if b == 'N': nex = [-1 * x for x in ex] else: ...
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
from math import ceil n, m, a = map(int, input().split()) result = ceil(m/a) * ceil(n/a) print(result)
There is a right triangle ABC with ∠ABC=90°. Given the lengths of the three sides, |AB|,|BC| and |CA|, find the area of the right triangle ABC. It is guaranteed that the area of the triangle ABC is an integer. Constraints * 1 \leq |AB|,|BC|,|CA| \leq 100 * All values in input are integers. * The area of the triangl...
3
print(eval("*".join(input().split()[:2]))//2)
It's one more school day now. Sasha doesn't like classes and is always bored at them. So, each day he invents some game and plays in it alone or with friends. Today he invented one simple game to play with Lena, with whom he shares a desk. The rules are simple. Sasha draws n sticks in a row. After that the players tak...
3
n,k=[(int(i)) for i in input().split()] if ((n//k)%2!=0): print("yes") elif((n//k)%2==0): print("No")
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...
3
from sys import stdin,stdout from math import gcd,sqrt,floor,ceil # Fast I/O input = stdin.readline #print = stdout.write def list_inp(x):return list(map(x,input().split())) def map_inp(x):return map(x,input().split()) def lcm(a,b): return (a*b)/gcd(a,b) s = input().strip('\n') s1 = set() for i in s: if i.isalpha(...
Devu is a dumb guy, his learning curve is very slow. You are supposed to teach him n subjects, the ith subject has ci chapters. When you teach him, you are supposed to teach all the chapters of a subject continuously. Let us say that his initial per chapter learning power of a subject is x hours. In other words he can...
1
n,m = [int(x) for x in raw_input().split()] l = [int(x) for x in raw_input().split()] ans = 0 l.sort() for i in l: ans += i*m if m> 1: m -=1 print ans
Ksusha the Squirrel is standing at the beginning of a straight road, divided into n sectors. The sectors are numbered 1 to n, from left to right. Initially, Ksusha stands in sector 1. Ksusha wants to walk to the end of the road, that is, get to sector n. Unfortunately, there are some rocks on the road. We know that K...
3
n,k=map(int,input().split()) z="#"*k l=str(input()) if z in l: print("NO") else: print("YES")
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
1
n=input() for i in range(n): s=raw_input() if(len(s)<=10): print s else: print s[0] +str(len(s)-2)+s[len(s)-1]
There are n points on the plane, (x_1,y_1), (x_2,y_2), …, (x_n,y_n). You need to place an isosceles triangle with two sides on the coordinate axis to cover all points (a point is covered if it lies inside the triangle or on the side of the triangle). Calculate the minimum length of the shorter side of the triangle. I...
3
from sys import exit n = int(input()) ans = 0 for i in range(n): a, b = map(int, input().split()) ans = max(ans, a + b) print(ans)
Dawid has four bags of candies. The i-th of them contains a_i candies. Also, Dawid has two friends. He wants to give each bag to one of his two friends. Is it possible to distribute the bags in such a way that each friend receives the same amount of candies in total? Note, that you can't keep bags for yourself or thro...
3
a,b,c,d = map(int,input().split(" ")) if(a+b==c+d): print("YES") elif(a+c==b+d): print("YES") elif(a+d==c+b): print("YES") elif(a+b+c==d): print("YES") elif(a+b+d==c): print("YES") elif(a+c+d==b): print("YES") elif(b+c+d==a): print("YES") else: print("NO")
Your friend who lives in undisclosed country is involved in debt. He is borrowing 100,000-yen from a loan shark. The loan shark adds 5% interest of the debt and rounds it to the nearest 1,000 above week by week. Write a program which computes the amount of the debt in n weeks. Input An integer n (0 ≤ n ≤ 100) is g...
3
T=100000 n=int(input()) for x in range(n): T*=1.05 if T%1000==0: pass else: T=T-(T%1000)+1000 print(int(T))
Petya works as a PR manager for a successful Berland company BerSoft. He needs to prepare a presentation on the company income growth since 2001 (the year of its founding) till now. Petya knows that in 2001 the company income amounted to a1 billion bourles, in 2002 — to a2 billion, ..., and in the current (2000 + n)-th...
3
import sys k = sys.stdin.readline() while k: line = sys.stdin.readline() curr = 1 years = [] for i, x in enumerate(line.split()): if int(x) == curr: years.append(str(2000+int(i+1))) curr += 1 if curr == 1: print(0) else: print(curr-1) prin...
Ashish has two strings a and b, each of length n, and an integer k. The strings only contain lowercase English letters. He wants to convert string a into string b by performing some (possibly zero) operations on a. In one move, he can either * choose an index i (1 ≤ i≤ n-1) and swap a_i and a_{i+1}, or * choos...
3
import sys input = sys.stdin.readline def prog(): for _ in range(int(input())): n,k = map(int,input().split()) strings = [input().strip(),input().strip()] amts = [[0]*26 for i in range(2)] total = 0 total2 = 0 worked = True for i in range(2): ...
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 _ in range(t): a, b = map(int, input().split()) k = abs(a-b) print(k//10 + int(k%10!=0))
Cat Noku has obtained a map of the night sky. On this map, he found a constellation with n stars numbered from 1 to n. For each i, the i-th star is located at coordinates (xi, yi). No two stars are located at the same position. In the evening Noku is going to take a look at the night sky. He would like to find three d...
1
__author__ = 'aste' def triangle_area(a, b, c): return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]); def main(): n = int(raw_input()) points = [] for i in range(0, n): x, y = map(int, raw_input().split()) points.append((x, y, i + 1)) points.sort() for i in ra...
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
if __name__ == '__main__': n, m = map(int, input().split(" ")) known_sequence = list(map(int, input().split(" "))) fingerprint_buttons = set(map(int, input().split(" "))) intersect = set(known_sequence) & fingerprint_buttons answer = [] for d in known_sequence: if d in intersect: ...
You are given three positive (i.e. strictly greater than zero) integers x, y and z. Your task is to find positive integers a, b and c such that x = max(a, b), y = max(a, c) and z = max(b, c), or determine that it is impossible to find such a, b and c. You have to answer t independent test cases. Print required a, b a...
3
t=int(input()) for case in range(t) : List=[int(j) for j in input().split(" ")] List.sort() if List[1]==List[2]: print("YES") print("1", end=" ") print(List[0],end=" ") print(List[1]) else: print("NO")
Polycarp has n coins, the value of the i-th coin is a_i. Polycarp wants to distribute all the coins between his pockets, but he cannot put two coins with the same value into the same pocket. For example, if Polycarp has got six coins represented as an array a = [1, 2, 4, 3, 3, 2], he can distribute the coins into two ...
3
n = int(input()) a = input().split() x = 0 for i in a: if a.count(i) > x: x = a.count(i) print(x)
ZS the Coder is coding on a crazy computer. If you don't type in a word for a c consecutive seconds, everything you typed disappear! More formally, if you typed a word at second a and then the next word at second b, then if b - a ≤ c, just the new word is appended to other words on the screen. If b - a > c, then ever...
3
def answer(): a = [int(x) for x in input().split()] b = [int(x) for x in input().split()] c = [] i=0 while i<len(b)-1: diff = -b[i]+b[i+1] c.append((diff)) i+=1 sub=0 i=len(c)-1 j=0 #print(c) while i>=0: j+=1 if c[i]>a[1]: retur...
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array. According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the requ...
3
n = int(input()) a = {int(i):idx for idx,i in enumerate(input().split())} m = int(input()) ma = [int(i) for i in input().split()] v = 0 p = 0 for i in ma: idx = a[i] v += (idx+1) p += (n-idx) print(v,p)
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())-1 s=input() k=1 while n!=0: n-=1 if input()!=s: k+=1 s=s[::-1] print(k)
Ilya got tired of sports programming, left university and got a job in the subway. He was given the task to determine the escalator load factor. Let's assume that n people stand in the queue for the escalator. At each second one of the two following possibilities takes place: either the first person in the queue ente...
1
n, p, t = map(float, raw_input().split()) n = int(n) t = int(t) s = 0 z = [] for i in range(0,n+1): z.append(0) z[0] = 1 for i in range(1,t+1): for j in range(n,-1,-1): if j > 0 and j < n: z[j] = (z[j-1]*p+z[j]*(1-p)) elif j == n: z[j] = z[j-1]*p + z[j] else: ...
You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft k torches. One torch can be crafted using one stick and one coal. Hopefully, you've met a very handsome wandering trader who has two trade offers: * exchange 1 stick for x sticks (you lose 1 stick and gain x sticks...
3
for i in range(int(input())): l = [int(j) for j in input().split(" ")] ans=0 coal = l[2] ans+=coal stickreq = coal*l[1]+l[2] steps = int((stickreq-1)//(l[0]-1)) if (stickreq-1)%(l[0]-1)!=0: steps+=1 ans+=steps print(ans)
NN is an experienced internet user and that means he spends a lot of time on the social media. Once he found the following image on the Net, which asked him to compare the sizes of inner circles: <image> It turned out that the circles are equal. NN was very surprised by this fact, so he decided to create a similar pi...
1
from math import sin, pi n, r = map(float, raw_input().split()) print sin(pi/n)*r/(1-sin(pi/n))
There is a house with n flats situated on the main street of Berlatov. Vova is watching this house every night. The house can be represented as an array of n integer numbers a_1, a_2, ..., a_n, where a_i = 1 if in the i-th flat the light is on and a_i = 0 otherwise. Vova thinks that people in the i-th flats are distur...
3
x = int(input()) y = [int(i) for i in input().split()] z = 0 for i in range(1, x-1): if y[i] == 0 and y[i-1] == y[i+1] == 1: y[i+1] = 0 z += 1 print(z)
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different. Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some num...
3
s=input() s=input() ele=[] ans=0 if len(s)>26: print(-1) else: for i in s: if i in ele: ans+=1 else: ele.append(i) print(ans)
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
s = input() t = input() ls = len(s) lt = len(t) inds = ls - 1 indt = lt - 1 while inds >= 0 and indt >= 0 and s[inds] == t[indt]: inds -= 1 indt -= 1 print(inds + indt + 2)
There is a graph of n rows and 10^6 + 2 columns, where rows are numbered from 1 to n and columns from 0 to 10^6 + 1: <image> Let's denote the node in the row i and column j by (i, j). Initially for each i the i-th row has exactly one obstacle — at node (i, a_i). You want to move some obstacles so that you can reach ...
1
from __future__ import division, print_function from itertools import permutations import threading,bisect,math,heapq,sys from collections import deque # threading.stack_size(2**27) # sys.setrecursionlimit(10**4) from sys import stdin, stdout i_m=9223372036854775807 def cin(): return map(int,sin().split()) def...
Your math teacher gave you the following problem: There are n segments on the x-axis, [l_1; r_1], [l_2; r_2], …, [l_n; r_n]. The segment [l; r] includes the bounds, i.e. it is a set of such x that l ≤ x ≤ r. The length of the segment [l; r] is equal to r - l. Two segments [a; b] and [c; d] have a common point (inters...
3
t = int(input()) mas = [] for i in range(t): n = int(input()) mas_x = [] mas_y = [] for j in range(n): x, y = map(int, input().split()) mas_x.append(x) mas_y.append(y) mas_x.sort() mas_y.sort() x = mas_x[-1] y = mas_y[0] a = x-y if a<0: a = 0 m...
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them. Input The first line contains integ...
3
b = int(input()) a = input() ans = 0 for m in range(1,b): if a[m] == a[m-1]: ans += 1 print(ans)
Panic is rising in the committee for doggo standardization — the puppies of the new brood have been born multi-colored! In total there are 26 possible colors of puppies in the nature and they are denoted by letters from 'a' to 'z' inclusive. The committee rules strictly prohibit even the smallest diversity between dog...
3
b = int(input()) a = input() n = 0 if(b==len(a)): while(n<len(a)): if((a.count(a[n])>1) or (b==1)): x=0 break else: x=1 n = n+1 if(x==1): print('No') else: print('Yes')
Sheldon, Leonard, Penny, Rajesh and Howard are in the queue for a "Double Cola" drink vending machine; there are no other people in the queue. The first one in the queue (Sheldon) buys a can, drinks it and doubles! The resulting two Sheldons go to the end of the queue. Then the next in the queue (Leonard) buys a can, d...
1
n = input() t = 1 while n > 5*t: n -= 5*t t *= 2 if n <= t: print 'Sheldon' elif n <= 2*t: print 'Leonard' elif n <= 3*t: print 'Penny' elif n <= 4*t: print 'Rajesh' else: print 'Howard'
You have a string A = A_1 A_2 ... A_n consisting of lowercase English letters. You can choose any two indices i and j such that 1 \leq i \leq j \leq n and reverse substring A_i A_{i+1} ... A_j. You can perform this operation at most once. How many different strings can you obtain? Constraints * 1 \leq |A| \leq 200...
3
s=input() l={} for i in s: if i in l: l[i]+=1 else: l[i]=1 def c(x): return x*(x-1)//2 sm=c(len(s)) for i in l: sm-=c(l[i]) print(sm+1)
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
from math import * n=int(input()) l=list(map(int,input().split())) r=[None]*n j=1 for i in l: r[i-1]=j j+=1 print(*r)
Today, Yasser and Adel are at the shop buying cupcakes. There are n cupcake types, arranged from 1 to n on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type i is an integer a_i. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative. Yasser, ...
3
num_t = int(input()) for t in range(num_t): n = int(input()) arr = [int(a) for a in input().strip().split()] pref_sum = 0 ok = True for e in arr: pref_sum += e if pref_sum <= 0: ok = False break suf_sum = 0 for e in arr[::-1]: suf_sum += e ...
Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be. ...
1
def check(s, t, dict): return not(dict.has_key(s)) or dict[s]==t def main(): exp=raw_input() real=raw_input() dict={} inv_dict={} n=len(exp) for i in xrange(0,n): tmp=[exp[i],real[i]] tmp.sort() s,t=tmp if s!=t: if dict.has_key(s) and dict[s]!=t: ...
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: * Tetrahedron. Tetrahedron has 4 triangular faces. * Cube. Cube has 6 square faces. * Octahedron. Octahedron has 8 triangular faces. * Dodecahedron. Dodecahedron has 12 pentagonal faces. *...
3
def sum(a): s=0 while a>0: s=s+a%10 a//=10 return s ans=0 for i in range(int(input())): x=input() if x == 'Tetrahedron': ans+=4 elif x== 'Cube': ans+=6 elif x== 'Octahedron': ans+=8 elif x== 'Dodecahedron': ans+=12 elif x== 'Icosahedron...
You are given an array a consisting of n integers. In one move, you can jump from the position i to the position i - a_i (if 1 ≤ i - a_i) or to the position i + a_i (if i + a_i ≤ n). For each position i from 1 to n you want to know the minimum the number of moves required to reach any position j such that a_j has the ...
3
from collections import deque import os import sys from io import BytesIO, IOBase from types import GeneratorType from collections import defaultdict BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writa...
Little girl Margarita is a big fan of competitive programming. She especially loves problems about arrays and queries on them. Recently, she was presented with an array a of the size of 10^9 elements that is filled as follows: * a_1 = -1 * a_2 = 2 * a_3 = -3 * a_4 = 4 * a_5 = -5 * And so on ... ...
3
# import sys # sys.stdin=open("input.in",'r') # sys.stdout=open("output.out",'w') def solve(n): if n%2==0: return n//2 else: return (-n+ (n-1)//2) n=int(input()) for i in range(n): l,r=map(int,input().split()) print(solve(r)-solve(l-1))
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them. Input The first line contains integ...
3
def main(): n = int(input()) pattern = input() previousStone = pattern[0] count = 0 for i in pattern[1:]: nextStone = i # print(previousStone, nextStone) if previousStone == nextStone: count += 1 previousStone = nextStone print(count) if __name__ == '_...
We have an integer sequence A, whose length is N. Find the number of the non-empty contiguous subsequences of A whose sums are 0. Note that we are counting the ways to take out subsequences. That is, even if the contents of some two subsequences are the same, they are counted individually if they are taken from differ...
3
import collections n = int(input()) a = [int(i) for i in input().split()] s = [a[0]] for i in range(1,n):s.append(s[i-1]+a[i]) c = collections.Counter(s) d = [i*(i-1)//2 for i in c.values()] print(sum(d)+c[0])
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
def nearly_lucky_number(string): lucky_digits = 0 for letter in string: if letter == '4' or letter == '7': lucky_digits += 1 return lucky_digits == 4 or lucky_digits == 7 print("YES" if nearly_lucky_number(input()) else "NO")
ZS the Coder is coding on a crazy computer. If you don't type in a word for a c consecutive seconds, everything you typed disappear! More formally, if you typed a word at second a and then the next word at second b, then if b - a ≤ c, just the new word is appended to other words on the screen. If b - a > c, then ever...
3
n, c = map(int, input().split()) a = list(map(int, input().split())) if c == 0: print(0) else: i = 1 while n > 1: n = n - 1 if a[n] - a[n-1] <= c: i += 1 else: break print(i)
Bob is a pirate looking for the greatest treasure the world has ever seen. The treasure is located at the point T, which coordinates to be found out. Bob travelled around the world and collected clues of the treasure location at n obelisks. These clues were in an ancient language, and he has only decrypted them at hom...
3
n=int(input()) xy=[];ab=[] for i in range(n): xy.append(list(map(int,input().split()))) for i in range(n): ab.append(list(map(int,input().split()))) ans=[] for i in xy: for j in ab: ans.append((i[0]+j[0],i[1]+j[1])) d={} for i in ans: if i in d: d[i]+=1 if d[i]==n: pr...