problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
The new "Die Hard" movie has just been released! There are n people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 ruble bill. A "Die Hard" ticket costs 25 rubles. Can the booking clerk sell a ticket to each person and give the change if he initially has no money and sells the...
1
#!/usr/bin/python from __future__ import division from sys import stdin, stdout N = int (stdin.readline ()) arr = map (int, stdin.readline ().split ()) twentyfive, fifty = 0, 0 good = True for e in arr: if e == 25: twentyfive += 1 elif e == 50: if twentyfive > 0: twentyfive -= 1 fifty += 1 else: go...
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg...
3
# n=int(input()) # if(n%2==0): # print("YES") # else: # print("NO") # for _ in range(int(input())): # n=(input()) # if(len(n)<=10): # print(n) # else: # print(n[0]+str(len(n)-2)+n[len(n)-1]) # a=0 # for _ in range(int(input())): # n=list(map(int,input().split())) # count=0 ...
On a two-dimensional plane, there are m lines drawn parallel to the x axis, and n lines drawn parallel to the y axis. Among the lines parallel to the x axis, the i-th from the bottom is represented by y = y_i. Similarly, among the lines parallel to the y axis, the i-th from the left is represented by x = x_i. For ever...
3
n, m = map(int, input().split()) X = [int(x) for x in input().split()] Y = [int(y) for y in input().split()] p = 10 ** 9 + 7 print(sum([(X[i + 1] - X[i]) * (i + 1) * (n - i - 1) % p for i in range(n - 1)]) * sum([(Y[i + 1] - Y[i]) * (i + 1) * (m - i - 1) % p for i in range(m - 1)]) % p)
Manao has a monitor. The screen of the monitor has horizontal to vertical length ratio a:b. Now he is going to watch a movie. The movie's frame has horizontal to vertical length ratio c:d. Manao adjusts the view in such a way that the movie preserves the original frame ratio, but also occupies as much space on the scre...
3
from fractions import Fraction as f r=list(map(int,input().split())) a,b=r[0],r[1] c,d=r[2],r[3] ans=min(abs(f(a*b-c*d*(f(a,c)**2),a*b)),abs(f(a*b-c*d*(f(b,d)**2),a*b))) if ans==0: print('0/1') else: print(ans)
Allen is hosting a formal dinner party. 2n people come to the event in n pairs (couples). After a night of fun, Allen wants to line everyone up for a final picture. The 2n people line up, but Allen doesn't like the ordering. Allen prefers if each pair occupies adjacent positions in the line, as this makes the picture m...
3
# itne me hi thakk gaye? n = int(input()) arr = list(map(int, input().split())) count = 0 for ii in range(2*n): i = arr[ii] x = arr.index(i) y = arr.index(i, x+1) arr1 = arr[:x+1] arr2 = [] for z in arr[x+1:]: if z != i: arr2.append(z) newarr = arr1 + [i] + arr2 # print(newarr) arr = newarr[::] count += ...
A number is ternary if it contains only digits 0, 1 and 2. For example, the following numbers are ternary: 1022, 11, 21, 2002. You are given a long ternary number x. The first (leftmost) digit of x is guaranteed to be 2, the other digits of x can be 0, 1 or 2. Let's define the ternary XOR operation βŠ™ of two ternary n...
3
import sys input = sys.stdin.readline def main(): def solve(x): a = '' b = '' aislarger = 0 for i,d in enumerate(str(x)): # print(d) # print(a,b) if i == 0: a += '1' b += '1' elif d == '0': ...
Takahashi, Nakahashi and Hikuhashi have integers A, B and C, respectively. After repeating the following operation K times, find the integer Takahashi will get minus the integer Nakahashi will get: * Each of them simultaneously calculate the sum of the integers that the other two people have, then replace his own inte...
3
a, b, c, k = map(int, input().split()) if k % 2 == 1: print(b - a) elif k % 2 == 0: print(a - b)
Running with barriers on the circle track is very popular in the country where Dasha lives, so no wonder that on her way to classes she saw the following situation: The track is the circle with length L, in distinct points of which there are n barriers. Athlete always run the track in counterclockwise direction if you...
1
from random import random import math import re import fractions # N = input() N, M = map(int, raw_input().split(" ")) A = sorted(map(int, raw_input().split(" "))) B = sorted(map(int, raw_input().split(" "))) A.append(M+A[0]) B.append(M+B[0]) da = [] db = [] for i in xrange(N): da.append(A[i+1]-A[i]) db.append...
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array a of n non-negative integers. Dark created that array 1000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high...
3
t=int(input()) def gag(a,k): ans=0 for x in range(len(a)-1): a1,b1=a[x],a[x+1] if a1==-1: a1=k if b1==-1: b1=k m=abs(a1-b1) if m>ans: ans=m return ans round=lambda x:int(x+0.5) for x in range(t): n=int(input()) a=list(map(in...
Ivan has n songs on his phone. The size of the i-th song is a_i bytes. Ivan also has a flash drive which can hold at most m bytes in total. Initially, his flash drive is empty. Ivan wants to copy all n songs to the flash drive. He can compress the songs. If he compresses the i-th song, the size of the i-th song reduce...
3
n, m = map(int, input().split()) C = [] S = 0 k = 0 for _ in range(n): a, b = map(int, input().split()) S += a C.append(a - b) if S > m + sum(C): print(-1) elif S <= m: print(0) else: # m < S <= m + sum(C) C.sort(reverse=True) ind = 0 while (S > m): S = S - C[ind] ind += ...
Fox Ciel and her friends are in a dancing room. There are n boys and m girls here, and they never danced before. There will be some songs, during each song, there must be exactly one boy and one girl are dancing. Besides, there is a special rule: * either the boy in the dancing pair must dance for the first time (so...
1
N, M = map(int,raw_input().split()) print N + M - 1 for i in range (M): print 1, (i+1) for j in range (2,N+1): print j, 1
For a given array a consisting of n integers and a given integer m find if it is possible to reorder elements of the array a in such a way that βˆ‘_{i=1}^{n}{βˆ‘_{j=i}^{n}{(a_j)/(j)}} equals m? It is forbidden to delete elements as well as insert new elements. Please note that no rounding occurs during division, for exampl...
3
for _ in range(int(input())): # n = int(input()) n,m = [int(x) for x in input().split()] a = [int(x) for x in input().split()] # k = input() if sum(a)==m:print('YES') else:print('NO')
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()) w = [] for i in range(n): w.append(input()) for i in range(n): if len(w[i]) > 10: print(w[i][0] + str(len(w[i]) - 2) + w[i][-1]) else: print(w[i])
There will be a launch of a new, powerful and unusual collider very soon, which located along a straight line. n particles will be launched inside it. All of them are located in a straight line and there can not be two or more particles located in the same point. The coordinates of the particles coincide with the dista...
1
import sys elements = input() el_d = raw_input() elem_reach = [] el_x = map(int, raw_input().split()) for i in range(0,elements-1): if el_d[i] == 'R' and el_d[i+1] == 'L': elem_reach.append(el_x[i+1]-el_x[i]) if len(elem_reach)>0: elem_reach.sort() print elem_reach[0]/2 else: print -1
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the...
3
dr, zabor = list(map(int, input().split())) a = list(map(int, input().split())) c = 0 for i in range(dr): if a[i] <= zabor: c = c + 1 #счСтчик ΡˆΠΈΡ€ΠΈΠ½Ρ‹ else: c = c + 2 print(c)
You are given a rectangular cake, represented as an r Γ— c grid. Each cell either has an evil strawberry, or is empty. For example, a 3 Γ— 4 cake may look as follows: <image> The cakeminator is going to eat the cake! Each time he eats, he chooses a row or a column that does not contain any evil strawberries and contain...
1
''' Created on 2013-7-21 @author: Administrator ''' row, col = map(int, raw_input().split()) arr = [] for i in range(row): arr.append(str(raw_input())) rflag, cflag = [True]*row, [True]*col for i in range(row): for j in range(col): if arr[i][j]=='S': rflag[i], cflag[j] = False, False res = ...
This is the easy version of the problem. The difference between the versions is the constraint on n and the required number of operations. You can make hacks only if all versions of the problem are solved. There are two binary strings a and b of length n (a binary string is a string consisting of symbols 0 and 1). In ...
3
import os import sys from io import BytesIO, IOBase def transform(string, n): ops = [] string += '0' for i in range(1, n+1): if string[i]!=string[i-1]: ops.append(i) return ops def main(): t = int(input()) for _ in range(t): n = int(input()) a, b = inpu...
You are visiting a large electronics store to buy a refrigerator and a microwave. The store sells A kinds of refrigerators and B kinds of microwaves. The i-th refrigerator ( 1 \le i \le A ) is sold at a_i yen (the currency of Japan), and the j-th microwave ( 1 \le j \le B ) is sold at b_j yen. You have M discount tic...
3
a, b, m=map(int, input().split()) a=list(map(int, input().split())) b=list(map(int, input().split())) mprice=min(a)+min(b) for _ in range(m): x, y, c=map(int, input().split()) p=a[x-1]+b[y-1]-c if p<mprice: mprice=p print(mprice)
We have an N \times N square grid. We will paint each square in the grid either black or white. If we paint exactly A squares white, how many squares will be painted black? Constraints * 1 \leq N \leq 100 * 0 \leq A \leq N^2 Inputs Input is given from Standard Input in the following format: N A Outputs Print...
3
N = int(input()) a = int(input()) print (N *N - a)
Overlooking the captivating blend of myriads of vernal hues, Arkady the painter lays out a long, long canvas. Arkady has a sufficiently large amount of paint of three colours: cyan, magenta, and yellow. On the one-dimensional canvas split into n consecutive segments, each segment needs to be painted in one of the colo...
3
lengthCanvas = int(input("")) canvas = input("") colors = ["C","M","Y"] flag = True for i in range(len(canvas)-1): if canvas[i] == canvas[i+1] and canvas[i] != "?": flag = False if flag: flag = False if canvas[0] == "?" or canvas[len(canvas)-1] == "?": flag = True for i in range(len(c...
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
def find_pairs(lst, k): i = 0 j = len(lst) - 1 result = 0 while i < j: x, y = lst[i], lst[j] s = x + y if s == k: result += 1 i += 1 j -= 1 else: if s < k: i += 1 else: j -= 1 ...
Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock. <image> The combination lock is represented by n rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has t...
3
n=int(input()) a=input() b=input() ans=0 for i in range (n): ans += min(abs(int(a[i])-int(b[i])),10-abs(int(a[i])-int(b[i]))) print (ans)
M-kun has the following three cards: * A red card with the integer A. * A green card with the integer B. * A blue card with the integer C. He is a genius magician who can do the following operation at most K times: * Choose one of the three cards and multiply the written integer by 2. His magic is successful if...
3
A,B,C=map(int,input().split()) K=int(input()) i=0 while A>=B: B2=2*B B=B2 i=i+1 while B>=C: C2=2*C C=C2 i=i+1 print('No'if i>K else'Yes')
We have a tree with N vertices numbered 1 to N. The i-th edge in the tree connects Vertex u_i and Vertex v_i, and its length is w_i. Your objective is to paint each vertex in the tree white or black (it is fine to paint all vertices the same color) so that the following condition is satisfied: * For any two vertices p...
3
N = int(input()) tree = [[] for _ in range(N+1)] for i in range(N-1): u,v,w = map(int, input().split()) tree[u].append([v,w]) tree[v].append([u,w]) d = [-1 for _ in range(N+1)] d[1] = 0 q = [1] while q: cur = q.pop() for n,l in tree[cur]: if d[n] == -1: d[n] = d[cur] + l ...
You have integer n. Calculate how many ways are there to fully cover belt-like area of 4n-2 triangles with diamond shapes. Diamond shape consists of two triangles. You can move, rotate or flip the shape, but you cannot scale it. 2 coverings are different if some 2 triangles are covered by the same diamond shape in ...
3
#!/usr/bin/env python3 def ntvdm(): t = int(input()) for _ in range(t): print(input()) ntvdm()
In Omkar's last class of math, he learned about the least common multiple, or LCM. LCM(a, b) is the smallest positive integer x which is divisible by both a and b. Omkar, having a laudably curious mind, immediately thought of a problem involving the LCM operation: given an integer n, find positive integers a and b suc...
3
""" pppppppppppppppppppp ppppp ppppppppppppppppppp ppppppp ppppppppppppppppppppp pppppppp pppppppppppppppppppppp pppppppppppppppppppppppppppppppp pppppppppppppppppppp...
Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited n his friends there. If t...
3
n=int(input()) inp=input().split(' ') fl=inp[::] #print(inp) for i in range(len(inp)): fl[int(inp[i])-1]=str(i+1) print(' '.join(fl))
The Smart Beaver from ABBYY decided to have a day off. But doing nothing the whole day turned out to be too boring, and he decided to play a game with pebbles. Initially, the Beaver has n pebbles. He arranges them in a equal rows, each row has b pebbles (a > 1). Note that the Beaver must use all the pebbles he has, i. ...
3
n=int(input()) k=2 ans=n while k*k<=n: while n%k==0: n//=k ans+=n if k==2: k=3 else: k+=2 if n>1: ans+=1 print(ans)
A frog lives on the axis Ox and needs to reach home which is in the point n. She starts from the point 1. The frog can jump to the right at a distance not more than d. So, after she jumped from the point x she can reach the point x + a, where a is an integer from 1 to d. For each point from 1 to n is known if there is...
3
n, d = map(int, input().split()) A = input() def solve(): if A[-1] == '0': return -1 currReachable = maxReachable = n - 1 ans = 1 for i in range(n - 2, -1, -1): if A[i] == '1': if i + d >= maxReachable: currReachable = i elif i + d < maxReachable and currReachable - d <= i: ans += 1 maxReach...
Omkar is building a waterslide in his water park, and he needs your help to ensure that he does it as efficiently as possible. Omkar currently has n supports arranged in a line, the i-th of which has height a_i. Omkar wants to build his waterslide from the right to the left, so his supports must be nondecreasing in he...
3
#from collection import defaultdict as dd import sys input=sys.stdin.readline t=int(input()) while t: n=int(input()) #n,k=map(int,input().split()) l=list(map(int,input().split())) mi=l[-1] cou=0 for i in range(n-2,-1,-1): if(l[i]>=mi): cou+=l[i]-mi mi=l[i] ...
Two bored soldiers are playing card war. Their card deck consists of exactly n cards, numbered from 1 to n, all values are different. They divide cards between them in some manner, it's possible that they have different number of cards. Then they play a "war"-like card game. The rules are following. On each turn a fi...
3
z = lambda :list(map(int, input().split())) n = int(input()) k1 = z()[1:] k2 = z()[1:] c = 0 while k1 and k2: x, y = k1.pop(0), k2.pop(0) if x > y: k1 += [y, x] else: k2 += [x, y] if c > 1000: print(-1) break c += 1 else: print(c, 1 if k1 else 2)
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." β€” an excerpt from contest rules. A total of n participants took part in the contest (n β‰₯ k), and you already know their scores. Calculate how many ...
3
import sys def get_vals(func=str): return map(func, input().split()) def get(func=str): return func(input()) input = lambda: sys.stdin.readline().rstrip('\r\n') write = sys.stdout.write def test(): pass def main(): n, k = get_vals(int) pts = [*get_vals(int)] gage = pts[k-1] result ...
One fall day Joe got bored because he couldn't find himself something interesting to do. Marty suggested Joe to generate a string of length n to entertain him somehow. It didn't seem particularly difficult, but Joe's generated string had to follow these rules: * the string may only contain characters 'a', 'b', or 'c...
1
for _ in range(input()): n,k=[int(i) for i in raw_input().split()] s="abc"*(n/3+1) print s[:n]
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
n = int(input()) estimates = input().split() print('HARD') if '1' in estimates else print('EASY')
You are given a non-negative integer n, its decimal representation consists of at most 100 digits and doesn't contain leading zeroes. Your task is to determine if it is possible in this case to remove some of the digits (possibly not remove any digit at all) so that the result contains at least one digit, forms a non-...
1
list1=[8*i for i in xrange(2)] list2=[8*i for i in xrange(2,13)] list3=[8*i for i in xrange(13,125)] s=str(raw_input()) numlist=[] for ss in s: numlist.append(int(ss)) for i in numlist: if i in list1: print 'YES' print i exit() for i in xrange(len(numlist)-1): for j in xrange(i+1,len...
Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it. Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and...
1
n = int(raw_input()) a = map(int, raw_input().split()) MAX = 100001 c = [0] * MAX for aa in a: c[aa] += 1 res = [-1] * MAX def dp(x): if x<1: return 0 if res[x] > -1: return res[x] res[x] = max(c[x]*x + dp(x-2), c[x-1]*(x-1) + dp(x-3)) return res[x] res[0] = 0 res[1] = c[1] res[2...
Alice and Bob are playing chess on a huge chessboard with dimensions n Γ— n. Alice has a single piece left β€” a queen, located at (a_x, a_y), while Bob has only the king standing at (b_x, b_y). Alice thinks that as her queen is dominating the chessboard, victory is hers. But Bob has made a devious plan to seize the vic...
3
def sign(x): return x > 0 - x < 0 n = int(input()) A = list(map(int, input().split())) B = list(map(int, input().split())) C = list(map(int, input().split())) B = [B[0] - A[0], B[1] - A[1]] C = [C[0] - A[0], C[1] - A[1]] ok = True if sign(B[0]) != sign(C[0]) or sign(B[1]) != sign(C[1]): ok = False # B = [...
Kabra is a very good friend of JP. So JP has assigned him a task. Given an array, two operations can be performed on it. They are 1) L X : Rotate the array towards left by X. 2) R X : Rotate the array towards right by X. Now you will be given 2 arrays containing N unique elements. The first one is the inital array(A) a...
1
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' N,M=map(int,raw_input().split()) inic=map(int,raw_input().split()) targ=map(int,raw_input().split()) done=False try: good=targ.index(inic[0]) except ValueError: print -1 done=True...
Professor GukiZ makes a new robot. The robot are in the point with coordinates (x1, y1) and should go to the point (x2, y2). In a single step the robot can change any of its coordinates (maybe both of them) by one (decrease or increase). So the robot can move in one of the 8 directions. Find the minimal number of steps...
1
a, b = map(int, raw_input().split()) c, d = map(int, raw_input().split()) if abs(a - c)> abs(b - d): print abs(a -c) else: print abs(b - d)
Initially Ildar has an empty array. He performs n steps. On each step he takes a subset of integers already added to the array and appends the mex of this subset to the array. The mex of an multiset of integers is the smallest non-negative integer not presented in the multiset. For example, the mex of the multiset [0...
3
n=int(input()) A=list(map(int,input().split())) now=-1 flag=True for i in range(n): if(A[i]>now+1): print(i+1) flag=False break elif(A[i]==now+1): now+=1 if(flag): print(-1)
It is November 18 now in Japan. By the way, 11 and 18 are adjacent Lucas numbers. You are given an integer N. Find the N-th Lucas number. Here, the i-th Lucas number L_i is defined as follows: * L_0=2 * L_1=1 * L_i=L_{i-1}+L_{i-2} (iβ‰₯2) Constraints * 1≀N≀86 * It is guaranteed that the answer is less than 10^{18}. ...
3
N = int(input()) a, b = 2, 1 for i in range(N - 1): a, b = b, (a + b) print(b)
Write a program which reads an integer $S$ [second] and converts it to $h:m:s$ where $h$, $m$, $s$ denote hours, minutes (less than 60) and seconds (less than 60) respectively. Constraints * $0 \leq S \leq 86400$ Input An integer $S$ is given in a line. Output Print $h$, $m$ and $s$ separated by ':'. You do not n...
1
n= input() a= int(n / 3600) b= int(n % 3600 / 60) c= int(n % 3600 % 60) print "%d:%d:%d" %(a,b,c)
Monk has a very good friend, Puchi. As weird as his name, are the games he plays. One fine day, they decided to play a game to test how diverse their choices are. Both of them choose exactly one integer each. Monk chooses an integer M and Puchi chooses an integer P. The diversity of their choices is defined as the nu...
1
t = int(raw_input()) for tc in xrange(1, t+1): a = raw_input().split() a = [int(k) for k in a] print bin((a[0]^a[1])).count('1')
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...
1
import string a=list(string.ascii_lowercase) b=[0]*26 n=int(raw_input()) word=raw_input().lower() for i in word: if i in a: b[a.index(i)]+=1 if all(v>=1 for v in b): print 'YES' else: print 'NO'
Luckily, Serval got onto the right bus, and he came to the kindergarten on time. After coming to kindergarten, he found the toy bricks very funny. He has a special interest to create difficult problems for others to solve. This time, with many 1 Γ— 1 Γ— 1 toy bricks, he builds up a 3-dimensional object. We can describe ...
3
import sys import functools import itertools import os import math # ---------------------------------------------------- # β–ˆβ–ˆ β–„β–ˆβ–€β–“β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–„ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–„ β–ˆ β–“β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–€β–ˆβ–ˆβ–ˆ β–„β–„β–„ β–„β–„β–„ β–ˆβ–ˆβ–’ β–ˆβ–“ β–ˆβ–ˆβ–“ β–ˆβ–ˆβ–ˆβ–„ β–ˆ β–„β–„β–„ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–‘ β–ˆβ–ˆ # β–ˆβ–ˆβ–„β–ˆβ–’ β–’β–ˆβ–ˆβ–€ β–ˆβ–ˆβ–Œβ–’β–ˆβ–ˆ β–’ β–ˆβ–ˆ β–“β–ˆβ–ˆβ–’ β–ˆβ–ˆ β–€β–ˆ β–ˆ β–“β–ˆ β–€ β–“β–ˆβ–ˆ β–’ β–ˆβ–ˆβ–’β–’β–ˆβ–ˆβ–ˆβ–ˆβ–„...
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like. Now let's imagine a typical morning in your family. You haven't w...
3
n = int(input()) a = list(map(int, input().split())) a = sorted(a, reverse=True) k = sum(a) for i in range(n): j = sum(a[:i+1]) if j > (k-j): print(i+1) break
Petr stands in line of n people, but he doesn't know exactly which position he occupies. He can say that there are no less than a people standing in front of him and no more than b people standing behind him. Find the number of different positions Petr can occupy. Input The only line contains three integers n, a and ...
3
n,a,b=map(int,input().split()) c=min(n-a,1+b) print(c)
Kate has a set S of n integers \{1, ..., n\} . She thinks that imperfection of a subset M βŠ† S is equal to the maximum of gcd(a, b) over all pairs (a, b) such that both a and b are in M and a β‰  b. Kate is a very neat girl and for each k ∈ \{2, ..., n\} she wants to find a subset that has the smallest imperfection am...
3
n = int(input()) L = [0 for _ in range(n+1)] for i in range(1,n+1): for j in range(i+i,n+1,i): L[j]=i L.sort() print(*L[2:])
Another Codeforces Round has just finished! It has gathered n participants, and according to the results, the expected rating change of participant i is a_i. These rating changes are perfectly balanced β€” their sum is equal to 0. Unfortunately, due to minor technical glitches, the round is declared semi-rated. It means...
3
import math c=0 for _ in range(int(input())): n=int(input()) #x=[int(n) for n in input().split()] #s=input() if not n&1: print(n//2) elif c&1: print(n//2) c+=1 else: print(math.ceil(n/2)) c+=1
We have a sequence p = {p_1,\ p_2,\ ...,\ p_N} which is a permutation of {1,\ 2,\ ...,\ N}. You can perform the following operation at most once: choose integers i and j (1 \leq i < j \leq N), and swap p_i and p_j. Note that you can also choose not to perform it. Print `YES` if you can sort p in ascending order in th...
3
N = int(input()) s = list(map(int, input().split())) A = 0 for i in range (N): if s[i] != i+1: A+=1 if A <= 2 : print('YES') else: print('NO')
Caisa solved the problem with the sugar and now he is on the way back to home. Caisa is playing a mobile game during his path. There are (n + 1) pylons numbered from 0 to n in this game. The pylon with number 0 has zero height, the pylon with number i (i > 0) has height hi. The goal of the game is to reach n-th pylon...
3
n = int(input()) a = input() A = [] for i in a.split(): A.append(int(i)) count = A[0] Sum = 0 ''' for j in range(0,n-1): if count>=A[j+1]: count = count +A[j]-A[j+1] elif count<A[j+1]: Sum = Sum + A[j+1]-count count = A[j+1] print(Sum+A[0]) ''' print(max(A))
We have a 3 \times 3 grid. A number c_{i, j} is written in the square (i, j), where (i, j) denotes the square at the i-th row from the top and the j-th column from the left. According to Takahashi, there are six integers a_1, a_2, a_3, b_1, b_2, b_3 whose values are fixed, and the number written in the square (i, j) is...
3
c=[list(map(int,input().split())) for i in range(3)] if (c[0][0]+c[1][1]+c[2][2])*2==c[0][1]+c[0][2]+c[1][0]+c[1][2]+c[2][0]+c[2][1]: print('Yes') else: print('No')
The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row. Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all...
1
#!/bin/python from sys import stdin n=int(stdin.readline().strip()) arr=map(int,stdin.readline().strip().split()) max=arr[n-1]+1 ans=[0]*n for i in range(n-2,-1,-1): if arr[i]<max: ans[i]=max-arr[i] else: ans[i]=0 max=arr[i]+1 for i in range(n): print ans[i],
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If...
3
s = input() danger = False c = 0; l = '' for i in s: if i == l: c += 1 else: c = 1 l = i if c == 7: danger = True break if danger: print('YES') else: print('NO')
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
import sys input = sys.stdin.readline I = lambda : list(map(int,input().split())) s=input().strip() a,b,c=s.count('B'),s.count("S"),s.count('C') n1,n2,n3=I() p1,p2,p3=I() r,=I() xx=[a,b,c].count(0) if xx==2: print([((n1+r//p1 if i==a else (n2+r//p2 if i==b else n3+r//p3)))//i for i in [a,b,c] if i][0]) elif xx: if a...
You have two variables a and b. Consider the following sequence of actions performed with these variables: 1. If a = 0 or b = 0, end the process. Otherwise, go to step 2; 2. If a β‰₯ 2Β·b, then set the value of a to a - 2Β·b, and repeat step 1. Otherwise, go to step 3; 3. If b β‰₯ 2Β·a, then set the value of b to b - 2...
3
def check1(a,b): if(a==0 or b==0): print(a,b) else: check2(a,b) def check2(a,b): if(a>=(2*b)): a=a%(2*b) check1(a,b) else: check3(a,b) def check3(a,b): if(b>=(2*a)): b=b%(2*a) check1(a,b) else: print(a,b) t=list(map(int,input().split())) a=t[0] b=t[1] check1(a,b)
According to an old legeng, a long time ago Ankh-Morpork residents did something wrong to miss Fortune, and she cursed them. She said that at some time n snacks of distinct sizes will fall on the city, and the residents should build a Snacktower of them by placing snacks one on another. Of course, big snacks should be ...
3
n= int(input()) l=map(int,input().split()) b=[0]*(n+2) for i in l: b[i]=1 while b[n]: print (n , end =' ') n-=1 print ()
You are given two arrays a and b, each consisting of n positive integers, and an integer x. Please determine if one can rearrange the elements of b so that a_i + b_i ≀ x holds for each i (1 ≀ i ≀ n). Input The first line of input contains one integer t (1 ≀ t ≀ 100) β€” the number of test cases. t blocks follow, each d...
3
f = int(input()) for j in range(f): n, x = map(int, input().split()) massiv1 = sorted(list(map(int, input().split()))) massiv2 = sorted(list(map(int, input().split())), reverse=True) if j + 1 != f: fuckup = input() isTrue = True for i in range(n): if massiv1[i] + massiv2[i] > x: ...
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
from sys import stdin,stdout from collections import defaultdict import math input=stdin.readline #def print(x):stdout.write(str(x)+'\n') for _ in range(int(input())): n=int(input()) l=list(map(int,input().split())) f=0 mini=1000000000000 for i in range(n-1): if l[i]>l[i+1]: f=1 ...
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
def main(): inp = list(map(int, input().split())) Y = inp[0] W = inp[1] num = 6 - max(Y, W) + 1 if(num % 2 == 1): if(num == 3): print('1/2') else: print(str(num) + '/6') else: if(num == 2): print('1/3') return if(num...
A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay iΒ·k dollars for the i-th banana). He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas? Input The first lin...
3
k,n,w=map(int,input("").split()) b=k*(w*(w+1)/2) if b>n: a=b-n print(int(a)) else: print(0)
Small, but very brave, mouse Brain was not accepted to summer school of young villains. He was upset and decided to postpone his plans of taking over the world, but to become a photographer instead. As you may know, the coolest photos are on the film (because you can specify the hashtag #film for such). Brain took a ...
3
rows = int(input().split(" ")[0]) for _ in range(rows): line = input() if "C" in line or "M" in line or "Y" in line: print("#Color") break else: print("#Black&White")
Our beloved detective, Sherlock is currently trying to catch a serial killer who kills a person each day. Using his powers of deduction, he came to know that the killer has a strategy for selecting his next victim. The killer starts with two potential victims on his first day, selects one of these two, kills selected ...
3
x, y = input().split() n = int(input()) res = [] res.append((x,y)) for i in range(n): a , b = input().split() if a == x: x = b elif a == y: y = b res.append((x, y)) for a, b in res: print(a + " " + b)
There are n cities in Berland and some pairs of them are connected by two-way roads. It is guaranteed that you can pass from any city to any other, moving along the roads. Cities are numerated from 1 to n. Two fairs are currently taking place in Berland β€” they are held in two different cities a and b (1 ≀ a, b ≀ n; a ...
3
from sys import stdin def input(): return next(stdin)[:-1] class DisjointUnionSet: def __init__(self, size): self.parent = list(range(size)) self.rank = [0] * size def find_set(self, v): if v == self.parent[v]: return v self.parent[v] = self.find_set(self.par...
You are given two integers a and b, and q queries. The i-th query consists of two numbers l_i and r_i, and the answer to it is the number of integers x such that l_i ≀ x ≀ r_i, and ((x mod a) mod b) β‰  ((x mod b) mod a). Calculate the answer for each query. Recall that y mod z is the remainder of the division of y by z...
3
import sys from math import gcd input=sys.stdin.readline for _ in range(int(input())): a,b,q=map(int,input().split()) lcm=a*b//(gcd(a,b)) data=[((i%a)%b!=(i%b)%a) for i in range(lcm)] for i in range(1,lcm): data[i]+=data[i-1] def func(num): s=(num+1)//lcm t=(num+1)%lcm ...
You are given a board of size n Γ— n, where n is odd (not divisible by 2). Initially, each cell of the board contains one figure. In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell (i, j) you can move...
3
t=int(input()) for _ in range(t): n=int(input()) sum=0 i=1 while i<n: sum+=2*((n-i)**2) i+=2 print(sum)
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
x=int(input()) if(x==0 or x==2): print("NO") else: if(x%2==0): print("YES") else: print("NO")
Everybody knows that the Berland citizens are keen on health, especially students. Berland students are so tough that all they drink is orange juice! Yesterday one student, Vasya and his mates made some barbecue and they drank this healthy drink only. After they ran out of the first barrel of juice, they decided to pl...
1
n=int(raw_input()) s=raw_input() i=0 c=0 while i<len(s): if i%n==0 and i>=4: if s[i-1]==s[i-2] and s[i-1]==s[i-3]: c+=1 i+=1 print c
You are a lover of bacteria. You want to raise some bacteria in a box. Initially, the box is empty. Each morning, you can put any number of bacteria into the box. And each night, every bacterium in the box will split into two bacteria. You hope to see exactly x bacteria in the box at some moment. What is the minimu...
3
n = int(input()) x = 0 while n > 1: x += (n) % 2 n = n >> 1 print(1 + x)
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos. In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" ...
1
inp=raw_input() prevChar=inp[0] prevCount=0 ans=prevChar currentCount=1 for i in range(1,len(inp)): if(inp[i]==prevChar): currentCount+=1 if(currentCount==3): currentCount-=1 elif(prevCount==2 and currentCount==2): currentCount-=1 else: ans+=prevCh...
AtCoDeer the deer found two positive integers, a and b. Determine whether the product of a and b is even or odd. Constraints * 1 ≀ a,b ≀ 10000 * a and b are integers. Input Input is given from Standard Input in the following format: a b Output If the product is odd, print `Odd`; if it is even, print `Even`. E...
3
print(['Even','Odd'][max(0,sum(map(lambda x:int(x)%2,input().split()))-1)])
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network. Bu...
1
name = list(raw_input()) p = [] i = 0 while i <= len(name) - 1: if name[i] not in p: p.append(name[i]) i += 1 if len(p) % 2 == 1: print 'IGNORE HIM!' else: print 'CHAT WITH HER!'
Two-gram is an ordered pair (i.e. string of length two) of capital Latin letters. For example, "AZ", "AA", "ZA" β€” three distinct two-grams. You are given a string s consisting of n capital Latin letters. Your task is to find any two-gram contained in the given string as a substring (i.e. two consecutive characters of ...
3
from collections import Counter n = int(input()) s = str(input()) last = s[0] two_grams = [] for i in range(1, n): two_grams.append(last+s[i]) last = s[i] c = Counter(two_grams) most_common_gram = c.most_common(1) print(most_common_gram[0][0])
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings. Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, seco...
3
n = int(input()) for x in range (0, n+1): if x == 0: str = "I hate " if x == n - 1: str = str + "it" break if x % 2 == 0: str = str + "that I love " elif x % 2 == 1: str = str + "that I hate " print(str)
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 i in range(int(input())): n = int(input()) lst = list(map(int, input().split()))[:n] switch = True lst.sort() for j in range(len(lst)-1): if lst[j+1] - lst[j] > 1: switch = False break if switch: print("YES") else: print("NO")
Write a program of the Insertion Sort algorithm which sorts a sequence A in ascending order. The algorithm should be based on the following pseudocode: for i = 1 to A.length-1 key = A[i] /* insert A[i] into the sorted sequence A[0,...,j-1] */ j = i - 1 while j >= 0 and A[j] > key A[j+1] = A[j] j-- A[j+1] = key Note...
3
#54 n=int(input()) *l,=list(map(int,input().split())) for i in range(n): temp=l[i] j=i-1 while j>=0 and l[j]>temp: l[j+1] = l[j] j-=1 l[j+1] = temp print(*l)
Johnny has a younger sister Anne, who is very clever and smart. As she came home from the kindergarten, she told his brother about the task that her kindergartener asked her to solve. The task was just to construct a triangle out of four sticks of different colours. Naturally, one of the sticks is extra. It is not allo...
3
def triangle(a,b,c): if(a+b>c and b+c>a and a+c>b): return 1 return 0 def segment(a,b,c): if(a+b==c or a+c==b or b+c==a): return 1 return 0 a,b,c,d=map(int,input().split()) if(triangle(a,b,c)==1 or triangle(a,b,d)==1 or triangle(a,c,d)==1 or triangle(b,c,d)==1): print("TRIANGLE") eli...
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the oppo...
3
n=int(input()) i=input() t=1 while n-1>0: n-=1 m=input() if m[1]==i[0]: t+=1 i=m print(t)
A permutation p is an ordered group of numbers p1, p2, ..., pn, consisting of n distinct positive integers, each is no more than n. We'll define number n as the length of permutation p1, p2, ..., pn. Simon has a positive integer n and a non-negative integer k, such that 2k ≀ n. Help him find permutation a of length 2n...
3
from sys import stdin, stdout n, k = map(int, stdin.readline().split()) if k: s = {2 * n - k, 2 * n} ans = [2 * n - k, 2 * n] for i in range(2 * n, 0, -1): if i not in s: ans.append(i) else: ans = [i for i in range(2 * n, 0, -1)] stdout.write(' '.join(list(map(str, ans))))
Santa Claus has received letters from n different kids throughout this year. Of course, each kid wants to get some presents from Santa: in particular, the i-th kid asked Santa to give them one of k_i different items as a present. Some items could have been asked by multiple kids. Santa is really busy, so he wants the ...
3
import sys from collections import Counter from itertools import chain def input(): return sys.stdin.readline().rstrip() def input_ints(): return [int(_) for _ in input().split()] INV = {} def inv(x): if x not in INV: INV[x] = pow(x, M - 2, M) return INV[x] M = 998244353 n = int(input()) a...
Let's call a positive integer composite if it has at least one divisor other than 1 and itself. For example: * the following numbers are composite: 1024, 4, 6, 9; * the following numbers are not composite: 13, 1, 2, 3, 37. You are given a positive integer n. Find two composite integers a,b such that a-b=n. I...
3
import sys import math input = sys.stdin.readline n=int(input()) print(9*n,8*n)
You are given an array a consisting of n integers. Initially all elements of a are either 0 or 1. You need to process q queries of two kinds: * 1 x : Assign to a_x the value 1 - a_x. * 2 k : Print the k-th largest value of the array. As a reminder, k-th largest value of the array b is defined as following: ...
3
size, requests = map(int, input().split()) one, zero = 0, 0 array = [] line = input().split() for i in line: array.append(int(i)) if int(i) == 1: one += 1 else: zero += 1 for i in range(requests): line = input().split() f, s = int(line[0]), int(line[1]) if f == 1: if ...
You are given a huge integer a consisting of n digits (n is between 1 and 3 β‹… 10^5, inclusive). It may contain leading zeros. You can swap two digits on adjacent (neighboring) positions if the swapping digits are of different parity (that is, they have different remainders when divided by 2). For example, if a = 032...
3
for _ in[0]*int(input()): l=x,y=[[],[]];i=j=0;r=[] for d in input():l[int(d)%2]+=d, x+=':',;y+=':', while x[i]+y[j]<'::': if x[i]<y[j]:r+=x[i],;i+=1 else:r+=y[j],;j+=1 print(''.join(r))
There are n pillars aligned in a row and numbered from 1 to n. Initially each pillar contains exactly one disk. The i-th pillar contains a disk having radius a_i. You can move these disks from one pillar to another. You can take a disk from pillar i and place it on top of pillar j if all these conditions are met: ...
3
n = int(input()) arr = list(map(int,input().split())) flag = False mx = arr.index(max(arr)) l1 = arr[:mx] l2 = arr[mx+1 : ] if sorted(l1) == arr[:mx] and sorted(l2 , reverse = True) == arr[mx+1 : ]: flag = True if flag == True: print('YES') else: print('NO')
Polycarp takes part in a quadcopter competition. According to the rules a flying robot should: * start the race from some point of a field, * go around the flag, * close cycle returning back to the starting point. Polycarp knows the coordinates of the starting point (x1, y1) and the coordinates of the poin...
3
x1,y1=map(int,input().split()) x2,y2=map(int,input().split()) d1=(abs(x1-x2)+1)*2 d2=(abs(y1-y2)+1)*2 if (x1==x2) or (y1==y2): print(d1+d2+2) else: print(d1+d2)
Polycarp loves ciphers. He has invented his own cipher called repeating. Repeating cipher is used for strings. To encrypt the string s=s_{1}s_{2} ... s_{m} (1 ≀ m ≀ 10), Polycarp uses the following algorithm: * he writes down s_1 ones, * he writes down s_2 twice, * he writes down s_3 three times, * ... ...
3
import sys n = int((sys.stdin.readline()).strip()) enc = (sys.stdin.readline()).strip() dec = [] i = 1 index = 0 while index<n: dec.append(enc[index]) index+=i i+=1 print("".join(dec))
The busses in Berland are equipped with a video surveillance system. The system records information about changes in the number of passengers in a bus after stops. If x is the number of passengers in a bus just before the current bus stop and y is the number of passengers in the bus just after current bus stop, the sy...
3
from itertools import accumulate n, w = map(int, input().split()) a = list(map(int, input().split())) s_a = [0] + list(accumulate(a)) mn, mx = min(s_a), max(s_a) mn_ = max(0, -mn) mx_ = w - mx if mx_ < 0 or mx_ < mn_ or mn_ > w or mx - mn > w or mx_ - mn_ > w or mn < -w or mx > w or min(a) < -w or max(a) > w: p...
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are r...
1
x,y = map(int, raw_input().split()) t = raw_input() count = (x-y) / 2 t = t.replace('(','', count) t = t.replace(')','', count) print t
Students in a class are making towers of blocks. Each student makes a (non-zero) tower by stacking pieces lengthwise on top of each other. n of the students use pieces made of two blocks and m of the students use pieces made of three blocks. The students don’t want to use too many blocks, but they also want to be uniq...
3
# ========= /\ /| |====/| # | / \ | | / | # | /____\ | | / | # | / \ | | / | # ========= / \ ===== |/====| # code def condn(x,n,m): return not ((x//2) >= n and (x//3) >= m and (x//2 + x//3 - x//6) >= (n+m)) if __name_...
The USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of n haybale piles on the farm. The i-th pile contains a_i haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an a...
3
t = int(input()) for _ in range(t): n, d = map(int, input().split()) a = list(map(int, input().split())) for j in range(0, d): i = 1 while i < n: if a[i] > 0: break i += 1 if i < n and a[i] > 0: a[i] -= 1 a[i - 1] += 1 ...
On one quiet day all of sudden Mister B decided to draw angle a on his field. Aliens have already visited his field and left many different geometric figures on it. One of the figures is regular convex n-gon (regular convex polygon with n sides). That's why Mister B decided to use this polygon. Now Mister B must find ...
3
import math from decimal import * n,a = map(int, input().split()) d = Decimal(180 / n) res = Decimal(181) for i in range(1, n-1): min = abs(Decimal(a - d*i)) if min < res: res = min k = i + 2 print("2 1 ", k, sep = '')
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('')) if(n%2==0 and n!=2): print('YES') else: print('NO')
There is a knight - the chess piece - at the origin (0, 0) of a two-dimensional grid. When the knight is at the square (i, j), it can be moved to either (i+1,j+2) or (i+2, j+1). In how many ways can the knight reach the square (X, Y)? Find the number of ways modulo 10^9 + 7. Constraints * 1 \leq X \leq 10^6 * 1 \l...
3
def s_comb(n,k): s=1 r=min(k,n-k) p=10**9+7 for c in range(r): s=(s*(n-c)*pow(c+1,p-2,p))%p return s x,y=map(int,input().split()) if (x+y)%3!=0 or 2*y<x or 2*x<y: print(0) else: r=min(2*y-x,2*x-y)//3 print(s_comb((x+y)//3,r))
Guy-Manuel and Thomas have an array a of n integers [a_1, a_2, ..., a_n]. In one step they can add 1 to any element of the array. Formally, in one step they can choose any integer index i (1 ≀ i ≀ n) and do a_i := a_i + 1. If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and T...
3
for _ in range(int(input())): n,c=int(input()),0 arr=list(map(int,input().split())) for i in range(n): if arr[i]==0: c+=1 arr[i]=1 if sum(arr)==0: c+=1 print(c)
There are n athletes in front of you. Athletes are numbered from 1 to n from left to right. You know the strength of each athlete β€” the athlete number i has the strength s_i. You want to split all athletes into two teams. Each team must have at least one athlete, and each athlete must be exactly in one team. You want...
3
t = int(input()) for i in range(t): n = int(input()) li = list(map(int, input().split())) li.sort() diff = 10000 for i in range(1,n): diff = min(diff, li[i]-li[i-1]) print(diff)
You have integer n. Calculate how many ways are there to fully cover belt-like area of 4n-2 triangles with diamond shapes. Diamond shape consists of two triangles. You can move, rotate or flip the shape, but you cannot scale it. 2 coverings are different if some 2 triangles are covered by the same diamond shape in ...
3
t = int(input()) y = [] for i in range(t): k = int(input()) y.append(k) for i in range(len(y)): z = y[i] print(z)
You are given a graph with n nodes and m directed edges. One lowercase letter is assigned to each node. We define a path's value as the number of the most frequently occurring letter. For example, if letters on a path are "abaca", then the value of that path is 3. Your task is find a path whose value is the largest. I...
3
'''from collections import defaultdict,deque import sys def beauty(n,m,s,x,y): q=deque() res=0 dg=[0 for i in range(n)] cnt=0 graph=defaultdict(list) for i in range(m): l,k=x[i],y[i] l=l-1 k=k-1 graph[l].append(k) dg[k]=dg[k]+1 mt=[[0 for i in range(2...
The School β„–0 of the capital of Berland has n children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value ti: * ti = 1, if the i-th child is good at programming, *...
3
n=int(input()) l=list(map(int,input().split())) a=[] b=[] c=[] x,y,z=0,0,0 for i in range(n): if(l[i]==1): x=x+1 a.append(i+1) elif(l[i]==2): y=y+1 b.append(i+1) elif(l[i]==3): z=z+1 c.append(i+1) m=min(x,z,y) if(m==0): print(0) else: print(m) for ...
Polycarp loves ciphers. He has invented his own cipher called repeating. Repeating cipher is used for strings. To encrypt the string s=s_{1}s_{2} ... s_{m} (1 ≀ m ≀ 10), Polycarp uses the following algorithm: * he writes down s_1 ones, * he writes down s_2 twice, * he writes down s_3 three times, * ... ...
3
n = int(input()) t = input() x = 0 y = 0 s = '' if n == 1: print(t) else: while y < n: s += t[y] x += 1 y += x print(s)
You have an array a of length n. For every positive integer x you are going to perform the following operation during the x-th second: * Select some distinct indices i_{1}, i_{2}, …, i_{k} which are between 1 and n inclusive, and add 2^{x-1} to each corresponding position of a. Formally, a_{i_{j}} := a_{i_{j}} + 2^{...
3
import sys readline = sys.stdin.readline T = int(readline()) Ans = [None]*T for qu in range(T): N = int(readline()) A = list(map(int, readline().split())) A = [10**9 + a for a in A] ctr = A[0] ans = 0 for i in range(1, N): a = A[i] if a >= ctr: ctr = a co...