problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
Sonya decided to organize an exhibition of flowers. Since the girl likes only roses and lilies, she decided that only these two kinds of flowers should be in this exhibition. There are n flowers in a row in the exhibition. Sonya can put either a rose or a lily in the i-th position. Thus each of n positions should cont...
1
n = int(raw_input().split(' ')[0]) print ''.join(map(str, [0, 1] * (n / 2) + ([0] if n & 1 else [])))
Each of you probably has your personal experience of riding public transportation and buying tickets. After a person buys a ticket (which traditionally has an even number of digits), he usually checks whether the ticket is lucky. Let us remind you that a ticket is lucky if the sum of digits in its first half matches th...
3
n=int(input()) pat=input() a=[] b=[] for i in range(n): a.append(int(pat[i])) for i in range(n): l = i + n b.append(int(pat[l])) a.sort() b.sort() k=0 if a[0] > b[0]: for i in range(n): if a[i]<=b[i]: print("NO") k=-1 break elif a[0] < b[0]: for i in range...
A binary string is a string where each character is either 0 or 1. Two binary strings a and b of equal length are similar, if they have the same character in some position (there exists an integer i such that a_i = b_i). For example: * 10010 and 01111 are similar (they have the same character in position 4); * 10...
3
#!/usr/bin/env python3 import sys input = sys.stdin.readline t = int(input()) for _ in range(t): n = int(input()) s = input().rstrip() print(s[n-1] * n)
You are given a text consisting of n lines. Each line contains some space-separated words, consisting of lowercase English letters. We define a syllable as a string that contains exactly one vowel and any arbitrary number (possibly none) of consonants. In English alphabet following letters are considered to be vowels:...
3
import sys input() a=list(map(int, input().split())) ans=all(sum(s.count(c) for c in 'aeiouy')==a.pop(0) for s in sys.stdin) print('YES' if ans else 'NO')
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
l = raw_input() k = raw_input() if l[::-1] == k: print "YES" else: print "NO"
Mishka got an integer array a of length n as a birthday present (what a surprise!). Mishka doesn't like this present and wants to change it somehow. He has invented an algorithm and called it "Mishka's Adjacent Replacements Algorithm". This algorithm can be represented as a sequence of steps: * Replace each occurre...
3
R = lambda: map(int, input().split()) n = int(input()) a = list(R()) b = list(map(lambda x: x if x%2 else x-1, a)) print(*b, sep=' ')
The only difference between easy and hard versions is constraints. The BerTV channel every day broadcasts one episode of one of the k TV shows. You know the schedule for the next n days: a sequence of integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ k), where a_i is the show, the episode of which will be shown in i-th day. The...
3
t = int(input()) for i in range(t): n, k, d = map(int, input().split()) serials = list(map(int, input().split())) nums = [] for j in range(0, n - d + 1): nums.append(len(set(serials[j:j + d]))) print(min(nums))
There are n people who want to participate in a boat competition. The weight of the i-th participant is w_i. Only teams consisting of two people can participate in this competition. As an organizer, you think that it's fair to allow only teams with the same total weight. So, if there are k teams (a_1, b_1), (a_2, b_2)...
3
t=int(input()) for i in range(t): n=int(input()) a=list(map(int,input().split())) d={} for x in a: if x not in d: d[x]=1 else: d[x]+=1 ans=0 for i in range(1,101): dt=d.copy() s=0 for j in a: if(dt[j]<=0): ...
The Little Elephant has an integer a, written in the binary notation. He wants to write this number on a piece of paper. To make sure that the number a fits on the piece of paper, the Little Elephant ought to delete exactly one any digit from number a in the binary record. At that a new number appears. It consists of ...
3
def delete(arr, i): n = len(arr) for i in range(i , n-1): arr[i] = arr[i+1] return arr[:n-1] s = input() s = list(s) f = 1 for i in range(len(s)): if(s[i] == '0'): s = delete(s, i) f = 0 break if(f): s = delete(s, len(s)-1) print("".join(s))
Leo has developed a new programming language C+=. In C+=, integer variables can only be changed with a "+=" operation that adds the right-hand side value to the left-hand side variable. For example, performing "a += b" when a = 2, b = 3 changes the value of a to 5 (the value of b does not change). In a prototype progr...
3
t = int(input()) for _ in range(t): a,b,n = [int(i) for i in input().split()] if a < b: a,b = b,a tmp = 0 count =0 if a > n or b > n: print(0) else: while tmp <= n: tmp = a + b b = a a = tmp count += 1 print(count)
Karen is getting ready for a new school day! <image> It is currently hh:mm, given in a 24-hour format. As you know, Karen loves palindromes, and she believes that it is good luck to wake up when the time is a palindrome. What is the minimum number of minutes she should sleep, such that, when she wakes up, the time i...
3
def parse(n): if n[0] == '0': return int(n[1]) else: return int(n) def Func(time): if time == time[::-1]: return 0 a , b = time.split(':') r = a[::-1] if a == '23' and int(b) > 32: return 60 - int(b) ls = [(1,10), (2,20), (3,30), (4,40), (5,50), (10,1), (11,11),(12,21...
You are given a non-negative integer n, its decimal representation consists of at most 100 digits and doesn't contain leading zeroes. Your task is to determine if it is possible in this case to remove some of the digits (possibly not remove any digit at all) so that the result contains at least one digit, forms a non-...
3
s = input() n = len(s) f = False for i in range(n): for j in range(i+1, n): for k in range(j+1, n): if not f and not (s[i] == s[j] == s[k] == '0') and int(s[i]+s[j]+s[k]) % 8 == 0: f = True print('YES') print((s[i]+s[j]+s[k])) if not f: for i ...
A card pyramid of height 1 is constructed by resting two cards against each other. For h>1, a card pyramid of height h is constructed by placing a card pyramid of height h-1 onto a base. A base consists of h pyramids of height 1, and h-1 cards on top. For example, card pyramids of heights 1, 2, and 3 look as follows: ...
3
import math t = int(input()) for _ in range(t): n=int(input()) c=0 while(n>1): x=int((-1+(1+24*n)**(1/2))//6) c=c+1 n =n-((3*(x**2)+x)//2) print(c)
You are given a matrix a of size n × m consisting of integers. You can choose no more than \left⌊m/2\right⌋ elements in each row. Your task is to choose these elements in such a way that their sum is divisible by k and this sum is the maximum. In other words, you can choose no more than a half (rounded down) of eleme...
3
n, m, k = map(int, input().split()) # a = [] # for _ in range(n): # a.append(list(map(int, input().split()))) dp = [float("-inf") for i in range(k)] dp[0] = 0 sz = m // 2 for _ in range(n): a = list(map(int, input().split())) pre = dp dp = [[float("-inf") for _ in range(k)] for _ in range(sz + 1)] dp[0] = pre ...
Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are n drinks in his fridge, the volume fraction of orange juice in the i-th drink equals pi percent. One day Vasya decided to make himself an orange cocktail. He took equal proportions of ea...
3
n = int(input()) a = list(map(int, input().split())) a = [i / 100 for i in a] print("{:.12f}".format(sum(a) / n * 100))
You are given two arrays a and b both consisting of n positive (greater than zero) integers. You are also given an integer k. In one move, you can choose two indices i and j (1 ≤ i, j ≤ n) and swap a_i and b_j (i.e. a_i becomes b_j and vice versa). Note that i and j can be equal or different (in particular, swap a_2 w...
3
from functools import reduce import sys class Read: @staticmethod def string(): return input() @staticmethod def int(): return int(input()) @staticmethod def list(delimiter=' '): return input().split(delimiter) @staticmethod def list_int(delimiter=' '): ...
You are given an integer n and an integer k. In one step you can do one of the following moves: * decrease n by 1; * divide n by k if n is divisible by k. For example, if n = 27 and k = 3 you can do the following steps: 27 → 26 → 25 → 24 → 8 → 7 → 6 → 2 → 1 → 0. You are asked to calculate the minimum numbe...
3
t=0 n=[] k=[] a=0 def Input(): global n,k,t t=int(input()) for index in range(t): x,y=list(map(int,input().split())) n.append(x) k.append(y) def Output(): global n,k,t for index in range(t): count=0 while n[index]!=0: if n[index]%k[index]==0: count+=1 n[index]=n[ind...
IT City company developing computer games invented a new way to reward its employees. After a new game release users start buying it actively, and the company tracks the number of sales with precision to each transaction. Every time when the next number of sales is divisible by all numbers from 2 to 10 every developer ...
3
n = int(input()) up_to_k = 2520*[0] num = 0 for i in range(2520): for j in range(2, 11): if (i + 1) % j == 0: break else: num += 1 up_to_k[i] = num div = n // 2520 rem = n % 2520 if (rem == 0): print(div * up_to_k[-1]) else: print(div * up_to_k[-1] + up_to_k[rem - 1])
Given an array of N elements, check if it is possible to obtain a sum of S, by choosing some (or none) elements of the array and adding them. Input: First line of the input contains number of test cases T. Each test case has three lines. First line has N, the number of elements in array. Second line contains N space s...
1
import sys T = int(sys.stdin.readline()) while T > 0: N = int(sys.stdin.readline()) nums = map(int, sys.stdin.readline().split()) S = int(sys.stdin.readline()) if S == 0: print 'YES' else: def memo(func): cache = {} def solve_memo(*args): if cache.has_key(args) == False: cache[args] = func(*arg...
The only difference between easy and hard versions is on constraints. In this version constraints are lower. You can make hacks only if all versions of the problem are solved. Koa the Koala is at the beach! The beach consists (from left to right) of a shore, n+1 meters of sea and an island at n+1 meters from the shor...
3
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 from bisect import bisect_left as lower_bound, bisect_right as upper_bound def so(): ...
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). For a positive integer n, we call a...
3
for _ in range(int(input())): print(' '.join(map(str, range(1, int(input()) + 1))))
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it: * deletes all the vowels, * inserts a character "." before each consonant, * repl...
1
s=raw_input() print('.'+'.'.join(i for i in s if i.lower() not in 'aeiouy').lower())
There are N mountains ranging from east to west, and an ocean to the west. At the top of each mountain, there is an inn. You have decided to choose where to stay from these inns. The height of the i-th mountain from the west is H_i. You can certainly see the ocean from the inn at the top of the westmost mountain. F...
3
input() ans, mx = 0, 0 for i in list(map(int, input().split())): if mx <= i: ans += 1 mx = i print(ans)
You are given a rooted tree with n vertices. The vertices are numbered from 1 to n, the root is the vertex number 1. Each vertex has a color, let's denote the color of vertex v by cv. Initially cv = 0. You have to color the tree into the given colors using the smallest possible number of steps. On each step you can c...
3
from sys import stdin, stdout import math,sys,heapq from itertools import permutations, combinations from collections import defaultdict,deque,OrderedDict from os import path import random import bisect as bi def yes():print('YES') def no():print('NO') if (path.exists('input.txt')): #------------------Sublime-----...
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow th...
1
n = int(raw_input()) for x in xrange(n): cell = raw_input() j = 0 while not cell[j].isdigit(): j += 1 i = j while i < len(cell) and cell[i].isdigit(): i += 1 if i == len(cell): z = 0 col = 0 for y in list(cell[:j])[::-1]: ...
You are playing a game where your character should overcome different obstacles. The current problem is to come down from a cliff. The cliff has height h, and there is a moving platform on each height x from 1 to h. Each platform is either hidden inside the cliff or moved out. At first, there are n moved out platforms...
3
# -*- coding: utf-8 -*- import sys def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a...
There is a bookshelf which can fit n books. The i-th position of bookshelf is a_i = 1 if there is a book on this position and a_i = 0 otherwise. It is guaranteed that there is at least one book on the bookshelf. In one move, you can choose some contiguous segment [l; r] consisting of books (i.e. for each i from l to r...
3
t = int(input()) for z in range(t): n = int(input()) a = list(map(int, input().split(' '))) b = [] cnt = 0 for i in range(n): if (a[i] == 0): cnt+=1 elif(i == 0 or cnt != 0): b.append(cnt) cnt = 0 b.append(cnt) sm = 0 for i in range(1,...
Recall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples: * for the array [0, 0, 1, 0, 2] MEX equals to 3 because numbers 0, 1 and 2 are presented in the array and 3 is the minimum non-negative integer not presented in the array; * for the array [1, 2, 3, 4] MEX eq...
3
from sys import stdin, stdout q, x = map(int, stdin.readline().split()) mex=0 l=[0]*(x+1) for i in range(q): n=int(stdin.readline()) l[n%x]+=1 while(l[mex%x]): l[mex%x]-=1 mex+=1 print (mex)
Write a program which manipulates a sequence A = {a0, a1, . . . , an-1} with the following operations: * find(s, t): report the minimum element in as, as+1, . . . ,at. * update(i, x): change ai to x. Note that the initial values of ai (i = 0, 1, . . . , n−1) are 231-1. Constraints * 1 ≤ n ≤ 100000 * 1 ≤ q ≤ 10000...
3
class SegmentTree: def __init__(self, N_, element, function_=(lambda l, r: l + r)): """ :param N_: セグ木のサイズ :param element: 単位元 :param function: 子の要素に対して行われる計算,デフォルトだと加算 """ self.N = 1 while self.N < N_: self.N *= 2 self.element = element ...
Each of you probably has your personal experience of riding public transportation and buying tickets. After a person buys a ticket (which traditionally has an even number of digits), he usually checks whether the ticket is lucky. Let us remind you that a ticket is lucky if the sum of digits in its first half matches th...
1
n = input() number_str = map(int, list(raw_input())) first_half, second_half = number_str[:n], number_str[n:] large_count = 0 less_count = 0 for i in range(n): if max(first_half) == max(second_half): large_count += 1 less_count += 1 elif max(first_half) > max(second_half): large_count +=...
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya wonders eagerly what minimum lucky number has the sum of digits equal to n. Help him cope with...
3
import sys input = sys.stdin.readline for _ in range(1): n=int(input()) c4=0 while n%7!=0: n-=4 c4+=1 if n<0: print(-1) else: print('4'*c4+'7'*(n//7))
A Hitachi string is a concatenation of one or more copies of the string `hi`. For example, `hi` and `hihi` are Hitachi strings, while `ha` and `hii` are not. Given a string S, determine whether S is a Hitachi string. Constraints * The length of S is between 1 and 10 (inclusive). * S is a string consisting of lowerc...
3
print('YNeos'[1-(input()in['hi'*i for i in range(11)])::2])
Two players play a simple game. Each player is provided with a box with balls. First player's box contains exactly n1 balls and second player's box contains exactly n2 balls. In one move first player can take from 1 to k1 balls from his box and throw them away. Similarly, the second player can take from 1 to k2 balls f...
3
nn=input() nn=nn.split() n1=int(nn[0]) n2=int(nn[1]) k1=int(nn[2]) k2=int(nn[3]) if n1>n2: print('First') else: print('Second')
You took a peek on Thanos wearing Infinity Gauntlet. In the Gauntlet there is a place for six Infinity Gems: * the Power Gem of purple color, * the Time Gem of green color, * the Space Gem of blue color, * the Soul Gem of orange color, * the Reality Gem of red color, * the Mind Gem of yellow color. ...
3
d = dict(zip("purple, green, blue, orange, red, yellow".split(", "), "Power, Time, Space, Soul, Reality, Mind".split(", "))) for _ in [0]*int(input()): d.pop(input()) print(len(d),*d.values(),sep='\n')
Nastya just made a huge mistake and dropped a whole package of rice on the floor. Mom will come soon. If she sees this, then Nastya will be punished. In total, Nastya dropped n grains. Nastya read that each grain weighs some integer number of grams from a - b to a + b, inclusive (numbers a and b are known), and the wh...
3
T=int(input()) for t in range(T): n,a,b,c,d=map(int,input().split()) mn=a-b mx=a+b flag=0 if n*mn>c+d: flag=1 if n*mx<c-d: flag=1 if flag==1: print("NO") else: print("YES")
Given an integer x, find 2 integers a and b such that: * 1 ≤ a,b ≤ x * b divides a (a is divisible by b). * a ⋅ b>x. * a/b<x. Input The only line contains the integer x (1 ≤ x ≤ 100). Output You should output two integers a and b, satisfying the given conditions, separated by a space. If no pair of in...
3
n=int(input()) if(n*n>n and n/n<n): print(n,n) else: print(-1)
"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()) all = [int(i) for i in input().split()] count = 0 for j in range(len(all)): if all[j] >= all[k-1] and all[j] > 0 : count+=1 print(count)
Masha lives in a multi-storey building, where floors are numbered with positive integers. Two floors are called adjacent if their numbers differ by one. Masha decided to visit Egor. Masha lives on the floor x, Egor on the floor y (not on the same floor with Masha). The house has a staircase and an elevator. If Masha u...
3
x,y,z,a,b,c=map(int,input().split());print("YES" if (abs(x-z)*b+abs(x-y)*b+3*c<=abs(x-y)*a) else "NO")
Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of length k have the same sum. A subarray of an array is any sequence of consecutive elements. Phoenix currently has an array a of length n. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautifu...
3
import os import sys from io import BytesIO, IOBase def solution(arr, n, k): if n == k: write(n) write(*arr) return st = sorted(x for x in set(arr)) if len(st) > k: write(-1) return if k == 1: write(len(arr)) write(*arr) return res...
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
n = int(input()) i = 0 a = [] output = 0 tetrahedron = "Tetrahedron" cube = "Cube" octahedron = "Octahedron" dodecahedron = "Dodecahedron" icosahedron = "Icosahedron" while i < n: a.append(input()) i += 1 for ngone in a: if ngone == tetrahedron: output += 4 elif ngone == cube: output ...
You are given two integers x and y (it is guaranteed that x > y). You may choose any prime integer p and subtract it any number of times from x. Is it possible to make x equal to y? Recall that a prime number is a positive integer that has exactly two positive divisors: 1 and this integer itself. The sequence of prime...
3
t=int(input()) for _ in range(t): x,y=map(int,(input().split())) if x>y+1: print("YES") else: print("NO")
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them. Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain nu...
3
n=(input().split("WUB")) print(*n)
Duff is addicted to meat! Malek wants to keep her happy for n days. In order to be happy in i-th day, she needs to eat exactly ai kilograms of meat. <image> There is a big shop uptown and Malek wants to buy meat for her from there. In i-th day, they sell meat for pi dollars per kilogram. Malek knows all numbers a1, ....
3
n=int(input()) m=100 s=0 for _ in range(n): a,b=map(int,input().split()) m=min(m,b) s=s+a*m print(s)
While playing with geometric figures Alex has accidentally invented a concept of a n-th order rhombus in a cell grid. A 1-st order rhombus is just a square 1 × 1 (i.e just a cell). A n-th order rhombus for all n ≥ 2 one obtains from a n-1-th order rhombus adding all cells which have a common side with it to it (look ...
1
""" Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. * Readability counts * // Author : raj1307 - Raj Singh // Date...
Statistics claims that students sleep no more than three hours a day. But even in the world of their dreams, while they are snoring peacefully, the sense of impending doom is still upon them. A poor student is dreaming that he is sitting the mathematical analysis exam. And he is examined by the most formidable profess...
3
def student_dream(x1, y1, x2, y2): if x1 - 1 <= y2 <= 2 * (x1 + 1) or y1 - 1 <= x2 <= 2 * (y1 + 1): return "YES" return "NO" X1, Y1 = [int(i) for i in input().split()] X2, Y2 = [int(j) for j in input().split()] print(student_dream(X1, Y1, X2, Y2))
Given are a positive integer N and a string S of length N consisting of lowercase English letters. Determine whether the string is a concatenation of two copies of some string. That is, determine whether there is a string T such that S = T + T. Constraints * 1 \leq N \leq 100 * S consists of lowercase English letter...
3
n=int(input()); s=str(input()); if s[:n//2]==s[n//2:]: print("Yes"); else: print("No");
After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum nu...
3
stud = int(input()) st = map(int, input().split()) c1 = c2 = c3 = c4 = answer = 0 for i in st: if i == 1: c1 += 1 elif i == 2: c2 += 1 elif i == 3: c3 += 1 else: c4 += 1 answer = c4 answer += c2 // 2 c2 %= 2 if c1 <= c3: answer += c1 answer += c2 answer += c...
One day Misha and Andrew were playing a very simple game. First, each player chooses an integer in the range from 1 to n. Let's assume that Misha chose number m, and Andrew chose number a. Then, by using a random generator they choose a random integer c in the range between 1 and n (any integer from 1 to n is chosen w...
1
line = raw_input().split(' ') limit = int(line[0]) other = int(line[1]) if limit == 1: print 1 else: sol = -1 + other if limit - other > other - 1: sol = 1 + other print sol
This problem is same as the next one, but has smaller constraints. It was a Sunday morning when the three friends Selena, Shiro and Katie decided to have a trip to the nearby power station (do not try this at home). After arriving at the power station, the cats got impressed with a large power transmission system cons...
3
n=int(input()) x=[0 for i in range(0,n+1)] y=[0 for i in range(0,n+1)] for i in range(1,n+1): x[i],y[i]=map(int,input().split()) di={} for i in range(1,n+1): a={}; for j in range(i+1,n+1): if x[j]-x[i]==0: if '0' not in a: a['0']=1 else: a['0']=a['0']+1 else: k=(y[j]-y[i])/(x[j]-x[i]) if k no...
You are given an integer x. Can you make x by summing up some number of 11, 111, 1111, 11111, …? (You can use any number among them any number of times). For instance, * 33=11+11+11 * 144=111+11+11+11 Input The first line of input contains a single integer t (1 ≤ t ≤ 10000) — the number of testcases. The fi...
3
for _ in range(int(input())): # n = int(input()) # a = [int(y) for y in input().split()] # # r, c, x = [int(y) for y in input().split()] # # n, k = [int(y) for y in input().split()] s = input() n=int(s) leng = len(s) found=False if n<10:found=False if n%11==0:found=True if n%11<=n/111:found=True else:found=...
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
import sys if __name__ == "__main__": n = int(sys.stdin.read()) if n <= 2: sys.stdout.write("NO") elif n % 2 == 0: sys.stdout.write("YES") else: sys.stdout.write("NO")
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them. Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain nu...
3
s1 = input().replace("WUB",' ') print(s1)
Note that this is the first problem of the two similar problems. You can hack this problem only if you solve both problems. You are given a tree with n nodes. In the beginning, 0 is written on all edges. In one operation, you can choose any 2 distinct leaves u, v and any real number x and add x to values written on al...
3
n = int(input()) dep = [] for i in range(n) : dep.append(0) for i in range(n-1) : a, b = input().split(' ') a = int(a) b = int(b) dep[a-1] = dep[a-1]+1 dep[b-1] = dep[b-1]+1 good = 1 for i in range(n) : if dep[i] == 2 : good = 0 if good == 1 : print('YES') else : print('NO')...
In the beginning of the new year Keivan decided to reverse his name. He doesn't like palindromes, so he changed Naviek to Navick. He is too selfish, so for a given n he wants to obtain a string of n characters, each of which is either 'a', 'b' or 'c', with no palindromes of length 3 appearing in the string as a substr...
1
import sys n = int(raw_input()) a = "aa" b = "bb" for i in range(n/2): if(i%2==0): sys.stdout.write(a) else: sys.stdout.write(b) if(n%2==1): if(n%4==1): print "a" elif(n%4==3): print "b" else: print
"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()) i = [0] * n c = list(map(int, input().split())) m = 0 for g in c: if g >= c[k - 1] and g > 0: m += 1 print(m)
This problem is actually a subproblem of problem G from the same contest. There are n candies in a candy box. The type of the i-th candy is a_i (1 ≤ a_i ≤ n). You have to prepare a gift using some of these candies with the following restriction: the numbers of candies of each type presented in a gift should be all di...
3
from collections import Counter from sys import * for _ in range(int(input())): n=int(stdin.readline()) l=list(map(int,stdin.readline().rstrip().split())) c=Counter(l) s=list(set(l)) s.sort(reverse=True) k=set() for x in s: if c[x] not in k: k.add(c[x]) else: j=c[x] for y in range(j,-1,-1): if y...
You are given an array a consisting of n integers numbered from 1 to n. Let's define the k-amazing number of the array as the minimum number that occurs in all of the subsegments of the array having length k (recall that a subsegment of a of length k is a contiguous part of a containing exactly k elements). If there i...
3
import math T = int(input()) #lets = 'abcdefghijklmnopqrstuvwxyz' #key = {lets[i]:i for i in range(26)} for t in range(T): n = int(input()) #n,k = map(int,input().split()) a = list(map(int,input().split())) #a = input() d = False m = [0]*(n+1) lm = [-1]*(n+1) app = set(a) for i in range(n): m[...
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
# ============================= # Problem - 160A - Twins # Python3 # Author - wdaubry # ============================= def main(): from sys import stdout n = int(input()) lis = list(map(int, input().split())) sum = 0 for el in lis: sum += el money = 0 ind = 0 while m...
The only difference between easy and hard versions are constraints on n and k. You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most k most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals 0...
3
from collections import deque n, k = [int(x) for x in input().split()] vals = [int(x) for x in input().split()] S = set() Q = deque() for ids in vals: if not ids in S: S.add(ids) Q.appendleft(ids) if len(Q) > k: S.remove(Q.pop()) print(len(Q)) print(*Q)
The administration of the Tomsk Region firmly believes that it's time to become a megacity (that is, get population of one million). Instead of improving the demographic situation, they decided to achieve its goal by expanding the boundaries of the city. The city of Tomsk can be represented as point on the plane with ...
3
n, s = map(int, input().split()) ml = [] def dis(x, y): return (x**2 + y**2)**0.5 for _ in range(n): x, y, i = map(int, input().split()) ml.append([dis(x, y), i]) ml.sort() r = 0 i = 0 while i < n and s < 10**6: s += ml[i][1] r = ml[i][0] i += 1 if s >= 10**6: print(r) else: print...
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 _ in range(int(input())): n = int(input()) arr = list(map(int, input().split())) i = n - 1 while i > 0 and arr[i-1] >= arr[i]: i -= 1 while i > 0 and arr[i-1] <= arr[i]: i -= 1 print(i)
Akari has n kinds of flowers, one of each kind. She is going to choose one or more of these flowers to make a bouquet. However, she hates two numbers a and b, so the number of flowers in the bouquet cannot be a or b. How many different bouquets are there that Akari can make? Find the count modulo (10^9 + 7). Here,...
3
def comb_mod(n,m,mod): p = q = 1 for i in range(m): p = p*(n-i) % mod q = q*(i+1) % mod return p* pow(q,mod-2,mod) % mod n,a,b = map(int,input().split()) mod = 10**9 +7 print( (pow(2,n,mod)-1 -comb_mod(n,a,mod) -comb_mod(n,b,mod) ) % mod )
You are given two positive integers n and k. Print the k-th positive integer that is not divisible by n. For example, if n=3, and k=7, then all numbers that are not divisible by 3 are: 1, 2, 4, 5, 7, 8, 10, 11, 13 .... The 7-th number among them is 10. Input The first line contains an integer t (1 ≤ t ≤ 1000) — the ...
3
for j in range(int(input())): n, k = map(int, input().split()) k += k // (n - 1) if not k % n: k -= 1 print(k)
Polygon is not only the best platform for developing problems but also a square matrix with side n, initially filled with the character 0. On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly 2...
3
for _ in range(int(input())): n = int(input()) l = [] for i in range(n): l.append(input()) ans = "YES" for i in range(n-1): for j in range(len(l[i])-1): if l[i][j] == "1" and l[i+1][j] == "0" and l[i][j+1] == "0": ans = "NO" break i...
Mishka wants to buy some food in the nearby shop. Initially, he has s burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1 ≤ x ≤ s, buy food that costs exactly x burles and obtain ⌊x/10⌋ burles as a cashback (in other words, Mishka ...
3
n= int(input()) #count = 0 p = 0 p = int(p) #count = int(count) def count(n,sum): if(n < 10): print(int(sum+n)) else: r = n%10 n = n-r sum += n n = n/10 n += r count(n, sum) for i in range(n): s = int(input()) count(s, 0)
Fafa owns a company that works on huge projects. There are n employees in Fafa's company. Whenever the company has a new project to start working on, Fafa has to divide the tasks of this project among all the employees. Fafa finds doing this every time is very tiring for him. So, he decided to choose the best l employ...
3
# -*- coding: utf-8 -*- """ Created on Thu May 30 08:50:33 2019 @author: avina """ n = int(input()) h = 0 for i in range(1,n): if n%i == 0: h+=1 print(h)
On a chessboard with a width of n and a height of n, rows are numbered from bottom to top from 1 to n, columns are numbered from left to right from 1 to n. Therefore, for each cell of the chessboard, you can assign the coordinates (r,c), where r is the number of the row, and c is the number of the column. The white ki...
3
n=int(input("")) x,y=map(int,input().split()) wM=max(x-1,y-1) bM=max(n-x,n-y) if(wM<=bM): print("White") else: print("Black")
Ohana Matsumae is trying to clean a room, which is divided up into an n by n grid of squares. Each square is initially either clean or dirty. Ohana can sweep her broom over columns of the grid. Her broom is very strange: if she sweeps over a clean square, it will become dirty, and if she sweeps over a dirty square, it ...
1
n=int(raw_input()) a=[] for i in range(n): a.append(map(int,raw_input().split())) g=0 for i in range(n): count=0 for j in range(n): if a[i]==a[j]: count+=1 g=max(g,count) print g
Being stuck at home, Ray became extremely bored. To pass time, he asks Lord Omkar to use his time bending power: Infinity Clock! However, Lord Omkar will only listen to mortals who can solve the following problem: You are given an array a of n integers. You are also given an integer k. Lord Omkar wants you to do k ope...
3
from sys import stdin t = int(input()) for _ in range(t): n,k = map(int,input().split()) a = list(map(int,input().split())) mx = max(a) for i in range(n): a[i] = mx - a[i] if k % 2 != 0: print(*a) continue mx = max(a) for i in range(n): a[i] = mx - a[i] p...
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()) for i in range(t): n,a,b=map(int,input().split()) c=97 s="" for i in range(a): if i<b-1: s+=str(chr(c)) c+=1 else: s+=str(chr(c)) k=0 for j in range(a,n): s+=s[k] k+=1 print(s)
problem In one programming contest, it is customary to play a bingo game at a social gathering after the competition. However, the bingo card used in this bingo game is a little special and is created according to the following conditions. * The Bingo card is divided into squares of N rows and N columns, and one posi...
3
while True: n, m, s = map(int, input().split()) if not n: break n2 = n ** 2 dpp = [0] * (s + 1) dpp[0] = 1 for i in range(1, n2 + 1): dpn = [0] * (s + 1) for j in range(i * (i + 1) // 2, s + 1): dpn[j] += dpp[j - i] + dpn[j - i] if j - m - 1 >= 0:...
There are two infinite sources of water: * hot water of temperature h; * cold water of temperature c (c < h). You perform the following procedure of alternating moves: 1. take one cup of the hot water and pour it into an infinitely deep barrel; 2. take one cup of the cold water and pour it into an infin...
3
#------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase from fractions import Fraction BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() ...
There are n warriors in a row. The power of the i-th warrior is a_i. All powers are pairwise distinct. You have two types of spells which you may cast: 1. Fireball: you spend x mana and destroy exactly k consecutive warriors; 2. Berserk: you spend y mana, choose two consecutive warriors, and the warrior with gr...
3
n,m=map(int,input().split()) x,k,y=map(int,input().split()) a=[-1]+list(map(int,input().split()))+[-2] b=[-1]+list(map(int,input().split()))+[-2] if m>n:print(-1) elif m==n:print(-int(a!=b)) else: g={} for i in range(n+2):g[a[i]]=i binds=[] for i in b: if(i not in g)or(binds and binds[-1]>g[i]):...
Alicia has an array, a_1, a_2, …, a_n, of non-negative integers. For each 1 ≤ i ≤ n, she has found a non-negative integer x_i = max(0, a_1, …, a_{i-1}). Note that for i=1, x_i = 0. For example, if Alicia had the array a = \{0, 1, 2, 0, 3\}, then x = \{0, 0, 1, 2, 2\}. Then, she calculated an array, b_1, b_2, …, b_n: ...
3
n=int(input()) b=list(map(int,input().split())) a=[None for i in range(n)] a[0]=b[0] mx=0 for i in range(1,n): mx=max(mx,a[i-1]) a[i]=b[i]+mx for i in a: print(i,end=" ")
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
w=input() unique_words = set(w) unique_word_count = len(unique_words) if unique_word_count == 2: print (0) elif unique_word_count == 3: print(1) else: print (unique_word_count-4)
Brio wants to get a beautiful house constructed near the National Highway. As his in laws are very much fond of triangles, he decided to give his house a perfect Triangular Shape. Now, here comes the problem that he faces. The plots in Hackers' Land are all circular in shape. You need to help Brio find the area of the ...
1
import sys PI = 3.1415 def f(a, b, c): p = (a + b + c) * 0.5 area2 = p * (p - a) * (p - b) * (p - c) r2 = (a * b * c)**2 / (16 * area2) return PI * r2 t = int(raw_input()) for _ in range(t): a, b, c = map(float, raw_input().split()) print("{0:.4f}".format(f(a, b, c)))
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 isSure(arr): sure=0 for item in arr: if item==1: sure+=1 if sure>=2: return 'sure' else: return 'not sure' count=0 loopCount = int(input()) for i in range(loopCount): arr = list(map(int,input().split())) if isSure(arr)=='sure': count+=1 print(count)
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word. Note, that during capitalization all the letters except the first one remains unchanged. Input A single line contains a non-empty word. This word consists of lowercase and uppercase English letters....
3
word = input() word = list(word) i = 0 new = [] if ( ord(word[i]) >= 96 and ord(word[i]) <= 123 ): z = ord(word[i]) - 32 new.append(chr(z)) else: (new.append(word[i])) i = i+1 while (i < len(word) ): new.append(word[i]) i = i+1 print(''.join(new))
Nick had received an awesome array of integers a=[a_1, a_2, ..., a_n] as a gift for his 5 birthday from his mother. He was already going to explore its various properties but after unpacking he was disappointed a lot because the product a_1 ⋅ a_2 ⋅ ... a_n of its elements seemed to him not large enough. He was ready t...
1
from sys import stdin,stdout I = lambda : map(int,stdin.readline().split()) P = lambda x: stdout.write(str(x)+" ") n = I()[0] a = I() A = [] p = 0 for i in range(n): A.append([a[i],i]) if a[i]>=0: A[i][0] = -A[i][0]-1 A.sort() if n%2: A[0][0] = - A[0][0] - 1 ans = [0]*n # print A for i in range(n): ans[A[i][1]]...
There are n piles of stones, where the i-th pile has a_i stones. Two people play a game, where they take alternating turns removing stones. In a move, a player may remove a positive number of stones from the first non-empty pile (the pile with the minimal index, that has at least one stone). The first player who canno...
3
import sys input = sys.stdin.readline I = lambda : list(map(int,input().split())) t,=I() for _ in range(t): n,=I() l=I() mv=ct=0;ix=-1 p=-1 for i in range(n): if l[i]==1: ix=i;ct+=1 elif p==-1: p=i if ct==n: mv=n%2 else: mv=(p%2==0) if mv: print("First") else: print("Second") """ First Secon...
Given a sequence of numbers a1, a2, a3, ..., an, find the maximum sum of a contiguous subsequence of those numbers. Note that, a subsequence of one element is also a contiquous subsequence. Input The input consists of multiple datasets. Each data set consists of: n a1 a2 . . an You can assume that 1 ≤ n ≤ 5000 ...
3
while 1: n = int(input()) if n == 0: break m = [None] * n t = [None] * n for i in range(n): a = int(input()) m[i] = t[i] = a for j in range(i): t[j] += a m[j] = max(m[j], t[j]) print(max(m))
Let's define the following recurrence: $$$a_{n+1} = a_{n} + minDigit(a_{n}) ⋅ maxDigit(a_{n}).$$$ Here minDigit(x) and maxDigit(x) are the minimal and maximal digits in the decimal representation of x without leading zeroes. For examples refer to notes. Your task is calculate a_{K} for given a_{1} and K. Input The ...
3
t = int(input()) for i in range(t): a,k=map(int,input().split()) l=list(map(int,str(a))) s=a for j in range(k-1): s=s+(min(l)*max(l)) if min(l)==0: break l=list(map(int,str(s))) print(s)
You are given n strings s_1, s_2, …, s_n consisting of lowercase Latin letters. In one operation you can remove a character from a string s_i and insert it to an arbitrary position in a string s_j (j may be equal to i). You may perform this operation any number of times. Is it possible to make all n strings equal? In...
3
for _ in range(int(input())): n = int(input()) d = dict() for i in range(n): a = input() for j in range(len(a)): if len(d) == 0: d[a[j]] = 1 elif a[j] in d.keys(): d[a[j]] += 1 else: d[a[j]] = 1 count = 0...
Polycarp has spent the entire day preparing problems for you. Now he has to sleep for at least a minutes to feel refreshed. Polycarp can only wake up by hearing the sound of his alarm. So he has just fallen asleep and his first alarm goes off in b minutes. Every time Polycarp wakes up, he decides if he wants to sleep...
3
import math t = int(input()) while(t>0): l = list(map(int,input().split())) a=l[0] b=l[1] c=l[2] d=l[3] if(b>=a): print(b) elif(a>b and c<=d): print(-1) else: x= math.ceil((a-b)/(c-d)) print(b+x*c) t-=1
Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1, p2, ..., pn. Your task is to find such permutation p of length n, that the group of numbers |p1 - p2|, |p2 - p3|, ..., |pn - 1 - pn| has exactly k d...
3
n,k=[int(i) for i in input().split()] r=1 k1=k+1 for i in range(k+1): if i%2==0: print(r,end=' ') r+=1 else: print(k1,end=' ') k1-=1 for i in range(k+2,n+1): print(i,end=' ')
Yesterday Oz heard a story about insect colony. The specialty of insects is that they splits sometimes i.e an insect of size A can split into two insects of positive integral sizes B and C such that A = B + C. Also sometimes they attack each other i.e. two insects of sizes P and Q will become R = P XOR Q . You are give...
1
t = input() for _ in range(t): n = map(int, raw_input().split()) a = filter(lambda x: x%2, n[1:]) if len(a)%2 == 0: print "Yes" else: print "No"
Unary is a minimalistic Brainfuck dialect in which programs are written using only one token. Brainfuck programs use 8 commands: "+", "-", "[", "]", "<", ">", "." and "," (their meaning is not important for the purposes of this problem). Unary programs are created from Brainfuck programs using the following algorithm...
3
from sys import stdin,stdout ii1 = lambda: int(stdin.readline().strip()) is1 = lambda: stdin.readline().strip() iia = lambda: list(map(int, stdin.readline().strip().split())) isa = lambda: stdin.readline().strip().split() mod = 1000003 d = { ">":1000, "<":1001, "+":1010, "-":1011, ".":1100, ",...
You took a peek on Thanos wearing Infinity Gauntlet. In the Gauntlet there is a place for six Infinity Gems: * the Power Gem of purple color, * the Time Gem of green color, * the Space Gem of blue color, * the Soul Gem of orange color, * the Reality Gem of red color, * the Mind Gem of yellow color. ...
1
map = { "purple" : "Power", "green" : "Time", "blue" : "Space", "orange" : "Soul", "red" : "Reality", "yellow" : "Mind" } n = input() a = [] for i in range(n): a.append(raw_input()) ans = [] for i in map: if i not in a: ans.append(map[i]) print len(ans) for i in ans: print...
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr...
3
s1 = input() s2 = input() s1l = list(s1) s2l = list(s2) val = '0' for i in range(len(s1l)): x = ord(s1l[i].lower()) y = ord(s2l[i].lower()) if x < y: val = '-1' break if x > y: val = '1' break print(val)
Santa has to send presents to the kids. He has a large stack of n presents, numbered from 1 to n; the topmost present has number a_1, the next present is a_2, and so on; the bottom present has number a_n. All numbers are distinct. Santa has a list of m distinct presents he has to send: b_1, b_2, ..., b_m. He will send...
3
t = int(input()) for ii in range(t): n,m = list(map(int, input().split())) a = [None] + list(map(int, input().split())) b = [None] + list(map(int, input().split())) bb = [None] * (n+2) for i in range(1,m+1): bb[b[i]] = i total = 0 last_ind = n last_b = m for i in range(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
#!/usr/bin/python a=int(input()) max=a flag=0 for i in range(2,max,2): if (a-i)%2==0 and (a-i)!=0: print("YES") flag=1 break if flag==0: print("NO")
You are given a picture consisting of n rows and m columns. Rows are numbered from 1 to n from the top to the bottom, columns are numbered from 1 to m from the left to the right. Each cell is painted either black or white. You think that this picture is not interesting enough. You consider a picture to be interesting...
3
def minim(a): smallest = min(a) return smallest, [index for index, element in enumerate(a) if smallest == element] def remove_1(inds_r, inds_c, matrix): for i in inds_r: for j in inds_c: if matrix[i][j] == '.': return -1 return 0 if __name__ =...
Ori and Sein have overcome many difficult challenges. They finally lit the Shrouded Lantern and found Gumon Seal, the key to the Forlorn Ruins. When they tried to open the door to the ruins... nothing happened. Ori was very surprised, but Sein gave the explanation quickly: clever Gumon decided to make an additional de...
3
import heapq import sys input=sys.stdin.readline class Combination: def __init__(self, n, MOD): self.fact = [1] for i in range(1, n + 1): self.fact.append(self.fact[-1] * i % MOD) self.inv_fact = [0] * (n + 1) self.inv_fact[n] = pow(self.fact[n], MOD - 2, MOD) for...
Pashmak decided to give Parmida a pair of flowers from the garden. There are n flowers in the garden and the i-th of them has a beauty number bi. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty difference i...
3
n=int(input()) a=sorted(map(int,input().split())) maxi = max(a) mini = min(a) l = len(a) print(maxi-mini,maxi != mini and a.count(maxi)*a.count(mini) or maxi==mini and (l*(l-1)//2))
Your friend has n cards. You know that each card has a lowercase English letter on one side and a digit on the other. Currently, your friend has laid out the cards on a table so only one side of each card is visible. You would like to know if the following statement is true for cards that your friend owns: "If a car...
3
x=input() print(x.count('a')+x.count('e')+x.count('i')+x.count('o')+x.count('u')+x.count('1')+x.count('3')+x.count('5')+x.count('7')+x.count('9'))
Takahashi will take part in an eating contest. Teams of N members will compete in this contest, and Takahashi's team consists of N players numbered 1 through N from youngest to oldest. The consumption coefficient of Member i is A_i. In the contest, N foods numbered 1 through N will be presented, and the difficulty of ...
3
N, K = map(int,input().split()) A = list(map(int,input().split())) F = list(map(int,input().split())) A.sort() F.sort(reverse = True) def solve(n): cnt = 0 for i in range(N): cnt += max(0, A[i] - n // F[i]) return cnt <= K left = -1 right = 10 ** 12 + 1 while left + 1 < right: mid = (left + ...
Twilight Sparkle was playing Ludo with her friends Rainbow Dash, Apple Jack and Flutter Shy. But she kept losing. Having returned to the castle, Twilight Sparkle became interested in the dice that were used in the game. The dice has m faces: the first face of the dice contains a dot, the second one contains two dots, ...
3
m,n=map(int, input().split()) m=float(m) n=float(n) x=1.0000/float(m) # x=x**n # print (x) count=0.00000 p=m while (p>0): # count=count+(p*(p**n-((p-1)**n)))*x a=((p*x)**n)-(((p-1)*x)**n) a=a*p count=count+a p=p-1 # count=float(count) # val=count*x if n==1: print (float(m+1)/2) else: ...
You are given a chessboard of size 1 × n. It is guaranteed that n is even. The chessboard is painted like this: "BWBW...BW". Some cells of the board are occupied by the chess pieces. Each cell contains no more than one chess piece. It is known that the total number of pieces equals to <image>. In one step you can mov...
1
a=input() import math c=[0]*(a+1) b=map(int,raw_input().split()) b.sort() s=0 for i in range(1,a+1,2): s+=math.fabs(b[i/2]-i) m=0 for i in range(2,a+1,2): m+=math.fabs(b[(i-1)/2]-i) l=min(s,m) print int(l)
During the lesson small girl Alyona works with one famous spreadsheet computer program and learns how to edit tables. Now she has a table filled with integers. The table consists of n rows and m columns. By ai, j we will denote the integer located at the i-th row and the j-th column. We say that the table is sorted in...
1
n,m=map(int,raw_input().split()) lst=[] from sys import * for i in range(0,n): l=[int(x) for x in stdin.readline().split()] lst.append(l) dp=[] #from sys import * for i in range(0,n+2): l=[] for j in range(0,m+2): l.append(0) dp.append(l) for j in range(0,m): for i in range(n-1,-1,-1): ...
Consider the following problem: given an array a containing n integers (indexed from 0 to n-1), find max_{0 ≤ l ≤ r ≤ n-1} ∑_{l ≤ i ≤ r} (r-l+1) ⋅ a_i. In this problem, 1 ≤ n ≤ 2 000 and |a_i| ≤ 10^6. In an attempt to solve the problem described, Alice quickly came up with a blazing-fast greedy algorithm and coded it....
3
#!/usr/bin/env python from __future__ import division, print_function import os import 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 main(): k = int(input()) m = -k % 2000 ...