problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
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
sheet = [2, 5, 8] n, k = map(int, input().split()) sheet[0]*=n; sheet[1]*=n; sheet[2]*=n; sum = 0 if sheet[0]%k==0: sum+=sheet[0]//k else: sum+=sheet[0]//k+1 if sheet[1]%k==0: sum+=sheet[1]//k else: sum+=sheet[1]//k+1 if sheet[2]%k==0: sum+=sheet[2]//k else: sum+=sheet[2]//k+1 print(sum)
You are given two integers a and b. Print a+b. Input The first line contains an integer t (1 ≀ t ≀ 10^4) β€” the number of test cases in the input. Then t test cases follow. Each test case is given as a line of two integers a and b (-1000 ≀ a, b ≀ 1000). Output Print t integers β€” the required numbers a+b. Example ...
3
a=int(input()) for i in range(a): n,m=list(map(int,input().split())) print(n+m)
Nezzar's favorite digit among 1,…,9 is d. He calls a positive integer lucky if d occurs at least once in its decimal representation. Given q integers a_1,a_2,…,a_q, for each 1 ≀ i ≀ q Nezzar would like to know if a_i can be equal to a sum of several (one or more) lucky numbers. Input The first line contains a singl...
3
for _ in range(int(input())): n,d=map(int,input().split()) q=list(map(int,input().split())) for i in range(n): p=q[i] am="NO" for i in range(1,10): if p>=d*i and (p-d*i)%10==0: am="YES" if p<10*d: print(am) else: pri...
You are given a string s of even length n. String s is binary, in other words, consists only of 0's and 1's. String s has exactly n/2 zeroes and n/2 ones (n is even). In one operation you can reverse any substring of s. A substring of a string is a contiguous subsequence of that string. What is the minimum number of...
3
for _ in range(int(input())): n = int(input()) s = input() one, non = 0, 0 for i in range(len(s) - 1): if(s[i] == s[i + 1]): if(s[i] == '1'): one += 1 else : non += 1 print(max(one, non))
You are given three positive integers n, a and b. You have to construct a string s of length n consisting of lowercase Latin letters such that each substring of length a has exactly b distinct letters. It is guaranteed that the answer exists. You have to answer t independent test cases. Recall that the substring s[l ...
3
import string alpha = string.ascii_lowercase t = int(input()) for _ in range(t): n, a, b = [int(x) for x in input().split()] pointer = 0 s = "" while len(s) < n: s += alpha[pointer % b] pointer += 1 print(s)
Many computer strategy games require building cities, recruiting army, conquering tribes, collecting resources. Sometimes it leads to interesting problems. Let's suppose that your task is to build a square city. The world map uses the Cartesian coordinates. The sides of the city should be parallel to coordinate axes....
3
n = int(input()) x, y = (int(x) for x in input().split()) x1, y1, x2, y2 = x, y, x, y for i in range(n - 1): x, y = (int(x) for x in input().split()) x1 = min(x1, x) x2 = max(x2, x) y1 = min(y1, y) y2 = max(y2, y) print(max(x2 - x1, y2 - y1) ** 2)
Takahashi had a pair of two positive integers not exceeding N, (a,b), which he has forgotten. He remembers that the remainder of a divided by b was greater than or equal to K. Find the number of possible pairs that he may have had. Constraints * 1 \leq N \leq 10^5 * 0 \leq K \leq N-1 * All input values are integers. ...
3
N,K=map(int,input().split()) res=0 for b in range(1,N+1): if(b<=K): continue res+=(N//b)*(b-K) if(K!=0): res+=max(0,N%b-(K-1)) else: res+=N%b print(res)
You are given two integers n and m (m < n). Consider a convex regular polygon of n vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length). <image> Examples of convex regular polygons Your task is to say if it is poss...
3
c = int(input()) for i in range(c): n, m = map(int, input().split()) if n % m == 0: print('YES') else: print('NO')
Among Johnny's numerous hobbies, there are two seemingly harmless ones: applying bitwise operations and sneaking into his dad's office. As it is usually the case with small children, Johnny is unaware that combining these two activities can get him in a lot of trouble. There is a set S containing very important number...
3
t = 1 t = int(input()) for _ in range(t): n = int(input()) a= list(map(int, input().split())) ans = float('inf') for i in range(1,1024): l=[] for j in a: l.append(i^j) if set(l)==set(a): ans = i break if ans == float('inf'): print(-1) else: print(ans)
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
#CODE FESTIVAL 2017 qual C a s=input() if "AC" in s: print("Yes") else: print("No")
Orac is studying number theory, and he is interested in the properties of divisors. For two positive integers a and b, a is a divisor of b if and only if there exists an integer c, such that aβ‹… c=b. For n β‰₯ 2, we will denote as f(n) the smallest positive divisor of n, except 1. For example, f(7)=7,f(10)=2,f(35)=5. ...
3
for _ in range(int(input())): n,m = input().split() n,m = int(n), int(m) #print(n,m) r=0 def ge(a: int): for i in range(2,int(a//2) +1): #print(i,a) if a%i==0: return i return a j=1 while j<2: r= ge(n) +n ...
Given is an integer N. Find the minimum possible positive integer k such that (1+2+\cdots+k) is a multiple of N. It can be proved that such a positive integer k always exists. Constraints * 1 \leq N \leq 10^{15} * All values in input are integers. Input Input is given from Standard Input in the following format: ...
3
from itertools import product def main(): n = int(input()) n_copy = n if n == 1: print(1) exit() if n % 2 == 0: ans = 2 * n - 1 n *= 2 else: ans = n - 1 factors = [] for p in range(2, n): if p * p > n: if n > 1: ...
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 = input() if int(w) == 2: print("NO") elif int(w)%2 == 0: print("YES") else: print("NO")
Misha and Vanya have played several table tennis sets. Each set consists of several serves, each serve is won by one of the players, he receives one point and the loser receives nothing. Once one of the players scores exactly k points, the score is reset and a new set begins. Across all the sets Misha scored a points ...
3
k, a, b = map(int, input().split()) mx_a = a // k mx_b = b // k if mx_a == 0 and b % k != 0: print(-1) elif mx_b == 0 and a % k != 0: print(-1) else: print(mx_a + mx_b)
Karen is getting ready for a new school day! <image> It is currently hh:mm, given in a 24-hour format. As you know, Karen loves palindromes, and she believes that it is good luck to wake up when the time is a palindrome. What is the minimum number of minutes she should sleep, such that, when she wakes up, the time i...
3
##n = int(input()) ##a = list(map(int, input().split())) ##print(' '.join(map(str, res))) def list_input(): return list(map(int, input().split())) s = list(map(int, input().split(':'))) y = s[0]*60+s[1] for x in range(0, 1440): z = x+y if z >= 1440: z -= 1440 hh = z//60 mm = z%60 hs = s...
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 = list(map(int,input().split())) A = [list(map(int,input().split())) for i in range(n)] B = [map(int,input().split()) for i in range(m)] B_T = list(map(list, zip(*B))) for a in A: row = [] for b in B_T: row.append(sum([x*y for (x,y) in zip(a,b)])) print(' '.join(map(str,row)))
Kolya is very absent-minded. Today his math teacher asked him to solve a simple problem with the equation a + 1 = b with positive integers a and b, but Kolya forgot the numbers a and b. He does, however, remember that the first (leftmost) digit of a was d_a, and the first (leftmost) digit of b was d_b. Can you reconst...
3
a, b = list(map(int, input().split())) if b - a > 1: print(-1) elif a == 9 and b == 1: print(99, 100) elif a > b: print(-1) else: if a == b: print(a * 10 + 1, b * 10 + 2) elif a + 1 == b: print(a, b) elif a == 9 and b == 1: print(99, 100)
Student Valera is an undergraduate student at the University. His end of term exams are approaching and he is to pass exactly n exams. Valera is a smart guy, so he will be able to pass any exam he takes on his first try. Besides, he can take several exams on one day, and in any order. According to the schedule, a stud...
1
N = int(raw_input()) exams = [] for n in range(N): a,b = map(int, raw_input().split()) exams.append((a,b)) exams.sort() cur = 0 for n in range(N): if exams[n][1] >= cur: cur = exams[n][1] else: cur = exams[n][0] print cur
The city park of IT City contains n east to west paths and n north to south paths. Each east to west path crosses each north to south path, so there are n2 intersections. The city funded purchase of five benches. To make it seems that there are many benches it was decided to place them on as many paths as possible. Ob...
3
n = int(input()) a = int(n*(n-1)*(n-2)*(n-3)*(n-4)/120*n*(n-1)*(n-2)*(n-3)*(n-4)/120) print(int(a*120))
The length of the longest common prefix of two strings s = s_1 s_2 … s_n and t = t_1 t_2 … t_m is defined as the maximum integer k (0 ≀ k ≀ min(n,m)) such that s_1 s_2 … s_k equals t_1 t_2 … t_k. Koa the Koala initially has n+1 strings s_1, s_2, ..., s_{n+1}. For each i (1 ≀ i ≀ n) she calculated a_i β€” the length of ...
3
inp = lambda: map(int, input().split(" ")) t, = inp() for _ in range(t): n, = inp() a = list(inp()) res = [] str1 = "a"*51 print(str1) for i in a: str1 = list(str1) str1[i] = "b" if str1[i] == "a" else "a" print("".join(str1))
You are given strings s and t, consisting of lowercase English letters. You will create a string s' by freely rearranging the characters in s. You will also create a string t' by freely rearranging the characters in t. Determine whether it is possible to satisfy s' < t' for the lexicographic order. Constraints * The ...
3
i,s=input,sorted;print(["No","Yes"]["".join(s(i()))<"".join(s(i()))[::-1]])
Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you? You are given a system of equations: <image> You should count, how many there are pai...
1
n,m=map(int,raw_input().split()) cnt=0 for a in range(1001): for b in range(1001): if(a*a+b==n) and a+b*b==m: cnt+=1 print cnt
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 = input() if int(w) == 2: print("NO") elif (int(w) % 2) == 0: print("YES") else: print("NO")
Little Petya often travels to his grandmother in the countryside. The grandmother has a large garden, which can be represented as a rectangle 1 Γ— n in size, when viewed from above. This rectangle is divided into n equal square sections. The garden is very unusual as each of the square sections possesses its own fixed h...
3
x=int(input()) y=list(map(int,input().split(" "))) st=[] counter=1 for i in range(len(y)): j=i+1 k=i-1 while(j<=len(y)-1 and y[j]<=y[j-1]): counter+=1 j+=1 while(k>=0 and y[k]<=y[k+1]): counter+=1 k-=1 st.append(counter) counter=1 print(max(x f...
You are given two sequences a_1, a_2, ..., a_n and b_1, b_2, ..., b_n. Each element of both sequences is either 0, 1 or 2. The number of elements 0, 1, 2 in the sequence a is x_1, y_1, z_1 respectively, and the number of elements 0, 1, 2 in the sequence b is x_2, y_2, z_2 respectively. You can rearrange the elements i...
3
#import sys #sys.stdin=open("test.in","r") t=int(input()) def solve(): a=[int(i) for i in input().split()] b=[int(i) for i in input().split()] ans=0 ans+=2*(min(a[2],b[1])) k=min(a[2],b[1]) b[1]=max(b[1]-k,0) a[2]=max(a[2]-k,0) if b[0]+b[1]>=a[1]: print(ans) else: ans...
Many internet protocols these days include the option of associating a media type with the content being sent. The type is usually inferred from the file extension. You are to write a program that facilitates the lookup of media types for a number of files. You will be given a table of media type associations that asso...
1
import sys filetypes={} (inptypes,noofinps) = map(int,sys.stdin.readline().split()) for z in range(inptypes): data = sys.stdin.readline().split() filetypes[data[0]] = data[1] data.sort(reverse=True) for z in range(noofinps): data = sys.stdin.readline().split()[0].split('.') try: if len(data...
Given a set of integers (it can contain equal elements). You have to split it into two subsets A and B (both of them can contain equal elements or be empty). You have to maximize the value of mex(A)+mex(B). Here mex of a set denotes the smallest non-negative integer that doesn't exist in the set. For example: * m...
3
t=int(input()) for ttt in range(t): n=int(input()) f=list(map(int, input().split())) d={} max=0 for i in range(len(f)): if f[i] not in d.keys(): d[f[i]]=0 d[f[i]]+=1 if f[i]>max: max=f[i] k=0 q=0 for i in range(max+2): if i not in d.keys() or d[i]==0: k+=(i*(2-q)) break elif d[i]==1: if...
You are given an array a consisting of n integers a_1, a_2, ... , a_n. In one operation you can choose two elements of the array and replace them with the element equal to their sum (it does not matter where you insert the new element). For example, from the array [2, 1, 4] you can obtain the following arrays: [3, 4],...
1
t = int(raw_input()) for i in xrange(t): n = int(raw_input()) a = map(int, raw_input().split()) mod3 = [0, 0, 0] for e in a: mod3[e % 3] += 1 res = min(mod3[1], mod3[2]) mod3[1] -= res mod3[2] -= res res += mod3[1] / 3 + mod3[2] / 3 + mod3[0] print res
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya loves tickets very much. As we know, each ticket has a number that is a positive integer. It...
3
input() s = input() print('NO' if (any(i not in '47' for i in s)) | (sum(map(int, s[:len(s)//2])) != sum(map(int, s[len(s)//2:]))) else 'YES')
After playing Neo in the legendary "Matrix" trilogy, Keanu Reeves started doubting himself: maybe we really live in virtual reality? To find if this is true, he needs to solve the following problem. Let's call a string consisting of only zeroes and ones good if it contains different numbers of zeroes and ones. For exa...
3
n=int(input()) s=input() count_1 = 0 count_0 = 0 for ch in s: if ch=='0': count_0 += 1 else: count_1 += 1 if count_0 != count_1: print(1) print(s) else: print(2) print(s[0],s[1:])
Karen is getting ready for a new school day! <image> It is currently hh:mm, given in a 24-hour format. As you know, Karen loves palindromes, and she believes that it is good luck to wake up when the time is a palindrome. What is the minimum number of minutes she should sleep, such that, when she wakes up, the time i...
3
s = input() h, m = map(int, s.split(':')) for i in range(60 * 24): hh = ('0' + str(h)) if h < 10 else str(h) mm = ('0' + str(m)) if m < 10 else str(m) if hh[::-1] == mm: print(i) break if m < 59: m += 1 else: h = (h+1) % 24 m = 0
You are given a rectangular board of M Γ— N squares. Also you are given an unlimited number of standard domino pieces of 2 Γ— 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions: 1. Each domino completely covers two squa...
3
m,n=map(int,input().strip().split()) x=m*n print(x//2)
You are given an array A, consisting of n positive integers a_1, a_2, ..., a_n, and an array B, consisting of m positive integers b_1, b_2, ..., b_m. Choose some element a of A and some element b of B such that a+b doesn't belong to A and doesn't belong to B. For example, if A = [2, 1, 7] and B = [1, 3, 4], we can ...
3
# ANSHUL GAUTAM # IIIT-D from math import * from copy import * from string import * # alpha = ascii_lowercase from random import * from sys import stdin from sys import maxsize from operator import * # d = sorted(d.items(), key=itemgetter(1)) from itertools import * from collections import Counter # d = dict(Co...
There are N rabbits on a number line. The rabbits are conveniently numbered 1 through N. The coordinate of the initial position of rabbit i is x_i. The rabbits will now take exercise on the number line, by performing sets described below. A set consists of M jumps. The j-th jump of a set is performed by rabbit a_j (2≀...
1
from math import log n = int(raw_input()) x = map(int, raw_input().split()) m, k = map(int, raw_input().split()) a = map(lambda x:int(x) - 2, raw_input().split()) logk = log(k, 2) dy = [x[i + 1] - x[i] for i in xrange(n - 1)] swap = [range(n - 1) for _ in xrange(int(logk + 1))] for i in xrange(m): swap[0][a[i]],...
You are given two segments [l_1; r_1] and [l_2; r_2] on the x-axis. It is guaranteed that l_1 < r_1 and l_2 < r_2. Segments may intersect, overlap or even coincide with each other. <image> The example of two segments on the x-axis. Your problem is to find two integers a and b such that l_1 ≀ a ≀ r_1, l_2 ≀ b ≀ r_2 an...
3
# -*- coding: utf-8 -*- # @Date : 2019-01-23 20:20:26 # @Author : raj lath (oorja.halt@gmail.com) # @Link : link # @Version : 1.0.0 from sys import stdin max_val=int(10e12) min_val=int(-10e12) def read_int() : return int(stdin.readline()) def read_ints() : return [int(x) for x in stdin.readline().spli...
Top-model Izabella participates in the competition. She wants to impress judges and show her mathematical skills. Her problem is following: for given string, consisting of only 0 and 1, tell if it's possible to remove some digits in such a way, that remaining number is a representation of some positive integer, divisi...
3
#!/usr/bin/env python3 from sys import stdin, stdout def rint(): return map(int, stdin.readline().split()) #lines = stdin.readlines() a = input() found1 = 0 count0 = 0 for aa in a: if found1 == 0: if aa == '1': found1 = 1 continue else: if aa == '0': count...
We have a string S consisting of uppercase English letters. Additionally, an integer N will be given. Shift each character of S by N in alphabetical order (see below), and print the resulting string. We assume that `A` follows `Z`. For example, shifting `A` by 2 results in `C` (`A` \to `B` \to `C`), and shifting `Y` ...
3
N=int(input()) S=input() S="".join(chr(65+(ord(s)-65+N)%26) for s in S) print(S)
A and B are preparing themselves for programming contests. An important part of preparing for a competition is sharing programming knowledge from the experienced members to those who are just beginning to deal with the contests. Therefore, during the next team training A decided to make teams so that newbies are solvi...
1
s = raw_input().split(" ") n = int(s[0]) m = int(s[1]) qts = 0 while (n >= 1 and m > 1) or (n > 1 and m >= 1): if n > m: n -= 2 m -= 1 qts += 1 else : m -= 2 n -= 1 qts += 1 print qts
Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of length k have the same sum. A subarray of an array is any sequence of consecutive elements. Phoenix currently has an array a of length n. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautifu...
3
import sys,os.path if __name__ == '__main__': if(os.path.exists('input.txt')): sys.stdin = open("input.txt","r") sys.stdout = open("output.txt","w") for _ in range(int(input())): n,k = map(int,input().split()) a = list(map(int,input().split())) s = set() for i in ...
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
from math import * readints = lambda: map(int, input().split(' ')) n=int(input()) a=list(readints()) x = max(max(a), int(ceil(sum(a)/(n-1)))) print(x)
Dwarfs have planted a very interesting plant, which is a triangle directed "upwards". This plant has an amusing feature. After one year a triangle plant directed "upwards" divides into four triangle plants: three of them will point "upwards" and one will point "downwards". After another year, each triangle plant divide...
3
n = int(input()) res = pow(2, n, 1000000007) print((res+1)*res//2 % 1000000007)
Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number a and Antisimon receives number b. They also have a heap of n stones. The players take turns to make a move and Simon starts. During a move a player should take from ...
3
# int(input()) # [int(s) for s in input().split()] # input() from math import gcd def solve(): a, b, n = [int(s) for s in input().split()] ans = 0 while n > 0: if ans == 0: n = n - gcd(n, a) else: n = n - gcd(n, b) ans = ans ^ 1 print(ans^1) if __name...
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types. * `0 p x`: a_p \gets a_p + x * `1 l r`: Print \sum_{i = l}^{r - 1}{a_i}. Constraints * 1 \leq N, Q \leq 500,000 * 0 \leq a_i, x \leq 10^9 * 0 \leq p < N * 0 \leq l_i < r_i \leq N * All values in Input are integer. I...
3
class BIT: def __init__(self, n): self.n = n self.data = [0] * n def sum(self, i): s = 0 while i > 0: s += self.data[i - 1] i &= i - 1 return s def update(self, i, x): while i < self.n: self.data[i] += x i |= i...
The only difference between easy and hard versions is constraints. You are given a sequence a consisting of n positive integers. Let's define a three blocks palindrome as the sequence, consisting of at most two distinct elements (let these elements are a and b, a can be equal b) and is as follows: [\underbrace{a, a, ...
1
import atexit, io, sys buffer = io.BytesIO() sys.stdout = buffer @atexit.register def write(): sys.__stdout__.write(buffer.getvalue()) maxVal = 205 for cs in range(int(raw_input())): n = int(raw_input()) a = map(int, raw_input().split()) cum = [ [0] * n for _ in range(maxVal)] for k in rang...
A flow network is a directed graph which has a $source$ and a $sink$. In a flow network, each edge $(u, v)$ has a capacity $c(u, v)$. Each edge receives a flow, but the amount of flow on the edge can not exceed the corresponding capacity. Find the maximum flow from the $source$ to the $sink$. Constraints * $2 \leq |V...
3
# Acceptance of input import sys file_input = sys.stdin V, E = map(int, file_input.readline().split()) adj_mat = [[0] * V for i in range(V)] for line in file_input: u, v, c = map(int, line.split()) adj_mat[u][v] = c # Dinic's algorithm import collections # BFS for residual capacity network to construct ...
Lolek and Bolek are about to travel abroad by plane. The local airport has a special "Choose Your Plane" offer. The offer's conditions are as follows: * it is up to a passenger to choose a plane to fly on; * if the chosen plane has x (x > 0) empty seats at the given moment, then the ticket for such a plane costs ...
1
from bisect import * NAME = "P2" try: inFile = open(NAME+".txt") except: pass def read(): try: return inFile.readline().strip() except: return raw_input().strip() n,m = map(int,read().split()) planes = map(int,read().split()) planes.sort() original = list(planes) high = 0 count = 0 wh...
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())): n=int(input()) l=list(map(int,input().split())) l1=[] for j in l: if(j%2!=0): l1.append(j) else: pass if(len(l1)==n and n%2!=0): print("YES") elif(len(l1)==n and n%2==0): print("NO") elif(len(l1)!=0 and len...
Little boy Valera studies an algorithm of sorting an integer array. After studying the theory, he went on to the practical tasks. As a result, he wrote a program that sorts an array of n integers a1, a2, ..., an in the non-decreasing order. The pseudocode of the program, written by Valera, is given below. The input of ...
1
n = input() if n <= 2: print -1 else: for i in range(n) : print n - i,
Write a program which prints multiplication tables in the following format: 1x1=1 1x2=2 . . 9x8=72 9x9=81 Input No input. Output 1x1=1 1x2=2 . . 9x8=72 9x9=81 Example Input Output
3
for i in range(1, 10): for j in range(1, 10): s = "{}x{}={}".format(i, j, i*j) print(s)
You're given an array a. You should repeat the following operation k times: find the minimum non-zero element in the array, print it, and then subtract it from all the non-zero elements of the array. If all the elements are 0s, just print 0. Input The first line contains integers n and k (1 ≀ n,k ≀ 10^5), the length ...
3
n,k=map(int,input().split()) l=list(map(int,input().split())) l=list(set(l)) l.sort() s=0 if len(l)<k: for i in range(len(l)): l[i]=abs(l[i]-s) print(l[i]) s+=l[i] for j in range(k-len(l)): print("0") else: for i in range(k): l[i]=l[i]-s print(l[i]) s+=l[i]
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()) a=list(map(int,input().split())) a.sort() output=0 for i in range(n): counter=0 for j in range(i,n): if a[j]-a[i]<=d: counter+=1 else: break output+=(counter-1)*2 print(output)
There are n products in the shop. The price of the i-th product is a_i. The owner of the shop wants to equalize the prices of all products. However, he wants to change prices smoothly. In fact, the owner of the shop can change the price of some product i in such a way that the difference between the old price of this ...
3
for _ in range(int(input())): n, k = [int(i) for i in input().split()] a = [int(i) for i in input().split()] maxi,mini = max(a),min(a) if mini+k>=maxi: print(mini+k) else: if mini+k>=maxi-k: print(mini+k) else: print(-1)
Input The only line of the input contains a 7-digit hexadecimal number. The first "digit" of the number is letter A, the rest of the "digits" are decimal digits 0-9. Output Output a single integer. Examples Input A278832 Output 0 Input A089956 Output 0 Input A089957 Output 1 Input A1440...
3
s = input() a = int(s[-1]) print(a%2)
Given are a sequence of N integers A_1, A_2, \ldots, A_N and a positive integer S. For a pair of integers (L, R) such that 1\leq L \leq R \leq N, let us define f(L, R) as follows: * f(L, R) is the number of sequences of integers (x_1, x_2, \ldots , x_k) such that L \leq x_1 < x_2 < \cdots < x_k \leq R and A_{x_1}+A_{...
3
# coding: utf-8 # Your code here! import sys sys.setrecursionlimit(10**6) readline = sys.stdin.readline read = sys.stdin.read n,s,*a = [int(i) for i in read().split()] MOD = 998244353 def mul(c,m,dp): #multiply (1-x^c) up to x^m for i in range(m,c-1,-1): dp[i] += dp[i-c] dp[i] %= MOD dp = [0]...
Naman has two binary strings s and t of length n (a binary string is a string which only consists of the characters "0" and "1"). He wants to convert s into t using the following operation as few times as possible. In one operation, he can choose any subsequence of s and rotate it clockwise once. For example, if s = ...
3
n = int(input()) a, b = input(), input() if sorted(a) != sorted(b): print(-1) exit(0) _00 = _01 = _10 = _11 = 0 for i in range(n): if a[i] == b[i]: continue if a[i] == '0': if _11 > 0: _11 -= 1 _10 += 1 elif _01 > 0: _01 -= 1 _00 +=...
Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first n. He writes down the followin...
3
import math k, n = [int(x) for x in input().split()] if n <= math.ceil(k/2): print(2*n - 1) else: n = n - math.ceil(k/2) print(2*n)
Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited n his friends there. If t...
3
n = int(input()) x = list(map(int,input().split())) ans = [0 for i in range(n)] i = 0 while i < n: ans[x[i]-1]=i+1 i+=1 [print(ans[z], end = ' ') for z in range(n)]
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution....
3
n=int(input()) mat = [list(map(int,input().split())) for i in range(n)] c=0 for e in mat: if(sum(e)>=2): c+=1 print(c)
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
a,b=map(int,input().split()) s=((a*2)//b)+((a*5)//b)+((a*8)//b) if ((a*2)%b)!=0: s=s+1 if ((a*5)%b)!=0: s=s+1 if ((a*8)%b)!=0: s=s+1 print(int(s))
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
hp = int(input()) categories = { 1: 'A', 3: 'B', 2: 'C', 0: 'D', } options = [0, 1, 2] best_category = 'D' best_option = None for option in options: remainder = (hp + option) % 4 category = categories[remainder] if category < best_category: best_category = category best_op...
Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, inf...
3
n=int(input()) x=input() if n%2==1: ans=x[0] for i in range(1,n): if i%2==1: ans=x[i]+ans else: ans=ans+x[i] print(ans) else: # ans=x[int(n/2)-1]+x[int(n/2)] ans=x[:2] for i in range(2,n): if i % 2==0: ans=x[i]+ans else: ...
Dawid has four bags of candies. The i-th of them contains a_i candies. Also, Dawid has two friends. He wants to give each bag to one of his two friends. Is it possible to distribute the bags in such a way that each friend receives the same amount of candies in total? Note, that you can't keep bags for yourself or thro...
3
s=list(map(int,input().split())) s.sort() s=s[::-1] if s[0]==sum(s[1:]) or s[0]+s[-1]==sum(s[1:-1]): print("YES") else: print("NO")
This is the easy version of the problem. The difference between the versions is in the number of possible operations that can be made. You can make hacks if and only if you solved both versions of the problem. You are given a binary table of size n Γ— m. This table consists of symbols 0 and 1. You can make such operat...
1
from __future__ import division, print_function ''' Hey stalker :) ''' INF = 10 ** 50 TEST_CASES = True from collections import defaultdict, deque, Counter from functools import reduce from bisect import bisect_left def main(): n, m = get_list() matrix = [list(map(int, input())) for _ in range(n)] moves ...
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=input().replace('+','') x=[] for i in range(len(s)): x.append(s[i]) x=sorted(x) ss=x[0] for i in range(1,len(x)): ss+='+'+x[i] print(ss)
You have a garland consisting of n lamps. Each lamp is colored red, green or blue. The color of the i-th lamp is s_i ('R', 'G' and 'B' β€” colors of lamps in the garland). You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garlan...
3
set_colors = set(['R', 'G', 'B']) def diff(*args): diff = set_colors - set(args) return diff.pop() length = int(input()) word = list(input()) index = [0, 1, 2] colors = ['R', 'G', 'B'] new_word = word flips = 0 for ix, c in enumerate(word): if ix == 0: pass elif ix == length - 1: prev = word[ix - ...
Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him? Given a n Γ— n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of th...
3
#https://codeforces.com/contest/462/problem/A n=int(input()) l=[] for i in range(n): l.append(input()) f=0 for i in range(n): for j in range(n): c=0 if i-1>=0 and l[i-1][j]=='o': c+=1 if i+1<n and l[i+1][j]=='o': c+=1 if j-1>=0 and l[i][j-1]=='o': c+=1 if j+1<n and l[i][j+1]=='o': c+=1 if c&1:...
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...
3
k, n, w = map(int,input().split()) sum = (k)*(w*(w+1)/2) if sum-n <0:print(0) else:print (int(sum-n))
This morning, Roman woke up and opened the browser with n opened tabs numbered from 1 to n. There are two kinds of tabs: those with the information required for the test and those with social network sites. Roman decided that there are too many tabs open so he wants to close some of them. He decided to accomplish this...
3
import math as m n, k = list(map(int, input().split())) a=[] ab = 0 bel = 0 s = 0 e = 0 b = 0 count = 0 ans = 0 for i in range(n): a.append(0) a = list(map(int, input().split())) for i in range(len(a)): if a[i] > 0: ab = ab + 1 if a[i] < 0: bel = bel +1 while b <= (k-1): for...
You are given a rectangular board of M Γ— N squares. Also you are given an unlimited number of standard domino pieces of 2 Γ— 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions: 1. Each domino completely covers two squa...
3
from math import floor a=list(map(int,input().split())) x=floor((a[0]*a[1])/2) print(x)
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...
3
k,n,w=map(int,input().split()) cost=0 for i in range(1,w+1): cost=cost+i*k borrow=cost-n if(borrow<0): borrow=0 print(borrow)
There are n boxers, the weight of the i-th boxer is a_i. Each of them can change the weight by no more than 1 before the competition (the weight cannot become equal to zero, that is, it must remain positive). Weight is always an integer number. It is necessary to choose the largest boxing team in terms of the number o...
3
n=int(input()) a=[int(o) for o in input().split()] a=sorted(a) a=a[::-1] s=set() for i in a: if i+1 not in s: s.add(i+1) elif i not in s: s.add(i) elif i-1 not in s and i-1!=0: s.add(i-1) print(len(s))
Many computer strategy games require building cities, recruiting army, conquering tribes, collecting resources. Sometimes it leads to interesting problems. Let's suppose that your task is to build a square city. The world map uses the Cartesian coordinates. The sides of the city should be parallel to coordinate axes....
3
# mukulchandel import sys n=int(sys.stdin.readline()) mx=-1234567890 my=-1234567890 nx=1234567890 ny=1234567890 for i in range(n): x,y=map(int,sys.stdin.readline().split()) mx=max(mx,x) my=max(my,y) nx=min(nx,x) ny=min(ny,y) print(max((mx-nx),(my-ny))**2)
You have two integers l and r. Find an integer x which satisfies the conditions below: * l ≀ x ≀ r. * All digits of x are different. If there are multiple answers, print any of them. Input The first line contains two integers l and r (1 ≀ l ≀ r ≀ 10^{5}). Output If an answer exists, print any of them. Oth...
3
a, b = map(int, input().split()) c = set() d = 0 for i in range(a, b + 1): c.clear() for t in str(i): c.add(t) if len(c) == len(str(i)): d = i break elif len(c) < len(str(i)) and i == b: d = -1 break print(d)
You are given the current time in 24-hour format hh:mm. Find and print the time after a minutes. Note that you should find only the time after a minutes, see the examples to clarify the problem statement. You can read more about 24-hour format here <https://en.wikipedia.org/wiki/24-hour_clock>. Input The first line...
3
s , n = map(int , input().split(':')) t = int(input()) s += (t //60) n += (t % 60) if n > 59 : n = n -60 s += 1 if s > 23 : s = s%24 s= str(s).zfill(2) n = str(n).zfill(2) print(f'{s}:{n}')
Input The only line of the input contains a 7-digit hexadecimal number. The first "digit" of the number is letter A, the rest of the "digits" are decimal digits 0-9. Output Output a single integer. Examples Input A278832 Output 0 Input A089956 Output 0 Input A089957 Output 1 Input A1440...
3
x = int(input(), 16) if x % 2 == 0: print(0) else: print(1)
Initially, you have the array a consisting of one element 1 (a = [1]). In one move, you can do one of the following things: * Increase some (single) element of a by 1 (choose some i from 1 to the current length of a and increase a_i by one); * Append the copy of some (single) element of a to the end of the array...
3
t=int(input()) for _ in range(t): n=int(input()) ans=10**18 for k in range(int(n**0.5)+100): moves=k+(n+k)//(k+1)-1 ans=min(ans,moves) print(ans)
During the lunch break all n Berland State University students lined up in the food court. However, it turned out that the food court, too, has a lunch break and it temporarily stopped working. Standing in a queue that isn't being served is so boring! So, each of the students wrote down the number of the student ID of...
3
n=int(input()) d,f={},{} ans=[0]*n for i in range(n): a,b=map(int,input().split()) d[a],f[b],=b,a if a==0: ans[1]=b if b==0: ans[-2]=a i,c=1,ans[1] while(1): if i+2>n-1: break x=d[c] c=x i+=2 ans[i]=x if n%2==0: i,c=n-2,ans[-2] while(1): if...
You are given an undirected unweighted graph consisting of n vertices and m edges. You have to write a number on each vertex of the graph. Each number should be 1, 2 or 3. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd. Calculate the number of possible ways t...
3
#import resource #resource.setrlimit(resource.RLIMIT_STACK, [0x100000000, resource.RLIM_INFINITY]) import sys, threading sys.setrecursionlimit(10**6) # max depth of recursion threading.stack_size(2**25) # new thread will get stack of such size def main(): mod=998244353 def ain(): return list(map(int,si...
This is the hard version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task. You are given a string s, consisting of lowercase English letters. Find the longest string, t, which satisfies the fol...
3
from sys import stdin from bisect import bisect_left as bl from bisect import bisect_right as br def input(): return stdin.readline()[:-1] def intput(): return int(input()) def sinput(): return input().split() def intsput(): return map(int, sinput()) class RangedList: def __init__(self, sta...
You are given a sequence of length N: A_1, A_2, ..., A_N. For each integer i between 1 and N (inclusive), answer the following question: * Find the maximum value among the N-1 elements other than A_i in the sequence. Constraints * 2 \leq N \leq 200000 * 1 \leq A_i \leq 200000 * All values in input are integers. Inp...
3
n = int(input()) a = [int(input()) for _ in range(n)] s = sorted(a) for x in a: if s[-1] == x: print(s[-2]) else: print(s[-1])
You have decided to give an allowance to your child depending on the outcome of the game that he will play now. The game is played as follows: * There are three "integer panels", each with a digit between 1 and 9 (inclusive) printed on it, and one "operator panel" with a `+` printed on it. * The player should constru...
3
A,B,C = map(int,input().split()) print(A+B+C+9*max(A,B,C))
Polycarp loves ciphers. He has invented his own cipher called repeating. Repeating cipher is used for strings. To encrypt the string s=s_{1}s_{2} ... s_{m} (1 ≀ m ≀ 10), Polycarp uses the following algorithm: * he writes down s_1 ones, * he writes down s_2 twice, * he writes down s_3 three times, * ... ...
3
n = int(input()) s = input() c = 1 s1 = "" for i in range (n): if i + 1 == ((c * (c + 1)) // 2): c += 1 s1 += s[i] #print(i, c, s1, "uuuuuuu") print(s1)
On a random day, Neko found n treasure chests and m keys. The i-th chest has an integer a_i written on it and the j-th key has an integer b_j on it. Neko knows those chests contain the powerful mysterious green Grapes, thus Neko wants to open as many treasure chests as possible. The j-th key can be used to unlock the ...
3
chests, keys = input().split() chest_numbers= input().split() keys_numbers= input().split() number=0 odd_chests=0 even_keys=0 for i in chest_numbers: test_chest=int(i)%2 if test_chest==1: odd_chests=odd_chests+1 for j in keys_numbers: test_key=int(j)%2 if test_key==0: even_keys=even_keys...
A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all n squad soldiers to line up on the parade ground. By the military charter the soldiers should stand in the order of non-increasing of their h...
3
n=int(input()) a=list(map(int,input().split())) max_idx=0 min_idx=0 for i in range(n): if a[max_idx]<a[i]: max_idx=i if a[min_idx]>=a[i]: min_idx=i if min_idx>max_idx: print(max_idx+(n-1-min_idx)) else: print(max_idx+(n-1-min_idx) - 1)
A new e-mail service "Berlandesk" is going to be opened in Berland in the near future. The site administration wants to launch their project as soon as possible, that's why they ask you to help. You're suggested to implement the prototype of site registration system. The system should work on the following principle. ...
1
def main(): n = int(raw_input()) system = {} for i in range(n): name = raw_input() if name in system: system[name] += 1 print(name + `system[name]`) else: print("OK") system[name] = 0 #--------- if __name__ == '__main__': main()
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
#http://codeforces.com/problemset/problem/228/A print 4-len(set(map(int, raw_input().split())))
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution....
3
n_prob = int( input() ) count = 0 for i in range( n_prob ): a,b,c = [int(x) for x in input().split()] if (a == 1 and b== 1) or (b == 1 and c== 1) or (a == 1 and c== 1): count += 1 print( count )
Pavel has several sticks with lengths equal to powers of two. He has a_0 sticks of length 2^0 = 1, a_1 sticks of length 2^1 = 2, ..., a_{n-1} sticks of length 2^{n-1}. Pavel wants to make the maximum possible number of triangles using these sticks. The triangles should have strictly positive area, each stick can be ...
3
n = int(input()) ans =0 y = 0 a = [] cnt = 0 str_in = input() a =list(map(int, str_in.strip().split())) for i in range(len(a)): t=min(int(a[i]/2),y) ans+=t a[i]-=int(t*2) y-=t ans+=a[i]//3 y+=a[i]%3 print(int(ans))
You are a coach at your local university. There are n students under your supervision, the programming skill of the i-th student is a_i. You have to create a team for a new programming competition. As you know, the more students some team has the more probable its victory is! So you have to create a team with the maxi...
1
def meu_map(l): for i in range(len(l)): l[i] = int(l[i]) def time(array, n): maximo = 0 pont1 = 0 pont2 = 0 while pont2 < n: if array[pont2] <= array[pont1] + 5: pont2 += 1 else: maximo = max(maximo, pont2 - pont1) pont1 += 1 maximo ...
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official language...
1
import sys class Node(object): def __init__(self): self.nei = [] self.vis = False def dfs(node): node.vis = True kn_l = 0 for nei in node.nei: if not nei.vis: dfs(nei) kn_l |= 1 return kn_l def C(): n, m = map(int, sys.stdin.readline().strip().s...
You can not just take the file and send it. When Polycarp trying to send a file in the social network "Codehorses", he encountered an unexpected problem. If the name of the file contains three or more "x" (lowercase Latin letters "x") in a row, the system considers that the file content does not correspond to the socia...
3
n=int(input()) s=list(input()) c=0 for i in range(n): if(s[i:i+3].count('x')==3): c=c+1 print(c)
The weight of a sequence is defined as the number of unordered pairs of indexes (i,j) (here i < j) with same value (a_{i} = a_{j}). For example, the weight of sequence a = [1, 1, 2, 2, 1] is 4. The set of unordered pairs of indexes with same value are (1, 2), (1, 5), (2, 5), and (3, 4). You are given a sequence a of n...
3
def getval(v, k): if len(v) == 1: return 0 v.sort() curr = 0 i = len(v)-1 j = 0 while i >= 1: curr += (v[j] * i * k) i -= 1 j += 1 sqsum = 0 for x in v: sqsum += x * x sum = 0 for x in v: sum += x sumsq = sum*sum b = (sumsq - sqsum) //...
There are two sisters Alice and Betty. You have n candies. You want to distribute these n candies between two sisters in such a way that: * Alice will get a (a > 0) candies; * Betty will get b (b > 0) candies; * each sister will get some integer number of candies; * Alice will get a greater amount of candie...
3
cases = int(input()) mylist = [] resultlist = [] for i in range(cases): mylist.append(eval(input())) for num in mylist: if num <= 2: resultlist.append(0) else: if num % 2 == 0: resultlist.append((num // 2) - 1) else: resultlist.append((num - 1) // 2) for nu...
Vasya has got n books, numbered from 1 to n, arranged in a stack. The topmost book has number a_1, the next one β€” a_2, and so on. The book at the bottom of the stack has number a_n. All numbers are distinct. Vasya wants to move all the books to his backpack in n steps. During i-th step he wants to move the book number...
3
import sys n = int(sys.stdin.readline().strip()) A = sys.stdin.readline().strip() B = sys.stdin.readline().strip() A = [int(i) for i in A.split()] B = [int(i) for i in B.split()] C = [0 for i in range(len(A)+1)] for i in range(len(B)): C[A[i]] = i + 1 x = 0 R = [] for i in B: y = C[i] - x if y > 0: ...
This problem is actually a subproblem of problem G from the same contest. There are n candies in a candy box. The type of the i-th candy is a_i (1 ≀ a_i ≀ n). You have to prepare a gift using some of these candies with the following restriction: the numbers of candies of each type presented in a gift should be all di...
3
import sys, collections def candy_box(a): counter = [] for value in sorted(collections.Counter(a).values(), reverse = True): counter += [max(min(value, counter[-1] - 1), 0) if counter else value] return sum(counter) #sys.stdin = open('temp.txt', 'r') input_ = sys.stdin.read().split('\n')[1:-1] for i in range(1, len(...
You are given four integers A, B, C, and D. Find the number of integers between A and B (inclusive) that can be evenly divided by neither C nor D. Constraints * 1\leq A\leq B\leq 10^{18} * 1\leq C,D\leq 10^9 * All values in input are integers. Input Input is given from Standard Input in the following format: A B ...
3
a,b,c,d=map(int,input().split()) from fractions import * f=lambda x:x-x//c-x//d+x//(c*d//gcd(c,d)) print(f(b)-f(a-1))
Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it. Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and...
3
def solve(L): d = {} for i in L: if i not in d: d[i] = 1 else: d[i] += 1 f = [] for i in d: f.append((i, i * d[i])) f.sort(key=lambda x: x[0]) dp = [0, f[0][1]] for i in range(1, len(f)): if f[i][0] > f[i - 1][0] + 1: dp.app...
Polycarp has n friends, the i-th of his friends has a_i candies. Polycarp's friends do not like when they have different numbers of candies. In other words they want all a_i to be the same. To solve this, Polycarp performs the following set of actions exactly once: * Polycarp chooses k (0 ≀ k ≀ n) arbitrary friends...
3
import sys,os,io from sys import stdin,stdout from math import log, gcd, ceil from collections import defaultdict, deque, Counter from heapq import heappush, heappop from bisect import bisect_left , bisect_right import bisect import math input = stdin.readline alphabets = list('abcdefghijklmnopqrstuvwxyz') def isPr...
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [...
3
num_test_cases = int(input()) ns = [] lists = [] for i in range(num_test_cases): ns.append(int(input())) lists.append([int(s) for s in input().split(' ')]) for n, a in zip(ns, lists): b = [a[0]] for ai in a[1:]: if ai * b[-1] > 0: b[-1] = max(ai, b[-1]) else: ...
Once again Tavas started eating coffee mix without water! Keione told him that it smells awful, but he didn't stop doing that. That's why Keione told his smart friend, SaDDas to punish him! SaDDas took Tavas' headphones and told him: "If you solve the following problem, I'll return it to you." <image> The problem is:...
3
def generate(num, pref): global res if num == 0: res += 1 if pref == n: print(res) exit() else: generate(num - 1, pref + '4') generate(num - 1, pref + '7') n = input() num = len(n) res = 0 for i in range(1, num): res += 2 ** i generate(num, '') pr...