problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
You are given an array a consisting of n integers a_1, a_2, ... , a_n. In one operation you can choose two elements of the array and replace them with the element equal to their sum (it does not matter where you insert the new element). For example, from the array [2, 1, 4] you can obtain the following arrays: [3, 4],...
3
import sys from collections import Counter def input(): return sys.stdin.readline().strip() def dinput(): return int(input()) def tinput(): return input().split() def rinput(): return map(int, tinput()) def main(): n = int(input()) a = rinput() s = 0 d = 0 f = 0 for val in a...
Phoenix has decided to become a scientist! He is currently investigating the growth of bacteria. Initially, on day 1, there is one bacterium with mass 1. Every day, some number of bacteria will split (possibly zero or all). When a bacterium of mass m splits, it becomes two bacteria of mass m/2 each. For example, a ba...
3
#!/usr/bin/python3 import sys readline = sys.stdin.readline ns = lambda: readline().rstrip() ni = lambda: int(readline().rstrip()) nm = lambda: map(int, readline().split()) nl = lambda: list(map(int, readline().split())) # def solve(): # n, x = nm() # d = nl()*2 # f = [x*(x+1)//2 for x in d] # for...
After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≀ si ≀ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum nu...
3
n=int(input()) lst=[int(i) for i in input().split()] hsh=[0,0,0,0,0] for i in lst: hsh[i]+=1 i=4 cnt=0 while i>0: if i==4: cnt+=hsh[i] elif i==3: if hsh[i]<=hsh[1]: cnt+=hsh[i] hsh[1]-=hsh[i] elif hsh[i]>hsh[1]: cnt+=hsh[i] hsh[1]=0 ...
You are given n strings. Each string consists of lowercase English letters. Rearrange (reorder) the given strings in such a way that for every string, all strings that are placed before it are its substrings. String a is a substring of string b if it is possible to choose several consecutive letters in b in such a way...
3
l=[] z=input for i in range(int(z())): l1=z() l.append([len(l1),l1]) l=sorted(l) x=l[0][1] c=0 d=1 for i in sorted(l): if x in i[1]: c+=1 x=i[1] else: d=0 break if d==1: print('YES') for i in l: print(i[1]) else: print('NO')
Skier rides on a snowy field. Its movements can be described by a string of characters 'S', 'N', 'W', 'E' (which correspond to 1 meter movement in the south, north, west or east direction respectively). It is known that if he moves along a previously unvisited segment of a path (i.e. this segment of the path is visite...
3
for _ in range(int(input())): visited = {} s = input() p1, p2, count, n = 0, 0, 0, len(s) for i in range(n): prev1, prev2 = p1, p2 if s[i] == 'N': p1 += 1 if s[i] == "S": p1 -= 1 if s[i] == "E": p2 += 1 if s[i] == "W": ...
Gotou just received a dictionary. However, he doesn't recognize the language used in the dictionary. He did some analysis on the dictionary and realizes that the dictionary contains all possible diverse words in lexicographical order. A word is called diverse if and only if it is a nonempty string of English lowercase...
1
import sys from collections import deque import copy import math def get_read_func(fileobject): if fileobject == None : return raw_input else: return fileobject.readline def is_tasai(S): appare_set = set([]) for s in S: if s in appare_set: return False appare...
There are n candies in a row, they are numbered from left to right from 1 to n. The size of the i-th candy is a_i. Alice and Bob play an interesting and tasty game: they eat candy. Alice will eat candy from left to right, and Bob β€” from right to left. The game ends if all the candies are eaten. The process consists o...
3
s=[] for jjk in range(int(input())): n=int(input()) q=list(map(int,input().split( ))) a=0 b=0 g=0 fa=0 fb=0 j=0 while len(q)!=0: if j%2==0: while fa<=fb and len(q)!=0: fa+=q[0] a+=q[0] del(q[0]) g+=1 ...
Devu is a dumb guy, his learning curve is very slow. You are supposed to teach him n subjects, the ith subject has ci chapters. When you teach him, you are supposed to teach all the chapters of a subject continuously. Let us say that his initial per chapter learning power of a subject is x hours. In other words he can...
1
n,x = map(int, raw_input().split()) c = map(int,raw_input().split()) c.sort() t = 0 for i in range(n): t += (c[i] * x) if x > 1: x -= 1 print t
Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus. She has n friends who are also grannies (Maria is not included in this number). The i-th granny is ready to attend the ceremony, provided that at the time of her appearance in t...
3
def main(): n = int(input()) a = sorted(map(int, input().split()), reverse=True) for i, b in enumerate(a): if b > n: n -= 1 else: print(n + 1) return print(1) for _ in range(int(input())): main()
Andre has very specific tastes. Recently he started falling in love with arrays. Andre calls an nonempty array b good, if sum of its elements is divisible by the length of this array. For example, array [2, 3, 1] is good, as sum of its elements β€” 6 β€” is divisible by 3, but array [1, 1, 2, 3] isn't good, as 7 isn't div...
3
import sys input=sys.stdin.readline from itertools import groupby R=lambda:map(int,input().split()) I=lambda:int(input()) S=lambda:input().rstrip('\n') L=lambda:list(R()) def HalfDead(): for _ in range(I()): a=[1]*I() print(*a) if __name__=='__main__': HalfDead()
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()) r=[2,1] for i in range(2,87): r.append(r[i-2]+r[i-1]) print(r[n])
Input The input contains a single integer a (0 ≀ a ≀ 35). Output Output a single integer. Examples Input 3 Output 8 Input 10 Output 1024
3
p = { 0: 4, 1: 1, 2: 3, 3: 2, 4: 0, 5: 5 } n = int(input()) res = 0 for i in range(6): if (n & (1 << i)): res |= (1 << p[i]) print(res)
You are locked in a room with a door that has a keypad with 10 keys corresponding to digits from 0 to 9. To escape from the room, you need to enter a correct code. You also have a sequence of digits. Some keys on the keypad have fingerprints. You believe the correct code is the longest not necessarily contiguous subse...
3
n, m = map(int, input().split()) x = input().split() y = input().split() x = [e for e in x if e in y] print(' '.join(x))
Write a program which solve a simultaneous equation: ax + by = c dx + ey = f The program should print x and y for given a, b, c, d, e and f (-1,000 ≀ a, b, c, d, e, f ≀ 1,000). You can suppose that given equation has a unique solution. Input The input consists of several data sets, 1 line for each data set. In a ...
3
import sys #from me.io import dup_file_stdin #@dup_file_stdin def solve(): for line in sys.stdin: a,b,c,d,e,f=map(float,line.split(' ')) print("{:.3f} {:.3f}".format((c*e-b*f)/(a*e-b*d)+0,(c*d-a*f)/(b*d-a*e)+0)) solve()
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...
1
numberOfStones = int(raw_input().strip()) listOfStones = list(raw_input().strip()) lastCharacter = listOfStones[0] count = 0 for character in listOfStones[1:]: if character == lastCharacter: count += 1 lastCharacter = character print count
Vanya walks late at night along a straight street of length l, lit by n lanterns. Consider the coordinate system with the beginning of the street corresponding to the point 0, and its end corresponding to the point l. Then the i-th lantern is at the point ai. The lantern lights all points of the street that are at the ...
3
a,b=map(int,input().split()) y=list(map(int,input().split())) y.sort() l=[] if (0 not in y) and (15 in y): l.append(y[0]) elif (0 in y) and (15 not in y): l.append(b-y[-1]) elif (0 not in y) and (15 not in y): l.append(y[0]) l.append(b-y[-1]) for i in range(len(y)-1): l.append((y[i+1]-y[i])/2) print...
Fox Ciel starts to learn programming. The first task is drawing a fox! However, that turns out to be too hard for a beginner, so she decides to draw a snake instead. A snake is a pattern on a n by m table. Denote c-th cell of r-th row as (r, c). The tail of the snake is located at (1, 1), then it's body extends to (1,...
3
s=input().split(' ') n=int(s[0]) m=int(s[1]) l=0 for k in range(n): if k%2==0: print('#'*m) else: if l%2==0: print(('.'*(m-1)+'#')) else: print('#'+('.'*(m-1))) l+=1
Drazil is playing a math game with Varda. Let's define <image> for positive integer x as a product of factorials of its digits. For example, <image>. First, they choose a decimal number a consisting of n digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then th...
3
n = input() F_a = input() mass_1 = [] mass_2 = [] mas = [] for i in F_a: mass_1.append(int(i)) for i in mass_1: if i == 2: mas = [2] if len(mass_2) > 0: for j in mas: flag = True for y in range(len(mass_2)): if j >= mass_2[y]: ...
Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is n. There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains 2 apartments, every other floor contains x apartments each. Apartments are numbered starting from one, from...
3
import sys import re import math count = 0 def solve(a, b): if a == 1 or a == 2: return 1 return math.ceil((a - 2) / b) + 1 for line in sys.stdin: if count == 0: count = 1 continue group_match = re.match('([0-9]+) ([0-9]+)', line) a, b = [int(group_match[i]) for i in ran...
Xenia lives in a city that has n houses built along the main ringroad. The ringroad houses are numbered 1 through n in the clockwise order. The ringroad traffic is one way and also is clockwise. Xenia has recently moved into the ringroad house number 1. As a result, she's got m things to do. In order to complete the i...
3
n, m = map(int, input().split()) s = map(int, input().split()) f = [1] f = f + list(s) d = 0 for i in range(m): if f[i]>f[i+1]: d += n + f[i+1] - f[i] elif f[i]<f[i+1]: d += f[i+1] - f[i] print(d)
Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to th...
3
numbers=[int(x) for x in input().split()] counters={} for n in numbers: if n in counters: counters[n]+=1 else: counters[n]=0 print (sum(counters.values()))
Sasha is a very happy guy, that's why he is always on the move. There are n cities in the country where Sasha lives. They are all located on one straight line, and for convenience, they are numbered from 1 to n in increasing order. The distance between any two adjacent cities is equal to 1 kilometer. Since all roads in...
3
import sys input = lambda: sys.stdin.readline().strip() inp = lambda: list(map(int,input().split())) n,k = inp() t = min(k,n-1) extra = 0 j = 2 for i in range(t+1,n): extra+=j j+=1 print(t+extra)
An n Γ— n table a is defined as follows: * The first row and the first column contain ones, that is: ai, 1 = a1, i = 1 for all i = 1, 2, ..., n. * Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the remaining elements are defin...
3
def factorial(n): if n==0: return 1 elif n==1: return 1 else: total=1 for x in range(1,n+1): total*=x return total def C(n,k): return int(float(factorial(n))/(float(factorial(n-k))*float(factorial(k)))) N=int(input("")) if N==1: print(1) else: ...
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it: * deletes all the vowels, * inserts a character "." before each consonant, * repl...
3
import sys s = sys.stdin.read().lower().strip() r = "" vowels = ["A", "E", "I", "O", "U", "a", "e", "i", "o", "u", "Y", "y"] for i in s: if not(i in vowels): r += "." + i print(r)
Polycarpus is a system administrator. There are two servers under his strict guidance β€” a and b. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program re...
3
n = int(input()) count_i_1=0 count_l_1=0 count_l_2=0 count_i_2=0 for i in range(n): t, x, y = input().split() t, x, y = int(t), int(x), int(y) if t == 1: count_i_1+=x count_l_1+=y else: count_i_2+=x count_l_2+=y if count_i_1>=count_l_1: print("LIVE") else: print(...
"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
(n,k)=map(int,input().split()) n=list(map(int,input().rstrip().split())) s,t,c=n[k-1],0,0 if s>0: t=n[::-1].index(s) print(len(n)-t) else: for i in n: if i>0: c+=1 else: break print(c) ...
Write a program which identifies the number of combinations of three integers which satisfy the following conditions: * You should select three distinct integers from 1 to n. * A total sum of the three integers is x. For example, there are two combinations for n = 5 and x = 9. * 1 + 3 + 5 = 9 * 2 + 3 + 4 = 9 Note...
1
import itertools a = [] while True: n = map(int, raw_input().split()) if n == [0, 0]: break a.append(n) for n in range(len(a)): x = 0 b = [] for m in range(a[n][0]): if m == range(a[n][0]): break b.append(m+1) c = list(itertools.combinations(b, 3)) for l in rang...
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
x=int(input()) y=list(map(int,input().split())) if not max(y)-min(y)==0: print(max(y)-min(y),y.count(max(y))*y.count(min(y))) else: print(0,int(len(y)/2*(len(y)-1)))
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory. George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living...
3
t=int(input()) c=0 for i in range(t): a,b=map(int,input().split()) if 2+a<=b: c+=1 print(c)
Polycarp is an organizer of a Berland ICPC regional event. There are n universities in Berland numbered from 1 to n. Polycarp knows all competitive programmers in the region. There are n students: the i-th student is enrolled at a university u_i and has a programming skill s_i. Polycarp has to decide on the rules now....
3
from math import * from collections import defaultdict as dt from sys import stdin inp = lambda : stdin.readline().strip()#input() I = lambda : int(inp())#int(input()) M = lambda : map(int,stdin.readline().split())#map(input()) L = lambda : list(map(int,stdin.readline().split()))#list(input()) mod = 1000000009 inf = 10...
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
year = int(input()) if year == 9000:print(9012) else: for i in range(year+1, 9013): if len(set(str(i)))==4: print(i) break
Let's denote correct match equation (we will denote it as CME) an equation a + b = c there all integers a, b and c are greater than zero. For example, equations 2 + 2 = 4 (||+||=||||) and 1 + 2 = 3 (|+||=|||) are CME but equations 1 + 2 = 4 (|+||=||||), 2 + 2 = 3 (||+||=|||), and 0 + 1 = 1 (+|=|) are not. Now, you ha...
3
#!/usr/bin/env python # coding: utf-8 # In[5]: q = int(input()) L = [] N = [] for i in range(q): L.append(int(input())) for j in L: if j%2 == 0: if j == 2: N.append(2) else: N.append(0) else: N.append(1) for i in N: print(i) # In[ ]:
The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her n students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often oddl...
1
def func(h): s = 0 for i in xrange(len(h)-1): s += h[i+1] - h[i] return s n, m = map(int, raw_input().split()) l = map(int, raw_input().split()) l.sort() mn = None for k in xrange(m-n+1): s = func(l[k:k+n]) if mn is None or s < mn: mn = s print mn
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob β€” to check his answers, he needs a program that among the given n numbers finds one that is di...
3
n = int(input()) even = 0 odd = 0 a = [] for x in input().split(): a.append(int(x)) if int(x)%2==0: even += 1 else: odd += 1 for i in range(n): if ((even == 1 and a[i]%2==0) or (odd == 1 and a[i]%2!=0)): print(i+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...
3
b = set(list(input())) if len(b)%2==0: print("CHAT WITH HER!") else: print("IGNORE HIM!")
Long time ago Alex created an interesting problem about parallelogram. The input data for this problem contained four integer points on the Cartesian plane, that defined the set of vertices of some non-degenerate (positive area) parallelogram. Points not necessary were given in the order of clockwise or counterclockwis...
1
a=map(int,raw_input().split()) b=map(int,raw_input().split()) c=map(int,raw_input().split()) d={} d[tuple([i+j-k for (i,j,k) in zip(a,b,c)])]=True d[tuple([i+j-k for (i,j,k) in zip(b,c,a)])]=True d[tuple([i+j-k for (i,j,k) in zip(c,a,b)])]=True print len(d) for x,y in d.keys(): print "%d %d" % (x,y)
Devu is a renowned classical singer. He is invited to many big functions/festivals. Recently he was invited to "All World Classical Singing Festival". Other than Devu, comedian Churu was also invited. Devu has provided organizers a list of the songs and required time for singing them. He will sing n songs, ith song wi...
1
import sys n,d = map(int,sys.stdin.readline().split()) l = list(map(int,sys.stdin.readline().split())) ans = sum(l)+ 10*(n-1) if ans > d: print -1 else: temp = d-ans print temp/5+2*(n-1)
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
x = input() y = input() if x.lower() > y.lower(): print("1") elif x.lower() < y.lower(): print("-1") else: print("0")
Once upon a time there was only one router in the well-known company Bmail. Years went by and over time new routers were purchased. Every time they bought a new router, they connected it to one of the routers bought before it. You are given the values p_i β€” the index of the router to which the i-th router was connected...
3
n = int(input()) s = list(map(int,input().split())) d = dict() for i in range(n-1): d[i+2] = s[i] l = n k = list() while(l>1): k.append(str(l)) l = d[l] k.append("1") k.reverse() print(" ".join(k))
There are n houses along the road where Anya lives, each one is painted in one of k possible colors. Anya likes walking along this road, but she doesn't like when two adjacent houses at the road have the same color. She wants to select a long segment of the road such that no two adjacent houses have the same color. H...
3
nk=input().split(" ") n=int(nk[0]) k=int(nk[1]) ar=input().split(" ") ar=list(filter(lambda x:x!='',ar)) c=1 mx=1 i=0 while i<n-1: if ar[i]!=ar[i+1]: c+=1 else: if c>mx: mx=c c=1 i+=1 if c>mx: mx=c print(mx)
Petya is having a party soon, and he has decided to invite his n friends. He wants to make invitations in the form of origami. For each invitation, he needs two red sheets, five green sheets, and eight blue sheets. The store sells an infinite number of notebooks of each color, but each notebook consists of only one co...
3
import sys import math import bisect def main(): n, k = map(int, input().split()) ans = math.ceil(n * 2 / k) + math.ceil(n * 5 / k) + math.ceil(n * 8 / k) print(ans) if __name__ == "__main__": main()
Bash wants to become a Pokemon master one day. Although he liked a lot of Pokemon, he has always been fascinated by Bulbasaur the most. Soon, things started getting serious and his fascination turned into an obsession. Since he is too young to go out and catch Bulbasaur, he came up with his own way of catching a Bulbas...
1
n=raw_input('') print min(n.count('B'),n.count('u')/2,n.count('l'),n.count('b'),n.count('a')/2,n.count('s'),n.count('r'),)
Ivan has a robot which is situated on an infinite grid. Initially the robot is standing in the starting cell (0, 0). The robot can process commands. There are four types of commands it can perform: * U β€” move from the cell (x, y) to (x, y + 1); * D β€” move from (x, y) to (x, y - 1); * L β€” move from (x, y) to (x...
3
n = int(input()) cur = {"U": 0, "D": 0, "L": 0, "R": 0} commands = input() for i in range(n): cur[commands[i]] += 1 print(min(cur["U"], cur["D"]) * 2 + min(cur["L"], cur["R"]) * 2)
Fukushima Prefecture is also famous for producing fruits, and among them, peaches and apples boast one of the highest production volumes in Japan. By the way, when I made a print manuscript of an English pamphlet for sale, I mistakenly wrote the description about apples and the description about peaches in reverse. Yo...
1
print raw_input().replace("apple","(").replace("peach","apple").replace("(","peach")
Polycarp has an array a consisting of n integers. He wants to play a game with this array. The game consists of several moves. On the first move he chooses any element and deletes it (after the first move the array contains n-1 elements). For each of the next moves he chooses any element with the only restriction: its...
3
''' ragi ''' n = int(input()) a = [int(x) for x in input().split()] odd = [] even = [] for elem in a: if elem & 1: odd.append(elem) else: even.append(elem) odd.sort() even.sort() req = min(len(odd),len(even)) len_odd = min(0,req-len(odd)) len_even = min(0,req-len(even)) while(req): odd....
A railroad running from west to east in Atcoder Kingdom is now complete. There are N stations on the railroad, numbered 1 through N from west to east. Tomorrow, the opening ceremony of the railroad will take place. On this railroad, for each integer i such that 1≀i≀N-1, there will be trains that run from Station i t...
3
N = int(int(input())) C_S_F = [list(map(int, input().split(" "))) for _ in range(N-1)] for i in range(N-1): time = 0 for j in range(i, N-1): c, s, f = C_S_F[j] time = max(s, time + abs(time%-f)) time += c print(time) print(0)
On a chessboard with a width of n and a height of n, rows are numbered from bottom to top from 1 to n, columns are numbered from left to right from 1 to n. Therefore, for each cell of the chessboard, you can assign the coordinates (r,c), where r is the number of the row, and c is the number of the column. The white ki...
3
n = int(input()) r,c = map(int,input().split()) w = min(r-1,c-1) + abs(r-c) b = min(n-r,n-c) + abs(r-c) if b < w : print("Black") else: print("White")
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
nh = input().split(" ") nh = [int(i) for i in nh] inp = input().split(" ") inp = [int(i) for i in inp] Weite = nh[0] for i in inp: if i>nh[1]: Weite +=1 print(Weite)
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
def main(): n, k, d = map(int, input().split()) l = list(map(int, input().split())) rez = d for i in range(n - d + 1): rez = min(rez, len(set(l[i:i+d]))) print(rez) t = int(input()) for i in range(t): main()
There are N apple trees in a row. People say that one of them will bear golden apples. We want to deploy some number of inspectors so that each of these trees will be inspected. Each inspector will be deployed under one of the trees. For convenience, we will assign numbers from 1 through N to the trees. An inspector ...
1
import math n,d=map(float,raw_input().split()) print int(math.ceil(n/(d+d+1)))
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms: 1. Make vi-th array element equal to xi. In other words, perform the assignment avi = xi. 2. Increase each array element by yi....
3
def main(): n, m = map(int, input().split()) aa = list(map(int, input().split())) delta, res = 0, [] for _ in range(m): l = list(map(int, input().split())) if l[0] == 1: aa[l[1] - 1] = (l[2], delta) elif l[0] == 2: delta += l[1] else: x...
It's time polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got down to business. In total, there are n tasks for the day and each animal should do each of these tasks. For each task, they have evaluated its difficulty. Also animals decided to do the tasks in order...
1
def f2(): from collections import Counter N = int(raw_input()) x = map(int, raw_input().split()) c = Counter(x) max_c = max(c.values()) if max_c == 1: print 'NO' elif max_c == 2: set_two = set() for k in c: if c[k] == 2 and len(set_two) < 2: ...
A burglar got into a matches warehouse and wants to steal as many matches as possible. In the warehouse there are m containers, in the i-th container there are ai matchboxes, and each matchbox contains bi matches. All the matchboxes are of the same size. The burglar's rucksack can hold n matchboxes exactly. Your task i...
3
carryingLimit,sacks = map(int,input().split()) warehouses,matches = [],0 for m in range(sacks): a,b = map(int,input().split()) warehouses.append((a,b)) warehouses.sort(key = lambda x: x[1],reverse = True) for j in range(sacks): mLeft = carryingLimit - warehouses[j][0] if mLeft >= 0: carryingLimi...
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s. You have to answer t independent test cases. Input The first line of the input co...
3
t = int(input()) from math import * for i in range(t): a,b = map(int, input().split(' ')) # print(a,b) k = a s = ceil(a /b) ans = b*s-a print(ans) # make a divisible by b.
The weather is fine today and hence it's high time to climb the nearby pine and enjoy the landscape. The pine's trunk includes several branches, located one above another and numbered from 2 to y. Some of them (more precise, from 2 to p) are occupied by tiny vile grasshoppers which you're at war with. These grasshoppe...
1
p, y = map(int, raw_input().split()) def isPrime(num): i=2 while i <= p and i*i <= num: if num%i == 0: return False i += 1 return True ans = -1 for i in xrange(y, p, -1): if isPrime(i): ans = i break print ans
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'...
3
n, m, a = list(map(int, input().split())) if m % a == 0: x = m // a else: x = m // a + 1 if n % a == 0: y = n // a else: y = n // a + 1 print(x * y)
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
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Nov 1 06:07:42 2020 @author: Error """ def solve(n, heights): maxVal = heights[0] maxValIdx = 0 minVal = heights[n-1] minValIdx = n-1 for i in range(n): if heights[i] > maxVal: maxVal = heights[i] ...
The only difference between easy and hard versions is the number of elements in the array. You are given an array a consisting of n integers. In one move you can choose any a_i and divide it by 2 rounding down (in other words, in one move you can set a_i := ⌊(a_i)/(2)βŒ‹). You can perform such an operation any (possibl...
3
""" NTC here """ from sys import setcheckinterval,stdin setcheckinterval(1000) #print("Case #{}: {} {}".format(i, n + m, n * m)) iin=lambda :int(stdin.readline()) lin=lambda :list(map(int,stdin.readline().split())) from collections import defaultdict n,k=lin() a=lin() a.sort() sol=[[0,0] for i in range(2*10**5+1)] fo...
An n Γ— n table a is defined as follows: * The first row and the first column contain ones, that is: ai, 1 = a1, i = 1 for all i = 1, 2, ..., n. * Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the remaining elements are defin...
3
n = int(input()) a = [] m = 0 for i in range(n): a.append([1] * n) for i in range(n): for j in range(n): if i > 0 and j > 0: a[i][j] = a[i][j - 1] + a[i - 1][j] for i in range(n): for j in range(n): if a[i][j] > m: m = a[i][j] print(m)
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line. Unfortunately, from time to ti...
3
print(len([i for i in list(set(input().replace('{', '').replace('}', '').split(', '))) if i != '']))
You're given two arrays a[1 ... n] and b[1 ... n], both of the same length n. In order to perform a push operation, you have to choose three integers l, r, k satisfying 1 ≀ l ≀ r ≀ n and k > 0. Then, you will add k to elements a_l, a_{l+1}, …, a_r. For example, if a = [3, 7, 1, 4, 1, 2] and you choose (l = 3, r = 5, ...
3
""" NTC here """ from sys import stdin def iin(): return int(stdin.readline()) def lin(): return list(map(int, stdin.readline().split())) # range = xrange # input = raw_input def main(): t=iin() while t: t-=1 n=iin() a=lin() b=lin() ans='YES' i=0 ...
Orac is studying number theory, and he is interested in the properties of divisors. For two positive integers a and b, a is a divisor of b if and only if there exists an integer c, such that aβ‹… c=b. For n β‰₯ 2, we will denote as f(n) the smallest positive divisor of n, except 1. For example, f(7)=7,f(10)=2,f(35)=5. ...
3
t = int(input()) def min_v(a): for i in range(2, a + 1): if a % i == 0: return i for q in range(t): n, k = map(int, input().split()) res = 0 n += min_v(n) n += 2 * (k - 1) print(n)
The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: * d1 is the distance between the 1-st and the 2-nd station; * d2 is the distance between the 2-nd and the 3-rd station; ... * dn - 1 is the distance between the n - 1-th and the n-th station; ...
3
d = int(input()) sum_1 = 0 sum_2 = 0 a = input().split() i = 0 while i < d: a[i] = int(a[i]) i = i + 1 s, t = input().split() s = int(s) t = int(t) i = 1 while i < min(s, t): sum_1 += a[i-1] i += 1 i = max(s, t) while i <= d: sum_1 += a[i-1] i = i + 1 i = min(s, t) while i < max(s, t): ...
You're given an array a. You should repeat the following operation k times: find the minimum non-zero element in the array, print it, and then subtract it from all the non-zero elements of the array. If all the elements are 0s, just print 0. Input The first line contains integers n and k (1 ≀ n,k ≀ 10^5), the length ...
3
n,k=map(int,input().strip().split()) v = list(map(int,input().strip().split())) v.sort() sub = 0 i = 0 while k: if(i>=n): a=0 k-=1 print(a) else: a = v[i]-sub sub=v[i] if(a>0): print(a) k-=1 i+=1
Kirito is stuck on a level of the MMORPG he is playing now. To move on in the game, he's got to defeat all n dragons that live on this level. Kirito and the dragons have strength, which is represented by an integer. In the duel between two opponents the duel's outcome is determined by their strength. Initially, Kirito'...
3
from operator import itemgetter dragons = list(); boolean = list(); answer = 'YES'; first = input().split(); s=int(first[0]); n= int(first[1]); for j in range(n): jth = input().split(); dragons.append([int(jth[0]), int(jth[1])]); boolean.append(True); dragons.sort(key=itemgetter(0)); dragons.sort(key=item...
A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters Β«+Β» and Β«1Β» into this sequence. For example, sequences Β«(())()Β», Β«()Β» and Β«(()(()))Β» are regular, while Β«)(Β», Β«(()Β» and Β«(()))(Β» are not. One day Johnny got bracket sequence. He decided to remove some...
1
c, r = 0, 0 for x in raw_input(): if x == '(': c += 1 elif c: c -= 1 r += 2 print r
You are given n strings. Each string consists of lowercase English letters. Rearrange (reorder) the given strings in such a way that for every string, all strings that are placed before it are its substrings. String a is a substring of string b if it is possible to choose several consecutive letters in b in such a way...
3
def cmp(a): return len(a) n = int(input()) v = [""] * n for i in range(n): v[i] = input() v = sorted(v, key=cmp) ans = True for i in range(n - 1): sf = v[i] sl = v[i + 1] flag = False for j in range(len(sl) - len(sf) + 1): if sl[j:j + len(sf)] == sf: flag = True ...
As it's the first of April, Heidi is suspecting that the news she reads today are fake, and she does not want to look silly in front of all the contestants. She knows that a newspiece is fake if it contains heidi as a subsequence. Help Heidi assess whether the given piece is true, but please be discreet about it... In...
3
s = input() a, b, c = "heidi", "", 0 for i in s: if c < 5 and i == a[c]: b += i c += 1 print("YES" if a == b else "NO")
Given a sequence of numbers a1, a2, a3, ..., an, find the maximum sum of a contiguous subsequence of those numbers. Note that, a subsequence of one element is also a contiquous subsequence. Input The input consists of multiple datasets. Each data set consists of: n a1 a2 . . an You can assume that 1 ≀ n ≀ 5000 ...
3
while(1): N = int(input()) if N==0: break sums = [] nums = [] s = 0 for i in range(N): n = int(input()) nums.append(n) s += n if s<0: s=0 sums.append(s) if max(nums) >= 0: print(max(sums)) else: print(max(nums))
There are b boys and g girls participating in Olympiad of Metropolises. There will be a board games tournament in the evening and n participants have accepted the invitation. The organizers do not know how many boys and girls are among them. Organizers are preparing red badges for girls and blue ones for boys. Vasya ...
3
b=int(input()) r=int(input()) n=int(input()) print(n+1-max(0,n-r)-max(0,n-b))
There is a game called "I Wanna Be the Guy", consisting of n levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game. Little X can pass only p levels of the game. And Little Y can pass only q levels of the game. You are given the indices of levels Little X can pass ...
1
levels = int(input()) p = map(int, raw_input().split()) q = map(int, raw_input().split()) p.pop(0) q.pop(0) x = 0 for i in range(1, levels+1): if i not in p and i not in q: x = 1 if x ==1: print 'Oh, my keyboard!' else: print 'I become the guy.'
Little C loves number Β«3Β» very much. He loves all things about it. Now he has a positive integer n. He wants to split n into 3 positive integers a,b,c, such that a+b+c=n and none of the 3 integers is a multiple of 3. Help him to find a solution. Input A single line containing one integer n (3 ≀ n ≀ 10^9) β€” the integ...
3
n=int(input()) if (n-2) % 3==0: print('1 2 '+str(n-3)) else: print('1 1 '+str(n-2))
Lee is going to fashionably decorate his house for a party, using some regular convex polygons... Lee thinks a regular n-sided (convex) polygon is beautiful if and only if he can rotate it in such a way that at least one of its edges is parallel to the OX-axis and at least one of its edges is parallel to the OY-axis a...
3
T = int(input()) for t in range(T): n = int(input()) if n % 4 == 0: print("YES") else: print("NO")
Ehab loves number theory, but for some reason he hates the number x. Given an array a, find the length of its longest subarray such that the sum of its elements isn't divisible by x, or determine that such subarray doesn't exist. An array a is a subarray of an array b if a can be obtained from b by deletion of several...
1
for _ in range(input()): n,x=map(int,raw_input().split()) a=map(int,raw_input().split()) sm=0 cnt=[] h=0 for i in a: sm+=i if i%x!=0: cnt.append(h) h+=1 if sm%x!=0: print n else: if len(cnt)==0: print -1 else: ...
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
count = int(input()) for i in range(count): n, m = map(int, input().split(' ')) list_n = list(map(int, input().split(' '))) list_m = list(map(int, input().split(' '))) for j in range(n): if(list_n[j] in list_m): print('YES') print(1, list_n[j]) break else:...
There are two popular keyboard layouts in Berland, they differ only in letters positions. All the other keys are the same. In Berland they use alphabet with 26 letters which coincides with English alphabet. You are given two strings consisting of 26 distinct letters each: all keys of the first and the second layouts i...
3
def isConvertible(s): while True: try: int(s) return True except ValueError: return False def FindPos(item, p): for i in range(len(p)): if item.lower() == p[i] or item.upper() == p[i]: return i return 0 def solve(s1, s2, s3): r = "" for x in s3: if isConvertible(x...
You have an integer variable x. Initially, x=0. Some person gave you a string S of length N, and using the string you performed the following operation N times. In the i-th operation, you incremented the value of x by 1 if S_i=`I`, and decremented the value of x by 1 if S_i=`D`. Find the maximum value taken by x duri...
3
input() x,mx=0,0 for w in input(): #print(w) x+=1 if w=='I' else -1 mx = max(x,mx) print(mx)
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it: * deletes all the vowels, * inserts a character "." before each consonant, * repl...
1
s = raw_input() ans = [] for i in s.lower(): if i in "aeiouy": continue ans.append('.') ans.append(i) print "".join(ans)
Mishka started participating in a programming contest. There are n problems in the contest. Mishka's problem-solving skill is equal to k. Mishka arranges all problems from the contest into a list. Because of his weird principles, Mishka only solves problems from one of the ends of the list. Every time, he chooses whic...
3
rd = lambda: list(map(int, input().split())) n, k = rd() a = rd() L = 0 r = n - 1 ans = 0 while L < n - 1: if a[L] > k: break L += 1 ans += 1 while r >= 0 and r >= L: if a[r] > k: break ans += 1 r -= 1 print(ans)
There are n knights sitting at the Round Table at an equal distance from each other. Each of them is either in a good or in a bad mood. Merlin, the wizard predicted to King Arthur that the next month will turn out to be particularly fortunate if the regular polygon can be found. On all vertices of the polygon knights ...
1
n = input() kts = map(int, raw_input().split()) can = False for i in xrange(1,n/3+1): if n%i != 0: continue for j in xrange(i): can = True for k in xrange(0,n,i): if(kts[k+j] == 0): can = False break if(can): print "YES" break if can: break if not can: print "NO"
You are given a set of 2n+1 integer points on a Cartesian plane. Points are numbered from 0 to 2n inclusive. Let P_i be the i-th point. The x-coordinate of the point P_i equals i. The y-coordinate of the point P_i equals zero (initially). Thus, initially P_i=(i,0). The given points are vertices of a plot of a piecewis...
3
import math n, k = map(int, input().split()) if(k%n == 0): print(k//n) else: print(k//n +1)
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
len_line = int(input()) line = list(map(int, input().split())) b = [1] for i in range(len_line - 1): if line[i] <= line[i + 1]: b.append(b[i] + 1) else: b.append(1) print(max(b))
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from 1 to n. For every edge e of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge e (and only this edge) is...
1
def main(): n = int(raw_input()) a = [map(int, raw_input().split()) for _ in xrange(n - 1)] for x in a: if max(x) != n: print "NO" return a = [min(x) for x in a] c = [0] * n for x in a: c[x] += 1 s = 0 for i in xrange(n): s += c[i] ...
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line. Unfortunately, from time to ti...
3
a=list(input()) alpha=[0]*26 i=1 if(len(a)>2): while(i<len(a)): alpha[ord(a[i])-97]+=1 i+=3 print(26-alpha.count(0)) else: print(0)
There are n students in the first grade of Nlogonia high school. The principal wishes to split the students into two classrooms (each student must be in exactly one of the classrooms). Two distinct students whose name starts with the same letter will be chatty if they are put in the same classroom (because they must ha...
3
n=int(input()) d={} for i in range(n): s=input() if d.get(s[0])==None:d[s[0]]=0 d[s[0]]+=1 res=0 for i,x in enumerate(d): if d[x]>2: y=d[x] d1,d2,m=y//2,y//2,y%2 if m==1:d2+=1 if d1>1:res+=((d1-1)*d1//2) if d2>1:res+=((d2-1)*d2//2) print(res)
Input The input contains a single integer a (1 ≀ a ≀ 40). Output Output a single string. Examples Input 2 Output Adams Input 8 Output Van Buren Input 29 Output Harding
3
lis=[0,1,1,1,2,1,2,1,5,2,2,1,5,1,2,1,14,1,5,1,5,2,2,1,15,2,2,5,4,1,4,1,51,1,2,1,14,1,2,2,14,1,6,1,4,2,2,1,52,2,5,1,5,1,15,2,13,2,2,1,13,1,2,4,267,1,4,1,5,1,4,1,50,1,2,3,4,1,6,1,52,15,2,1,15,1,2,1,12,1,10,1,4,2] print(lis[int(input())])
You are given a deck of n cards numbered from 1 to n (not necessarily in this order in the deck). You have to sort the deck by repeating the following operation. * Choose 2 ≀ k ≀ n and split the deck in k nonempty contiguous parts D_1, D_2,..., D_k (D_1 contains the first |D_1| cards of the deck, D_2 contains the f...
3
n = int(input()) c = [int(x) for x in input().split()] solved = c.copy() solved.sort() ans = [] for i in range(1, n): for j in range(1, n): a = c.index(j) b = c.index(j+1) z = b+1 if b > a: if a+1 == b and a == solved: break continue ...
You are given a string S of length N consisting of lowercase English letters. We will cut this string at one position into two strings X and Y. Here, we would like to maximize the number of different letters contained in both X and Y. Find the largest possible number of different letters contained in both X and Y when ...
3
n=int(input()) s=input() ans=0 for i in range(1,n-1): ans=max(ans,len(set(list(s[:i]) )&set(list(s[i:])) )) print(ans)
The developers of Looksery have to write an efficient algorithm that detects faces on a picture. Unfortunately, they are currently busy preparing a contest for you, so you will have to do it for them. In this problem an image is a rectangular table that consists of lowercase Latin letters. A face on the image is a 2 ...
3
a , b = map(int , input().split()) arr = ["x" * (b+2)] r = lambda : list(map(int, input().split())) c = 0 for i in range(a): arr.append('x' + input() + 'x') arr.append("x"*(b+2)) # print(arr) valid = list("acef") for i in range(1,a+1): for j in range(1,b+1): ff = arr[i][j] + arr[i+1][j] + arr[i][j+1] + ...
Vasya came up with a password to register for EatForces β€” a string s. The password in EatForces should be a string, consisting of lowercase and uppercase Latin letters and digits. But since EatForces takes care of the security of its users, user passwords must contain at least one digit, at least one uppercase Latin l...
1
from string import lowercase, uppercase for i in range(input()): s = raw_input() lowerind, upperind, numind = 0, 0, 0 lowercnt, uppercnt, numcnt = 0, 0, 0 for i in range(1, len(s) + 1): if s[i-1] in lowercase: lowerind = i lowercnt += 1 elif s[i-1] in uppercase: upperind = i uppercnt += 1 else: ...
Inna is a great piano player and Dima is a modest guitar player. Dima has recently written a song and they want to play it together. Of course, Sereja wants to listen to the song very much. A song is a sequence of notes. Dima and Inna want to play each note at the same time. At that, they can play the i-th note at vo...
3
num = int(input()) arr_a = list(map(int,(input()).split())) arr_b = list(map(int,(input()).split())) joy = 0 for i in range(num): if arr_b[i] == 1: joy -= 1 continue if arr_a[i] * 2 >= arr_b[i]: temp = arr_b[i] // 2 joy = joy + temp * (arr_b[i] - temp) else: joy -= 1 ...
Drazil is playing a math game with Varda. Let's define <image> for positive integer x as a product of factorials of its digits. For example, <image>. First, they choose a decimal number a consisting of n digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then th...
3
mod = 1000000007 ii = lambda : int(input()) si = lambda : input() dgl = lambda : list(map(int, input())) f = lambda : map(int, input().split()) il = lambda : list(map(int, input().split())) ls = lambda : list(input()) n = ii() l = ['', '', '2', '3', '322', '5', '53', '7', '7222', '7332'] s = si() ans='' for i in s: ...
Moscow is hosting a major international conference, which is attended by n scientists from different countries. Each of the scientists knows exactly one language. For convenience, we enumerate all languages of the world with integers from 1 to 109. In the evening after the conference, all n scientists decided to go to...
3
import sys if __name__ == "__main__": n = int(sys.stdin.readline()) a = [int(i) for i in sys.stdin.readline().strip().split()] m = int(sys.stdin.readline()) b = [int(i) for i in sys.stdin.readline().strip().split()] c = [int(i) for i in sys.stdin.readline().strip().split()] lang_cnt = {} ...
There are n cards (n is even) in the deck. Each card has a positive integer written on it. n / 2 people will play new card game. At the beginning of the game each player gets two cards, each card is given to exactly one player. Find the way to distribute cards such that the sum of values written of the cards will be ...
3
n = int(input()) vec = list(map(int, input().split())) ans = list() for i in range(n) : tmp_list = list() tmp_list.append(vec[i]) tmp_list.append(i+1) ans.append(tmp_list) ans = sorted(ans) for i in range(n//2): print(ans[i][1] , ans[-(i+1)][1])
Orac is studying number theory, and he is interested in the properties of divisors. For two positive integers a and b, a is a divisor of b if and only if there exists an integer c, such that aβ‹… c=b. For n β‰₯ 2, we will denote as f(n) the smallest positive divisor of n, except 1. For example, f(7)=7,f(10)=2,f(35)=5. ...
3
# cook your dish here t=int(input()) i=0 for i in range(t): var=0 n,k=map(int,input().split()) for i in range(2,n+1): if n%i==0: var=i break var+=n ans=(k-1)*2+var print(ans)
Mary has just graduated from one well-known University and is now attending celebration party. Students like to dream of a beautiful life, so they used champagne glasses to construct a small pyramid. The height of the pyramid is n. The top level consists of only 1 glass, that stands on 2 glasses on the second level (co...
3
def push(graph, pos, level): if graph[pos] > 1: over = graph[pos] - 1 graph[pos] = 1 if level + pos < numberofglasses: graph[level + pos] += over / 2 if level + pos + 1 < numberofglasses: graph[level + pos + 1] += over / 2 if level + pos < numberofglas...
Today Patrick waits for a visit from his friend Spongebob. To prepare for the visit, Patrick needs to buy some goodies in two stores located near his house. There is a d1 meter long road between his house and the first shop and a d2 meter long road between his house and the second shop. Also, there is a road of length ...
3
p, q, r = map(int, input().split()) print(min(p+q+r,2*(p+q),2*(p+r),2*(q+r)))
Koa the Koala and her best friend want to play a game. The game starts with an array a of length n consisting of non-negative integers. Koa and her best friend move in turns and each have initially a score equal to 0. Koa starts. Let's describe a move in the game: * During his move, a player chooses any element of...
3
t = int(input()) import math for _ in range(t): n = int(input()) arr = list(map(int,input().strip().split()))[:n] a = max(arr) if a == 0: k = 0 else: k = int(math.log2(a))+1 flag = 0 for i in range(k,-1,-1): x = 0;y = 0;f = 1<<i for num in arr: ...
Iahub got bored, so he invented a game to be played on paper. He writes n integers a1, a2, ..., an. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices i and j (1 ≀ i ≀ j ≀ n) and flips all values ak for which their positions are in range [i, j] (that is i ≀ k ≀ j)...
1
n = int(raw_input()) a = list(map(int,raw_input().split())) lostones = 0 gainedones = 0 started = False ones = 0 for i in range(n): if a[i]==1: ones+=1 ans = ones if ones == n: print n-1 exit() for i in range(n): if a[i]==1: if not started: continue else: ...
A TV show called "Guess a number!" is gathering popularity. The whole Berland, the old and the young, are watching the show. The rules are simple. The host thinks of an integer y and the participants guess it by asking questions to the host. There are four types of acceptable questions: * Is it true that y is stric...
3
n=int(input()) l1=[-2*(10**9),2*(10**9)] for i in range(n): inp=list(input().split()) if inp[0]=='>': x=int(inp[1]) if inp[2]=='Y': l1[0]=max(l1[0],x+1) else : l1[1]=min(l1[1],x) elif inp[0]=='<': x=int(inp[1]) if inp[2]=='N': l1[0]...