problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
Patrick has just finished writing a message to his sweetheart Stacey when he noticed that the message didn't look fancy. Patrick was nervous while writing the message, so some of the letters there were lowercase and some of them were uppercase. Patrick believes that a message is fancy if any uppercase letter stands to...
3
s = input() n = len(s) d = [[0]*2 for _ in range(0,n+1)] if(s[0].isupper()): d[0][0] = 0 d[0][1] = 1 else: d[0][0] = 1 d[0][1] = 0 for i in range(1,n): if(s[i].isupper()): d[i][0] = d[i-1][0] d[i][1] = min(d[i-1][0],d[i-1][1]) + 1 else: d[i][0] = d[i-1][0] + 1 ...
You are given two segments [l_1; r_1] and [l_2; r_2] on the x-axis. It is guaranteed that l_1 < r_1 and l_2 < r_2. Segments may intersect, overlap or even coincide with each other. <image> The example of two segments on the x-axis. Your problem is to find two integers a and b such that l_1 ≤ a ≤ r_1, l_2 ≤ b ≤ r_2 an...
3
q = int(input()) for _ in range(q): l1, r1, l2, r2 = [int(x) for x in input().split()] if l1 < l2: print(l1, r2) else: print(r1, l2)
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()) a = [int(x) for x in input().split(' ')] if len(a) == 1: print(0) else: a.sort() in1 = a[len(a)-2] - a[0] in2 = a[len(a)-1] - a[1] print(min(in1, in2))
Polycarp has interviewed Oleg and has written the interview down without punctuation marks and spaces to save time. Thus, the interview is now a string s consisting of n lowercase English letters. There is a filler word ogo in Oleg's speech. All words that can be obtained from ogo by adding go several times to the end...
3
import re num = input() x = input() y = re.sub('o(go)+','***',x) print(y)
It's a walking tour day in SIS.Winter, so t groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another. Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P": * "A" corresponds to an angry...
3
a = int(input()) for i in range(a): z = 0 d = 0 l = int(input()) s = input() while s != s.replace('AP', 'AA'): s = s.replace('AP', 'AA') z+=1 print(z)
Masha has n types of tiles of size 2 × 2. Each cell of the tile contains one integer. Masha has an infinite number of tiles of each type. Masha decides to construct the square of size m × m consisting of the given tiles. This square also has to be a symmetric with respect to the main diagonal matrix, and each cell of ...
3
t=int(input()) for _ in range(t): n,m=map(int,input().split()) board=[[list(map(int,input().split())),list(map(int,input().split()))] for _ in range(n)] if m%2==1: print('NO') continue for i in range(n): a11,a12=board[i][0] a21,a22=board[i][1] if a12==a21: ...
Ann has recently started commuting by subway. We know that a one ride subway ticket costs a rubles. Besides, Ann found out that she can buy a special ticket for m rides (she can buy it several times). It costs b rubles. Ann did the math; she will need to use subway n times. Help Ann, tell her what is the minimum sum of...
3
import math n, m, a, b = map(int, input().split()) print(min(n*a,min((math.ceil(n/m)*b,(math.floor(n/m)*b + (n%m)*a)))))
During the quarantine, Sicromoft has more free time to create the new functions in "Celex-2021". The developers made a new function GAZ-GIZ, which infinitely fills an infinite table to the right and down from the upper left corner as follows: <image> The cell with coordinates (x, y) is at the intersection of x-th row ...
3
# from math import factorial as fac from collections import defaultdict # from copy import deepcopy import sys, math f = None try: f = open('q1.input', 'r') except IOError: f = sys.stdin if 'xrange' in dir(__builtins__): range = xrange # print(f.readline()) # sys.setrecursionlimit(10**5) def print_case_iterable...
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution....
3
no = int(input()) a = [] for i in range(no): flag = [] flag = list(map(int,input().split())) a.append(flag) f = 0 for i in range(no): e = a[i] if e[0]==e[1]==e[2]==1: f = f+1 elif e[0]==e[1]==1 or e[1]==e[2]==1 or e[2]==e[0]==1: f = f+1 print(f)
There is a graph of n rows and 10^6 + 2 columns, where rows are numbered from 1 to n and columns from 0 to 10^6 + 1: <image> Let's denote the node in the row i and column j by (i, j). Initially for each i the i-th row has exactly one obstacle — at node (i, a_i). You want to move some obstacles so that you can reach ...
3
t = int(input()) for _ in range(t): n,u,v = map(int,input().split()) l = list(map(int,input().split())) max_diff = 0 for i in range(n-1): if abs(l[i] - l[i+1]) > max_diff: max_diff = abs(l[i] - l[i+1]) if max_diff >= 2: print(0) elif max_diff == 1: print(min(u...
Sasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table M with n rows and n columns such that M_{ij}=a_i ⋅ a_j where a_1, ..., a_n is some sequence of positive integers. Of course, the girl decided to take it to school with her. But while she was having lunch, hoolig...
3
n=int(input()) l=[] q=[] w=[] for i in range(0,n): p=input().rstrip().split(' ') l.append(p) x=list(p) x.sort(key=int) q.append(int(x[1])) #print(l) A=min(q); V=q.index(A) #A=int(q[0]) for i in range(1,A+1): w=[0]*n; w[V]=i; for j in range(0,len(l[V])): if j!=V and int(l[V][j])!=...
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
w = int(input()) if w % 2 == 0 and w != 2 and w>0: print('YES') else: print('NO')
Step up and down Kazuki, commonly known as Kerr, who attends JAG University, was invited by your friend this summer to participate in the ICPC (International Collegiate Potchari Contest). ICPC is a sports contest and requires a high degree of athletic ability. However, Mr. Kerr was always in front of the computer, and...
1
while True: n = int(raw_input()) if n == 0: break s = raw_input().split() state = [False, False] counter = 0 stand = False for step in s: if step == "lu": state[0] = True elif step == "ru": state[1] = True elif step == "ld": state[0] = False elif step == "rd": state...
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()) num=0 for i in range(n): p,q=[int(a) for a in input().split()] if q-p>=2: num+=1 print(num)
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob. Right now, Limak and Bob weigh a and b respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight. Limak eats a lot and his weight is tripled after every year, while Bob's weight...
3
import copy from sys import stdin, stdout def parser(fileName): a, b = map(int, stdin.readline().rstrip().split()) # c = stdin.readline() # return a, b, c return a, b def solution(A, B): A_temp = copy.copy(A) B_temp = copy.copy(B) sol = None for i in range(1,10): A_temp *= 3 ...
Alice likes snow a lot! Unfortunately, this year's winter is already over, and she can't expect to have any more of it. Bob has thus bought her a gift — a large snow maker. He plans to make some amount of snow every day. On day i he will make a pile of snow of volume Vi and put it in her garden. Each day, every pile w...
3
import heapq from bisect import bisect_left, bisect_right from collections import Counter from collections import OrderedDict from collections import deque from itertools import accumulate, product import math R = lambda: map(int, input().split()) n = int(input()) snows = list(R()) melts = list(R()) acc = list(accum...
Theatre Square in the capital city of Berland has a rectangular shape with the size n × m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a × a. What is the least number of flagstones needed to pave the Square? It'...
1
import string #num_test = int(raw_input()) #for i in range(0, num_test): data = raw_input().split(' ') n = int(data[0]) m = int(data[1]) a = int(data[2]) if a == 1: print n*m else: if (n <= a and m >= a): if m == a: print 1 else: print m / a + 1 elif (m <= a and ...
A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all n squad soldiers to line up on the parade ground. By the military charter the soldiers should stand in the order of non-increasing of their h...
3
n = int(input()) lst = [int(s) for s in input().split()] maxH = max(lst) minH = min(lst) iMax = lst.index(maxH) iMin = n - 1 - lst[::-1].index(minH) res = iMax+n-1-iMin if iMax > iMin: res -= 1 print(res)
You are given two arrays a and b, both of length n. All elements of both arrays are from 0 to n-1. You can reorder elements of the array b (if you want, you may leave the order of elements as it is). After that, let array c be the array of length n, the i-th element of this array is c_i = (a_i + b_i) \% n, where x \% ...
1
#!/usr/bin/env python from __future__ import division, print_function # Testing code by c1729 import os import random import sys from io import BytesIO, IOBase if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip else: _str = st...
Amr is a young coder who likes music a lot. He always wanted to learn how to play music but he was busy coding so he got an idea. Amr has n instruments, it takes ai days to learn i-th instrument. Being busy, Amr dedicated k days to learn how to play the maximum possible number of instruments. Amr asked for your help ...
1
def instruments_to_learn(instruments, days): ind_day_tuples = sorted(enumerate(instruments), key=lambda x: x[1]) to_learn = [] for ind, day_req in ind_day_tuples: if day_req > days: break days -= day_req to_learn.append(ind + 1) return t...
A permutation is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as pi. We'll call number n the size of permutation p1, p2, ..., pn. Nickolas adores permutations. He likes some permutations more than the o...
3
def ppp(n): l= [] d= 1 while d< n: l.append(d+1) l.append(d) d = d+2 return l n= int(input()) if n%2 != 0: print(-1) else: t = ppp(n) print(*t)
A word or a sentence in some language is called a pangram if all the characters of the alphabet of this language appear in it at least once. Pangrams are often used to demonstrate fonts in printing or test the output devices. You are given a string consisting of lowercase and uppercase Latin letters. Check whether thi...
3
n = int(input()) if {*input().lower()} == {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}: print('YES') else: print('NO')
We have N+1 integers: 10^{100}, 10^{100}+1, ..., 10^{100}+N. We will choose K or more of these integers. Find the number of possible values of the sum of the chosen numbers, modulo (10^9+7). Constraints * 1 \leq N \leq 2\times 10^5 * 1 \leq K \leq N+1 * All values in input are integers. Input Input is given from S...
3
N,K=map(int,input().split()) r=0 md=10**9+7 for k in range(K,N+2): r += k*(N-k+1)+1 print(r%md)
You have a plate and you want to add some gilding to it. The plate is a rectangle that we split into w× h cells. There should be k gilded rings, the first one should go along the edge of the plate, the second one — 2 cells away from the edge and so on. Each ring has a width of 1 cell. Formally, the i-th of these rings ...
3
w, h, k=map(int,input().split()) s=(w+h)*2-4 k-=1 while k!=0: h -= 4 w -= 4 s+=(w+h)*2-4 k-=1 print(s)
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits. Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has on...
3
def distinct(i): d = [0]*10 while i > 0: d[int(i%10)] += 1 i = int(i/10) for i in range(10): if d[i] > 1: return False return True y = int(input()) for i in range(y+1, 9013): if distinct(i): print(i) break
You received a notebook which is called Death Note. This notebook has infinite number of pages. A rule is written on the last page (huh) of this notebook. It says: "You have to write names in this notebook during n consecutive days. During the i-th day you have to write exactly a_i names.". You got scared (of course yo...
3
import sys input = sys.stdin.readline out = sys.stdout n, m = map(int,input().split()) a = list(map(int,input().split())) current = 0 for i in range(n): k = 0 if current != 0: z = m - current current = 0 k += 1 a[i] -= z if a[i] != 0: k += a[i] // m ...
You are given a graph consisting of n vertices and m edges. It is not guaranteed that the given graph is connected. Some edges are already directed and you can't change their direction. Other edges are undirected and you have to choose some direction for all these edges. You have to direct undirected edges in such a w...
3
from math import * from collections import * from bisect import * import sys input=sys.stdin.readline t=int(input()) def fa(a): indeg=[0 for i in range(n+1)] r=[] qu=deque([]) for i in range(1,n+1): for j in gr[i]: indeg[j]+=1 for i in range(1,n+1): if(indeg[i]==0): ...
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point x(x > 0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order ...
1
# -*-coding:utf-8 -*- x=input() i=0 while x>0: x-=5 i+=1 print i
Vasya and Petya have invented a new game. Vasya takes a stripe consisting of 1 × n square and paints the squares black and white. After that Petya can start moves — during a move he may choose any two neighboring squares of one color and repaint these two squares any way he wants, perhaps in different colors. Petya can...
1
n = int(raw_input()) s, a, b = raw_input(), 0, 0 for i in xrange(n): if i%2 == int(s[i]): a = a+1 else: b=b+1 print min(a,b)
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits. Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has on...
3
from collections import deque import math n = int(input()) #print(n//1000) #print((n%1000)//100) #print((n%100)//10) #print(n%10) while(True): n+=1 if (n//1000)!=((n%1000)//100) and (n//1000)!=(n%100)//10 and (n//1000)!=(n%10): if ((n%1000)//100)!=(n%100)//10 and ((n%1000)//100)!=(n%10): if (...
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). For a positive integer n, we call a...
3
def con(v): l = [] for j in v: j = str(j) l.append(j) return(" ".join(l)) t = int(input()) i = 0 while i < t: n = int(input()) k = [] for s in range(1, n+1): k.append(s) print(con(k)) i += 1
Bob is playing a game named "Walk on Matrix". In this game, player is given an n × m matrix A=(a_{i,j}), i.e. the element in the i-th row in the j-th column is a_{i,j}. Initially, player is located at position (1,1) with score a_{1,1}. To reach the goal, position (n,m), player can move right or down, i.e. move from ...
3
import io import os from collections import Counter, defaultdict, deque def solve(K,): if K == 0: return "1 1\n" + str(0) def bob(a): n = len(a) m = len(a[0]) dp = [[0 for j in range(m + 1)] for i in range(n + 1)] dp[0][1] = a[0][0] for i in range(1, n + 1): ...
Being tired of participating in too many Codeforces rounds, Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other. He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits ...
3
t = int(input()) while(t > 0): t -= 1 x,y,a,b = input().split(' ') x,y,a,b = int(x), int(y), int(a), int(b) if((y-x)%(a+b) == 0): print((y-x)//(a+b)) else: print(-1)
So, the New Year holidays are over. Santa Claus and his colleagues can take a rest and have guests at last. When two "New Year and Christmas Men" meet, thear assistants cut out of cardboard the letters from the guest's name and the host's name in honor of this event. Then the hung the letters above the main entrance. O...
3
guest = input() residence_host = input() pile = input() letter = { 'A' : 0, 'B' : 0, 'C' : 0, 'D' : 0, 'E' : 0, 'F' : 0, 'G' : 0, 'H' : 0, 'I' : 0, 'J' : 0, 'K' : 0, 'L' : 0, 'M' : 0, 'N' : 0, 'O' : 0, 'P' : 0, 'Q' : 0, 'R' : 0, 'S' : 0, 'T' : 0, 'U' : 0, 'V' : 0, 'W' : 0, 'X' : 0, 'Y' : 0, 'Z' : 0 } for i in pile : ...
Let's call a list of positive integers a_0, a_1, ..., a_{n-1} a power sequence if there is a positive integer c, so that for every 0 ≤ i ≤ n-1 then a_i = c^i. Given a list of n positive integers a_0, a_1, ..., a_{n-1}, you are allowed to: * Reorder the list (i.e. pick a permutation p of \{0,1,...,n - 1\} and change...
3
from math import ceil MAX = 10e18 n = int(input()) a = list(map(int,input().split())) a.sort() val = ceil(pow(a[n-1],1/(n-1))) ans = MAX # print(val) for i in range(1,val+1): temp = 0 for j in range(len(a)): temp += abs(a[j] - pow(i,j)) # print(temp) ans = min(ans,temp) print(ans)
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
n=int(input()) for i in range(0,n): p=input().rstrip().split(' ') if int(p[0])==1 or int(p[1])==1: print("YES") else: if int(p[0])>=3 or int(p[1]) >= 3: print("NO") else: print("YES")
Pay attention to the non-standard memory limit in this problem. In order to cut off efficient solutions from inefficient ones in this problem, the time limit is rather strict. Prefer to use compiled statically typed languages (e.g. C++). If you use Python, then submit solutions on PyPy. Try to write an efficient solut...
3
# exec(open('test.py').read()) for _ in range(int(input())): n = int(input()) l = list(map(int, input().split())) cnt = [0]*(n+1) for i in range(n): s = l[i] for j in range(i+1,n): s += l[j] if s <= n : cnt[s] += 1 else : break ans = 0 for i in range(n): ans+=cnt[l[i]]>0 print(ans)
Last week, Hamed learned about a new type of equations in his math class called Modular Equations. Lets define i modulo j as the remainder of division of i by j and denote it by <image>. A Modular Equation, as Hamed's teacher described, is an equation of the form <image> in which a and b are two non-negative integers a...
3
a, b = [int(i) for i in input().split()] o = a - b sum = 0 l = 1 if o > 0: for i in range(1, int(o ** 0.5) + l): if o % i == 0: if o // i > b and i > b: sum += 2 if i == o // i: sum -= 1 if (o // i > b and i <= b) or (o // i <= b an...
You are given a string s. Among the different substrings of s, print the K-th lexicographically smallest one. A substring of s is a string obtained by taking out a non-empty contiguous part in s. For example, if s = `ababc`, `a`, `bab` and `ababc` are substrings of s, while `ac`, `z` and an empty string are not. Also,...
3
s=input();print(sorted({s[I//6:I//6+I%6]for I in range(len(s)*6)})[int(input())])
Yaroslav has an array that consists of n integers. In one second Yaroslav can swap two neighboring array elements. Now Yaroslav is wondering if he can obtain an array where any two neighboring elements would be distinct in a finite time. Help Yaroslav. Input The first line contains integer n (1 ≤ n ≤ 100) — the numb...
1
from collections import * n = int(raw_input()) A = map(int, raw_input().split()) C = Counter(A) A = sorted(A,key=lambda k: -C[k]) l = [0]*n l[ ::2] = A[:(n+1)/2] l[1::2] = A[(n+1)/2:] print 'NO' if any(l[i]==l[i+1] for i in xrange(len(l)-1)) else 'YES'
Everybody knows that opposites attract. That is the key principle of the "Perfect Matching" dating agency. The "Perfect Matching" matchmakers have classified each registered customer by his interests and assigned to the i-th client number ti ( - 10 ≤ ti ≤ 10). Of course, one number can be assigned to any number of cust...
3
n = int(input()) l = list(map(int,input().split())) d = {l[i]:0 for i in range(len(l))} ans = 0 for i in range(len(l)): d[l[i]] = d[l[i]] + 1 for i in d: if i > 0 and -i in d: ans = ans + d[i]*d[-i] elif i == 0: ans = ans + int((d[0]*(d[0]-1))/2) print(ans)
You are given n numbers a_1, a_2, …, a_n. Is it possible to arrange them in a circle in such a way that every number is strictly less than the sum of its neighbors? For example, for the array [1, 4, 5, 6, 7, 8], the arrangement on the left is valid, while arrangement on the right is not, as 5≥ 4 + 1 and 8> 1 + 6. <im...
3
n = int(input()) a = sorted(map(int, input().split())) if a[n-1] >= a[n-2] + a[n-3]: print('NO') else: b = a[:n-2] + [a[n-1], a[n-2]] print('YES') print(' '.join(map(str, b)))
X and A are integers between 0 and 9 (inclusive). If X is less than A, print 0; if X is not less than A, print 10. Constraints * 0 \leq X, A \leq 9 * All values in input are integers. Input Input is given from Standard Input in the following format: X A Output If X is less than A, print 0; if X is not less th...
3
x, y = map(int, input().split()) print(10 if x >= y else 0)
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation. The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe...
3
string = str(input()) d = [0, 0 ,0] for i in range(len(string)): if string[i] == '1': d[0] += 1 elif string[i] == '2': d[1] += 1 elif string[i] == '3': d[2] += 1 string = '' for i in range(len(d)): for j in range(d[i]): string += str(i + 1) + '+' print(string[:-1])
Vasya wants to turn on Christmas lights consisting of m bulbs. Initially, all bulbs are turned off. There are n buttons, each of them is connected to some set of bulbs. Vasya can press any of these buttons. When the button is pressed, it turns on all the bulbs it's connected to. Can Vasya light up all the bulbs? If Va...
1
n,m = map(int,raw_input().split()) b=[0 for i in range(m)] for i in range(n): arr= map(int,raw_input().split()) for j in arr[1:]: b[j-1]=1 for i in b: if i==0: print "NO" exit() print "YES"
Takahashi has two positive integers A and B. It is known that A plus B equals N. Find the minimum possible value of "the sum of the digits of A" plus "the sum of the digits of B" (in base 10). Constraints * 2 ≤ N ≤ 10^5 * N is an integer. Input Input is given from Standard Input in the following format: N Outp...
1
def calc(n): ans = 0 while n > 0: ans += n % 10 n /= 10 return ans n = int(raw_input()) mn = 100 for a in range(1, n/2+1): mn = min(mn, calc(a) + calc(n-a)) print mn
Given a permutation p of length n, find its subsequence s_1, s_2, …, s_k of length at least 2 such that: * |s_1-s_2|+|s_2-s_3|+…+|s_{k-1}-s_k| is as big as possible over all subsequences of p with length at least 2. * Among all such subsequences, choose the one whose length, k, is as small as possible. If mul...
3
for _ in range(int(input())): n = int(input()) arr = list(map(int,input().split())) res = [arr[0]] res_len = 2 ans = 0 for i in range(1,n-1): if arr[i+1] > arr[i] and arr[i-1] > arr[i]: res.append(arr[i]) res_len += 1 elif arr[i+1] < arr[i] and arr[i-1] < ...
You are given a string s consisting only of lowercase Latin letters. You can rearrange all letters of this string as you wish. Your task is to obtain a good string by rearranging the letters of the given string or report that it is impossible to do it. Let's call a string good if it is not a palindrome. Palindrome is...
3
from collections import Counter x = int(input()) lst = [] for i in range(x): lst.append(input()) def convert_non_palindrome(s): counts = Counter(s) if len(counts) == 1: return '-1' sorted_s = ''.join([x for x in sorted(s)]) return sorted_s for s in lst: print(convert_non_palindrome(s)...
The only difference between easy and hard versions is constraints. The BerTV channel every day broadcasts one episode of one of the k TV shows. You know the schedule for the next n days: a sequence of integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ k), where a_i is the show, the episode of which will be shown in i-th day. The...
3
for _ in range(int(input())): n,k,d=map(int, input().split()) l=list(map(int, input().split())) s=l[0:d] k=set(s) minn=min(len(k),d) for i in range(1,n-d+1): s.pop(0) s.append(l[i+d-1]) minn=min(len(set(s)),minn) print(minn)
"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
a,b = map(int,input().split()) x = list(map(int,input().split())) c = 0 y = x[b-1] for i in x: if i >= y and i > 0: c += 1 print(c)
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
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**10 mod = 10**9+7 dd = [(-1,0),(0,1),(1,0),(0,-1)] ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(): return [int(x) for x in sys.stdin....
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, ....
1
def m(a, p): m1 = min(a) if a[0] == m1: return sum(p)*m1 else: for i in range(len(a)): if a[i] == m1: break return m(a[:i], p[:i]) + sum(p[i:])*m1 n = int(raw_input()) a = [] p = [] for i in range(n): w = map(int, raw_input().split()) a.append(w[0]...
Santa has n candies and he wants to gift them to k kids. He wants to divide as many candies as possible between all k kids. Santa can't divide one candy into parts but he is allowed to not use some candies at all. Suppose the kid who recieves the minimum number of candies has a candies and the kid who recieves the max...
3
for i in range(int(input())): a,b=[int(x) for x in input().split()] metade = b//2 res = a%b ans=a if (res>metade): ans-=(res-metade) print(ans)
You have array of n numbers a_{1}, a_{2}, …, a_{n}. Rearrange these numbers to satisfy |a_{1} - a_{2}| ≤ |a_{2} - a_{3}| ≤ … ≤ |a_{n-1} - a_{n}|, where |x| denotes absolute value of x. It's always possible to find such rearrangement. Note that all numbers in a are not necessarily different. In other words, some numb...
3
t = int(input()) for _ in range(t): n = int(input()) A = sorted(map(int, input().split())) arr = [] for i in range(n//2): arr.append(A[n-i-1]) arr.append(A[i]) if n % 2 == 1: arr.append(A[n//2]) print(' '.join(map(str, reversed(arr))))
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them. Input The first line contains integ...
3
number_stone = int(input()) string = input() index = 0 count = 0 while index < number_stone: if string[index] == string[index + 1:index + 2]: count += 1 index += 1 print(count)
You are given a rectangular board of M × N squares. Also you are given an unlimited number of standard domino pieces of 2 × 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions: 1. Each domino completely covers two squa...
3
M,N=input().split() M=int(M) N=int(N) if(N%2==M%2==0): print(M*N//2) elif(M%2==N%2==1): print((M*N-1)//2) else: print(M*N//2)
A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive. Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the sa...
1
from sys import exit n, m = map(int, raw_input().split()) free = [1 for i in range(n + 1)] free[0] = 0 adj = [[0 for j in range(n + 1)] for i in range(n + 1)] for _ in range(m): x, y = map(int, raw_input().split()) adj[x][y] = adj[y][x] = 1 for i in range(1, n + 1): if sum(adj[i]) > 2: print -1 ...
We have N boxes, numbered 1 through N. At first, box 1 contains one red ball, and each of the other boxes contains one white ball. Snuke will perform the following M operations, one by one. In the i-th operation, he randomly picks one ball from box x_i, then he puts it into box y_i. Find the number of boxes that may ...
3
N,M = map(int,input().split()) B = [1 for i in range(N)] P = set([1]) for i in range(M): x,y = map(int,input().split()) B[x-1] -= 1 B[y-1] += 1 if x in P: P.add(y) if B[x-1] == 0 and x in P: P.remove(x) print(len(P))
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation. The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe...
3
k=input(); l=k.split("+"); l.sort(); print("+".join(l));
On February 14 Denis decided to give Valentine to Nastya and did not come up with anything better than to draw a huge red heart on the door of the length k (k ≥ 3). Nastya was very confused by this present, so she decided to break the door, throwing it on the mountains. Mountains are described by a sequence of heights...
3
#B t = int(input()) while t: n,k = map(int,input().split()) a = list(map(int,input().split())) b =[0 for i in range(n)] c = 0 m = 0 l = 0 for i in range(2,n): if a[i-1]>a[i] and a[i-1]>a[i-2]: b[i-1] = 1 c += 1 else: b[i] = 0 if i>=...
Given three integers x, m and n. Evaluate (1 + x + x^ 2 + .. + x^ m) (mod n) Input First line of the input contains a single integer T representing number of test cases that follow. For next T lines, each line contains three space separated integers x, m and n. Output Output exactly T lines each containing the...
1
for _ in range(input()): x,m,n=map(int,raw_input().split()) if x==1: print (m+1)%n; else: print ((pow(x,m+1,(x-1)*n)-1+(x-1)*n)%((x-1)*n))/(x-1)
Pashmak decided to give Parmida a pair of flowers from the garden. There are n flowers in the garden and the i-th of them has a beauty number bi. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty difference i...
3
def fac(n): return (n*(n-1))//2 n=int(input()) a=list(map(int, input().split())) a.sort() if (a[0]!= a[-1]): print(a[-1] - a[0],(a.count(a[0]) * a.count(a[-1])),end=' ') else: print(a[-1] - a[0],fac(a.count(a[0]) ),end=' ' )
Your friend Mishka and you attend a calculus lecture. Lecture lasts n minutes. Lecturer tells ai theorems during the i-th minute. Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array t of Mishka's behavior. If Mishka is asleep during the i-th m...
3
from sys import stdout, stdin #video def acc_sum(_list, awake): acc = [] _sum = 0 for i in range(len(_list)): if awake[i] == 1: _sum+=_list[i] acc += [_sum] return acc def calulate_sum(i,j, _list): if i > 0: return _list[j]-_list[i-1] return _list[j] def ...
You have n problems. You have estimated the difficulty of the i-th one as integer ci. Now you want to prepare a problemset for a contest, using some of the problems you've made. A problemset for the contest must consist of at least two problems. You think that the total difficulty of the problems of the contest must b...
1
n,l,r,x=map(int,raw_input().split()) t=map(int,raw_input().split()) import itertools c=itertools.product([0,1], repeat=n) ans=0 for a in c: if sum(a)>1: p=[] for i in range(n): if a[i]: p.append(t[i]) if l<=sum(p)<=r and max(p)-min(p)>=x: ans+=1 print ...
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≤ i ≤ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is it...
3
n=int(input()) x=list(map(int, input().split())) temp=1 hasil=1 for i in range(1,n): if x[i-1]<=x[i]: temp+=1 else: temp=1 if hasil<temp: hasil=temp print(hasil)
This problem is actually a subproblem of problem G from the same contest. There are n candies in a candy box. The type of the i-th candy is a_i (1 ≤ a_i ≤ n). You have to prepare a gift using some of these candies with the following restriction: the numbers of candies of each type presented in a gift should be all di...
3
for q in range(int(input())): n=int(input()) a=list(map(int,input().split(" "))) freq={} for i in a: if i in freq: freq[i]+=1 else: freq[i]=1 l=[] for key,value in freq.items(): l.append(value) l.sort() mval=l[-1] su=l[-1] for i in...
Andrey received a postcard from Irina. It contained only the words "Hello, Andrey!", and a strange string consisting of lowercase Latin letters, snowflakes and candy canes. Andrey thought that this string is an encrypted message, and decided to decrypt it. Andrey noticed that snowflakes and candy canes always stand af...
3
s = input() k = int(input()) c = 0 p = 0 has_star = False for i in range(len(s)): if s[i] in ['*', '?']: if s[i] == '*': has_star = True c -= 1 else: p += 1 c += 1 if k < c: print("Impossible") elif (not has_star) and (k > p): print("Impossible") else: sig...
Maxim always goes to the supermarket on Sundays. Today the supermarket has a special offer of discount systems. There are m types of discounts. We assume that the discounts are indexed from 1 to m. To use the discount number i, the customer takes a special basket, where he puts exactly qi items he buys. Under the term...
1
m = input() q = raw_input().split(' ') for i in xrange(m): q[i] = int(q[i]) n = input() a = raw_input().split(' ') for i in xrange(n): a[i] = int(a[i]) best = min(q) a = sorted(a, reverse = True) answer = 0 for i in xrange(n): if ((i + 1) % (best + 2) == 0) or ((i + 2) % (best + 2) == 0): continue answer += a[...
Two students of AtCoder Kindergarten are fighting over candy packs. There are three candy packs, each of which contains a, b, and c candies, respectively. Teacher Evi is trying to distribute the packs between the two students so that each student gets the same number of candies. Determine whether it is possible. Not...
3
A=list(map(int,input().split()));print(("No","Yes")[sum(A)/2 in A])
Polycarpus loves hamburgers very much. He especially adores the hamburgers he makes with his own hands. Polycarpus thinks that there are only three decent ingredients to make hamburgers from: a bread, sausage and cheese. He writes down the recipe of his favorite "Le Hamburger de Polycarpus" as a string of letters 'B' (...
3
st = input() B = st.count('B') S = st.count('S') C = st.count('C') b,s,c=map(int,input().split()) bp, sp, cp = map(int,input().split()) r=int(input()) lm=0; rm=int(1e15)+1 while rm-lm>1: m=(rm+lm)//2 # print(m) bb=max(m*B-b,0) ss=max(m*S-s,0) cc=max(m*C-c, 0) #print(bp*bb+ss*sp+cc*cp) if bp*b...
Cricket has gone from a history of format which are test match, 50-50 and 20-20. Therefore, ICC decided to start a new type of format i.e. toss. For this ICC started a competition known as ‘Toss ka Boss’. Here the team captains compete with each other. For the first match we have two captains which will compete with ea...
1
t = int(raw_input()) for _ in range(t): s = raw_input() fin = 0 curr = 0 for i in s: if i == 'H': curr += 1 else: curr = 0 fin += curr print fin
The only difference between easy and hard versions is the maximum value of n. You are given a positive integer number n. You really love good numbers so you want to find the smallest good number greater than or equal to n. The positive integer is called good if it can be represented as a sum of distinct powers of 3 (...
3
for _ in range(int(input())): n = int(input()) s = '' while n!=0: s= str(n%3)+ s n = n//3 #print(n) dd = len(s) A =[] buf = 0 for i in range(dd): A.append(int(s[i])) #print(s) #print(A) for i in range(dd -1,-1,-1): if A...
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() b=int(a) if(b%2==0 and b!=2): print("YES") else: print("NO")
It's that time of the year when the Russians flood their countryside summer cottages (dachas) and the bus stop has a lot of people. People rarely go to the dacha on their own, it's usually a group, so the people stand in queue by groups. The bus stop queue has n groups of people. The i-th group from the beginning has ...
3
from math import ceil n,m = map(int,input().split()) l = list(map(int,input().split())) i = 0 t = 0 while i < n: s = m while i < n: s = s - l[i] if s >= 0: i = i + 1 else: break t = t + 1 print(t)
You are given an undirected graph with N vertices and 0 edges. Process Q queries of the following types. * `0 u v`: Add an edge (u, v). * `1 u v`: Print 1 if u and v are in the same connected component, 0 otherwise. Constraints * 1 \leq N \leq 200,000 * 1 \leq Q \leq 200,000 * 0 \leq u_i, v_i \lt N Input Input is ...
3
import sys class UnionFind: def __init__(self, n: int) -> None: self.forest = [-1] * n def union(self, x: int, y: int) -> None: x = self.findRoot(x) y = self.findRoot(y) if x == y: return if self.forest[x] > self.forest[y]: x, y = y, x s...
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()) lv=1 sum=0 while lv<=n: a=input() if a=="Tetrahedron": sum=sum+4 elif a=="Cube": sum=sum+6 elif a=="Octahedron": sum=sum+8 elif a=="Dodecahedron": sum=sum+12 elif a=="Icosahedron": sum=sum+20 lv=lv+1 print(sum)
You have decided to give an allowance to your child depending on the outcome of the game that he will play now. The game is played as follows: * There are three "integer panels", each with a digit between 1 and 9 (inclusive) printed on it, and one "operator panel" with a `+` printed on it. * The player should constru...
1
X = map(int, raw_input().split()) y = max(X) print 10*y+sum(X)-y
So, the New Year holidays are over. Santa Claus and his colleagues can take a rest and have guests at last. When two "New Year and Christmas Men" meet, thear assistants cut out of cardboard the letters from the guest's name and the host's name in honor of this event. Then the hung the letters above the main entrance. O...
3
s1 = input(); s2 = input(); s3 = input() s1 = ''.join(sorted(s1)); s2 = ''.join(sorted(s2)); s3 = ''.join(sorted(s3)) s4 = s1+s2; s4 = ''.join(sorted(s4)) if s4==s3: print('YES') else:print('NO')
Once again, Boris needs the help of Anton in creating a task. This time Anton needs to solve the following problem: There are two arrays of integers a and b of length n. It turned out that array a contains only elements from the set \{-1, 0, 1\}. Anton can perform the following sequence of operations any number of ti...
3
# cook your dish here for _ in range(int(input())): n=int(input()) l1=list(map(int,input().split())) l2=list(map(int,input().split())) x=-1 y=-1 z=-1 for i in range(n): if(l1[i]==0): x=i break for i in range(n): if(l1[i]==1): y=i ...
Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be n problems, sorted by difficulty, i.e. problem 1 is the easiest and problem n is the hardest. Limak knows it will take him 5·i minutes to solve the i-th...
3
s=input() x=s.split() n=int(x[0]) k=int(x[1]) time=4*60 spent=0 remaining=time-k c=0 for i in range(1,n+1): spent=spent+(5*i) if spent>remaining: break else: c=c+1 print(c)
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
test_cases= int(input()) while(test_cases>0): input_str = input() if(len(input_str)>10): first_char = input_str[0] last_char= input_str[len(input_str)-1] word_len = len(input_str)-2 print(first_char+str(word_len)+last_char) else: print(input_str) test_cases=test_c...
We have N locked treasure boxes, numbered 1 to N. A shop sells M keys. The i-th key is sold for a_i yen (the currency of Japan), and it can unlock b_i of the boxes: Box c_{i1}, c_{i2}, ..., c_{i{b_i}}. Each key purchased can be used any number of times. Find the minimum cost required to unlock all the treasure boxes....
3
N, M = map(int, input().split()) INF = 10**9 dp = [INF]*(1<<N) dp[0] = 0 for _ in range(M): a, b = map(int, input().split()) c = sum(map(lambda x: 1 << (int(x)-1), input().split())) for j in range(1<<N): dp[j|c] = min(dp[j|c], dp[j] + a) ans = dp[-1] if ans == INF: print(-1) else: print(ans)
Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity. There are n columns of toy cubes in the box arranged in a line. The i-th column contains ai cubes. At first, the gravity in the box is pulling...
1
raw_input() list_number = list(map(int, raw_input().split())) list_number.sort() print(' '.join(map(str, list_number)))
Wabbit is trying to move a box containing food for the rest of the zoo in the coordinate plane from the point (x_1,y_1) to the point (x_2,y_2). He has a rope, which he can use to pull the box. He can only pull the box if he stands exactly 1 unit away from the box in the direction of one of two coordinate axes. He will...
3
t=int(input()) for i in range(0,t): t=0 x1,y1,x2,y2=map(int,input().split()) if y1==y2: t = abs(x2 - x1) elif x1==x2: t=abs(y2-y1) else: t = abs(x2 - x1) + 2 + abs(y2-y1) print(t)
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th...
3
s = input() countLower = 0 for c in s: if c.islower(): countLower += 1 print(s.lower() if countLower >= (len(s)/2) else s.upper())
You are given an integer N. Among the divisors of N! (= 1 \times 2 \times ... \times N), how many Shichi-Go numbers (literally "Seven-Five numbers") are there? Here, a Shichi-Go number is a positive integer that has exactly 75 divisors. Constraints * 1 \leq N \leq 100 * N is an integer. Input Input is given from S...
3
n = int(input()) f = [0]*(n+1) for i in range(2,n+1): a = i for j in range(2,i+1): while a % j == 0: f[j] += 1 a //= j def number(m): c = 0 for i in range(n): if f[i] >= m - 1: c += 1 return c print(number(75) + number(25)*(number(3) - 1) + number(...
It's that time of the year when the Russians flood their countryside summer cottages (dachas) and the bus stop has a lot of people. People rarely go to the dacha on their own, it's usually a group, so the people stand in queue by groups. The bus stop queue has n groups of people. The i-th group from the beginning has ...
3
a,b = map(int, input().split()) ar = list(map(int, input().split())) count=1 sums=0 for i in range(a): sums += ar[i] if(sums > b): sums = ar[i] count+= 1 print(count)
You are given two arrays of integers a_1,…,a_n and b_1,…,b_m. Your task is to find a non-empty array c_1,…,c_k that is a subsequence of a_1,…,a_n, and also a subsequence of b_1,…,b_m. If there are multiple answers, find one of the smallest possible length. If there are still multiple of the smallest possible length, f...
3
def task(): s = input() a = set(map(int, input().split())) b = set(map(int, input().split())) res = a & b if len(res) == 0: print('NO') else: print('YES') print(1, min(res)) n = int(input()) for _ in range(n): task()
You are given an array a of n integers. You want to make all elements of a equal to zero by doing the following operation exactly three times: * Select a segment, for each number in this segment we can add a multiple of len to it, where len is the length of this segment (added integers can be different). It can...
3
import os from io import BytesIO, IOBase from collections import Counter import sys def main(): n=int(input()) a=list(map(int,input().split())) if n==1: print(1,1) print(0) print(1,1) print(0) print(1,1) print(-a[0]) else: print(1,1) print...
A penguin Rocher has n sticks. He has exactly one stick with length i for all 1 ≤ i ≤ n. He can connect some sticks. If he connects two sticks that have lengths a and b, he gets one stick with length a + b. Two sticks, that were used in the operation disappear from his set and the new connected stick appears in his se...
3
test=int(input()) for i in range(0,test): n=int(input()) print((1+n)//2)
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
n = int(input()) def melon(x): if x == 1: return 'NO'; if x == 2: return 'NO'; if(x%2 == 0): return 'YES'; else: return 'NO'; print(melon(n))
We have an integer sequence A, whose length is N. Find the number of the non-empty contiguous subsequences of A whose sums are 0. Note that we are counting the ways to take out subsequences. That is, even if the contents of some two subsequences are the same, they are counted individually if they are taken from differ...
3
from collections import * from itertools import * N=int(input()) A=list(map(int,input().split())) s=[0]+list(accumulate(A)) s_cnt=Counter(s) ans=0 for x in s_cnt.values(): ans+=(x*(x-1))//2 print(ans)
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves. We know that several boy&girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair m...
3
def try_kuhn (v): if u[v]: return False u[v] = 1 for to in g[v]: if mt[to] == -1 or try_kuhn(mt[to]): mt[to] = v return True return False n = int(input()) #размер 1 доли A = list(map(int, input().split())) m = int(input()) #размер 2 доли B = list(map(int, input().split())) g = [[] for i in range(n)] k =...
«Bersoft» company is working on a new version of its most popular text editor — Bord 2010. Bord, like many other text editors, should be able to print out multipage documents. A user keys a sequence of the document page numbers that he wants to print out (separates them with a comma, without spaces). Your task is to w...
3
import sys pages = list(map(int, sys.stdin.readline().strip().split(","))) unipages = set(pages) unilist = [] for i in unipages: unilist.append(i) unilist.sort() unilen = len(unilist) first = unilist[0] prev = first for i in range(1, unilen): if unilist[i] == prev + 1: prev = unilist[i] else: last = prev if fi...
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
#import sys #sys.stdin = open('inA', 'r') #n = int(input()) #a = [int(x) for x in input().split()] a,b,c,d = map(int, input().split()) m = sorted([a,b,c]) a,b,c = m r = 0 if c-b<d: r += d - (c-b) if b-a<d: r += d - (b-a) print(r)
You are given a sequence a_1, a_2, ..., a_n consisting of n integers. You can choose any non-negative integer D (i.e. D ≥ 0), and for each a_i you can: * add D (only once), i. e. perform a_i := a_i + D, or * subtract D (only once), i. e. perform a_i := a_i - D, or * leave the value of a_i unchanged. It is...
3
n=int(input()) x=list(map(int,input().split())) mx=max(x) mn=min(x) if (mx-mn)%2==0: mid=(mx-mn)//2 poss=[mx,mn,mx-mid] else: mid=mx-mn poss=[mx,mn] for i in x: if i not in poss: mid=-1 print(mid) """ if i==1: judge=sub else: if len(s)==2 and type((max(s)-min(s))/2)...
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
def main(): n = int(input()) arr = list(map(int, input().split())) last_page = 0 count = 0 while last_page < n: max_page = last_page while last_page <= max_page: tmp_page = arr[last_page] - 1 if tmp_page > max_page: max_page = tmp_page ...
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≤ i ≤ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is it...
3
size = int(input()) seq = input().split(' ') seq = list(map(int , seq)) previous = 0 max_seg = 0 orders = [] for i in seq: if previous <= i: max_seg = max_seg + 1 else: orders.append(max_seg) max_seg = 1 previous = i orders.append(max_seg) print(max(orders))
Recently Anton found a box with digits in his room. There are k2 digits 2, k3 digits 3, k5 digits 5 and k6 digits 6. Anton's favorite integers are 32 and 256. He decided to compose this integers from digits he has. He wants to make the sum of these integers as large as possible. Help him solve this task! Each digit c...
3
k2, k3, k5, k6 = [int(i) for i in input().split()] sum = 0 sum += min(k2, k5, k6) * 256 k2 -= min(k2, k5, k6) if k2 > 0 and k3 > 0: sum += min(k2, k3) * 32 print(sum)
After reaching your destination, you want to build a new colony on the new planet. Since this planet has many mountains and the colony must be built on a flat surface you decided to flatten the mountains using boulders (you are still dreaming so this makes sense to you). <image> You are given an array h_1, h_2, ..., ...
3
T = int(input()) for _ in range(T): N, K = map(int, input().split()) h = list(map(int, input().split())) a = [max(h[i:]) - h[i] for i in range(N)] # print(sum(a)) if K > sum(a): print(-1); continue i, j = 0, 0 while K: w = 1 i = 0 while i < N and h[i] >= h[i + 1]: ...