problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
You are given a grid with n rows and m columns, where each cell has a non-negative integer written on it. We say the grid is good if for each cell the following condition holds: if it has a number k > 0 written on it, then exactly k of its neighboring cells have a number greater than 0 written on them. Note that if the...
3
for i in range(int(input())): n,m=map(int,input().split()) l=[] for i in range(n): l.append(list(map(int,input().split()))) f=0 for i in range(n): for j in range(m): if [i,j] in [[0,0],[0,m-1],[n-1,0],[n-1,m-1]]: if l[i][j]>2: print("NO...
There are n athletes in front of you. Athletes are numbered from 1 to n from left to right. You know the strength of each athlete β€” the athlete number i has the strength s_i. You want to split all athletes into two teams. Each team must have at least one athlete, and each athlete must be exactly in one team. You want...
3
for ii in range(int(input())): n = int(input()) arr = a = list(map(int , input().split())) arr = sorted(arr) # Initialize difference as infinite diff = 10 ** 20 # Find the min diff by comparing adjacent # pairs in sorted array for i in range(n - 1): if arr[i + 1] - arr[i] < dif...
Takahashi loves numbers divisible by 2. You are given a positive integer N. Among the integers between 1 and N (inclusive), find the one that can be divisible by 2 for the most number of times. The solution is always unique. Here, the number of times an integer can be divisible by 2, is how many times the integer can...
3
N = int(input()) print(1<<len(bin(N))-3)
You are given a tree with N vertices. Here, a tree is a kind of graph, and more specifically, a connected undirected graph with N-1 edges, where N is the number of its vertices. The i-th edge (1≀i≀N-1) connects Vertices a_i and b_i, and has a length of c_i. You are also given Q queries and an integer K. In the j-th qu...
3
import sys sys.setrecursionlimit(10**9) N = int(input()) T = [[] for _ in range(N+1)] for _ in range(N-1) : a,b,c = map(int,input().split()) T[a].append([b,c]) T[b].append([a,c]) Q,K = map(int,input().split()) dist = [None]*(N+1) def dfs(now,d) : dist[now] = d for to,c in T[now] : if di...
"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
''' Welcome to GDB Online. GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl, C#, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog. Code, Compile, Run and Debug online from anywhere in world. ''' #print ('Hello World') (n,k)=map(int,i...
Alice and Bob play ping-pong with simplified rules. During the game, the player serving the ball commences a play. The server strikes the ball then the receiver makes a return by hitting the ball back. Thereafter, the server and receiver must alternately make a return until one of them doesn't make a return. The one ...
3
from sys import stdin """ n=int(stdin.readline().strip()) n,m=map(int,stdin.readline().strip().split()) s=list(map(int,stdin.readline().strip().split())) s=stdin.readline().strip() """ cas=int(stdin.readline().strip()) ans=0 def sm(x): return ((x)*(x+1))//2 for ca in range(cas): n,m=map(int,stdin.readline().st...
There is the faculty of Computer Science in Berland. In the social net "TheContact!" for each course of this faculty there is the special group whose name equals the year of university entrance of corresponding course of students at the university. Each of students joins the group of his course and joins all groups f...
3
n=int(input()) l=list(sorted(map(int,input().split()))) print(l[n//2])
Mary has just graduated from one well-known University and is now attending celebration party. Students like to dream of a beautiful life, so they used champagne glasses to construct a small pyramid. The height of the pyramid is n. The top level consists of only 1 glass, that stands on 2 glasses on the second level (co...
3
full = 0 n, t = (int(v) for v in input().strip().split()) g = [t] for i in range(n): g2 = [0] * (len(g)+1) for j,l in enumerate(g): if l<1: continue full += 1 g2[j] += (l-1)/2 g2[j+1] += (l-1)/2 #print(g) g = g2 print(full)
Let n be an integer. Consider all permutations on integers 1 to n in lexicographic order, and concatenate them into one big sequence P. For example, if n = 3, then P = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]. The length of this sequence is n β‹… n!. Let 1 ≀ i ≀ j ≀ n β‹… n! be a pair of indices. We call the...
3
import math def factorial(n): for i in range(1, n + 1): factorial = factorial * i return factorial def f(n): l = factorial(n) * n ans = l * (l - n + 2) // 2 for i in range(1, n): ans -= factorial(n) // factorial(i + 1) n(i * (n - i) - 1) return ans def solve(n): ...
You have been blessed as a child of Omkar. To express your gratitude, please solve this problem for Omkar! An array a of length n is called complete if all elements are positive and don't exceed 1000, and for all indices x,y,z (1 ≀ x,y,z ≀ n), a_{x}+a_{y} β‰  a_{z} (not necessarily distinct). You are given one integer ...
3
t=int(input()) for i in range(t): n=int(input()) for j in range(n-1): print(1,end=" ") print(1)
Your program is to use the brute-force approach in order to find the Answer to Life, the Universe, and Everything. More precisely... rewrite small numbers from input to output. Stop processing input after reading in the number 42. All numbers at input are integers of one or two digits. SAMPLE INPUT 1 2 88 42 99 SAMPL...
1
# /usr/bin/python -tt # -*- coding: utf-8 -*- ''' ''' N = int(raw_input()) while N != 42: print N N = int(raw_input())
Two players decided to play one interesting card game. There is a deck of n cards, with values from 1 to n. The values of cards are pairwise different (this means that no two different cards have equal values). At the beginning of the game, the deck is completely distributed between players such that each player has a...
3
R=lambda:input().split() exec(int(R()[0])*"n=R()[0];R();print('YNEOS'[n in R()::2]);")
Kirito is stuck on a level of the MMORPG he is playing now. To move on in the game, he's got to defeat all n dragons that live on this level. Kirito and the dragons have strength, which is represented by an integer. In the duel between two opponents the duel's outcome is determined by their strength. Initially, Kirito'...
3
s,n=[int(i)for i in input().split()] pair=[] for i in range(n): x,y=[int(i) for i in input().split()] pair.append((x,y)) pair=sorted(pair) #print(pair) for i in range(n): if pair[i][0]>=s: r='NO' break else: s+=pair[i][1] if i==n-1: r='YES' print(r)
There are N gems. The value of the i-th gem is V_i. You will choose some of these gems, possibly all or none, and get them. However, you need to pay a cost of C_i to get the i-th gem. Let X be the sum of the values of the gems obtained, and Y be the sum of the costs paid. Find the maximum possible value of X-Y. Co...
3
n=int(input()) x=list(map(int,input().split())) y=list(map(int,input().split())) ans=0 for (p,q) in zip(x,y): if p-q>0: ans+=p-q print(ans)
You have a given integer n. Find the number of ways to fill all 3 Γ— n tiles with the shape described in the picture below. Upon filling, no empty spaces are allowed. Shapes cannot overlap. <image> This picture describes when n = 4. The left one is the shape and the right one is 3 Γ— n tiles. Input The only line cont...
3
import sys input = sys.stdin.readline n = int(input()) if n % 2 != 0: print(0) else: print(2**(n//2))
Throughout Igor K.'s life he has had many situations worthy of attention. We remember the story with the virus, the story of his mathematical career and of course, his famous programming achievements. However, one does not always adopt new hobbies, one can quit something as well. This time Igor K. got disappointed in ...
3
import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') n, m, a, b = map(int, input().split()) a, b = a - 1, b - 1 if b + 1 == n: b = (b // m + 1) * m - 1 if a // m == b // m: print(1) elif a % m == 0 and b % m == m - 1: print(1) elif b % m +...
You are given two sequences a_1, a_2, ..., a_n and b_1, b_2, ..., b_n. Each element of both sequences is either 0, 1 or 2. The number of elements 0, 1, 2 in the sequence a is x_1, y_1, z_1 respectively, and the number of elements 0, 1, 2 in the sequence b is x_2, y_2, z_2 respectively. You can rearrange the elements i...
3
for _ in range(int(input())): a, b, c = map(int, input().split()) x, y, z = map(int, input().split()) ans = 0 ans += 2 * min(c, y) c -= ans // 2 y -= ans // 2 z -= c z -= a if z > 0: ans -= 2 * z print(ans)
You are given an array a consisting of n integer numbers. Let instability of the array be the following value: max_{i = 1}^{n} a_i - min_{i = 1}^{n} a_i. You have to remove exactly one element from this array to minimize instability of the resulting (n-1)-elements array. Your task is to calculate the minimum possible...
3
n=int(input()) l=[int(x) for x in input().split()] l.sort() s=[] for i in l: s.append(i) l.remove(l[n-1]) s.remove(s[0]) m1=max(l)-min(l) m2=max(s)-min(s) if m1<m2: print(m1) else: print(m2)
Let quasi-palindromic number be such number that adding some leading zeros (possible none) to it produces a palindromic string. String t is called a palindrome, if it reads the same from left to right and from right to left. For example, numbers 131 and 2010200 are quasi-palindromic, they can be transformed to strin...
3
x = input() k = 0 for i in range(len(x)-1,0,-1): if x[i] == "0": k +=1 else: break z = x[:len(x)-k] m = len(z)-1 flag = 0 for i in range(len(z)//2): if z[i] != z[m]: flag = 1 break m -= 1 if flag == 1: print("NO") else: print("YES")
You have a list of numbers from 1 to n written from left to right on the blackboard. You perform an algorithm consisting of several steps (steps are 1-indexed). On the i-th step you wipe the i-th number (considering only remaining numbers). You wipe the whole number (not one digit). <image> When there are less than ...
3
def missing(x): return 2 * x n = int(input()) a = list() for i in range(n): m, x = [int(j) for j in input().split()] a.append(missing(x)) for elem in a: print(elem)
The letters shop showcase is a string s, consisting of n lowercase Latin letters. As the name tells, letters are sold in the shop. Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string s. There are m friends, the i-th of them is named t_i. Eac...
3
def read(): return list(map(int, input().split())) [n] = read() s = input() indices = [[] for i in range(26)] for i in range(n): indices[ord(s[i]) - ord('a')] += [i + 1] def run(): s = input() a = [0 for _ in range(26)] for i in range(len(s)): a[ord(s[i]) - ord('a')] += 1 ans = 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
t = int(input()) for _ in range(t): a, b, c, d = map(int, input().split()) if a <= b: print(b) continue else: if c-d <= 0: print(-1) continue else: a -= b print(b+((a-1)//(c-d)+1)*c)
The Patisserie AtCoder sells cakes with number-shaped candles. There are X, Y and Z kinds of cakes with 1-shaped, 2-shaped and 3-shaped candles, respectively. Each cake has an integer value called deliciousness, as follows: * The deliciousness of the cakes with 1-shaped candles are A_1, A_2, ..., A_X. * The deliciousn...
3
X, Y, Z, K = map(int, input().split()) A = list(map(int, input().split())) B = list(map(int, input().split())) C = sorted(map(int, input().split()), reverse=True) AB = [] for a in A: for b in B: AB.append(a+b) AB.sort(reverse = True) ans = [] for ab in AB[:K]: for c in C: ans.append(ab+c) ans.sort(revers...
The game of Berland poker is played with a deck of n cards, m of which are jokers. k players play this game (n is divisible by k). At the beginning of the game, each player takes n/k cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he...
3
for _ in range(int(input())): n, m, k = map(int, input().split()) t = min(n // k, m) print(t - (m - t) // (k - 1) - ((m - t) % (k - 1) > 0))
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
S=input() X=[ord(s)-65 for s in S] for i in range(2,len(X)): if (X[i-1]+X[i-2])%26==X[i]: True else: print("NO") exit() print("YES")
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
def sol(): a = list(map(int, input().split())) b = list(map(int, input().split())) n = [b-a for a, b in zip(a, b)] while n and n[-1] == 0: n.pop() n.reverse() while n and n[-1] == 0: n.pop() if not n or (len(set(n)) == 1 and n[0] > 0): return('YES') else: ...
Kirito is stuck on a level of the MMORPG he is playing now. To move on in the game, he's got to defeat all n dragons that live on this level. Kirito and the dragons have strength, which is represented by an integer. In the duel between two opponents the duel's outcome is determined by their strength. Initially, Kirito'...
3
s, n = map(int,input().split()) k = s alls = [] stat = 'YES' for a in range(n): x, y = map(int,input().split()) alls.append([x,y]) alls = sorted(alls, key = lambda x:(x[0],x[1])) for b in range(n): if k > alls[b][0]: k += alls[b][1] else: stat = 'NO' print(stat)
You are given two positive integers n (1 ≀ n ≀ 10^9) and k (1 ≀ k ≀ 100). Represent the number n as the sum of k positive integers of the same parity (have the same remainder when divided by 2). In other words, find a_1, a_2, …, a_k such that all a_i>0, n = a_1 + a_2 + … + a_k and either all a_i are even or all a_i ar...
3
tc=int(input()) while tc!=0: tc=tc-1 n,k=map(int,input().split(' ')) a=[] if n%2==0: if k%2==0: for i in range(0,k-1): a.append(1) if n-(k-1)<=0: print("NO") continue a.append(n-(k-1)) else: f...
There are two sisters Alice and Betty. You have n candies. You want to distribute these n candies between two sisters in such a way that: * Alice will get a (a > 0) candies; * Betty will get b (b > 0) candies; * each sister will get some integer number of candies; * Alice will get a greater amount of candie...
3
from sys import stdin t = int(stdin.readline()) for _ in range(t): n = int(stdin.readline()) print((n - 1) // 2)
Let's define a split of n as a nonincreasing sequence of positive integers, the sum of which is n. For example, the following sequences are splits of 8: [4, 4], [3, 3, 2], [2, 2, 1, 1, 1, 1], [5, 2, 1]. The following sequences aren't splits of 8: [1, 7], [5, 4], [11, -3], [1, 1, 4, 1, 1]. The weight of a split is t...
3
n = int(input()) n += 1 print(n//2 + n %2)
Old timers of Summer Informatics School can remember previous camps in which each student was given a drink of his choice on the vechorka (late-evening meal). Or may be the story was more complicated? There are n students living in a building, and for each of them the favorite drink a_i is known. So you know n integer...
3
from math import ceil n, k = [int(p) for p in input().split()] freq = {} for i in range(1, k+1): freq[i] = 0 for i in range(n): freq[int(input())] += 1 total = 0 remain = 0 for i in freq: total += freq[i]//2 remain += freq[i] % 2 a = ceil(n/2) ans = 0 if total >= a: print(2*a) else: ans += 2*total a -= total if...
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc....
3
a = input() b = input() a_ = ''.join(reversed(a)) if b == a_: print('YES') else: print('NO')
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
word = input() uppercases = sum(char.upper() == char for char in word) if (uppercases > len(word) // 2): print(word.upper()) else: print(word.lower())
A sequence a_1,a_2,... ,a_n is said to be /\/\/\/ when the following conditions are satisfied: * For each i = 1,2,..., n-2, a_i = a_{i+2}. * Exactly two different numbers appear in the sequence. You are given a sequence v_1,v_2,...,v_n whose length is even. We would like to make this sequence /\/\/\/ by replacing s...
3
from collections import Counter n=int(input()) a=list(map(int,input().split())) if a.count(a[0])==n: print(n//2) exit() x=a[::2] y=a[1::2] xx=Counter(x) yy=Counter(y) xxx=xx.most_common() yyy=yy.most_common() if xxx[0][0]!=yyy[0][0]: print(n-xxx[0][1]-yyy[0][1]) else: print(min(n-xxx[1][1]-yyy[0...
Vanya is managed to enter his favourite site Codehorses. Vanya uses n distinct passwords for sites at all, however he can't remember which one exactly he specified during Codehorses registration. Vanya will enter passwords in order of non-decreasing their lengths, and he will enter passwords of same length in arbitrar...
3
[n,k] = input().split(' ') n = int(n) k = int(k) l = 0 d = 0 arr = []*(n+1) for i in range(n): str =input() arr.append(str) str1 = input() len1=len(str1) for i in range(n): if len(arr[i]) <len1: l=l+1 elif len(arr[i]) == len1: d=d+1 ans1 = l+ int(l/k)*5+1 ansr = l+d+int ((l+d-1)/k)*...
This task will exclusively concentrate only on the arrays where all elements equal 1 and/or 2. Array a is k-period if its length is divisible by k and there is such array b of length k, that a is represented by array b written exactly <image> times consecutively. In other words, array a is k-periodic, if it has period...
1
n, k = map(int, raw_input().split()) a = map(int, raw_input().split()) ans = 0 for j in xrange(k): t1 = t2 = 0 for i in xrange(n / k): if a[i * k + j] == 1: t1 += 1 else: t2 += 1 ans += min(t1, t2) print ans
The circle line of the Roflanpolis subway has n stations. There are two parallel routes in the subway. The first one visits stations in order 1 β†’ 2 β†’ … β†’ n β†’ 1 β†’ 2 β†’ … (so the next stop after station x is equal to (x+1) if x < n and 1 otherwise). The second route visits stations in order n β†’ (n-1) β†’ … β†’ 1 β†’ n β†’ (n-1) ...
1
from sys import stdin lines = stdin.readlines() n,a,x,b,y = map(int,lines[0].split()) flag = True while flag: if a == b: result = "YES" flag = False elif a != x and b != y: a += 1 b -= 1 elif a == x and b != y: result = "NO" flag = False elif a != x and b...
You are given the array a consisting of n positive (greater than zero) integers. In one move, you can choose two indices i and j (i β‰  j) such that the absolute difference between a_i and a_j is no more than one (|a_i - a_j| ≀ 1) and remove the smallest of these two elements. If two elements are equal, you can remove a...
1
""" CONTESTANT: ngtien2 CONTEST: Codeforces Round #617 (Div. 3) LANGUAGE: PyPy 2.7 (7.2.0) PROBLEM: A. Array with Odd Sum """ t = int(raw_input()) for i in xrange(t): n = int(raw_input()) a = map(lambda x: x % 2, map(int, raw_input().split())) if sum(a) == 0 or (sum(a) == n and n % 2 == 0): print...
Vanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed h and the processor smashes k centimeters of potato each second. If there are less than k centimeters remaining, than during this second processor smashes all the remaining potato. Vanya h...
3
def goodceil(a , b): return (a + b - 1) // b n, maxh, k = map(int, input().split()) p = list(map(int, input().split())) curh = 0 curtime = 0 time = 0 i = 0 while i < len(p): while (i < len(p)) and (curh + p[i] <= maxh): curh += p[i] i += 1 if i <= (len(p) - 1): curtime = goodceil(c...
Given 2 integers u and v, find the shortest array such that [bitwise-xor](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of its elements is u, and the sum of its elements is v. Input The only line contains 2 integers u and v (0 ≀ u,v ≀ 10^{18}). Output If there's no array that satisfies the condition, print "...
3
U, V = map(int, input().split()) if U > V or U % 2 != V % 2: print(-1) elif U == V: if U == 0: print(0) else: print(1) print(U) else: x = (V-U)//2 if x & U == 0: print(2) print(U+x, x) else: print(3) print(U, x, x)
A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not. You are given a string s of length n, consisting of digits. In one operation you can delete any character from strin...
3
for z in range(int(input())): n=int(input()) s=input() if '8' in s: ind=s.index("8") if n-ind>=11:print("YES") else:print("NO") else:print("NO")
Jerry is a little mouse. He is trying to survive from the cat Tom. Jerry is carrying a parallelepiped-like piece of cheese of size A Γ— B Γ— C. It is necessary to trail this cheese to the Jerry's house. There are several entrances in the Jerry's house. Each entrance is a rounded hole having its own radius R. Could you he...
3
import math while True : d, w, h = map(int, input().split()) if d == 0 and w == 0 and h == 0 : break length = [d, w, h] len_1 = sorted([d, w, h])[0] len_2 = sorted([d, w, h])[1] max_d = math.sqrt(len_1**2 + len_2**2) n = int(input()) for i in range(n) : r = int(...
Kirito is stuck on a level of the MMORPG he is playing now. To move on in the game, he's got to defeat all n dragons that live on this level. Kirito and the dragons have strength, which is represented by an integer. In the duel between two opponents the duel's outcome is determined by their strength. Initially, Kirito'...
3
n,m=map(int,input().split()) a=[list(map(int,input().split())) for i in range(m)] a.sort() s=1 for i in range(m): x,y=a[i][0],a[i][1] s*=n>x n+=y if s==0: print("NO") else: print("YES")
For a positive integer n let's define a function f: f(n) = - 1 + 2 - 3 + .. + ( - 1)nn Your task is to calculate f(n) for a given integer n. Input The single line contains the positive integer n (1 ≀ n ≀ 1015). Output Print f(n) in a single line. Examples Input 4 Output 2 Input 5 Output -3 Note f(4)...
1
import sys, math def rs(): return sys.stdin.readline().strip() def ri(): return int(sys.stdin.readline().strip()) def ras(): return list(sys.stdin.readline().strip()) def rai(): return map(int,sys.stdin.readline().strip().split()) def raf(): return map(float,sys.stdin.readline().strip().split()) ...
For two sequences S and T of length N consisting of 0 and 1, let us define f(S, T) as follows: * Consider repeating the following operation on S so that S will be equal to T. f(S, T) is the minimum possible total cost of those operations. * Change S_i (from 0 to 1 or vice versa). The cost of this operation is D \time...
3
mod=10**9+7 n=int(input()) arr=list(map(int,input().split())) arr=sorted(arr) ans=0 for i in range(n): ans+=pow(2,2*n-2,mod)*(n-i+1)*arr[i] ans%=mod print(int(ans))
Small, but very brave, mouse Brain was not accepted to summer school of young villains. He was upset and decided to postpone his plans of taking over the world, but to become a photographer instead. As you may know, the coolest photos are on the film (because you can specify the hashtag #film for such). Brain took a ...
3
def main(): r, c = map(int, input().split()) f = list() for i in range(r): g = input().split() f.append(g) for i in f: for e in i: if e != 'B' and e != 'W' and e != 'G': print("#Color") return print("#Black&White") if __name__ == ...
Ivan recently bought a detective book. The book is so interesting that each page of this book introduces some sort of a mystery, which will be explained later. The i-th page contains some mystery that will be explained on page a_i (a_i β‰₯ i). Ivan wants to read the whole book. Each day, he reads the first page he didn'...
3
n=int(input()) pages=list(map(int,input().split())) days=0 maxm=pages[0] for i in range(1,n+1): if(pages[i-1]>maxm): maxm=pages[i-1] if(i==maxm): days+=1 print(days)
Areas on the Cross-Section Diagram Your task is to simulate a flood damage. For a given cross-section diagram, reports areas of flooded sections. <image> Assume that rain is falling endlessly in the region and the water overflowing from the region is falling in the sea at the both sides. For example, for the abov...
3
""" をルゴγƒͺズムとデータ構造 P.116 γ‚’Pythonγ§ζ›Έγ„γŸ """ s = input() stack1 = list() stack2 = list() sm = 0 for i, c in enumerate(s): if c == '\\': stack1.append(i) continue if c == '/' and len(stack1) > 0: j = stack1.pop() sm += i - j a = i - j while len(stack2) > 0 and stack2[...
Karan has decided to give stickers to all the attendees of the last day of Google Week. The stickers will be given such that the last person to enter the hall gets a single sticker. The second last person entering the hall gets two stickers and so on. Given the strength of the audience, can you tell him the total numb...
1
from sys import stdin a = stdin.readlines() for i in a[1:]: n = int(i) print ((n*(n+1))/2 % 2**32)
There are N squares arranged in a row, numbered 1, 2, ..., N from left to right. You are given a string S of length N consisting of `.` and `#`. If the i-th character of S is `#`, Square i contains a rock; if the i-th character of S is `.`, Square i is empty. In the beginning, Snuke stands on Square A, and Fnuke stand...
3
n,a,b,c,d = map(int, input().split()) s = input() if '##' in s[a-1:c] or '##' in s[b-1:d]: print('No') else: if c<d: print('Yes') else: if '...' in s[b-2:d+1]: print('Yes') else: print('No')
There are N students and M checkpoints on the xy-plane. The coordinates of the i-th student (1 \leq i \leq N) is (a_i,b_i), and the coordinates of the checkpoint numbered j (1 \leq j \leq M) is (c_j,d_j). When the teacher gives a signal, each student has to go to the nearest checkpoint measured in Manhattan distance. T...
3
N,M = list(map(int,input().split())) s = [list(map(int,input().split())) for i in range(N)] c = [list(map(int,input().split())) for i in range(M)] for i in range(N): d = [] for j in range(M): d.append(abs(s[i][0]-c[j][0])+abs(s[i][1]-c[j][1])) print(d.index(min(d))+1)
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory. George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living...
3
n=int(input()) tot=0 for i in range(n): x,c=map(int,input().split()) if c-x>=2: tot+=1 print(int(tot))
Consider the set of all nonnegative integers: {0, 1, 2, ...}. Given two integers a and b (1 ≀ a, b ≀ 10^4). We paint all the numbers in increasing number first we paint 0, then we paint 1, then 2 and so on. Each number is painted white or black. We paint a number i according to the following rules: * if i = 0, it ...
3
from sys import stdout, stdin, exit for i in stdin: t=int(i) break while t: for i in stdin: a,b=list(map(int,i.strip().split())) break if a==1 or b==1: stdout.write('Finite\n') else: def GCD(a,b): if a==0: return b else: ...
Manao has a monitor. The screen of the monitor has horizontal to vertical length ratio a:b. Now he is going to watch a movie. The movie's frame has horizontal to vertical length ratio c:d. Manao adjusts the view in such a way that the movie preserves the original frame ratio, but also occupies as much space on the scre...
1
from fractions import * a, b, c, d = map(int, raw_input().split(" ")) if a * d == b * c: print "0/1" elif a * d > b * c: print Fraction(a - Fraction(b, d) * c, a) else: print Fraction(b - Fraction(a, c) * d, b)
In distant future on Earth day lasts for n hours and that's why there are n timezones. Local times in adjacent timezones differ by one hour. For describing local time, hours numbers from 1 to n are used, i.e. there is no time "0 hours", instead of it "n hours" is used. When local time in the 1-st timezone is 1 hour, lo...
3
n = int(input()) ps = [ int(a) for a in input().split() ] s,f = [ int(a) for a in input().split() ] window = f-s ps += ps[:window] def f(x): return (s-1-x)%n + 1 answers = [] c = m = sum(ps[:window]) for i in range(n): if c > m: answers = [f(i)] m = c elif c == m: answers += [f(i)...
Someday, Drazil wanted to go on date with Varda. Drazil and Varda live on Cartesian plane. Drazil's home is located in point (0, 0) and Varda's home is located in point (a, b). In each step, he can move in a unit distance in horizontal or vertical direction. In other words, from position (x, y) he can go to positions (...
1
a, b, s = map(int,raw_input().split()) if a<=0: a = a*(-1) if b<=0: b = b*(-1) s = ((s - a) - b) if s%2 == 0 and s>=0: print 'Yes' else: print 'No'
Polycarp decided to relax on his weekend and visited to the performance of famous ropewalkers: Agafon, Boniface and Konrad. The rope is straight and infinite in both directions. At the beginning of the performance, Agafon, Boniface and Konrad are located in positions a, b and c respectively. At the end of the performa...
3
a,b,c,d=map(int,input().split()) l=[a,b,c] l.sort() res=0 if(abs(l[0]-l[1])<d): res+=abs((l[1]-d)-l[0]) if(l[2]-l[1]<d): res+=abs(l[1]+d-l[2]) print(res)
There is a robot on a coordinate plane. Initially, the robot is located at the point (0, 0). Its path is described as a string s of length n consisting of characters 'L', 'R', 'U', 'D'. Each of these characters corresponds to some move: * 'L' (left): means that the robot moves from the point (x, y) to the point (x...
3
t = int(input()) while t > 0: n = int(input()) s = input() x = 0 y = 0 mem = {(0, 0): 0} r = n l = -1 for i in range(n): if s[i] == 'L': x -= 1 elif s[i] == 'R': x += 1 elif s[i] == 'U': y += 1 else: y -= 1 ...
Snuke has N integers: 1,2,\ldots,N. He will choose K of them and give those to Takahashi. How many ways are there to choose K consecutive integers? Constraints * All values in input are integers. * 1 \leq K \leq N \leq 50 Input Input is given from Standard Input in the following format: N K Output Print the a...
3
#A N, K= map(int, input().split()) print(N - K + 1)
The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: * d1 is the distance between the 1-st and the 2-nd station; * d2 is the distance between the 2-nd and the 3-rd station; ... * dn - 1 is the distance between the n - 1-th and the n-th station; ...
3
n = int(input()) t = list(map(int, input().split())) * 2 a, b = sorted(map(lambda x: int(x) - 1, input().split())) print(min(sum(t[a:b]), sum(t[b:a+n])))
We have a grid of H rows and W columns. Initially, there is a stone in the top left cell. Shik is trying to move the stone to the bottom right cell. In each step, he can move the stone one cell to its left, up, right, or down (if such cell exists). It is possible that the stone visits a cell multiple times (including t...
3
h,w=map(int,input().split()) a=[list(input()) for i in range(h)] c=0 for j in range(h): for k in range(w): if a[j][k]=='#':c+=1 if c==h+w-1:print('Possible') else:print('Impossible')
There are two rival donut shops. The first shop sells donuts at retail: each donut costs a dollars. The second shop sells donuts only in bulk: box of b donuts costs c dollars. So if you want to buy x donuts from this shop, then you have to buy the smallest number of boxes such that the total number of donuts in them ...
3
for _ in range(int(input())): a, b, c = map(int, input().split()) print(1 if a < c else -1, b if c < a * b else -1)
AtCoDeer has three cards, one red, one green and one blue. An integer between 1 and 9 (inclusive) is written on each card: r on the red card, g on the green card and b on the blue card. We will arrange the cards in the order red, green and blue from left to right, and read them as a three-digit integer. Is this integer...
3
print("YES" if int("".join(input().split()))%4==0 else "NO")
Summer holidays! Someone is going on trips, someone is visiting grandparents, but someone is trying to get a part-time job. This summer Noora decided that she wants to earn some money, and took a job in a shop as an assistant. Shop, where Noora is working, has a plan on the following n days. For each day sales manager...
3
planDays,chosenDays=map(int,input().split()) total=[] t=0 for i in range(planDays): products,clients=map(int,input().split()) # if (i+1)% chosenDays ==0: # products=2*products # if products >= clients: # total+= clients # elif products < clients and products !=0 : # ...
"You must lift the dam. With a lever. I will give it to you. You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them. Hermit Lizard agreed to give Danik the lever. But to get a stone...
3
import sys input=sys.stdin.readline t=int(input()) for you in range(t): n=int(input()) l=input().split() li=[int(i) for i in l] hashi=dict() count=0 for i in li: for j in range(31,-1,-1): if(i&(1<<j)): ans=j break if(ans in hashi): ...
In Berland, there is the national holiday coming β€” the Flag Day. In the honor of this event the president of the country decided to make a big dance party and asked your agency to organize it. He has several conditions: * overall, there must be m dances; * exactly three people must take part in each dance; * eac...
3
from sys import * input = lambda:stdin.readline() int_arr = lambda : list(map(int,stdin.readline().strip().split())) str_arr = lambda :list(map(str,stdin.readline().split())) get_str = lambda : map(str,stdin.readline().strip().split()) get_int = lambda: map(int,stdin.readline().strip().split()) get_float = lambda : ma...
So the Beautiful Regional Contest (BeRC) has come to an end! n students took part in the contest. The final standings are already known: the participant in the i-th place solved p_i problems. Since the participants are primarily sorted by the number of solved problems, then p_1 β‰₯ p_2 β‰₯ ... β‰₯ p_n. Help the jury distrib...
3
import sys input = lambda: sys.stdin.readline().rstrip() def first(m): cur = m[-1] if len(m) >= 2: k = 0 while cur == m[-1]: del m[-1] if len(m) == 0: return False if len(m) <= 2: return False return m else: return...
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...
3
n = int(input()) print('aabb' * (n // 4) + 'aabb'[:(n % 4)])
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
a = input() a = int(a) if(a == 2): print("NO") elif(a % 2 == 0): print("YES") else: print("NO")
Takahashi is now competing in a programming contest, but he received TLE in a problem where the answer is `YES` or `NO`. When he checked the detailed status of the submission, there were N test cases in the problem, and the code received TLE in M of those cases. Then, he rewrote the code to correctly solve each of th...
3
n,m=list(map(int,input().split())) print((m*1900+(n-m)*100)*2**m)
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the oppo...
3
n=int(input()) l=[] c=0 for i in range(0,n): k=int(input()) l.append(k) for i in range (len(l)): if i==len(l)-1: break if l[i]!=l[i+1]: c+=1 else: continue print(c+1)
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
n ,m = map(int, input().split()) Max = max(n,m) Min = min(n,m) result=0 while Max!=0 and Min!=0 and Max+Min>2: Max-=2 Min-=1 Max2=Max Min2=Min Max = max(Max2, Min2) Min = min(Max2, Min2) result+=1 print(result)
Valera is a little boy. Yesterday he got a huge Math hometask at school, so Valera didn't have enough time to properly learn the English alphabet for his English lesson. Unfortunately, the English teacher decided to have a test on alphabet today. At the test Valera got a square piece of squared paper. The length of the...
1
n = input() square = [] for x in range(0,n): s = raw_input() square.append(s) i = 0 j = n - 1 flag = True diag = square[0][0] op = square[0][1] if (diag == op): flag = False for x in range (0,len(square)): if (flag == False): break for y in range(0,len(square[x])): if (y == i or y == j): if (square[x][y] !...
Polycarp wants to cook a soup. To do it, he needs to buy exactly n liters of water. There are only two types of water bottles in the nearby shop β€” 1-liter bottles and 2-liter bottles. There are infinitely many bottles of these two types in the shop. The bottle of the first type costs a burles and the bottle of the se...
3
q = int(input()) for i in range(q): n, a, b = [int(i) for i in input().split()] if b >= a*2: r = n*a else: r = (n//2)*b + (n%2)*a print(r)
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
import sys import math import os from collections import Counter # To store no of test cases here (2). #t=int(sys.stdin.readline()) # # To store input here (0 1 1) and (0 1 2). a_1 = list(sys.stdin.readline()) a_2 = a_1.copy() setes = Counter(a_1) if setes['0']==0: print(''.join(a_1[:-2])) else: for x in a_1: i...
Finally, a basketball court has been opened in SIS, so Demid has decided to hold a basketball exercise session. 2 β‹… n students have come to Demid's exercise session, and he lined up them into two rows of the same size (there are exactly n people in each row). Students are numbered from 1 to n in each row in order from ...
3
n = int(input()) x = list(map(int,input().split())) y = list(map(int,input().split())) t = [[0 for i in range(3)] for j in range(n+1)] for i in range(1,n+1): t[i][0] = max(t[i-1]) t[i][1] = max(t[i-1][0],t[i-1][2])+ x[i-1] t[i][2] = max(t[i-1][0],t[i-1][1])+ y[i-1] print(max(t[n]))
The Kingdom of Takahashi has N towns, numbered 1 through N. There is one teleporter in each town. The teleporter in Town i (1 \leq i \leq N) sends you to Town A_i. Takahashi, the king, loves the positive integer K. The selfish king wonders what town he will be in if he starts at Town 1 and uses a teleporter exactly K...
3
n,k,*a=map(int,open(0).read().split()) d={} s=1 while k:k-=1;s=a[s-1];k%=d.get(s,2**61)-k;d[s]=k print(s)
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like. Now let's imagine a typical morning in your family. You haven't w...
3
n = int(input()) arr = list(int(a) for a in input().split(" ")) arr = sorted(arr, reverse = True) for i in range(len(arr)+1): arr1 = arr[:i] arr2 = arr[i:] sum1 = sum(arr1) sum2 = sum(arr2) if sum1 > sum2: print(i) break
Snuke loves working out. He is now exercising N times. Before he starts exercising, his power is 1. After he exercises for the i-th time, his power gets multiplied by i. Find Snuke's power after he exercises N times. Since the answer can be extremely large, print the answer modulo 10^{9}+7. Constraints * 1 ≀ N ≀ 10...
3
import math n = int(input()) print(math.factorial(n)%(10**(9) + 7))
In this problem, we use the 24-hour clock. Takahashi gets up exactly at the time H_1 : M_1 and goes to bed exactly at the time H_2 : M_2. (See Sample Inputs below for clarity.) He has decided to study for K consecutive minutes while he is up. What is the length of the period in which he can start studying? Constraint...
3
a,b,c,d,e = map(int, input().split()) val = (c-a)*60+(d-b) print(val-e)
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()); s = 0; dayskg = 0 cenamin = 100 for i in range(n): kg, cena = map(int, input().split()) if (cena < cenamin): cenamin = cena s +=kg*cenamin print(s)
Gottfried learned about binary number representation. He then came up with this task and presented it to you. You are given a collection of n non-negative integers a_1, …, a_n. You are allowed to perform the following operation: choose two distinct indices 1 ≀ i, j ≀ n. If before the operation a_i = x, a_j = y, then a...
3
n=int(input()) a=list(map(int,input().split())) ct=[0]*30 for x in a: for sf in range(30): ct[sf]+=(x>>sf)&1 ans=[0]*n for i in range(30): for j in range(ct[i]): ans[j]|=1<<i print(sum([x**2 for x in ans]))
The math faculty of Berland State University has suffered the sudden drop in the math skills of enrolling students. This year the highest grade on the entrance math test was 8. Out of 100! Thus, the decision was made to make the test easier. Future students will be asked just a single question. They are given a sequen...
3
# -*- coding: utf-8 -*- """ 1 circle 2 triangle 3 square """ def convert(string): return string.split(sep=None,maxsplit=-1) def toint(lst): result=[] for i in lst: result.append(int(i)) return result n=int(input()) temp=toint(convert(input())) count=0 measure="Finite" for i in range(n-1): ...
Sereja has an array a, consisting of n integers a1, a2, ..., an. The boy cannot sit and do nothing, he decided to study an array. Sereja took a piece of paper and wrote out m integers l1, l2, ..., lm (1 ≀ li ≀ n). For each number li he wants to know how many distinct numbers are staying on the positions li, li + 1, ......
3
k = map(int, input().split()) kk = list(k) n = kk[0] m = kk[1] aux = set() aa = map(int, input().split()) a = list(aa) for i in range(n-1,-1,-1): aux.add(a[i]) a[i] = len(aux) resp = "" for i in range(m): act = int(input()) resp += str(a[act-1]) + "\n" print(resp)
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...
1
a=input() b=input() c=input() print max(a*b*c,a*(b+c),(a+b)*c,a+b*c,a*b+c,a+b+c)
Input The input contains a single integer a (1 ≀ a ≀ 64). Output Output a single integer. Examples Input 2 Output 1 Input 4 Output 2 Input 27 Output 5 Input 42 Output 6
1
n=int(input());print([int("0111212152215121e1515221f22541410121e122e1614221025151f2d221d1240"[n],36),n//16+49+(n>>6)*214][n>>4>1 and n&15==0])
Polycarp has n coins, the value of the i-th coin is a_i. Polycarp wants to distribute all the coins between his pockets, but he cannot put two coins with the same value into the same pocket. For example, if Polycarp has got six coins represented as an array a = [1, 2, 4, 3, 3, 2], he can distribute the coins into two ...
3
n=int(input()) l=[int(x) for x in input().split(" ")] a=0 f = {} for i in l: if (i in f): f[i] += 1 else: f[i] = 1 for key, value in f.items(): if value>a: a=value print(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
for t in range(int(input())): n = int(input()) if n<2: print(n) else: print(n//2)
In the evening, after the contest Ilya was bored, and he really felt like maximizing. He remembered that he had a set of n sticks and an instrument. Each stick is characterized by its length li. Ilya decided to make a rectangle from the sticks. And due to his whim, he decided to make rectangles in such a way that maxi...
1
from collections import Counter n = input() sticks = map(int, raw_input().split()) cnt = Counter() for s in sticks: cnt[s] += 1 T = sorted(map(list, cnt.items())) for i in range(len(T))[1:][::-1]: if T[i][1] % 2 and T[i-1][0] == T[i][0] - 1: T[i][1] -= 1 T[i-1][1] += 1 pairs = [] for length, count in T: pairs +...
Limak is a little polar bear. He has n balls, the i-th ball has size ti. Limak wants to give one ball to each of his three friends. Giving gifts isn't easy β€” there are two rules Limak must obey to make friends happy: * No two friends can get balls of the same size. * No two friends can get balls of sizes that di...
3
n = int(input()) ll = list(map(int,input().split())) #l=sorted(list(set(ll))) a=[0 for i in range(1001)] #print(a) maxx=0 for i in ll: a[i]=1 if i>maxx: maxx=i #print(a) flag=0 maxx+=1 for i in range(2,maxx): if(a[i]==1 and a[i-1]==1 and a[i-2]==1): flag=1 break; if flag: print('...
There are some ambiguities when one writes Berland names with the letters of the Latin alphabet. For example, the Berland sound u can be written in the Latin alphabet as "u", and can be written as "oo". For this reason, two words "ulyana" and "oolyana" denote the same name. The second ambiguity is about the Berland s...
3
def expand(x): x = x.replace('u', 'oo') x = x.replace('h', 'kh') return x def reduce(x): nx = '' while True: nx = x.replace('oo', 'u') if nx == x: break x = nx while True: nx = x.replace('kh', 'h') if nx == x: break x = nx if 'oo' in x or 'kh'...
Navi got a task at school to collect N stones. Each day he can collect only one stone. As N can be a very large number so it could take many days to complete the task, but then he remembers that his mother gave him a magic that can double anything (i.e if he has 2 stones, the magic will make them to 4 stones). Navi ...
1
t=int(raw_input()) while t: t=t-1 n=int(raw_input()) no_b=0 while n: if n%2==1: no_b+=1 n=n/2 print no_b
Little Robber Girl likes to scare animals in her zoo for fun. She decided to arrange the animals in a row in the order of non-decreasing height. However, the animals were so scared that they couldn't stay in the right places. The robber girl was angry at first, but then she decided to arrange the animals herself. She ...
3
n=int(input()) a=list(map(int,input().split())) ans=[] coun=0 def maxin(a): global coun x=a.index(max(a)) while x<len(a)-1: ans.append((x+1,x+2)) coun+=1 a[x],a[x+1]=a[x+1],a[x] x=x+1 a=a[:-1] return a while len(a)!=1: a=maxin(a) for i in ans: pri...
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 ...
3
def wannabe(): n= int(input()) levels = [i for i in range(1,n+1)] passed = [] x_lvls = list(map(int,input().split())) y_lvls = list(map(int,input().split())) for lvl_x in x_lvls[1:]: passed.append(lvl_x) for lvl_y in y_lvls[1:]: passed.append(lvl_y) if len(...
One Sunday Petr went to a bookshop and bought a new book on sports programming. The book had exactly n pages. Petr decided to start reading it starting from the next day, that is, from Monday. Petr's got a very tight schedule and for each day of the week he knows how many pages he will be able to read on that day. Som...
1
def fun(n, d): i = 0 while n - d[i] > 0: n -= d[i] i = (i+1) % 7 return i+1 if __name__ == "__main__": n = int(raw_input()) d = map(int,raw_input().split(" ")) print fun(n, d)
Valera is a little boy. Yesterday he got a huge Math hometask at school, so Valera didn't have enough time to properly learn the English alphabet for his English lesson. Unfortunately, the English teacher decided to have a test on alphabet today. At the test Valera got a square piece of squared paper. The length of the...
3
n = int(input() ) A = [input() for _ in range(n) ] if len(set([A[i][j] for i in range(n) for j in range(n) ] ) ) == 2: ok_x = True ok_y = True for i in range(n): for j in range(n): if i == j or i == n - 1 - j: ok_x &= A[i][j] == A[0][0] else: ...
Kevin Sun wants to move his precious collection of n cowbells from Naperthrill to Exeter, where there is actually grass instead of corn. Before moving, he must pack his cowbells into k boxes of a fixed size. In order to keep his collection safe during transportation, he won't place more than two cowbells into a single ...
1
n,k = map(int,raw_input().split()) s = map(int,raw_input().split()) m = n - k if k >= n: print s[-1] quit() l = s[-1] - 1 r = s[-1]*n + 1 while r - l > 1: mid = (l + r) / 2 if all(s[m-1-i]+s[m+i] <= mid for i in xrange(m)): r = mid else: l = mid print r
Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in n different shops in the city. It's known that the price of one bottle in the shop i is equal to xi coins. Vasiliy plans to buy his favorite drink fo...
3
import bisect input() lt=sorted([int(i) for i in input().split()]) for i in range(int(input())): print(bisect.bisect(lt,int(input())))
Recently Polycarp noticed that some of the buttons of his keyboard are malfunctioning. For simplicity, we assume that Polycarp's keyboard contains 26 buttons (one for each letter of the Latin alphabet). Each button is either working fine or malfunctioning. To check which buttons need replacement, Polycarp pressed som...
1
t = int(input()) for _ in xrange(t): S = raw_input() pc = 1 prev = S[0] works = [False]*26 for x in S[1:]: if x==prev: pc += 1 else: if pc%2: works[ord(prev)-97] = True ...
Today, Mezo is playing a game. Zoma, a character in that game, is initially at position x = 0. Mezo starts sending n commands to Zoma. There are two possible commands: * 'L' (Left) sets the position x: =x - 1; * 'R' (Right) sets the position x: =x + 1. Unfortunately, Mezo's controller malfunctions sometimes. ...
3
n = input() c = input() l = 0; r= 0 for i in c: if (i=="L"): l+=1 else: r+=1 print(r+l+1)