problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
You are given a non-decreasing array of non-negative integers a_1, a_2, …, a_n. Also you are given a positive integer k. You want to find m non-decreasing arrays of non-negative integers b_1, b_2, …, b_m, such that: * The size of b_i is equal to n for all 1 ≀ i ≀ m. * For all 1 ≀ j ≀ n, a_j = b_{1, j} + b_{2, j}...
3
import math t = int(input()) for _ in range(t): n, k = map(int, input().split()) a = list(map(int, input().split())) ans = 1 for i in range(1, n): if(a[i] != a[i-1]): ans += 1 if(k == 1): if(ans > 1): print(-1) else: print(1) else: ...
Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options: 1. on this day the gym is closed and...
3
from sys import stdin, stdout def main(): n = int(stdin.readline()) a = [0] + list(map(int, stdin.readline().split())) r = [0]*110 c = [0]*110 g = [0]*110 for i in range(1, n+1): r[i] = min(c[i-1], g[i-1], r[i-1]) + 1 if a[i] == 0: c[i] = 111 ...
Masha lives in a multi-storey building, where floors are numbered with positive integers. Two floors are called adjacent if their numbers differ by one. Masha decided to visit Egor. Masha lives on the floor x, Egor on the floor y (not on the same floor with Masha). The house has a staircase and an elevator. If Masha u...
3
l=list(map(int,input().split())) st=abs(l[0]-l[1])*l[3] lf=(abs(l[0]-l[2])*l[4])+(3*l[5])+(abs(l[0]-l[1])*l[4]) if(st>=lf): print('YES') else: print('NO')
Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is n. There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains 2 apartments, every other floor contains x apartments each. Apartments are numbered starting from one, from...
3
# https://vjudge.net/contest/411440#problem/F import math if __name__ == '__main__': n_tests = int(input()) for test in range(n_tests): apt, n_apts = [int(i) for i in input().split()] if apt <= 2: print("1") elif apt <= (n_apts + 2): print("2") elif (apt...
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
t = int(input()) for _ in range(t): s = input() ans = '' for i in range(0,len(s)-2,2): ans += s[i] ans += s[-2] + s[-1] print(ans)
The average miner Vaganych took refresher courses. As soon as a miner completes the courses, he should take exams. The hardest one is a computer test called "Testing Pants for Sadness". The test consists of n questions; the questions are to be answered strictly in the order in which they are given, from question 1 to ...
3
# 103A from sys import stdin __author__ = 'artyom' n = int(stdin.readline().strip()) count = 0 a = list(map(int, stdin.readline().strip().split())) for i in range(n): v = a[i] count += (v - 1) * i count += v print(count)
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
a=int(input()) b=input() c=b[-1] b=b[0:-1] for i in range(1,len(b)+1): if len(c)%2!=0: c=c[0:(len(c)-1)//2]+b[-i]+c[(len(c)-1)//2::] else: c=c[0:len(c)//2]+b[-i]+c[(len(c))//2::] print(c)
Finished her homework, Nastya decided to play computer games. Passing levels one by one, Nastya eventually faced a problem. Her mission is to leave a room, where a lot of monsters live, as quickly as possible. There are n manholes in the room which are situated on one line, but, unfortunately, all the manholes are clo...
1
import sys from collections import defaultdict strInp = lambda : raw_input().strip().split() intInp = lambda : list(map(int,strInp())) n , k = intInp() ans = 2*n + 1 + min(k-1,n-k) + n - 1 print(ans)
Young boy Artem tries to paint a picture, and he asks his mother Medina to help him. Medina is very busy, that's why she asked for your help. Artem wants to paint an n Γ— m board. Each cell of the board should be colored in white or black. Lets B be the number of black cells that have at least one white neighbor adja...
3
for i in range(int(input())): n,m = map(int,input().split()) c = [['X' for _ in range(m)] for _ in range(n)] for i in range(n): for j in range(m): if (i+j)%2 == 0: c[i][j] = 'B' else: c[i][j] = 'W' if (n*m)%2 == 0: if n%2 ==0: c[n-1][0] = 'B' else : c[n-1][m-1] = 'B' print("\n".join(""....
Gerald has been selling state secrets at leisure. All the secrets cost the same: n marks. The state which secrets Gerald is selling, has no paper money, only coins. But there are coins of all positive integer denominations that are powers of three: 1 mark, 3 marks, 9 marks, 27 marks and so on. There are no coins of oth...
3
n = int(input()) c = 0 while not n % 3: n //= 3 print((n+2)//3)
Happy new year! The year 2020 is also known as Year Gyeongja (κ²½μžλ…„, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years. There are two sequences of n strings s_1, s_2, s_3, …, s_{n} and m strings t_1, t_2, t_3, …, t_{m}. ...
3
def main(): n, m = list(map(int, input().split())) s = list(input().split()) t = list(input().split()) q = int(input()) in_ls = [] for i in range(q): tmp = int(input()) in_ls.append(tmp) for i in range(q): year = in_ls[i] ans = s[(year - 1) % n] + t[(year...
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find ...
3
HAPPY_NUMS = set({4, 7, 44, 47, 74, 77, 444, 447, 474, 477, 744, 747, 774, 777}) def solve(): number = int(input()) is_half_happy = False if number in HAPPY_NUMS: is_half_happy = True else: for divider in HAPPY_NUMS: if number % divider == 0: is_half_happy =...
It is winter now, and Max decided it's about time he watered the garden. The garden can be represented as n consecutive garden beds, numbered from 1 to n. k beds contain water taps (i-th tap is located in the bed xi), which, if turned on, start delivering water to neighbouring beds. If the tap on the bed xi is turned ...
3
# A import math t = int(input()) ans = [] for _ in range(t): n, k = map(int, input().split()) taps = input().split() for i in range(k): taps[i] = int(taps[i]) max_time = 0 for i in range(n): min_time = 1000 for j in range(k): min_time = min(min_time, int(math.f...
Polycarp has guessed three positive integers a, b and c. He keeps these numbers in secret, but he writes down four numbers on a board in arbitrary order β€” their pairwise sums (three numbers) and sum of all three numbers (one number). So, there are four numbers on a board in random order: a+b, a+c, b+c and a+b+c. You h...
3
nums = sorted([int(x) for x in input().split()]) s = nums.pop() ans = [s - num for num in nums] print(*ans)
So, the New Year holidays are over. Santa Claus and his colleagues can take a rest and have guests at last. When two "New Year and Christmas Men" meet, thear assistants cut out of cardboard the letters from the guest's name and the host's name in honor of this event. Then the hung the letters above the main entrance. O...
3
s1=input() s2=input() s3=input() if(len(s3)==len(s1)+len(s2)): s4=s1+s2 s4=sorted(s4) s3=sorted(s3) for i in range (len(s3)) : if(s3[i]!=s4[i]): c=0 break else: c=1 if(c==1): print("YES") else: print("NO") else: print("NO")
A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay iΒ·k dollars for the i-th banana). He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas? Input The first lin...
1
k,n,w = map(int, raw_input().split()) #bananas, $$, bananas wanted tot=0 for i in range(1,w+1): tot+=i cost = tot*k borrow = abs(n-cost) if (n-cost)<0 else 0 print borrow #3+6+9+12 = 30-17=13
One day, liouzhou_101 got a chat record of Freda and Rainbow. Out of curiosity, he wanted to know which sentences were said by Freda, and which were said by Rainbow. According to his experience, he thought that Freda always said "lala." at the end of her sentences, while Rainbow always said "miao." at the beginning of ...
3
n=int(input()) for i in range(0,n): s=input() if(s[0:5]=="miao."): if(s[len(s)-5:]=="lala."): print ("OMG>.< I don't know!") else : print ("Rainbow's") elif(s[len(s)-5:]=="lala."): if(s[0:5]=="miao."): print ("OMG>.< I don't know!") else :...
Polycarp plays "Game 23". Initially he has a number n and his goal is to transform it to m. In one move, he can multiply n by 2 or multiply n by 3. He can perform any number of moves. Print the number of moves needed to transform n to m. Print -1 if it is impossible to do so. It is easy to prove that any way to trans...
3
# -*- coding: utf-8 -*- # @Time : 2019/3/19 22:35 # @Author : LunaFire # @Email : gilgemesh2012@gmail.com # @File : A. Game 23.py def main(): n, m = map(int, input().split()) if m % n != 0: print(-1) return k, ret = m // n, 0 while k > 1: if k % 2 != 0 and k % 3 != 0...
You are given strings s and t. Find one longest string that is a subsequence of both s and t. Constraints * s and t are strings consisting of lowercase English letters. * 1 \leq |s|, |t| \leq 3000 Input Input is given from Standard Input in the following format: s t Output Print one longest string that is a su...
3
s = input() t = input() n = len(s) m = len(t) dp = [[0] * (m + 1) for _ in range(n + 1)] for i in range(n): for j in range(m): dp[i][j] = max([dp[i][j-1], dp[i-1][j], dp[i - 1] [j - 1] + (s[i] == t[j])]) ans = [] i = n - 1 j = m - 1 while i >= 0 and j >= 0: if i >= 0 and dp[i ...
After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≀ si ≀ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum nu...
3
a=input() b=[int(i) for i in input().split()] tot=0 tot=b.count(4)+(int(b.count(2)/2)) u=b.count(1) d=b.count(2)%2 t=b.count(3) if t>=u: tot=tot+u t=t-u u=0 else: tot=tot+t u=u-t t=0 d=d+int(u/2) u=u%2 tot=tot+ int(d/2) d=d%2 if u+d!=0: tot=tot+1 tot=tot+t print(tot)
Theatre Square in the capital city of Berland has a rectangular shape with the size n Γ— m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a Γ— a. What is the least number of flagstones needed to pave the Square? It'...
3
n, m, a = input ().split (); n = int (n); m = int (m); a = int (a); x = n // a; if (n % a != 0): x += 1; y = m // a; if (m % a != 0): y += 1; print (x * y);
You have N bamboos. The lengths (in centimeters) of these are l_1, l_2, ..., l_N, respectively. Your objective is to use some of these bamboos (possibly all) to obtain three bamboos of length A, B, C. For that, you can use the following three kinds of magics any number: * Extension Magic: Consumes 1 MP (magic point)....
3
n, a, b, c = list(map(int, input().split())) l = [int(input()) for i in range(n)] def dfs(cur, ta, tb, tc): if cur==n: if ta<=0 or tb<=0 or tc<=0: return 1e9 else: return abs(a-ta)+abs(b-tb)+abs(c-tc)-30 t1 = dfs(cur+1, ta, tb, tc) t2 = dfs(cur+1, ta+l[cur], tb, tc)+10 t3 = dfs(cur+1, ta, ...
You have final scores of an examination for n students. Calculate standard deviation of the scores s1, s2 ... sn. The variance Ξ±2 is defined by Ξ±2 = (βˆ‘ni=1(si - m)2)/n where m is an average of si. The standard deviation of the scores is the square root of their variance. Constraints * n ≀ 1000 * 0 ≀ si ≀ 100 Inpu...
1
#!/usr/bin/env python if __name__ == '__main__': while True: n = int(raw_input()) if n == 0: break s = map(float, raw_input().split()) m = sum(s)/len(s) print (sum(map(lambda x : (x-m)**2, s))/len(s))**0.5
The new "Die Hard" movie has just been released! There are n people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 ruble bill. A "Die Hard" ticket costs 25 rubles. Can the booking clerk sell a ticket to each person and give the change if he initially has no money and sells the...
1
n=int(raw_input()) l=[int(x) for x in raw_input().split()] chk=[0,0] for i in l: if i==25: chk[0]+=1 elif i==50: chk[1]+=1 chk[0]-=1 else: if chk[1]: chk[1]-=1 chk[0]-=1 else: chk[0]-=3 if chk[0]<0 or chk[1]<0: print 'NO...
Bran and his older sister Arya are from the same house. Bran like candies so much, so Arya is going to give him some Candies. At first, Arya and Bran have 0 Candies. There are n days, at the i-th day, Arya finds ai candies in a box, that is given by the Many-Faced God. Every day she can give Bran at most 8 of her cand...
3
read = lambda: tuple(map(int, input().split())) n, k = read() l = read() sm,a = 0,0 d = 0 for v in l: a += v sm += min(a, 8) a -= min(a, 8) d += 1 if sm >= k: break print(d if sm >= k else -1)
It is a holiday season, and Koala is decorating his house with cool lights! He owns n lights, all of which flash periodically. After taking a quick glance at them, Koala realizes that each of his lights can be described with two parameters a_i and b_i. Light with parameters a_i and b_i will toggle (on to off, or off t...
3
n = int(input()) s = input() d = {} ans = 0 for i in range(n): a,b = map(int,input().split()) if s[i] == "1": for e in range(0,b): if e in d: d[e] += 1 else: d[e] = 1 if s[i] == "0": k = b while k < 126: for j in ran...
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: * Tetrahedron. Tetrahedron has 4 triangular faces. * Cube. Cube has 6 square faces. * Octahedron. Octahedron has 8 triangular faces. * Dodecahedron. Dodecahedron has 12 pentagonal faces. *...
3
n = int(input()) polys = [] face = 0 for i in range(n): new_poly = input() polys.append(new_poly) for poly in polys: if poly == "Tetrahedron": face += 4 elif poly == "Cube": face += 6 elif poly == "Octahedron": face += 8 elif poly == "Dodecahedron": face += 12 ...
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If...
1
l = raw_input() if l.count('1111111')>0 or l.count('0000000')>0: print "YES" else: print "NO"
Young boy Artem tries to paint a picture, and he asks his mother Medina to help him. Medina is very busy, that's why she asked for your help. Artem wants to paint an n Γ— m board. Each cell of the board should be colored in white or black. Lets B be the number of black cells that have at least one white neighbor adja...
3
import sys t=int(sys.stdin.readline()) for _ in range(t): n,m=map(int,sys.stdin.readline().split()) ans=[['B' for x in range(m)] for y in range(n)] ans[-1][-1]='W' '''z=True for i in range(n): if z: a=True else: a=False for j in range(m): i...
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 ...
3
n,a,b = map(int, input().split()) suits = list(map(int, input().split())) i=0 j=n-1 flag = True cost = 0 while i<=j: if suits[i] == suits[j] and (suits[i]!=2): i+=1 j-=1 continue else: if (suits[i]==2 and suits[j] == 1) or (suits[i]==1 and suits[j]==2): cost+=b ...
You are given n numbers a_1, a_2, …, a_n. Is it possible to arrange them in a circle in such a way that every number is strictly less than the sum of its neighbors? For example, for the array [1, 4, 5, 6, 7, 8], the arrangement on the left is valid, while arrangement on the right is not, as 5β‰₯ 4 + 1 and 8> 1 + 6. <im...
3
n=int(input()) l=list(map(int,input().split())) l.sort() if(l[n-1]>=l[n-2]+l[n-3]): print("NO") else: print("YES") print(l[n-3],end=" ") print(l[n-1],end=" ") print(l[n-2],end=" ") for i in range(n-4,-1,-1): print(l[i],end=" ")
There are N Snukes lining up in a row. You are given a string S of length N. The i-th Snuke from the front has two red balls if the i-th character in S is `0`; one red ball and one blue ball if the i-th character in S is `1`; two blue balls if the i-th character in S is `2`. Takahashi has a sequence that is initially ...
1
m = 998244353 S = map(int, raw_input()) N = len(S) pr = [0]*(N*2) pb = [0]*(N*2) pr[0] = 2-S[0] pb[0] = S[0] for i in xrange(1, N): pr[i] = pr[i-1]+(2-S[i]) pb[i] = pb[i-1]+S[i] for i in xrange(N, N*2): pr[i] = pr[i-1] pb[i] = pb[i-1] dp = [] for i in xrange(N*2+1): dp.append([0]*(N*2+1)) dp[0][0]=1 for i in ...
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
for _ in range(int(input())): a=input() n=len(a) b="" for i in range(0,n,2): b+=a[i] b+=a[-1] print(b)
Sonya decided that having her own hotel business is the best way of earning money because she can profit and rest wherever she wants. The country where Sonya lives is an endless line. There is a city in each integer coordinate on this line. She has n hotels, where the i-th hotel is located in the city with coordinate ...
1
a = map(int,raw_input().split()) n = a[0] d = a[1] a = map(int,raw_input().split()) if(n==1): print 2 else: s = 1 for i in range(n-1): if(a[i+1]-a[i] == 2*d): s+=1 elif(a[i+1]-a[i] > 2*d): s+=2 else: s+=0 s+=1 print s
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
from math import inf as _inf import sys as _sys _NEGATIVE_INF = -_inf def main(): n, m, k = _read_ints() a = tuple(tuple(_read_ints()) for i_row in range(n)) result = find_max_sum(a, k) print(result) def _read_line(): result = _sys.stdin.readline() assert result[-1] == "\n" return resu...
You are given two integers n and m (m < n). Consider a convex regular polygon of n vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length). <image> Examples of convex regular polygons Your task is to say if it is poss...
3
t = int(input()) for T in range(t): n,m = list(map(int,input().split())) if(n%m == 0): print("YES") else: print("NO")
Snuke lives on an infinite two-dimensional plane. He is going on an N-day trip. At the beginning of Day 1, he is at home. His plan is described in a string S of length N. On Day i(1 ≦ i ≦ N), he will travel a positive distance in the following direction: * North if the i-th letter of S is `N` * West if the i-th letter...
1
def isAbleToBack(plan): alphaToInt = {'E':0, 'W':1, 'N':2, 'S':3} count = [False]*4 for c in plan: count[alphaToInt[c]] = True for i in xrange(4): if count[i] and not count[i^1]: return False return True def main(): plan = raw_input().strip() if isAbleToBack(plan...
You are lost in a dense jungle and it is getting dark. There is at least one path that leads you to the city on the other side but you cannot see anything until you are right in front of it as the trees and bushes obscure the path. Devise an algorithm that is guaranteed to find the way out. Your goal is to go out of...
1
from collections import defaultdict def Adj(n): adj_list = defaultdict(list) for i in xrange(len(n)): for j in xrange(len(n)): #print i,j for k in [[i+1,j],[i-1,j],[i,j+1],[i,j-1]]: if N > k[0] >= 0 and N > k[1] >= 0: if n[k[0]][k[1]] != 'T': ...
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If...
1
pos = raw_input() i = 1 cnt = 1 dan = "NO" while i < len(pos): if pos[i] == pos[i-1]: cnt += 1 else: cnt = 1 if cnt >= 7: dan = "YES" break i += 1 print dan
You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes. You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consi...
1
def py_2(): n,m = map(int,raw_input().split()) a = {} for i in xrange(m): tmp = map(str,raw_input().split()) a[tmp[0]] = tmp[1] s = map(str,raw_input().split()) slen = len(s) for i in xrange(slen): tmp = a[s[i]] if len(s[i]) > len(tmp): s[i] = tmp print ' '.join(s) py_2()
Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then...
3
n = int (input()) from time import time k = time () names = {} res = [] for i in range (n) : s = input() if s in names : res[names[s]] = False names [s] = i res.append(s) for i in range (n-1,-1,-1): if res[i] != False : print(res[i])
Recently Anton found a box with digits in his room. There are k2 digits 2, k3 digits 3, k5 digits 5 and k6 digits 6. Anton's favorite integers are 32 and 256. He decided to compose this integers from digits he has. He wants to make the sum of these integers as large as possible. Help him solve this task! Each digit c...
3
k2, k3, k5, k6 = map(int, input().split()) s = min(k2, k5, k6) * 256 k2 -= min(k2, k5, k6) s += min(k2, k3) * 32 print(s)
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob β€” to check his answers, he needs a program that among the given n numbers finds one that is di...
3
n = int(input()) li = list(map(int, input().split())) s = 0 while li[s]%2 == li[s-1]%2: s = s + 1 if li[s+1]%2 == li[s-1]%2: print(s+1) elif s == 0: print(n) else: print(s)
You are given an array a consisting of n integer numbers. Let instability of the array be the following value: max_{i = 1}^{n} a_i - min_{i = 1}^{n} a_i. You have to remove exactly one element from this array to minimize instability of the resulting (n-1)-elements array. Your task is to calculate the minimum possible...
3
if __name__ == "__main__": n = int(input()) a = list(map(int, input().split())) a.sort() print(min(a[n-2]-a[0], a[n-1]-a[1]))
Due to the coronavirus pandemic, city authorities obligated citizens to keep a social distance. The mayor of the city Semyon wants to light up Gluharniki park so that people could see each other even at night to keep the social distance. The park is a rectangular table with n rows and m columns, where the cells of the...
3
import math t=int(input()) for i in range(t): n1,m1=input().split(" ") n=int(n1) m=int(m1) print(math.ceil((n*m)/2))
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
for _ in range(int(input())): n, m = list(map(int, input().split())) a = list(map(int, input().split())) p = list(map(int, input().split())) p.sort() notSorted = True while True: notSorted = False swapped = False for i in p: i -= 1 if a[i] > a[i+1]...
A string b is a subsequence of a string a if b can be obtained from a by deletion of several (possibly, zero or all) characters. For example, "xy" is a subsequence of "xzyw" and "xy", but not "yx". You are given a string a. Your task is to reorder the characters of a so that "trygub" is not a subsequence of the result...
3
from sys import stdin, gettrace if gettrace(): inputi = input else: def input(): return next(stdin)[:-1] def inputi(): return stdin.buffer.readline() def solve(): n = input() ss = list(input()) tc = ss.count('t') res = [s for s in ss if s != 't'] + ['t']*tc print(''....
You are both a shop keeper and a shop assistant at a small nearby shop. You have n goods, the i-th good costs a_i coins. You got tired of remembering the price of each product when customers ask for it, thus you decided to simplify your life. More precisely you decided to set the same price for all n goods you have. ...
3
import math t=int(input()) for _ in range(t): n=int(input()) s=list(map(int,input().split())) x=sum(s) if x==0: print(0) else: x=x/n print(int(math.ceil(x)))
Coach Ankit is forming a team for the Annual Inter Galactic Relay Race. He has N students that train under him and he knows their strengths. The strength of a student is represented by a positive integer. The coach has to form a team of K students. The strength of a team is defined by the strength of the weakest stude...
1
""" calculate ncr%p where p is prime using inverse modulo 1)nck = n*(n-1)*(n-2)...(n-k+1) ---------------------- = num/den 1*2*............k 2)nck = num*den^-1 3)nck%p = ((num%p)*(den^-1%p))%p 4)den^-1 = den^(p-2)=den^b 4)nck%p = ((num%p)*(den^b%p))%p 5)we know that (a^b)%c = ((a%c)^b)%c;...
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob. Right now, Limak and Bob weigh a and b respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight. Limak eats a lot and his weight is tripled after every year, while Bob's weight...
3
a,b=map(int,input().split(" ")) c=0 while a<=b : a=a*3 b=b*2 c=c+1 print(c)
Pashmak decided to give Parmida a pair of flowers from the garden. There are n flowers in the garden and the i-th of them has a beauty number bi. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty difference i...
3
n = int(input()) l = list(map(int,input().split())) l.sort() dif = abs(l[n-1]-l[0]) c1 = c2 = 0 for i in range(n): if(l[i] == l[0]): c1 = c1 + 1 elif l[i] == l[n-1]: c2 = c2 + 1 if dif == 0: print(dif,n*(n-1)//2) else: print(dif,c1*c2)
Tom loves vowels, and he likes long words with many vowels. His favorite words are vowelly words. We say a word of length k is vowelly if there are positive integers n and m such that nβ‹… m = k and when the word is written by using n rows and m columns (the first row is filled first, then the second and so on, with each...
1
import math k=int(input()) u,v=0,0 for i in xrange(5,int(math.sqrt(k))+1): if k%i==0: u=i v=k//i break if u==0 or v==0: print -1 else: r="aeiou" s="" for i in xrange(u): for j in xrange(v): s+=r[(i+j)%5] print s
You are given an integer sequence 1, 2, ..., n. You have to divide it into two sets A and B in such a way that each element belongs to exactly one set and |sum(A) - sum(B)| is minimum possible. The value |x| is the absolute value of x and sum(S) is the sum of elements of the set S. Input The first line of the input ...
3
n = int(input()) k = n % 4 if (k == 0 or k == 3): print(0) else: print(1)
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 _ in range(int(input())): s=input() n=len(s) if(n<=10): print(s) else: print(s[0]+str(n-2)+s[n-1])
Dima and his friends have been playing hide and seek at Dima's place all night. As a result, Dima's place got messy. In the morning they decided that they need to clean the place. To decide who exactly would clean the apartment, the friends want to play a counting-out game. First, all the guys stand in a circle, and t...
3
''' Created on Jan 5, 2015 @author: mohamed265 ''' n = int(input()) t = sum([int(x) for x in input().split()]) slon = 0 for i in range(1, 6): if (i + t) % (n + 1) != 1: slon += 1 print(slon)
A well-known art union called "Kalevich is Alive!" manufactures objects d'art (pictures). The union consists of n painters who decided to organize their work as follows. Each painter uses only the color that was assigned to him. The colors are distinct for all painters. Let's assume that the first painter uses color 1...
1
m, n = map(int, raw_input().split()) T = [] for i in range(m): T.append(map(int, raw_input().split())) memo = [[0] * n for _ in range(m)] memo[0][0] = T[0][0] for i in range(1, n): memo[0][i] = memo[0][i - 1] + T[0][i] for i in range(1, m): for j in range(n): if j == 0: memo[i][j] = memo...
You are given an integer N that has exactly four digits in base ten. How many times does `2` occur in the base-ten representation of N? Constraints * 1000 \leq N \leq 9999 Input Input is given from Standard Input in the following format: N Output Print the answer. Examples Input 1222 Output 3 Input 34...
3
cs = list(input()) ans = len(list(filter(lambda c: c == '2', cs))) print(ans)
Emily's birthday is next week and Jack has decided to buy a present for her. He knows she loves books so he goes to the local bookshop, where there are n books on sale from one of m genres. In the bookshop, Jack decides to buy two books of different genres. Based on the genre of books on sale in the shop, find the nu...
3
n, m = map(int, input().split()) a = [int(s) for s in input().split()] b = [0]*m for i in range(n): b[a[i] - 1] += 1 sum = n * (n - 1)// 2 for i in range(m): sum -= max(0, b[i] * (b[i] - 1)//2) print(sum)
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point x(x > 0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order ...
3
x = int(input()) if x >= 5: if x % 5 == 0: print(x//5) elif x % 5 > 0: print((x//5) + 1) else: print(1)
Lord Omkar has permitted you to enter the Holy Church of Omkar! To test your worthiness, Omkar gives you a password which you must interpret! A password is an array a of n positive integers. You apply the following operation to the array: pick any two adjacent numbers that are not equal to each other and replace them ...
3
t = int(input()) for k in range(t): n = int(input()) a = [int(i) for i in input().split()] if a.count(a[0]) == n: print(n) else: print(1)
Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. For example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. When a team plays as ...
3
n=int(input()) a=[0]*n b=[0]*n for i in range(n): a[i],b[i]=map(int,input().split()) print(sum(a.count(x) for x in b))
An atom of element X can exist in n distinct states with energies E1 < E2 < ... < En. Arkady wants to build a laser on this element, using a three-level scheme. Here is a simplified description of the scheme. Three distinct states i, j and k are selected, where i < j < k. After that the following process happens: ...
1
import bisect n, u = map(float, raw_input().split()) l = map(float, raw_input().split()) ans = -1 for i in range(int(n)-1): a = l[i] b = l[i+1] c = l[bisect.bisect_right(l, a + u) - 1] if c > b: ans = max(ans, (c-b)/(c-a)) print ans
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr...
3
a = str(input()).lower() b = str(input()).lower() if (a<b): print(-1) elif (a>b): print(1) else: print(0)
Valentin participates in a show called "Shockers". The rules are quite easy: jury selects one letter which Valentin doesn't know. He should make a small speech, but every time he pronounces a word that contains the selected letter, he receives an electric shock. He can make guesses which letter is selected, but for eac...
3
l = False string = "abcdefghijklmnopqrstuvwxyz" varians = list(string) n = int(input()) k = 0 for i in range(n): v, s = input().split() if len(varians) == 1: l = True if v == '.': for simb in s: if simb in varians: del varians[varians.index(simb)] elif v == '!...
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
for t in range(int(input())): a,b=map(int,input().split()) print(min(a,b,(a+b)//3))
We've got no test cases. A big olympiad is coming up. But the problemsetters' number one priority should be adding another problem to the round. The diameter of a multiset of points on the line is the largest distance between two points from this set. For example, the diameter of the multiset {1, 3, 2, 1} is 2. Diame...
3
n, d = map(int, input().split(" ")) A = list(map(int, input().split(" "))) lo, ans, cur, idx = A[0], 1, 1, 0 A.sort() ans = 0 for i in range(0, n): cur = 0 for j in range(i, n): if A[j] - A[i] <= d: cur = cur + 1 else: break ans = max(cur, ans) print(n - ans)
You have a large electronic screen which can display up to 998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 7 segments which can be turned on and off to compose different digits. The following picture describes how you can dis...
3
t = int(input()) while t > 0: t -= 1 n = int(input()) if n%2 == 0: rt = n // 2 string = str(1) for i in range(rt-1): string = string + str(1) print(string) else: rt = n//2 - 1 string = str(7) for i in range(rt): string = str...
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the...
3
l1 = list(map(int,input().split())) l2 = list(map(int,input().split())) ans = 0 for f in l2 : if f > l1[1] : ans +=2 else : ans +=1 print(ans)
A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs. Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages ...
3
n = int(input()) list1 = list(map(int, input().split())) time = [0] * (n + 1) time[0] = 1 ans = 1 for i in range(n): if time[list1[i]] == 1: time[i + 1] = 1 time[list1[i]] = 0 else: ans += 1 time[i + 1] = 1 print(ans)
Given an integer x, find 2 integers a and b such that: * 1 ≀ a,b ≀ x * b divides a (a is divisible by b). * a β‹… b>x. * a/b<x. Input The only line contains the integer x (1 ≀ x ≀ 100). Output You should output two integers a and b, satisfying the given conditions, separated by a space. If no pair of in...
3
x = int(input()) print(-1) if x == 1 else print(x, x)
Jzzhu has invented a kind of sequences, they meet the following property: <image> You are given x and y, please calculate fn modulo 1000000007 (109 + 7). Input The first line contains two integers x and y (|x|, |y| ≀ 109). The second line contains a single integer n (1 ≀ n ≀ 2Β·109). Output Output a single integer...
3
x,y=map(int,input().split()) m=int(input()) s=[x,y,y-x,-x,-y,x-y] print(s[(m-1)%6]%(10**9+7))
You are given four positive integers n, m, a, b (1 ≀ b ≀ n ≀ 50; 1 ≀ a ≀ m ≀ 50). Find any such rectangular matrix of size n Γ— m that satisfies all of the following conditions: * each row of the matrix contains exactly a ones; * each column of the matrix contains exactly b ones; * all other elements are zeros....
1
for _ in range(input()): n,m,a,b=[int(i) for i in raw_input().split()] if n*a!=m*b: print "NO" else: print "YES" for i in range(n): s="1"*a+"0"*(m-a) val=(a*i)%m print s[val:]+s[:val]
Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1, p2, ..., pn. Your task is to find such permutation p of length n, that the group of numbers |p1 - p2|, |p2 - p3|, ..., |pn - 1 - pn| has exactly k d...
1
n, k = map(int, raw_input().split(' ')) lst = [1] vis = [0 for i in range(0, k+2)] for i in range(k, 0, -1): tmp = lst[-1] + i if tmp <= k+1 and vis[tmp] == 0: lst.append(tmp) vis[tmp] = 1 else: tmp = lst[-1] - i if lst[-1] - i > 0 else i - lst[-1] if vis[tmp] == 0: ...
Vasya's birthday is approaching and Lena decided to sew a patterned handkerchief to him as a present. Lena chose digits from 0 to n as the pattern. The digits will form a rhombus. The largest digit n should be located in the centre. The digits should decrease as they approach the edges. For example, for n = 5 the handk...
1
#FIN = open("input.txt", "r") #FOUT = open("output.txt", "w") InputData = raw_input().split() n = int(InputData[0]) for i in range(n + 1): for j in range(n - i): print ' ', for j in range(i + 1): print j, for j in range(i): print i - 1 - j, print for i in range(n): for j in ...
Today, Wet Shark is given n integers. Using any of these integers no more than once, Wet Shark wants to get maximum possible even (divisible by 2) sum. Please, calculate this value for Wet Shark. Note, that if Wet Shark uses no integers from the n integers, the sum is an even integer 0. Input The first line of the ...
3
n = int(input()) a = list(map(int, input().split())) mn = 1000000000000000000000001 if sum(a) % 2 == 0: print(sum(a)) else: for i in range(n): if a[i] % 2 == 1: mn = min(mn, a[i]) print(sum(a)-mn)
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 math as mt n,m,a = input().split() n = int(n) m = int(m) a = int(a) ans = mt.ceil(n/a)*mt.ceil(m/a) print(ans)
You're given an array a_1, …, a_n of n non-negative integers. Let's call it sharpened if and only if there exists an integer 1 ≀ k ≀ n such that a_1 < a_2 < … < a_k and a_k > a_{k+1} > … > a_n. In particular, any strictly increasing or strictly decreasing array is sharpened. For example: * The arrays [4], [0, 1], [...
3
t=int(input()) while t: t-=1 n=int(input()) lip=list(map(int, input().split())) pref, suff=-1, n for i in range(n): if lip[i]<i: break pref=i for i in range(n-1, -1, -1): if lip[i] < n -1 -i : break suff=i if suff<=pref: print(...
Little Dormi received a histogram with n bars of height a_1, a_2, …, a_n for Christmas. However, the more he played with his new histogram, the more he realized its imperfections, so today he wanted to modify it to his liking. To modify the histogram, Little Dormi is able to perform the following operation an arbitrar...
3
def ugliness(a, n): badsoorat = 0 for i in range(n): if i==0: badsoorat+=a[i] elif i == n-1: badsoorat+= abs(a[i]-a[i-1]); badsoorat+=a[i] else: badsoorat += abs(a[i]-a[i-1]) return badsoorat def main(a,n): score = ugliness(a, n) if n == 1: print(a[0]); return ...
Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game. Rules of the game are very simple: at first number of rounds n is defined. I...
3
a=0 b=0 for _ in range(int(input())): m, c = map(int, input().split()) if m>c: a+=1 elif c>m: b+=1 if a>b: print('Mishka') elif b>a: print('Chris') else: print('Friendship is magic!^^')
Lee just became Master in Codeforces, and so, he went out to buy some gifts for his friends. He bought n integers, now it's time to distribute them between his friends rationally... Lee has n integers a_1, a_2, …, a_n in his backpack and he has k friends. Lee would like to distribute all integers in his backpack betwe...
3
t = int(input()) for _ in range(t): n,k = map(int,input().split()) a = sorted(list(map(int,input().split()))) w = sorted(list(map(int,input().split()))) ans = 0 g = [a.pop() for i in range(k)] for i in range(k): best = g[i] for j in range(w[i]-1): best = a.pop() ...
There are N bags, each containing two white balls. The i-th box contains two balls with integers x_i and y_i written on them, respectively. For each of these bags, you will paint one of the balls red, and paint the other blue. Afterwards, the 2N balls will be classified according to color. Then, we will define the f...
3
n=int(input()) x,y=zip(*sorted(sorted(map(int,input().split())) for _ in range(n))) p=max(range(n),key=lambda i:y[i]) r=a=x[-1] b=d=10**9 for i in range(p): a=max(a,y[i]) b=min(b,y[i]) d=min(d,a-min(b,x[i+1])) print(min((x[-1]-x[0])*(y[p]-min(y)),(y[p]-x[0])*d))
You are visiting a large electronics store to buy a refrigerator and a microwave. The store sells A kinds of refrigerators and B kinds of microwaves. The i-th refrigerator ( 1 \le i \le A ) is sold at a_i yen (the currency of Japan), and the j-th microwave ( 1 \le j \le B ) is sold at b_j yen. You have M discount tic...
3
A,B,M=map(int,input().split()) a=list(map(int,input().split())) b=list(map(int,input().split())) MIN=min(a)+min(b) for i in range(M): x,y,c=map(int,input().split()) if a[x-1]+b[y-1]-c<MIN: MIN=a[x-1]+b[y-1]-c print(MIN)
The only difference between easy and hard versions is constraints. If you write a solution in Python, then prefer to send it in PyPy to speed up execution time. A session has begun at Beland State University. Many students are taking exams. Polygraph Poligrafovich is going to examine a group of n students. Students ...
3
import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.wr...
You are given an array a consisting of n integer numbers. Let instability of the array be the following value: max_{i = 1}^{n} a_i - min_{i = 1}^{n} a_i. You have to remove exactly one element from this array to minimize instability of the resulting (n-1)-elements array. Your task is to calculate the minimum possible...
3
import math n = int(input()) cl = list(map(int, input().split())) cl = sorted(cl) if n==2: print(0) else: a = cl[-1]-cl[1] b = cl[n-2]-cl[0] if a<b: print(a) else: print(b)
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
n ,cad= input().lower(),'' for i in n: if not (i in ['a','e','i','o','u','y']): cad+='.'+i print(cad)
Alice and Bob have received three big piles of candies as a gift. Now they want to divide these candies as fair as possible. To do this, Alice takes one pile of candies, then Bob takes one of the other two piles. The last pile is split between Alice and Bob as they want: for example, it is possible that Alice takes the...
3
# Pradnyesh Choudhari # Sat Jul 18 23:01:41 2020 exec(int(input()) * 'print(sum(map(int, input().split())) // 2);')
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
for t in range(int(input())): n = int(input()) l=list(map(int,input().split())) l2=[0 for i in range(n+1)] if(n==1): print(0) continue else: d=dict() m=0 x=0 for i in l: ...
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 ...
3
blres=0 whres=0 for i in range(8): s = input()[0:8] for i in s: if i!='.': if i=='Q': whres+=9 if i=='N': whres+=3 if i=='R': ...
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
n,a,b,c = map(int, input().split()) n = n%4 if(n==0): print(0) elif(n==1): print(min(c,a+b,3*a)) elif(n==2): print(min(2*c,b,2*a)) else: print(min(3*c,b+c,a))
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
import re n=int(input()) m=input() s=[] l=[] r=re.split(r'\s+',m) for i in range(n): if int(r[i])==0: s.append(0) else: s.append(1) i=0 while i <n: j=0 while j <= i: sum = 0 for k in range(n): if j<=k<=i: sum+=(1-s[k]) else: ...
Johnny has a younger sister Anne, who is very clever and smart. As she came home from the kindergarten, she told his brother about the task that her kindergartener asked her to solve. The task was just to construct a triangle out of four sticks of different colours. Naturally, one of the sticks is extra. It is not allo...
3
def triangle(a,b,c): if a+b>c and b+c>a and c+a>b: return True return False def func(a,b,c): if a+b==c or b+c==a or c+a==b: return True return False a,b,c,d = list(map(int,input().split())) if triangle(a,b,c)==True or triangle(b,c,d)==True or triangle(a,c,d)==True or triangle(a,b,d)==True: print("TRIANGLE") el...
In the beginning of the new year Keivan decided to reverse his name. He doesn't like palindromes, so he changed Naviek to Navick. He is too selfish, so for a given n he wants to obtain a string of n characters, each of which is either 'a', 'b' or 'c', with no palindromes of length 3 appearing in the string as a substr...
1
def solution(n): return "aabb" * (n/4) + "aabb"[:n%4] def main(): n = input() print solution(n) if __name__=="__main__": main()
Polycarpus has a ribbon, its length is n. He wants to cut the ribbon in a way that fulfils the following two conditions: * After the cutting each ribbon piece should have length a, b or c. * After the cutting the number of ribbon pieces should be maximum. Help Polycarpus and find the number of ribbon pieces ...
3
def read_ints(): return list(map(int, input().split())) if __name__ == "__main__": n, a, b, c = read_ints() tmp = [0 for _ in range(n+1)] if a <= n: tmp[a] = 1 if b <= n: tmp[b] = 1 if c <= n: tmp[c] = 1 for i in range(1, n+1): if i >= a and tmp[i - a] != 0: ...
Petya is having a party soon, and he has decided to invite his n friends. He wants to make invitations in the form of origami. For each invitation, he needs two red sheets, five green sheets, and eight blue sheets. The store sells an infinite number of notebooks of each color, but each notebook consists of only one co...
1
def x(n, k): r = n // k if n % k > 0: r += 1 return r s = raw_input().strip().split(' ') (n, k) = (int(s[0]), int(s[1])) r = x(2 * n, k) + x(5 * n, k) + x(8 * n, k) print r
Your favorite shop sells n Kinder Surprise chocolate eggs. You know that exactly s stickers and exactly t toys are placed in n eggs in total. Each Kinder Surprise can be one of three types: * it can contain a single sticker and no toy; * it can contain a single toy and no sticker; * it can contain both a sing...
3
t= int(input()) for _ in range(t): n,s,t= map(int,input().split()) p= s+t-n only_toy= t-p only_st= s-p q= max(only_toy,only_st) print(q+1)
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like. Now let's imagine a typical morning in your family. You haven't w...
3
import string if __name__ == '__main__': n = int(input()) list1 = list(map(int, input().split())) list1.sort(reverse = True) count = 1 total = 0 total2 = list1[0] for i in range(n): total = total + list1[i] total -= list1[0] for i in range(1, n + 1...
Vasya decided to learn to play chess. Classic chess doesn't seem interesting to him, so he plays his own sort of chess. The queen is the piece that captures all squares on its vertical, horizontal and diagonal lines. If the cell is located on the same vertical, horizontal or diagonal line with queen, and the cell cont...
3
print('black' if input()[-1] in '13579' else 'white\n1 2')
There are n students in the first grade of Nlogonia high school. The principal wishes to split the students into two classrooms (each student must be in exactly one of the classrooms). Two distinct students whose name starts with the same letter will be chatty if they are put in the same classroom (because they must ha...
3
#!/Users/genaro/venvs/venv3/bin/python n = int(input()) d = [0] * 26 for _ in range(n): d[ord(input()[0]) - ord('a')] += 1 t = 0 for i in range(26): a = d[i]//2 b = d[i] - a if a > 1: t +=a*(a-1)//2 if b > 1: t += b*(b-1)//2 print(t)
Polycarp has guessed three positive integers a, b and c. He keeps these numbers in secret, but he writes down four numbers on a board in arbitrary order β€” their pairwise sums (three numbers) and sum of all three numbers (one number). So, there are four numbers on a board in random order: a+b, a+c, b+c and a+b+c. You h...
3
l = [int(x) for x in input().split()] l.sort() print(l[0]+l[1]-l[3], l[1]+l[2]-l[3], l[0]+l[2]-l[3])
Alyona has recently bought a miniature fridge that can be represented as a matrix with h rows and 2 columns. Initially there is only one shelf at the bottom of the fridge, but Alyona can install arbitrary number of shelves inside the fridge between any two rows. A shelf is two cells wide, does not occupy any space but ...
3
import heapq n, h = map(int, input().split()) a = list(map(int, input().split())) temp_a = [] heapq.heapify(temp_a) k = 0 tmp_h = h while tmp_h >= 0: if k < n: heapq.heappush(temp_a, a[k]) k += 1 largest = heapq.nlargest(k, temp_a) tmp_h = h for i in range(0, k, 2): ...