problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
Nastya just made a huge mistake and dropped a whole package of rice on the floor. Mom will come soon. If she sees this, then Nastya will be punished. In total, Nastya dropped n grains. Nastya read that each grain weighs some integer number of grams from a - b to a + b, inclusive (numbers a and b are known), and the wh...
3
a=int(input()) h=[] for i in range(0,a): n,a,b,c,d=list(map(int,input().split())) L = n * (a - b) R = n * (a + b) if R < c - d or c + d < L: h.append("No") else: h.append("Yes") print(*h,sep='\n')
A game is played on a strip consisting of N cells consecutively numbered from 1 to N. Alice has her token on cell A. Borys has his token on a different cell B. Players take turns, Alice moves first. The moving player must shift his or her token from its current cell X to the neighboring cell on the left, cell X-1, or...
1
[N,A,B]=map(int,raw_input().split()) if (A-B)%2==0: print "Alice" else: print "Borys"
The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a pla...
3
n = int(input()) k = n a = list() while n > 0: n -= 1 q, s = input().split() s = int(s) a.append([q, s]) l1 = {} while k > 0: k -= 1 if a[k][0] in l1: c = a[k][1] + l1.get(a[k][0]) l1[a[k][0]] = c else: l1[a[k][0]] = a[k][1] n = max(l1.values()) l2 = {} for name, sc...
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
3
a = int(input("")) for i in range(a): word = input("") ln = len(word) if ln <= 10: print(word) else: print(word[0],end='') print(len(word)-2,end='') print(word[-1])
There is an infinitely long street that runs west to east, which we consider as a number line. There are N roadworks scheduled on this street. The i-th roadwork blocks the point at coordinate X_i from time S_i - 0.5 to time T_i - 0.5. Q people are standing at coordinate 0. The i-th person will start the coordinate 0 ...
3
import heapq class BalancingTree: def __init__(self): self.p = [] self.q = [] def insert(self, x): heapq.heappush(self.p, x) def erase(self, x): heapq.heappush(self.q, x) def minimum(self): while self.q and self.p[0] == self.q[0]: heapq.heappop(sel...
Vus the [Cossack](https://en.wikipedia.org/wiki/Cossacks) holds a programming competition, in which n people participate. He decided to award them all with pens and notebooks. It is known that Vus has exactly m pens and k notebooks. Determine whether the Cossack can reward all participants, giving each of them at leas...
3
a,b,c=tuple(map(int,input().split())) if b>=a and c>=a: print('YES') else: print('NO')
You want to arrange n integers a1, a2, ..., an in some order in a row. Let's define the value of an arrangement as the sum of differences between all pairs of adjacent integers. More formally, let's denote some arrangement as a sequence of integers x1, x2, ..., xn, where sequence x is a permutation of sequence a. The ...
3
n=int(input());a=sorted(map(int,input().split()));a[0],a[-1]=a[-1],a[0];print(*a)
To get on the Shinkansen, you need two tickets, a "ticket" and a "limited express ticket". These are separate tickets because some of the routes may not use the Shinkansen, but for routes that use only the Shinkansen, one ticket can be used as both a ticket and a limited express ticket. It may also be issued. Automati...
3
a,b,c = map(int,input().split()) if a == 1: if b == 1: print("Open") else: print("Close") else: if b == 0: if c == 0: print("Close") else: print("Open") else: print("Close")
Your company was appointed to lay new asphalt on the highway of length n. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing. Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are ...
3
t = int(input()) def ceil(a, b): return a // b + (a % b > 0) for _ in range(t): n,g,b = map(int,input().split()) k = (ceil(n, 2) - 1) // g last = ceil(n, 2) - k * g ans = k * (g + b) + last print(max(ans, n))
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries. The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world. There is at most one...
3
def dfs(u,vis): vis.add(u) for v in g[u]: if v not in vis: dfs(v,vis) n,m,k = map(int,list(input().split())) govs_ind = map(int,list(input().split())) orig = set() countries = set(range(1,n+1)) g = [ [] for i in range(n+1) ] for i in range(m): u,v = map(int,list(input().split())) if(u>v): u,v = v,u ori...
Our monk loves food. Hence,he took up position of a manager at Sagar,a restaurant that serves people with delicious food packages. It is a very famous place and people are always queuing up to have one of those packages. Each package has a cost associated with it. The packages are kept as a pile. The job of a manager...
1
NoQueries = input() Food = [] for x in xrange(0,NoQueries): line = raw_input() line = line.split() if line[0] == "1": if Food: temp = int(Food.pop()) print temp else: print "No Food" elif line[0] == "2": Food.append(line[1])
Taro is going to play a card game. However, now he has only n cards, even though there should be 52 cards (he has no Jokers). The 52 cards include 13 ranks of each of the four suits: spade, heart, club and diamond. Note 解説 Input In the first line, the number of cards n (n ≤ 52) is given. In the following n line...
3
n = int(input()) list = [] for i in range(n): list.append(input()) for s in ["S", "H", "C", "D"]: for r in range(1, 14): if s + " " + str(r) not in list: print(s,r)
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...
1
x = int(raw_input()) print 2**(x/2) if (x%2 == 0 and x != 0) else 0
A group of people played a game. All players had distinct scores, which are positive integers. Takahashi knows N facts on the players' scores. The i-th fact is as follows: the A_i-th highest score among the players is B_i. Find the maximum possible number of players in the game. Constraints * 1 \leq N \leq 10^5 * 1...
3
n=int(input()) t=0 ans=0 for i in range(n): a,b=map(int,input().split()) if t<a: ans=a+b t=a print(ans)
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...
3
for _ in range(int(input())): n = int(input()) s = list(map(int,input().split())) s.sort() k = s[-1] f=1 for i in range(len(s)-2,-1,-1): if abs(k - s[i]) <= 1: s.remove(k) k=s[i] else: print("NO") f=0 break if f and ...
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
3
n=int(input()) a=[0]*n c=[0]*n b=[0]*n q=[0]*n for i in range(n): a[i]=list(input()) if len(a[i])>10: b[i]=a[i].pop(0) c[i]=a[i].pop(len(a[i])-1) b[i]=b[i]+str(len(a[i]))+ c[i] print(b[i]) else: for j in range(len(a[i])): if j==len(a[i])-1: ...
Andre has very specific tastes. Recently he started falling in love with arrays. Andre calls an nonempty array b good, if sum of its elements is divisible by the length of this array. For example, array [2, 3, 1] is good, as sum of its elements — 6 — is divisible by 3, but array [1, 1, 2, 3] isn't good, as 7 isn't div...
3
for i in range(0, int(input())): print("1 " * int(input()))
Vasya learns to type. He has an unusual keyboard at his disposal: it is rectangular and it has n rows of keys containing m keys in each row. Besides, the keys are of two types. Some of the keys have lowercase Latin letters on them and some of the keys work like the "Shift" key on standard keyboards, that is, they make ...
3
from collections import defaultdict def search(a, t): l = 0 r = len(a)-1 while (r-l)>=0: mid = (l+r)//2 if a[mid] == t: return True if a[mid] < t: l = mid+1 if a[mid] >= t: r = mid-1 return False...
10^9 contestants, numbered 1 to 10^9, will compete in a competition. There will be two contests in this competition. The organizer prepared N problems, numbered 1 to N, to use in these contests. When Problem i is presented in a contest, it will be solved by all contestants from Contestant L_i to Contestant R_i (inclus...
3
from operator import itemgetter n=int(input()) l=[list(map(int,input().split())) for i in range(n)] for i in range(n): l[i]=[l[i][0],l[i][1],(l[i][0]+l[i][1])/2] len=[] for i in range(n): len.append(l[i][1]-l[i][0]+1) maxlen=max(len) x=len.index(maxlen) L3=1;R3=10**9 for i in range(n): if l!=x: L3=max(L3,l[i]...
After returning from the army Makes received a gift — an array a consisting of n positive integer numbers. He hadn't been solving problems for a long time, so he became interested to answer a particular question: how many triples of indices (i, j, k) (i < j < k), such that ai·aj·ak is minimum possible, are there in the...
3
n = input() a = [int(n) for n in input().split()] a.sort() first = a.count((a[0])) second = a.count((a[1])) if a[0] == a[1]: second -= 1 third = a.count((a[2])) if first >= 3: ans = ((first)*(first-1)*(first-2))/6 elif second >= 2: ans = ((second)*(second-1))/2 else : ans = third print(int(ans))
Young wilderness explorers set off to their first expedition led by senior explorer Russell. Explorers went into a forest, set up a camp and decided to split into groups to explore as much interesting locations as possible. Russell was trying to form groups, but ran into some difficulties... Most of the young explorer...
3
import sys input = sys.stdin.readline Q = int(input()) Query = [] for _ in range(Q): N = int(input()) A = list(map(int, input().split())) Query.append((N, A)) for N, A in Query: A.sort() ans = 0 Ma = 0 Mem = 0 for a in A: Ma = max(Ma, a) Mem += 1 if Ma <= Mem: ...
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
g=int(input('')) numsArr = [int(x) for x in input("").split()] even=0 odd=0 indexOdd=0 indexEven=0 for i in numsArr: if int(i)%2==0: even+=1 indexEven=numsArr.index(i) else: odd+=1 indexOdd=numsArr.index(i) if even==1: print(indexEven+1) else: print(in...
You have n gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The i-th gift consists of a_i candies and b_i oranges. During one move, you can choose some gift 1 ≤ i ≤ n and do one of the following operations: * eat exactly...
3
# cook your dish here for _ in range(int(input())): n=int(input()) a=list(map(int,input().split())) b=list(map(int,input().split())) ma=min(a) mb=min(b) for i in range(len(a)): a[i]-=ma for i in range(len(b)): b[i]-=mb ans=0 for i in range(len(a)): an...
Andrewid the Android is a galaxy-famous detective. He is now investigating the case of vandalism at the exhibition of contemporary art. The main exhibit is a construction of n matryoshka dolls that can be nested one into another. The matryoshka dolls are numbered from 1 to n. A matryoshka with a smaller number can be ...
3
n, k = map(int, input().split()) for _ in range(k): a = list(map(int, input().split()))[1:] + [0] if a[0] != 1: continue i = 0 while a[i + 1] == i + 2: i += 1 print(2 * n - k - 1 - 2 * i)
Well, here is another math class task. In mathematics, GCD is the greatest common divisor, and it's an easy task to calculate the GCD between two positive integers. A common divisor for two positive numbers is a number which both numbers are divisible by. But your teacher wants to give you a harder task, in this task...
3
import sys input = sys.stdin.readline from math import * def bs(a,x,y): l=0 r=len(a)-1 ans=-1 while l<=r: mid=l+(r-l)//2 if x<=a[mid]<=y: ans=a[mid] l=mid+1 elif a[mid]>y: r=mid-1 else: l=mid+1 return ans a,b = m...
Iahub got bored, so he invented a game to be played on paper. He writes n integers a1, a2, ..., an. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices i and j (1 ≤ i ≤ j ≤ n) and flips all values ak for which their positions are in range [i, j] (that is i ≤ k ≤ j)...
3
def count(a,size): max_so_far = 0 max_ending_here = 0 for i in range(0, size): if a[i] == 1: max_ending_here -= 1 else: max_ending_here += 1 if max_ending_here > max_so_far: max_so_far = max_ending_here if max_ending_here < 0: ...
Your friend has recently learned about coprime numbers. A pair of numbers {a, b} is called coprime if the maximum number that divides both a and b is equal to one. Your friend often comes up with different statements. He has recently supposed that if the pair (a, b) is coprime and the pair (b, c) is coprime, then the...
3
l,r=map(int,input().split());q=int(l&1) if r-l<2or(r-l==2and l&1):print(-1) else:print(*[l+q,l+q+1,l+q+2])
This is the easy version of the problem. The difference between the versions is that in the easy version all prices a_i are different. You can make hacks if and only if you solved both versions of the problem. Today is Sage's birthday, and she will go shopping to buy ice spheres. All n ice spheres are placed in a row ...
3
n=int(input()) arr=list(map(int,input().split())) arr.sort() small=arr[:len(arr)//2] large=arr[len(arr)//2:] i=0 while i<len(arr): if i%2==0: arr[i]=large[i//2] else: arr[i]=small[i//2] i+=1 print((len(arr)-1)//2) for i in arr: print(i,end=" ")
Alice guesses the strings that Bob made for her. At first, Bob came up with the secret string a consisting of lowercase English letters. The string a has a length of 2 or more characters. Then, from string a he builds a new string b and offers Alice the string b so that she can guess the string a. Bob builds b from a...
3
if __name__=='__main__': t = int(input()) while t: b = input() s = b[0] for i in range(1,len(b)-1,2): s+=b[i] s+=b[-1] print(s) t-=1
We have A apples and P pieces of apple. We can cut an apple into three pieces of apple, and make one apple pie by simmering two pieces of apple in a pan. Find the maximum number of apple pies we can make with what we have now. Constraints * All values in input are integers. * 0 \leq A, P \leq 100 Input Input is g...
3
A,P = map(int,input().split(' ')) print(int((A*3+P)/2))
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms: 1. Make vi-th array element equal to xi. In other words, perform the assignment avi = xi. 2. Increase each array element by yi....
1
def iarr(): return map(int,raw_input().split()) [n,m] = iarr() arr = zip(iarr(),[0]*n) s = [0] t = 0 for i in xrange(m): op = iarr() if(op[0] == 1): arr[op[1]-1] = [op[2],t] elif(op[0] == 2): s.append(s[-1]+op[1]) t+=1 else: print arr[op[1]-1][0] + s[-1] - s[arr[op[1]-1][...
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(2*a<=b): print(a*n) else: print(b*(n//2) + a*(n%2))
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
n = int(input()) a = sorted(list(map(int, input().split()))) if len(a) == 1: print('YES\n0\n\n1') print(a[0]) else: s1, s2 = [a[0]], [a[1]] for q in range(2, len(a)): if s1[-1] != a[q]: s1.append(a[q]) elif s2[-1] != a[q]: s2.append(a[q]) else: ...
Little C loves number «3» very much. He loves all things about it. Now he has a positive integer n. He wants to split n into 3 positive integers a,b,c, such that a+b+c=n and none of the 3 integers is a multiple of 3. Help him to find a solution. Input A single line containing one integer n (3 ≤ n ≤ 10^9) — the integ...
3
n = int(input()) n -= 1 x = n // 2 y = n - x while x % 3 == 0 or y % 3 == 0: x -= 1 y += 1 print(1, x, y)
Alicia has an array, a_1, a_2, …, a_n, of non-negative integers. For each 1 ≤ i ≤ n, she has found a non-negative integer x_i = max(0, a_1, …, a_{i-1}). Note that for i=1, x_i = 0. For example, if Alicia had the array a = \{0, 1, 2, 0, 3\}, then x = \{0, 0, 1, 2, 2\}. Then, she calculated an array, b_1, b_2, …, b_n: ...
3
n = int(input()) *b, = map(int, input().split( )) a = [] mx = 0 for i in range(n): a.append(b[i]+mx) mx = max(mx,a[-1]) print(*a)
Find the convex hull of a given set of points P. In other words, find the smallest convex polygon containing all the points of P. Here, in a convex polygon, all interior angles are less than or equal to 180 degrees. Please note that you should find all the points of P on both corner and boundary of the convex polygon....
3
#!/usr/bin/env python # -*- coding: utf-8 -*- """ input: 7 2 1 0 0 1 2 2 2 4 2 1 3 3 3 output: 5 0 0 2 1 4 2 3 3 1 3 """ import sys from operator import attrgetter EPS = 1e-9 def cross(a, b): return a.real * b.imag - a.imag * b.real def dot(a, b): return a.real * b.real + a.imag * b.imag def check_ccw...
Another programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place. You know the rules of comparing the results of two give...
1
n, k = map(int, raw_input().split()) p = [] for i in range(n): p.append(map(int, raw_input().split())) p = [x for x in reversed(sorted(p, key = lambda x: (x[0], -x[1])))] i = 0 while i < n: if i + 1 <= k <= i + 1 + p.count(p[i]) - 1: print p.count(p[i]) break i += p.count(p[i])...
Alice and Bob, both have to drink water. But they both don't want to go, so they will play a game to decide who will fetch water for both of them. Alice will choose a number randomly between 1 and N (both inclusive) and Bob will choose a number randomly between 1 and M (both inclusive). Both will write their numbers on...
1
import fractions as fs N = input() A = [] for i in range(N): t = raw_input().split() t2=[] t2.append(int(t[0])) t2.append(int(t[1])) A.append(t2) def getOdd(n,m): if (n*m)&1 : return n*m/2 else: return ((n*m-1)/2)+1 def solve(x): n = x[0] m = x[1] odd = getOdd(n,m) tot = n*m c = fs.gcd(odd,tot) a ...
You are given a string S as input. This represents a valid date in the year 2019 in the `yyyy/mm/dd` format. (For example, April 30, 2019 is represented as `2019/04/30`.) Write a program that prints `Heisei` if the date represented by S is not later than April 30, 2019, and prints `TBD` otherwise. Constraints * S is...
3
S = input() if int(S[5:7]) < 5: print("Heisei") else: print("TBD")
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
from sys import stdin,stdout import math for _ in range(int(stdin.readline())): a,b,c,d=map(int,stdin.readline().split()) s=b count=0 if b>=a: print(b) else: if c<=d: print("-1") else: count=math.ceil((a-b)/(c-d)) ans=b+(count*c) stdout.write(str(ans)) print()
While playing with geometric figures Alex has accidentally invented a concept of a n-th order rhombus in a cell grid. A 1-st order rhombus is just a square 1 × 1 (i.e just a cell). A n-th order rhombus for all n ≥ 2 one obtains from a n-1-th order rhombus adding all cells which have a common side with it to it (look ...
3
N = int(input()) ans = 1 + (2 * (N - 1)*N) print(ans)
Duff is in love with lovely numbers! A positive integer x is called lovely if and only if there is no such positive integer a > 1 such that a2 is a divisor of x. <image> Malek has a number store! In his store, he has only divisors of positive integer n (and he has all of them). As a birthday present, Malek wants to g...
1
def main(): n = input() i = 2 ans = 1 while i * i <= n: if n % i == 0: ans *= i while n % i == 0: n /= i i += 1 if n > 1: ans *= n print ans main()
You are given an array a consisting of n integers numbered from 1 to n. Let's define the k-amazing number of the array as the minimum number that occurs in all of the subsegments of the array having length k (recall that a subsegment of a of length k is a contiguous part of a containing exactly k elements). If there i...
3
for x in range(int(input())): n = int(input()) m=list(map(int,input().split())) d={} ind={} for i in range(n): if m[i] in d: d[m[i]]=max(d[m[i]],i-ind[m[i]]) ind[m[i]]=i else: ind[m[i]]=i d[m[i]]=i+1 #print(d,ind) for i in ...
Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpr...
3
from fractions import Fraction y,w=input().split() y=int(y) w=int(w) x=max(y,w) x=7-x print(Fraction(x,6).numerator,"/",Fraction(x,6).denominator,sep="")
You are given a positive integer n. Let S(x) be sum of digits in base 10 representation of x, for example, S(123) = 1 + 2 + 3 = 6, S(0) = 0. Your task is to find two integers a, b, such that 0 ≤ a, b ≤ n, a + b = n and S(a) + S(b) is the largest possible among all such pairs. Input The only line of input contains a...
3
n = int(input()) ans = 0 while n % 10 == 9: ans += 9 n //=10 if n == 0: print(ans) else: cnt = 0 while(n != 0): ans += n % 10 cnt += 1 n //= 10 ans += (cnt - 1) * 9 print(ans)
You've been in love with Coronavirus-chan for a long time, but you didn't know where she lived until now. And just now you found out that she lives in a faraway place called Naha. You immediately decided to take a vacation and visit Coronavirus-chan. Your vacation lasts exactly x days and that's the exact number of d...
3
import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self...
You are given an array consisting of n integers a_1, a_2, ..., a_n. Initially a_x = 1, all other elements are equal to 0. You have to perform m operations. During the i-th operation, you choose two indices c and d such that l_i ≤ c, d ≤ r_i, and swap a_c and a_d. Calculate the number of indices k such that it is poss...
3
for _ in range(int(input())): n,x,m = map(int,input().split()) l = x;r = x for _ in range(m): w,z = map(int,input().split()) if w <= l <= z or w <= r <= z: if w < l: l = w if z > r: r = z print(r-l+1)
Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome. Gildong lo...
3
def is_palindrome(word, n): for i in range(n): if word[i] != word[n - i - 1]: return False return True def are_palindromes(word_a, word_b, n): for i in range(n): if (word_a[i] != word_b[n - i - 1]): return False return True result = 0 t, n = map(int, input()....
You have n gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The i-th gift consists of a_i candies and b_i oranges. During one move, you can choose some gift 1 ≤ i ≤ n and do one of the following operations: * eat exactly...
3
t = int(input()) for _ in range(t): n = int(input()) a = [int(x) for x in input().split()] b = [int(x) for x in input().split()] ans = 0 for i in range(n): ans += max(a[i] - min(a), b[i] - min(b)) print(ans)
You are given n segments on a number line; each endpoint of every segment has integer coordinates. Some segments can degenerate to points. Segments can intersect with each other, be nested in each other or even coincide. The intersection of a sequence of segments is such a maximal set of points (not necesserily having...
3
n = int(input()) s = [list(map(int, input().split())) for i in range(n)] #print(s) a, b = 0, 100000000000000 for i in s: a = max(a, i[0]) b = min(b, i[1]) ans = 1000000000000 i2, i3 = -1, -1 len1 = 1000000000000000 len2 = 1000000000000000 #print(s) for i in range(n): if s[i][0] == a: if len1 > s[i][...
There are N cities on a number line. The i-th city is located at coordinate x_i. Your objective is to visit all these cities at least once. In order to do so, you will first set a positive integer D. Then, you will depart from coordinate X and perform Move 1 and Move 2 below, as many times as you like: * Move 1: tr...
3
N, X = map(int, input().split()) x = list(map(int, input().split())) ans = abs(x[0]-X) import fractions for i in range(1,N): ans = fractions.gcd(abs(x[i]-X),ans) print(ans)
You are given integers N and K. Find the number of triples (a,b,c) of positive integers not greater than N such that a+b,b+c and c+a are all multiples of K. The order of a,b,c does matter, and some of them can be the same. Constraints * 1 \leq N,K \leq 2\times 10^5 * N and K are integers. Input Input is given from ...
3
n,k=map(int,input().split()) print((n//k)**3 if k%2==1 else (n//k)**3+((n+k//2)//k)**3)
Polycarp urgently needs a shovel! He comes to the shop and chooses an appropriate one. The shovel that Policarp chooses is sold for k burles. Assume that there is an unlimited number of such shovels in the shop. In his pocket Polycarp has an unlimited number of "10-burle coins" and exactly one coin of r burles (1 ≤ r ...
1
ent = raw_input() preco,cent = map(int,ent.split()) soma = preco quant = 1 while True: if soma%10 != 0 and soma%10 != cent: quant +=1 soma += preco else: break print quant
Today's morning was exceptionally snowy. Meshanya decided to go outside and noticed a huge snowball rolling down the mountain! Luckily, there are two stones on that mountain. Initially, snowball is at height h and it has weight w. Each second the following sequence of events happens: snowball's weights increases by i,...
3
w, h = map(int, input().split()) a, b = map(int, input().split()) c, d = map(int, input().split()) nw = w for i in range(h, -1, -1): nw += i if i == b: nw -= a if i == d: nw -= c nw = max(0, nw) print(nw)
Orac is studying number theory, and he is interested in the properties of divisors. For two positive integers a and b, a is a divisor of b if and only if there exists an integer c, such that a⋅ c=b. For n ≥ 2, we will denote as f(n) the smallest positive divisor of n, except 1. For example, f(7)=7,f(10)=2,f(35)=5. ...
3
cases = int(input()) for i in range(cases): n,k = [int(p) for p in input().split()] divs = 0 if n % 2 == 0: print(n+k*2) else: for j in range(3,1001): if n % j == 0: divs += 1 n = n+j break if divs > 0: prin...
Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw. The first player wrote number a, the second player wrote number b. How many ways ...
1
a,b=map(int,raw_input().split()) A,B,C=[0,0,0] for i in range(1,7): d=abs(a-i) v=abs(b-i) if d>v: A +=1 elif d<v: C +=1 else: B+=1 print C,B,A
Despite his bad reputation, Captain Flint is a friendly person (at least, friendly to animals). Now Captain Flint is searching worthy sailors to join his new crew (solely for peaceful purposes). A sailor is considered as worthy if he can solve Flint's task. Recently, out of blue Captain Flint has been interested in ma...
3
t = int(input()) for i in range(t): n = int(input()) if n > 30: print("YES") if n == 36: print(5 , 6 , 10 ,15) elif n == 40: print(6 , 9 , 10 , 15) elif n == 44: print(6 , 7 , 10 , 21) else: print(6 , 10 , 14 , (n-30)) e...
Ksusha the Squirrel is standing at the beginning of a straight road, divided into n sectors. The sectors are numbered 1 to n, from left to right. Initially, Ksusha stands in sector 1. Ksusha wants to walk to the end of the road, that is, get to sector n. Unfortunately, there are some rocks on the road. We know that K...
3
n , k = map(int,input().split()) l = input() h = [] count1 = 0 for i in l: if i=="#": count1 += 1 h.append(count1) elif i==".": count1 = 0 h.append(count1) if max(h)>=k: print("NO") elif max(h)<k or len(h)==0: print("YES")
Ehab loves number theory, but for some reason he hates the number x. Given an array a, find the length of its longest subarray such that the sum of its elements isn't divisible by x, or determine that such subarray doesn't exist. An array a is a subarray of an array b if a can be obtained from b by deletion of several...
3
#!/usr/bin/python3 # Codeforces - Round 628 # Problem B - CopyCopyCopyCopyCopy # Utilility Functions def read_int(): n = int(input()) return n def read_ints(): ints = [int(x) for x in input().split(" ")] return ints # Main t = read_int() for i in range(t): n = read_int() a = read_ints() print (len(set(...
Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashta...
3
n=int(input()) A=[input() for i in range(n)] #print(A) for i in range(n-1,0,-1): if A[i]<A[i-1]: p=0 while p<len(A[i]) and A[i-1][p]<=A[i][p]: p+=1 A[i-1]=A[i-1][:p] print('\n'.join(A))
A new e-mail service "Berlandesk" is going to be opened in Berland in the near future. The site administration wants to launch their project as soon as possible, that's why they ask you to help. You're suggested to implement the prototype of site registration system. The system should work on the following principle. ...
3
compare = {} for i in range(int(input())): string = input() if string not in compare: print("OK") compare[string]=1 else: print(string+str(compare[string])) compare[string] += 1
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: * Tetrahedron. Tetrahedron has 4 triangular faces. * Cube. Cube has 6 square faces. * Octahedron. Octahedron has 8 triangular faces. * Dodecahedron. Dodecahedron has 12 pentagonal faces. *...
3
n = int(input()) faces = { 'T': 4, 'C': 6, 'O': 8, 'D': 12, 'I': 20 } print(sum(faces[input()[0]] for _ in range(n)))
The city park of IT City contains n east to west paths and n north to south paths. Each east to west path crosses each north to south path, so there are n2 intersections. The city funded purchase of five benches. To make it seems that there are many benches it was decided to place them on as many paths as possible. Ob...
3
import math n=int(input()) v=math.factorial(n)//(math.factorial(n-5)*120) print(v*v*120)
Gennady owns a small hotel in the countryside where he lives a peaceful life. He loves to take long walks, watch sunsets and play cards with tourists staying in his hotel. His favorite game is called "Mau-Mau". To play Mau-Mau, you need a pack of 52 cards. Each card has a suit (Diamonds — D, Clubs — C, Spades — S, or ...
3
fc = input().strip() cards = list(filter(lambda x: x[1]==fc[1] or x[0]==fc[0], input().strip().split())) if len(cards) > 0: print("YES") else: print("NO")
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi). They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan consider...
1
#!/usr/bin/python import os import sys import itertools def solve(f): n = f.read_int() xl = {} yl = {} pl = {} for i in xrange(n): x, y = f.read_long_list() xl[x] = xl.get(x, 0) + 1 yl[y] = yl.get(y, 0) + 1 pl[(x,y)] = pl.get((x,y), 0) + 1 c = 0 for i in ...
A + B is often used as an example of the easiest problem possible to show some contest platform. However, some scientists have observed that sometimes this problem is not so easy to get accepted. Want to try? Input The input contains two integers a and b (0 ≤ a, b ≤ 103), separated by a single space. Output Output ...
1
p = map(int, raw_input().split()) result = p[0]+p[1] print result
Bob loves everything sweet. His favorite chocolate bar consists of pieces, each piece may contain a nut. Bob wants to break the bar of chocolate into multiple pieces so that each part would contain exactly one nut and any break line goes between two adjacent pieces. You are asked to calculate the number of ways he can...
3
import math l1 = int(input()) l2 = input().split() l2 = [int(i) for i in l2] r=1; x=[] for i in range (l1): if(l2[i]==1): x.append(i); if(x.__len__()==0): print(0); else: for i in range(1, x.__len__()): r = r * (x[i]-x[i-1]); print(r);
You are given an array a consisting of n integers numbered from 1 to n. Let's define the k-amazing number of the array as the minimum number that occurs in all of the subsegments of the array having length k (recall that a subsegment of a of length k is a contiguous part of a containing exactly k elements). If there i...
3
for _ in range(int(input())): n=int(input()) arr=list(map(int,input().split())) arr=[0]+arr d=dict() dp=[0]*(n+1) dp1=[0]*(n+1) ans=[-1]*(n+1) for j in range(1,n+1): i=arr[j] dp[i]=max(dp[i],j-dp1[i]) dp1[i]=j for x in range(1,n+1): dp[x]=max(dp[x],n-dp1[x]+1) i=dp...
There are n points on a plane. The i-th point has coordinates (x_i, y_i). You have two horizontal platforms, both of length k. Each platform can be placed anywhere on a plane but it should be placed horizontally (on the same y-coordinate) and have integer borders. If the left border of the platform is (x, y) then the r...
3
import bisect from collections import deque from sys import stdin tt = int(stdin.readline()) for loop in range(tt): n,k = map(int,stdin.readline().split()) x = list(map(int,stdin.readline().split())) y = list(map(int,stdin.readline().split())) x.sort() unAB = deque([]) nmax = 0 ans = 0 ...
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr...
3
a=input() b=input() a=a.upper() b=b.upper() flag=0 for i , j in zip(a,b): if i==j: continue if i>j: flag=1 break else: flag=-1 break print(flag)
On some day in January 2018, Takaki is writing a document. The document has a column where the current date is written in `yyyy/mm/dd` format. For example, January 23, 2018 should be written as `2018/01/23`. After finishing the document, she noticed that she had mistakenly wrote `2017` at the beginning of the date col...
3
st = input() print("2018" + st[4:])
You are given a special jigsaw puzzle consisting of n⋅ m identical pieces. Every piece has three tabs and one blank, as pictured below. <image> The jigsaw puzzle is considered solved if the following conditions hold: 1. The pieces are arranged into a grid with n rows and m columns. 2. For any two pieces that sh...
3
t = int(input()) for i in range(t): a, b = map(int, input().split()) if a == 1 or b == 1: print("YES") continue if a > 2 or b > 2: print("NO") else: print('YES')
International Women's Day is coming soon! Polycarp is preparing for the holiday. There are n candy boxes in the shop for sale. The i-th box contains d_i candies. Polycarp wants to prepare the maximum number of gifts for k girls. Each gift will consist of exactly two boxes. The girls should be able to share each gift ...
3
from collections import Counter n, k = (int(i) for i in input().split()) candies = Counter((int(i) % k for i in input().split())) pairs = (candies[0] // 2) * 2 for i in range(1, k): j = k - i pairs += min(candies[i], candies[j]) if k & 1 == 0: if candies[k // 2] & 1: pairs -= 1 print(pairs)
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition. Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character...
3
embosser = 'abcdefghijklmnopqrstuvwxyz' pointer = 'a' counter , diff1 , diff2 = 0 , 0 , 0 inpt = input() for x in inpt: diff1 = abs(embosser.index(x) - embosser.index(pointer)) diff2 = 26 - diff1 if diff1 > diff2: counter += diff2 else : counter += diff1 pointer = x print(counter)
Today is August 24, one of the five Product Days in a year. A date m-d (m is the month, d is the date) is called a Product Day when d is a two-digit number, and all of the following conditions are satisfied (here d_{10} is the tens digit of the day and d_1 is the ones digit of the day): * d_1 \geq 2 * d_{10} \geq 2 *...
3
n,m=map(int,input().split()) ans=0 for i in range(m): if i+1 >= 22: a=(i+1)//10 b=(i+1)%10 if b >= 2 and a*b<=n: ans = ans +1 print(ans)
Vova, the Ultimate Thule new shaman, wants to build a pipeline. As there are exactly n houses in Ultimate Thule, Vova wants the city to have exactly n pipes, each such pipe should be connected to the water supply. A pipe can be connected to the water supply if there's water flowing out of it. Initially Vova has only on...
3
n, k = map(int, input().split()) def prod(n): if n%2: return n*((n+1)//2) else: return (n//2)*(n+1) def total_count(n, k): if k >= n: return (0, 0, 1) else: count = 0 l = 1; r = k s = prod(k) while l <= r: mid = (l+r)//2 if n > s - prod(mid) + mid: r = mid-1 else: l = mid+1 n = n...
You are given two integers a and b. In one move, you can choose some integer k from 1 to 10 and add it to a or subtract it from a. In other words, you choose an integer k ∈ [1; 10] and perform a := a + k or a := a - k. You may use different values of k in different moves. Your task is to find the minimum number of mo...
3
t = int(input()) for _ in range(t): a,b = map(int,input().split()) if a == b: print(0) else: if a > b: a,b = b,a temp = b-a if temp%10 == 0: print(temp//10) else: print(temp//10 + 1)
Gerald has n younger brothers and their number happens to be even. One day he bought n2 candy bags. One bag has one candy, one bag has two candies, one bag has three candies and so on. In fact, for each integer k from 1 to n2 he has exactly one bag with k candies. Help him give n bags of candies to each brother so th...
3
# -*- coding: utf-8 -*- """ Created on Fri Mar 6 20:45:22 2020 @author: Lenovo """ #https://codeforces.com/problemset/problem/334/A def candy_bags(): brothers = int(input()) bags = [i for i in range(1,(brothers**2)+1)] all_brothers = [[] for i in range(brothers)] for i in range(len(all_...
You are given a sequence a consisting of n integers. You may partition this sequence into two sequences b and c in such a way that every element belongs exactly to one of these sequences. Let B be the sum of elements belonging to b, and C be the sum of elements belonging to c (if some of these sequences is empty, the...
3
x=int(input()) y=[int(n) for n in input().split()] m=k=0 for n in range(x): if y[n]>=0: # print(y[n]) m+=y[n] else: k+=y[n] # print(y[n]) print(m-k)
You are given an array a_1, a_2, ..., a_n where all a_i are integers and greater than 0. In one operation, you can choose two different indices i and j (1 ≤ i, j ≤ n). If gcd(a_i, a_j) is equal to the minimum element of the whole array a, you can swap a_i and a_j. gcd(x, y) denotes the [greatest common divisor (GCD)](...
3
t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) min_element = min(a) bckt = [] for i in range(n): if a[i]%min_element == 0: bckt.append(a[i]) a[i] = -1 bckt.sort(reverse=True) for i in range(n): ...
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy...
3
s =[0, 0, 0] for _ in range(int(input())): v = [int(z) for z in input().split()] s[0] += v[0] s[1] += v[1] s[2] += v[2] print('YES' if (s[0]==0 and s[1]==0 and s[2]==0) else 'NO')
Vasya is an active Internet user. One day he came across an Internet resource he liked, so he wrote its address in the notebook. We know that the address of the written resource has format: <protocol>://<domain>.ru[/<context>] where: * <protocol> can equal either "http" (without the quotes) or "ftp" (without the q...
3
s = input() s1 = '' index = 0 th = s.find('http') tp = s.find('ftp') if th != -1 and tp != -1: if th < tp: s1 += 'http'+'://' index += 4 elif th > tp: s1 += 'ftp' +'://' index += 3 elif th != -1 and tp == -1: s1 += 'http'+'://' index += 4 elif th == -1 and tp != -1: s...
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
hold=[] moves=0 for ___ in range(5): hold.append([int(a) for a in input().split()]) for matrix in hold: if 1 in matrix: if matrix[2]!=1: a = matrix.index(1) if a-2>0: moves+=a-2 else: moves+=2-a matrix.remove(1) matrix.insert(2,1) if hold.index(matrix)!=2: ...
2N players are running a competitive table tennis training on N tables numbered from 1 to N. The training consists of rounds. In each round, the players form N pairs, one pair per table. In each pair, competitors play a match against each other. As a result, one of them wins and the other one loses. The winner of the...
3
N, A, B = map(int, input().split()) if (A+B)%2 == 0: print((B-A)//2) else: print(min(A-1, N-B)+1+(B-A-1)//2)
We have a string s consisting of lowercase English letters. Snuke is partitioning s into some number of non-empty substrings. Let the subtrings obtained be s_1, s_2, ..., s_N from left to right. (Here, s = s_1 + s_2 + ... + s_N holds.) Snuke wants to satisfy the following condition: * For each i (1 \leq i \leq N), it ...
3
s = input() n = len(s) cA = ord('a') P = {0: 0} cur = 0 dp = [10**18]*(n+1) dp[-1] = 0 for i in range(n): c = ord(s[i]) - cA dp[i] = dp[i-1] + 1 cur ^= 1 << c # even if cur in P: dp[i] = min(dp[i], P[cur] + 1) # odd for k in range(26): need = cur ^ (1 << k) if need ...
"Night gathers, and now my watch begins. It shall not end until my death. I shall take no wife, hold no lands, father no children. I shall wear no crowns and win no glory. I shall live and die at my post. I am the sword in the darkness. I am the watcher on the walls. I am the shield that guards the realms of men. I ple...
1
n=input() arr=map(int,raw_input().split()) mini,maxi,minc,maxc=min(arr),max(arr),0,0 for i in range(n): if(arr[i]==mini): minc+=1 if(arr[i]==maxi): maxc+=1 if(n-minc-maxc>=0): print n-minc-maxc else: print 0
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr...
3
word1 = input() word2 = input() word1 = word1.lower() word2 = word2.lower() if word1 == word2: print(0) elif word1 < word2: print(-1) else: print(1)
Alice got many presents these days. So she decided to pack them into boxes and send them to her friends. There are n kinds of presents. Presents of one kind are identical (i.e. there is no way to distinguish two gifts of the same kind). Presents of different kinds are different (i.e. that is, two gifts of different ki...
3
n, m = map(int,input().split()) print (pow((2 ** m) - 1, n, 1000000007))
Young Timofey has a birthday today! He got kit of n cubes as a birthday present from his parents. Every cube has a number ai, which is written on it. Timofey put all the cubes in a row and went to unpack other presents. In this time, Timofey's elder brother, Dima reordered the cubes using the following rule. Suppose t...
3
import math n = int(input()) arr = [int(inp) for inp in input().split()] last = int(math.ceil(n / 2)) for i in range(0, last): if i % 2 == 0: arr[i], arr[n - i - 1] = arr[n - i - 1], arr[i] for num in arr: print(num, end=' ') print('')
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
import sys data = sys.stdin.readlines() n = int(data[0]) if len([int(x) for x in data[1].split() if int(x) != 0]) == 0: sys.stdout.write("EASY") else: sys.stdout.write("HARD")
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official language...
3
n,m = map(int,input().split(' ')) b = [-1 for i in range(m + 1)] ans = 0 for i in range(n): a = list(map(int,input().split(' '))) a = a[1:] if len(a) == 0: ans += 1 before = [] for x in a: if b[x] != -1: before.append(b[x]) else: b[x] = i for...
A dice is a cube, its faces contain distinct integers from 1 to 6 as black points. The sum of numbers at the opposite dice faces always equals 7. Please note that there are only two dice (these dices are mirror of each other) that satisfy the given constraints (both of them are shown on the picture on the left). <imag...
3
n=int(input()) x=int(input()) y=7-x f=0 for i in range(n): a,b=map(int,input().split()) if(a==x or a==y): f=1 break elif(b==x or b==y): f=1 break if(f==1): print('NO') else: print('YES')
There are n emotes in very popular digital collectible card game (the game is pretty famous so we won't say its name). The i-th emote increases the opponent's happiness by a_i units (we all know that emotes in this game are used to make opponents happy). You have time to use some emotes only m times. You are allowed t...
3
n, m, k = map(int, input().split()) a = list(map(int, input().split())) a.sort(reverse=True) print((m // (k + 1)) * (a[0] * k + a[1]) + m % (k + 1) * a[0])
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()) tiempo = map(int, raw_input().split()) lenbest = 0 izq=N der=N-1 suma=0 while izq>=0: while suma<=T: lenbest = max(lenbest, der-izq+1) izq-=1 if izq==-1: print lenbest exit(0) suma += tiempo[izq] while suma>T: suma -= tiempo[der] der -= 1
Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus. She has n friends who are also grannies (Maria is not included in this number). The i-th granny is ready to attend the ceremony, provided that at the time of her appearance in t...
3
t=int(input()) l=[] for i in range(t): n=int(input()) a=[] a=[int(x) for x in input().split()] d=1 a.sort() for k in range(n-1,-1,-1): people=k+1 if a[k]<=people: d=k+2 break l.append(d) for x in l: print(x)
Recently, Mike was very busy with studying for exams and contests. Now he is going to chill a bit by doing some sight seeing in the city. City consists of n intersections numbered from 1 to n. Mike starts walking from his house located at the intersection number 1 and goes along some sequence of intersections. Walking...
3
###### ### ####### ####### ## # ##### ### ##### # # # # # # # # # # # # # ### # # # # # # # # # # # # # ### ###### ######### # # # # # # ...
You are given N positive integers a_1, a_2, ..., a_N. For a non-negative integer m, let f(m) = (m\ mod\ a_1) + (m\ mod\ a_2) + ... + (m\ mod\ a_N). Here, X\ mod\ Y denotes the remainder of the division of X by Y. Find the maximum value of f. Constraints * All values in input are integers. * 2 \leq N \leq 3000 * 2 ...
3
n = int(input()) lst = list(map(int, input().split())) print(sum(lst) - n)
Write a program which manipulates a sequence A = {a0, a1, . . . , an-1} with the following operations: * find(s, t): report the minimum element in as, as+1, . . . ,at. * update(i, x): change ai to x. Note that the initial values of ai (i = 0, 1, . . . , n−1) are 231-1. Constraints * 1 ≤ n ≤ 100000 * 1 ≤ q ≤ 10000...
3
class SegmentTree: def __init__(self, n): self.n = n self.T = T = [2**31 - 1 for _ in range(2*n-1)] def update(self, i, x): i += self.n - 1 self.T[i] = x while(i > 0): i = (i - 1) // 2 self.T[i] = min(self.T[i*2+1], self.T[i*2+2]) ...
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 k in xrange(t): i = 0 while i < n - 1: if s[i] == 'B' and s[i + 1] == 'G': s[i], s[i + 1] = s[i + 1], s[i] i += 1 i += 1 print ''.join(s)
A bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not. The teacher gave Dmitry's class a very strange task — she asked every student...
1
'''input 6 )(())( ''' from sys import stdin,stdout I = lambda : map(int,stdin.readline().split()) import bisect # t = input() # for _ in range(t): def notproper(s,x,y): # print s,x,y if x == 0: s = s[x:y+1] else: s = s[x+1:y+1] o,c = 0,0 for i in s: if i == '(': o+=1 else: c+=1 if c>o: # pri...