problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≤ i ≤ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is it...
3
n = int(input()) a = list(map(int, input().split(' '))) max_seq = 0 seq = 1 for i in range(1, n): if a[i - 1] <= a[i]: seq += 1 else: max_seq = max(max_seq, seq) seq = 1 max_seq = max(max_seq, seq) print(max_seq)
There is a rectangular grid of n rows of m initially-white cells each. Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and...
3
def table(n, m, lst): for i in range(n): for j in range(n): if lst[i] != lst[j]: for k in range(m): if lst[i][k] == lst[j][k] == "#": return "No" return "Yes" N, M = [int(i) for i in input().split()] b = list() for i in range(N): ...
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
def binpow(n, k): if k <= 1: return n ** k if k % 2 == 0: a = binpow(n, k // 2) return a*a a = binpow(n, k - 1) return n * a def log2(n): i = 0 n -= 1 while n > 1: n //= 2 i += 1 return i def qw(n): if n == 1: return 0 if n == 2: return 1 m = log2(n) q = binpow(2, m) return (qw(n - q) + 1) ...
Let's play Amidakuji. In the following example, there are five vertical lines and four horizontal lines. The horizontal lines can intersect (jump across) the vertical lines. <image> In the starting points (top of the figure), numbers are assigned to vertical lines in ascending order from left to right. At the first...
1
from __future__ import (division, absolute_import, print_function, unicode_literals) from sys import stdin L = [i + 1 for i in xrange(int(stdin.readline()))] for _, line in zip(xrange(int(stdin.readline())), stdin): a, b = (int(t) - 1 for t in line.split(',')) L[a], L[b] = L[b], L[a] fo...
For the multiset of positive integers s=\\{s_1,s_2,...,s_k\}, define the Greatest Common Divisor (GCD) and Least Common Multiple (LCM) of s as follow: * \gcd(s) is the maximum positive integer x, such that all integers in s are divisible on x. * lcm(s) is the minimum positive integer x, that divisible on all integ...
3
from sys import stdin, stdout, setrecursionlimit input = stdin.readline # setrecursionlimit(int(1e6)) inf = float('inf') from collections import defaultdict as dd from collections import Counter, deque from heapq import * import math from math import floor, ceil, sqrt def geti(): return map(int, input().strip().split()...
Let n be a positive integer. Let a, b, c be nonnegative integers such that a + b + c = n. Alice and Bob are gonna play rock-paper-scissors n times. Alice knows the sequences of hands that Bob will play. However, Alice has to play rock a times, paper b times, and scissors c times. Alice wins if she beats Bob in at lea...
3
from math import ceil t = int(input()) for i in range(t): n = int(input()) ar, ap, aS = map(int, input().split()) s = input() br, bp, bs = 0, 0, 0 for x in s: if x == 'R': br += 1 elif x == 'P': bp += 1 else: bs += 1 su = min(ar, bs) + min(ap, br) + min(aS, bp) # print(su) if su >= ceil(n/2): ...
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
input=raw_input() input_arr=input.split(" ") k=int(input_arr[0]) n=int(input_arr[1]) w=int(input_arr[2]) i=0 total=0 while i<w: i+=1 total+= k*i if n>=total: print(0) else: print(total-n)
Vasya has found a strange device. On the front panel of a device there are: a red button, a blue button and a display showing some positive integer. After clicking the red button, device multiplies the displayed number by two. After clicking the blue button, device subtracts one from the number on the display. If at so...
3
n, m = (int(x) for x in input().split()) i = 0 while m > n: if m % 2 == 0: m = m // 2 else: m += 1 i += 1 if m < n: i += n-m print(i)
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
w = int(raw_input()) w -= 2 if w <= 0 or w % 2: print 'NO' else: print 'YES'
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem. Pete and Bi...
3
w= int(input()) if w != 2: if w %2==0: print("YES") else: print('NO') elif w == 2: print("NO")
Curry making As the ACM-ICPC domestic qualifying is approaching, you who wanted to put more effort into practice decided to participate in a competitive programming camp held at a friend's house. Participants decided to prepare their own meals. On the first night of the training camp, the participants finished the da...
3
import math while 1: r,w,c,rr=map(int,input().split()) if r==w==c==rr==0:break print(math.ceil((w*c-r)/rr) if w*c-r>=0 else 0)
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 ...
3
from sys import stdin, stdout from math import floor,ceil n=int(input()) a=sorted(list(int(stdin.readline()) for i in range(n))) mid=floor((n-1)/2) c=0 i=n-1;x=mid;k=n while x>=0: if 2*a[x]<=a[i]: k-=1 i-=1 x-=1 k=max(ceil(n/2),k) stdout.write(str(k))
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
n=raw_input().split(" ") #print len(n) new=set(n) #print new #print len(new) print len(n)-len(new)
Tokitsukaze is one of the characters in the game "Kantai Collection". In this game, every character has a common attribute — health points, shortened to HP. In general, different values of HP are grouped into 4 categories: * Category A if HP is in the form of (4 n + 1), that is, when divided by 4, the remainder is ...
3
q=int(input()) w=q%4 if w==1: print('0 A') if w==2: print('1 B') if w==3: print('2 A') if w==0: print('1 A')
When Serezha was three years old, he was given a set of cards with letters for his birthday. They were arranged into words in the way which formed the boy's mother favorite number in binary notation. Serezha started playing with them immediately and shuffled them because he wasn't yet able to read. His father decided t...
3
n=int(input()) str = input() a = str.count('n') b = str.count('z') if a and b: print(a*'1 '+b*'0 ') elif a and not b: print(a*'1 ') elif not a and b: print(b*'0 ')
You are given an array a consisting of n integers. Your task is to determine if a has some subsequence of length at least 3 that is a palindrome. Recall that an array b is called a subsequence of the array a if b can be obtained by removing some (possibly, zero) elements from a (not necessarily consecutive) without c...
3
def main(): t = int(input()) for _ in range(t): n = int(input()) arr = list(map(int, input().strip().split())) ma = {} for i, ele in enumerate(arr): if ele not in ma: ma[ele] = [] ma[ele].append(i) flag = False for key in ma: ...
For god's sake, you're boxes with legs! It is literally your only purpose! Walking onto buttons! How can you not do the one thing you were designed for? Oh, that's funny, is it? Oh it's funny? Because we've been at this for twelve hours and you haven't solved it either, so I don't know why you're laughing. You've got ...
3
from sys import stdin input = stdin.readline def gt(): return list(map(int, input().split())) def test(ar): for i in range(1,len(ar)): if ar[i] >= ar[i-1]: return True return False t ,= gt() while t: t -= 1 n ,= gt() ar = gt() if test(ar): print("YES") ...
Vasilisa the Wise from the Kingdom of Far Far Away got a magic box with a secret as a present from her friend Hellawisa the Wise from the Kingdom of A Little Closer. However, Vasilisa the Wise does not know what the box's secret is, since she cannot open it again. She hopes that you will help her one more time with tha...
1
import sys r1,r2 = map(int, raw_input().split()) c1,c2 = map(int, raw_input().split()) d1,d2 = map(int, raw_input().split()) for a in xrange(1,10): for b in xrange(1,10): if a == b: continue if a + b != r1: continue for c in xrange(1,10): if a == c or b ==...
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If...
3
import re m = input() if bool(re.search('1{7}|0{7}', m)) : print('YES') else: print('NO')
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
w= input() res="" a=['a','e','i','o','u','y'] a1=['A','E','I','O','U','Y'] re= list() for c in w: if c in a or c in a1: continue else: re.append(c) q=0 while q < len(re)-1: re.insert(q+1,'.') q+=2 re.insert(0,'.') result="" for f in re: result+=(str(f)) print(result.l...
You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the integers from 1 through N. You would like to sort this sequence in ascending order by repeating the following operation: * Choose an element in the sequence and move it to the beginning or the end of the sequence. Find the minimum number of op...
3
n = int(input()) t = [0]*n for i in range(n): p = int(input())-1 t[p] = i maxi = 1 c = 1 for i in range(n-1): a = t[i] b = t[1+i] if a < b: c += 1 else: maxi = max(c,maxi) c = 1 maxi = max(c,maxi) print(n - maxi)
In BerSoft n programmers work, the programmer i is characterized by a skill r_i. A programmer a can be a mentor of a programmer b if and only if the skill of the programmer a is strictly greater than the skill of the programmer b (r_a > r_b) and programmers a and b are not in a quarrel. You are given the skills of ea...
3
(n, k) = map(int, input().split()) d = {} a = [] for x in input().split(): x = int(x) if not x in d: d[x] = 0 d[x] += 1 a.append(x) lst = sorted(d) lst.reverse() d1 = {lst[0]: d[lst[0]]} for x in range(1, len(lst)): d1[lst[x]] = d1[lst[x - 1]] + d[lst[x]] array = [0] * n for x in ran...
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word. Note, that during capitalization all the letters except the first one remains unchanged. Input A single line contains a non-empty word. This word consists of lowercase and uppercase English letters....
3
n=list(input()) b=n[0] c=b.upper() n[0]=c i=0 l=len(n) a="" while i<l : a=a+n[i] i=i+1 print(a)
Summer holidays! Someone is going on trips, someone is visiting grandparents, but someone is trying to get a part-time job. This summer Noora decided that she wants to earn some money, and took a job in a shop as an assistant. Shop, where Noora is working, has a plan on the following n days. For each day sales manager...
3
from heapq import nlargest [n, f] = map(int, input().split()) seq, maxl = [], [] for i in range(n): [k, l] = [int(x) for x in input().split()] mx = l if 2 * k >= l else 2 * k orgl = l if k >= l else k maxl.append([mx - orgl, i]) seq.append([k, l]) m, sub = 0, [] maxl = nlargest(f, maxl) for item in...
You are given an array a consisting of n integer numbers. You have to color this array in k colors in such a way that: * Each element of the array should be colored in some color; * For each i from 1 to k there should be at least one element colored in the i-th color in the array; * For each i from 1 to k al...
3
n,k = map(int,input().split()) arr = list(map(int,input().split())) map = {} for i in arr: if i in map: map[i]+=1 else: map[i]=1 flag=True for i in map: if map[i]>k: flag=False if flag==False: print('NO') elif flag: print('YES') ans = [] for i in range(n): a...
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation. The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe...
3
ques=input() ans="" a1=[] for i in range(len(ques)): if i%2==0: a1.append(ques[i]) a1.sort(reverse=False) for i in range(len(a1)): ans=ans+a1[i] if i==len(a1)-1: break else: ans=ans+"+" print(ans)
There was an electronic store heist last night. All keyboards which were in the store yesterday were numbered in ascending order from some integer number x. For example, if x = 4 and there were 3 keyboards in the store, then the devices had indices 4, 5 and 6, and if x = 10 and there were 7 of them then the keyboards ...
3
size = int(input()) nums = input().split(' ') lst = [] for i in range(size): lst.append(int(nums[i])) minimum = min(lst) maximum = max(lst) print((maximum - minimum + 1) - size)
You are given two integers x and y (it is guaranteed that x > y). You may choose any prime integer p and subtract it any number of times from x. Is it possible to make x equal to y? Recall that a prime number is a positive integer that has exactly two positive divisors: 1 and this integer itself. The sequence of prime...
3
t=int(input()) for i in range(t): a,b=map(int,input().split()) if (a-b)==1: print("NO") else: print("YES")
You are given a string s, consisting of n lowercase Latin letters. A substring of string s is a continuous segment of letters from s. For example, "defor" is a substring of "codeforces" and "fors" is not. The length of the substring is the number of letters in it. Let's call some string of length n diverse if and o...
3
p= int(input()) a = list(input()) if p==1: print('NO') else: for i in range(p-1): if a[i]!=a[i+1]: print('YES') print (a[i]+a[i+1]) break else: if i==p-2: print('NO') break else: pass
You are given two integers a and b. In one move, you can choose some integer k from 1 to 10 and add it to a or subtract it from a. In other words, you choose an integer k ∈ [1; 10] and perform a := a + k or a := a - k. You may use different values of k in different moves. Your task is to find the minimum number of mo...
3
from __future__ import division, print_function import os import sys from io import BytesIO, IOBase def main(): def solve(): a, b = [ int(x) for x in input().split() ] if a > b: a, b = b, a movesWith10 = (b - a) // 10 a += 10*movesWith10 lastMove = 1 if (b - a > 0) else 0...
One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number ...
3
""" pppppppppppppppppppp ppppp ppppppppppppppppppp ppppppp ppppppppppppppppppppp pppppppp pppppppppppppppppppppp pppppppppppppppppppppppppppppppp pppppppppppppppppppp...
Aoki is in search of Takahashi, who is missing in a one-dimentional world. Initially, the coordinate of Aoki is 0, and the coordinate of Takahashi is known to be x, but his coordinate afterwards cannot be known to Aoki. Time is divided into turns. In each turn, Aoki and Takahashi take the following actions simultaneou...
3
import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines # 偶奇をあわせて寄せていくだけ X,P = map(int,read().split()) def f(x): y = x // 2 return y * 100 / P if X % 2 == 0: answer = f(X) else: answer = 1 + (P * f(X-1) + (100-P) * f(X+1))/100 print(answer...
Vasya has started watching football games. He has learned that for some fouls the players receive yellow cards, and for some fouls they receive red cards. A player who receives the second yellow card automatically receives a red card. Vasya is watching a recorded football match now and makes notes of all the fouls tha...
3
import collections a = input() b = input() stats = collections.defaultdict(int) removed = set() for _ in range(int(input())): minute, team, number, card = str.split(input()) player = team + number stats[player] += int(1 if card == "y" else 2) if stats[player] > 1 and player not in removed: r...
You are given a board of size n × n, where n is odd (not divisible by 2). Initially, each cell of the board contains one figure. In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell (i, j) you can move...
3
from sys import stdin import math a = int(stdin.readline()) for b in range(0,a): c=int(stdin.readline()) D=int(((c-1)*(c)*(c+1))/3) print(D)
Emuskald is addicted to Codeforces, and keeps refreshing the main page not to miss any changes in the "recent actions" list. He likes to read thread conversations where each thread consists of multiple messages. Recent actions shows a list of n different threads ordered by the time of the latest message in the thread....
3
n = int(input()) a = list(map(int,input().split())) i = n-1 while(a[i] > a[i-1]): i -= 1 print(i)
There is a building consisting of 10~000 apartments numbered from 1 to 10~000, inclusive. Call an apartment boring, if its number consists of the same digit. Examples of boring apartments are 11, 2, 777, 9999 and so on. Our character is a troublemaker, and he calls the intercoms of all boring apartments, till someone...
3
t = int(input()) while t > 0: t -= 1 x = input() print((int(x[0]) - 1)*10 + len(x)*(len(x) + 1)//2)
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
num = int(input()) multiples = [4,7,44,47,74,77,444,447,474,477,744,747,774,777] i = 0 isAlmostLucky = False while i < len(multiples) and multiples[i] <= num: if num % multiples[i] == 0: isAlmostLucky = True break i += 1 print( "YES" if isAlmostLucky else "NO")
You are given a complete directed graph K_n with n vertices: each pair of vertices u ≠ v in K_n have both directed edges (u, v) and (v, u); there are no self-loops. You should find such a cycle in K_n that visits every directed edge exactly once (allowing for revisiting vertices). We can write such cycle as a list of...
3
t=int(input()) for _ in range(t): n,l,r=map(int,input().split()) L=[0] tt=2*(n-1) for i in range(n): L.append(tt) tt-=2 L[-1]=1 temp=0 ct=r-l+1 c=0 tot=0 for i in range(1,len(L)): if(tot+L[i]<l): tot+=L[i] else: rem=l-tot...
Eleven wants to choose a new name for herself. As a bunch of geeks, her friends suggested an algorithm to choose a name for her. Eleven wants her name to have exactly n characters. <image> Her friend suggested that her name should only consist of uppercase and lowercase letters 'O'. More precisely, they suggested th...
3
def f(n): a=b=1 while True: if b > n: return yield b c = a+b a = b b = c n = int(input()) s = [False for _ in range(n)] for i in f(n): s[i-1] = True print(''.join([('O' if p else 'o') for p in s]))
There are n people and k keys on a straight line. Every person wants to get to the office which is located on the line as well. To do that, he needs to reach some point with a key, take the key and then go to the office. Once a key is taken by somebody, it couldn't be taken by anybody else. You are to determine the mi...
3
n,k,p = map(int,input().split()) a = [] b = [] temp = input().split() for i in range(n): a.append(int(temp[i])) temp = input().split() for i in range(k): b.append(int(temp[i])) list.sort(a) list.sort(b) mini = 0 for i in range(k-n+1): maxi = 0 cur = 0 for j in range(n): if p >= a[j]: ...
A string t is called an anagram of the string s, if it is possible to rearrange letters in t so that it is identical to the string s. For example, the string "aab" is an anagram of the string "aba" and the string "aaa" is not. The string t is called a substring of the string s if it can be read starting from some posi...
3
p, t = input(), input() n, m = len(t), len(p) if n > m: print(0) else: q = {c: p[: n].count(c) - t.count(c) - 1 for c in 'abcdefghijklmnopqrstuvwxyz'} q['?'] = 0 s = int(all(q[c] < 0 for c in 'abcdefghijklmnopqrstuvwxyz')) for i, j in zip(*[p[: m - n], p[n :]]): q[i] -= 1 q[j] += 1 ...
Welcome! Everything is fine. You have arrived in The Medium Place, the place between The Good Place and The Bad Place. You are assigned a task that will either make people happier or torture them for eternity. You have a list of k pairs of people who have arrived in a new inhabited neighborhood. You need to assign ea...
3
# ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase 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...
Vova is playing a computer game. There are in total n turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is k. During each turn Vova can choose what to do: * If the current charge of his laptop battery is strictly gre...
3
#!/usr/bin/env python3 # -*- coding: utf-8 -*- query_num = int(input()) for i in range(query_num): k, n, a, b = map(int, input().split()) if (k // b) < n or (k//b == n and k%b==0): print(-1) continue #(a-b)*x < k-b*n gap = a-b right = k-b*n turns = (right-1) // g...
One day Bob got a letter in an envelope. Bob knows that when Berland's post officers send a letter directly from city «A» to city «B», they stamp it with «A B», or «B A». Unfortunately, often it is impossible to send a letter directly from the city of the sender to the city of the receiver, that's why the letter is sen...
3
dict_route = {} cnt = int(input("").strip()) for i in range(cnt): peer = input("").strip().split() for p in peer: if not dict_route.get(p): dict_route[p] = [] peer_copy = peer.copy() peer_copy.remove(p) dict_route[p] += peer_copy start_end_keys = [] for key, val in ...
Screen resolution of Polycarp's monitor is a × b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x, y) (0 ≤ x < a, 0 ≤ y < b). You can consider columns of pixels to be numbered from 0 to a-1, and rows — from 0 to b-1. Polycarp wants to open a rectangular window of maximal size, which ...
3
import math as m T = int(input()) for t in range(0, T): a, b, x, y = map(int, input().split()) combs = [x*b,(a-x-1)*b,y*a,(b-y-1)*a] print(f"{max(combs)}")
«One dragon. Two dragon. Three dragon», — the princess was counting. She had trouble falling asleep, and she got bored of counting lambs when she was nine. However, just counting dragons was boring as well, so she entertained herself at best she could. Tonight she imagined that all dragons were here to steal her, and ...
3
k = int(input()) l = int(input()) m = int(input()) n = int(input()) d = int(input()) ans = len([x for x in range(1,d+1) if (x % k == 0 or x % l == 0 or x % m == 0 or x % n == 0)]) print(ans)
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word s. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if...
3
word = input() h = False e = False l1 = False l2 = False o = False hello = False for l in word: if not h: if l == 'h': h = True continue if not e: if l == 'e': e = True continue if not l1: if l == 'l': l1 = True continue ...
Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be n problems, sorted by difficulty, i.e. problem 1 is the easiest and problem n is the hardest. Limak knows it will take him 5·i minutes to solve the i-th...
3
# Ammirhossein Alimirzaei # Email: Amirhosseiny76@ayhoo.com # Instagram : Amirhossein_Alimirzaei # Telegram : @HajLorenzo N=list(map(int,input().split())) TIME=240-N[1] I=1 C=0 for _ in range(N[0]): TIME -= 5 * (_+1) if (TIME >= 0): C += 1 else: break print(C)
Polycarpus has a hobby — he develops an unusual social network. His work is almost completed, and there is only one more module to implement — the module which determines friends. Oh yes, in this social network one won't have to add friends manually! Pairs of friends are deduced in the following way. Let's assume that ...
1
import sys FROM = 0 TO = 1 TIME = 2 def run(inputStream): numMessages, maxTimeOffset = map(int, inputStream.readline().split()) messages = [] for messageNo in range(numMessages): rawMessage = inputStream.readline().split() messages.append((rawMessage[FROM], rawMessage[TO], int(rawMessage[T...
The chef won a duet singing award at Techsurge & Mridang 2012. From that time he is obsessed with the number 2. He just started calculating the powers of two. And adding the digits of the results. But he got puzzled after a few calculations. So gave you the job to generate the solutions to 2^n and find their sum of di...
1
def po(n): re,base=1,2 while(n): if n%2: re*=base base*=base n/=2 su=0 while(re): su+=re%10 re/=10 return su t=int(raw_input()) for i in xrange(t): n=int(raw_input()) print po(n)
Let us define the FizzBuzz sequence a_1,a_2,... as follows: * If both 3 and 5 divides i, a_i=\mbox{FizzBuzz}. * If the above does not hold but 3 divides i, a_i=\mbox{Fizz}. * If none of the above holds but 5 divides i, a_i=\mbox{Buzz}. * If none of the above holds, a_i=i. Find the sum of all numbers among the first...
3
print(sum(i for i in range(1,int(input())+1)if i%3 and i%5))
Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!). Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scisso...
1
import sys #import urllib import random #if( len(sys.argv) != 3 ): # print "Usage app.py (input file) (output file)" def gcd(a, b): while b: a, b = b, a % b return a def mcd(n, m): return (n/gcd(n,m))*m n = int(sys.stdin.readline()) a = sys.stdin.readline()[:-1] b = sys.stdin.readline()[:-1] ...
Tanya has n candies numbered from 1 to n. The i-th candy has the weight a_i. She plans to eat exactly n-1 candies and give the remaining candy to her dad. Tanya eats candies in order of increasing their numbers, exactly one candy per day. Your task is to find the number of such candies i (let's call these candies goo...
3
#!/usr/bin/env python # coding: utf-8 # In[2]: t = """1 4 3 3""" # In[34]: # t = """1 4 3 3""" n_ = int(input()) # nums = [[0 for _ in range(4)]]*n_ # for i in range(n): # nums[i][3] = int(input()) nums = list(map(int, input().split())) prev_ch = 0 prev_nch = 0 for i, n in enumerate(nums): ch = i % 2...
Like any unknown mathematician, Yuri has favourite numbers: A, B, C, and D, where A ≤ B ≤ C ≤ D. Yuri also likes triangles and once he thought: how many non-degenerate triangles with integer sides x, y, and z exist, such that A ≤ x ≤ B ≤ y ≤ C ≤ z ≤ D holds? Yuri is preparing problems for a new contest now, so he is v...
3
def readStr(): return input() def readInts(): return list(map(int, readStr().split(' '))) def s(a, b, c, z): s = 0 if b + c - z > 0: s += (b + c - z) * (b + c - z + 1) // 2 if a + c - z > 1: s -= (a + c - z - 1) * (a + c - z) // 2 if 2*b - z > 1: s -= (2*b - z - 1)...
Vasya has n pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every m-th day (at days with numbers m, 2m, 3m, ...) mom buys a pair of socks to Vasya. She does it late in the eve...
3
# -*- coding: utf-8 -*- """ Created on Tue Dec 10 17:52:43 2019 @author: 93464 """ n,k=map(int,input().split()) aa = 0 while n>= k: aa = aa+k n = n-k+1 aa = aa+n print(aa)
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
n = int(input()) for i in range(n): w = input() print(w[0]+str(len(w)-2)+w[-1] if len(w) > 10 else w)
Olesya loves numbers consisting of n digits, and Rodion only likes numbers that are divisible by t. Find some number that satisfies both of them. Your task is: given the n and t print an integer strictly larger than zero consisting of n digits that is divisible by t. If such number doesn't exist, print - 1. Input T...
1
import math n, t = map(int, raw_input().split()) a = 10**(n-1) while a % t != 0: a += 1 if len(str(a)) == n: print a else: print -1
Fafa owns a company that works on huge projects. There are n employees in Fafa's company. Whenever the company has a new project to start working on, Fafa has to divide the tasks of this project among all the employees. Fafa finds doing this every time is very tiring for him. So, he decided to choose the best l employ...
3
import sys import math import bisect def main(): n = int(input()) ans = 0 for i in range(1, n): if (n - i) % i == 0: ans += 1 print(ans) if __name__ == "__main__": main()
Some dwarves that are finishing the StUDY (State University for Dwarven Youngsters) Bachelor courses, have been told "no genome, no degree". That means that all dwarves should write a thesis on genome. Dwarven genome is far from simple. It is represented by a string that consists of lowercase Latin letters. Dwarf Mish...
3
import collections s1 = input() s2 = input() c1 = collections.Counter(s1) c2 = collections.Counter(s2) c = 0 s1 = list(s1) s2 = list(s2) if(len(c1) == len(c2)): for i in c1: if c1[i] != c2[i]: print('NO') break else: for i in range(len(s1)): if s1[i...
We have a string S consisting of lowercase English letters. If the length of S is at most K, print S without change. If the length of S exceeds K, extract the first K characters in S, append `...` to the end of them, and print the result. Constraints * K is an integer between 1 and 100 (inclusive). * S is a string ...
3
n = int(input()) s = input() if n<len(s): print(s[:n],"...",sep="") else: print(s)
You are given a sequence of n digits d_1d_2 ... d_{n}. You need to paint all the digits in two colors so that: * each digit is painted either in the color 1 or in the color 2; * if you write in a row from left to right all the digits painted in the color 1, and then after them all the digits painted in the color ...
3
for _ in range(int(input())): n=int(input()) s=list(map(int,list(input().strip()))) ans=[0]*n arr=[] for i in range(n): arr.append([s[i],i]) # arr.sort(key=lambda x:x[1],reverse=True) arr.sort(key=lambda x:x[0]) ans[arr[0][1]]=1 for i in range(1,n): if arr[i][1]>arr[i-1][1]: ans[arr[i][1]]=1 else: ...
Mishka started participating in a programming contest. There are n problems in the contest. Mishka's problem-solving skill is equal to k. Mishka arranges all problems from the contest into a list. Because of his weird principles, Mishka only solves problems from one of the ends of the list. Every time, he chooses whic...
1
nk=list(map(int,raw_input().split())) n=nk[0] k=nk[1] A=list(map(int,raw_input().split())) counter=0 if(k<max(A)): while(A[0]<=k)or(A[len(A)-1]<=k): if(A[0]<=k): counter+=1 A.pop(0) elif(A[len(A)-1]<=k): counter+=1 A.pop(len(A)-1) elif(k>=max(A)): ...
Your task is to write a program of a simple dictionary which implements the following instructions: * insert str: insert a string str in to the dictionary * find str: if the distionary contains str, then print 'yes', otherwise print 'no' Notes Template in C Constraints * A string consists of 'A', 'C', 'G', or 'T' ...
3
d={} n=int(input()) for i in range(n): com,gen=input().split(" ") if com=="insert": d[gen]=d.get(gen,0)+1 if com=="find": if gen in d: print("yes") else: print("no")
Boboniu gives you * r red balls, * g green balls, * b blue balls, * w white balls. He allows you to do the following operation as many times as you want: * Pick a red ball, a green ball, and a blue ball and then change their color to white. You should answer if it's possible to arrange all the b...
3
import math import time from collections import defaultdict,deque,Counter from sys import stdin,stdout from bisect import bisect_left,bisect_right from queue import PriorityQueue import sys t=int(input()) for _ in range(t): a=list(map(int,stdin.readline().split())) c=0 for i in range(4): if(a[i]&1)...
Given are N points (x_i, y_i) in a two-dimensional plane. Find the minimum radius of a circle such that all the points are inside or on it. Constraints * 2 \leq N \leq 50 * 0 \leq x_i \leq 1000 * 0 \leq y_i \leq 1000 * The given N points are all different. * The values in input are all integers. Input Input is giv...
3
n = int(input()) xy=[list(map(int,input().split())) for i in range(n)] import math def calc(x1, y1, x2, y2, x3, y3): try: d = 2 * ((y1 - y3) * (x1 - x2) - (y1 - y2) * (x1 - x3)) x = ((y1 - y3) * (y1 ** 2 - y2 ** 2 + x1 ** 2 - x2 ** 2) - (y1 - y2) * (y1 ** 2 - y3 ** 2 + x1 ** 2 - x3 ** 2)) / d ...
There are n people who want to participate in a boat competition. The weight of the i-th participant is w_i. Only teams consisting of two people can participate in this competition. As an organizer, you think that it's fair to allow only teams with the same total weight. So, if there are k teams (a_1, b_1), (a_2, b_2)...
3
for i in range(int(input())): n = int(input()) t= list(map(int,input().split())) f={} for j in t: if j not in f: f[j]=1 else: f[j]+=1 ans=0 t.sort() b = list(set(t)) for j in range(2,2*n+1): temp=0 for k in b: ...
You are given a permutation p_1, p_2, ..., p_n. Recall that sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once. Find three indices i, j and k such that: * 1 ≤ i < j < k ≤ n; * p_i < p_j and p_j > p_k. Or say that there are no such indices. Input The first lin...
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():...
Cowboy Vlad has a birthday today! There are n children who came to the celebration. In order to greet Vlad, the children decided to form a circle around him. Among the children who came, there are both tall and low, so if they stand in a circle arbitrarily, it may turn out, that there is a tall and low child standing n...
3
n=int(input()) arr=list(map(int,input().split())) arr.sort() newarr=[-1]*n start,end=0,n-1 i=0 while(i<n): newarr[start]=arr[i] i=i+1 start=start+1 if(i<n and start!=end): newarr[end]=arr[i] i=i+1 end=end-1 print(*newarr)
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network. Bu...
3
user = input("") count = ("") for i in user: if i not in count: count += i if len(count) % 2 ==0: print("CHAT WITH HER!") else: print("IGNORE HIM!")
Queue is a container of elements that are inserted and deleted according to FIFO (First In First Out). For $n$ queues $Q_i$ ($i = 0, 1, ..., n-1$), perform a sequence of the following operations. * enqueue($t$, $x$): Insert an integer $x$ to $Q_t$. * front($t$): Report the value which should be deleted next from $Q_t...
3
from collections import deque n,q=map(int, input().split( )) Q=[] for i in range(n): D=deque() Q.append(D) for i in range(q): c,*a=map(int,input().split( )) if c==0: Q[a[0]].append(a[1]) elif c==1: if len(Q[a[0]])>0: print(Q[a[0]][0]) else: pass el...
Sasha is a very happy guy, that's why he is always on the move. There are n cities in the country where Sasha lives. They are all located on one straight line, and for convenience, they are numbered from 1 to n in increasing order. The distance between any two adjacent cities is equal to 1 kilometer. Since all roads in...
3
n,v = list(map(int,input().split())) print(n-1 if n-1<=v else v + (n-v-1)*(n-v+2)//2)
There is a sequence of length N: A_1, A_2, ..., A_N. Initially, this sequence is a permutation of 1, 2, ..., N. On this sequence, Snuke can perform the following operation: * Choose K consecutive elements in the sequence. Then, replace the value of each chosen element with the minimum value among the chosen elements....
3
n, m = map(int, input().split()) print(-(-(n-1)//(m-1)))
You are given some Tetris field consisting of n columns. The initial height of the i-th column of the field is a_i blocks. On top of these columns you can place only figures of size 2 × 1 (i.e. the height of this figure is 2 blocks and the width of this figure is 1 block). Note that you cannot rotate these figures. Yo...
3
t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) m = min(a) print('NO' if any([(x-m)&1 for x in a]) else 'YES') # ok = 1 # for x in a: # if (x-m)&1: # ok = 0 # break # print('YES' if ok else 'NO')
You are locked in a room with a door that has a keypad with 10 keys corresponding to digits from 0 to 9. To escape from the room, you need to enter a correct code. You also have a sequence of digits. Some keys on the keypad have fingerprints. You believe the correct code is the longest not necessarily contiguous subse...
1
x, z = map(int, raw_input().split()) l = list(map(int, raw_input().split())) m = list(map(int, raw_input().split())) w = [] for i in range(x): if l[i] in m: w.append(l[i]) print ' '.join(map(str ,w))
Captain Flint and his crew keep heading to a savage shore of Byteland for several months already, drinking rum and telling stories. In such moments uncle Bogdan often remembers his nephew Denis. Today, he has told a story about how Denis helped him to come up with an interesting problem and asked the crew to solve it. ...
3
for i in range (int(input())): n=int(input()) if n%4==0: print('9'*(n-((n-1)//4+1))+'8'*((n-1)//4+1)) else: print('9'*(n-(n//4+1))+'8'*(n//4+1))
A permutation of length n is a sequence of integers from 1 to n of length n containing each number exactly once. For example, [1], [4, 3, 5, 1, 2], [3, 2, 1] are permutations, and [1, 1], [0, 1], [2, 2, 1, 4] are not. There was a permutation p[1 ... n]. It was merged with itself. In other words, let's take two instanc...
3
t=int(input ()) for tt in range(t): n=int(input()) z=list(input().split()) a=[] a.append(z[0]) for i in range(1,len(z)): c=0 for j in range(0,i): if(z[j]==z[i]): c=1 break if(c==0): a.append(z[i]) f=[] for k in r...
Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpr...
3
[a, b] = list(map(int, input().split(" "))) r = ['1/6', '1/3', '1/2', '2/3', '5/6', '1/1'] print(r[6 - max(a,b)])
Arkady invited Anna for a dinner to a sushi restaurant. The restaurant is a bit unusual: it offers n pieces of sushi aligned in a row, and a customer has to choose a continuous subsegment of these sushi to buy. The pieces of sushi are of two types: either with tuna or with eel. Let's denote the type of the i-th from t...
3
from sys import stdin n=int(stdin.readline().strip()) s=list(map(int,stdin.readline().strip().split())) s1=[] x=1 for i in range(1,n): if s[i]!=s[i-1]: s1.append(x) x=1 else: x+=1 s1.append(x) ans=0 for i in range(1,len(s1)): ans=max(ans,min(s1[i],s1[i-1])*2) print(ans)
Theatre Square in the capital city of Berland has a rectangular shape with the size n × m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a × a. What is the least number of flagstones needed to pave the Square? It'...
3
n,m,a=map(int,input().split()) if n%a==0: c=n//a else: c=(n//a)+1 if m%a==0: c1=m//a else: c1=(m//a)+1 ans=c*c1 print(ans)
Petya is having a party soon, and he has decided to invite his n friends. He wants to make invitations in the form of origami. For each invitation, he needs two red sheets, five green sheets, and eight blue sheets. The store sells an infinite number of notebooks of each color, but each notebook consists of only one co...
3
n,k=[int(x) for x in input().split()] print(-((-2*n)//k+(-5*n)//k+(-8*n)//k))
Today is August 24, one of the five Product Days in a year. A date m-d (m is the month, d is the date) is called a Product Day when d is a two-digit number, and all of the following conditions are satisfied (here d_{10} is the tens digit of the day and d_1 is the ones digit of the day): * d_1 \geq 2 * d_{10} \geq 2 *...
3
m,d=map(int,input().split()) ans=0 for i in range(1,m+1): for j in range(1,d+1): d10=j//10 d1=j-d10*10 if d1>=2 and d10>=2 and i==d1*d10: ans+=1 print(ans)
Tokitsukaze is one of the characters in the game "Kantai Collection". In this game, every character has a common attribute — health points, shortened to HP. In general, different values of HP are grouped into 4 categories: * Category A if HP is in the form of (4 n + 1), that is, when divided by 4, the remainder is ...
3
x = int(input()) rem = x % 4 if rem == 0: print("1 A") elif rem == 1: print("0 A") elif rem == 2: print("1 B") else: print("2 A")
The problem of hiding a part of a formula and searching for the hidden number is called verbal arithmetic. This time, I'm dealing with an expression in which some numbers in the expression are hidden by X. Enter the following formula and create a program that outputs the result. Formula * A simple one-line addition e...
3
if __name__ == '__main__': while True: try: a,z = input().split("=") x,y = a.split("+") start = 0 if (len(x) > 1 and x[0] == "X") or (len(y) > 1 and y[0] == "X") or (len(z) > 1 and z[0] == "X"): start = 1 # x + y = zの形式に変換 ans = False for i in range(start,10): x1 = x.replace("X",str(i)...
You like playing chess tournaments online. In your last tournament you played n games. For the sake of this problem, each chess game is either won or lost (no draws). When you lose a game you get 0 points. When you win you get 1 or 2 points: if you have won also the previous game you get 2 points, otherwise you get 1 ...
3
t = int (input ()) tests = [] for i in range (t): n, k = map (int, input().split()) s = input () tests.append ([n,k,s]) for test in tests: n, k, s = test result = 0 w = s.count('W') if w == 0: if k == 0: print (0) else: print (min(n,k)*...
There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of ope...
1
import atexit import io import sys @atexit.register def flush(): sys.__stdout__.write(sys.stdout.getvalue()) sys.stdout = io.BytesIO() input = sys.stdin.readline sys.stdout = io.BytesIO() n = int(input()) b = list(input().strip()) w = b[:] moves = [] for i in xrange(n - 1): if b[i] == "W": moves.append(i + 1...
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
n = int(input().strip()) printing = [] for test in range(n): m = input() a = input().strip().split(" ") b= [] for c in a: b.append(int(c)) b.sort() if int(b[0]) + int(b[1]) <= int(b[-1]): d = [] d.append(a.index(str(b[0]))+1) d.append(a...
Valera had two bags of potatoes, the first of these bags contains x (x ≥ 1) potatoes, and the second — y (y ≥ 1) potatoes. Valera — very scattered boy, so the first bag of potatoes (it contains x potatoes) Valera lost. Valera remembers that the total amount of potatoes (x + y) in the two bags, firstly, was not gerater ...
3
import math y, k, n = map(int, input().split()) x = k * math.ceil(y / k) - y if x == 0: x = k i = 0 if y + x > n: print(-1) else: while y + i * k + x <= n: print(i * k + x, end=' ') i += 1
Valera has got n domino pieces in a row. Each piece consists of two halves — the upper one and the lower one. Each of the halves contains a number from 1 to 6. Valera loves even integers very much, so he wants the sum of the numbers on the upper halves and the sum of the numbers on the lower halves to be even. To do t...
3
t = int(input()) c = [0, 0, 0, 0] for _ in range(t): a, b = input().split(' ') a = int(a)%2 b = int(b)%2 c[a + 2 * b] += 1 #print(c) if (c[1]+c[3])%2 == 0 and (c[2]+c[3])%2 == 0: print(0) elif (abs(c[2]-c[1])%2 == 0): if c[1] == 0 and c[2] == 0: print(-1) else: print(1) e...
Nikolay has a lemons, b apples and c pears. He decided to cook a compote. According to the recipe the fruits should be in the ratio 1: 2: 4. It means that for each lemon in the compote should be exactly 2 apples and exactly 4 pears. You can't crumble up, break up or cut these fruits into pieces. These fruits — lemons, ...
3
ans = 0 a = int(input().strip()) b = int(input().strip()) c = int(input().strip()) while a>=1 and b>=2 and c>=4: ans+=7 a-=1 b-=2 c-=4 print(ans)
Polycarp has n coins, the value of the i-th coin is a_i. Polycarp wants to distribute all the coins between his pockets, but he cannot put two coins with the same value into the same pocket. For example, if Polycarp has got six coins represented as an array a = [1, 2, 4, 3, 3, 2], he can distribute the coins into two ...
3
T = int(input()) numbers = [int(s) for s in input().split(" ")] maxi = 0 for i in range(0,len(numbers)): lol = numbers.count(numbers[i]) if lol>maxi: maxi = lol print(maxi)
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated. The language is that peculiar as it has exactly one variable, called x. Also, there are two operations: * Operation ++ increases the value of variable x by 1. * Operation -- decreases the value of variable x by 1....
3
x = 0 n = int(input()) for i in range (n): s = input() if "++" in s: x += 1 elif "--" in s: x -= 1 print(x)
Now it's time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. They've been best friends ever since primary school and hopefully, that can somehow help them in teamwork. For each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing ...
3
n, m = map(int, input().split()) if n - m > 1 or m > 2*(n+1): print(-1) exit() res, x = '', 0 while n >= 1 and m >= 1: res += '10' n -= 1 m -= 1 x += 1 res = ('0' * n) + res.replace('1', '11', m) + ('1' * max(0, m-x)) print(res)
Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they ...
3
n=int(input()) st=[] for i in range(n): s=input() if s not in st: print ("NO") st.append(s) else: print ("YES")
You are given the array a consisting of n positive (greater than zero) integers. In one move, you can choose two indices i and j (i ≠ j) such that the absolute difference between a_i and a_j is no more than one (|a_i - a_j| ≤ 1) and remove the smallest of these two elements. If two elements are equal, you can remove a...
3
arr=[] test_cases=int(input('')) for x in range(test_cases): input('') a=[] a = list(map(int,input().split())) arr.append(a) for i in range(test_cases): leng=len(arr[i]) summ=0 even_count=0 odd_count=0 for j in range(leng): if arr[i][j] %2==0: even_c...
You have decided to watch the best moments of some movie. There are two buttons on your player: 1. Watch the current minute of the movie. By pressing this button, you watch the current minute of the movie and the player automatically proceeds to the next minute of the movie. 2. Skip exactly x minutes of the movi...
1
n, x = map(int, raw_input().split(' ')) m = [] for i in range(n): m.append(map(int, raw_input().split(' '))) m.sort(key=lambda x: x[0]) m.reverse() r = 0 c = 1 while m: a = m.pop() while (c + x) <= a[0]: c += x r += a[0] - c + 1 r += a[1] - a[0] c = a[1] + 1 print r
One way to create a task is to learn from life. You can choose some experience in real life, formalize it and then you will get a new task. Let's think about a scene in real life: there are lots of people waiting in front of the elevator, each person wants to go to a certain floor. We can formalize it in the following...
3
n, k = map(int, input().split()) a = list(map(int, input().split())) a.sort() prev = 1 ans = 0 for i, x in enumerate(a): t = n - i c = (t + k - 1) // k v = 2 * c * (x - prev) ans += v prev = x 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
# -*- coding: utf-8 -*- """ Created on Fri Oct 23 22:53:24 2020 @author: qzb11 """ import copy word = list(input().lower()) word2 = copy.deepcopy(word) vowel = ['a','o','y','e','u','i'] x = 0 for n in word: if n in vowel: word2.remove(n); l = len(word2); while x < 2*l: word2.insert(x, '.'); x += 2;...
How many multiples of d are there among the integers between L and R (inclusive)? Constraints * All values in input are integers. * 1 \leq L \leq R \leq 100 * 1 \leq d \leq 100 Input Input is given from Standard Input in the following format: L R d Output Print the number of multiples of d among the integers b...
1
FAST_IO = 1 if FAST_IO: import io, sys, atexit rr = iter(sys.stdin.read().splitlines()).next sys.stdout = _OUTPUT_BUFFER = io.BytesIO() @atexit.register def write(): sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) else: rr = raw_input rri = lambda: int(rr()) rrm = lambda: map(int, rr()....
You are given a multiset S initially consisting of n distinct non-negative integers. A multiset is a set, that can contain some elements multiple times. You will perform the following operation k times: * Add the element ⌈(a+b)/(2)⌉ (rounded up) into S, where a = \operatorname{mex}(S) and b = max(S). If this numbe...
3
from sys import stdin,stdout,setrecursionlimit from functools import lru_cache, cmp_to_key from heapq import merge, heapify, heappop, heappush,nlargest from math import * from collections import defaultdict as dd, deque, Counter as C from itertools import combinations as comb, permutations as perm , accumulate from bis...
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 def solve(n,m): if n==1 and m ==1: return 1 if n==1 or m==1: return math.ceil((n*m)/2) if n%2==0 and m%2==0: return (n*m)//2 else: a = n b = m if n%2 != 0: a = n-1 if m%2 != 0: b = m-1 ans = (a*b)//2 ...