problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
Polycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row, where all 26 lowercase Latin letters will be arranged in some order. Polycarp uses the same password s on all websites where he is registered (it is bad, but he doesn't care)...
1
for _ in range(input()): a=raw_input() t=len(a) c=1 cp=0 g=a[0]; if t==1: print"YES" print"abcdefghijklmnopqrstuvwxyz";continue v=[0 for j in range(26)];v[ord(a[0])-ord('a')]=1 if t>1: i=1 while(i<t): if(a[i]!=g): g+=a[i]; ...
Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful. Therefore, Sasha decided ...
1
n=int(raw_input()) s=0;i=0;r=0 d={(0,0):1} for j in map(int,raw_input().split()): s^=j i^=1 c=d.get((s,i),0) r+=c d[s,i]=c+1 print r
The map of Bertown can be represented as a set of n intersections, numbered from 1 to n and connected by m one-way roads. It is possible to move along the roads from any intersection to any other intersection. The length of some path from one intersection to another is the number of roads that one has to traverse along...
3
###################################################### ############Created by Devesh Kumar################### #############devesh1102@gmail.com#################### ##########For CodeForces(Devesh1102)################# #####################2020############################# ###############################################...
You are given three integers x, y and n. Your task is to find the maximum integer k such that 0 ≤ k ≤ n that k mod x = y, where mod is modulo operation. Many programming languages use percent operator % to implement it. In other words, with given x, y and n you need to find the maximum possible integer from 0 to n tha...
3
t=int(input()) while t>0 : x,y,n=map(int,input().split()) if ((n//x)*x+y<=n) : print((n//x)*x+y) else : print(((n//x)-1)*x+y) t-=1
After seeing the "ALL YOUR BASE ARE BELONG TO US" meme for the first time, numbers X and Y realised that they have different bases, which complicated their relations. You're given a number X represented in base bx and a number Y represented in base by. Compare those two numbers. Input The first line of the input con...
3
def readnum(): n, b = (int(w) for w in input().split()) x = 0 nums = list(int(w) for w in input().split()) return sum(nums[i] * b**(n-1-i) for i in range(n)) x = readnum() y = readnum() if x==y: print('=') if x<y: print('<') if x>y: print('>')
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network. Bu...
3
strg=input() lst=strg.split() s=set(strg) if len(s)%2!=0: print('IGNORE HIM!') else: print('CHAT WITH HER!')
Arpa is taking a geometry exam. Here is the last problem of the exam. You are given three points a, b, c. Find a point and an angle such that if we rotate the page around the point by the angle, the new position of a is the same as the old position of b, and the new position of b is the same as the old position of c....
3
from sys import exit from math import * ax, ay, bx, by, cx, cy = map(int, input().split()) l1 = (bx - ax)**2 + (by - ay)**2 l2 = (cx - bx)**2 + (cy - by)**2 dx = bx - ax dy = by - ay if l1 != l2: print('No') elif cx == bx + dx and cy == by + dy: print('No') else: print('Yes')
You are given two integers n and k. You are asked to choose maximum number of distinct integers from 1 to n so that there is no subset of chosen numbers with sum equal to k. A subset of a set is a set that can be obtained from initial one by removing some (possibly all or none) elements of it. Input The first line c...
3
t = int(input()) def canMake(n, lst): for i in range(len(lst)): if(n >= lst[i]): n -= lst[i] return n == 0 def solve(): n,k = map(int, input().split()) ans = [] for i in reversed(range(1, n + 1)): comp = k - i if(not canMake(comp, ans) and i != k): ans...
Innovation technologies are on a victorious march around the planet. They integrate into all spheres of human activity! A restaurant called "Dijkstra's Place" has started thinking about optimizing the booking system. There are n booking requests received by now. Each request is characterized by two numbers: ci and p...
3
n = int(input()) d ={} for x in range(n): grp, m = map(int, input().strip().split()) if m not in d: d[m] = [[grp,x+1]] else: d[m].append([grp,x+1]) k = int(input()) arr = list(map(int, input().strip().split())) sums = 0 count = 0 last = -1 lis = [] #print(d) for e in sorte...
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one r...
3
# import sys # sys.stdin = open('cf602c.in') from collections import deque n, m = map(int, input().split()) g_trn = [[] for _ in range(n)] for _ in range(m): u, v = map(int, input().split()) g_trn[u - 1].append(v - 1) g_trn[v - 1].append(u - 1) g_bus = [list(set(range(n)) - set(g_trn[i])) for i in range(n)] que...
Guy-Manuel and Thomas have an array a of n integers [a_1, a_2, ..., a_n]. In one step they can add 1 to any element of the array. Formally, in one step they can choose any integer index i (1 ≤ i ≤ n) and do a_i := a_i + 1. If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and T...
3
from sys import stdin,stdout import bisect def st(): return list(stdin.readline().strip()) def inp(): return int(stdin.readline()) def li(): return list(map(int,stdin.readline().split())) def mp(): return map(int,stdin.readline().split()) def pr(n): stdout.write(str(n)+"\n") def soe(limit): ...
You have probably registered on Internet sites many times. And each time you should enter your invented password. Usually the registration form automatically checks the password's crypt resistance. If the user's password isn't complex enough, a message is displayed. Today your task is to implement such an automatic che...
1
s = raw_input().strip() import string if len(s) >= 5 and any(c in string.uppercase for c in s) and any(c in string.lowercase for c in s) and any(c in string.digits for c in s): print "Correct" else: print "Too weak"
So, the New Year holidays are over. Santa Claus and his colleagues can take a rest and have guests at last. When two "New Year and Christmas Men" meet, thear assistants cut out of cardboard the letters from the guest's name and the host's name in honor of this event. Then the hung the letters above the main entrance. O...
3
a = input() b = input() c = input() d_a = {} for char in a: try: d_a[char] += 1 except KeyError: d_a[char] = 1 d_b = {} for char in b: try: d_b[char] += 1 except KeyError: d_b[char] = 1 d_c = {} for char in c: try: d_c[char] += 1 except KeyError: ...
As a German University in Cairo (GUC) student and a basketball player, Herr Wafa was delighted once he heard the news. GUC is finally participating in the Annual Basketball Competition (ABC). A team is to be formed of n players, all of which are GUC students. However, the team might have players belonging to differen...
1
n, m, h = [int(v) for v in raw_input().split()] S = [int(v) for v in raw_input().split()] if sum(S) < n: print -1.0 exit() k = n - 1 n = sum(S) - 1 a = S[h - 1] - 1 x = 1 res = 1.0 for v in range(0, a): res *= n - k - v res /= n - v print 1.0 - res
You are a coach of a group consisting of n students. The i-th student has programming skill a_i. All students have distinct programming skills. You want to divide them into teams in such a way that: * No two students i and j such that |a_i - a_j| = 1 belong to the same team (i.e. skills of each pair of students in t...
3
num_queries = int(input()) for _ in range(num_queries): _ = int(input()) skills = sorted(set(map(int, input().split()))) for i, skill in enumerate(skills[:-1]): if skill + 1 == skills[i + 1]: print(2) break else: print(1)
Colonel has n badges. He wants to give one badge to every of his n soldiers. Each badge has a coolness factor, which shows how much it's owner reached. Coolness factor can be increased by one for the cost of one coin. For every pair of soldiers one of them should get a badge with strictly higher factor than the secon...
3
n = int(input()) a = sorted(map(int, input().split())) cost = 0 for i in range(1, n): if a[i-1] >= a[i]: cost += a[i-1] - a[i] + 1 a[i] = a[i-1] +1 print(cost)
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated. The language is that peculiar as it has exactly one variable, called x. Also, there are two operations: * Operation ++ increases the value of variable x by 1. * Operation -- decreases the value of variable x by 1....
1
n=input() c=0 while(n>0): s=raw_input() if(s.count('+')==2): c+=1 else: c-=1 n-=1 print c
You are given a integer n (n > 0). Find any integer s which satisfies these conditions, or report that there are no such numbers: In the decimal representation of s: * s > 0, * s consists of n digits, * no digit in s equals 0, * s is not divisible by any of it's digits. Input The input consists of mult...
3
t = int(input()) for _ in range(t): n = int(input()) if n == 1: print(-1) else: print('2', end = '') for i in range(1, n): print('3', end = '') print()
Vampire Mr. C is a vampire. If he is exposed to the sunlight directly, he turns into ash. Nevertheless, last night, he attended to the meeting of Immortal and Corpse Programmers Circle, and he has to go home in the near dawn. Fortunately, there are many tall buildings around Mr. C's home, and while the sunlight is blo...
3
from collections import defaultdict,deque import sys,heapq,bisect,math,itertools,string,queue,datetime sys.setrecursionlimit(10**8) INF = float('inf') mod = 10**9+7 eps = 10**-7 def inpl(): return list(map(int, input().split())) def inpl_str(): return list(input().split()) def calc(p,x): return p*(100+x)//100 wh...
Joisino is about to compete in the final round of a certain programming competition. In this contest, there are N problems, numbered 1 through N. Joisino knows that it takes her T_i seconds to solve problem i(1≦i≦N). Also, there are M kinds of drinks offered to the contestants, numbered 1 through M. If Joisino takes d...
3
N=int(input()) T=list(map(int,input().split())) TA=sum(T) M=int(input()) for i in range(M): P,X=map(int,input().split()) ans=TA+X-T[P-1] print(ans)
In AtCoder Kingdom, Gregorian calendar is used, and dates are written in the "year-month-day" order, or the "month-day" order without the year. For example, May 3, 2018 is written as 2018-5-3, or 5-3 without the year. In this country, a date is called Takahashi when the month and the day are equal as numbers. For exam...
3
a,b=map(int, input().split()) print(a if a<=b or a==1 else a-1)
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() diff = 0 for i in range(n): if s[i] == "1": diff += 1 else: diff -= 1 if diff == 0: print(2) print(s[:-1]+" "+s[-1]) else: print(1) print(s)
Misha and Vasya participated in a Codeforces contest. Unfortunately, each of them solved only one problem, though successfully submitted it at the first attempt. Misha solved the problem that costs a points and Vasya solved the problem that costs b points. Besides, Misha submitted the problem c minutes after the contes...
3
a, b, c, d = map(int, input().split()) m = max(3 * a // 10, a - c * a // 250) v = max(3 * b // 10, b - d * b // 250) if m > v: print('Misha') elif v > m: print('Vasya') else: print('Tie')
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative. She would like to r...
3
def digit(n, d): return n % (2**(d+1)) // 2**d def get_ans(nums): for d in range(30, -1, -1): s = 0 b = None for i, n in enumerate(nums): if digit(n, d): s += 1 b = i if s == 1: return [nums[b]] + nums[:b] + nums[b+1:] ...
Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him. One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For e...
3
n = int(input()) inp = input().split() pts = [int(i) for i in inp] min_pts = pts[0] max_pts = pts[0] ans = 0 for i in pts: if i < min_pts: ans += 1 min_pts = i elif i > max_pts: ans += 1 max_pts = i print (ans)
Let's define the following recurrence: $$$a_{n+1} = a_{n} + minDigit(a_{n}) ⋅ maxDigit(a_{n}).$$$ Here minDigit(x) and maxDigit(x) are the minimal and maximal digits in the decimal representation of x without leading zeroes. For examples refer to notes. Your task is calculate a_{K} for given a_{1} and K. Input The ...
3
t = int(input()) for _ in range(t): no,b = map(int,input().split()) for i in range(b-1): prev = no no += min(list(map(int,list(str(no)))))*max(list(map(int,list(str(no))))) if prev == no: break print(no)
Constraints * 1 ≤ |V| ≤ 100 * 0 ≤ |E| ≤ 9900 * -2 × 107 ≤ di ≤ 2 × 107 * There are no parallel edges * There are no self-loops Input An edge-weighted graph G (V, E). |V| |E| s0 t0 d0 s1 t1 d1 : s|E|-1 t|E|-1 d|E|-1 |V| is the number of vertices and |E| is the number of edges in G. The graph vertices are named wi...
3
def warshall_floyd(d): #d[i][j]: iからjへの最短距離 for k in range(n): for i in range(n): for j in range(n): d[i][j] = min(d[i][j],d[i][k] + d[k][j]) return d ############################## n,w = map(int,input().split()) #n:頂点数 w:辺の数 d = [[float("inf") for i in range(n)] for i ...
One day Vasya was sitting on a not so interesting Maths lesson and making an origami from a rectangular a mm × b mm sheet of paper (a > b). Usually the first step in making an origami is making a square piece of paper from the rectangular sheet by folding the sheet along the bisector of the right angle, and cutting t...
3
######### ## ## ## #### ##### ## # ## # ## # # # # # # # # # # # # # # # # # # # # # # # ### # # # # # # # # # # # # # ##### # # # # ### # # # # # # # # ##### # # # # # # # # # # # # # # # # # # #########...
Year 2118. Androids are in mass production for decades now, and they do all the work for humans. But androids have to go to school to be able to solve creative tasks. Just like humans before. It turns out that high school struggles are not gone. If someone is not like others, he is bullied. Vasya-8800 is an economy-cl...
1
import math x,y=map(int,raw_input().split()) z=y*math.log10(x)-x*math.log10(y); if(z>0): print(">") if(z<0): print("<") if(z==0): print("=")
You are given a marine area map that is a mesh of squares, each representing either a land or sea area. Figure B-1 is an example of a map. <image> Figure B-1: A marine area map You can walk from a square land area to another if they are horizontally, vertically, or diagonally adjacent to each other on the map. Two ar...
3
import sys sys.setrecursionlimit(10**8) #再帰関数の上限を変更 ans = [] def dfs(x, y): c[x][y] = 0 #今いる場所を0にする for dx in range(-1, 2): for dy in range(-1, 2): nx = x + dx ny = y + dy ##動く先が範囲内で、1であれば移動する if 0 <= nx < h and 0 <= ny < w and c[nx][ny] == 1: ...
Phoenix has n coins with weights 2^1, 2^2, ..., 2^n. He knows that n is even. He wants to split the coins into two piles such that each pile has exactly n/2 coins and the difference of weights between the two piles is minimized. Formally, let a denote the sum of weights in the first pile, and b denote the sum of weigh...
3
for i in range(int(input())): n = int(input()) a, b = 2**n, 0 for i in range(n//2, n): b+=2**i for i in range(1, n//2): a+=2**i print(abs(a - b))
Consider sequences \\{A_1,...,A_N\\} of length N consisting of integers between 1 and K (inclusive). There are K^N such sequences. Find the sum of \gcd(A_1, ..., A_N) over all of them. Since this sum can be enormous, print the value modulo (10^9+7). Here \gcd(A_1, ..., A_N) denotes the greatest common divisor of A_1...
3
N,K = map(int,input().split()) gcddic = {} mod_n = (10**9+7) for i in range(K,0,-1): x = pow((K//i),N,mod_n) ll=2 while(ll*i<=K): x -= gcddic[ll*(i)] ll += 1 gcddic[i] = x sumnation = 0 for i,l in gcddic.items(): sumnation += i*l print(sumnation%mod_n)
Three friends are going to meet each other. Initially, the first friend stays at the position x = a, the second friend stays at the position x = b and the third friend stays at the position x = c on the coordinate axis Ox. In one minute each friend independently from other friends can change the position x by 1 to the...
3
for _ in range(int(input())): a,s,flag=[0,0,0],0,0 a[0],a[1],a[2]=map(int,input().split()) a.sort() if (a[0]==a[1] and a[1]!=a[2]) or (a[1]==a[2] and a[1]!=a[0]): if a[1]-a[0]>=2 or a[2]-a[1]>=2: flag=1 a[0]-=a[1] a[2]-=a[1] a[1]=0 if a[0]<0: a[0]+=1 if a[2]>0: a[...
A positive (strictly greater than zero) integer is called round if it is of the form d00...0. In other words, a positive integer is round if all its digits except the leftmost (most significant) are equal to zero. In particular, all numbers from 1 to 9 (inclusive) are round. For example, the following numbers are roun...
3
def get_summands(n): multiplier = 1 result = [] while n > 0: units = n % 10 rounded = units * multiplier if rounded: result.append(rounded) n = n // 10 multiplier = multiplier * 10 return result def main(): t = int(input()) global_ans = "" for _ in range(t): n = int(input()) ans = get_summands...
Vasya is writing an operating system shell, and it should have commands for working with directories. To begin with, he decided to go with just two commands: cd (change the current directory) and pwd (display the current directory). Directories in Vasya's operating system form a traditional hierarchical tree structure...
3
n = int(input()) class Node: def __init__(self, name, parent=None): self.name = name self.parent = parent self.children = {} def add_child(self, child_node): self.children.append(child_node) class FileSystem: def __init__(self): self.ptr = Node('/') sel...
There are n students in the first grade of Nlogonia high school. The principal wishes to split the students into two classrooms (each student must be in exactly one of the classrooms). Two distinct students whose name starts with the same letter will be chatty if they are put in the same classroom (because they must ha...
3
import math n=int(input()) c={} for i in range(n): x=input() if x[0] in c: c[x[0]]+=1 else: c[x[0]]=1 p=0 for i in c.values(): a=math.ceil(i/2) b=math.floor(i/2) p+=((a*(a-1))+(b*(b-1)))//2 print(p)
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: * Tetrahedron. Tetrahedron has 4 triangular faces. * Cube. Cube has 6 square faces. * Octahedron. Octahedron has 8 triangular faces. * Dodecahedron. Dodecahedron has 12 pentagonal faces. *...
3
n = int(input()) #polyhedrons = [x for x in input().strip().split(' ')] faces = 0 for i in range(n): polyhedron = input().strip() if polyhedron == 'Tetrahedron': faces += 4 elif polyhedron == 'Cube': faces += 6 elif polyhedron == 'Octahedron': faces += 8 elif polyhedron == 'Dodecahedron': faces += 12 ...
There are two types of burgers in your restaurant — hamburgers and chicken burgers! To assemble a hamburger you need two buns and a beef patty. To assemble a chicken burger you need two buns and a chicken cutlet. You have b buns, p beef patties and f chicken cutlets in your restaurant. You can sell one hamburger for ...
3
t=int(input()) for i in range(t): b,p,f=map(int,input().split()) h,c=map(int,input().split()) sum=0 b=b//2 if(h>=c): sum+=min(b,p)*h b-=min(b,p) sum+=min(b,f)*c else: sum+=min(b,f)*c b-=min(b,f) sum+=min(b,p)*h print(sum)
Vasya likes everything infinite. Now he is studying the properties of a sequence s, such that its first element is equal to a (s1 = a), and the difference between any two neighbouring elements is equal to c (si - si - 1 = c). In particular, Vasya wonders if his favourite integer b appears in this sequence, that is, the...
3
a,b,c=map(int,input().split()) if(c==0): if(a==b): print('YES') else: print('NO') else: if((b-a)==0): print('YES') elif((b-a)>0 and c>0): if(((b-a)%c)==0): print('YES') else: print('NO') elif((b-a)<0 and c<0): if(((b-a)%c)==0): print('YES') else: print('NO') else: print('NO')
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like. Now let's imagine a typical morning in your family. You haven't w...
3
n= int(input()) k= sorted(list(map(int,input().split()))) l=0 p=0 while l<=sum(k): l+=k.pop() p+=1 print(p)
You have n gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The i-th gift consists of a_i candies and b_i oranges. During one move, you can choose some gift 1 ≤ i ≤ n and do one of the following operations: * eat exactly...
3
for i in range(int(input())): n = int(input()) a = [int(i) for i in input().split()] b = [int(i) for i in input().split()] l = min(a) r = min(b) cnt=0 for i in range(n): if a[i]>l: cnt+=a[i]-l a[i]=(a[i]-l) else: a[i]=0 for i in range(n): if b[i]>r: cnt+=(max(0,b[i]-a[i]-r)) print(cnt)
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different. Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some num...
3
n=int(input()) s=input() sList=[] if n>26: print(-1) else: for i in range(n): sList.append(s[i]) swaps=0 for i in range(n-1): for j in range(i+1,n): if sList[i]==sList[j]: sList[j]=swaps swaps+=1 print(swaps)
You are given an array a of length n consisting of zeros. You perform n actions with this array: during the i-th action, the following sequence of operations appears: 1. Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; 2. Let ...
3
from heapq import * for i in range(int(input())): n=int(input()) q = [(1-n,1,n)] order = [] ans = [0] * n count=1 while(q): val = heappop(q) #print(val) r = (val[1]+val[2])//2 order.append(r) ans[r-1]=count count+=1 if(val[2]-val[1]...
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()) a = list(map(int,input().split())) a.sort() i = 0 ln = nn = 1 j = n-1 while (a[i]==a[i+1] and i<n-1 and a[0]!=a[-1]): i+=1 nn+=1 while(a[j]==a[j-1] and j>0 and a[0]!=a[-1]): j-=1 ln+=1 dis = a[-1]-a[0] if a[0]!=a[-1]: k = ln*nn else: k = n*(n-1)//2 print(dis, end = " ") print(k)
You are given a string s. You have to reverse it — that is, the first letter should become equal to the last letter before the reversal, the second letter should become equal to the second-to-last letter before the reversal — and so on. For example, if your goal is to reverse the string "abddea", you should get the str...
3
# by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO, IOBase from collections import deque def update(seg_tree,xx,u,v): curr = deque([(1,1,xx)]) while len(curr): x = curr.popleft() if x[1] >= u and x[2] <= v: seg_tree[x[0]] += 1 ...
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000. This new device is equipped with specially designed artificial intelligence (AI). Employees of Pine...
3
a = input() b = input() nIndex = 0 nSum = 0 while True : nRet = a.find(b, nIndex) if nRet == -1 : break; nSum += 1 nIndex = nRet + len(b) print(nSum)
Consider a rooted tree. A rooted tree has one special vertex called the root. All edges are directed from the root. Vertex u is called a child of vertex v and vertex v is called a parent of vertex u if there exists a directed edge from v to u. A vertex is called a leaf if it doesn't have children and has a parent. Let...
3
from collections import defaultdict n=int(input()) graph=defaultdict(lambda:[]) for i in range(n-1): x=int(input()) graph[x].append(i+2) ans="Yes" key=list(graph.keys()) for i in key: if(len(graph[i])<3): ans="No" break else: val=0 for j in graph[i]: if(graph...
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s. You have to answer t independent test cases. Input The first line of the input co...
3
for _ in range(int(input())): n, s = map(str, input().split()) s = int(s) n = list(n) q = 0 for i in range(len(n)): q += int(n[i]) if q <= s: print(0) else: if int(n[0]) < s: a = [n[0]] r = int(n[0]) m = 0 for i in ran...
Igor K. always used to trust his favorite Kashpirovsky Antivirus. That is why he didn't hesitate to download the link one of his groupmates sent him via QIP Infinium. The link was said to contain "some real funny stuff about swine influenza". The antivirus had no objections and Igor K. run the flash application he had ...
3
s = input() d = {} for i in range(10): x = input() d[x] = str(i) ans = '' for i in range(8): ans += d[s[i*10 : (i * 10 + 10)]] print(ans)
Local authorities have heard a lot about combinatorial abilities of Ostap Bender so they decided to ask his help in the question of urbanization. There are n people who plan to move to the cities. The wealth of the i of them is equal to ai. Authorities plan to build two cities, first for n1 people and second for n2 peo...
3
n,n1,n2=map(int,input().split()) a=list(map(int,input().split())) a.sort(reverse=True) b=[] c=[] if n1<n2: for i in range(n1): b.append(a.pop(0)) for i in range(n2): c.append(a.pop(0)) else: for i in range(n2): c.append(a.pop(0)) for i in range(n1): b.append(a.pop(0)) ...
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()) pi=[int(x) for x in input().split()] a='' out=[0]*n for i in range(n): out[pi[i]-1]=i+1 for i in out: a=a+str(i)+' ' print(a)
Some natural number was written on the board. Its sum of digits was not less than k. But you were distracted a bit, and someone changed this number to n, replacing some digits with others. It's known that the length of the number didn't change. You have to find the minimum number of digits in which these two numbers c...
1
from __future__ import print_function k = int(raw_input()) n =raw_input() a = [] for i in range(len(n)): a.append(int(n[i])) a.sort() i = 0 s = sum(a) while s<k: s = s - a[i] + 9 i += 1 print(i)
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...
1
import string a=raw_input() a=a.split("+") b=[] for k in a: b.append(int(k)) b=sorted(b) if len(b) > 1: i=1 S=str(b[0]) while i<len(b): S=S+"+"+str(b[i]) i=i+1 print S else: print a[0]
Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him. One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For e...
3
n=int(input()) inp=list(map(int,input().split())) max1=inp[0] min1=inp[0] lst=[] for i in range(1,n): if(inp[i] > max1): max1=inp[i] lst.append(inp[i]) elif(inp[i] < min1): min1=inp[i] lst.append(inp[i]) print(len(set(lst)))
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
def next(char): return chr((ord(char) - ord('a') + 1) % 26 + ord('a')) def generate_curr_from_prev(prev: str, k: int): if(k == 200): return prev else: return prev[:k] + next(prev[k]) + "a"*(200-k-1) def solve(): n = int(input().strip()) a = list(map(int, input().strip().split()))...
Ayush, Ashish and Vivek are busy preparing a new problem for the next Codeforces round and need help checking if their test cases are valid. Each test case consists of an integer n and two arrays a and b, of size n. If after some (possibly zero) operations described below, array a can be transformed into array b, the ...
3
import sys input = sys.stdin.readline from collections import Counter def cnt(A): C = Counter() for i in range(len(A)//2): a, b = A[i], A[-i-1] C[(min(a, b), max(a, b))] += 1 return C for _ in range(int(input())): n = int(input()) A = list(map(int, input().split())) B = list(map(int, input().split())) if...
wHAT DO WE NEED cAPS LOCK FOR? Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage. Let's consider that a word has been typed with the Caps lock key accidentall...
3
a=input() x=int(1) k=int(0) b=len(a) while x<b: if a[x].isupper()==True: k=k+1 x=x+1 if k==b-1: if a[0].islower()==True: print(a.capitalize()) else: print(a.lower()) else: print(a)
Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS: You are given two integers d, m, find the number of arrays a, satisfying the following constraints: * The length of a is n, n ≥ 1 * 1 ≤ a_1 < a_2 < ... < a_n ≤ d * Define an array b of length n as foll...
3
def go(): d, m = map(int, input().split()) i = d.bit_length() res = 0 while i >= 0: bi = 1 << i if d >= bi: res += (bitvals[i]%m) * (d - bi + 1) res = res%m d=bi-1 i -= 1 return res%m bitvals = [1] for i in range(33): bitvals.append(b...
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch. Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with number...
3
def binsearch(nums, target): left = 0 right = len(nums) - 1 while left <= right: mid = (left + right) // 2 if nums[mid] == target: return mid elif nums[mid] > target: right = mid - 1 elif nums[mid] < target: left = mid + 1 return left ...
You are given three sequences: a_1, a_2, …, a_n; b_1, b_2, …, b_n; c_1, c_2, …, c_n. For each i, a_i ≠ b_i, a_i ≠ c_i, b_i ≠ c_i. Find a sequence p_1, p_2, …, p_n, that satisfy the following conditions: * p_i ∈ \\{a_i, b_i, c_i\} * p_i ≠ p_{(i mod n) + 1}. In other words, for each element, you need to choose ...
3
t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) c = list(map(int, input().split())) ans = [a[0]] for i in range(1, n): if a[i] != ans[-1] and a[i] != ans[0]: ans.append(a[i]) elif b[i] != an...
You still have partial information about the score during the historic football match. You are given a set of pairs (a_i, b_i), indicating that at some point during the match the score was "a_i: b_i". It is known that if the current score is «x:y», then after the goal it will change to "x+1:y" or "x:y+1". What is the l...
3
from math import * import sys def minp(): return sys.stdin.readline().strip() def mint(): return int(minp()) def mints(): return map(int, minp().split()) n = mint() pa, pb = 0,0 pl = 0 c = 0 for i in range(n): a, b = mints() l = max(max(pa,pb),pl) r = min(a,b) #print(l,r) if r >= l: c += r-l+1 pl = r+1 ...
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different. Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some num...
3
'''input 2 aa ''' n = int(input()) s = input() print(n - len(set(list(s))) if n <= 26 else -1)
String can be called correct if it consists of characters "0" and "1" and there are no redundant leading zeroes. Here are some examples: "0", "10", "1001". You are given a correct string s. You can perform two different operations on this string: 1. swap any pair of adjacent characters (for example, "101" <image>...
3
n=int(input()) a=input() count_1=a.count('1') count_0=a.count('0') if count_1==n: print(1) elif count_0==n: print(0) else: i = 0 s = "1" while i < count_0: s += '0' i += 1 print(s)
Soon after the Chunga-Changa island was discovered, it started to acquire some forms of civilization and even market economy. A new currency arose, colloquially called "chizhik". One has to pay in chizhiks to buy a coconut now. Sasha and Masha are about to buy some coconuts which are sold at price z chizhiks per cocon...
3
a=list(map(int,input().split())) x,y,p=a lx,ly=x%p,y%p ct=int((x+y)//p) g=0 if (lx+ly)>=p: g=p-max(lx,ly) print(ct,g)
For years, the Day of city N was held in the most rainy day of summer. New mayor decided to break this tradition and select a not-so-rainy day for the celebration. The mayor knows the weather forecast for the n days of summer. On the i-th day, a_i millimeters of rain will fall. All values a_i are distinct. The mayor k...
3
n,x,y=map(int,input().split()) arr=list(map(int,input().split())) for i in range(n): flag=0 for j in range(i-1,max(i-x-1,-1),-1): if(arr[j]<=arr[i]): flag=1 for j in range(i+1,min(i+y+1,n)): if(arr[j]<=arr[i]): flag=1 if(flag==0): print(i+1) exit(0)
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=int(input()) if a==2: print('NO') elif ((a % 2 == 0) and(1<=a<=100)and( (a % 2) % 2==0 )) : print('YES') else: print('NO')
Find the minimum area of a square land on which you can place two identical rectangular a × b houses. The sides of the houses should be parallel to the sides of the desired square land. Formally, * You are given two identical rectangles with side lengths a and b (1 ≤ a, b ≤ 100) — positive integers (you are given ...
3
t = int(input()) for _ in range(t): a, b = map(int, input().split()) a, b = min(a,b), max(a,b) print(max(2 * a, b) ** 2)
For a positive integer n let's define a function f: f(n) = - 1 + 2 - 3 + .. + ( - 1)nn Your task is to calculate f(n) for a given integer n. Input The single line contains the positive integer n (1 ≤ n ≤ 1015). Output Print f(n) in a single line. Examples Input 4 Output 2 Input 5 Output -3 Note f(4)...
1
n=input() res=0 if n%2==1: n=n+1 res=(-1)*(n/2) else: res=n/2 print res
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1. Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divi...
3
# num = int(input()) # biggest_prime = 1 # prime_sum_list = [] # for i in range(1, num): # factors = 1 # for j in range(2, i // 2 + 1): # if i % j == 0: # break # else: # biggest_prime = i # # print(biggest_prime) num = int(input()) print(num // 2) if num % 2 == 0: # print(n...
Maksim walks on a Cartesian plane. Initially, he stands at the point (0, 0) and in one move he can go to any of four adjacent points (left, right, up, down). For example, if Maksim is currently at the point (0, 0), he can go to any of the following points in one move: * (1, 0); * (0, 1); * (-1, 0); * (0, -...
3
import itertools as it def dist(a, b): return abs(a[0] - b[0]) + abs(a[1] - b[1]) def spir_dist(x): a, b = x if a >= b: return b else: return 2 * b - a n = int(input()) A = [[0, 0]] for _ in range(n): x, y = map(int, input().split()) A += [[x, y]] A_s = sorted(A, key=max) ...
Lunar New Year is approaching, and you bought a matrix with lots of "crosses". This matrix M of size n × n contains only 'X' and '.' (without quotes). The element in the i-th row and the j-th column (i, j) is defined as M(i, j), where 1 ≤ i, j ≤ n. We define a cross appearing in the i-th row and the j-th column (1 < i...
3
n = int(input()) M = [] for i in range(n): M.append(list(input())) ans = 0 for i in range(1,n-1): for j in range(1,n-1): if M[i][j] == 'X' and M[i-1][j-1]=='X' and M[i-1][j+1]=='X' and M[i+1][j-1] =='X' and M[i+1][j+1] == 'X': ans +=1 print(ans)
You are given three positive (i.e. strictly greater than zero) integers x, y and z. Your task is to find positive integers a, b and c such that x = max(a, b), y = max(a, c) and z = max(b, c), or determine that it is impossible to find such a, b and c. You have to answer t independent test cases. Print required a, b a...
3
import sys import math,bisect from itertools import groupby,accumulate from heapq import heapify,heappop,heappush from collections import deque,Counter,OrderedDict #input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__ def neo(): return map(int,input().split()) def Neo(): return list(map(int,input().spli...
One day, as Sherlock Holmes was tracking down one very important criminal, he found a wonderful painting on the wall. This wall could be represented as a plane. The painting had several concentric circles that divided the wall into several parts. Some parts were painted red and all the other were painted blue. Besides,...
3
num=int(input()) arr=[0]*num arr=input().split() for i in range (num): arr[i]=int(arr[i]) arr.sort() if num%2==1: final=0 for i in range (0,num,+2): if i==0: final=final+(arr[i]**2) else: final=final+(arr[i]**2-arr[i-1]**2) print (final*3.1415926536) else: fin...
Kirito is stuck on a level of the MMORPG he is playing now. To move on in the game, he's got to defeat all n dragons that live on this level. Kirito and the dragons have strength, which is represented by an integer. In the duel between two opponents the duel's outcome is determined by their strength. Initially, Kirito'...
3
m,n=map(int,input().split()) a=[] for i in range(n): l=list(map(int,input().split())) a.append(l) a.sort() count=0 for i in a: if m>i[0]: m+=i[1] count+=1 if count==n: 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
n=int(input()) L=input().split() for i in range(n): L[i]=int(L[i]) L1=[] for k in range(n): i=j=k l=r=0 while(i+1<=len(L)-1 and L[i]>=L[i+1]): i+=1 l+=1 while(j-1>=0 and L[j]>=L[j-1]): j-=1 r+=1 L1.append(r+l+1) print(max(L1))
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr...
3
a=input() b=input() a1=a.lower() b1=b.lower() if a1<b1: print(-1) elif a1>b1: print(1) else: print(0)
Snuke loves puzzles. Today, he is working on a puzzle using `S`- and `c`-shaped pieces. In this puzzle, you can combine two `c`-shaped pieces into one `S`-shaped piece, as shown in the figure below: 9b0bd546db9f28b4093d417b8f274124.png Snuke decided to create as many `Scc` groups as possible by putting together one ...
3
n,m=map(int,input().split()) s=(2*n+m)//4 if (s+1)*4<=2*n+m: s+=1 print(min(m//2,s))
There are N+1 towns. The i-th town is being attacked by A_i monsters. We have N heroes. The i-th hero can defeat monsters attacking the i-th or (i+1)-th town, for a total of at most B_i monsters. What is the maximum total number of monsters the heroes can cooperate to defeat? Constraints * All values in input are i...
3
n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) monster = sum(a) for i in range(n): a[i + 1] -= min(b[i] - min(b[i], a[i]), a[i + 1]) a[i] -= min(b[i], a[i]) print(monster - sum(a))
In Berland it is the holiday of equality. In honor of the holiday the king decided to equalize the welfare of all citizens in Berland by the expense of the state treasury. Totally in Berland there are n citizens, the welfare of each of them is estimated as the integer in ai burles (burle is the currency in Berland). ...
3
input() a=list(map(int,input().split())) print(sum([max(a)-i for i in a]))
Alice and Bob have received three big piles of candies as a gift. Now they want to divide these candies as fair as possible. To do this, Alice takes one pile of candies, then Bob takes one of the other two piles. The last pile is split between Alice and Bob as they want: for example, it is possible that Alice takes the...
3
n = int(input()) for _ in range(n): print(sum(map(int, input().split()[:3])) // 2)
Let's call a number k-good if it contains all digits not exceeding k (0, ..., k). You've got a number k and an array a containing n numbers. Find out how many k-good numbers are in a (count each number every time it occurs in array a). Input The first line contains integers n and k (1 ≤ n ≤ 100, 0 ≤ k ≤ 9). The i-th ...
3
""" https://codeforces.com/contest/365/problem/A 10 6 1234560 1234560 1234560 1234560 1234560 1234560 1234560 1234560 1234560 1234560 2 1 1 10 """ n, k = (int(i) for i in input().split()) sol = 0 set1 = set(str(i) for i in range(k + 1)) for i in range(n): set2 = set(input()) if set1.issubset(set2): ...
After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length n which satisfies the following requirements: * There is at least one digit in the string, * There is at least one lowercase (small) letter of the Latin alphabet in the string...
3
import math as mt import sys,string input=sys.stdin.readline #print=sys.stdout.write import random from collections import deque,defaultdict L=lambda : list(map(int,input().split())) Ls=lambda : list(input().split()) M=lambda : map(int,input().split()) I=lambda :int(input()) n,m=M() l=[] for _ in range(n): s=inpu...
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
N, M = map(int, input().split()) A = [] ans = 0 for i in range(N): A.append(list(map(int,input().split()))) for i in range(2): for j in range(2): for k in range(2): a, b, c = (-1)**i, (-1)**j, (-1)**k tmp = [x[0]*a+x[1]*b+x[2]*c for x in A] tmp.sort(reverse=True) ...
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
import sys import heapq import random import collections import bisect # available on Google, not available on Codeforces # import numpy as np # import scipy def solve(a,b,x,y): # fix inputs here if a+b < x+y: # console("not enough cookies") return "No" a,b = sorted([a,b]) if a < y: ...
There is a cave consisting of N rooms and M one-directional passages. The rooms are numbered 1 through N. Takahashi is now in Room 1, and Room N has the exit. The i-th passage connects Room s_i and Room t_i (s_i < t_i) and can only be traversed in the direction from Room s_i to Room t_i. It is known that, for each roo...
3
n, m = map(int, input().split()) G = [[] for _ in range(n)] ST = tuple(tuple(map(lambda x:int(x)-1, input().split())) for _ in range(m)) for s, t in ST: G[s].append(t) #枝(s, t)を塞いだ時にそれぞれそこからあと何手かかるかを求める def f(s, t): dp = [0]*n #そこからあと何手かかるかの期待値 for i in range(n-2, -1, -1): temp = 0 for v in G[i]: te...
One day a well-known sponsor of a well-known contest decided to give every participant of the contest a T-shirt as a present. A natural problem occurred: on the one hand, it is not clear how many T-shirts of what sizes should be ordered, and on the other hand, one doesn't want to order too many T-shirts (and we do not ...
3
################# # July 18th 2019. ################# ############################################################### # Getting Problem-Data from Codeforces. shirtCounts = list(map(int,input().split(' '))) # Specifying preferences based on size demanded. preferences = { 'S' :['S','M','L','XL','XXL'], 'M' :['M','L'...
Due to the coronavirus pandemic, city authorities obligated citizens to keep a social distance. The mayor of the city Semyon wants to light up Gluharniki park so that people could see each other even at night to keep the social distance. The park is a rectangular table with n rows and m columns, where the cells of the...
3
MOD = 1000000007 ii = lambda : int(input()) si = lambda : input() dgl = lambda : list(map(int, input())) f = lambda : map(int, input().split()) il = lambda : list(map(int, input().split())) ls = lambda : list(input()) from collections import * import math for _ in range(ii()): a,b=f() print(math.ceil((a*b...
DZY has a hash table with p buckets, numbered from 0 to p - 1. He wants to insert n numbers, in the order they are given, into the hash table. For the i-th number xi, DZY will put it into the bucket numbered h(xi), where h(x) is the hash function. In this problem we will assume, that h(x) = x mod p. Operation a mod b d...
3
h = [] a = -1 P, N = map(int, input().split()) for i in range(N): v = int(input()) % P if (v in h) and a == -1: a = i + 1 h.append(v) print(a)
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it: * deletes all the vowels, * inserts a character "." before each consonant, * repl...
3
v=('a','e','i','o','u','y','A','E','I','O','U','Y') s=tuple(input().lower()) k=[x for x in s if x not in v] t=[] for i in range(0,len(k)): t.append('.') t.append(k[i]) print("".join(t))
Vivek was roaming around in the electronics shop, where he saw a box called as BlackBox. He was intrigued by its function, so he bought it. It's functionality states that for given integer input N ≤ 1000 - it outputs the sum of all the digits in factorial of N (N!). Now Vivek wants to extend its functionality for la...
1
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' # Read input from stdin and provide input before running code n = raw_input() n = int(n) k = 0 for j in range(n): k = raw_input() k = int(k) i = 1 fact = 1 while i <= ...
A bracket sequence is a string that is one of the following: 1. An empty string; 2. The concatenation of `(`, A, and `)` in this order, for some bracket sequence A ; 3. The concatenation of A and B in this order, for some non-empty bracket sequences A and B / Given are N strings S_i. Can a bracket sequence be forme...
3
n = int(input()) s=['' for _ in range(n)] for i in range(n): s[i]=input() #x=[[0,0] for _ in range(n)] hp,hm=0,0 p=[] m=[] for i in range(n): t=s[i] lv=0 mn=0 for u in t: if u == '(': lv+=1 elif u == ')': lv-=1 mn=min(mn,lv) #x[i][0],x[i][1]=lv,mn ...
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." — an excerpt from contest rules. A total of n participants took part in the contest (n ≥ k), and you already know their scores. Calculate how many ...
3
n,k=map(int,input().split()) A=list(map(int,input().split())) t=0 for i in range(n): if A[i]>=A[k-1] and A[i]>0: t+=1 print(t)
It is known that the area of a regular dodecagon inscribed in a circle of radius a is 3a^2. Given an integer r, find the area of a regular dodecagon inscribed in a circle of radius r. Constraints * 1 \leq r \leq 100 * r is an integer. Input Input is given from Standard Input in the following format: r Output ...
3
a=input() print(int(a)*int(a)*3)
An array b is called to be a subarray of a if it forms a continuous subsequence of a, that is, if it is equal to a_l, a_{l + 1}, …, a_r for some l, r. Suppose m is some known constant. For any array, having m or more elements, let's define it's beauty as the sum of m largest elements of that array. For example: * ...
3
n,m,k=map(int,input().split()) A=list(map(int,input().split())) B=list(enumerate(A)) B.sort(key=lambda x:x[1]) B.reverse() LIST=[0]*n ANS=0 for i in range(m*k): LIST[B[i][0]]=1 ANS+=B[i][1] ANSLIST=[] count=0 for i in range(n): if LIST[i]==1: count+=1 if count==m: ANSLIST.append(i+1...
You are given a bracket sequence s of length n, where n is even (divisible by two). The string s consists of n/2 opening brackets '(' and n/2 closing brackets ')'. In one move, you can choose exactly one bracket and move it to the beginning of the string or to the end of the string (i.e. you choose some index i, remov...
3
def MoveBrackets(n,s): total = 0 moves = [] for i in range(n): if s[i] == "(": total += 1 else: total -= 1 moves.append(total) return min(moves)*-1 Lista = [] total = int(input()) for i in range(total*2): All = [str(i) for i...
Little girl Susie went shopping with her mom and she wondered how to improve service quality. There are n people in the queue. For each person we know time ti needed to serve him. A person will be disappointed if the time he waits is more than the time needed to serve him. The time a person waits is the total time wh...
3
def main(): input() tot = res = 0 for t in sorted(map(int, input().split())): if t >= tot: res += 1 tot += t print(res) if __name__ == '__main__': main()
After the mysterious disappearance of Ashish, his two favourite disciples Ishika and Hriday, were each left with one half of a secret message. These messages can each be represented by a permutation of size n. Let's call them a and b. Note that a permutation of n elements is a sequence of numbers a_1, a_2, …, a_n, in ...
1
import sys if sys.subversion[0] == "PyPy": import io, atexit sys.stdout = io.BytesIO() atexit.register(lambda: sys.__stdout__.write(sys.stdout.getvalue())) sys.stdin = io.BytesIO(sys.stdin.read()) input = lambda: sys.stdin.readline().rstrip() RS = raw_input RA = lambda x=int: map(x, RS().split())...
Consider a conveyor belt represented using a grid consisting of n rows and m columns. The cell in the i-th row from the top and the j-th column from the left is labelled (i,j). Every cell, except (n,m), has a direction R (Right) or D (Down) assigned to it. If the cell (i,j) is assigned direction R, any luggage kept o...
3
t=int(input()) while t: t-=1 n,m=map(int,input().split()) b=[] c=0 for i in range(n): temp=list(map(str,input())) if temp[m-1]=="R": c+=1 if i==n-1: k=temp.count("D") print(k+c)
This winter is so cold in Nvodsk! A group of n friends decided to buy k bottles of a soft drink called "Take-It-Light" to warm up a bit. Each bottle has l milliliters of the drink. Also they bought c limes and cut each of them into d slices. After that they found p grams of salt. To make a toast, each friend needs nl ...
3
n,k,l,c,d,p,nl,np=input().split() var=[n,k,l,c,d,p,nl,np] n=int(n) k=int(k) l=int(l) c=int(c) d=int(d) p=int(p) nl=int(nl) np=int(np) e=min((k*l/(n*nl)),c*d/n,p/(n*np)) print(int(e))
A and B are preparing themselves for programming contests. B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code. Initially, the compiler displayed n compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix s...
3
n=int(input()) a1=[int(x) for x in input().split()] a2=[int(x) for x in input().split()] a3=[int(x) for x in input().split()] s1=sum(a1) s2=sum(a2) s3=sum(a3) print(s1-s2) print(s2-s3)