problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
You are given an array a of n integers, where n is odd. You can make the following operation with it: * Choose one of the elements of the array (for example a_i) and increase it by 1 (that is, replace it with a_i + 1). You want to make the median of the array the largest possible using at most k operations. The...
3
n, k = map(int, input().split()) a = sorted(map(int, input().split())) a += [10**10] m = (n - 1) // 2 med = 0 sum1 = 0 for i in range(m, n): sum1 += a[i] c = min(a[i + 1], (k + sum1) // (i + 1 - m)) if c < a[i]: break if c > med: med = c print(med)
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
n = input() num = int(n) + 1 while num <= 10000: var = str(num) c1 = var.count(var[0]) c2 = var.count(var[1]) c3 = var.count(var[2]) c4 = var.count(var[3]) #print(num, c1, c2, c3, c4, var) if c1 == 1 and c2 == 1 and c3 == 1 and c4 == 1: print(var) break num += 1
A and B are preparing themselves for programming contests. To train their logical thinking and solve problems better, A and B decided to play chess. During the game A wondered whose position is now stronger. For each chess piece we know its weight: * the queen's weight is 9, * the rook's weight is 5, * the ...
1
from sys import stdin b, w = 0, 0 for board in stdin.readlines(): w += 9 * board.count('Q') + 5 * board.count('R') + 3 * (board.count('B') + board.count('N')) + board.count('P') b += 9 * board.count('q') + 5 * board.count('r') + 3 * (board.count('b') + board.count('n')) + board.count('p') if (b > w): print "Blac...
Polycarpus has been working in the analytic department of the "F.R.A.U.D." company for as much as n days. Right now his task is to make a series of reports about the company's performance for the last n days. We know that the main information in a day report is value ai, the company's profit on the i-th day. If ai is n...
1
n = input() a = map(int, raw_input().split()) c = 0 ret = [0] for i in xrange(len(a)): if a[i] < 0: c += 1 if c == 3: ret.append(0) c = 1 ret[-1] += 1 print len(ret) print " ".join(map(str, ret))
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
def main(): vowels = ['a', 'o', 'y', 'e', 'u', 'i'] s = raw_input().lower() res = ['.' + c for c in s if c not in vowels] print ''.join(res) if __name__ == '__main__': main()
Find the minimum area of a square land on which you can place two identical rectangular a Γ— b houses. The sides of the houses should be parallel to the sides of the desired square land. Formally, * You are given two identical rectangles with side lengths a and b (1 ≀ a, b ≀ 100) β€” positive integers (you are given ...
3
import sys cases = int(sys.stdin.readline()) for _ in range(cases): ''' inputs ''' # n = int(sys.stdin.readline()) # single input a, b = map(int, sys.stdin.readline().split()) # two inputs # A = list(map(int, sys.stdin.readline().split())) # list input '''code ...
In this problem we assume the Earth to be a completely round ball and its surface a perfect sphere. The length of the equator and any meridian is considered to be exactly 40 000 kilometers. Thus, travelling from North Pole to South Pole or vice versa takes exactly 20 000 kilometers. Limak, a polar bear, lives on the N...
1
var = 0 N = int(raw_input()) dist = [] dir = [] for n in xrange(N): a,b = raw_input().split() a = int(a) dist.append(a) dir.append(b) last = 0 for n in xrange(N): if(var == 0 and dir[n] != "South"): print "NO" exit() if(var == 20000 and dir[n] != "North"): print "NO" exit() elif(dir[n] == "North"): var...
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...
3
n,m = map(int,input().split()) a = list(map(int,input().split())) a.sort() min1 = float("inf") for i in range(n-1,m): # print(a) if a[i]-a[i-n+1] < min1: # print(a[i],a[i-n+1]) min1 = a[i]-a[i-n+1] print(min1)
You are given an array a[0 … n-1] of length n which consists of non-negative integers. Note that array indices start from zero. An array is called good if the parity of each index matches the parity of the element at that index. More formally, an array is good if for all i (0 ≀ i ≀ n - 1) the equality i mod 2 = a[i] m...
3
tests = int(input()) for _ in range(tests): n = int(input()) sp = list(map(int, input().split())) ch = 0 for i in sp: if i % 2 == 0: ch += 1 if ch != n - n // 2: print(-1) continue count = 0 for i in range(n): if i % 2 != sp[i] % 2: cou...
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution....
3
n=int(input()) i=0 x=[] while i<n: p=input() x.append(p) i=i+1 l=0 for ad in x: k=ad.split() if sum(map(int,k))>=2: l=l+1 print(l)
You've got array a[1], a[2], ..., a[n], consisting of n integers. Count the number of ways to split all the elements of the array into three contiguous parts so that the sum of elements in each part is the same. More formally, you need to find the number of such pairs of indices i, j (2 ≀ i ≀ j ≀ n - 1), that <image>...
3
n = int(input()) A = list(map(int, input().split(' '))) s = sum(A) I = [] J = [] equal_sum = int(s/3) ans = 0 sum_check = 0 if n > 2 and s%3 == 0: for i in range(0,n): sum_check += A[i] if (sum_check == equal_sum): I.append(i) sum_check = 0 for j in range(n-1, -1, -1): sum_check += A[j] if (sum_check == e...
Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are n drinks in his fridge, the volume fraction of orange juice in the i-th drink equals pi percent. One day Vasya decided to make himself an orange cocktail. He took equal proportions of ea...
1
#!usr/bin/python from __future__ import division; summ = 0; n = input(); a = [int(i) for i in raw_input().split()]; for i in range(0, n): div = (a[i] / 100); summ += div; last = (summ / n) * 100; print last;
A little girl loves problems on bitwise operations very much. Here's one of them. You are given two integers l and r. Let's consider the values of <image> for all pairs of integers a and b (l ≀ a ≀ b ≀ r). Your task is to find the maximum value among all considered ones. Expression <image> means applying bitwise excl...
3
import math L, R = map(int, input().strip().split()) if L == R: print(0) else: p = int(math.log2(R)) tar = 2**p while not(tar > L): L -= tar R -= tar p = int(math.log2(R)) tar = 2**p print(2**(p+1)-1) # tar = 2**p # if tar > L: # print(2**(p+1)-1) # else: #...
You are given a tree with n vertices. You are allowed to modify the structure of the tree through the following multi-step operation: 1. Choose three vertices a, b, and c such that b is adjacent to both a and c. 2. For every vertex d other than b that is adjacent to a, remove the edge connecting d and a and add t...
3
import sys from math import ceil,sqrt,sin,pi,tan from collections import defaultdict read=sys.stdin.buffer.readline import heapq mi=lambda:map(int,read().split()) li=lambda:list(mi()) cin=lambda:int(read()) def ispd(s): n=len(s) if s[:n//2]==s[[(n//2)+1,n//2][n%2==0]:][::-1]: return True return Fal...
You are given a board of size n Γ— n, where n is odd (not divisible by 2). Initially, each cell of the board contains one figure. In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell (i, j) you can move...
3
import sys input=sys.stdin.readline t=int(input()) for i in range(t): n=int(input()) ans=0 for j in range(1,n//2+1): ans+=(8*j)*j sys.stdout.write(str(ans)+'\n')
A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not. Ahcl wants to construct a beautiful string. He has a string s, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each c...
3
t = int(input()) s_sum = '' for i in range(t): st = input() + ' ' s_new = ' ' T = 0 for j in range(len(st) - 1): abc_dict = {'a': 0, 'b': 0, 'c': 0} if st[j] == st[j+1] and st[j] != '?' and j != len(st): s_sum = s_sum + '-1' + '\n' T = 1 break ...
You are given a board of size n Γ— n, where n is odd (not divisible by 2). Initially, each cell of the board contains one figure. In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell (i, j) you can move...
3
t=int(input()) while t>0: n=int(input()) if n==1: print(0) elif n==3: print(8) else: sum=0 for i in range(3,n+2,2): sum= sum+ (4*i-4)*(i//2) print(sum) t=t-1
A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times b, b + a, b + 2a, b + 3a, ... and Morty screams at times d, d + c, d + 2c, d + 3c, .... <image> The Monster will catch them if at any point they scream at the same tim...
3
a,b = map(int, input().split()) c,d = map(int, input().split()) flag = False for i in range(500): for j in range(500): if b + a*i == d + c*j: flag = True print(b+a*i) if flag: break #break vΓ²ng nΓ y nαΊΏu Δ‘Γ£ True if flag: break #break vΓ²ng nΓ y nαΊΏu False if not flag: pr...
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 = input() if(s.count('A')>s.count('D')): print("Anton") elif(s.count('A')<s.count('D')): print('Danik') else: print("Friendship")
A permutation of length n is a sequence of integers from 1 to n of length n containing each number exactly once. For example, [1], [4, 3, 5, 1, 2], [3, 2, 1] are permutations, and [1, 1], [0, 1], [2, 2, 1, 4] are not. There was a permutation p[1 ... n]. It was merged with itself. In other words, let's take two instanc...
3
def fun(): new=int(input()) for i in range(new): yes=int(input()) lo=list(map(int,input().split())) arr=[] for y in lo: if y not in arr: arr.append(y) print(y, end=' ') print() fun()
You are given integers N,\ A and B. Determine if there exists a permutation (P_0,\ P_1,\ ...\ P_{2^N-1}) of (0,\ 1,\ ...\ 2^N-1) that satisfies all of the following conditions, and create one such permutation if it exists. * P_0=A * P_{2^N-1}=B * For all 0 \leq i < 2^N-1, the binary representations of P_i and P_{i+1} ...
3
N, A, B = map(int, input().split()) if bin(A).count("1")%2 == bin(B).count("1")%2: print("No") exit(0) print("Yes") ans = [] def solve(c, A, B, S): P = A ^ B U = P & S b = 1 if c == 1: ans.append(A) ans.append(B) return for i in range(N): if U & b: ...
You are given an array a of length n. You are also given a set of distinct positions p_1, p_2, ..., p_m, where 1 ≀ p_i < n. The position p_i means that you can swap elements a[p_i] and a[p_i + 1]. You can apply this operation any number of times for each of the given positions. Your task is to determine if it is poss...
3
t=int(input()) for _ in range(t): n,pn=map(int,input().split()) arr=list(map(int,input().split())) p=list(map(int,input().split())) c=1 for i in range(n): for j in range(0, n-i-1): if arr[j] > arr[j+1] : if j+1 in p: arr[j], arr[j+1] = arr[j+1]...
Ted has a pineapple. This pineapple is able to bark like a bulldog! At time t (in seconds) it barks for the first time. Then every s seconds after it, it barks twice with 1 second interval. Thus it barks at times t, t + s, t + s + 1, t + 2s, t + 2s + 1, etc. <image> Barney woke up in the morning and wants to eat the ...
3
t, s, x = map(int, input().split()) print("YES" if (x - t >= 0 and (x - t) % s == 0) or (x - t - 1 >= 0 and (x - t - 1) % s == 0 and (x - t - 1) // s > 0) else "NO")
Sereja has an array a, consisting of n integers a1, a2, ..., an. The boy cannot sit and do nothing, he decided to study an array. Sereja took a piece of paper and wrote out m integers l1, l2, ..., lm (1 ≀ li ≀ n). For each number li he wants to know how many distinct numbers are staying on the positions li, li + 1, ......
3
# -*- coding: utf-8 -*- n, m = map(int, input().split()) a = list(map(int, input().split())) l = [int(input()) for i in range(m)] ans = [0] * n s = set() for i in range(n-1, -1, -1): s.add(a[i]) ans[i] = len(s) for i in range(m): print(ans[l[i]-1])
So nearly half of the winter is over and Maria is dreaming about summer. She's fed up with skates and sleds, she was dreaming about Hopscotch all night long. It's a very popular children's game. The game field, the court, looks as is shown in the figure (all blocks are square and are numbered from bottom to top, blocks...
1
b = [0.5, 1] a,x,y = list(map(int, str(raw_input()).split())) if((abs(x) >= a) or (y%a == 0)): print '-1'; else: if(y < 2*a): if(abs(x) >= a/2.0): print '-1'; else: print str((y/a)+1) else: num = y/(2*a) num *= 3 y = y%(2*a) if(y/a == 1...
Recently, you found a bot to play "Rock paper scissors" with. Unfortunately, the bot uses quite a simple algorithm to play: he has a string s = s_1 s_2 ... s_{n} of length n where each letter is either R, S or P. While initializing, the bot is choosing a starting index pos (1 ≀ pos ≀ n), and then it can play any numbe...
3
t = int(input()) while (t): ss = input() r,s,p = 0,0,0 for i in range(len(ss)): r += (ss[i] == 'S') s += (ss[i] == 'P') p += (ss[i] == 'R') if (max(r,s,p) == r): print('R'*len(ss)) elif (max(r,s,p) == s): print('S'*len(ss)) else: print('P'*len(ss)) t -= 1
The football season has just ended in Berland. According to the rules of Berland football, each match is played between two teams. The result of each match is either a draw, or a victory of one of the playing teams. If a team wins the match, it gets w points, and the opposing team gets 0 points. If the game results in ...
3
n, p, w, d = [int(x) for x in input().split()] x=-1 y=-1 for i in range(w+1): if (p-i*d)%w==0: y=i x=(p-y*d)//w break if x<0 or y<0 or x+y>n: print(-1) else: print(x,y,n-x-y)
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 ...
1
m, d = map(int,raw_input().split()) month = [31,28,31,30,31,30,31,31,30,31,30,31] for i, mo in enumerate(month): if(i+1==m): ost = mo - (8-d) nedels = 1 + (ost - ost%7)/7 if(ost%7>0): nedels += 1 print(nedels) break
For given integers m and n, compute mn (mod 1,000,000,007). Here, A (mod M) is the remainder when A is divided by M. Constraints * 1 ≀ m ≀ 100 * 1 ≀ n ≀ 109 Input m n Two integers m and n are given in a line. Output Print mn (mod 1,000,000,007) in a line. Examples Input 2 3 Output 8 Input 5 8 Output...
3
kMod = 1000000007 m, n = map(int, input().split()) buf = {1:m} i = 2 while i <= n: prev = buf[i // 2] cur = (prev * prev) % kMod buf[i] = cur i *= 2 ans = 1 i = 0 while (1 << i) <= n: if (1<<i) & n: ans *= buf[1<<i] ans %= kMod i += 1 print(ans)
Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word. Hongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character ...
1
"Hongcow learns the cyclic shift" s = raw_input() already_used = [s] for i in range(len(s)): temp = s[len(s)-1] temp += s[:len(s)-1] if temp in already_used: pass else: already_used.append(temp) s = temp print len(already_used)
You are an experienced Codeforces user. Today you found out that during your activity on Codeforces you have made y submissions, out of which x have been successful. Thus, your current success rate on Codeforces is equal to x / y. Your favorite rational number in the [0;1] range is p / q. Now you wonder: what is the s...
3
import sys from fractions import gcd as gcdlib def main(): t=int(sys.stdin.readline().rstrip()) for _ in range(t): x,y,p,q=list(map(int,sys.stdin.readline().split())) res,m,k=find_best_solution(p-q,p,-(y*p-x*q)) if res==False: result=-1 elif m<0 or k<0: result=-1 ...
At the beginning of the school year Berland State University starts two city school programming groups, for beginners and for intermediate coders. The children were tested in order to sort them into groups. According to the results, each student got some score from 1 to m points. We know that c1 schoolchildren got 1 po...
3
n=int(input()) marks=[int(i) for i in input().split()] x,y=map(int,input().split()) sm=0 f=0 tot=sum(marks) for i in range(n): sm+=marks[i] if sm>=x: store=sm rem=tot-sm if rem>=x and rem<=y and sm<=y: print(i+2) exit() if store>y: continue...
You've got a 5 Γ— 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix: 1....
3
ans = 0 for i in range(5): line = input().split() if "1" in line: ans = abs(i - 2) + abs(line.index("1") - 2) print(ans)
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
s=input() s=s.lower() s1="" for x in s: if x not in ["a","o","y","e","u","i"]: s1=s1+x s2="" for i in range (len(s1)): s2=s2+"."+s1[i] print (s2)
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated. The language is that peculiar as it has exactly one variable, called x. Also, there are two operations: * Operation ++ increases the value of variable x by 1. * Operation -- decreases the value of variable x by 1....
3
userinput=input() X=0 oplist=list() for i in range(int(userinput)): opinput=input() z=oplist.append(opinput) for t in range(len(oplist)): operator=oplist[t] if (operator[1]=="+" and operator[2]=="+") or (operator[0]=="+" and operator[1]=="+"): X+=1 if (operator[1]=="-" and operator[2]=="-"...
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≀ i ≀ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is it...
3
n = int(input()) f = list(map(int, input().split())) k = 1 m = 1 for i in range(1,n): if f[i] >= f[i-1]: k+=1 m = max(m,k) else: k = 1 print(m)
You are given the array a consisting of n positive (greater than zero) integers. In one move, you can choose two indices i and j (i β‰  j) such that the absolute difference between a_i and a_j is no more than one (|a_i - a_j| ≀ 1) and remove the smallest of these two elements. If two elements are equal, you can remove a...
3
tests = int(input()) def solve(): n = int(input()) s = input() a = [int(x) for x in s.split(' ')] a.sort() for i in range(1,n): if a[i] - a[i-1] > 1: return 'NO' return 'YES' for i in range(tests): print(solve())
A triple of numbers is said to be poor when two of those numbers are equal but the other number is different from those two numbers. You will be given three integers A, B, and C. If this triple is poor, print `Yes`; otherwise, print `No`. Constraints * A, B, and C are all integers between 1 and 9 (inclusive). Input...
3
if len(set(list(map(int,input().split()))))==2:print('Yes') else:print('No')
Alice guesses the strings that Bob made for her. At first, Bob came up with the secret string a consisting of lowercase English letters. The string a has a length of 2 or more characters. Then, from string a he builds a new string b and offers Alice the string b so that she can guess the string a. Bob builds b from a...
3
# import sys # sys.stdin = open('input.txt', 'r') # sys.stdout = open('output.txt', 'w') def ii():return int(input()) def si():return input() def li():return list(map(int,input().split())) def iwl():return map(int,input().split()) t=ii() for i in range(t): s=si() i=0 ans="" while(i<len(s)): if(i==0 or i==len(s)-1...
Takahashi has two positive integers A and B. It is known that A plus B equals N. Find the minimum possible value of "the sum of the digits of A" plus "the sum of the digits of B" (in base 10). Constraints * 2 ≀ N ≀ 10^5 * N is an integer. Input Input is given from Standard Input in the following format: N Outp...
1
s = sum(map(int,raw_input())) if s == 1: print 10 else: print s
We will play a one-player game using a number line and N pieces. First, we place each of these pieces at some integer coordinate. Here, multiple pieces can be placed at the same coordinate. Our objective is to visit all of the M coordinates X_1, X_2, ..., X_M with these pieces, by repeating the following move: Move...
3
N,M,*X=map(int,open(0).read().split()) X.sort() print(0 if N>=M else sum(sorted(abs(X[i+1]-X[i])for i in range(M-1))[:M-N]))
A median of an array of integers of length n is the number standing on the ⌈ {n/2} βŒ‰ (rounding up) position in the non-decreasing ordering of its elements. Positions are numbered starting with 1. For example, a median of the array [2, 6, 4, 1, 3, 5] is equal to 3. There exist some other definitions of the median, but i...
3
""" Author - Satwik Tiwari . 17th NOV , 2020 - Tuesday """ #=============================================================================================== #importing some useful libraries. from __future__ import division, print_function from fractions import Fraction import sys import os from io import Byte...
A string s of length n can be encrypted by the following algorithm: * iterate over all divisors of n in decreasing order (i.e. from n to 1), * for each divisor d, reverse the substring s[1 ... d] (i.e. the substring which starts at position 1 and ends at position d). For example, the above algorithm applied t...
3
n=int(input()) s=input() m=n for i in range(2,int(n/2)+1): if n%i==0: s1=s[0:i] s=s1[::-1]+s[i:n] print (s[::-1])
Having learned the multiplication table, Takahashi can multiply two integers between 1 and 9 (inclusive) together. He cannot do any other calculation. Given are two integers A and B. If Takahashi can calculate A \times B, print the result; if he cannot, print `-1` instead. Constraints * 1 \leq A \leq 20 * 1 \leq B ...
3
n,m=map(int,input().split()) if(n<=9 and m<=9): print(n*m) else: print(-1)
You are given three positive integers n, a and b. You have to construct a string s of length n consisting of lowercase Latin letters such that each substring of length a has exactly b distinct letters. It is guaranteed that the answer exists. You have to answer t independent test cases. Recall that the substring s[l ...
3
_ORD_A = ord('a') def getNextLetter(currentLetter, b): currentLetterOrd = ord(currentLetter) currentLetterIndex = currentLetterOrd - _ORD_A nextLetterIndex = currentLetterIndex + 1 if nextLetterIndex > b - 1: nextLetterIndex = 0 nextLetterIndex return chr(nextLetterInde...
Takahashi has decided to distribute N AtCoder Crackers to K users of as evenly as possible. When all the crackers are distributed, find the minimum possible (absolute) difference between the largest number of crackers received by a user and the smallest number received by a user. Constraints * 1 \leq N,K \leq 100 * A...
3
print(int(eval(input().replace(" ","%"))>0))
Bike is interested in permutations. A permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] is not. A permutation triple of permutations of length n (a, b, c) is called a...
3
n = int(input()) if n % 2 == 0: print (-1) else: for i in range (0, n): if i == n - 1: print (i) else: print (i, end = ' ') for i in range (0, n): if i == n - 1: print (i) else: print (i, end = ' ') for i in range (0, n): ...
High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters. Vasya can change no more than k characters of the original string. W...
3
def solve(i, j): alpha = { 'a': 0, 'b': 0 } alpha[string[i]] += 1 alpha[string[j]] += 1 m = 0 while i < j < len(string): a = alpha['a'] b = alpha['b'] if a <= k or b <= k: m = max(m, j-i+1) if a > k and b > k: alpha[string[i]] -= 1 ...
Ashish and Vivek play a game on a matrix consisting of n rows and m columns, where they take turns claiming cells. Unclaimed cells are represented by 0, while claimed cells are represented by 1. The initial state of the matrix is given. There can be some claimed cells in the initial state. In each turn, a player must ...
3
for _ in range(int(input())): n,m=map(int,input().split()) #list1=[[0 for j in range(m)]for i in range(n)] list1=[] for i in range(n): ll=list(map(int,input().split())) list1.append(ll) l=[0 for j in range(m)] # list2=[] # for i in range(m): # s=0 # for j...
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves. We know that several boy&girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair m...
3
a=int(input()) b=list(map(int,input().strip(' ').split(' '))) c=int(input()) d=list(map(int,input().strip(' ').split(' '))) b.sort() d.sort() count=0 for i in range(0,a): for j in range(0,c): if abs(b[i]-d[j])<=1 and d[j]!=-2: d[j]=-2 count+=1 break print(count)
There is a bookshelf which can fit n books. The i-th position of bookshelf is a_i = 1 if there is a book on this position and a_i = 0 otherwise. It is guaranteed that there is at least one book on the bookshelf. In one move, you can choose some contiguous segment [l; r] consisting of books (i.e. for each i from l to r...
3
import sys,bisect,string,math,time,functools,random,fractions from heapq import heappush,heappop,heapify from collections import deque,defaultdict,Counter from itertools import permutations,combinations,groupby rep=range;R=range def Golf():n,*t=map(int,open(0).read().split()) def I():return int(input()) def S_():return...
Arkady invited Anna for a dinner to a sushi restaurant. The restaurant is a bit unusual: it offers n pieces of sushi aligned in a row, and a customer has to choose a continuous subsegment of these sushi to buy. The pieces of sushi are of two types: either with tuna or with eel. Let's denote the type of the i-th from t...
3
#ti= 1 tuna #t2= 2 eel #half and half # max a min chnage the las element each time that the las e is not the same as the # arr[i] #the current element is not the same as the last element, update the answer. def sushiForTwo(n, arr): t=0 e=0 le=0 cL=0 for i in range(len(arr)): if arr[i] ==1 an...
Polygon is not only the best platform for developing problems but also a square matrix with side n, initially filled with the character 0. On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly 2...
3
tests = int(input()) for i in range(tests): n = int(input()) lines = [] for x in range(n): lines.append(input()) result = 1 for x in range(n - 1): if result != 1: break for y in range(n - 1): if lines[x][y] == '1': if lines[x + 1][y] =...
Iahub got bored, so he invented a game to be played on paper. He writes n integers a1, a2, ..., an. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices i and j (1 ≀ i ≀ j ≀ n) and flips all values ak for which their positions are in range [i, j] (that is i ≀ k ≀ j)...
3
num = eval(input()) data = [eval(i) for i in input().split()] count = data.count(1) add = -100 for i in range(num): for j in range(i+1, num+1): k = data[i:j].count(0) - data[i:j].count(1) add = max(add, k) print(count + add)
You are given a string s, consisting of n lowercase Latin letters. A substring of string s is a continuous segment of letters from s. For example, "defor" is a substring of "codeforces" and "fors" is not. The length of the substring is the number of letters in it. Let's call some string of length n diverse if and o...
3
def main(): n = int(input()) s = input() for i in range(n - 1): if s[i] != s[i + 1]: print("YES") print(s[i] + s[i + 1]) return print("NO") main()
You are given a special jigsaw puzzle consisting of nβ‹… m identical pieces. Every piece has three tabs and one blank, as pictured below. <image> The jigsaw puzzle is considered solved if the following conditions hold: 1. The pieces are arranged into a grid with n rows and m columns. 2. For any two pieces that sh...
3
import math from sys import stdin,stdout #% 998244353 from heapq import heapify,heappop,heappush from collections import Counter T = int(stdin.readline()) for i in range(T): #N=int(stdin.readline()) n,m=list(map(int,stdin.readline().split())) if n==1 or m==1: print("YES") elif n==2 and m==2: ...
After seeing the "ALL YOUR BASE ARE BELONG TO US" meme for the first time, numbers X and Y realised that they have different bases, which complicated their relations. You're given a number X represented in base bx and a number Y represented in base by. Compare those two numbers. Input The first line of the input con...
1
X = 0 n, b = map(int, raw_input().split()) ls = raw_input().split() ls.reverse() for i in range(n): X += int(ls[i]) * b ** i Y = 0 n, b = map(int, raw_input().split()) ls = raw_input().split() ls.reverse() for i in range(n): Y += int(ls[i]) * b ** i if X < Y: print '<' elif X == Y: print '=' else: ...
wHAT DO WE NEED cAPS LOCK FOR? Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage. Let's consider that a word has been typed with the Caps lock key accidentall...
3
s = input() first = s[0] last = s.replace(s[0],"",1) if first.islower() and last.isupper(): print(s.capitalize()) elif len(s) == 1: if s.isupper(): print(s.lower()) else: print(s.upper()) elif s.isupper(): print(s.lower()) else: print(s)
Three years have passes and nothing changed. It is still raining in London, and Mr. Black has to close all the doors in his home in order to not be flooded. Once, however, Mr. Black became so nervous that he opened one door, then another, then one more and so on until he opened all the doors in his house. There are ex...
3
n = int(input()) A = [int(x) for x in input().split()] l = A.count(0) r = A.count(1) lo, ro = 0, 0 k = 0 for x in A: if x == 0: lo += 1 else: ro += 1 k += 1 if (lo == l or ro == r): print(k) break
Given is an integer N. Find the number of digits that N has in base K. Constraints * All values in input are integers. * 1 \leq N \leq 10^9 * 2 \leq K \leq 10 Input Input is given from Standard Input in the following format: N K Output Print the number of digits that N has in base K. Examples Input 11 2 O...
3
N,K=map(int,input().split()) x=0 while K**x<=N: x=x+1 print(x)
You are given two very long integers a, b (leading zeroes are allowed). You should check what number a or b is greater or determine that they are equal. The input size is very large so don't use the reading of symbols one by one. Instead of that use the reading of a whole line or token. As input/output can reach huge...
1
a = raw_input() b = raw_input() i = 0 while i < len(a) and a[i] == '0': i += 1 j = 0 while j < len(b) and b[j] == '0': j += 1 a = a[i:] b = b[j:] if(len(a)>len(b)): print ">" elif len(b)>len(a): print "<" else: i = 0 j = 0 while i < len(a) and a[i] == b[j]: i += 1 j += 1 if i == len(a): print "=" else...
You are given an array a_1, a_2, ... , a_n. Array is good if for each pair of indexes i < j the condition j - a_j β‰  i - a_i holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option). For example, if a = [1, 1, ...
3
# https://codeforces.com/contest/1312/problem/B from sys import stdin from random import randint n = int(stdin.readline()) for _ in range(n): stdin.readline() arr = map(int, stdin.readline().split()) # arr = (randint(1, 300) for _ in range(100)) res = sorted(arr, reverse=True) # res = shuffle(arr)...
You have n students under your control and you have to compose exactly two teams consisting of some subset of your students. Each student had his own skill, the i-th student skill is denoted by an integer a_i (different students can have the same skills). So, about the teams. Firstly, these two teams should have the s...
3
from collections import Counter for i in range(int(input())): n = int(input()) arr = [int(i) for i in input().split()] cnt = Counter(arr) dist = len(cnt) - 1 ans = 0 for i in cnt: val = cnt[i] if val > dist: ans = max(ans, min(dist+1, val-1)) elif val == dis...
Let's call an array t dominated by value v in the next situation. At first, array t should have at least 2 elements. Now, let's calculate number of occurrences of each number num in t and define it as occ(num). Then t is dominated (by v) if (and only if) occ(v) > occ(v') for any other number v'. For example, arrays [1...
3
import sys input = sys.stdin.buffer.readline # input = sys.stdin.readline from collections import deque q = int(input()) for _ in range(q): n = int(input()) x = list ( map(int,input().split())) # s=set() shortes =9999999999 dic ={} # dq = deque() for i in range(n): if x[i] in dic.ke...
You are given a string s of length n consisting only of the characters 0 and 1. You perform the following operation until the string becomes empty: choose some consecutive substring of equal characters, erase it from the string and glue the remaining two parts together (any of them can be empty) in the same order. For...
1
import sys testing = len(sys.argv) == 4 and sys.argv[3] == "myTest" interactive = False if testing: cmd = sys.stdout from time import time start_time = int(round(time() * 1000)) readAll = open(sys.argv[1], 'r').read sys.stdout = open(sys.argv[2], 'w') else: readAll = sys.stdin.read # #########...
There are N people, conveniently numbered 1 through N. They were standing in a row yesterday, but now they are unsure of the order in which they were standing. However, each person remembered the following fact: the absolute difference of the number of the people who were standing to the left of that person, and the nu...
1
from collections import Counter n = int(raw_input()) ct = Counter(map(int, raw_input().split())) correct = True for i,j in zip(ct.keys(), ct.values()): if (n % 2) == (i % 2): correct = False elif i >= n: correct = False elif i == 0: if j != 1: correct = False else: ...
After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer. At the start of the day they have x ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. Each person in the q...
3
i = input().split() q = int(i[0]) x = int(i[1]) sadChild = 0 for j in range(q): next = input().split() newIceCream = int(next[1]) if next[0] == '+': x = x + newIceCream else: if x - newIceCream < 0: sadChild = sadChild + 1 else: x = x - newIceCream prin...
Two neighboring kingdoms decided to build a wall between them with some gates to enable the citizens to go from one kingdom to another. Each time a citizen passes through a gate, he has to pay one silver coin. The world can be represented by the first quadrant of a plane and the wall is built along the identity line (...
3
x=int(input()) p=input() c,r,u=0,0,0 for i in range(x-1): if p[i]=='R':r+=1 elif p[i]=='U':u+=1 if u==r: r,u=0,0 if p[i+1]==p[i]:c+=1 print(c) # My code says who am i # I want to burn and born at this way # In my eye there is not any things Except love ...
Cengiz recently learned Fibonacci numbers and now he is studying different algorithms to find them. After getting bored of reading them, he came with his own new type of numbers that he named XORinacci numbers. He defined them as follows: * f(0) = a; * f(1) = b; * f(n) = f(n-1) βŠ• f(n-2) when n > 1, where βŠ• de...
3
t=int(input()) for i in range(t): a,b,n=input().split() a=int(a) b=int(b) n=int(n) k=(n+1)%3 if k==0: print(a^b) if k==1: print(a) if k==2: print(b)
You are given two strings s and t, both consisting only of lowercase Latin letters. The substring s[l..r] is the string which is obtained by taking characters s_l, s_{l + 1}, ..., s_r without changing the order. Each of the occurrences of string a in a string b is a position i (1 ≀ i ≀ |b| - |a| + 1) such that b[i..i...
1
def ind(r,g,low,up): if(up-low==0): if(r[low]>g): return(low) else: return(low+1) elif(up-low==1): if(r[low]>g): return(low) elif(r[low+1]>g): return(low+1) else: return(low+2) else: k=((u...
There are N points in a two-dimensional plane. The initial coordinates of the i-th point are (x_i, y_i). Now, each point starts moving at a speed of 1 per second, in a direction parallel to the x- or y- axis. You are given a character d_i that represents the specific direction in which the i-th point moves, as follows:...
3
n = int(input()) xy = [[],[],[],[]] s = {'L':0,'R':1,'U':2,'D':3} for i in range(n): x,y,d = input().split() xy[s[d]] += [[int(x),int(y)]] q = 10**9 xmax, xmin, ymax, ymin = [-q,-q,-q],[q,q,q],[-q,-q,-q],[q,q,q] sx = [0,2,1,1] sy = [1,1,2,0] for i in range(4): if xy[i]: z = max(xy[i],key=lambda z:z[0]) xm...
The programming competition season has already started and it's time to train for ICPC. Sereja coaches his teams for a number of year and he knows that to get ready for the training session it's not enough to prepare only problems and editorial. As the training sessions lasts for several hours, teams become hungry. Thu...
3
input() p=0 for x in map(int, input().split()): if x<p: p=-1 break p^=x&1 print('YES' if p==0 else 'NO')
A card pyramid of height 1 is constructed by resting two cards against each other. For h>1, a card pyramid of height h is constructed by placing a card pyramid of height h-1 onto a base. A base consists of h pyramids of height 1, and h-1 cards on top. For example, card pyramids of heights 1, 2, and 3 look as follows: ...
3
#auth: starkizard #logic: actually doing what the question asked, but optimized. possible=[2] i=1 j=2 while possible[-1]<=10**9: i+=j possible.append(i*3 - j) j+=1 for _ in range(int(input())): ans=0 x=int(input()) while x >=2: pointer=0 while pointer<len(possible)-1: ...
Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad. Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element eq...
3
n,k=map(int,input().split()) c=0 while k%2==0: k=k//2 c+=1 print(c+1)
Two-gram is an ordered pair (i.e. string of length two) of capital Latin letters. For example, "AZ", "AA", "ZA" β€” three distinct two-grams. You are given a string s consisting of n capital Latin letters. Your task is to find any two-gram contained in the given string as a substring (i.e. two consecutive characters of ...
3
from collections import Counter n = int(input()) s = input() s1 = s[0:(n-1)] s2 = s[1:n] s = [m+str(n) for m,n in zip(s1,s2)] s = Counter(s).most_common(1) print(s[0][0])
You are given two integers n and k. Your task is to find if n can be represented as a sum of k distinct positive odd (not divisible by 2) integers or not. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. The next t lines...
3
MAX = int(1e7) ANS ={True: "YES", False: "NO"} oddNumber = 1 s = 0; a = [0] while s < MAX: s += oddNumber a.append(s) oddNumber += 2 t = int(input()) for i in range(t): n, k = map(int, input().split()) firstTest = (n + k) % 2 == 0 if k < len(a): secondTest = a[k] <= n ...
Manao has a monitor. The screen of the monitor has horizontal to vertical length ratio a:b. Now he is going to watch a movie. The movie's frame has horizontal to vertical length ratio c:d. Manao adjusts the view in such a way that the movie preserves the original frame ratio, but also occupies as much space on the scre...
1
import fractions [a, b, c, d] = map(int, raw_input().split()) screen = fractions.Fraction(a, b) movie = fractions.Fraction(c, d) if screen >= movie: ans = (screen - movie) / screen else: ans = (1 / screen - 1 / movie) * screen print "{}/{}".format(ans.numerator, ans.denominator)
The bear decided to store some raspberry for the winter. He cunningly found out the price for a barrel of honey in kilos of raspberry for each of the following n days. According to the bear's data, on the i-th (1 ≀ i ≀ n) day, the price for one barrel of honey is going to is xi kilos of raspberry. Unfortunately, the b...
3
def main(): n, c = map(int, input().split()) l = list(map(int, input().split())) print(max(0, max(a - b for a, b in zip(l, l[1:])) - c)) main()
You got a job as a marketer in a pet shop, and your current task is to boost sales of cat food. One of the strategies is to sell cans of food in packs with discounts. Suppose you decided to sell packs with a cans in a pack with a discount and some customer wants to buy x cans of cat food. Then he follows a greedy str...
3
import math from collections import deque from sys import stdin, stdout, setrecursionlimit from string import ascii_letters letters = ascii_letters[:26] from collections import defaultdict #from functools import reduce input = stdin.readline #print = stdout.write for _ in range(int(input())): a, b = map(int, inpu...
You need to find if a number can be expressed as sum of two perfect powers. That is, given x find if there exists non negative integers a, b, m, n such that a^m + b^n = x. Input First line of the input contains number of test cases T. It is followed by T lines, each line contains a sinle number x. Output For each te...
1
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' import math def solution(n): t = set() t.add(1) for i in xrange(2, int(math.sqrt(n)) + 1): u = i * i while u < n: t.add(u) u *= i ...
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()) s=list(map(int, input().split())) t=[0 for i in range(6001)] for i in range(len(s)): t[s[i]]+=1 ans=0 for i in range(6001): if t[i]>1: ans += t[i]-1 t[i+1]+=t[i]-1 print(ans)
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. Petya wonders eagerly what minimum lucky number has the sum of digits equal to n. Help him cope with...
3
k=int(input()) x=[k%4, max(-0.1,k-7)%4, max(-0.1,k-14)%4, max(-0.1,k-21)%4] if x.count(0)==0: print("-1") else: y=7*x.index(0) seven=x.index(0) z=(k-y)//4 if z>=7: seven+=z//7*4 z=z%7 print('4'*z+'7'*seven)
Arnab is a robber and he has managed to rob N different strings from Akash. Now he decides to sell these strings in the market to make some profit. But, of all the strings he has, he wants to find the size of the largest anagram group so that he can easily sell that one first and make maximum profit initially. Help him...
1
tc = int(raw_input()) d = {} c = 0 for i in range(0, tc): s = raw_input() x = sorted(s) s = "".join(x) d[s] = d.get(s, 0) + 1 for num in d: if d[num] > c: c = d[num] print c
Polycarp plays a well-known computer game (we won't mention its name). In this game, he can craft tools of two types β€” shovels and swords. To craft a shovel, Polycarp spends two sticks and one diamond; to craft a sword, Polycarp spends two diamonds and one stick. Each tool can be sold for exactly one emerald. How many...
3
import math for i in range (int(input())): a,b=map(int,input().split()) n=min(a,b) print(min(n,(a+b)//3))
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
import sys; import math; inputLine=sys.stdin.readline().split(); n=int(inputLine[0]); m=int(inputLine[1]); a=int(inputLine[2]); if(a>=m and a>=n): flagstones=1 else: flagstones=math.ceil(n/a)*math.ceil(m/a) print (flagstones)
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth. Now Diamond has given Bort a string consisting of only uppercase English letters of length n. There is a great number of "QAQ" in the string (Diamond is so cute!). <image> illustration by ηŒ«ε±‹ https://twitter.com/nekoy...
3
l = list(input()) h = 0 for i in range(len(l)): for j in range(i,len(l)): for n in range(j,len(l)): if l[i] + l[j] + l[n] == "QAQ": h += 1 print(h)
You have reached the final level of Hunger Games and as usual a tough task awaits you. You have a circular dining table and N hungery animals.You need to place them on the table.Each animal has a hunger value. You can place the animals in any order on the circular table.Once you place them you need to calculate the Dan...
1
n=int(raw_input()) hunger=raw_input().split() hunger=[int(i) for i in hunger] hunger.sort() maxs=hunger[1]-hunger[0] for i in range(0,len(hunger)-2): if(hunger[i+2]-hunger[i]>maxs): maxs=hunger[i+2]-hunger[i] if(hunger[-1]-hunger[-2]>maxs): maxs=hunger[-1]-hunger[-2] print maxs
Two famous competing companies ChemForces and TopChemist decided to show their sets of recently discovered chemical elements on an exhibition. However they know that no element should be present in the sets of both companies. In order to avoid this representatives of both companies decided to make an agreement on the ...
3
n1 = int(input()) cf ={} result = 0 for i in range(0,n1): str_in = input() num = [int(n) for n in str_in.split()] cf[num[0]] = num[1] result += num[1] n2 = int(input()) for i in range(0,n2): str_in = input() num = [int(n) for n in str_in.split()] if num[0] in cf: if num[1] > cf[num[0...
A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not. Ahcl wants to construct a beautiful string. He has a string s, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each c...
3
from sys import stdin, stdout from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log from collections import defaultdict as dd, deque from heapq import merge, heapify, heappop, heappush, nsmallest from bisect import bisect_left as bl, bisect_right as br, bisect mod = pow(10, 9) + 7 mod2 = 998244353...
Let's say string s has period k if s_i = s_{i + k} for all i from 1 to |s| - k (|s| means length of string s) and k is the minimum positive integer with this property. Some examples of a period: for s="0101" the period is k=2, for s="0000" the period is k=1, for s="010" the period is k=2, for s="0011" the period is k=...
3
for _ in range(int(input())): s=input() print([s,['01'*len(s),'10'*len(s)][int(s[0])]]['1' in s and '0' in s])
You manage 4 buildings, each of which has 3 floors, each of which consists of 10 rooms. Write a program which reads a sequence of tenant/leaver notices, and reports the number of tenants for each room. For each notice, you are given four integers b, f, r and v which represent that v persons entered to room r of fth fl...
1
import sys printf = sys.stdout.write bilt1 = [0] * 30 bilt2 = [0] * 30 bilt3 = [0] * 30 bilt4 = [0] * 30 sha = "#" * 20 count = 0; x = input() for i in range(x): b,f,r,v =map(int, raw_input().split()) if b == 1: bilt1[((f - 1) * 10) + (r - 1)] = bilt1[((f - 1) * 10) + (r - 1)] + v elif b == 2: ...
You are given a positive integer n, it is guaranteed that n is even (i.e. divisible by 2). You want to construct the array a of length n such that: * The first n/2 elements of a are even (divisible by 2); * the second n/2 elements of a are odd (not divisible by 2); * all elements of a are distinct and positi...
3
t = int(input()) for ig in range(t): n = int(input()) r = n//2 if(r&1): print('NO') else: print('YES') ele = 2 for i in range(r): print(ele,end= ' ') ele+=2 ele = 1 for i in range(r-1): print(ele,end=' ') ele...
Find the minimum area of a square land on which you can place two identical rectangular a Γ— b houses. The sides of the houses should be parallel to the sides of the desired square land. Formally, * You are given two identical rectangles with side lengths a and b (1 ≀ a, b ≀ 100) β€” positive integers (you are given ...
3
t = int(input()) for _ in range(t): a, b = map(int, input().split()) if a > b: a, b = b, a x = max(2 * a, b) print(x ** 2)
A group of n dancers rehearses a performance for the closing ceremony. The dancers are arranged in a row, they've studied their dancing moves and can't change positions. For some of them, a white dancing suit is already bought, for some of them β€” a black one, and for the rest the suit will be bought in the future. On ...
1
n,a,b = map(int, raw_input().split()) t = map(int,raw_input().split()) wyn = 0 for x in range(0,len(t),+1): if x>(len(t))-x-2: break if (t[x] == 0 and t[len(t)-1-x] == 1) or (t[x]==1 and t[len(t)-1-x] == 0): print -1 exit(0) elif (t[x] == 0 and t[len(t)-1-x] == 2) or (t[x] == 2 and t...
"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 ...
1
import string inp = raw_input().split(" ") num_n = string.atoi(inp[0]) num_k = string.atoi(inp[1]) inplist = raw_input().split(" ") listn = [] for i in range(0,num_n): listn.append(string.atoi(inplist[i])) listn.sort(reverse=True) #print listn, if listn[num_k-1]!=0: result = num_k for i in range(num_k,num_n...
Facetook is a well known social network website, and it will launch a new feature called Facetook Priority Wall. This feature will sort all posts from your friends according to the priority factor (it will be described). This priority factor will be affected by three types of actions: * 1. "X posted on Y's wall" (...
1
m = raw_input() score = {'posted' : 15, 'commented': 10, 'likes' : 5} cnt = {} for i in xrange(input()): str = raw_input().split() cnt.setdefault(str[0], 0) cnt.setdefault(str[-2][:-2], 0) if str[0] == m or str[-2][:-2] == m: cnt[str[0]] -= score[str[1]] cnt[str[-2][:-2]] -= score[str[1]...
Takahashi loves the number 7 and multiples of K. Where is the first occurrence of a multiple of K in the sequence 7,77,777,\ldots? (Also see Output and Sample Input/Output below.) If the sequence contains no multiples of K, print `-1` instead. Constraints * 1 \leq K \leq 10^6 * K is an integer. Input Input is giv...
3
k=int(input()) if k%2<1 or k%5<1: print(-1) exit() a,t,m=1,7,0 while 1: t=t*10%k m+=t if m%k: a+=1 else: break print(a)
Mashmokh works in a factory. At the end of each day he must turn off all of the lights. The lights on the factory are indexed from 1 to n. There are n buttons in Mashmokh's room indexed from 1 to n as well. If Mashmokh pushes button with index i, then each light with index not less than i that is still turned on turn...
3
X = list(map(int, input().split())) Lights = [0 for i in range(X[0])] Buttons = list(map(int, input().split())) for i in Buttons: for j in range(i - 1, len(Lights)): if Lights[j] == 0: Lights[j] = i print(*Lights)
You're given an integer n. For every integer i from 2 to n, assign a positive integer a_i such that the following conditions hold: * For any pair of integers (i,j), if i and j are coprime, a_i β‰  a_j. * The maximal value of all a_i should be minimized (that is, as small as possible). A pair of integers is call...
3
from math import * from collections import Counter,defaultdict,deque from sys import stdin, stdout input = stdin.readline I=lambda:int(input()) M =lambda:map(int,input().split()) LI=lambda:list(map(int,input().split())) for _ in range(1): n=I() a=[0]*(n+1) i=2;c=1 while i<=n: if not a[i]: for j in ran...
During the break the schoolchildren, boys and girls, formed a queue of n people in the canteen. Initially the children stood in the order they entered the canteen. However, after a while the boys started feeling awkward for standing in front of the girls in the queue and they started letting the girls move forward each...
3
n,k = [int(i) for i in input().split()] s = input() for i in range(k): s = s.replace('BG','GB') print(s)