problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days. In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day. Du will chat in the group for n days. On the i-th day: * If Du can speak, he'll make fun of Boboniu ...
3
#!/usr/bin/env python3 import sys input = sys.stdin.readline n, d, m = map(int, input().split()) a = [int(item) for item in input().split()] muzzle = [] no_muzzle = [] for item in a: if item <= m: no_muzzle.append(item) else: muzzle.append(item) no_muzzle.sort(reverse=True) muzzle.sort(revers...
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." — an excerpt from contest rules. A total of n participants took part in the contest (n ≥ k), and you already know their scores. Calculate how many ...
3
a,b=map(int,input().split()) score=[int(x) for x in input().split()] num=0 for i in range(a): if score[i]>=score[b-1] and score[i]>0: num+=1 else: pass print(num)
Peter likes to travel by train. He likes it so much that on the train he falls asleep. Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour. The boy start...
3
import string s = input() x = input() y = input() a = False b = False if x in s: if y in s[s.find(x) + len(x):]: a = True s = s[::-1] if x in s: if y in s[s.find(x) + len(x):]: b = True if a and b: print("both") elif a: print("forward") elif b: print("backward") else: print("fant...
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had a red socks and b blue socks. According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot. Every day Vasya puts on new socks in the morning and ...
3
a=list(map(int,input().split())) if a[0]<a[1]: print(a[0],end=" ") print(int((a[1]-a[0])/2)) elif a[0]==a[1]: print(a[0],end=" ") print("0") else: print(a[1],end=" ") print(int((a[0]-a[1])/2))
Little beaver is a beginner programmer, so informatics is his favorite subject. Soon his informatics teacher is going to have a birthday and the beaver has decided to prepare a present for her. He planted n flowers in a row on his windowsill and started waiting for them to grow. However, after some time the beaver noti...
3
def can(val, arr, m, w): lis = [] n = len(arr) for i in range(n): lis.append(max(0, val - arr[i])) yaha = [0] * n ans = lis[0] curr = lis[0] if(w < n): yaha[w] = -(lis[0]) for i in range(n): curr += yaha[i] # print(i, lis[i], curr) rem = max(0, lis...
After winning gold and silver in IOI 2014, Akshat and Malvika want to have some fun. Now they are playing a game on a grid made of n horizontal and m vertical sticks. An intersection point is any point on the grid which is formed by the intersection of one horizontal stick and one vertical stick. In the grid shown be...
1
n, m = map(int,raw_input().split()) if(n<=m): if(n%2==1): print "Akshat" else: print "Malvika" else: if(m%2==1): print "Akshat" else: print "Malvika"
Two players play a simple game. Each player is provided with a box with balls. First player's box contains exactly n1 balls and second player's box contains exactly n2 balls. In one move first player can take from 1 to k1 balls from his box and throw them away. Similarly, the second player can take from 1 to k2 balls f...
3
n1,n2,k1,k2 = map(int, input().split(' ')) if n1 <= n2 : print("Second") else : print("First")
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the oppo...
3
n = int(input()) mas = [] s = '' new_mas = [] for i in range(n): mas.append(input()) s += mas[0] for i in range(1, len(mas)): if s[len(s)-1] == mas[i][0]: new_mas.append(s) s = mas[i] else: s += mas[i] print(len(new_mas)+1)
Ivar the Boneless is a great leader. He is trying to capture Kattegat from Lagertha. The war has begun and wave after wave Ivar's warriors are falling in battle. Ivar has n warriors, he places them on a straight line in front of the main gate, in a way that the i-th warrior stands right after (i-1)-th warrior. The fir...
3
def next(A,n, x): l = 0 r = n-1 p = -1 while l <= r: m = (l+r)//2 if A[m] <= x: l = m+1 else: p = m r = m-1 return p N, Q = map(int, input().split()) A = list(map(int, input().split())) B = list(map(int, input().split())) P = [] P.app...
Homer has two friends Alice and Bob. Both of them are string fans. One day, Alice and Bob decide to play a game on a string s = s_1 s_2 ... s_n of length n consisting of lowercase English letters. They move in turns alternatively and Alice makes the first move. In a move, a player must choose an index i (1 ≤ i ≤ n) ...
3
####################################################################################################################### # Author: BlackFyre # Language: PyPy 3.7 ####################################################################################################################### from sys import stdin, stdou...
Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks. Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off. You know that there will be n interesting minutes t1, t2, ..., tn. Yo...
1
def input_list(): s = raw_input() s = s.split(' ') l = [0 for i in range(len(s))] for i in range(len(s)): l[i] = int(s[i]) return l n = int(raw_input()) a = input_list() a = [0] + a + [90] t = 90 for i in range(n + 1): if a[i + 1] - a[i] > 15: t = a[i] + 15 break ...
Little Vasya has received a young builder’s kit. The kit consists of several wooden bars, the lengths of all of them are known. The bars can be put one on the top of the other if their lengths are the same. Vasya wants to construct the minimal number of towers from the bars. Help Vasya to use the bars in the best way ...
1
raw_input() d={} for e in raw_input().split(): a = int(e) d[a] = d.get(a,0) + 1 print max(d.values()), len(d)
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(list(map(int,input().split())),reverse=True) ans=-a[0] for i in range(n): ans+=a[i//2] print(ans)
Very soon there will be a parade of victory over alien invaders in Berland. Unfortunately, all soldiers died in the war and now the army consists of entirely new recruits, many of whom do not even know from which leg they should begin to march. The civilian population also poorly understands from which leg recruits beg...
1
def main(): n = input() left = [] right = [] sumleft = 0 sumright = 0 for i in range(n) : lr = [int(j) for j in raw_input().split()] left.append(lr[0]) right.append(lr[1]) sumleft += lr[0] sumright += lr[1] ret = abs(sumleft-sumright) ans = 0 for i in range(n): if ret < abs((sumleft-left[i]+right[i...
A TV show called "Guess a number!" is gathering popularity. The whole Berland, the old and the young, are watching the show. The rules are simple. The host thinks of an integer y and the participants guess it by asking questions to the host. There are four types of acceptable questions: * Is it true that y is stric...
3
n=int(input()) k=-2000000000 l=2000000000 for x in range(n): a,z,b=input().split() a=a z=int(z) b=b if(a=='>'and b=='Y'and k<z+1): k=z+1 elif(a=='>='and b=='Y'and k<z): k=z elif(a=='>'and b=='N'and l>z): l=z elif(a=='>='and b=='N'and l>z-1): l=z-1 elif(a=='<'and b=='Y'and l>z-1): l=z-1 elif(a=='<='a...
Innokentiy decides to change the password in the social net "Contact!", but he is too lazy to invent a new password by himself. That is why he needs your help. Innokentiy decides that new password should satisfy the following conditions: * the length of the password must be equal to n, * the password should con...
3
li = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] n, k = map(int , input().split()) li = li[:k] ans ="" i = 0 while(len(ans) < n): ans += li[i] i += 1 i %= k print(ans)
Requirements * All inputs are of non-negative integer value. * T_{\text{max}} = 10000 * 200 \leq |V| \leq 400 * 1.5 |V| \leq |E| \leq 2 |V| * 1 \leq u_{i}, v_{i} \leq |V| (1 \leq i \leq |E|) * 1 \leq d_{u_i, v_i} \leq \lceil 4\sqrt{2|V|} \rceil (1 \leq i \leq |E|) * The given graph has no self-loops / multiple edges a...
3
#!usr/bin/env python3 from collections import defaultdict,deque from heapq import heappush, heappop import sys import math import bisect import random def LI(): return [int(x) for x in sys.stdin.readline().split()] def I(): return int(sys.stdin.readline()) def LS():return [list(x) for x in sys.stdin.readline().split()]...
Alena has successfully passed the entrance exams to the university and is now looking forward to start studying. One two-hour lesson at the Russian university is traditionally called a pair, it lasts for two academic hours (an academic hour is equal to 45 minutes). The University works in such a way that every day it...
3
def func(s): if len(s)<3: return sum(s) k=0 for i in range(1,len(s)-1): if s[i]==0: if s[i-1]==s[i+1]==1: k+=1 return sum(s)+k n=int(input()) s=list(map(int,input().split())) print(func(s))
It's a walking tour day in SIS.Winter, so t groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another. Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P": * "A" corresponds to an angry...
3
import sys t = int(sys.stdin.readline()) for _ in range(t): k = int(sys.stdin.readline()) S = sys.stdin.readline() m = 0 i = 0 c = 0 while i != k: if S[i] == "P": if c != 0: c+=1 elif S[i] == "A": if c != 0: if m < c-1: ...
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in t...
1
from collections import defaultdict def palidrome(s): i = 0 l = len(s)-1 while i < l: if s[i] != s[l]: return False i+=1 l+=-1 return True def solve(l, s): st = s[l:] + s[:l] return palidrome(st) and st != s s = raw_input() m = defaultdict(int) for i in s: m[...
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 for j in range(n): inp = [int(x) for x in input().split(" ")] if sum(inp) >= 2: i += 1 print(i)
Compute A \times B. Constraints * 1 \leq A \leq 100 * 1 \leq B \leq 100 * All values in input are integers. Input Input is given from Standard Input in the following format: A B Output Print the value A \times B as an integer. Examples Input 2 5 Output 10 Input 100 100 Output 10000
3
#--- a, b = map(int, input().split()) print(a*b)
zscoder loves simple strings! A string t is called simple if every pair of adjacent characters are distinct. For example ab, aba, zscoder are simple whereas aa, add are not simple. zscoder is given a string s. He wants to change a minimum number of characters so that the string s becomes simple. Help him with this tas...
3
s = list(input()) chng = dict() for i in range(26): chng[chr(ord('a')+i)] = chr(ord('a')+i+1) chng['z'] = 'a' for i in range(1, len(s)): if s[i] == s[i-1]: s[i] = chng[s[i]] if i+1 < len(s) and s[i] == s[i+1]: s[i] = chng[s[i]] print(''.join(s))
While walking down the street Vanya saw a label "Hide&Seek". Because he is a programmer, he used & as a bitwise AND for these two words represented as a integers in base 64 and got new word. Now Vanya thinks of some string s and wants to know the number of pairs of words of length |s| (length of s), such that their bit...
1
def f(): M = 10**9+7 s = raw_input().strip() n = len(s) ones = 0 for c in s: if '0' <= c <= '9': x = ord(c)-ord('0') elif 'A' <= c <= 'Z': x = 10 + ord(c)-ord('A') elif 'a' <= c <= 'z': x = 36 + ord(c)-ord('a') elif c == '-': ...
There are n integers b1, b2, ..., bn written in a row. For all i from 1 to n, values ai are defined by the crows performing the following procedure: * The crow sets ai initially 0. * The crow then adds bi to ai, subtracts bi + 1, adds the bi + 2 number, and so on until the n'th number. Thus, ai = bi - bi + 1 + bi...
3
T_ON = 0 DEBUG_ON = 0 MOD = 998244353 def solve(): n = read_int() A = read_ints() B = A[:] for i in range(n-1): B[i] += A[i+1] print_nums(B) def main(): T = read_int() if T_ON else 1 for i in range(T): solve() def debug(*xargs): if DEBUG_ON: print(*xargs) ...
When new students come to the Specialized Educational and Scientific Centre (SESC) they need to start many things from the beginning. Sometimes the teachers say (not always unfairly) that we cannot even count. So our teachers decided to teach us arithmetics from the start. And what is the best way to teach students add...
3
t = input() s = t.split('+') s = [s[0]] + s[1].split('=') a, b, c = len(s[0]), len(s[1]), len(s[2]) if a + b == c: pass elif b > 1 and a + b - 1 == c + 1: b -= 1; c += 1 elif a > 1 and a - 1 + b == c + 1: a -= 1; c += 1 elif c > 1 and a + b + 1 == c - 1: b += 1; c -= 1 else: print('Impossible') ...
There are n kangaroos with pockets. Each kangaroo has a size (integer number). A kangaroo can go into another kangaroo's pocket if and only if the size of kangaroo who hold the kangaroo is at least twice as large as the size of kangaroo who is held. Each kangaroo can hold at most one kangaroo, and the kangaroo who is ...
1
def main(): n=input() s=sorted(int(raw_input()) for i in xrange(n)) m=n/2-1 r=n-1 R=0 while m>=0: if s[m]*2 <= s[r]: r-=1 R+=1 m-=1 print n-R if __name__ == '__main__': main()
Dreamoon wants to climb up a stair of n steps. He can climb 1 or 2 steps at each move. Dreamoon wants the number of moves to be a multiple of an integer m. What is the minimal number of moves making him climb to the top of the stairs that satisfies his condition? Input The single line contains two space separated i...
3
n,m = [int(x) for x in input().split()] for i in range((n + 1)//2, n + 1): if i % m == 0: print(i) exit(0) print(-1)
Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to th...
1
import collections s = [int(j) for j in raw_input().split()] counter = collections.Counter(s) print 4-len(counter)
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...
1
x = int(raw_input()) if x>2 and not x%2: print("YES") else: print("NO")
You are given two integers a and b. You may perform any number of operations on them (possibly zero). During each operation you should choose any positive integer x and set a := a - x, b := b - 2x or a := a - 2x, b := b - x. Note that you may choose different values of x in different operations. Is it possible to mak...
3
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools # import time,random,resource # sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**10 mod = 10**9+7 mod2 = 998244353 dd = [(-1,0),(0,1),(1,0),(0,-1)] ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(...
You have two integers l and r. Find an integer x which satisfies the conditions below: * l ≤ x ≤ r. * All digits of x are different. If there are multiple answers, print any of them. Input The first line contains two integers l and r (1 ≤ l ≤ r ≤ 10^{5}). Output If an answer exists, print any of them. Oth...
3
# n, m = map(int,input().split()) def is_dictinct(num): return len(set(str(num))) == len(str(num)) n, m = [int(num) for num in input().split()] ans = -1 for i in range(n, m+1): if(is_dictinct(i)): ans = i break 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
g = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'z'] s = input() s1 = '' for i in range(len(s)): if s[i] in g: s1 += '.' + s[i] elif chr(ord(s[i]) + 32) in g: s1 += '.' + chr(ord(s[i]) + 32) print(s1)
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
t = int(input()) for i in range(t): n = int(input()) ones = n // 2 n = n % 2 nines = 0 if n >= 4: nines = n // 4 n = n % 4 ones = ones - nines sevens = 0 if n >= 1: sevens = n ones = ones - sevens ans = '' for i in range(nines): ans += '9' for i in range(sevens): ans += '7' ...
Snuke has decided to play a game using cards. He has a deck consisting of N cards. On the i-th card from the top, an integer A_i is written. He will perform the operation described below zero or more times, so that the values written on the remaining cards will be pairwise distinct. Find the maximum possible number of...
1
N = int(raw_input()) A = map(int, raw_input().split()) s = len(set(A)) if (N - s) % 2 != 0: s -= 1 print s
Johny likes numbers n and k very much. Now Johny wants to find the smallest integer x greater than n, so it is divisible by the number k. Input The only line contains two integers n and k (1 ≤ n, k ≤ 109). Output Print the smallest integer x > n, so it is divisible by the number k. Examples Input 5 3 Output 6...
3
s= input("").split(' ') n= int(s[0]) k= int(s[1]) if k>n: print(str(k)) else: a=int(n/k) counter= k*a while True: if(counter>n): print(str(counter)) break counter=counter+k
The R1 company has recently bought a high rise building in the centre of Moscow for its main office. It's time to decorate the new office, and the first thing to do is to write the company's slogan above the main entrance to the building. The slogan of the company consists of n characters, so the decorators hung a lar...
3
n,k=map(int,input().split()) los=input() if n==1: print('PRINT',los,sep=' ') else: if k>n/2 and k!=n and k!=1: for i in range(n-k): print('RIGHT') for i in range(n): print('PRINT',los[n-i-1],sep=' ') if i!=n-1: print('LEFT') if k<=n/2 and k...
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
a, b, c = map(int, input().split()) num = input() s = 0 for i in range(a - b, a): if i == a - 1 - c: if num[i] == "0": s += 1 elif num[i] == "1": s += 1 print(s)
Rng is going to a festival. The name of the festival is given to you as a string S, which ends with `FESTIVAL`, from input. Answer the question: "Rng is going to a festival of what?" Output the answer. Here, assume that the name of "a festival of s" is a string obtained by appending `FESTIVAL` to the end of s. For ex...
3
#!/usr/bin/env python3 # -*- coding: utf-8 -*- s = input() head = s[:-8] print(head)
JATC and his friend Giraffe are currently in their room, solving some problems. Giraffe has written on the board an array a_1, a_2, ..., a_n of integers, such that 1 ≤ a_1 < a_2 < … < a_n ≤ 10^3, and then went to the bathroom. JATC decided to prank his friend by erasing some consecutive elements in the array. Since he...
3
n=int(input()) a=list(map(int,input().split())) ct=0 flag=0 m=0 for i in range(n-1): if a[i]==a[i+1]-1: if a[i]==1: ct+=1 if a[i+1]==1000: ct+=1 ct+=1 m=max(ct-1,m) else: ct=0 print(m)
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm: * if the last digit of the number is non-zero, she decreases the number by one; * if the last digit of the number is ze...
3
n, k = map(int, input().split()) for _ in range(k): if n%10 != 0: n-=1 else: n = int(n/10) print(n)
Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it ...
1
a = input() #print a b = [] sum = 0 c = [] for i in range(a): #print i b.append(raw_input().split()) sum = sum - int(b[i][0]) + int(b[i][1]) #print b[i][1] c.append(sum) #list(c) print max(c)
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
s=str(input()) if [4,7].count(s.count('4')+s.count('7'))!=0: print('YES') else: print('NO')
<image> There is a container that is bifurcated as shown in the figure. Drop 10 balls numbered from 1 to 10 through the opening A of the container and place the balls in the left cylinder B or the right cylinder C. Since plate D can rotate left and right around the fulcrum E, you can move plate D to decide whether to...
1
N = int(raw_input()) for i in range(N): A = map(int, raw_input().split()) B, C = [], [] B.append(0) C.append(0) flag = True for i in A: if B[-1] < i: B.append(i) elif C[-1] < i: C.append(i) else: flag = False break if flag: print "YES" else: print "N...
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
numberOfTestCases = 1 def nL (n, lucky_digits): cd = 0 for i in str(n): if int(i) in lucky_digits: cd += 1 # print(cd) if cd in lucky_digits: return "YES" return "NO" for test in range(numberOfTestCases): arr = [int(i) for i in input().split(" ")] # print (...
You're given an array a of length 2n. Is it possible to reorder it in such way so that the sum of the first n elements isn't equal to the sum of the last n elements? Input The first line contains an integer n (1 ≤ n ≤ 1000), where 2n is the number of elements in the array a. The second line contains 2n space-separat...
3
n = int(input().strip()) arr = list(map(int, input().strip().split())) arr.sort() if sum(arr[:n]) == sum(arr[n:]): print(-1) else: for elem in arr: print(elem, end=" ")
You are given an array a_1, a_2, ... , a_n, which is sorted in non-decreasing order (a_i ≤ a_{i + 1}). Find three indices i, j, k such that 1 ≤ i < j < k ≤ n and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to a_i, a_j and a_k (for example it is possible to...
3
for z in range(int(input())): n = int(input()) a = list(map(int, input().split())) if a[0] + a[1] <= a[n-1]: print(1,2,n) else: print(-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
s = input().split("WUB") f = False for p in s: if p != '': if f: print(' ', end='') print(p, end='') f = True print()
You are given an array a of n integers. Count the number of pairs of indices (i, j) such that i < j and a_j - a_i = j - i. Input The first line contains one integer t (1 ≤ t ≤ 10^4). Then t test cases follow. The first line of each test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5). The second line of each test ca...
3
from collections import Counter from sys import stdin def read_int(): return int(stdin.readline()) def read_ints(): return map(int, stdin.readline().split()) t = read_int() for case_num in range(t): n = read_int() a = list(read_ints()) cnt = Counter() ans = 0 for i, num in enumerate(a)...
Little Vova studies programming in an elite school. Vova and his classmates are supposed to write n progress tests, for each test they will get a mark from 1 to p. Vova is very smart and he can write every test for any mark, but he doesn't want to stand out from the crowd too much. If the sum of his marks for all tests...
1
import sys def main(): N, K, P, X, Y = map(int, raw_input().split()) grade = map(int, raw_input().split()) keep = [0 for i in range(N)] p = N-1 answer = [] TK = N-K grade.sort() for i in range(K-1, -1, -1): if(grade[i] >= Y): keep[p] = grade[i] p -= 1...
This is an interactive problem. Vasya and Petya are going to play the following game: Petya has some positive integer number a. After that Vasya should guess this number using the following questions. He can say a pair of non-negative integer numbers (x, y). Petya will answer him: * "x", if (x mod a) ≥ (y mod a). ...
3
import sys def question(x, y, a): #a = 1543 if x % a >= y % a: return "x" else: return "y" def real_question(x, y): print("? {0} {1}".format(x, y)) sys.stdout.flush() return input() class CodeforcesTask1103BSolution: def __init__(self): self.result = '' def...
Polycarp has created his own training plan to prepare for the programming contests. He will train for n days, all days are numbered from 1 to n, beginning from the first. On the i-th day Polycarp will necessarily solve a_i problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first...
3
import sys import math as mt import bisect #input=sys.stdin.readline #t=int(input()) t=1 def solve(): suma=sum(l[:]) suma1=0 for i in range(n): suma1+=l[i] if suma1>=(suma/2): return i+1 for _ in range(t): n=int(input()) #a...
Ayush, Ashish and Vivek are busy preparing a new problem for the next Codeforces round and need help checking if their test cases are valid. Each test case consists of an integer n and two arrays a and b, of size n. If after some (possibly zero) operations described below, array a can be transformed into array b, the ...
3
for _ in range(int(input())): n, a, b = int(input()), list(map(int, input().split())), list(map(int, input().split())) a1, b1 = [], [] for i in range((n + 1) // 2): a1.append([min(a[i], a[n - i - 1]), max(a[i], a[n - i - 1])]) b1.append([min(b[i], b[n - i - 1]), max(b[i], b[n - i - 1])]) ...
At first, there was a legend related to the name of the problem, but now it's just a formal statement. You are given n points a_1, a_2, ..., a_n on the OX axis. Now you are asked to find such an integer point x on OX axis that f_k(x) is minimal possible. The function f_k(x) can be described in the following way: ...
1
for _ in range(input()): n,k=map(int,raw_input().split()) a=map(int,raw_input().split()) d=a[-1]-a[0] p=0 for i in range(n-k): m=a[i+k]-a[i] if m<d: d=m p=i print a[p]+d//2
AtCoDeer is thinking of painting an infinite two-dimensional grid in a checked pattern of side K. Here, a checked pattern of side K is a pattern where each square is painted black or white so that each connected component of each color is a K × K square. Below is an example of a checked pattern of side 3: cba927b2484f...
3
n, k = map(int, input().split()) d = [[0 for _ in range(k+1)] for _ in range(k+1)] e = [[0 for _ in range(k+1)] for _ in range(k+1)] cnt_d, cnt_e = 0, 0 for _ in range(n): x, y, c = input().split() x, y = int(x), int(y) res = (x // k + y // k) % 2 if (res == 0 and c == 'B') or (res == 1 and c == 'W'):...
N tiles are arranged in a row from left to right. The initial color of each tile is represented by a string S of length N. The i-th tile from the left is painted black if the i-th character of S is `0`, and painted white if that character is `1`. You want to repaint some of the tiles black or white, so that any two a...
3
S = input() n = S[::2].count("0") + S[1::2].count("1") print(min(n, len(S) - n))
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...
3
n=int(input()) s=input() if n==1 or n==2: print(s,end=""), elif n%2==1: for i in range(n-1,-1,-1): if i%2!=0: print(s[i],end="") for i in range(0,n): if i%2==0: print(s[i],end="") else: for i in range(n - 1, -1, -1): if i % 2 == 0: print(s...
Snuke, a water strider, lives in a rectangular pond that can be seen as a grid with H east-west rows and W north-south columns. Let (i,j) be the square at the i-th row from the north and j-th column from the west. Some of the squares have a lotus leaf on it and cannot be entered. The square (i,j) has a lotus leaf on i...
3
#!/usr/bin/env python3 import sys import math from bisect import bisect_right as br from bisect import bisect_left as bl sys.setrecursionlimit(2147483647) from heapq import heappush, heappop,heappushpop from collections import defaultdict from itertools import accumulate from collections import Counter from collection...
Amidakuji is a traditional method of lottery in Japan. To make an amidakuji, we first draw W parallel vertical lines, and then draw horizontal lines that connect them. The length of each vertical line is H+1 [cm], and the endpoints of the horizontal lines must be at 1, 2, 3, ..., or H [cm] from the top of a vertical l...
3
# -*- coding: utf-8 -*- #D - Number of Amidakuji import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines MOD = 10**9+7 H,W,K = map(int,readline().split()) facts = [1,1,2,3,5,8,13,21,34] # a = [0] # b = [1] # for i in range(W): # a.append(b[i]) # b.app...
Greg is a beginner bodybuilder. Today the gym coach gave him the training plan. All it had was n integers a1, a2, ..., an. These numbers mean that Greg needs to do exactly n exercises today. Besides, Greg should repeat the i-th in order exercise ai times. Greg now only does three types of exercises: "chest" exercises,...
3
# -*- coding: utf-8 -*- """ Created on Thu Oct 12 19:57:13 2017 @author: ASUS """ n = int (input ()) L = list (map (int , input ().split (' '))) chest = 0 biceps = 0 back = 0 for i in range (len(L)): if (i+1)%3 == 1: chest += L[i] elif (i+1)%3 == 2: biceps += L[i] else : back += L[...
Luckily, Serval got onto the right bus, and he came to the kindergarten on time. After coming to kindergarten, he found the toy bricks very funny. He has a special interest to create difficult problems for others to solve. This time, with many 1 × 1 × 1 toy bricks, he builds up a 3-dimensional object. We can describe ...
3
p = print r,c,h = map(int,input().split()) m=[] a = list(map(int,input().split())) b = list(map(int,input().split())) flag = [] for i in range(r): x=[] x = list(map(int,input().split())) m.append(x) for i in range(r): for j in range(c): if m[i][j] == 1: m[i][j] = min(a[j],b[i]) for...
On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k pe...
1
import math n,l,v1,v2,k=[float(x) for x in raw_input().split()] x= l/(1.0+ ( (v1/(v1+v2)) + (v1/(v2-v1)) ) *((math.ceil(n/k)-1)*((v2-v1)/v2))) print '%0.6f' %(x/v2 +(l-x)/v1)
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=input().split() n=int(n) k=int(k) ln=(2**n)-1 pos=2**(n-1) ans=n while pos!=k: n-=1 pos=2**(n-1) k=abs(((ln//2)+1)-k) ln=(2**n)-1 ans=n print(ans)
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
c,qua = map(int,input().split()) counter = 0 for i in range(c): sign,k = input().split() k = int(k) if sign == "+": qua += k elif sign == "-" and qua >= k: qua -= k else: counter += 1 print(qua,counter)
Takahashi is distributing N balls to K persons. If each person has to receive at least one ball, what is the maximum possible difference in the number of balls received between the person with the most balls and the person with the fewest balls? Constraints * 1 \leq K \leq N \leq 100 * All values in input are intege...
3
a,b = list(map(int,input().split())) print(a%b)
You have a string S of length N. Initially, all characters in S are `1`s. You will perform queries Q times. In the i-th query, you are given two integers L_i, R_i and a character D_i (which is a digit). Then, you must replace all characters from the L_i-th to the R_i-th (inclusive) with D_i. After each query, read th...
3
import sys input = sys.stdin.readline mod = 998244353 n, q = map(int, input().split()) class LazySegTree: def __init__(self, N): self.INF = 2**31-1 self.N = N self.LV = (self.N - 1).bit_length() self.N0 = 2 ** self.LV self.data = [0] * (2 * self.N0) self.lazy = [0]...
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
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ################################## # University of Wisconsin-Madison # Author: Yaqi Zhang ################################## # standard library import sys def main(): T = int(input()) for _ in range(T): n = int(input()) if n // 2 % 2: ...
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem. Pete and Bi...
3
# -*- coding: utf-8 -*- w = int(input()) if w is 2 or w % 2 is not 0: print('NO') else: print('YES')
For a positive integer X, let f(X) be the number of positive divisors of X. Given a positive integer N, find \sum_{K=1}^N K\times f(K). Constraints * 1 \leq N \leq 10^7 Input Input is given from Standard Input in the following format: N Output Print the value \sum_{K=1}^N K\times f(K). Examples Input 4 O...
3
N=int(input()) ans=0 for i in range(1,N+1): ans+=i*(N//i+1)*(N//i)//2 print(ans)
Polycarp has built his own web service. Being a modern web service it includes login feature. And that always implies password security problems. Polycarp decided to store the hash of the password, generated by the following algorithm: 1. take the password p, consisting of lowercase Latin letters, and shuffle the l...
3
for _ in range(int(input())): p = sorted(input()) h = input() x = len(p) printed = False for n in range(len(h)-(x-1)): if sorted(h[n:n+x]) == p: print("YES") printed = True break if not printed: print("NO")
Polycarp has spent the entire day preparing problems for you. Now he has to sleep for at least a minutes to feel refreshed. Polycarp can only wake up by hearing the sound of his alarm. So he has just fallen asleep and his first alarm goes off in b minutes. Every time Polycarp wakes up, he decides if he wants to sleep...
3
import math N = int(input()) for i in range(0, N): a,b,c,d=map(int,input().split()) if(a<=b): print(b) else: if(d>=c): print("-1") else: m = a-b s = c-d v = math.ceil(m/s) print(v*c+b)
Vasya has got three integers n, m and k. He'd like to find three integer points (x_1, y_1), (x_2, y_2), (x_3, y_3), such that 0 ≤ x_1, x_2, x_3 ≤ n, 0 ≤ y_1, y_2, y_3 ≤ m and the area of the triangle formed by these points is equal to nm/k. Help Vasya! Find such points (if it's possible). If there are multiple solutio...
1
n, m, k=map(int, raw_input().split()) def gcd(a, b): return a if b==0 else gcd(b, a%b) if n*m*2%k!=0: print "NO" else: #n*m*2/k if k%2==0: k/=2 g=gcd(n, k) x=n/g y=m/(k/g) else: g=gcd(n, k) x=n/g y=m/(k/g) if x*2<=n: x*=2 else: y*=2 print "YES" print 0, 0 print x, 0 print 0, y
Phoenix has n coins with weights 2^1, 2^2, ..., 2^n. He knows that n is even. He wants to split the coins into two piles such that each pile has exactly n/2 coins and the difference of weights between the two piles is minimized. Formally, let a denote the sum of weights in the first pile, and b denote the sum of weigh...
3
a=int(input()) for i in range(a): a1=[] a2=int(input()) for j in range(a2): a1.append(2**(j+1)) x=len(a1)//2-1 fsum=sum(a1[0:x])+a1[len(a1)-1] msum=sum(a1[x:len(a1)-1]) print(fsum-msum)
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
x=str(input("")) y="47" final=[each for each in x if each in y] z=len(final) z=str(z) u="12356890" sec =[each for each in z if each in u] if(len(sec)>0): print("NO") else: print("YES")
Santa Claus has n candies, he dreams to give them as gifts to children. What is the maximal number of children for whose he can give candies if Santa Claus want each kid should get distinct positive integer number of candies. Santa Class wants to give all n candies he has. Input The only line contains positive integ...
1
import math n = input() a=[1] while sum(a) <= n: a.append(a[-1]+1) a=a[:-1] a[-1] += (n-sum(a)) print len(a) print " ".join(map(str,a))
Given is an integer sequence A_1, ..., A_N of length N. We will choose exactly \left\lfloor \frac{N}{2} \right\rfloor elements from this sequence so that no two adjacent elements are chosen. Find the maximum possible sum of the chosen elements. Here \lfloor x \rfloor denotes the greatest integer not greater than x. ...
3
from collections import defaultdict INF = 2 ** 60 dp = defaultdict(lambda: -INF) n = int(input()) a = list(map(int, input().split())) + [0] * 10 dp[(0, 0)] = 0 dp[(1, 1)] = a[0] for i in range(n): for j in range(i // 2 - 2, i // 2 + 3): dp[(i + 2, j + 1)] = max([dp[(i + 2, j + 1)], dp[(i, j)] + a[i + 1]...
Small, but very brave, mouse Brain was not accepted to summer school of young villains. He was upset and decided to postpone his plans of taking over the world, but to become a photographer instead. As you may know, the coolest photos are on the film (because you can specify the hashtag #film for such). Brain took a ...
3
n, m = map(int, input().split()) q = '#Black&White' colors = 'CMY' a = [(list(input().split())) for i in range(n)] for i in range(n): for j in range(m): if a[i][j] in colors: q = '#Color' print(q)
You are given a matrix a of size n × m consisting of integers. You can choose no more than \left⌊m/2\right⌋ elements in each row. Your task is to choose these elements in such a way that their sum is divisible by k and this sum is the maximum. In other words, you can choose no more than a half (rounded down) of eleme...
3
def read_generator(): while True: tokens = input().split(' ') for t in tokens: yield t reader = read_generator() def readword(): return next(reader) def readint(): return int(next(reader)) def readfloat(): return float(next(reader)) def readline(): return input() d...
On the xy-plane, Snuke is going to travel from the point (x_s, y_s) to the point (x_t, y_t). He can move in arbitrary directions with speed 1. Here, we will consider him as a point without size. There are N circular barriers deployed on the plane. The center and the radius of the i-th barrier are (x_i, y_i) and r_i, r...
3
# coding: utf-8 # Your code here! import sys read = sys.stdin.read readline = sys.stdin.readline xs,ys,xt,yt = map(int,readline().split()) n, = map(int,readline().split()) xyr = [tuple(map(int,readline().split())) for _ in range(n)] + [(xs,ys,0),(xt,yt,0)] """ d: 隣接行列に対する Dijkstra O(N^2) """ def Dijkstra_matrix(d,s...
There are three friend living on the straight line Ox in Lineland. The first friend lives at the point x1, the second friend lives at the point x2, and the third friend lives at the point x3. They plan to celebrate the New Year together, so they need to meet at one point. What is the minimum total distance they have to...
3
a, _, c = sorted(map(int, input().split())) print(c - a)
Polycarp found under the Christmas tree an array a of n elements and instructions for playing with it: * At first, choose index i (1 ≤ i ≤ n) — starting position in the array. Put the chip at the index i (on the value a_i). * While i ≤ n, add a_i to your score and move the chip a_i positions to the right (i.e. r...
3
from collections import defaultdict,deque from sys import stdin,stdout t=int(stdin.readline().strip()) for _ in range(t): n=int(stdin.readline().strip()) #n,m,k=map(int,stdin.readline().split()) l=list(map(int,stdin.readline().strip().split())) ans=[0]*n for i in range(n-1,-1,-1): z=(i+l[i]...
Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first n. He writes down the followin...
3
l=input() l=l.split() n=int(l[0]) k=int(l[1]) if n%2==0: n_even=int(n/2) n_odd=int(n/2) else: n_even=int(n/2) n_odd=int(n/2) + 1 if k > n_odd: new_k=k-n_odd result=2*new_k else: result=k+(k-1) print(result)
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [...
3
# You have to be at your strongest when you're feeling at your weakest. Unknown # by : Blue Edge - Create some chaos for _ in range(int(input())): n=int(input()) a=list(map(int,input().split())) m=a[0] s=0 i=1 while i<n: if a[i]*a[i-1]>0: m=max(m,a[i]) else: ...
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...
1
__author__ = 'MoustaphaSaad' n = int(raw_input()) res = 0 for i in xrange(0, n): pp, qq = map(int, raw_input().split()) if qq - pp >= 2: res += 1 print res
Little penguin Polo loves his home village. The village has n houses, indexed by integers from 1 to n. Each house has a plaque containing an integer, the i-th house has a plaque containing integer pi (1 ≤ pi ≤ n). Little penguin Polo loves walking around this village. The walk looks like that. First he stands by a hou...
1
MOD = 1000000007 def exp(x, n): if n == 0: return 1 if n & 1 == 0: # n is even return (exp(x, n >> 1) ** 2) % MOD else: # n is odd return (x * exp(x, n - 1)) % MOD n, k = map(int, raw_input().strip().split()) R = [1, 2, 9, 64, 625, 7776, 117649, 2097152] print (R[k-1] * exp(n - k, n - k)) % MOD
Problem description You will be given a zero-indexed array A. You need to rearrange its elements in such a way that the following conditions are satisfied: A[i] ≤ A[i+1] if i is even. A[i] ≥ A[i+1] if i is odd. In other words the following inequality should hold: A[0] ≤ A[1] ≥ A[2] ≤ A[3] ≥ A[4], and so on. Operation...
1
test_case = int(raw_input()) for t in range(test_case): size = int(raw_input()) array = map(int, raw_input().split()) array.sort() for i in range(1, size): if i % 2 == 0: array[i], array[i-1] = array[i-1], array[i] for a in array: print a, print
Alice and Bob are decorating a Christmas Tree. Alice wants only 3 types of ornaments to be used on the Christmas Tree: yellow, blue and red. They have y yellow ornaments, b blue ornaments and r red ornaments. In Bob's opinion, a Christmas Tree will be beautiful if: * the number of blue ornaments used is greater b...
3
a,b,c=map(int,input().split()) m=min(a+1,b) m=min(m+1,c) print(3*m-3)
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...
3
""" Author: Ove Bepari _nnnn_ dGGGGMMb ,''''''''''''''''''''''. @p~qp~~qMb | Promoting GNU/Linux | M|@||@) M| _;......................' @,----.JM| -' JS^\__/ qKL dZP qKRb dZP qKKb fZP SMMb HZM ...
Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number n. How many times can Gerald put a spell on it until the number becomes one-di...
3
s = input() if len(s) == 1: print(0) else: n = sum(map(int, list(s))) res = 1 while n >= 10: t = 0 while n > 0: t += n%10 n//= 10 res += 1 n = t print(res)
Little girl Alyona is in a shop to buy some copybooks for school. She study four subjects so she wants to have equal number of copybooks for each of the subjects. There are three types of copybook's packs in the shop: it is possible to buy one copybook for a rubles, a pack of two copybooks for b rubles, and a pack of t...
3
l = list(map(int, input().split())) n = l[0]%4 if n == 3: print(min(l[1],l[3]*3, l[2]+l[3])) elif n == 2: print(min(l[1]*2,l[2], l[3]*2,l[1]+l[3])) elif n == 1: print(min(l[1]*3, l[3], l[1]+l[2])) else: print(0)
There was once young lass called Mary, Whose jokes were occasionally scary. On this April's Fool Fixed limerick rules Allowed her to trip the unwary. Can she fill all the lines To work at all times? On juggling the words Right around two-thirds Sh...
3
idk = int(input()) i = 2 factors = [] while i * i <= idk: if idk % i: i += 1 else: idk //= i factors.append(i) if idk > 1: factors.append(idk) r = '' for factor in factors: r += str(factor) print(r)
Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sendi...
1
""" [int(i) for i in raw_input().split(" ")] raw_input() raw_input().split(" ") """ def main(): n = int(raw_input()) H = {} for i in range(n): #read letters and fill hash counts S = raw_input() counts = {} for j in S: if j not in counts: ...
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 x in range(int(input())): word = str(input()) if len(word) <= 10: print(word) else: print(word[0] + str(len(word)-2) + word[len(word)-1])
You are given an integer n (n > 1). Your task is to find a sequence of integers a_1, a_2, …, a_k such that: * each a_i is strictly greater than 1; * a_1 ⋅ a_2 ⋅ … ⋅ a_k = n (i. e. the product of this sequence is n); * a_{i + 1} is divisible by a_i for each i from 1 to k-1; * k is the maximum possible (i. e...
3
import sys input = sys.stdin.readline import math def fact(x): L=int(math.sqrt(x)) FACT=dict() for i in range(2,L+2): while x%i==0: FACT[i]=FACT.get(i,0)+1 x=x//i if x!=1: FACT[x]=FACT.get(x,0)+1 return FACT t=int(input()) for tests in range(t): n...
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given n numbers finds one that is di...
1
a = int(raw_input()) c = map(int,raw_input().split()) d = [] e = [] for i in c: if(i%2==0): e.append(i) else: d.append(i) if(len(e)==1): print (c.index(e[0])+1) else: print (c.index(d[0])+1)
Let's call the following process a transformation of a sequence of length n. If the sequence is empty, the process ends. Otherwise, append the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor) (GCD) of all the elements of the sequence to the result and remove one arbitrary element from t...
3
def solve(n,k): print(1*k,end = ' ') if n==2: print(2*k,end = ' ') if n == 3: print(k,3*k,end = ' ') else: temp = n//2 if(n%2 == 0): temp -= 1 print((str(k)+' ')*temp,end='') if(n>3): solve(n//2,k*2) n = int(input()) solve(n,1)
Polycarp and his friends want to visit a new restaurant. The restaurant has n tables arranged along a straight line. People are already sitting at some tables. The tables are numbered from 1 to n in the order from left to right. The state of the restaurant is described by a string of length n which contains characters ...
3
t=int(input()) for i in range(t): n,k=input().split(" ") n=int(n) k=int(k) s=input() setter=0 answer=0 while(setter<n): if (s[setter]=='1'): setter+=k else : for j in range(setter+1,setter+k+1): if (j<n and s[j]=='1'): setter=j+k break if (j==setter+k): #print(setter) answe...
There is a game called "I Wanna Be the Guy", consisting of n levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game. Little X can pass only p levels of the game. And Little Y can pass only q levels of the game. You are given the indices of levels Little X can pass ...
3
a = int(input()) b = list(map(int, input().split())) c = list(map(int, input().split())) d, e = b.pop(0), c.pop(0) lvl = 0 for i in range(1, a + 1): all = False for j in b: if j == i: all = True break for l in c: if l == i: all = True break ...
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
b = [[4,3,2,3,4],[3,2,1,2,3],[2,1,0,1,2],[3,2,1,2,3],[4,3,2,3,4]] for i in range(5): l = [int(n) for n in input().split()] for j in range(5): if l[j] == 1: print(b[i][j])
Vova, the Ultimate Thule new shaman, wants to build a pipeline. As there are exactly n houses in Ultimate Thule, Vova wants the city to have exactly n pipes, each such pipe should be connected to the water supply. A pipe can be connected to the water supply if there's water flowing out of it. Initially Vova has only on...
1
import math from decimal import Decimal, ROUND_FLOOR def sum2(s, e): return sum1(e) - sum1(s - 1) - (e - s) def sum1(i): return i * (i + 1) / 2 line = raw_input().split() n = Decimal(line[0]) k = Decimal(line[1]) if(n == 1): print 0 elif(k > n): print 1 elif(sum2(Decimal(2),k) < n): print -1 else...