problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
You have array a1, a2, ..., an. Segment [l, r] (1 ≀ l ≀ r ≀ n) is good if ai = ai - 1 + ai - 2, for all i (l + 2 ≀ i ≀ r). Let's define len([l, r]) = r - l + 1, len([l, r]) is the length of the segment [l, r]. Segment [l1, r1], is longer than segment [l2, r2], if len([l1, r1]) > len([l2, r2]). Your task is to find a ...
3
""" ~~ author : dokueki ~~ created : 10~05~2020 """ import sys INT_MAX = sys.maxsize INT_MIN = -(sys.maxsize)-1 sys.setrecursionlimit(10**7) mod = 1000000007 def IOE(): sys.stdin = open("input.txt", "r") sys.stdout = open("output.txt", "w") def main(): n = int(sys.stdin.readline()) a = list(map(int...
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm: * if the last digit of the number is non-zero, she decreases the number by one; * if the last digit of the number is ze...
3
n, k = input().split() n = int(n) k = int(k) for i in range(k): u = n % 10 if u == 0: n = n/10 else: n = n - 1 print(int(n))
Tired of boring office work, Denis decided to open a fast food restaurant. On the first day he made a portions of dumplings, b portions of cranberry juice and c pancakes with condensed milk. The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes...
3
for _ in range(int(input())): a, b, c = map(int, input().split()) ans = 0 if a > 0: a -= 1 ans += 1 if b > 0: b -= 1 ans += 1 if c > 0: c -= 1 ans += 1 one, two, free = True, True, True if a > 0 and b > 0 and c <= a and c <= b: a -= 1 ...
One way to create a task is to learn from life. You can choose some experience in real life, formalize it and then you will get a new task. Let's think about a scene in real life: there are lots of people waiting in front of the elevator, each person wants to go to a certain floor. We can formalize it in the following...
3
n, k = map(int, input().split()) p = list(map(int, input().split())) p.sort() p.reverse() ans = 0 while p : ans += 2*(p[0]-1) if len(p) <= k : break else : p = p[k:] print(ans)
In this problem, you should process T testcases. For each testcase, you are given four integers N, M, A, B. Calculate \sum_{i = 0}^{N - 1} floor((A \times i + B) / M). Constraints * 1 \leq T \leq 100,000 * 1 \leq N, M \leq 10^9 * 0 \leq A, B < M Input Input is given from Standard Input in the following format: ...
3
# ε†™η΅Œγ—γΎγ—γŸγŒγ€δ½•γ‚‚γ‚γ‹γ£γ¦γ„γΎγ›γ‚“γ€‚ def floor_sum(n, m, a, b): "Return sum( floor( (A * i + B) / M ) for i in range(N) )" ret = 0 while True: if a >= m: ret += ((n - 1) * n) // 2 * (a // m) a %= m if b >= m: ret += n * (b // m) b %= m y_max = (a * n...
You've come to your favorite store Infinitesco to buy some ice tea. The store sells ice tea in bottles of different volumes at different costs. Specifically, a 0.25-liter bottle costs Q yen, a 0.5-liter bottle costs H yen, a 1-liter bottle costs S yen, and a 2-liter bottle costs D yen. The store has an infinite supply...
3
Q,H,S,D = map(int,input().split()) N = int(input()) S = min(4*Q,2*H,S) print(min(S*N,D*(N//2)+S*(N%2)))
Rudolf is on his way to the castle. Before getting into the castle, the security staff asked him a question: Given two binary numbers a and b of length n. How many different ways of swapping two digits in a (only in a, not b) so that bitwise OR of these two numbers will be changed? In other words, let c be the bitwise...
3
x=int(input()) y=list(input()) z=list(input()) a=[[i,j] for i,j in zip(y,z)] b=a.count(["0","0"]) c=a.count(["0","1"]) d=a.count(["1","0"]) e=a.count(["1","1"]) print(b*(d+e)+(c*d))
You have n students under your control and you have to compose exactly two teams consisting of some subset of your students. Each student had his own skill, the i-th student skill is denoted by an integer a_i (different students can have the same skills). So, about the teams. Firstly, these two teams should have the s...
3
# -*- coding: utf-8 -*- """ Created on Mon Apr 13 20:40:35 2020 @author: KSHITIZ ARORA """ import sys import math msg = sys.stdin.readlines() l=[] for i in msg: l.append (list (map(int, i.split()))) def size (l): st = set (l) s = {i:0 for i in st} for i in l: s[i] +=1 #print (s) m = ...
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
3
n=int(input("")) for j in range(0,n): s=input("") a=len(s) x=len(s) if(x>10): print("{}{}{}".format(s[0:1],a-2,s[a-1])) else: print(s)
Two boys decided to compete in text typing on the site "Key races". During the competition, they have to type a text consisting of s characters. The first participant types one character in v1 milliseconds and has ping t1 milliseconds. The second participant types one character in v2 milliseconds and has ping t2 millis...
3
line = list(map(int, input().split())) s = line[0] v1 = line[1] v2 = line[2] t1 = line[3] t2 = line[4] if v1 * s + 2 * t1 < v2 * s + 2 * t2: print('First') elif v1 * s + 2 * t1 > v2 * s + 2 * t2: print('Second') else: print('Friendship')
Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpr...
3
from fractions import Fraction def main(): a,b=map(int,input().split()) k=max(a,b) num=6-k+1 if num%6==0: print(1,'/',1,sep="") else: print(Fraction(num,6)) main()
ZS the Coder and Chris the Baboon are travelling to Udayland! To get there, they have to get on the special IOI bus. The IOI bus has n rows of seats. There are 4 seats in each row, and the seats are separated into pairs by a walkway. When ZS and Chris came, some places in the bus was already occupied. ZS and Chris are...
3
# -*- coding: utf-8 -*- """ Created on Sat Nov 16 21:00:22 2019 @author: LV """ n = int(input()) flag = 0 seat = [] for i in range(n): seat.append(input()) for i in range(len(seat)): if('OO' in seat[i]): seat[i] = seat[i].replace("OO", "++", 1) flag = 1 break if(flag): print('YES')...
The progress is not standing still in Berland. Recently all garbage containers in Bertown, the capital of Berland, were replaced by differentiated recycling bins, each accepting some category of waste. While this will definitely improve the ecological situation, for some citizens it's difficult to get used to the habit...
3
# -*- coding: utf-8 -*- """ Created on Thu Dec 31 14:57:56 2020 @author: SJK """ for _ in range(int(input())): c=list(map(int,input().rstrip().rsplit())) a=list(map(int,input().rstrip().rsplit())) c1,c2,c3,a1,a2,a3,a4,a5,a41,a51,a42,a52=c[0],c[1],c[2],a[0],a[1],a[2],a[3],a[4],0,0,0,0 if a4+a1>c1: ...
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 itertools #input n, m = (int(x) for x in input().split()) symbols = [] for i in range(n): symbols.append(list(input())) sym1 = [ '#', '*', '&'] # sym2 = set(list('1234567890')) # sym3 = set(list(string.ascii_lowercase)) # print(len(sym3)) min_shifts = 10000 for permutation in itertools.permutations(sym...
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem. Pete and Bi...
1
inp = int(raw_input()) if inp%2 == 0 and inp != 2: print "YES" else: print "NO"
A colored stripe is represented by a horizontal row of n square cells, each cell is pained one of k colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to k to repaint the cells. Input The first input line contains two integ...
1
''' Sun Oct 19 01:45:01 PDT 2014 135 Div2 prob c Greedy / Implentation ''' nums = map(int, raw_input('').split(' ')) n = nums[0] k = nums[1] pattern = raw_input('') def first(ch, ch2): start = ord('A') while start <= ord('Z'): if chr(start) != ch and chr(start) != ch2: return chr(start) ...
Nothing is eternal in the world, Kostya understood it on the 7-th of January when he saw partially dead four-color garland. Now he has a goal to replace dead light bulbs, however he doesn't know how many light bulbs for each color are required. It is guaranteed that for each of four colors at least one light is workin...
1
# cook your code here a = raw_input() p = {} count = {} for i in range(0, len(a)): cur = i % 4 if cur not in count: count[cur] = 0 if a[i] == '!': count[cur] += 1 else: if a[i] not in p: p[a[i]] = cur print str(count[p['R']]) + ' ' + str(count[p['B']]) +...
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
#!/usr/bin/env python3 from math import * from itertools import * from collections import * from bisect import * if __name__ == '__main__': x,y,c = map(int,input().split()) a = x//c x %= c b = y//c y %= c t = a+b if x+y >= c: if x > y: g = c-x else: ...
Once again, Boris needs the help of Anton in creating a task. This time Anton needs to solve the following problem: There are two arrays of integers a and b of length n. It turned out that array a contains only elements from the set \{-1, 0, 1\}. Anton can perform the following sequence of operations any number of ti...
3
def read_int(): return int(input().strip()) def read_ints(): return list(map(int, input().strip().split(' '))) def solve(): n = read_int() a = read_ints() b = read_ints() counter = {-1:0, 0:0, 1:0} for x in a: counter[x] += 1 for i in range(n-1, -1, -1): counter[a[i...
There are n candies in a row, they are numbered from left to right from 1 to n. The size of the i-th candy is a_i. Alice and Bob play an interesting and tasty game: they eat candy. Alice will eat candy from left to right, and Bob β€” from right to left. The game ends if all the candies are eaten. The process consists o...
3
for _ in range(int(input())): n=int(input()) x=list(map(int,input().split())) s1=0 s2=0 m=0 a=0 b=0 t=True start=0 end=n-1 while start<=end: if t: s1+=x[start] start+=1 else: s2+=x[end] end-=1 if s1>s2 and t: a+=s1 s2=0 t=False m+=1 elif s2>s1 and not t: b+=s2 s1=0 t=...
Mishka got a six-faced dice. It has integer numbers from 2 to 7 written on its faces (all numbers on faces are different, so this is an almost usual dice). Mishka wants to get exactly x points by rolling his dice. The number of points is just a sum of numbers written at the topmost face of the dice for all the rolls M...
3
a = int(input()) for i in range(a): s = int(input()) print(s // 2)
Taru and Chandu both are getting bored. So Taru thinks to play a game and he gives a number to Chandu and asks him to find the number of combinations formed by divisors in form of prime. For example:- For N = 36 divisor in form of prime are ( 2 , 2 , 3 , 3 ) Number of combinations formed by prime divisor of 36 a...
1
test=int(input()) import math for t in range(test): n=int(input()) x={} while n%2==0: x[2]=x.get(2,0)+1 n=n//2 i=3 while i<=math.sqrt(n): while n%i==0: x[i]=x.get(i,0)+1 n=n//i i+=2 if n>2: x[n]=x.get(n,0)+1 p=1 for i in x.k...
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point x(x > 0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order ...
3
n=int(input()) steps=1 if(n<=5): print(steps) else: while(n>5): steps += 1 n-=5 print(steps)
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
n, m = [int(x) for x in str(input()).split()] N = [int(x) for x in str(input()).split()] M = [int(x) for x in str(input()).split()] #find number of evens and odd Nodd = 0 Neven = 0 for elem in N: if(elem % 2 == 0): Neven += 1 else: Nodd += 1 Modd = 0 Meven = 0 for elem in M: if(ele...
There were n types of swords in the theater basement which had been used during the plays. Moreover there were exactly x swords of each type. y people have broken into the theater basement and each of them has taken exactly z swords of some single type. Note that different people might have taken different types of swo...
3
import math n = int(input()) a = list(map(int, input().split(' '))) maxa = max(a) b = list(map(lambda a_i: maxa-a_i, a)) gcd = b[0] for b_i in b: gcd = math.gcd(b_i, gcd) ans = 0 for b_i in b: ans += (b_i // gcd) print(ans, gcd)
Boboniu likes playing chess with his employees. As we know, no employee can beat the boss in the chess game, so Boboniu has never lost in any round. You are a new applicant for his company. Boboniu will test you with the following chess question: Consider a nΓ— m grid (rows are numbered from 1 to n, and columns are nu...
3
def fn(n, m, ii, jj): """Traverse the chess board.""" for j in range(jj, 0, -1): print(ii, j) #left for j in range(jj+1, m+1): print(ii, j) #right i = 1 #reset to 1st row dj = -1 while i <= n: if i == ii: i += 1 print(i, j) if not 0 < j + dj <= m: dj *= -1 i += 1 else: j += dj n, m, ii, jj = (...
You are given a string s consisting only of characters 0 and 1. A substring [l, r] of s is a string slsl + 1sl + 2... sr, and its length equals to r - l + 1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring. You have to determine the length of the longest balanc...
1
n = int(raw_input()) s = raw_input() a = [0]*n flag = 1; if s.count('1')==0 or s.count('0')== 0: flag = 0; for i in range(n): if s[i] == '0': a[i] = -1; else: a[i] = 1; d = {} a = [0]+a for i in range(1,n+1): a[i] += a[i-1]; if d.get(a[i]) == None: d[a[i]] = [i]; else: d[a[i]].append(i); if(flag == 0): p...
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended u...
3
__author__ = 'Utena' import collections s=input() if len(s)%2==1: print('No') exit(0) t1=t2=0 for i in range(len(s)): if s[i]=='-': if i%2==0:t1+=1 else:t2+=1 if t1==t2:print('Yes') else:print('No')
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). Consider a permutation p of length ...
3
n = int(input()) fact = 1 for i in range(1, n+1): fact = (fact*i)%1000000007 print(((fact) - 2**(n-1))%1000000007)
There are N people, conveniently numbered 1 through N. We want to divide them into some number of groups, under the following two conditions: * Every group contains between A and B people, inclusive. * Let F_i be the number of the groups containing exactly i people. Then, for all i, either F_i=0 or C≀F_i≀D holds. ...
3
N,A,B,C,D=map(int,input().split()) mod=10**9+7 factorial=[1] for i in range(1,1001): factorial.append((factorial[-1]*i)%mod) inverse=[pow(factorial[i],mod-2,mod) for i in range(1001)] Inverse=[[1] for i in range(1001)] for i in range(1001): for j in range(1,1001): Inverse[i].append((Inverse[i][-1]*in...
One day Alex was creating a contest about his friends, but accidentally deleted it. Fortunately, all the problems were saved, but now he needs to find them among other problems. But there are too many problems, to do it manually. Alex asks you to write a program, which will determine if a problem is from this contest ...
3
str = input() l = ["Danil", "Olya", "Slava", "Ann", "Nikita"] flag = 0 x = 0 for i in range(0,5): count = str.count(l[i]) if(count > 1): flag = 1 break elif(count == 1): x = x + 1 if(x == 1 and flag != 1): print("YES") else: print("NO")
There are n athletes in front of you. Athletes are numbered from 1 to n from left to right. You know the strength of each athlete β€” the athlete number i has the strength s_i. You want to split all athletes into two teams. Each team must have at least one athlete, and each athlete must be exactly in one team. You want...
3
t=int(input()) for i in range(t) : n=int(input()) s=list(map(int,input().split())) s.sort() x=s[1]-s[0] for i in range(2,n) : x=min(x,s[i]-s[i-1]) print(x)
Vanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed h and the processor smashes k centimeters of potato each second. If there are less than k centimeters remaining, than during this second processor smashes all the remaining potato. Vanya h...
3
n, h, k = map(int, input().split()) hei = list(map(int, input().split())) sec = 0 cur = 0 i = 0 while i < len(hei): sec += cur // k cur = cur % k if i < len(hei) and cur + hei[i] > h: sec += cur // k + 1 cur = 0 cur += hei[i] i += 1 while i < len(hei) and cur + hei[i] <= ...
Tom loves vowels, and he likes long words with many vowels. His favorite words are vowelly words. We say a word of length k is vowelly if there are positive integers n and m such that nβ‹… m = k and when the word is written by using n rows and m columns (the first row is filled first, then the second and so on, with each...
3
k = int(input()) if( k < 25): print(-1) exit() flag = 0 for i in range(5,int(k/5)+1): if(k/i == int(k/i) and k/i >= 5 ): n = int(k/i) m = i flag = 1 break if(flag == 0): print(-1) exit() a = ['a','e','i','o','u'] list = [] for i in range(5): list.append(a) a = [a[-1]]+a[:-1] for i in range(n...
Fox Ciel starts to learn programming. The first task is drawing a fox! However, that turns out to be too hard for a beginner, so she decides to draw a snake instead. A snake is a pattern on a n by m table. Denote c-th cell of r-th row as (r, c). The tail of the snake is located at (1, 1), then it's body extends to (1,...
3
line=input() N,M=line.split() n,m=int(N),int(M) list1=[] c=n//2+1 list3=["."]*(m-1) list3.append("#") list4=["#"] list4.extend(["."]*(m-1)) for i in range(0,c,1): list1.append(["#"]*m) for i in range(1,n-c+1,1): if i%2!=0: list1.insert(2*i-1,list3) else: list1.insert(2*i-1,list4) for i in ra...
Let's denote a k-step ladder as the following structure: exactly k + 2 wooden planks, of which * two planks of length at least k+1 β€” the base of the ladder; * k planks of length at least 1 β€” the steps of the ladder; Note that neither the base planks, nor the steps planks are required to be equal. For example...
3
for t in range(int(input().strip())): n = int(input()) plks = sorted(list(map(int, input().strip().split())), reverse=True) if n<3: print(0) continue else: print(max(min(plks[1]-1, n-2), 0))
Luke Skywalker gave Chewbacca an integer number x. Chewbacca isn't good at numbers but he loves inverting digits in them. Inverting digit t means replacing it with digit 9 - t. Help Chewbacca to transform the initial number x to the minimum possible positive number by inverting some (possibly, zero) digits. The decim...
1
num = raw_input() result = "" if num[0] == '9': result += num[0] elif ((9 - int(num[0])) < int(num[0])): result += str(9 - int(num[0])) else: result += num[0] for i in xrange(1, len(num), 1): if ((9 - int(num[i])) < int(num[i])): result += str(9 - int(num[i])) else: result += num[i] print result
There are three cells on an infinite 2-dimensional grid, labeled A, B, and F. Find the length of the shortest path from A to B if: * in one move you can go to any of the four adjacent cells sharing a side; * visiting the cell F is forbidden (it is an obstacle). Input The first line contains an integer t (1 ≀ ...
3
for _ in range(int(input())): a =input() x1,y1 = map(int,input().split()) x2,y2 = map(int,input().split()) f1,f2 = map(int,input().split()) if x1!=x2 and y1 != y2: print(abs(x2-x1)+abs(y2-y1)) continue if x1==x2: if f1!=x1: print(abs(y2-y1)) conti...
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
#785a n = int(input()) face = {"Tetrahedron": 4, "Cube": 6, "Octahedron": 8, "Dodecahedron": 12, "Icosahedron": 20} sum=0 while n!=0: s = input() if s in face.keys(): sum+=face.get(s) n-=1 print(sum)
Write a program which converts uppercase/lowercase letters to lowercase/uppercase for a given string. Constraints * The length of the input string < 1200 Input A string is given in a line. Output Print the converted string in a line. Note that you do not need to convert any characters other than alphabetical lett...
3
S = input() for s in S: s = s.upper() if s.lower() == s else s.lower() print(s, end='') 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
# -*- coding: utf-8 -*- """ Created on Wed Oct 23 14:44:07 2019 @author: sihan """ name=input() L=len(name) for i in range(1,len(name)): if name[i] in name[:i]: L-=1 if L%2==0: print('CHAT WITH HER!') else: print('IGNORE HIM!')
Today, Mezo is playing a game. Zoma, a character in that game, is initially at position x = 0. Mezo starts sending n commands to Zoma. There are two possible commands: * 'L' (Left) sets the position x: =x - 1; * 'R' (Right) sets the position x: =x + 1. Unfortunately, Mezo's controller malfunctions sometimes. ...
3
#1285A - Mezo Playing Zoma a = int(input()) b = input() Lefts = b.count('L') Rights = b.count('R') Count = 1 if Lefts > 0: Count += Lefts if Rights > 0: Count += Rights print(Count)
Sengoku still remembers the mysterious "colourful meteoroids" she discovered with Lala-chan when they were little. In particular, one of the nights impressed her deeply, giving her the illusion that all her fancies would be realized. On that night, Sengoku constructed a permutation p1, p2, ..., pn of integers from 1 t...
3
n=int(input()) a=list(map(int,input().split())) b=list(map(int,input().split())) k=[0 for i in range(len(a))] m=list(range(1,len(a)+1)) for i in range(len(a)): if a[i]==b[i]: k[i]=a[i] m.remove(a[i]) if len(m)==1: for i in range(len(a)): if k[i]==0: k[i]=m[0] else: r=[] for i in range(len(a)): if k[i]==...
Vasya takes part in the orienteering competition. There are n checkpoints located along the line at coordinates x1, x2, ..., xn. Vasya starts at the point with coordinate a. His goal is to visit at least n - 1 checkpoint in order to finish the competition. Participant are allowed to visit checkpoints in arbitrary order...
1
R=lambda:map(int,raw_input().split()) n,a=R() x=sorted(R()) def f(i,j): return abs(a-x[i])+abs(x[i]-x[j]) if n>1: print min(f(0,-2),f(1,-1),f(-2,0),f(-1,1)) else: print 0
How many hours do we have until New Year at M o'clock (24-hour notation) on 30th, December? Constraints * 1≀M≀23 * M is an integer. Input Input is given from Standard Input in the following format: M Output If we have x hours until New Year at M o'clock on 30th, December, print x. Examples Input 21 Output...
1
M = input() H_PER_D = 24 print H_PER_D * 2 - M
Vanya wants to pass n exams and get the academic scholarship. He will get the scholarship if the average grade mark for all the exams is at least avg. The exam grade cannot exceed r. Vanya has passed the exams and got grade ai for the i-th exam. To increase the grade for the i-th exam by 1 point, Vanya must write bi es...
3
n,r,a=[int(x) for x in input().split()] exams=[] grades=0 essays=0 for i in range(n): grade,essay=[int(x) for x in input().split()] grades+=grade exams.append([grade,essay]) if grades>=n*a: print(0) else: exams.sort(key=lambda x:x[1]) needs=n*a-grades while needs>0: for i in exams: ...
Just in case somebody missed it: this winter is totally cold in Nvodsk! It is so cold that one gets funny thoughts. For example, let's say there are strings with the length exactly n, based on the alphabet of size m. Any its substring with length equal to k is a palindrome. How many such strings exist? Your task is to ...
1
n, m, k = map(int , raw_input().split()) if k == 1 or n < k: x = n elif n == k: x = n//2 + n%2 else: x = 1 + k%2 print (m ** x)%(10 ** 9 + 7)
Alice and Bob play a game. They have a binary string s (a string such that each character in it is either 0 or 1). Alice moves first, then Bob, then Alice again, and so on. During their move, the player can choose any number (not less than one) of consecutive equal characters in s and delete them. For example, if the...
3
ts = int(input()) strs = [input() for t in range(ts)] strs = [s.split("0") for s in strs] strs = [sorted([len(s1) for s1 in s if len(s1)>0], reverse=True) for s in strs] scores = [sum([s[i] for i in range(0, len(s), 2)]) for s in strs] list(map(print, scores))
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of n students doing yet another trick. Let's assume that all these students are numbered from 1 to n. The teacher came to student a and put a hole in his badge. The student, ...
3
n = int(input()) + 1 g = [0, *map(int, input().split())] r = [0] * n for i in range(1, n): if not r[i]: j = i while not r[j]: r[j], j = j, g[j] if i != j: k = r[j] while i != j: r[i], i = k, g[i] print(' '.join(map(str, r[1:])))
After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≀ si ≀ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum nu...
3
a=int(input()) l=list(map(int,input().split())) k1=l.count(1) k2=l.count(2) k3=l.count(3) k4=l.count(4) k=k4+k3 if k1<k3: k1=0 else: k1=k1-k3 k=k+k2//2 if k2%2!=0: k1=k1+2 k=k+k1//4 if k1%4!=0: k+=1 print(k)
Denis was very sad after Nastya rejected him. So he decided to walk through the gateways to have some fun. And luck smiled at him! When he entered the first courtyard, he met a strange man who was selling something. Denis bought a mysterious item and it was... Random permutation generator! Denis could not believed hi...
3
from sys import stdin, stdout t = int(stdin.readline()) for _ in range(t): n = int(stdin.readline()) arr = map(int, stdin.readline().split()) max_ = next(arr) last = max_ for i in arr: if last + 1 == i: last = i continue if max_ < i: print("No") ...
You are given two arrays of integers a_1,…,a_n and b_1,…,b_m. Your task is to find a non-empty array c_1,…,c_k that is a subsequence of a_1,…,a_n, and also a subsequence of b_1,…,b_m. If there are multiple answers, find one of the smallest possible length. If there are still multiple of the smallest possible length, f...
3
import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writa...
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
from math import log from collections import defaultdict, deque from sys import stdin,stdout from bisect import bisect_left, bisect_right from copy import deepcopy inp=lambda : int(stdin.readline()) sip=lambda : stdin.readline() mulip =lambda : map(int, stdin.readline().split()) lst=lambda : list(map(float,stdin.readl...
This contest, AtCoder Beginner Contest, is abbreviated as ABC. When we refer to a specific round of ABC, a three-digit number is appended after ABC. For example, ABC680 is the 680th round of ABC. What is the abbreviation for the N-th round of ABC? Write a program to output the answer. Constraints * 100 ≀ N ≀ 999 I...
3
n=input() print('ABC'+n)
There are N squares aligned in a row. The i-th square from the left contains an integer a_i. Initially, all the squares are white. Snuke will perform the following operation some number of times: * Select K consecutive squares. Then, paint all of them white, or paint all of them black. Here, the colors of the squares...
3
N,K = map(int,input().split()) src = list(map(int,input().split())) cums = [0] cump = [0] for a in src: cums.append(cums[-1] + a) cump.append(cump[-1] + max(0,a)) ans = 0 for i in range(N-K+1): tmp = cump[i] tmp += max(0, cums[i+K] - cums[i]) tmp += cump[N] - cump[i+K] ans = max(tmp, ans) prin...
You are given an array a consisting of n integers. You have to find the length of the smallest (shortest) prefix of elements you need to erase from a to make it a good array. Recall that the prefix of the array a=[a_1, a_2, ..., a_n] is a subarray consisting several first elements: the prefix of the array a of length k...
3
for _ in range(int(input())): n=int(input()) s=list(map(int,input().split())) ans=n-1 while ans and s[ans]<=s[ans-1]:ans-=1 while ans and s[ans]>=s[ans-1]:ans-=1 print(ans)
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). ...
1
n=input();ans=0 nums=map(int,raw_input().split());mx=max(nums) for a in nums: ans+=(mx-a) print ans
You are given an array a consisting of n integers. You can perform the following operations arbitrary number of times (possibly, zero): 1. Choose a pair of indices (i, j) such that |i-j|=1 (indices i and j are adjacent) and set a_i := a_i + |a_i - a_j|; 2. Choose a pair of indices (i, j) such that |i-j|=1 (indice...
3
def most_freq(a): s = {} for i in range(len(a)): s[a[i]]=0 for i in range(len(a)): s[a[i]]+=1 l = 0 d = 0 for key in s: if(s[key]>l): l=s[key] d = key return d n = int(input()) a = list(map(int,input().split())) s = most_freq(a) p = a.index(s) ...
Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k. In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10k. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result ...
3
n, k = input().split() n = list(n) st_len = len(n) k = int(k) res = 0 while k > 0 and n: if n[-1] == '0': k -= 1 else: res += 1 n.pop() if n: print(res) else: print(st_len - 1)
Let's write all the positive integer numbers one after another from 1 without any delimiters (i.e. as a single string). It will be the infinite sequence starting with 123456789101112131415161718192021222324252627282930313233343536... Your task is to print the k-th digit of this sequence. Input The first and only lin...
3
# ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode...
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that. For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two ...
3
n=int(input()) if(n%2==0): print(4,n-4,sep=' ') else: print(9,n-9,sep=' ')
Let's denote a function f(x) in such a way: we add 1 to x, then, while there is at least one trailing zero in the resulting number, we remove that zero. For example, * f(599) = 6: 599 + 1 = 600 β†’ 60 β†’ 6; * f(7) = 8: 7 + 1 = 8; * f(9) = 1: 9 + 1 = 10 β†’ 1; * f(10099) = 101: 10099 + 1 = 10100 β†’ 1010 β†’ 101. ...
3
import sys n = int(input()) s = set() s.add(n) for i in range(50000): n += 1 while n % 10 == 0 and n != 0: n /= 10 s.add(n) print(len(s))
Polycarpus has a ribbon, its length is n. He wants to cut the ribbon in a way that fulfils the following two conditions: * After the cutting each ribbon piece should have length a, b or c. * After the cutting the number of ribbon pieces should be maximum. Help Polycarpus and find the number of ribbon pieces ...
3
n, a, b, c = map(int, input().split()) dp = [None for i in range(n + 1)] dp[0] = 0 for i in range(1, n + 1): for j in [a, b, c]: if i - j >= 0 and dp[i - j] != None: if dp[i] == None: dp[i] = 0 dp[i] = max(dp[i], 1 + dp[i - j]) print(dp[n])
When Petya went to school, he got interested in large numbers and what they were called in ancient times. For instance, he learned that the Russian word "tma" (which now means "too much to be counted") used to stand for a thousand and "tma tmyschaya" (which literally means "the tma of tmas") used to stand for a million...
1
from math import log k = int(raw_input()) l = int(raw_input()) a = log(l, k) if l == k**int(a) : print "YES" print int(log(l, k)) - 1 else : print "NO"
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()) shapes = {'Tetrahedron': 4, 'Cube': 6, 'Octahedron': 8, 'Dodecahedron': 12, 'Icosahedron': 20} ans = 0 for _ in range(n): ans += shapes[input()] print(ans)
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
a = [0]*10000 s = input() for i in range(len(s)): a[ord(s[i])] = 1; ans = 0 for x in range(1000): if a[x]: ans = ans+1; if ans % 2 != 0: print("IGNORE HIM!") else: print("CHAT WITH HER!")
A university student, Takahashi, has to take N examinations and pass all of them. Currently, his readiness for the i-th examination is A_{i}, and according to his investigation, it is known that he needs readiness of at least B_{i} in order to pass the i-th examination. Takahashi thinks that he may not be able to pass...
3
N=int(input()) A=[int(x) for x in input().split()] B=[int(y) for y in input().split()] ans=0 task=0 power=[] for i in range(N): if A[i]< B[i]: ans+=1 task+=(B[i]-A[i]) else: power.append(A[i]-B[i]) power.sort(reverse=True) for i in range(len(power)): if task<=0: break else: task-=power[i]...
You are given two arrays of integers a_1,…,a_n and b_1,…,b_m. Your task is to find a non-empty array c_1,…,c_k that is a subsequence of a_1,…,a_n, and also a subsequence of b_1,…,b_m. If there are multiple answers, find one of the smallest possible length. If there are still multiple of the smallest possible length, f...
3
for _ in range(int(input())): n, m = map(int, input().split(' ') ) A = list( map(int, input().split(' ')) ) B = list( map(int, input().split(' ')) ) l = n flag = 0 for i in range(n): if(A[i] in B): flag = 1 print("YES") print("{} {}".format("1", str(...
There are n bags with candies, initially the i-th bag contains i candies. You want all the bags to contain an equal amount of candies in the end. To achieve this, you will: * Choose m such that 1 ≀ m ≀ 1000 * Perform m operations. In the j-th operation, you will pick one bag and add j candies to all bags apart ...
3
a=int(input()) for i in range(a): b=int(input()) arr=[str(i) for i in range(b,1,-1)] arr=arr[::-1] print(len(arr)) print(' '.join(arr))
A tennis tournament with n participants is running. The participants are playing by an olympic system, so the winners move on and the losers drop out. The tournament takes place in the following way (below, m is the number of the participants of the current round): * let k be the maximal power of the number 2 such ...
1
n,b,p=map(int,raw_input().split()) x=b*2+1 x=x*(n-1) print x,n*p
Takahashi is solving quizzes. He has easily solved all but the last one. The last quiz has three choices: 1, 2, and 3. With his supernatural power, Takahashi has found out that the choices A and B are both wrong. Print the correct choice for this problem. Constraints * Each of the numbers A and B is 1, 2, or 3. * ...
3
print(min(3, 7-(1<<(int(input())-1))-(1<<(int(input())-1))))
Write a program which reads a sequence and prints it in the reverse order. Note θ§£θͺ¬ Constraints * n ≀ 100 * 0 ≀ ai < 1000 Input The input is given in the following format: n a1 a2 . . . an n is the size of the sequence and ai is the ith element of the sequence. Output Print the reversed sequence in a line. P...
3
n = int(input()) print(*input().split()[-1::-1])
You are given a string s. Each character is either 0 or 1. You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met. You may eras...
1
q = int(raw_input()) while q: q-=1 s = raw_input() beg = 0 while beg < len(s) and s[beg] == '0': beg+=1 end = len(s) - 1 while beg < len(s) and s[end] == '0': end-=1 count = 0 for c in s[beg:end+1]: if c == '0': count+=1 print count
You are given an array a consisting of n integer numbers. You have to color this array in k colors in such a way that: * Each element of the array should be colored in some color; * For each i from 1 to k there should be at least one element colored in the i-th color in the array; * For each i from 1 to k al...
3
n, k = list(map(int, input().split())) a = list(map(int, input().split())) c = [(a[i], i) for i in range(n)] c.sort() arr = [[] for _ in range(n)] cur = 0 colors = [None] * n for i in c: if (len(arr[cur]) > 0) and (arr[cur][-1] == i[0]): print("NO") exit(0) arr[cur].append(i[0]) colors[i[1]...
A lot of people in Berland hates rain, but you do not. Rain pacifies, puts your thoughts in order. By these years you have developed a good tradition β€” when it rains, you go on the street and stay silent for a moment, contemplate all around you, enjoy freshness, think about big deeds you have to do. Today everything ...
3
from math import pi d,h,v,e = map(int,input().split()) r = d/2 low = 0 high = 10005 pos = -1 while low <= high: mid = (low+high)/2 f = False volume = (pi)*(r)*(r)*(h+(mid*e)) drink = mid*v if drink >= volume: pos = mid high = mid-0.0000001 else: low = mid+0.0000001 ...
After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≀ si ≀ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum nu...
3
n = int(input()) s = input() l = s.split(" ") c = 0 x4 = l.count('4') x3 = l.count('3') x2 = l.count('2') x1 = l.count('1') c += x4 if x3 == x1: c += x1 x1 = 0 x3 = 0 if x3 != 0 and x1 != 0: if x3 > x1: c += x1 x3 = x3 - x1 x1 = 0 elif x3 < x1: c += x3 x1 ...
There are n cats in a line, labeled from 1 to n, with the i-th cat at position i. They are bored of gyrating in the same spot all day, so they want to reorder themselves such that no cat is in the same place as before. They are also lazy, so they want to minimize the total distance they move. Help them decide what cat ...
3
for s in[*open(0)][1:]: n=int(s);*a,=range(1,n+1) for i in range(1,n,2):a[i-1],a[i]=a[i],a[i-1] if n%2:a[-1],a[-3]=a[-3],a[-1] print(*a)
One day, n people (n is an even number) met on a plaza and made two round dances, each round dance consists of exactly n/2 people. Your task is to find the number of ways n people can make two round dances if each round dance consists of exactly n/2 people. Each person should belong to exactly one of these two round da...
3
import sys import math n = int(sys.stdin.readline()) v = math.factorial(n//2-1) x = math.factorial(n)//pow(math.factorial(n//2),2) print((v*v*x)//2)
Polygon is not only the best platform for developing problems but also a square matrix with side n, initially filled with the character 0. On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly 2...
3
# import math # from sys import stdin, stdout def main(): n = int(input()) arr = [] for _ in range(n): arr.append(list(str(input()))) for i in range(n): for j in range(n): if arr[i][j]=='1': if i!=n-1 and j!=n-1 and arr[i+1][j]!='1' and arr[i][j+1]!='1': print("NO") return print("YES") retur...
You have n students under your control and you have to compose exactly two teams consisting of some subset of your students. Each student had his own skill, the i-th student skill is denoted by an integer a_i (different students can have the same skills). So, about the teams. Firstly, these two teams should have the s...
3
t = int(input()) for x in range(t): n = int(input()) eq = 1 noteq = 0 a = list(sorted(list(map(int,input().split())))) tmpeq = 1 for i in range(1,n): if a[i] == a[i-1]: tmpeq += 1 else: noteq += 1 eq = max(eq,tmpeq) tmpeq = 1 eq = max(eq,tmpeq) tmpeq = 1 if eq - noteq >= 2: noteq += 1 eq -=...
While walking down the street Vanya saw a label "Hide&Seek". Because he is a programmer, he used & as a bitwise AND for these two words represented as a integers in base 64 and got new word. Now Vanya thinks of some string s and wants to know the number of pairs of words of length |s| (length of s), such that their bit...
3
ls = [0]*100010 for i in range(64): for j in range(64): ls[i&j] += 1 s = input() ss = 1 for i in s: if ord(i) >= ord('a') and ord(i) <= ord('z'): ss *= ls[ord(i) - ord('a') + 36] elif ord(i) >= ord('A') and ord(i) <= ord('Z'): ss *= ls[ord(i) - ord('A') + 10] elif ord(i) >= ord('...
There are n pillars aligned in a row and numbered from 1 to n. Initially each pillar contains exactly one disk. The i-th pillar contains a disk having radius a_i. You can move these disks from one pillar to another. You can take a disk from pillar i and place it on top of pillar j if all these conditions are met: ...
3
# 1197B n = int(input()) x = list(map(int,input().split())) flag = True max_val = max(x) max_pos = x.index(max_val) for i in range(max_pos + 1): if i<max_pos-1 and x[i+1] < x[i]: #print("NO") flag = False for i in range(max_pos,n+1): if i<n-1 and x[i+1] > x[i]: #print("NO") flag ...
You are given a long decimal number a consisting of n digits from 1 to 9. You also have a function f that maps every digit from 1 to 9 to some (possibly the same) digit from 1 to 9. You can perform the following operation no more than once: choose a non-empty contiguous subsegment of digits in a, and replace each digi...
1
""" Author : raj1307 - Raj Singh Institute : Jalpaiguri Government Engineering College Date : 26.04.19 """ from __future__ import division, print_function import itertools,os,sys #from collections import deque, Counter, OrderedDict,defaultdict #from heapq import nsmallest, nlargest, heapify, #heappop ,heappush,...
n heroes fight against each other in the Arena. Initially, the i-th hero has level a_i. Each minute, a fight between two different heroes occurs. These heroes can be chosen arbitrarily (it's even possible that it is the same two heroes that were fighting during the last minute). When two heroes of equal levels fight,...
3
tests = int(input()) for t in range(tests): n = int(input()) heroes = list(map(int, input().split(' '))) m = min(heroes) print(sum([1 for x in heroes if x > m]))
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
input() z=[0]*(10**5+1) for i in map(int,input().split()): z[i]+=i a=b=0 for i in z: a,b=max(a,i+b),a print(a)
Ashish and Vivek play a game on a matrix consisting of n rows and m columns, where they take turns claiming cells. Unclaimed cells are represented by 0, while claimed cells are represented by 1. The initial state of the matrix is given. There can be some claimed cells in the initial state. In each turn, a player must ...
3
import sys input = sys.stdin.readline I = lambda : list(map(int,input().split())) t, = I() for _ in range(t): n,m=I() l=[];r=[0]*n;c=[0]*m for i in range(n): k=I() l.append(k) for j in range(m): if k[j]: r[i]=1;c[j]=1 ct=0 for i in range(n): for j in range(m): if r[i]==0 and c[j]==0: ct+=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 = list(map(int,(input().split()))) a = 0 for i in range(1,w+1): a = a + k*i borrow = a - n if borrow < 0: print("0") else: print(borrow)
Vasya has recently got a job as a cashier at a local store. His day at work is L minutes long. Vasya has already memorized n regular customers, the i-th of which comes after t_{i} minutes after the beginning of the day, and his service consumes l_{i} minutes. It is guaranteed that no customer will arrive while Vasya is...
3
n,l,a=map(int,input().split()) s=c=0 if n==0: c=l//a elif n>0: for i in range(n): t,r=map(int,input().split()) c+=(t-s)//a s=t+r c+=(l-s)//a print(c)
Nastya just made a huge mistake and dropped a whole package of rice on the floor. Mom will come soon. If she sees this, then Nastya will be punished. In total, Nastya dropped n grains. Nastya read that each grain weighs some integer number of grams from a - b to a + b, inclusive (numbers a and b are known), and the wh...
3
def checkPoss(n,a,b,c,d): L = n*(a-b) R = n*(a+b) if(R < (c-d) or L > c+d): print("No") else: print("Yes") if __name__ == "__main__": t = int(input()) for i in range(t): n,a,b,c,d = map(int, input().split()) checkPoss(n,a,b,c,d)
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated. The language is that peculiar as it has exactly one variable, called x. Also, there are two operations: * Operation ++ increases the value of variable x by 1. * Operation -- decreases the value of variable x by 1....
3
try: t=int(input()) i=0 n=0 while i<t: k=input() if k[0]=='+' or k[1]=='+': n+=1 else: n-=1 i+=1 print(n) except: pass
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
3
if __name__ == "__main__": n = int(input()) i = 0 while i < n: word = str(input()) if len(word) > 10: result = [word[0]] result.append(str(len(word[1:len(word) - 1]))) result.append(word[-1]) print(''.join(result)) else: print(word) i += 1
You've got a 5 Γ— 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix: 1....
3
if __name__ == '__main__': l=[] for i in range(5): n=[int(x) for x in input().split()] l.append(n) for i in range(5): for j in range(5): if(l[i][j]==1): print(abs(i-2)+abs(j-2)) break
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=input() a=n.split() for i in range(len(a)) : a[i]=int(a[i]) t=(a[1]*a[2])//a[-2] c=(a[3]*a[4]) m=a[-3]//a[-1] n=a[4] def minp (a) : k=a[0] for i in a : if a[i]<k: k=a[i] return(int(k/len(a))) x=[t,c,m] w=min(x) print(w//(a[0]))
Each day in Berland consists of n hours. Polycarp likes time management. That's why he has a fixed schedule for each day β€” it is a sequence a_1, a_2, ..., a_n (each a_i is either 0 or 1), where a_i=0 if Polycarp works during the i-th hour of the day and a_i=1 if Polycarp rests during the i-th hour of the day. Days go ...
3
n=int(input()) l=list(map(int,input().split())) for i in range(n-1): l.append(l[i]) dp = [] c=0 ans = 0 for i in l: if i==1: c+=1 else: ans = max(ans,c) c=0 ans = max(ans,c) print(ans)
Theatre Square in the capital city of Berland has a rectangular shape with the size n Γ— m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a Γ— a. What is the least number of flagstones needed to pave the Square? It'...
1
input = raw_input().split() n, m, a = int(input[0]), int(input[1]), int(input[2]) if n%a == 0: n = n/a else: n = 1 + n/a if m%a==0: m = m/a else: m = 1 + m/a print n*m
While sailing on a boat, Inessa noticed a beautiful water lily flower above the lake's surface. She came closer and it turned out that the lily was exactly H centimeters above the water surface. Inessa grabbed the flower and sailed the distance of L centimeters. Exactly at this point the flower touched the water surfac...
1
#code h,l = (raw_input().split()) h = float(h) l = float(l) print (l*l -h*h)/(2*h)
Welcome to Codeforces Stock Exchange! We're pretty limited now as we currently allow trading on one stock, Codeforces Ltd. We hope you'll still be able to make profit from the market! In the morning, there are n opportunities to buy shares. The i-th of them allows to buy as many shares as you want, each at the price o...
3
def main(): n, m, r = map(int, input().split()) s = [int(x) for x in input().split()] b = [int(x) for x in input().split()] if min(s) < max(b): print(r % min(s) + (r // min(s)) * max(b)) else: print(r) if __name__ == "__main__": main()
The protection of a popular program developed by one of IT City companies is organized the following way. After installation it outputs a random five digit number which should be sent in SMS to a particular phone number. In response an SMS activation code arrives. A young hacker Vasya disassembled the program and foun...
1
n=list(raw_input()) t=n[1] n[1]=n[2] n[2]=n[4] n[4]=t n=''.join(n) n=int(n)**5 n=str(n) n=n[-5:] print n
You are given an array of integers a_1,a_2,…,a_n. Find the maximum possible value of a_ia_ja_ka_la_t among all five indices (i, j, k, l, t) (i<j<k<l<t). Input The input consists of multiple test cases. The first line contains an integer t (1≀ t≀ 2 β‹… 10^4) β€” the number of test cases. The description of the test cases ...
3
import itertools import functools t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) pos_a = list(filter(lambda x: x >= 0, a)) neg_a = list(filter(lambda x: x < 0, a)) pos_a.sort() neg_a.sort(reverse=True) if not len(pos_a): print(functools.red...
The mayor of Amida, the City of Miracle, is not elected like any other city. Once exhausted by long political struggles and catastrophes, the city has decided to leave the fate of all candidates to the lottery in order to choose all candidates fairly and to make those born under the lucky star the mayor. I did. It is a...
3
while True: n, m, a = list(map(int, input().split())) if n == 0: break hpq = [] for i in range(m): h, p, q = list(map(int, input().split())) hpq.append([h, p, q]) hpq = sorted(hpq, key=lambda x: x[0], reverse=True) for i in reversed(range(1, hpq[0][0] + 1)): for j...