problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
Navi got a task at school to collect N stones. Each day he can collect only one stone. As N can be a very large number so it could take many days to complete the task, but then he remembers that his mother gave him a magic that can double anything (i.e if he has 2 stones, the magic will make them to 4 stones). Navi ...
1
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' t = int(raw_input()) for _ in range(t): n = int(raw_input()) d = 0 while(n): n = n & (n-1) d += 1 print d
Arkady coordinates rounds on some not really famous competitive programming platform. Each round features n problems of distinct difficulty, the difficulties are numbered from 1 to n. To hold a round Arkady needs n new (not used previously) problems, one for each difficulty. As for now, Arkady creates all the problems...
1
n,m = map(int, raw_input().split()) a = [int(x) for x in raw_input().split()] d = [0]*100005 i = 0 c = set([]) j = "" k = 0 while i < m: c.add(a[i]) d[a[i]] = d[a[i]] + 1 if len(c) == n: j = j + '1' j1 = 0 c = list(c) k = 0 while j1 < len(c) + k: d[c[j1]] = d[c[j1]] - 1 if d[c[j1]...
There is a very secret base in Potatoland where potato mash is made according to a special recipe. The neighbours from Porridgia decided to seize this recipe and to sell it to Pilauland. For this mission they have been preparing special agent Pearlo for many years. When, finally, Pearlo learned all secrets of espionage...
1
# 12.A import sys def main(): a = sys.stdin.readline().strip() b = sys.stdin.readline().strip() c = sys.stdin.readline().strip() if a[0] == c[2] and a[1] == c[1] and a[2] == c[0] and b[0] == b[2]: print 'YES' else: print 'NO' if len (sys.argv) > 1: sys.stdin = open (sys.argv[1], 'r') main()
Petya loves lucky numbers. Everybody knows that positive integers are lucky if their decimal representation doesn't contain digits other than 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Lucky number is super lucky if it's decimal representation contains equal amount of digits 4 and 7. Fo...
1
def genmax(n): res = '' for i in range(0,n/2): res+='7' for i in range(0,n/2): res+='4' return res def genmin(n): res = '' for i in range(0,n/2): res+='4' for i in range(0,n/2): res+='7' return res if __name__ == "__main__": inp = raw_input() re...
Alice has a string s. She really likes the letter "a". She calls a string good if strictly more than half of the characters in that string are "a"s. For example "aaabb", "axaa" are good strings, and "baca", "awwwa", "" (empty string) are not. Alice can erase some characters from her string s. She would like to know wh...
3
from collections import Counter s = input() d = Counter(s) c = 0 #print(d['a']) #print(d) for i in d: if i == 'a': continue c = c+d[i] #print(c) if c < d['a']: print(len(s)) elif c == d['a']: print(len(s)-1) else: print(len(s)-(c-d['a'])-1)
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them. Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain nu...
3
str1 = input() str2 = str1.replace("WUB"," ") str2.strip() print(" ".join(str2.split()))
We will consider the numbers a and b as adjacent if they differ by exactly one, that is, |a-b|=1. We will consider cells of a square matrix n × n as adjacent if they have a common side, that is, for cell (r, c) cells (r, c-1), (r, c+1), (r-1, c) and (r+1, c) are adjacent to it. For a given number n, construct a squar...
3
def notYourMatrix(n): if n == 2: return [[-1]] l=[[0 for i in range(n)] for j in range(n)] r=0 s=0 p=0 dir =1 for i in range(1,n*n+1): l[r][s]=i if r == n-1 or s == n-1: if dir ==0: r = p s = 0 dir =1 ...
Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects must be strictly greater alphabetically than x (read statement for better understanding). You can make hacks in these problems independently. Koa the Koala has two...
3
def dfs(u):V[u]=0;return sum(dfs(v)for v in g[u]if V[v])+1 I=input for _ in[0]*int(I()): I();V=[1]*117;g=[[]for _ in V];f=0 for x,y in{*zip(map(ord,I()),map(ord,I()))}:f|=x>y;g[x]+=y,;g[y]+=x, print((sum(dfs(i)-1for i in range(117)if V[i]),-1)[f])
Mishka got a six-faced dice. It has integer numbers from 2 to 7 written on its faces (all numbers on faces are different, so this is an almost usual dice). Mishka wants to get exactly x points by rolling his dice. The number of points is just a sum of numbers written at the topmost face of the dice for all the rolls M...
3
t = int(input()) for i in range(t): x = int(input()) ans = x//7+1 print(ans)
A penguin Rocher has n sticks. He has exactly one stick with length i for all 1 ≤ i ≤ n. He can connect some sticks. If he connects two sticks that have lengths a and b, he gets one stick with length a + b. Two sticks, that were used in the operation disappear from his set and the new connected stick appears in his se...
1
FAST_IO = 0 if FAST_IO: import io, sys, atexit rr = iter(sys.stdin.read().splitlines()).next sys.stdout = _OUTPUT_BUFFER = io.BytesIO() @atexit.register def write(): sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) else: rr = raw_input rri = lambda: int(rr()) rrm = lambda: map(int, rr().s...
This is an easy version of the problem. The actual problems are different, but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different. You are given a string s consisting of n lowercase Latin letters. You have to color all its characters one of the two ...
3
import io import os from collections import Counter, defaultdict, deque def solve(N, S): # Same color must be already sorted since they can't be swapped with each other # Greedily build increasing subsequences indices = [[0]] # last value -> which list for i, x in enumerate(S[1:], 1): for...
It's one more school day now. Sasha doesn't like classes and is always bored at them. So, each day he invents some game and plays in it alone or with friends. Today he invented one simple game to play with Lena, with whom he shares a desk. The rules are simple. Sasha draws n sticks in a row. After that the players tak...
3
n,k=[int(i) for i in input().split(' ')] if((n//k)%2==0): print("NO") else: print("YES")
The grandest stage of all, Wrestlemania XXX recently happened. And with it, happened one of the biggest heartbreaks for the WWE fans around the world. The Undertaker's undefeated streak was finally over. Now as an Undertaker fan, you're disappointed, disheartened and shattered to pieces. And Little Jhool doesn't wan...
1
class Solution(object): def __init__(self, arr): self.arr = [] for i in xrange(0, len(arr)): self.arr.append(arr[i]) def rip_21_1(self): for i in xrange(0, len(self.arr)): if int(self.arr[i]) % 21 == 0: ...
There is a special offer in Vasya's favourite supermarket: if the customer buys a chocolate bars, he or she may take b additional bars for free. This special offer can be used any number of times. Vasya currently has s roubles, and he wants to get as many chocolate bars for free. Each chocolate bar costs c roubles. He...
3
def main(): number = int(input()) main_ls = list() for _ in range(1, number + 1): ls = list(map(int, input().split())) main_ls.append(ls) for i in range(0, number): s = main_ls[i][0] a = main_ls[i][1] b = main_ls[i][2] c = main_ls[i][3] raz = int(s...
Mr. Santa asks all the great programmers of the world to solve a trivial problem. He gives them an integer m and asks for the number of positive integers n, such that the factorial of n ends with exactly m zeroes. Are you among those great programmers who can solve this problem? Input The only line of input contains ...
1
n = int(raw_input()) c = 0 for i in range(1, 1000000): tmp = i while tmp % 5 == 0: tmp /= 5 c += 1 if c < n: continue if c == n: print "5" for j in range(i, i + 5): print j, " " if c > n: print 0 break
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
count=0 nums = int(input()) for i in range(nums): a, b = map(int, input().split(' ')) if b-a>=2: count +=1 print(count)
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={} for i in range(n): a[i]=[1] for i in range(n-1): a[0].append(1) i=1 while i<n: for j in range(1,n): t=a[i][j-1]+a[i-1][j] a[i].append(t) i=i+1 print(a[n-1][n-1])
Olga came to visit the twins Anna and Maria and saw that they have many cookies. The cookies are distributed into bags. As there are many cookies, Olga decided that it's no big deal if she steals a bag. However, she doesn't want the sisters to quarrel because of nothing when they divide the cookies. That's why Olga wan...
1
r=raw_input;r();a=map(int,r().split());print sum(1^sum(a)-i&1for i in a)
Given is a string S consisting of lowercase English letters. Find the maximum positive integer K that satisfies the following condition: * There exists a partition of S into K non-empty strings S=S_1S_2...S_K such that S_i \neq S_{i+1} (1 \leq i \leq K-1). Here S_1S_2...S_K represents the concatenation of S_1,S_2,....
3
S=input() ans = 0 prev = '' temp = '' for c in S: temp += c if temp != prev: ans += 1 prev = temp temp = '' print(ans)
While playing with geometric figures Alex has accidentally invented a concept of a n-th order rhombus in a cell grid. A 1-st order rhombus is just a square 1 × 1 (i.e just a cell). A n-th order rhombus for all n ≥ 2 one obtains from a n-1-th order rhombus adding all cells which have a common side with it to it (look ...
3
n=int(input()) count =0 fcount=0 for i in range(1,n+1): if i==n: fcount+=2*i-1 fcount+=2*count break count +=2*i-1 print(fcount)
Kilani is playing a game with his friends. This game can be represented as a grid of size n × m, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell). The game is played in rounds. In each round players expand turn by turn: firstly, t...
3
from collections import deque n,m,p = map(int, input().split()) spd = list(map(int, input().split())) spd.insert(0,-1) d = {'.': 0, '#': -1} d.update({str(v) : v for v in range(1, p + 1)}) g = [[d[c] for c in input().strip()] for _ in range(n)] h = [0 for i in range(10)] dist = [[[9999999 for _ in range(m)] for _ i...
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 = list(map(int, input().split())) a = list(map(int, input().split())) loc=1 ans=0 for now in a: if(now >= loc): ans += now - loc else: ans += n - (loc - now) loc = now print(ans)
You have a large electronic screen which can display up to 998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 7 segments which can be turned on and off to compose different digits. The following picture describes how you can dis...
3
""" 0 -> 6 1 -> 2 2 -> 5 3 -> 5 4 -> 4 5 -> 5 6 -> 6 7 -> 3 8 -> 7 9 -> 6 """ vec = [6, 2, 5, 5, 4, 5, 6, 3, 7, 6] # 0, 1, 2, 3, 4,5 ,6 ,7 , 8, 9 # 2, 3, 4, 5, 6, 7 # 2, 4, 5, 3, 7, 6 """ val = 25 25 / 7 10 palos 11111 """ # arr = [] # contador = 0 # while (contador<=1000000000): # str_n = str(contador)...
You are given a string S. Takahashi can insert the character `A` at any position in this string any number of times. Can he change S into `AKIHABARA`? Constraints * 1 \leq |S| \leq 50 * S consists of uppercase English letters. Input Input is given from Standard Input in the following format: S Output If it i...
3
s = input() if len(s) < 5: print("NO") exit() for i in range(0, 9, 2): if i == 8 and len(s) <= 8: s = s[:i] + "A" + s[i:] elif i != 2: if s[i] != "A": s = s[:i] + "A" + s[i:] if s == "AKIHABARA": print("YES") else: print("NO")
A New Year party is not a New Year party without lemonade! As usual, you are expecting a lot of guests, and buying lemonade has already become a pleasant necessity. Your favorite store sells lemonade in bottles of n different volumes at different costs. A single bottle of type i has volume 2i - 1 liters and costs ci r...
3
def ii(): return int(input()) def mi(): return map(int, input().split()) def li(): return list(mi()) n, L = mi() C = li() for i in range(1, n): C[i] = min(C[i], C[i-1] * 2) x = 2 ** (n-1) y = 0 z = 10 ** 18 for i in range(n-1, -1, -1): t = L // x y += C[i] * t z = min(z, y + C[i]) L %=...
Quickly after finishing the tutorial of the online game ATChat, you have decided to visit a particular place with N-1 players who happen to be there. These N players, including you, are numbered 1 through N, and the friendliness of Player i is A_i. The N players will arrive at the place one by one in some order. To ma...
3
N=int(input()) A=sorted([int(x) for x in input().split()],reverse=True) print(2*sum(A[0:~-N//2+1])-A[0]-(A[~-N//2] if N%2 else 0))
There is a frog staying to the left of the string s = s_1 s_2 … s_n consisting of n characters (to be more precise, the frog initially stays at the cell 0). Each character of s is either 'L' or 'R'. It means that if the frog is staying at the i-th cell and the i-th character is 'L', the frog can jump only to the left. ...
3
t = int(input()) for _ in range(t): s = input() count = 0 max_count = 0 for i in range(len(s)): if s[i] == 'L': count += 1 else: count = 0 if count > max_count: max_count = count print(max_count + 1)
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
def main(): pv1, pv2 = input().split() days = int(input()) print(pv1, pv2) for i in range(days): c, d = input().split() if pv1 == c: pv1 = d elif pv2 == c: pv2 = d print(pv1, pv2) main()
Colonel has n badges. He wants to give one badge to every of his n soldiers. Each badge has a coolness factor, which shows how much it's owner reached. Coolness factor can be increased by one for the cost of one coin. For every pair of soldiers one of them should get a badge with strictly higher factor than the secon...
3
n = int(input()) a = list(map(int,input().split())) num = [0] * 10001 for i in a: num[i]+= 1 res = 0 for i in range(1, 10001): if num[i] > 1: res+= num[i] - 1 num[i + 1]+= num[i] - 1 print(res)
A new delivery of clothing has arrived today to the clothing store. This delivery consists of a ties, b scarves, c vests and d jackets. The store does not sell single clothing items — instead, it sells suits of two types: * a suit of the first type consists of one tie and one jacket; * a suit of the second type ...
3
tie=int(input()) sca=int(input()) ves=int(input()) jac=int(input()) e=int(input()) f=int(input()) if f>e: mi=min(sca,ves,jac) ans=mi*f ans+=e*min(tie,jac-mi) print(ans) else: mi=min(tie,jac) ans=mi*e ans+=f*min(sca,ves,jac-mi) print(ans)
Let's define the following recurrence: $$$a_{n+1} = a_{n} + minDigit(a_{n}) ⋅ maxDigit(a_{n}).$$$ Here minDigit(x) and maxDigit(x) are the minimal and maximal digits in the decimal representation of x without leading zeroes. For examples refer to notes. Your task is calculate a_{K} for given a_{1} and K. Input The ...
3
def main(): for tin in range(int(input())): n,k=map(int,input().split()) x=list(str(n)) for _ in range(len(x)): x[_]=int(x[_]) c=min(x)*max(x) i=1; while(i<k and c!=0): n=n+c; x=list(str(n)) x=[int(x[_]) for _ in range(l...
The three friends, Kuro, Shiro, and Katie, met up again! It's time for a party... What the cats do when they unite? Right, they have a party. Since they wanted to have as much fun as possible, they invited all their friends. Now n cats are at the party, sitting in a circle and eating soup. The rules are simple: anyone...
3
no_of_cats,no_of_cats_left = map(int,input().split()) l = [] if(no_of_cats_left==0): print(1) elif(no_of_cats%2 == 0): if(no_of_cats//2 == no_of_cats_left): print(no_of_cats_left) elif(no_of_cats_left < no_of_cats//2): print(no_of_cats_left) else: print(no_of_cats - no_of_ca...
Vasya has n burles. One bottle of Ber-Cola costs a burles and one Bars bar costs b burles. He can buy any non-negative integer number of bottles of Ber-Cola and any non-negative integer number of Bars bars. Find out if it's possible to buy some amount of bottles of Ber-Cola and Bars bars and spend exactly n burles. I...
3
n = int(input()) a = int(input()) b = int(input()) x = y = 0 if a % b == 0: if n % b == 0: print("YES") print(0, n//b) else: print("NO") elif b % a == 0: if n % a == 0: print("YES") print(n//a, 0) else: print("NO") elif a >= b: while a*x <= n: if (n - a*x) % b == 0: break else: x += 1 i...
Everybody knows that opposites attract. That is the key principle of the "Perfect Matching" dating agency. The "Perfect Matching" matchmakers have classified each registered customer by his interests and assigned to the i-th client number ti ( - 10 ≤ ti ≤ 10). Of course, one number can be assigned to any number of cust...
3
n=int(input()) t=list(map(int,input().split())) couples=0 count={-10:0,-9:0,-8:0,-7:0,-6:0,-5:0,-4:0,-3:0,-2:0,-1:0,0:0,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,} for j in t: count[j]+=1 arr=list(count.values()) for i in range(10): couples+=arr[i]*arr[20-i] couples+=((count[0]-1)*count[0])//2 print(couples)
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
for test in range(int(input())): entrada = input() string = "" if(len(entrada) <= 10): print(entrada) else: string += entrada[0] + str(len(entrada)-2) + entrada[-1] print(string)
Little chandu is very fond of playing games. Recently, He found a few straws each of length 1 inches in the store room. He took all of them and decided to mark a rectangular area on the floor with straws and warn rest of the family members to not to enter that area so that he can play in peace. He wants to maximize tha...
1
t = int(raw_input()) for i in range(t): n = int(raw_input()) if n<4: print 0 elif n%2 == 0: if n%4 == 0: print (n/4)**2 else: n = (n-2)/4 print n*(n+1) else: if (n-1)%4 == 0: n = (n-1)/4 print n**2 else: n = (n+1)/4 print n*(n-1)
You are given a huge decimal number consisting of n digits. It is guaranteed that this number has no leading zeros. Each digit of this number is either 0 or 1. You may perform several (possibly zero) operations with this number. During each operation you are allowed to change any digit of your number; you may change 0...
3
n, x, y = map(int, input().split()) q = input() ans = 0 for i in range(n - 1, n - x - 1, -1): if i != n - y - 1 and q[i] == '1': ans += 1 if i == n - y - 1 and q[i] == '0': ans += 1 print(ans)
Being tired of participating in too many Codeforces rounds, Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other. He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits ...
3
for i in range(int(input())): x, y, x1, y1 = map(int, input().split()) if abs(x - y) % (x1 + y1) == 0: print(abs(x - y) // (x1 + y1)) else: print(-1)
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word. Note, that during capitalization all the letters except the first one remains unchanged. Input A single line contains a non-empty word. This word consists of lowercase and uppercase English letters....
3
s = input() new = "" s = list(s) s[0] = s[0].capitalize() for x in s: new += x print(new)
Snuke loves puzzles. Today, he is working on a puzzle using `S`- and `c`-shaped pieces. In this puzzle, you can combine two `c`-shaped pieces into one `S`-shaped piece, as shown in the figure below: 9b0bd546db9f28b4093d417b8f274124.png Snuke decided to create as many `Scc` groups as possible by putting together one ...
3
n,m=map(int,input().split()) if 2*n>m: print(m//2) else: print(n+(m-2*n)//4)
You are given two integers n and m. You have to construct the array a of length n consisting of non-negative integers (i.e. integers greater than or equal to zero) such that the sum of elements of this array is exactly m and the value ∑_{i=1}^{n-1} |a_i - a_{i+1}| is the maximum possible. Recall that |x| is the absolut...
3
from sys import stdin import math a = int(stdin.readline()) for b in range(0,a): c=stdin.readline().split() A=int(c[0]) B=int(c[1]) if A==1: print(0) continue if A==2: print(B) continue else: print(2*B)
We have a grid with H rows and W columns. At first, all cells were painted white. Snuke painted N of these cells. The i-th ( 1 \leq i \leq N ) cell he painted is the cell at the a_i-th row and b_i-th column. Compute the following: * For each integer j ( 0 \leq j \leq 9 ), how many subrectangles of size 3×3 of the gr...
3
from collections import Counter, defaultdict from itertools import product H, W, N = map(int, input().split()) c = defaultdict(int) for _ in range(N): a, b = map(int, input().split()) for dx, dy in product([-1, 0, 1], repeat=2): y = a - 2 + dy x = b - 2 + dx if 0 <= y < H - 2 and 0 <= ...
In some social network, there are n users communicating with each other in m groups of friends. Let's analyze the process of distributing some news between users. Initially, some user x receives the news from some source. Then he or she sends the news to his or her friends (two users are friends if there is at least o...
3
import sys from collections import deque input=sys.stdin.readline l= list(map(int,input().split())) n=l[0] k=l[1] dict={} for i in range(n): dict[i+1]=[] for i in range(k): l1=list(map(int,input().split())) if(l1[0]>1): for i in range(2,l1[0]+1): t=l1[i] dict[l1[1]].append(t) dict[t].append(l1[1]) d...
You may have already known that a standard ICPC team consists of exactly three members. The perfect team however has more restrictions. A student can have some specialization: coder or mathematician. She/he can have no specialization, but can't have both at the same time. So the team is considered perfect if it includ...
3
def solve (coder,math,nill) : minTeams = min(coder,math) if minTeams < 1 : return 0 other = max(coder,math) + nill required = minTeams*2 if other >= required : return minTeams else : diff = required - other if diff%3 == 0 : return minTeams -...
There are n warriors in a row. The power of the i-th warrior is a_i. All powers are pairwise distinct. You have two types of spells which you may cast: 1. Fireball: you spend x mana and destroy exactly k consecutive warriors; 2. Berserk: you spend y mana, choose two consecutive warriors, and the warrior with gr...
1
# Author : raj1307 - Raj Singh # Date : 12.07.2020 from __future__ import division, print_function import os,sys from io import BytesIO, IOBase if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip def ii(): return int(input())...
Petr wants to make a calendar for current month. For this purpose he draws a table in which columns correspond to weeks (a week is seven consequent days from Monday to Sunday), rows correspond to weekdays, and cells contain dates. For example, a calendar for January 2017 should look like on the picture: <image> Petr ...
3
M = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] m, d = list(map(int, input().split())) n = M[m] n += (d-1) if n%7 == 0: n /= 7 print(int(n)) else: n /= 7 print(int(n)+1)
Bizon the Champion is called the Champion for a reason. Bizon the Champion has recently got a present — a new glass cupboard with n shelves and he decided to put all his presents there. All the presents can be divided into two types: medals and cups. Bizon the Champion has a1 first prize cups, a2 second prize cups an...
1
from math import floor a = map(int,raw_input().split()) b = map(int,raw_input().split()) n = int(raw_input()) tota = 0 for i in a: tota += i totb = 0 for i in b: totb += i need = 0 need += int(floor(tota/5)) if tota%5 != 0: need += 1 need += int(floor(totb/10)) # print tota,totb,need if totb%10 != 0: ...
This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved. Pikachu is a cute and friendly pokémon living in the wild pikachu herd. But it has become known recently that infamous team R...
3
import sys input = sys.stdin.buffer.readline INF = 10 ** 8 t = int(input()) for _ in range(t): n, q = map(int, input().split()) a = list(map(int, input().split())) max_dp = [-INF] * (n + 1) min_dp = [INF] * (n + 1) max_dp[0] = 0 min_dp[0] = 0 for i in range(n): max_dp[i + 1] =...
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d...
3
num = list(input()) c4 = num.count('4') c7 = num.count('7') if c4+c7 == 4 or c4 + c7 == 7: print('YES') else: print('NO')
You've decided to carry out a survey in the theory of prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors. Consider positive integers a, a + 1, ..., b (a ≤ b). You want to find the minimum integer l (1 ≤ l ≤ b - a + 1) such that for any int...
3
def f(a, b): t = [1] * (b + 1) for i in range(3, int(b ** 0.5) + 1): if t[i]: t[i * i :: 2 * i] = [0] * ((b - i * i) // (2 * i) + 1) return [i for i in range(3, b + 1, 2) if t[i] and i > a] a, b, k = map(int, input().split()) p = f(a - 1, b) if 3 > a and b > 1: p = [2] + p if ...
In Berland it is the holiday of equality. In honor of the holiday the king decided to equalize the welfare of all citizens in Berland by the expense of the state treasury. Totally in Berland there are n citizens, the welfare of each of them is estimated as the integer in ai burles (burle is the currency in Berland). ...
3
t = int(input()) arr = input() l = list(map(int,arr.split(' '))) residue = 0 for num in l : residue += (max(l))-num print(residue)
There is a rooted tree (see Notes) with N vertices numbered 1 to N. Each of the vertices, except the root, has a directed edge coming from its parent. Note that the root may not be Vertex 1. Takahashi has added M new directed edges to this graph. Each of these M edges, u \rightarrow v, extends from some vertex u to it...
3
import sys input=sys.stdin.readline n,m=map(int,input().split()) Ans=[0]*(n+1) Children=[[] for _ in range(n+1)] Cnt=[0]*(n+1); Cnt[0]=1 for _ in range(n+m-1): a,b=map(int,input().split()) Children[a].append(b) Cnt[b]+=1 root=Cnt.index(min(Cnt)) V=[root] while V: v=V.pop() for u in Children[v]: ...
Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. For example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. When a team plays as ...
1
import sys n = int(sys.stdin.readline()) home = {} away = {} dup = 0 for x in range(n): line = [int(x) for x in sys.stdin.readline().split()] if line[0] in home: home[line[0]] += 1 else: home[line[0]] = 1 if line[1] in away: away[line[1]] += 1 else: away[line[1]] = ...
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1. Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divi...
1
import math n = input() l = [1]*100000 for i in range(2,int(math.sqrt(100000))): if l[i]: for j in range(i+i, 100000, i): l[j] = 0 res = [] for j in [i for i in range(2,100000) if l[i]]: if n/j: if n%j != 0: t = n/j - 1 n = n - (j*t) ...
Anton likes to play chess, and so does his friend Danik. Once they have played n games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie. Now Anton wonders, who won more games, he or Danik? Help him determine this. Input The first line of the input contains a...
3
n = int(input()) s = sorted(input()) c = 0 for i in s: if(i == 'A'): c += 1 else: break if(c > abs(len(s)-c)): print('Anton') elif(c < abs(len(s) - c)): print('Danik') else: print('Friendship')
Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, inf...
1
a = int(raw_input()) s = raw_input() c = ["" for x in xrange(a)] i = 0 lis = [x for x in xrange(a)] alias = a left = 0 right = 0 while(i<alias): if(a%2!=0): c[alias//2 + right] = s[i] right += 1 else: c[alias//2 - left-1] = s[i] left += 1 i += 1 a -= 1 print "".join(c)
John Smith knows that his son, Thomas Smith, is among the best students in his class and even in his school. After the students of the school took the exams in English, German, Math, and History, a table of results was formed. There are n students, each of them has a unique id (from 1 to n). Thomas's id is 1. Every st...
3
t=[] y=[] for i in range(int(input())): g=list(map(int,input().split())) t.append([sum(g),i+1]) y.append(sum(g)) t.sort() s=t[::-1] for k in range(len(s)): if s[k][1]==1: if y.count(y[0])>1: print((k+1)-(y.count(y[0])-1)) break else: print(k+1) ...
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem. Pete and Bi...
3
w = int(input()) if(w%2 == 1): print("NO") else : if(w>2): print("YES") else : print("NO")
We often go to supermarkets to buy some fruits or vegetables, and on the tag there prints the price for a kilo. But in some supermarkets, when asked how much the items are, the clerk will say that a yuan for b kilos (You don't need to care about what "yuan" is), the same as a/b yuan for a kilo. Now imagine you'd like ...
3
a = list(map(int,input().split())) c = [] for i in range(a[0]): b = list(map(int,input().split())) c.append(a[1]*b[0]/b[1]) print(min(c))
There are N participants in the CODE FESTIVAL 2016 Qualification contests. The participants are either students in Japan, students from overseas, or neither of these. Only Japanese students or overseas students can pass the Qualification contests. The students pass when they satisfy the conditions listed below, from t...
3
n,a,b=map(int,input().split()) ac=0 bc=0 for i in input(): if i=='a': if ac+bc<a+b: print('Yes') ac+=1 continue elif i=='b': if ac+bc<a+b and bc<b: print('Yes') bc+=1 continue print('No')
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
import string word=input() cntr=0 l=[] for i in word: if i in string.ascii_letters and i not in l: cntr+=1 l.append(i) print(cntr)
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
r = '' n = int(input()) for i in range(n): s = input() if len(s) > 10: r += s[0] + str(len(s) - 2) + s[-1] + '\n' else: r += s + '\n' print(r)
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...
1
if __name__ == "__main__": n, d = map(int, raw_input().split()) # n, d = 8, 4 n, d = n-1, d x = raw_input() # x = "10010101" jumps = 0 i = 0 j = 0 while(True): if(i+d>=n): break j = 0 while(j<=d and 0<=i+d-j<n and x[i+d-j]!='1'): j+=1 if(j>=d): print(-1) exit(0) # print (i, i+d-j), jum...
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
import re p = r'([01])\1{6}' s = input() print('YES' if re.search(p,s) else 'NO')
Vasya has got many devices that work on electricity. He's got n supply-line filters to plug the devices, the i-th supply-line filter has ai sockets. Overall Vasya has got m devices and k electrical sockets in his flat, he can plug the devices or supply-line filters directly. Of course, he can plug the supply-line filt...
3
nmk = list(map(int, input().strip().split())) n = nmk[0] m = nmk[1] k = nmk[2] lst = list(map(int, input().strip().split())) lst.sort(reverse = True) i = 0 while k < m and i < n: k = k + lst[i] - 1 i += 1 #print(k, m) if i <= n and k >= m: print(i) else: print(-1)
You have a list of numbers from 1 to n written from left to right on the blackboard. You perform an algorithm consisting of several steps (steps are 1-indexed). On the i-th step you wipe the i-th number (considering only remaining numbers). You wipe the whole number (not one digit). <image> When there are less than ...
3
n = int(input().strip()) for i in range(n): size, number = map(int, input().strip().split(' ')) print(number*2)
The letters shop showcase is a string s, consisting of n lowercase Latin letters. As the name tells, letters are sold in the shop. Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string s. There are m friends, the i-th of them is named t_i. Eac...
3
from collections import defaultdict as dd from bisect import bisect_left as lb t=int(input()) import string wor=input() lo=string.ascii_lowercase q=int(input()) dp=dict() for j in lo: dp[j]=[0] for i in wor: for j in lo: if j==i: dp[j]+=[dp[j][-1]+1] else: dp[j]+=[dp[j][...
You want to build a fence that will consist of n equal sections. All sections have a width equal to 1 and height equal to k. You will place all sections in one line side by side. Unfortunately, the ground beneath the fence is not flat. For simplicity, you can think that the ground level under the i-th section is equal...
3
#### IMPORTANT LIBRARY #### ############################ ### DO NOT USE import random --> 250ms to load the library ############################ ### In case of extra libraries: https://github.com/cheran-senthil/PyRival ###################### ####### IMPORT ####### ###################### from functools import cmp_to...
Hilbert's Hotel is a very unusual hotel since the number of rooms is infinite! In fact, there is exactly one room for every integer, including zero and negative integers. Even stranger, the hotel is currently at full capacity, meaning there is exactly one guest in every room. The hotel's manager, David Hilbert himself,...
3
T = int(input()) for _ in range(T): n = int(input()) v = list(map(int, input().split(" "))) for i in range(n): v[i] = ((v[i] % n) + n) % n f = 1 m = {} for i in range(2 * n + 1): t = i + v[(i % n + n) % n] if t in m: f = 0 break m[t] = 0 ...
Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not. Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindro...
3
t = input() print(t, end="") for c in t[::-1]: print(c, end="") print("")
You are given three strings a, b and c of the same length n. The strings consist of lowercase English letters only. The i-th letter of a is a_i, the i-th letter of b is b_i, the i-th letter of c is c_i. For every i (1 ≤ i ≤ n) you must swap (i.e. exchange) c_i with either a_i or b_i. So in total you'll perform exactly...
1
t=input() for i in range(t): s1=raw_input() s2=raw_input() s3=raw_input() ans=True for j in range(len(s1)): if s1[j]==s2[j]: if s1[j]==s3[j]: pass else: print "NO" ans=False break if s1[j]==s3[j] ...
The student council is preparing for the relay race at the sports festival. The council consists of n members. They will run one after the other in the race, the speed of member i is s_i. The discrepancy d_i of the i-th stage is the difference between the maximum and the minimum running speed among the first i members...
3
n=int(input()) s=list(map(int,input().split())) s.sort() dp=[0]*n for d in range(1,n): for i in range(n-d): dp[i]=min(dp[i+1],dp[i])+s[i+d]-s[i] print(dp[0]) #print(dp)
You have n barrels lined up in a row, numbered from left to right from one. Initially, the i-th barrel contains a_i liters of water. You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels x and y (the x-th barrel shouldn't be empty) and pour any possible amount of wa...
3
def solve(): s = [int(i) for i in input().split()] n = s[0] k = s[1] s = [int(i) for i in input().split()] s.sort() for i in range(1, k + 1): s[n-1] += s[n - 1 - i] print( s[n-1]) t = int(input()) for i in range(t): solve()
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation. The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe...
3
n = input() #get input from user lenn=len(n) #length of primary string s=n.replace('+','') #remove '+' sign from string ss=list(s) ascendingList =[] i=0 strlen = len(s) #length of string containing only numbers while i<strlen: #ascending the numbers a=min(ss) ascendingList.append(a) ss.remove(a) ...
There are n piles of stones, where the i-th pile has a_i stones. Two people play a game, where they take alternating turns removing stones. In a move, a player may remove a positive number of stones from the first non-empty pile (the pile with the minimal index, that has at least one stone). The first player who canno...
3
t=int(input()) i=0 winner=1 def switch(winner): if winner==1: winner=2 else: winner=1 return winner while i<t: number_of_piles=int(input()) pile=[int(x) for x in input().split()] check_set=set(pile) if check_set=={1}: if number_of_piles%2==0: winner=2 ...
Some natural number was written on the board. Its sum of digits was not less than k. But you were distracted a bit, and someone changed this number to n, replacing some digits with others. It's known that the length of the number didn't change. You have to find the minimum number of digits in which these two numbers c...
3
k=int(input()) l=sorted(map(int,input())) i=0 su=sum(l) while su<k: su+=9-l[i] i+=1 print(i)
Finished her homework, Nastya decided to play computer games. Passing levels one by one, Nastya eventually faced a problem. Her mission is to leave a room, where a lot of monsters live, as quickly as possible. There are n manholes in the room which are situated on one line, but, unfortunately, all the manholes are clo...
3
n,k=map(int,input().split()) f = 3 * n if n != k and k != 1: f = min(k - 1, n - k) + f print(f)
You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum: <image> Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p). Input The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn...
1
import itertools def compute(l, n): ans = 0 for i in range(n): a = [] a.append(l[i]) for j in range(i,n): a.append(l[j]) ans += min(a) #print ans return ans if __name__ == '__main__': n,m = map(int, raw_input().split()) li = range(1, n+1) lists = list(itertools.permutations(li)) max = -1 count = ...
Polycarp has recently created a new level in this cool new game Berlio Maker 85 and uploaded it online. Now players from all over the world can try his level. All levels in this game have two stats to them: the number of plays and the number of clears. So when a player attempts the level, the number of plays increases...
3
T = int(input()) for t in range(T): N = int(input()) arrP = [] arrC = [] for n in range(N): p, c = input().split(' ') arrP.append(int(p)) arrC.append(int(c)) if arrP[0] < arrC[0]: print("NO") else : flag = True for n in range(1,N): if(a...
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number! The only thing Mrs. Smith remembered was that any permutation of n can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband. The sequence of n integers is called a...
3
#list_int 並べて出力 print (' '.join(map(str,ans_li))) #list_str 並べて出力 print (' '.join(list)) from collections import defaultdict import sys,heapq,bisect,math,itertools,string,queue,datetime sys.setrecursionlimit(10**8) INF = float('inf') mod = 10**9+7 eps = 10**-7 AtoZ = [chr(i) for i in range(65,65+26)] atoz = [chr(i) fo...
Fedya studies in a gymnasium. Fedya's maths hometask is to calculate the following expression: (1n + 2n + 3n + 4n) mod 5 for given value of n. Fedya managed to complete the task. Can you? Note that given number n can be extremely large (e.g. it can exceed any integer type of your programming language). Input The si...
3
print('4' if int(input())%4==0 else '0')
We all know the problem about the number of ways one can tile a 2 × n field by 1 × 2 dominoes. You probably remember that it goes down to Fibonacci numbers. We will talk about some other problem below, there you also are going to deal with tiling a rectangular field with dominoes. You are given a 4 × n rectangular fie...
1
n=int(raw_input()) if(n%2): print 'aabb'*(n/4)+'aa'*((n/2)%2)+'c' print 'ddee'*(n/4)+'dd'*((n/2)%2)+'c' print 'f'+'aabb'*(n/4)+'aa'*((n/2)%2) print 'f'+'ddee'*(n/4)+'dd'*((n/2)%2) exit(0) print 'aabb'*(n/4)+'aa'*((n/2)%2) m=n-2 print 'c'+'ddee'*(m/4)+'dd'*((m/2)%2)+'h' print 'c'+'aabb'*(m/4)+'aa'*((m/2)%2)+'h' p...
You are given string s consists of opening and closing brackets of four kinds <>, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >. The following definition of a...
3
s = input() open = {'(', '{', '[', '<'} res = 0 our = [] for elem in s: if elem in open: our.append(elem) else: if our: res += (abs(ord(elem) - ord(our[-1])) > 2) our.pop() else: print('Impossible') exit() if our: print('Impossible') el...
There is a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and Vertex b_i, and the color and length of that edge are c_i and d_i, respectively. Here the color of each edge is represented by an integer between 1 and N-1 (inclusive). The same integer corresponds to the same color, and...
3
def examA(): N = DI()/dec(7) ans = N print(N) return def examB(): ans = 0 print(ans) return def examC(): ans = 0 print(ans) return def examD(): ans = 0 print(ans) return def examE(): ans = 0 print(ans) return def examF(): class LCA(object): ...
You have n barrels lined up in a row, numbered from left to right from one. Initially, the i-th barrel contains a_i liters of water. You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels x and y (the x-th barrel shouldn't be empty) and pour any possible amount of wa...
3
for _ in range(int(input())): n,k=map(int,input().split()) a=list(map(int, input().split())) a.sort() max_amount=a[n-1] i=n-2 for _ in range(k): max_amount=max_amount+a[i] i=i-1 print(max_amount)
Alice has a birthday today, so she invited home her best friend Bob. Now Bob needs to find a way to commute to the Alice's home. In the city in which Alice and Bob live, the first metro line is being built. This metro line contains n stations numbered from 1 to n. Bob lives near the station with number 1, while Alice ...
3
import sys from collections import defaultdict mod = 1000000007 def get_array(): return list(map(int, sys.stdin.readline().split())) def get_ints(): return map(int, sys.stdin.readline().split()) def input(): return sys.stdin.readline() def print_array(a): print(" ".join(map(str, a))) class Graph: def __init__(self)...
Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones. Once he thought about a string of length n consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and ...
3
# bsdk idhar kya dekhne ko aaya hai, khud kr!!! # import math # from itertools import * # import random # import calendar # import datetime # import webbrowser n = int(input()) string = input() print(abs(n - 2 * string.count("1")))
A telephone number is a sequence of exactly 11 digits such that its first digit is 8. Vasya and Petya are playing a game. Initially they have a string s of length n (n is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it fro...
3
n = int(input()) s = input() cnt = 0 for i in range(n - 10): if s[i] == '8': cnt += 1 if cnt >= ((n - 9) // 2): print('YES') else: print('NO')
You are the gym teacher in the school. There are n students in the row. And there are two rivalling students among them. The first one is in position a, the second in position b. Positions are numbered from 1 to n from left to right. Since they are rivals, you want to maximize the distance between them. If students a...
3
n=int(input()) for i in range(n): a,b,c,d = map(int,input().split()) if d>c: if d-c==a-1: print(a-1) elif b==0: print(d-c) elif b>=a-1-d+c: print(a-1) else: print(d-c+b) else: if c-d==a-1: print(a-1) elif b==0: print(c-d) elif b>=a-1-c+d: print(a-1) else: print(c-d+b)
In Japan, people make offerings called hina arare, colorful crackers, on March 3. We have a bag that contains N hina arare. (From here, we call them arare.) It is known that the bag either contains arare in three colors: pink, white and green, or contains arare in four colors: pink, white, green and yellow. We have ...
3
n=int(input()) S = input().split() print('Three' if not 'Y' in S else 'Four')
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1. The decoding of the lever description is ...
3
k = input().split('^') l = sum([(ord(x)-ord('0'))*(len(k[0])-i+1) for i, x in enumerate(k[0], 1) if x != '=' ]) r = sum([(ord(x)-ord('0'))*(i) for i, x in enumerate(k[1], 1) if x != '=']) print('balance' if l == r else 'left' if l > r else 'right')
Vanya loves playing. He even has a special set of cards to play with. Each card has a single integer. The number on the card can be positive, negative and can even be equal to zero. The only limit is, the number on each card doesn't exceed x in the absolute value. Natasha doesn't like when Vanya spends a long time pla...
3
n,x = map(int,input().split()) a = list(map(int,input().split())) s = abs(sum(a)) if s%x == 0: print(s//x) else: print(s//x+1)
This is the easy version of the problem. The difference between the versions is that in the easy version all prices a_i are different. You can make hacks if and only if you solved both versions of the problem. Today is Sage's birthday, and she will go shopping to buy ice spheres. All n ice spheres are placed in a row ...
3
n=int(input()) l=[int(i) for i in input().split()][:n] l.sort() final=[] if n==1 or n==2: print(0) print(*l) elif n%2!=0: temp=(n-1)//2 print(temp) i=-1 for i in range(temp,n-1): final.append(l[i]) final.append(l[temp-1]) temp-=1 final.append(l[i+1]) print(*final) else: temp=(n-2)//2 print(temp) final....
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, m = map(int, input().split()) print('YES' if sum(list(map(int, input().split()))) == m else 'NO')
Robbers, who attacked the Gerda's cab, are very successful in covering from the kingdom police. To make the goal of catching them even harder, they use their own watches. First, as they know that kingdom police is bad at math, robbers use the positional numeral system with base 7. Second, they divide one day in n hour...
3
from itertools import permutations def dfs(x): r = x==0 while x : r += 1 x //= 7 return r n ,m = map(int,input().split()) res, ln, lm = 0, dfs(n-1), dfs(m-1) for i in permutations('0123456', ln+lm): i = ''.join(i) res += int(i[:ln], 7) < n and int(i[ln:], 7) < m print(res) ...
Valera has got n domino pieces in a row. Each piece consists of two halves — the upper one and the lower one. Each of the halves contains a number from 1 to 6. Valera loves even integers very much, so he wants the sum of the numbers on the upper halves and the sum of the numbers on the lower halves to be even. To do t...
1
#!/usr/bin python n = int(raw_input()) flag = 0 sumx = 0 sumy = 0 for i in range(n) : x,y = [int(x) for x in raw_input().split()] if (x+y) % 2 == 1 : flag = 1 sumx += x sumy += y if sumx %2 ==0 and sumy %2 ==0: print 0 elif (sumx + sumy)%2 == 1: print -1 else: if flag == 1 : ...
You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum: <image> Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p). Input The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn...
3
ii=lambda:int(input()) kk=lambda:map(int, input().split()) ll=lambda:list(kk()) n,k=kk() pre,post = [],[] k-=1 v = 1 for i in range(n-2,-1,-1): if k&(2**i): post.append(v) else: pre.append(v) v+=1 print(*pre,n,*reversed(post))
HQ9+ is a joke programming language which has only four one-character instructions: * "H" prints "Hello, World!", * "Q" prints the source code of the program itself, * "9" prints the lyrics of "99 Bottles of Beer" song, * "+" increments the value stored in the internal accumulator. Instructions "H" and "Q"...
3
input_str = str(input()) if "H" in input_str or "Q" in input_str or "9" in input_str: print("YES") else: print("NO")
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them. Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain nu...
3
s = input() l = s.split('WUB') ans = [x for x in l if x != ""] print(*ans)
You are given an array of integers a_1,a_2,…,a_n. Find the maximum possible value of a_ia_ja_ka_la_t among all five indices (i, j, k, l, t) (i<j<k<l<t). Input The input consists of multiple test cases. The first line contains an integer t (1≤ t≤ 2 ⋅ 10^4) — the number of test cases. The description of the test cases ...
3
for i in range(int(input())): n = int(input()) ar = [int(i) for i in input().split()] ar.sort() print(max(ar[-1]*ar[-2]*ar[-3]*ar[1]*ar[0],ar[0]*ar[1]*ar[2]*ar[3]*ar[-1],ar[-1]*ar[-2]*ar[-3]*ar[-4]*ar[-5]))