problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
Lee is going to fashionably decorate his house for a party, using some regular convex polygons... Lee thinks a regular n-sided (convex) polygon is beautiful if and only if he can rotate it in such a way that at least one of its edges is parallel to the OX-axis and at least one of its edges is parallel to the OY-axis a...
3
t = int(input()) for i in range(t): number = int(input()) if number % 4 == 0: print("YES") else: print("NO")
Due to the coronavirus pandemic, city authorities obligated citizens to keep a social distance. The mayor of the city Semyon wants to light up Gluharniki park so that people could see each other even at night to keep the social distance. The park is a rectangular table with n rows and m columns, where the cells of the...
3
from math import ceil for _ in range(int(input())): n,m=map(int,input().split()) if n<m: n,m=m,n ans = m*(n//2) + (n%2)*ceil(m/2) print(ans)
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
testCase = int(input()) side = 0 for i in range(testCase): s = input() if s == "Tetrahedron": side += 4 elif s == "Cube": side += 6 elif s == "Octahedron": side += 8 elif s == "Dodecahedron": side += 12 elif s == "Icosahedron": side += 20 print(side)
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two...
1
# -*- coding: utf-8 -*- import collections def find_path(node): path = [node] while node != 1: node /= 2 path.append(node) return path def lowest_common_ancestor(node1, node2): path1 = find_path(node1) path2 = find_path(node2) return max(set(path1) & set(path2)) def find_sho...
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
t = int(input()) for z in range(t): a, b = map(int, input().split()) if a % b == 0: print(0) elif (a < b): print(b - a) else: temp = (int(a / b)) * b while (temp < a): temp = temp + b print(temp - a)
Let's consider all integers in the range from 1 to n (inclusive). Among all pairs of distinct integers in this range, find the maximum possible greatest common divisor of integers in pair. Formally, find the maximum value of gcd(a, b), where 1 ≀ a < b ≀ n. The greatest common divisor, gcd(a, b), of two positive integ...
3
t = int(input()) ans=[0]*t for i in range(t): n=int(input()) ans[i]=n//2 for i in range(t): print(int(ans[i]))
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
tc = int(input()); for _ in range(tc): length = int(input()); a = list(map(int,input().split())); b = list(map(int,input().split())); push = 0; bad = False; for i in range(length): diff = b[i] - a[i]; if (diff < 0): bad = True; break; elif (diff > 0): if (push == 0): pu...
You are given two positive integer sequences a_1, …, a_n and b_1, …, b_m. For each j = 1, …, m find the greatest common divisor of a_1 + b_j, …, a_n + b_j. Input The first line contains two integers n and m (1 ≀ n, m ≀ 2 β‹… 10^5). The second line contains n integers a_1, …, a_n (1 ≀ a_i ≀ 10^{18}). The third line co...
3
import math n, m = map(int, input().split()) a = [int(i) for i in input().split()] b = [int(i) for i in input().split()] a1 = a[0] common_gcd = 0 for a_i in a[1:]: common_gcd = math.gcd(common_gcd, a_i - a[0]) print(*[math.gcd(common_gcd, b_i + a1) for b_i in b], sep=' ')
Alice and Bob are decorating a Christmas Tree. Alice wants only 3 types of ornaments to be used on the Christmas Tree: yellow, blue and red. They have y yellow ornaments, b blue ornaments and r red ornaments. In Bob's opinion, a Christmas Tree will be beautiful if: * the number of blue ornaments used is greater b...
3
X = list(map(int, input().split())) print((min(X[0], X[1] - 1, X[2] - 2) * 3 + 3))
Takahashi, Nakahashi and Hikuhashi have integers A, B and C, respectively. After repeating the following operation K times, find the integer Takahashi will get minus the integer Nakahashi will get: * Each of them simultaneously calculate the sum of the integers that the other two people have, then replace his own inte...
3
a, b, c, k = map(int, input().split()) print((-1)**k*(a-b) if abs(a-b) <= 10**18 else "Unfair")
[Sakuzyo - Imprinting](https://www.youtube.com/watch?v=55Ca6av1kAY) A.R.C. Markland-N is a tall building with n floors numbered from 1 to n. Between each two adjacent floors in the building, there is a staircase connecting them. It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location...
3
n = int(input()) for _ in range(n): n, s, k = list(map(int, input().split(' '))) cls = list(map(int, input().split(' '))) i = 0 while True: right = s + i if right <= n and right not in cls: print(i) break left = s - i if left > 0 and left not in...
The preferred way to generate user login in Polygon is to concatenate a prefix of the user's first name and a prefix of their last name, in that order. Each prefix must be non-empty, and any of the prefixes can be the full name. Typically there are multiple possible logins for each person. You are given the first and ...
3
s1, s2 = input().split() ans = s1[0] for i in range(1, len(s1)): if s1[i] < s2[0]: ans += s1[i] if i == len(s1) - 1:ans += s2[0] else: ans += s2[0] break if len(s1) == 1:print(s1[0] + s2[0]) else:print(ans)
Vasya has a multiset s consisting of n integer numbers. Vasya calls some number x nice if it appears in the multiset exactly once. For example, multiset \{1, 1, 2, 3, 3, 3, 4\} contains nice numbers 2 and 4. Vasya wants to split multiset s into two multisets a and b (one of which may be empty) in such a way that the q...
3
from collections import deque n = int(input()) arr = list(map(int, input().split(" "))) dic = {} for i in arr: if i in dic: dic[i] += 1 else: dic[i] = 1 a = 0 b = 0 dic_ans = {} ones = set() twos = set() more = set() for i in dic: if dic[i] == 1: ones.add(i) elif dic[i] == 2: twos.add(i) else: more.a...
Student Valera is an undergraduate student at the University. His end of term exams are approaching and he is to pass exactly n exams. Valera is a smart guy, so he will be able to pass any exam he takes on his first try. Besides, he can take several exams on one day, and in any order. According to the schedule, a stud...
3
n = int(input()) pos = [] current_day = 0 for _ in range(n): pos.append(tuple(int(x) for x in input().split())) for i in sorted(pos): current_day = i[1] if current_day <= i[1] else i[0] print(current_day)
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, *...
1
# cook your code here import sys import math import random import operator from fractions import Fraction, gcd from decimal import Decimal, getcontext from itertools import product, permutations, combinations getcontext().prec = 100 MOD = 10**9 + 7 INF = float("+inf") n = int(raw_input()) arr = map(int, raw_input...
Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling. Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat t...
3
t=int(input()) for hh in range(t): n=int(input()) li=[int(i) for i in input().split()] d={} for i in li: d[i]=d.get(i,0)+1 so_key=sorted(d,key=d.get,reverse=True) max_key=so_key[0] for i in range(1,len(so_key)): if d[so_key[i]]==d[max_key]: d[so_key[i]]-=1 ...
A telephone number is a sequence of exactly 11 digits such that its first digit is 8. Vasya and Petya are playing a game. Initially they have a string s of length n (n is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it fro...
1
n=input() r=raw_input() n1=n-11 m2=(n1/2) m1=n1-m2 c=0 f=0 for i in range(n-10): if r[i]=='8' and m2: m2-=1 elif r[i]=='8': f=1 break else: c+=1 if not f: print 'NO' else: print 'YES'
Two polar bears Menshykov and Uslada from the St.Petersburg zoo and elephant Horace from the Kiev zoo got six sticks to play with and assess the animals' creativity. Menshykov, Uslada and Horace decided to make either an elephant or a bear from those sticks. They can make an animal from sticks in the following way: ...
3
a = list(map(int,input().split())) for i in range(6): if a.count(a[i])>=4: v = a[i] break else: print("Alien") exit() for i in range(4): a.remove(v) a.sort() if a[0]<a[1]: print("Bear") elif a[0]==a[1]: print("Elephant") else: print("Alien")
You've got a 5 Γ— 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix: 1....
3
a=[] for i in range(0,5): n=input().split() a.append(n) for i in range(0,5): for j in range(0,5): if a[i][j]=="1": x=i y=j pos=abs(2-x)+abs(2-y) print(pos)
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≀ i ≀ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is it...
3
num = input() lis = [int(x) for x in input().split()] lis2 = [] k = 0 if len(lis) == 1: print(1) else: for i in range(len(lis)-1): if lis[i] <= lis[i+1]: k += 1 lis2.append(k) else: lis2.append(k) k = 0 print(max(lis2)+1)
Problem description. An arithmetic progression(AP) is a sequence of numbers such that the difference of any two successive members of the sequence is a constant. For example:- 1, 4, 7, 10, 13, 16, 19, ... A geometric progression(GP) is a sequence of numbers where each term after the first is found by multiplying the p...
1
while 1: a,b,c=map(int,raw_input().split()) if a==0 and b==0 and c==0: break else: if b-a == c-b: print "%s %d" %("AP",c+(b-a)) else: print "%s %d" %("GP",c*(b/a))
Two integer sequences existed initially β€” one of them was strictly increasing, and the other one β€” strictly decreasing. Strictly increasing sequence is a sequence of integers [x_1 < x_2 < ... < x_k]. And strictly decreasing sequence is a sequence of integers [y_1 > y_2 > ... > y_l]. Note that the empty sequence and th...
3
import sys, collections if __name__ == "__main__": elements = input() numbers = map(int, input().split()) freqs = {} for number in list(numbers): if (number in freqs): freqs[number] += 1 else: freqs[number] = 1 if (freqs[number] > 2): ...
"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 ...
1
#!/usr/bin/python import sys n, k = [int(x) for x in raw_input().split(" ")] scores = [int(x) for x in raw_input().rstrip().split(" ")] threshold = scores[k-1] print len([x for x in scores if x >= threshold and x > 0])
There is a game called "I Wanna Be the Guy", consisting of n levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game. Little X can pass only p levels of the game. And Little Y can pass only q levels of the game. You are given the indices of levels Little X can pass ...
1
n = input() a = raw_input().split() b = raw_input().split() if len(set(a[1:]+b[1:])) == n: print "I become the guy." else: print "Oh, my keyboard!"
For a given polygon g, computes the area of the polygon. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≀ i ≀ n-1) are sides of g. The line segment connecting pn and p1 is also a side of the polygon. Note that the polygon is not necessarily convex. Constraints ...
3
def area(p,q):return p[0]*q[1]-p[1]*q[0] n=int(input()) point=[] x_1,y_1=[int(i) for i in input().split(" ")] for _ in range(n-1): x,y=[int(i) for i in input().split(" ")] point.append([x-x_1,y-y_1]) a=0 for i in range(n-2):a+=area(point[i],point[i+1]) print(a*0.5)
Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers a, b, c on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting e...
3
x=int(input()) y=int(input()) z=int(input()) print(max((x+y+z),(x*y*z),(x+y*z),((x+y)*z),((x*y)+z),(x*(y+z))))
Misha and Vasya participated in a Codeforces contest. Unfortunately, each of them solved only one problem, though successfully submitted it at the first attempt. Misha solved the problem that costs a points and Vasya solved the problem that costs b points. Besides, Misha submitted the problem c minutes after the contes...
3
a,b,c,d = map(int, input().split()) f = max(3*a//10, a-a*c//250) e = max(3*b//10, b-b*d//250) if e > f: print("Vasya") elif e < f: print("Misha") else: print("Tie")
In Omkar's last class of math, he learned about the least common multiple, or LCM. LCM(a, b) is the smallest positive integer x which is divisible by both a and b. Omkar, having a laudably curious mind, immediately thought of a problem involving the LCM operation: given an integer n, find positive integers a and b suc...
3
""" 616C """ """ 1152B """ import math # import sys def main(): # n ,m= map(int,input().split()) # arr = list(map(int,input().split())) # b = list(map(int,input().split())) # n = int(input()) # string = str(input()) n = int(input()) # a = list(map(int,input().split())) # s = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,...
Consider the following arithmetic progression with n terms: * x, x + d, x + 2d, \ldots, x + (n-1)d What is the product of all terms in this sequence? Compute the answer modulo 1\ 000\ 003. You are given Q queries of this form. In the i-th query, compute the answer in case x = x_i, d = d_i, n = n_i. Constraints *...
3
#################### # AC: ms (PyPy) #################### def main(): MOD = 10**6+3 # preprocess fac = [None] * (MOD+1) fac[0] = fac[1] = 1 for i in range(2, MOD+1): fac[i] = (fac[i-1] * i) % MOD Q = int(input()) for i in range(Q): x, d, n = map(int, input().split()) ...
You are given an integer n. In one move, you can either multiply n by two or divide n by 6 (if it is divisible by 6 without the remainder). Your task is to find the minimum number of moves needed to obtain 1 from n or determine if it's impossible to do that. You have to answer t independent test cases. Input The fi...
3
for _ in range(int(input())): n=int(input()) if n==1: print(0) else: c1=0 while n%2==0: n//=2 c1+=1 c2=0 while n%3==0: n//=3 c2+=1 if n!=1: print(-1) else: if c1>c2: ...
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 ...
3
n=int(input()) l=[] x=[] for i in range(n): l.append(input()) for i in range(n): x.append(l.count(l[i])) print(max(x))
Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree. A k-tree is an infinite rooted tree where: * each vertex has exactly k children; * each edge has some weight; * if we look at the edges that goes ...
1
def solve(): n,k,d = list(map(int,raw_input().split())) # ways n upto d-1 edges ways_small = [0 for _ in range(n+1)] for i in range(1,n+1,1): if i < d: ways_small[i] = 1 for j in range(1,d,1): if i < j: break ways_small[i...
The cows have just learned what a primitive root is! Given a prime p, a primitive root <image> is an integer x (1 ≀ x < p) such that none of integers x - 1, x2 - 1, ..., xp - 2 - 1 are divisible by p, but xp - 1 - 1 is. Unfortunately, computing primitive roots can be time consuming, so the cows need your help. Given ...
1
#!/usr/bin/env python # -*- coding: utf-8 -*- # def phi(n): result = n for i in range(2, n): if n % i == 0: while n % i == 0: n /= i result -= result / i if n > 1: result -= result / n return result def main(): p = int(raw_input()) m = 2 euler = 1 print(phi(p-1)) return 0 if __name__ == '__mai...
Write a program which counts and reports the number of each alphabetical letter. Ignore the case of characters. Constraints * The number of characters in the sentence < 1200 Input A sentence in English is given in several lines. Output Prints the number of alphabetical letters in the following format: a : The n...
3
import sys s=sys.stdin.read().lower() for i in range(97,123): print(chr(i),":",s.count(chr(i)))
Mahmoud wants to send a message to his friend Ehab. Their language consists of n words numbered from 1 to n. Some words have the same meaning so there are k groups of words such that all the words in some group have the same meaning. Mahmoud knows that the i-th word can be sent with cost ai. For each word in his messa...
3
import math l1 = list(map(int,input().split())) n = l1[0] k = l1[1] words = list(map(str,input().split())) cost = list(map(int,input().split())) dicti = {} total = 0 for i in range(len(words)): word = words[i] dicti[word] = i + 1 for i in range(k): group = list(map(int,input().split())) size = group[0] min_cost = ...
Takahashi bought a piece of apple pie at ABC Confiserie. According to his memory, he paid N yen (the currency of Japan) for it. The consumption tax rate for foods in this shop is 8 percent. That is, to buy an apple pie priced at X yen before tax, you have to pay X \times 1.08 yen (rounded down to the nearest integer)....
3
import math N=int(input()) x=math.ceil(N/1.08) if math.floor(x*1.08) == N: print(x) else: print(":(")
One rainy gloomy evening when all modules hid in the nearby cafes to drink hot energetic cocktails, the Hexadecimal virus decided to fly over the Mainframe to look for a Great Idea. And she has found one! Why not make her own Codeforces, with blackjack and other really cool stuff? Many people will surely be willing to...
3
n=int(input()) if 11<=n<=19: print(4) elif n==20: print(15) elif n==21: print(4) else: print(0)
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
l,b = list(map(int,input().split())) i = 0 while(l <= b): l = l *3 b = b *2 i += 1 print(i)
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangul...
3
import sys input=sys.stdin.readline n=int(input()) a=[] for i in range(n): a.append(sorted(list(map(int,input().split())))) b={} for i in range(n): for j in range(3): for k in range(j+1,3): if (a[i][j],a[i][k]) in b.keys(): b[(a[i][j],a[i][k])].add((a[i][3-j-k],i)) ...
Little girl Alyona is in a shop to buy some copybooks for school. She study four subjects so she wants to have equal number of copybooks for each of the subjects. There are three types of copybook's packs in the shop: it is possible to buy one copybook for a rubles, a pack of two copybooks for b rubles, and a pack of t...
1
n, a, b, c = map(int, raw_input().split()) ans = int(1e11) for i in range(5): for j in range(5): for k in range(5): if (n + i + 2 * j + 3 * k) % 4 == 0: ans = min(ans, i * a + j * b + k * c) print ans
We have a sandglass that runs for X seconds. The sand drops from the upper bulb at a rate of 1 gram per second. That is, the upper bulb initially contains X grams of sand. How many grams of sand will the upper bulb contains after t seconds? Constraints * 1≀X≀10^9 * 1≀t≀10^9 * X and t are integers. Input The input ...
3
x,t=map(int,input().split()) a=x-t if a<0: a=0 print(a)
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob β€” to check his answers, he needs a program that among the given n numbers finds one that is di...
3
n = int(input()) nums = list(map(int, input().split())) if nums[0] % 2 == 0: if nums[1] % 2 == 0: evenity = 0 else: if nums[2] % 2 == 0: evenity = 0 else: evenity = 1 else: if nums[1] % 2 == 0: if nums[2] % 2 == 0: evenity = 0 else:...
There always is something to choose from! And now, instead of "Noughts and Crosses", Inna choose a very unusual upgrade of this game. The rules of the game are given below: There is one person playing the game. Before the beginning of the game he puts 12 cards in a row on the table. Each card contains a character: "X"...
3
t = int(input()) res = [] for i in range(t): s = input() c = 0 p = [] for j in range(12): if s[j] == "X": p.append("1x12") c += 1 break for j in range(6): if s[j] == "X" and s[j + 6] == "X": p.append("2x6") c += 1 ...
After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third ro...
1
import string n=input() s=raw_input() a=string.lowercase d={} for c in s: if c in a: d[c]=d.get(c,0)+1 else: key=string.lower(c) if d.get(key,0)<>0: d[key]-=1 print sum(d.values())
Alice and Bob are playing a fun game of tree tag. The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges. Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first mov...
3
import sys from collections import deque as dq input = sys.stdin.readline for _ in range(int(input())): N, a, b, da, db = map(int, input().split()) e = [[] for _ in range(N + 1)] for _ in range(N - 1): u, v = map(int, input().split()) e[u].append(v) e[v].append(u) if da * 2 + 1 > db: print("Alic...
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()) if max(x-1,y-1) > max(n-x,n-y): print("Black") else: print("White")
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: * Employee A is the immediate manag...
1
n=int(input()) a=[] b=[] a.append(-100) b.append(-100) completed=[0]*(n+1) b=[[]]*(n+1) for i in range(0,n): temp=[int(input())] a.append(temp) #print a max_len=1 j=1 for i in range(1,n+1): # print "Here" temp=a[i][0] j=i counter=0 while(temp!=-1): temp=a[j][0] counter+=1 ...
The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, n is always even, and in C2, n is always odd. You are given a regular polygon with 2 β‹… n vertices (it's convex and has equal sides and equal angles) and all its sides have length 1. Let's name it as 2n...
3
import sys import math input=sys.stdin.readline for _ in range(int(input())): N=int(input()) n=2*N piee= math.pi result=math.cos(piee/n)/math.sin(piee/n) print(result)
You are given n integers a_1, a_2, ..., a_n, where n is odd. You are allowed to flip the sign of some (possibly all or none) of them. You wish to perform these flips in such a way that the following conditions hold: 1. At least (n - 1)/(2) of the adjacent differences a_{i + 1} - a_i for i = 1, 2, ..., n - 1 are grea...
3
for _ in range(int(input())): n=int(input()) arr=[int(c) for c in input().split()] ans=[(-1)**(i+1)*abs(arr[i]) for i in range(n)] print(*ans)
One beautiful July morning a terrible thing happened in Mainframe: a mean virus Megabyte somehow got access to the memory of his not less mean sister Hexadecimal. He loaded there a huge amount of n different natural numbers from 1 to n to obtain total control over her energy. But his plan failed. The reason for this w...
3
from itertools import combinations n = int(input()) a = '1010101010101010101010' b = [] for i in range(1,11): s = list(set(combinations(a,i))) for j in range(len(s)): s[j] = int(''.join(s[j])) b.extend(s) b = sorted(set(b)) m = len(b) #print(b) #print(m) for i in range(m): if(b[i] > n): print(i-1) exit...
Twilight Sparkle once got a crystal from the Crystal Mine. A crystal of size n (n is odd; n > 1) is an n Γ— n matrix with a diamond inscribed into it. You are given an odd integer n. You need to draw a crystal of size n. The diamond cells of the matrix should be represented by character "D". All other cells of the matr...
3
def solve(n): for i in range(1, n+1, 2): k = (n - i)//2 print("*"*k + 'D'*i + "*"*k) for i in range(n-2, 0, -2): k = (n - i)//2 print("*"*k + 'D'*i + "*"*k) def main(): n = int(input()) solve(n) main()
You are given an integer N that has exactly four digits in base ten. How many times does `2` occur in the base-ten representation of N? Constraints * 1000 \leq N \leq 9999 Input Input is given from Standard Input in the following format: N Output Print the answer. Examples Input 1222 Output 3 Input 34...
3
print(input().count("2"))
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th...
3
s=input() up=0 low=0 l=len(s) for i in range(l): if s[i].islower(): low+=1 else: up+=1 if up == low or low>up: st=s.lower() else: st=s.upper() print(st)
A and B are preparing themselves for programming contests. An important part of preparing for a competition is sharing programming knowledge from the experienced members to those who are just beginning to deal with the contests. Therefore, during the next team training A decided to make teams so that newbies are solvi...
3
mod = 1000000007 ii = lambda : int(input()) si = lambda : input() dgl = lambda : list(map(int, input())) f = lambda : map(int, input().split()) il = lambda : list(map(int, input().split())) ls = lambda : list(input()) n,m=f() if n>m: (n,m)=(m,n) i,j=0,0 c=0 while 1: n-=1 m-=2 if n>m: (n,m)=(m,n)...
Captain Flint and his crew keep heading to a savage shore of Byteland for several months already, drinking rum and telling stories. In such moments uncle Bogdan often remembers his nephew Denis. Today, he has told a story about how Denis helped him to come up with an interesting problem and asked the crew to solve it. ...
3
t = int(input()) for _ in range(t): n = int(input()) r = (n-1)//4 print('9'*(n-r-1) + '8'*(r+1))
An adult game master and N children are playing a game on an ice rink. The game consists of K rounds. In the i-th round, the game master announces: * Form groups consisting of A_i children each! Then the children who are still in the game form as many groups of A_i children as possible. One child may belong to at m...
3
K = int(input()) A = list(map(int, input().split())) def ceiling(x, mod): if x % mod == 0: return x // mod else: return x // mod + 1 m, M = 2, 2 p = 0 for i in range(K-1, -1, -1): m, M = A[i] * ceiling(m, A[i]), A[i] * (M // A[i]) + A[i] - 1 chk1, chk2 = m, M for i in range(K): chk1, chk2 = A[i] * (chk...
[Thanos sort](https://codegolf.stackexchange.com/questions/182221/implement-the-thanos-sorting-algorithm) is a supervillain sorting algorithm, which works as follows: if the array is not sorted, snap your fingers* to remove the first or the second half of the items, and repeat the process. Given an input array, what i...
3
n = int(input())#колличСство чисСл Π² массивС array = str(input()).split(' ') #массив чисСл n0 = n strt_of_grp = 0 out = 1 while n > 1: for i in range(1,int(n0/n)+1): for j in range(strt_of_grp,n*i-1): if int(array[j+1]) >= int(array[j]): out+=1 if out == n: ...
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 = map(int, input().split()) ans = 0 if m*a<=b: ans = n*a print(ans) else: while n>=m: ans += b n = n-m if n!=0: if n*a>b: ans+=b else: ans+=n*a print(ans)
Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers a, b, c on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting e...
3
def expressions() : a=int(input()) b=int(input()) c=int(input()) e1=a+(b*c) e2=a*(b+c) e3=a*b*c e4=(a+b)*c e5=a+b+c l=[e1,e2,e3,e4,e5] z=max(l) print (z) expressions()
Consider a rooted tree. A rooted tree has one special vertex called the root. All edges are directed from the root. Vertex u is called a child of vertex v and vertex v is called a parent of vertex u if there exists a directed edge from v to u. A vertex is called a leaf if it doesn't have children and has a parent. Let...
1
n = int(raw_input()) L = [True for i in range(n)] L[0] = False I = [None]*n for i in range(n-1): c = int(raw_input()) L[c-1] = False I[i+1] = c-1 leaf = [] parent = [] for i in range(n): if L[i] : leaf.append(i) else: parent.append(i) cnt = [0 for i in range(n)] for i in leaf: cnt[I[i]] += 1 ...
Winters are just damn freezing cold in Nvodsk! That's why a group of n friends prefers to take a taxi, order a pizza and call girls. The phone numbers in the city consist of three pairs of digits (for example, 12-34-56). Each friend has a phonebook of size si (that's the number of phone numbers). We know that taxi numb...
3
n=int(input()) def func(num): arr=[] for i in range(len(num)): arr.append(int(num[i])) if len(set(arr))==1: return 1 arr1=arr.copy() arr.sort(reverse=True) if arr1==arr and len(set(arr1))==6: return 2 else: return 3 tcount,pcount,gco...
A few years ago Sajjad left his school and register to another one due to security reasons. Now he wishes to find Amir, one of his schoolmates and good friends. There are n schools numerated from 1 to n. One can travel between each pair of them, to do so, he needs to buy a ticket. The ticker between schools i and j co...
3
#!/usr/bin/env python3 # -*- encoding:utf-8 -*- import sys def main(): """ Do the job.""" n = int(sys.stdin.readline()) res = int((n-1)/2) print("%s" % res) main()
At the beginning of the school year Berland State University starts two city school programming groups, for beginners and for intermediate coders. The children were tested in order to sort them into groups. According to the results, each student got some score from 1 to m points. We know that c1 schoolchildren got 1 po...
1
M = int(raw_input()) C = [None] + map(int, raw_input().split()) X, Y = map(int, raw_input().split()) for i in xrange(1, M+1): n1, n2 = sum(C[1:i]), sum(C[i:]) if X<=n1<=Y and X<=n2<=Y: print i break else: print 0
You are given a permutation p_1, p_2, ..., p_n. Recall that sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once. Find three indices i, j and k such that: * 1 ≀ i < j < k ≀ n; * p_i < p_j and p_j > p_k. Or say that there are no such indices. Input The first lin...
3
# for t in range(int(input())): # n = int(input()) # val = list(map(int, input().split())) # # i, j, k = 0, 0, 0 # answer_obtained = False # # for i in range(n): # if answer_obtained: # break # for j in range(i+1, n): # if answer_obtained: # br...
Bike is interested in permutations. A permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] is not. A permutation triple of permutations of length n (a, b, c) is called a...
3
n = int(input()) if n % 2 == 0: print(-1) exit(0) temp = [i for i in range(n)] print(*temp) temp2 = temp.copy() last = temp2[-1] del temp2[-1] temp2.insert(0, last) print(*temp2) for i in range(n): print((temp[i] + temp2[i]) % n, end = ' ')
Let's denote a function f(x) in such a way: we add 1 to x, then, while there is at least one trailing zero in the resulting number, we remove that zero. For example, * f(599) = 6: 599 + 1 = 600 β†’ 60 β†’ 6; * f(7) = 8: 7 + 1 = 8; * f(9) = 1: 9 + 1 = 10 β†’ 1; * f(10099) = 101: 10099 + 1 = 10100 β†’ 1010 β†’ 101. ...
3
n = int(input()) l1 = [n] def remove0s(a): while(a%10 == 0): a = a//10 return a def recfun(a): a += 1 if(a%10 == 0): a = remove0s(a) if a in l1: return l1.append(a) return recfun(a) recfun(n) print(len(l1)) """ 1098 + 2 --> 1100 --> 11 11 + 9 --> 20 --> 2 2 + 8 --> 10 --> 1 2 + 9 + 8 + 1 = 20 1098 , 10...
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th...
3
s = (input()) upper = 0 lower = 0 for i in s: if i.isupper(): upper += 1 else: lower += 1 if upper>lower: print(s.upper()) else: print(s.lower())
Arya has n opponents in the school. Each day he will fight with all opponents who are present this day. His opponents have some fighting plan that guarantees they will win, but implementing this plan requires presence of them all. That means if one day at least one of Arya's opponents is absent at the school, then Arya...
1
from sys import stdin, stdout n, d = [int(x) for x in stdin.readline().rstrip().split(" ")] max = 0 current = 0 for i in xrange(d): row = stdin.readline().rstrip() if '0' in row: current += 1 else: if max < current: max = current current = 0 if max < current: max =...
Igor the analyst has adopted n little bunnies. As we all know, bunnies love carrots. Thus, Igor has bought a carrot to be shared between his bunnies. Igor wants to treat all the bunnies equally, and thus he wants to cut the carrot into n pieces of equal area. Formally, the carrot can be viewed as an isosceles triangl...
3
from math import sqrt n,h=map(int,input().split()) h = h*1.00 l = [] for i in range(0,1500): l.append(sqrt(i)) area = sqrt((h*h)/n) for i in range(1,n): print(l[i]*area,end=" ")
Write a program which reads an integer $S$ [second] and converts it to $h:m:s$ where $h$, $m$, $s$ denote hours, minutes (less than 60) and seconds (less than 60) respectively. Constraints * $0 \leq S \leq 86400$ Input An integer $S$ is given in a line. Output Print $h$, $m$ and $s$ separated by ':'. You do not n...
1
S=input() h=S/3600 m=S%3600/60 s=S%3600%60 print str(h)+":"+str(m)+":"+str(s)
During the break the schoolchildren, boys and girls, formed a queue of n people in the canteen. Initially the children stood in the order they entered the canteen. However, after a while the boys started feeling awkward for standing in front of the girls in the queue and they started letting the girls move forward each...
1
[n,t]=map(int,raw_input().split()) s=list(raw_input()) for j in range(t): l=[] for i in range (n-1): if s[i]=='B' and s[i+1]=='G': l=l+[i] for i in l: s[i]='G' s[i+1]='B' print ''.join(s)
Subodh's CS department has been continuously organizing mock placement drives for students. If a student under-performs negative point is rewarded otherwise positive points is rewarded. The HOD wants to find consistency of a student. So, he wants to find out maximum consistent sum of a student score only if his/her ove...
1
x=input() y=list(raw_input().split(" ")) y=map(int,y) sum=0 max=0 for i in range(0,len(y)): if sum==0 and y[i]>0: sum+=y[i] elif sum>0: sum+=y[i] if sum > max: max=sum if sum<0: sum=0 print max
You are given n numbers a_1, a_2, ..., a_n. With a cost of one coin you can perform the following operation: Choose one of these numbers and add or subtract 1 from it. In particular, we can apply this operation to the same number several times. We want to make the product of all these numbers equal to 1, in other wo...
3
t=int(input()) a=list(map(int,input().strip().split(" "))) x=0 y=0 c1=0 c2=0 c3=0 for i in a: if i<0: x+=abs(i+1) c1+=1 elif i>0: y+=i-1 c2+=1 else: y+=1 c3+=1 if c3>0: print(x+y) else: if (c1)%2!=0: print(x+y+2) else: print(x+y) ...
It is September 9 in Japan now. You are given a two-digit integer N. Answer the question: Is 9 contained in the decimal notation of N? Constraints * 10≀N≀99 Input Input is given from Standard Input in the following format: N Output If 9 is contained in the decimal notation of N, print `Yes`; if not, print `No...
3
n=list(input()) print('Yes' if '9' in n else 'No')
Let's define a function f(x) (x is a positive integer) as follows: write all digits of the decimal representation of x backwards, then get rid of the leading zeroes. For example, f(321) = 123, f(120) = 21, f(1000000) = 1, f(111) = 111. Let's define another function g(x) = (x)/(f(f(x))) (x is a positive integer as well...
3
for _ in range(int(input())): s = input() print(len(s))
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 _ in range(t): x, y, z = [int(i) for i in input().split()] if x != y and y != z and x != z: print("NO") else: if x == y and y == z: print("YES") print(x, y, z) else: if x == y: if x >= z: ...
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it: * deletes all the vowels, * inserts a character "." before each consonant, * repl...
3
s = input() s = s.lower() for i in s: if (i!='a') and (i!='o') and (i!='y') and (i!='e') and (i!='u') and (i!='i'): print(".", i, sep='', end='')
Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it ...
3
c=0 a=[] for _ in range(int(input())): m,n=map(int,input().split()) c=c-m c=c+n a.append(c) print(max(a)) ...
During the break the schoolchildren, boys and girls, formed a queue of n people in the canteen. Initially the children stood in the order they entered the canteen. However, after a while the boys started feeling awkward for standing in front of the girls in the queue and they started letting the girls move forward each...
3
n,t=map(int,input().split()) s=input() for i in range(t): j=0 stemp="" while(j<n): if(j+1<n and (s[j]=="B" and s[j+1]=="G")): stemp+="GB" j+=1 else: stemp+=s[j] j+=1 s=stemp print(s)
Once again, Boris needs the help of Anton in creating a task. This time Anton needs to solve the following problem: There are two arrays of integers a and b of length n. It turned out that array a contains only elements from the set \{-1, 0, 1\}. Anton can perform the following sequence of operations any number of ti...
3
if __name__ == '__main__': t = int(input()) while t: n = int(input()) A=list(map(int,input().split())) B=list(map(int,input().split())) one =0 zero =0 f=True for i in range(len(A)): if A[i]>B[i] and zero == 0: f = False break elif A[i]<B[i] and o...
Valentina is looking for a new game to play with her friends. She asks her mom Marcia for an idea. After a moment Marcia described to girls the following simple game. Girls are divided into n teams, indexed 1 through n. Each girl chooses a lowercase letter, one of 'a' - 'z'. Of course, some girls can choose the same l...
1
for _ in range(int(raw_input())): n,s=raw_input().split() n=int(n) p={} for i in s: if p.has_key(i): p[i]+=1 else: p[i]=1 a=[] for i in range(n): s=raw_input() ct=0 for j in s: ct+=p.get(j,0) a.append([ct,-len(s)...
After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≀ si ≀ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum nu...
3
n = int(input()) a = [0] * 5 for i in input().split(): a[int(i)] += 1 ans = a[4] k = min(a[3], a[1]) ans += k a[1] -= k a[3] -= k ans += a[3] ans += (a[2]*2 + a[1]) // 4 if (a[2]*2 + a[1]) - (a[2]*2 + a[1]) // 4 * 4 > 0: ans += 1 print(ans)
Input The input consists of a single string of uppercase letters A-Z. The length of the string is between 1 and 10 characters, inclusive. Output Output "YES" or "NO". Examples Input GENIUS Output YES Input DOCTOR Output NO Input IRENE Output YES Input MARY Output NO Input SMARTP...
3
elems = ['H', 'HE', 'LI', 'BE', 'B', 'C', 'N', 'O', 'F', 'NE', 'NA', 'MG', 'AL', 'SI', 'P', 'S', 'CL', 'AR', 'K', 'CA', 'SC', 'TI', 'V', 'CR', 'MN', 'FE', 'CO', 'NI', 'CU', 'ZN', 'GA', 'GE', 'AS', 'SE', 'BR', 'KR', 'RB', 'SR', 'Y', 'ZR', 'NB', 'MO', 'TC', 'RU', 'RH', 'PD', 'AG', 'CD', 'IN', 'SN', 'SB', 'TE', 'I', 'XE',...
You are given two arrays of integers a_1,…,a_n and b_1,…,b_m. Your task is to find a non-empty array c_1,…,c_k that is a subsequence of a_1,…,a_n, and also a subsequence of b_1,…,b_m. If there are multiple answers, find one of the smallest possible length. If there are still multiple of the smallest possible length, f...
3
# template -> FastIntegerInput; import sys _ord, inp, num, neg, _Index = lambda x: x, [], 0, False, 0 i, s = 0, sys.stdin.buffer.read() try: while True: if s[i] >= b"0"[0]:num = 10 * num + _ord(s[i]) - 48 elif s[i] == b"-"[0]:neg = True elif s[i] != b"\r"[0]: inp.append(-num if n...
You are given an array a consisting of n integers. Your task is to say the number of such positive integers x such that x divides each number from the array. In other words, you have to find the number of common divisors of all elements in the array. For example, if the array a will be [2, 4, 6, 2, 10], then 1 and 2 ...
3
import math n=int(input()) l=list(map(int,input().split())) num=l[0] for i in range(1,n): num=math.gcd(l[i],num) count=0 for x in range(1,int(num**0.5)+1): if num%x==0: if num//x==x: count+=1 else: count+=2 print(count)
There are n beacons located at distinct positions on a number line. The i-th beacon has position ai and power level bi. When the i-th beacon is activated, it destroys all beacons to its left (direction of decreasing coordinates) within distance bi inclusive. The beacon itself is not destroyed however. Saitama will acti...
1
N=1<<20 n=input() c=[0]*N for _ in range(n): a,b=map(int,raw_input().split()) c[a]=b for i in range(N): c[i]=(1 if c[i]>=i else c[i-c[i]-1]+1) if c[i] else c[i-1] print n-max(c)
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
n = list(input()) a = n[0].upper() n[0] = a print(''.join(n))
Polycarp has three sisters: Alice, Barbara, and Cerene. They're collecting coins. Currently, Alice has a coins, Barbara has b coins and Cerene has c coins. Recently Polycarp has returned from the trip around the world and brought n coins. He wants to distribute all these n coins between his sisters in such a way that ...
3
t = int(input()) while t: t += -1 a, b, c, n = map(int, input().split()) if (a + b + c + n) % 3 == 0: temp = (a + b + c + n) // 3 if temp >= a and temp >= b and temp >= c: if 3 * temp - (a + b + c) == n: print("YES") else: print("NO") else: print("NO") els...
When preparing a tournament, Codeforces coordinators try treir best to make the first problem as easy as possible. This time the coordinator had chosen some problem and asked n people about their opinions. Each person answered whether this problem is easy or hard. If at least one of these n people has answered that th...
3
ans='EASY' n=int(input()) nums = list(map(int, input().split())) for i in nums: if i==1: ans='HARD' print(ans)
Bomboslav likes to look out of the window in his room and watch lads outside playing famous shell game. The game is played by two persons: operator and player. Operator takes three similar opaque shells and places a ball beneath one of them. Then he shuffles the shells by swapping some pairs and the player has to guess...
3
ans=((0,1,2),(1,0,2),(1,2,0),(2,1,0),(2,0,1),(0,2,1)); n=input() x=input() a=int(n) b=int(x) a=a%6 print(ans[a][b])
You are given a permutation p_1, p_2, ..., p_n. Recall that sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once. Find three indices i, j and k such that: * 1 ≀ i < j < k ≀ n; * p_i < p_j and p_j > p_k. Or say that there are no such indices. Input The first lin...
3
for i in range (int(input())): n=int(input()) n1=n l1=list(map(int,input().split())) c1=0 for j in range (n1): m1=max(l1) if(l1.index(m1)!=0 and l1.index(m1)!=len(l1)-1): print("YES") print(l1.index(m1)+c1,l1.index(m1)+c1+1,l1.index(m1)+2+c1) break...
Roma works in a company that sells TVs. Now he has to prepare a report for the last year. Roma has got a list of the company's incomes. The list is a sequence that consists of n integers. The total income of the company is the sum of all integers in sequence. Roma decided to perform exactly k changes of signs of sever...
1
n,k = map(int,raw_input().split()) a = list(map(int,raw_input().split())) o = 0 for i in range(n): if o==k: break if a[i]<0: a[i]=-a[i] o+=1 if o<k and (k-o)%2==1: s = a.index(min(a)) a[s]=-a[s] print(sum(a))
You are given a positive integer X. Find the largest perfect power that is at most X. Here, a perfect power is an integer that can be represented as b^p, where b is an integer not less than 1 and p is an integer not less than 2. Constraints * 1 ≀ X ≀ 1000 * X is an integer. Input Input is given from Standard Input ...
3
ans=1 x=int(input()) for i in range(1,101): for j in range(2,11): m=i**j if x>=m:ans=max(ans,m) print(ans)
Your friend recently gave you some slimes for your birthday. You have n slimes all initially with value 1. You are going to play a game with these slimes. Initially, you put a single slime by itself in a row. Then, you will add the other n - 1 slimes one by one. When you add a slime, you place it at the right of all a...
3
from collections import deque from sys import stdin as fin # fin = open("wfr2016a.in", "r") n = int(fin.readline()) stack = deque() for i in range(n): stack.append(1) # cur = 1 while len(stack) > 1 and stack[-1] == stack[-2]: stack.pop(); stack.append(stack.pop() + 1) for num in stack: pr...
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated. The language is that peculiar as it has exactly one variable, called x. Also, there are two operations: * Operation ++ increases the value of variable x by 1. * Operation -- decreases the value of variable x by 1....
3
n = int(input()) x = 0 for i in range(n): st = str(input()) if st[0] == '+' or st[1] == '+': x += 1 elif st[0] == '-' or st[1] == '-': x -= 1 print(x)
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it: * deletes all the vowels, * inserts a character "." before each consonant, * repl...
3
palavra = str(input()) palavra = palavra.lower() palavra = list(palavra) palavraF = str('') for i in range(len(palavra)): if palavra[i] == 'a' or palavra[i] == 'e' or palavra[i] == 'i' or palavra[i] == 'o' or palavra[i] == 'u' or palavra[i] == 'y': continue else: palavraF += '.' + palavra[i] ...
When Valera has got some free time, he goes to the library to read some books. Today he's got t free minutes to read. That's why Valera took n books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to n. Valera needs ai minutes to read the ...
1
n, t = map(int, raw_input().split()) books = map(int, raw_input().split()) for i in range(1, n): books[i] += books[i-1] books.insert(0,0) max = 0 for i in range(0, n+1): if(i+max >= n): break differ = books[i+max] - books[i] while True: if(differ < t and i+max+1 <= n) : ...
Example Input 7 >> Output 7
1
#!/usr/bin/python import re def main(): n = int(raw_input()) s = raw_input() print n-min(map(lambda x: x.end()-x.start(), [re.search(r'^<*', s), re.search(r'>*$', s)])) if __name__ == '__main__': main()
The last stage of Football World Cup is played using the play-off system. There are n teams left in this stage, they are enumerated from 1 to n. Several rounds are held, in each round the remaining teams are sorted in the order of their ids, then the first in this order plays with the second, the third β€” with the four...
3
import math n,a,b=map(int,input().split()) s=1 e=n cnt=0 def round(s,e,a,b,cnt,n): cnt+=1 m=(s+e)//2 if s<=a<=m and m+1<=b<=e: if cnt==1: print("Final!") else: print(int(math.log2(n)-cnt+1)) elif s<=a<=m and s<=b<=m: round(s,m,a,b,cnt,n) elif m+1<=a...
Let s be some string consisting of symbols "0" or "1". Let's call a string t a substring of string s, if there exists such number 1 ≀ l ≀ |s| - |t| + 1 that t = s_l s_{l+1} … s_{l + |t| - 1}. Let's call a substring t of string s unique, if there exist only one such l. For example, let s = "1010111". A string t = "010...
3
if __name__ == "__main__": N, K = [int(x) for x in input().split()] len = (N - K) // 2 + 1 s0 = '0' * (len - 1) + '1' print(s0 * (N // len) + s0[ : N % len])