problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
Petr, Nikita G. and Nikita are the most influential music critics in Saint-Petersburg. They have recently downloaded their favorite band's new album and going to listen to it. Nikita claims that the songs of entire album should be listened strictly in the same order as they are given, because there is the secret messag...
1
t=raw_input() t=int(t) for i in range(1,t+1): n=raw_input() n=int(n) ans=0.0 for j in range(1,n+1): ans=ans+(1.0*n)/j print ans
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
#!/usr/bin/env pypy polyhedrons = {"Tetrahedron":4,"Cube":6,"Octahedron":8,"Dodecahedron":12,"Icosahedron":20} n = int(input()) lst = [polyhedrons[input()] for _ in range(n)] print(sum(lst))
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
s = [int(x) for x in input().split("+")] for i in range(len(s)): c = sorted(s)[i] print(c, end="") if i != len(s) - 1: print("+", end="")
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'...
1
n, m, a = map(int, raw_input().split()) from math import ceil print int(ceil(n*1.0/a)*ceil(m*1.0/a))
There are league games and tournament games in sports competitions. In soccer league games, points are given to each of the wins, losses, and draws, and the rankings are competed based on the points. The points are win (3 points), negative (0 points), and draw (1 point), respectively. Enter the number of teams and the...
3
def getScore(d): return int(d[1]) * 3 + int(d[3]) isFirst = True while 1: n = int(input()) if n == 0: break if not isFirst: print() table = [] for i in range(0,n): d = list(_ for _ in input().split()) score = getScore(d) table.append((d[0],score)) ...
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
n = input() s = input().split() s = list(map(int,s)) a = list(range(0,4)) for i in range(0,4): a[i] = 0 taxi = 0 for i in range(0,len(s)): if (s[i] == 1): if (a[1] > 0): a[1] -= 1 else: a[3] += 1 taxi += 1 elif (s[i] == 2): if (a[2] > 0): ...
The only difference between the easy and the hard versions is constraints. A subsequence is a string that can be derived from another string by deleting some or no symbols without changing the order of the remaining symbols. Characters to be deleted are not required to go successively, there can be any gaps between th...
3
import sys n, k = map(int, sys.stdin.readline().split(' ')) s = sys.stdin.readline().strip() lt = [s] count = 0 flag = False result = 0 while lt: cur_s = lt[0] lt.pop(0) result += len(s) - len(cur_s) count += 1 if count >= k: break for i in range(0, len(cur_s)): new_s = c...
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
str = input() list1=str.split("+") list1.sort() print("+".join(list1))
A permutation p of size n is an array such that every integer from 1 to n occurs exactly once in this array. Let's call a permutation an almost identity permutation iff there exist at least n - k indices i (1 ≀ i ≀ n) such that pi = i. Your task is to count the number of almost identity permutations for given numbers...
3
""" while 1: n, k = map(int, input().split()) def solve(n, k): from itertools import permutations res = 0 for p in permutations([i for i in range(n)]): c = sum(i == p[i] for i in range(n)) if c >= n - k: res += 1 return res print(solve(n, k)...
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings. Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, seco...
3
n=int(input()) s='' for k in range(1,n): if k % 2 == 1: s+='I hate that ' else: s+='I love that ' if n % 2 == 1: s+='I hate it' else: s+='I love it' print(s)
Mishka got an integer array a of length n as a birthday present (what a surprise!). Mishka doesn't like this present and wants to change it somehow. He has invented an algorithm and called it "Mishka's Adjacent Replacements Algorithm". This algorithm can be represented as a sequence of steps: * Replace each occurre...
3
input() print(*[x if x%2!=0 else x-1 for x in map(int,input().split())])
Being stuck at home, Ray became extremely bored. To pass time, he asks Lord Omkar to use his time bending power: Infinity Clock! However, Lord Omkar will only listen to mortals who can solve the following problem: You are given an array a of n integers. You are also given an integer k. Lord Omkar wants you to do k ope...
3
t=int(input()) for i in range(t): n,k=input().split() n=int(n) k=int(k) list1=list(map(int,input().split())) if k%2==0: for j in range(2): d=max(list1) for i in range(n): list1[i]=d-list1[i] else: d=max(list1) for i in range(n)...
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th...
3
s = input() c = 0 for ch in s: if 'A' <= ch <='Z': c+=1 if c>len(s)/2: print(s.upper()) else: print(s.lower())
Neko loves divisors. During the latest number theory lesson, he got an interesting exercise from his math teacher. Neko has two integers a and b. His goal is to find a non-negative integer k such that the least common multiple of a+k and b+k is the smallest possible. If there are multiple optimal integers k, he needs ...
3
ii = lambda: int(input()) mi = lambda: map(int, input().split()) li = lambda: list(mi()) a,b=mi() a,b = min(a,b), max(a,b) X = b-a def gcd(a, b): if b == 0: return a else: return gcd(b, a % b) def lcm(a, b): return a*b//gcd(a,b) def prime_factor(x): pf = [] for i in range(1,...
A and B are preparing themselves for programming contests. To train their logical thinking and solve problems better, A and B decided to play chess. During the game A wondered whose position is now stronger. For each chess piece we know its weight: * the queen's weight is 9, * the rook's weight is 5, * the ...
3
x = 0 y = 0 for i in range(8): for i in input(): if i == 'Q': x += 9 elif i == 'R': x += 5 elif i == 'B' or i == 'N': x += 3 elif i == 'P': x += 1 elif i == 'q': y += 9 elif i == 'r': y += 5 ...
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are ...
3
n, d = map(int,input().split()) s=list(map(int,input().split())) ways=0 for i in range(n): for j in range(n): if i!=j and abs(s[i]-s[j])<=d: ways+=1 print(ways)
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 solve(): n = int(input()) a = list(map(int,input().split())) for i in range(n): for j in range(i+1,n): if(a[j]==a[i] and j-i>1): print("YES") return print("NO") for _ in range(int(input())): solve()
Arpa is researching the Mexican wave. There are n spectators in the stadium, labeled from 1 to n. They start the Mexican wave at time 0. * At time 1, the first spectator stands. * At time 2, the second spectator stands. * ... * At time k, the k-th spectator stands. * At time k + 1, the (k + 1)-th specta...
3
def solution851a(): n, k, t = map(int, input().split()) if t < k: ans = t elif k <= t <= n: ans = k else: ans = n + k - t print(ans) if __name__ == '__main__': solution851a()
Write a program which reads a $n \times m$ matrix $A$ and a $m \times l$ matrix $B$, and prints their product, a $n \times l$ matrix $C$. An element of matrix $C$ is obtained by the following formula: \\[ c_{ij} = \sum_{k=1}^m a_{ik}b_{kj} \\] where $a_{ij}$, $b_{ij}$ and $c_{ij}$ are elements of $A$, $B$ and $C$ res...
3
n, m, l = map(int, input().split()) A = [list(map(int, input().split())) for _ in [0]*n] B = [list(map(int, input().split())) for _ in [0]*m] C = [[0 for _ in range(l)] for _ in range(n)] for i in range(n): for j in range(l): for k in range(m): C[i][j] += A[i][k] * B[k][j] [print(*...
Fifa and Fafa are sharing a flat. Fifa loves video games and wants to download a new soccer game. Unfortunately, Fafa heavily uses the internet which consumes the quota. Fifa can access the internet through his Wi-Fi access point. This access point can be accessed within a range of r meters (this range can be chosen by...
3
import sys import math def dist(x1, y1, x2, y2): return math.sqrt((y2 - y1) ** 2 + (x2 - x1) ** 2) def solve(io): R, c_x, c_y, mate_x, mate_y = io.readInt(), io.readInt(), io.readInt(), io.readInt(), io.readInt() # is asshole in the room? distance = dist(c_x, c_y, mate_x, mate_y) if(distance >= R): ...
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, m, a = int(n), int(m), int(a) print((n//a + 1-(0**(n%a)))*(m//a + 1-(0**(m%a))))
The HR manager was disappointed again. The last applicant failed the interview the same way as 24 previous ones. "Do I give such a hard task?" β€” the HR manager thought. "Just raise number 5 to the power of n and get last two digits of the number. Yes, of course, n can be rather big, and one cannot find the power using ...
3
from math import ceil, log, floor, sqrt import math k = 1 def mod_expo(n, p, m): """find (n^p)%m""" result = 1 while p != 0: if p%2 == 1: result = (result * n)%m p //= 2 n = (n * n)%m return result def is_prime(n): m = 2 while m*m <= n: if n%m == 0: return False m += 1 return True def f...
You are given two positive integers n (1 ≀ n ≀ 10^9) and k (1 ≀ k ≀ 100). Represent the number n as the sum of k positive integers of the same parity (have the same remainder when divided by 2). In other words, find a_1, a_2, …, a_k such that all a_i>0, n = a_1 + a_2 + … + a_k and either all a_i are even or all a_i ar...
3
t=int(input()) for i in range(t): n,k=map(int,input().split()) if n%k==0: print("YES") for i in range(k): print(n//k,end=' ') print() elif n%2!=0 and k%2==0: print("NO") elif k>n: print("NO") elif n % 2 == 0: l = [] if (k - 1) * 2 ...
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings. Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, seco...
3
a = int(input()) for i in range(a): if i % 2 == 0: print("I hate", end=' ') else: print("I love", end=' ') if i != a-1: print("that", end=' ') else: print("it", end=' ')
A binary string is a string where each character is either 0 or 1. Two binary strings a and b of equal length are similar, if they have the same character in some position (there exists an integer i such that a_i = b_i). For example: * 10010 and 01111 are similar (they have the same character in position 4); * 10...
3
from sys import stdin input = lambda : stdin.readline().strip() for _ in range(int(input())): n = int(input()) s = input() ans = '' i = 0 while(i<n): ans += s[2*i] i += 1 print(ans)
Given is an integer N. Takahashi chooses an integer a from the positive integers not greater than N with equal probability. Find the probability that a is odd. Constraints * 1 \leq N \leq 100 Input Input is given from Standard Input in the following format: N Output Print the probability that a is odd. Your ...
3
n=int(input());print((n//2+n%2)/n)
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()) c=0 l,d=[],[] for i in range(n): x,y=map(int,input().split()) l.append(x) d.append(y) for i in l: for j in d: if(i==j): c=c+1 print(c)
problem To the west of the Australian continent is the wide Indian Ocean. Marine researcher JOI is studying the properties of N species of fish in the Indian Ocean. For each type of fish, a rectangular parallelepiped habitat range is determined in the sea. Fish can move anywhere in their habitat, including boundaries...
3
# copy n, k = map(int, input().split()) plst = [] xlst = [] ylst = [] dlst = [] for _ in range(n): x1, y1, d1, x2, y2, d2 = map(int, input().split()) plst.append((x1, y1, d1, x2, y2, d2)) xlst.append(x1) xlst.append(x2) ylst.append(y1) ylst.append(y2) dlst.append(d1) dlst.append(d2) xl...
You are given a sequence a consisting of n integers. You may partition this sequence into two sequences b and c in such a way that every element belongs exactly to one of these sequences. Let B be the sum of elements belonging to b, and C be the sum of elements belonging to c (if some of these sequences is empty, the...
1
n=int(raw_input()) a=list(map(int,raw_input().split())) sum=0 for i in range(n): if a[i]>=0: sum=sum+a[i] else: sum=sum-a[i] print sum
Gardener Alexey teaches competitive programming to high school students. To congratulate Alexey on the Teacher's Day, the students have gifted him a collection of wooden sticks, where every stick has an integer length. Now Alexey wants to grow a tree from them. The tree looks like a polyline on the plane, consisting o...
3
n=int(input()) a=[int(n) for n in input().split()] a.sort() mid=n//2 sum=(sum(a[0:mid]))**2+(sum(a[mid:]))**2 print(sum)
There is a game called "I Wanna Be the Guy", consisting of n levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game. Little X can pass only p levels of the game. And Little Y can pass only q levels of the game. You are given the indices of levels Little X can pass ...
3
n = int(input()) n1, *x1 = [int(x) for x in input().split()] n2, *x2 = [int(x) for x in input().split()] print('I become the guy.' if len(set(x1 + x2)) == n else 'Oh, my keyboard!')
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th...
3
s = input() import re A = re.findall(r'[A-Z]',s) a = re.findall(r'[a-z]',s) print(s.lower() if len(a)>=len(A) else s.upper())
IT City administration has no rest because of the fame of the Pyramids in Egypt. There is a project of construction of pyramid complex near the city in the place called Emerald Walley. The distinction of the complex is that its pyramids will be not only quadrangular as in Egypt but also triangular and pentagonal. Of co...
3
from functools import reduce from math import factorial l1, l2, l3 = [int(x) for x in input().split()] A = (2**0.5)/12 B = ((15 + 5*5**0.5)/288)**0.5 print((l1**3 + 2*l2**3)*A + B*l3**3)
You are given two arrays of integers a and b. For each element of the second array bj you should find the number of elements in array a that are less than or equal to the value bj. Input The first line contains two integers n, m (1 ≀ n, m ≀ 2Β·105) β€” the sizes of arrays a and b. The second line contains n integers β€” ...
3
n,m = map(int,input().split()) a = sorted([int(i) for i in input().split()]+[10**9+7]) b = [int(i) for i in input().split()] d = b.copy() b.sort() i,j = 0,0 e = {} while i<=n and j<m: if b[j]>=a[i]: i+=1 else: e[b[j]]=i j+=1 for i in d: print(e[i],end=" ")
You have array of n numbers a_{1}, a_{2}, …, a_{n}. Rearrange these numbers to satisfy |a_{1} - a_{2}| ≀ |a_{2} - a_{3}| ≀ … ≀ |a_{n-1} - a_{n}|, where |x| denotes absolute value of x. It's always possible to find such rearrangement. Note that all numbers in a are not necessarily different. In other words, some numb...
3
for _ in range(int(input())): N=int(input()) L=list(map(int,input().split())) L.sort(reverse=True) X=[] for i in range(N//2): X.append(L[i]) X.append(L[N-1-i]) if N%2!=0: X.append(L[N//2]) X.reverse() print(*X)
Acacius is studying strings theory. Today he came with the following problem. You are given a string s of length n consisting of lowercase English letters and question marks. It is possible to replace question marks with lowercase English letters in such a way that a string "abacaba" occurs as a substring in a resulti...
3
import sys, os.path from collections import deque from fractions import Fraction as f def IO(): if os.path.exists('input.txt'): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') else: input=sys.stdin.readline print=sys.stdout.write def nextInt(): return ...
Vasya has two arrays A and B of lengths n and m, respectively. He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array [1, ...
3
n1 = int(input()) a1 = list(map(int, input().split())) n2 = int(input()) a2 = list(map(int, input().split())) if n1 < n2: a1, a2 = a2, a1 if sum(a1) != sum(a2): print(-1) else: c = 1 f = 0 s = 0 c1 = a1[f] c2 = a2[s] while s + 1 < len(a2) and f + 1 < len(a1): if c1 == c2: ...
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...
3
n,m=map(int,input().split(" ")) di={} for i in range(m): a,b=map(str,input().split(" ")) di[a]=b li=list(map(str,input().split(" ",n)[:n])) st="" for i in range(len(li)): # if li[i] in di.keys(): if len(li[i])<=len(di[li[i]]): st+=li[i] else: st+=di[li[i]] # else: # if le...
Appleman and Toastman play a game. Initially Appleman gives one group of n numbers to the Toastman, then they start to complete the following tasks: * Each time Toastman gets a group of numbers, he sums up all the numbers and adds this sum to the score. Then he gives the group to the Appleman. * Each time Applema...
3
import heapq N = int(input()) A = sorted(list(map(lambda x: -int(x), input().split()))) if N == 1: print(-A[0]) exit() score = 0 while 1: a = heapq.heappop(A) b = heapq.heappop(A) c = a+b score += c heapq.heappush(A, c) if len(A) < 2: break print(-(score+A[0]))
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings. Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, seco...
3
i= int(input()) k=i+(i-1) bear=["I hate","that","I love","that"] for x in range(k): print (bear[x%4],end=" ") print ("it")
Polycarpus has a sequence, consisting of n non-negative integers: a1, a2, ..., an. Let's define function f(l, r) (l, r are integer, 1 ≀ l ≀ r ≀ n) for sequence a as an operation of bitwise OR of all the sequence elements with indexes from l to r. Formally: f(l, r) = al | al + 1 | ... | ar. Polycarpus took a piece of...
1
n=input() r=set() t={} for i in map(int,raw_input().split()):t={i|j for j in t};t.add(i);r|=t print len(r)
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
str1=input() a=[] for i in str1: if i=='h' and i not in a and 'e' not in a and 'l' not in a and 'o' not in a: a.append(i) elif i=='e' and i not in a and 'h' in a and 'l' not in a and 'o' not in a: a.append(i) elif i=='l' and a.count(i)<2 and 'h' in a and 'e' in a and 'o' not in a: a....
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory. George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living...
3
n = input() count = 0 for i in range(1,int(n)+1): o , p = input().split() o = int(o) p = int(p) if o == p: pass elif int(p-o)>=2: count = count+1 print(count)
E869120's and square1001's 16-th birthday is coming soon. Takahashi from AtCoder Kingdom gave them a round cake cut into 16 equal fan-shaped pieces. E869120 and square1001 were just about to eat A and B of those pieces, respectively, when they found a note attached to the cake saying that "the same person should not t...
3
a, b = map(int, input().split()) ans = ':(' if a > 8 or b > 8 else 'Yay!' print(ans)
Three poles stand evenly spaced along a line. Their heights are a, b and c meters, from left to right. We will call the arrangement of the poles beautiful if the tops of the poles lie on the same line, that is, b-a = c-b. Determine whether the arrangement of the poles is beautiful. Constraints * 1 \leq a,b,c \leq 10...
3
a,b,c = map(int,input().split()) print("NO" if 2*b-a-c else "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
# coding: utf - 8 ''' ΠŸΡ€ΠΎΠ²Π΅Ρ€ΠΊΠ° ''' W = int (input()) if W % 2 == 0 and W != 2 : print ('YES') else: print ('NO')
Your security guard friend recently got a new job at a new security company. The company requires him to patrol an area of the city encompassing exactly N city blocks, but they let him choose which blocks. That is, your friend must walk the perimeter of a region whose area is exactly N blocks. Your friend is quite lazy...
3
from math import ceil,floor from math import sqrt n=int(input()) l=sqrt(n) if ceil(l)==floor(l): print(int(4*l)) else: g1=ceil(l) g2=floor(l) m=(g1+g2)/2 if l>=m: print(ceil(l)*4) else: print((ceil(l)+floor(l))*2)
There are quite a lot of ways to have fun with inflatable balloons. For example, you can fill them with water and see what happens. Grigory and Andrew have the same opinion. So, once upon a time, they went to the shop and bought n packets with inflatable balloons, where i-th of them has exactly a_i balloons inside. T...
3
class pac: def __init__(self,val,ind): self.val=val self.ind=ind n=int(input()) arrr=list(map(int,input().split())) if (n==1): print(-1) elif n==2: if arrr[0]==arrr[1]: print(-1) else: print(1) print(1) else: arr=[] for i in range(n): arr.append(pac(arrr[i],i+1)) arr.sort(key = lambda pac: pac.va...
Drazil is playing a math game with Varda. Let's define <image> for positive integer x as a product of factorials of its digits. For example, <image>. First, they choose a decimal number a consisting of n digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then th...
3
# fact_dict = { # 0:1, 1:1, 2:2, 3:6, # 4:24, 5:120, 6:720, 7:5040, # 8:40320, 9:362880 # } # _ = input() # n = input().lstrip('0') # a1 = 1 # for i in n: # a1 *= fact_dict[int(i)] # print(a1) # a2 = '' # while a1 > 1: # print(a1 , a2) # if a1 % fact_dict[2]==0: # a1 /= fact_dict[2] # a2 += '...
Mad scientist Mike is building a time machine in his spare time. To finish the work, he needs a resistor with a certain resistance value. However, all Mike has is lots of identical resistors with unit resistance R0 = 1. Elements with other resistance can be constructed from these resistors. In this problem, we will co...
1
from fractions import * a, b = map(int, raw_input().split(" ")) count = 0 g = gcd(a, b) a /= g b /= g if a > b: count += a / b a = a % b while b <> 1: c = a a = b b = c if a > b: count += a / b a = a % b g = gcd(a, b) a /= g b /= g count+=a print count
Anna is a girl so brave that she is loved by everyone in the city and citizens love her cookies. She is planning to hold a party with cookies. Now she has a vanilla cookies and b chocolate cookies for the party. She invited n guests of the first type and m guests of the second type to the party. They will come to the ...
3
from math import * sInt = lambda: int(input()) mInt = lambda: map(int, input().split()) lInt = lambda: list(map(int, input().split())) t = sInt() for _ in range(t): a,b,n,m = mInt() if (n+m)<=(a+b) and m<=min(a,b): print("Yes") else: print("No")
Two-gram is an ordered pair (i.e. string of length two) of capital Latin letters. For example, "AZ", "AA", "ZA" β€” three distinct two-grams. You are given a string s consisting of n capital Latin letters. Your task is to find any two-gram contained in the given string as a substring (i.e. two consecutive characters of ...
3
input() s = input() d = {} for i in range(len(s) - 1): ss = s[i:i+2] if d.get(ss) == None: d[ss] = 1 else: d[ss] += 1 maxV = 0 maxK = '' for key, value in d.items(): if value > maxV: maxV = value maxK = key print(maxK)
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
m1 = 0 m2 = 0 mi1 = 1000000 mi2 = 1000000 n = int(input()) z = input().split() for y in z: x = int(y) if (x >= m1): m2 = m1 m1 = x elif (x > m2): m2 = x if (x <= mi1): mi2 = mi1 mi1 = x elif (x < mi2): mi2 = x if m2 == 0: m2 = m1 if mi2 == 0: ...
The HR manager was disappointed again. The last applicant failed the interview the same way as 24 previous ones. "Do I give such a hard task?" β€” the HR manager thought. "Just raise number 5 to the power of n and get last two digits of the number. Yes, of course, n can be rather big, and one cannot find the power using ...
3
# Again twenty five n = int(input()) print(25)
Vova had a pretty weird sleeping schedule. There are h hours in a day. Vova will sleep exactly n times. The i-th time he will sleep exactly after a_i hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is 0). Each time Vova sleeps exactly one day (in...
3
from heapq import heappush,heappop,heapify from collections import deque,defaultdict,Counter from itertools import permutations,combinations,groupby import functools import sys import bisect import string import math import time import random def Golf():*a,=map(int,open(0)) def I():return int(input()) def S_():return ...
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
def solve(): n = int(input()) array = list(map(int, input().split())) if n % 2 == 1: final = n // 2 + 1 else: final = n // 2 if array[final - 1] == array[final]: array[final] -= 1 for i in range(final): if array[i] < i or array[n - 1 - i] < i: ...
When preparing a tournament, Codeforces coordinators try treir best to make the first problem as easy as possible. This time the coordinator had chosen some problem and asked n people about their opinions. Each person answered whether this problem is easy or hard. If at least one of these n people has answered that th...
3
from collections import Counter n=int(input()) a=input().split() b=Counter(a) if(b['1']>=1): print('HARD') else: print('EASY')
ZS the Coder and Chris the Baboon are travelling to Udayland! To get there, they have to get on the special IOI bus. The IOI bus has n rows of seats. There are 4 seats in each row, and the seats are separated into pairs by a walkway. When ZS and Chris came, some places in the bus was already occupied. ZS and Chris are...
3
rows=int(input()) flg=0 alist= [[seat for seat in input()] for i in range(rows)] for i in range(rows): if flg==0: for t in range(4): if 'O' in alist[i][t]: if 'O' in alist[i][t+1]: alist[i][t]='+' alist[i][t+1]='+' flg+=1 break if flg!=0...
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...
3
shoes = [int(i) for i in input().split()] count = {} total = 0 for i in shoes: if i not in count: count[i] = True else: total += 1 print(total)
Snuke built an online judge to hold a programming contest. When a program is submitted to the judge, the judge returns a verdict, which is a two-character string that appears in the string S as a contiguous substring. (The judge can return any two-character substring of S.) Determine whether the judge can return the ...
3
print("Yes" if "AC" in input() else "No")
You are a lover of bacteria. You want to raise some bacteria in a box. Initially, the box is empty. Each morning, you can put any number of bacteria into the box. And each night, every bacterium in the box will split into two bacteria. You hope to see exactly x bacteria in the box at some moment. What is the minimu...
3
x = int(input()) binary = bin(x)[2:] print(binary.count('1'))
After celebrating the midcourse the students of one of the faculties of the Berland State University decided to conduct a vote for the best photo. They published the photos in the social network and agreed on the rules to choose a winner: the photo which gets most likes wins. If multiple photoes get most likes, the win...
3
from collections import Counter n = int(input()) co = Counter() ma = 0 ans = 0 for x in map(int, input().split()): co[x] += 1 if co[x] > ma: ans = x ma = co[x] print(ans)
Wilbur the pig is tinkering with arrays again. He has the array a1, a2, ..., an initially consisting of n zeros. At one step, he can choose any index i and either add 1 to all elements ai, ai + 1, ... , an or subtract 1 from all elements ai, ai + 1, ..., an. His goal is to end up with the array b1, b2, ..., bn. Of co...
1
from collections import defaultdict n = int(raw_input()) l = [int(x) for x in raw_input().split()] ret = abs(l[0]) for i in xrange(1, n): ret += abs(l[i] - l[i-1]) print ret
A company has N members, who are assigned ID numbers 1, ..., N. Every member, except the member numbered 1, has exactly one immediate boss with a smaller ID number. When a person X is the immediate boss of a person Y, the person Y is said to be an immediate subordinate of the person X. You are given the information ...
3
n,*a=map(int,open(0).read().split()) b=[0]*n for i in a: b[i-1]+=1 print(*b, sep="\n")
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
# coding: utf-8 # In[ ]: # In[21]: x = int(input()) c = 0 while(x > 5): x = x - 5 c = c + 1 c = c + 1 print(c) # In[ ]:
Given is a string S of length N-1. Each character in S is `<` or `>`. A sequence of N non-negative integers, a_1,a_2,\cdots,a_N, is said to be good when the following condition is satisfied for all i (1 \leq i \leq N-1): * If S_i= `<`: a_i<a_{i+1} * If S_i= `>`: a_i>a_{i+1} Find the minimum possible sum of the ele...
3
s = input() A = [0] * (len(s) + 1) for i, c in enumerate(s): if c == '<': A[i+1] = A[i] + 1 for i, c in enumerate(s[::-1]): if c == '>': x = len(s) - i A[x-1] = max(A[x-1], A[x] + 1) print(sum(A))
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
A=input () if (int(A)%2)==0 and int(A)!=2: print('Yes') else: print('NO')
There are n dormitories in Berland State University, they are numbered with integers from 1 to n. Each dormitory consists of rooms, there are a_i rooms in i-th dormitory. The rooms in i-th dormitory are numbered from 1 to a_i. A postman delivers letters. Sometimes there is no specific dormitory and room number in it o...
3
n, m = [int(i) for i in input().strip().split()] a = [int(i) for i in input().strip().split()] b = [int(i) for i in input().strip().split()] prefix = 0 prefix_sum = [0] for num in a: prefix += num prefix_sum.append(prefix) f_index = 1 for num in b: while num > prefix_sum[f_index]: f_index += 1 ...
You are given an array A of length N. Your task is to divide it into several contiguous subarrays. Here, all subarrays obtained must be sorted in either non-decreasing or non-increasing order. At least how many subarrays do you need to divide A into? Constraints * 1 \leq N \leq 10^5 * 1 \leq A_i \leq 10^9 * Each A_i ...
3
n=int(input()) l=list(map(int,input().split())) if n<=2:print(1);exit() ans=1 chk=0 left=0 while chk<n-2: if (l[left]-l[chk+1])*(l[chk+1]-l[chk+2])<0:ans+=1;chk+=2;left=chk else:chk+=1 print(ans)
You are given 4n sticks, the length of the i-th stick is a_i. You have to create n rectangles, each rectangle will consist of exactly 4 sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only...
3
q = int(input()) for _ in range(q): n = int(input()) a = list(map(int,input().split())) a.sort() k=a[-1]*a[0] while a!=[]: if a[-1]==a[-2] and a[0]==a[1]: t=a[-1]*a[0] if k==t: a.pop(-1) a.pop(-1) a.pop(0) ...
A student of z-school found a kind of sorting called z-sort. The array a with n elements are z-sorted if two conditions hold: 1. ai β‰₯ ai - 1 for all even i, 2. ai ≀ ai - 1 for all odd i > 1. For example the arrays [1,2,1,2] and [1,1,1,1] are z-sorted while the array [1,2,3,4] isn’t z-sorted. Can you make the...
3
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jun 30 11:36:12 2020 @author: shailesh """ n = int(input()) a = [int(i) for i in input().split()] a.sort() even_positions = a[(n+1)//2:] odd_positions = a[:(n+1)//2] l = [] for i in range(len(even_positions)): l.append(str(odd_positions[0]))...
Recently you have bought a snow walking robot and brought it home. Suppose your home is a cell (0, 0) on an infinite grid. You also have the sequence of instructions of this robot. It is written as the string s consisting of characters 'L', 'R', 'U' and 'D'. If the robot is in the cell (x, y) right now, he can move to...
3
q = int(input()) while q: s = input() m = {} m['D'] = 0 m['U'] = 0 m['L'] = 0 m['R'] = 0 for i in s: m[i] += 1 k = min(m['D'], m['U']) m['D'] = k m['U'] = k k1 = min(m['L'], m['R']) m['L'] = k1 m['R'] = k1 if m['D'] == 0: m['L'] = min(1, m['L']) ...
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it [here](http://tiny.cc/636xmz). The picture showing the correct sudoku solution: <image> Blocks are bordered with bold black color. Your task is to change at most 9 elements of this field (i.e. choose s...
3
import math from collections import Counter for _ in range(int(input())): # n = int(input()) a = [] for i in range(9): a.append(list(input())) l = [(0,0),(1,3),(2,6),(3,1),(4,4),(5,7),(6,2),(7,5),(8,8)] for i,j in l: a[i][j] = str(int(a[i][j]) + 1) if a[i][j]!='9' else '1' for 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
## 256 , 32 k2, k3, k5 ,k6 = map(int , input().split()) tmp = min((k5,k6,k2)) k2-=tmp tmp1 = min((k2,k3)) print(tmp*256 + tmp1*32)
You are given an array of n integers a_1,a_2,...,a_n. You have to create an array of n integers b_1,b_2,...,b_n such that: * The array b is a rearrangement of the array a, that is, it contains the same values and each value appears the same number of times in the two arrays. In other words, the multisets \\{a_1,a_...
3
t = int(input()) for i in range(t): n = int(input()) lst = [int(s) for s in input().split()] lst_sorted = sorted(lst) if sum(lst) == 0: print('NO') else: if sum(lst_sorted) > 0: lst_sorted.reverse() print('YES') print(*lst_sorted)
You are given a text of single-space separated words, consisting of small and capital Latin letters. Volume of the word is number of capital letters in the word. Volume of the text is maximum volume of all words in the text. Calculate the volume of the given text. Input The first line contains one integer number n ...
3
n = int(input()) t = input().split() ans = 0 for w in t: m = sum(1 for c in w if('A' <= c <= 'Z')) ans = max(ans,m) print(ans)
There are n incoming messages for Vasya. The i-th message is going to be received after ti minutes. Each message has a cost, which equals to A initially. After being received, the cost of a message decreases by B each minute (it can become negative). Vasya can read any message after receiving it at any moment of time. ...
3
#!/usr/bin/env python3 from sys import stdin, stdout def rint(): return map(int, stdin.readline().split()) #lines = stdin.readlines() n, A, B, C, T = rint() t = list(rint()) D = C - B if D < 0: print(n*A) else: sum = A*n for i in range(n): sum += D*(T-t[i]) print(sum)
A mischievous notice has arrived from the primitive slow-life organization "Akaruda". Akaruda is famous for mischief such as throwing a pie at the face of a VIP, but recently it has become more radical, such as using gunpowder to sprinkle rat fireworks at the reception venue. The notice is the following text. --- Per...
3
# -*- coding: utf-8 -*- """ http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0135 WA """ import sys from sys import stdin from math import sqrt, acos, cos, sin, radians, degrees input = stdin.readline def solve(time): # 12????????????90??? short_hand_angle = time[1] * -6 + 90 x_s = cos(radians(sho...
Polycarp has built his own web service. Being a modern web service it includes login feature. And that always implies password security problems. Polycarp decided to store the hash of the password, generated by the following algorithm: 1. take the password p, consisting of lowercase Latin letters, and shuffle the l...
3
t=int(input()) for kisuna in range(t): p=sorted(input()) h=input() ans='NO' for i in range(len(h)-len(p)+1): x=sorted(h[i:i+len(p)]) if x==p: ans='YES' break print(ans)
You are given an array consisting of n integers a_1, a_2, ..., a_n. Initially a_x = 1, all other elements are equal to 0. You have to perform m operations. During the i-th operation, you choose two indices c and d such that l_i ≀ c, d ≀ r_i, and swap a_c and a_d. Calculate the number of indices k such that it is poss...
3
for i in range(int(input())): n,x,m=[int(k) for k in input().split()] anshigh=None for i in range(m): l,r=[int(k) for k in input().split()] if not anshigh: if l<=x and x<=r: anslow=l anshigh=r else: if l<anslow and r>=anslow: ...
Step up and down Kazuki, commonly known as Kerr, who attends JAG University, was invited by your friend this summer to participate in the ICPC (International Collegiate Potchari Contest). ICPC is a sports contest and requires a high degree of athletic ability. However, Mr. Kerr was always in front of the computer, and...
3
while True: c = 0 ans = 0 a = int(input()) left = 0 right = 0 if a == 0: break b = input() b = b.split(" ") for i in b: if i == "lu": left = 1 elif i == "ru": right = 1 elif i == "rd": right = 0 elif i == "ld...
You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft k torches. One torch can be crafted using one stick and one coal. Hopefully, you've met a very handsome wandering trader who has two trade offers: * exchange 1 stick for x sticks (you lose 1 stick and gain x sticks...
3
from sys import stdin, stdout def gmi(): return map(int, stdin.readline().strip().split()) def gms(): return map(str, stdin.readline().strip().split()) def gari(): return list(map(int, stdin.readline().strip().split())) def gars(): return list(map(int, stdin.readline().strip().split())) def gs(): return stdin.readline(...
Tattah is asleep if and only if Tattah is attending a lecture. This is a well-known formula among Tattah's colleagues. On a Wednesday afternoon, Tattah was attending Professor HH's lecture. At 12:21, right before falling asleep, he was staring at the digital watch around Saher's wrist. He noticed that the digits on th...
3
h, m = input().split(':') res = h[::-1] if res < '60' and m < res: print(h, res, sep=':') else: res = '60' while not res < '60': h_int = (int(h) + 1) % 24 h = ('0' if h_int < 10 else '') + str(h_int) res = h[::-1] print(h, res, sep=':')
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()) s=[int(a) for a in input().split()] s.sort() dif=s[-1]-s[0] if s.count(s[0])==n: way=int((n-1)*n/2) print(dif,way) else: first=s.count(s[0]) last=s.count(s[-1]) way=first*last print(dif,way)
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 _ in range(int(input())): x = int(input()) arr=[0]*(x+1) lst = list(map(int,input().split())) for item in lst: arr[item]+=1 k = max(arr) p = x+1-arr.count(0) l1 = min(k-1,p) l2 = min(k,p-1) print(max(l1,l2))
Two bored soldiers are playing card war. Their card deck consists of exactly n cards, numbered from 1 to n, all values are different. They divide cards between them in some manner, it's possible that they have different number of cards. Then they play a "war"-like card game. The rules are following. On each turn a fi...
1
r = lambda: map(int, raw_input().split()) n = input() a = r()[1:] b = r()[1:] loop = 0 while True: if loop >= 1000: print -1 break loop += 1 x, y = a.pop(0), b.pop(0) if x > y: a += [y, x] else: b += [x, y] if not a or not b: print loop, print 1 if not b else 2 ...
Duff is in love with lovely numbers! A positive integer x is called lovely if and only if there is no such positive integer a > 1 such that a2 is a divisor of x. <image> Malek has a number store! In his store, he has only divisors of positive integer n (and he has all of them). As a birthday present, Malek wants to g...
1
def prime_factors(n): i = 2 factors = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(i) if n > 1: factors.append(n) return factors n = input() s = prime_factors(n) s = set(s) ans = 1 for i in s: ans*=i print ans
Problem : The Starks(S),Lannisters(L) and the Baratheons(B) are fighting for the Iron Throne. These three houses are fighting from ages to capture the throne. The N th battle goes on for N days before a winner emerges. Interestingly,the battles follow a pattern. If the battle number N is divisible by 3 it is fought...
1
import math tc=int(input()) while tc>0: D=int(input()) n=(math.sqrt(1+8*D)-1) / 2 if math.modf(n)[0]>0: k=int(n+1) else: k=int(n) if k%3==0: print "SL" if k%3==1: print "LB" if k%3==2: print "BS" tc=tc-1
Friends are going to play console. They have two joysticks and only one charger for them. Initially first joystick is charged at a1 percent and second one is charged at a2 percent. You can connect charger to a joystick only at the beginning of each minute. In one minute joystick either discharges by 2 percent (if not c...
3
a, b = map(int, input().split()) counter = 0 if a<=2 and b<=2: if a == 2: counter = 1 if b == 2: counter = 1 else: while a > 0 and b > 0: if a > b: b += 1 a += -2 counter += 1 else: a += 1 b += -2 counter += 1 print(counter)
Arkady decides to observe a river for n consecutive days. The river's water level on each day is equal to some real value. Arkady goes to the riverside each day and makes a mark on the side of the channel at the height of the water level, but if it coincides with a mark made before, no new mark is created. The water d...
3
#include <GOD> #Pato Boride Azin Khone , Vase Hamine Delet Khune import sys import math n = int(input()) arr = [int(i) for i in input().split()] tt = [0]*n for i in range(n): if(i != 0): tt[i]=max(tt[i-1] , arr[i]+1) else: tt[i]=arr[i]+1 ss = 0 for i in range(n-1 , -1 , -1): if(i != n-1...
Let LCM(x, y) be the minimum positive integer that is divisible by both x and y. For example, LCM(13, 37) = 481, LCM(9, 6) = 18. You are given two integers l and r. Find two integers x and y such that l ≀ x < y ≀ r and l ≀ LCM(x, y) ≀ r. Input The first line contains one integer t (1 ≀ t ≀ 10000) β€” the number of tes...
3
t = int(input()) for i in range(t): l, r = list(map(int, input().split())) if 2*l>r: print(-1, -1) else: print(l, 2*l)
You are given a range of positive integers from l to r. Find such a pair of integers (x, y) that l ≀ x, y ≀ r, x β‰  y and x divides y. If there are multiple answers, print any of them. You are also asked to answer T independent queries. Input The first line contains a single integer T (1 ≀ T ≀ 1000) β€” the number of...
3
R = lambda: map(int, input().split()) t = int(input()) while t > 0: t = t-1 l,r = R() if l == 1: print(l,r) else: for i in range(l,r): if i*2 <= r: print(i,i*2) break
The statement of this problem is the same as the statement of problem C1. The only difference is that, in problem C1, n is always even, and in C2, n is always odd. You are given a regular polygon with 2 β‹… n vertices (it's convex and has equal sides and equal angles) and all its sides have length 1. Let's name it as 2n...
3
import math for _ in range(int(input())): n = int(input()) print(1 / (2 * math.sin(math.pi / (4 * n))))
This is a harder version of the problem. In this version n ≀ 500 000 The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the compan...
3
import sys reader = (line.rstrip() for line in sys.stdin) input = reader.__next__ n = int(input()) m = list(map(int, input().split())) smaller_left = [-1] * n stack = [] for i in reversed(range(n)): val = m[i] while stack and val < stack[-1][0]: _, j = stack.pop() smaller_left[j] = i s...
Takahashi became a pastry chef and opened a shop La Confiserie d'ABC to celebrate AtCoder Beginner Contest 100. The shop sells N kinds of cakes. Each kind of cake has three parameters "beauty", "tastiness" and "popularity". The i-th kind of cake has the beauty of x_i, the tastiness of y_i and the popularity of z_i. Th...
3
import itertools n, m = map(int, input().split()) pice = [] for _ in range(n): x, y, z = map(int, input().split()) pice.append((x, y, z)) ans = 0 for i, j, k in itertools.product((-1, 1), repeat=3): a = [x * i + y * j + z * k for (x, y, z) in pice] a.sort() ans = max(ans, abs(sum(a[0:m]))) print(an...
You have a positive integer m and a non-negative integer s. Your task is to find the smallest and the largest of the numbers that have length m and sum of digits s. The required numbers should be non-negative integers written in the decimal base without leading zeroes. Input The single line of the input contains a pa...
1
# -*- coding: utf-8 -*- #α••β”Œβ—•α—œβ—•β”α•— HELLO HELLO HELLO α••β”Œβ—•α—œβ—•β”α•— m,s = tuple(int(i) for i in raw_input().strip().split(" ")) if s == 0 or s > 9 * m: if m == 1 and s == 0: print 0, 0 else: print -1, -1 else: d = [0 for i in range(m)] s -= 1 d[0] = 1 e = d[:] i = 0 j = m-1 w...
Kenkoooo is planning a trip in Republic of Snuke. In this country, there are n cities and m trains running. The cities are numbered 1 through n, and the i-th train connects City u_i and v_i bidirectionally. Any city can be reached from any city by changing trains. Two currencies are used in the country: yen and snuuk....
3
from heapq import heappop, heappush def dijkstra(costs, s, i): q = [(0, s)] while q: c, v = heappop(q) if costs[v] >= 0: continue costs[v] = c for link in links[v]: u = link[0] if costs[u] == -1: heappush(q, (c + link[i], u)...
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,k = map(int,input().split()) a=input() print((n+k-3)//(k-1))
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 = map(int,input().split()) print((n*2)//k + (n*5)//k + (n*8)//k + bool((n*2)/k-(n*2)//k) + bool((n*5)/k-(n*5)//k) + bool((n*8)/k-(n*8)//k))
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
for i in range(int(input())): x = int(input()) l = list(map(int , input().split())) e = 0 for j in l: if j%2 == 0: e+=1 if e == x or (x%2 == 0 and e == 0 ): print("NO") else: print("YES")