problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
Ternary numeric notation is quite popular in Berland. To telegraph the ternary number the Borze alphabet is used. Digit 0 is transmitted as «.», 1 as «-.» and 2 as «--». You are to decode the Borze code, i.e. to find out the ternary number given its representation in Borze alphabet. Input The first line contains a nu...
3
b=input() s='' a='' for i in b: s+=i if len(s)==2: if s=='..': a+='00' s='' elif s=='.-': a+='0' s='-' elif s=='--': a+='2' s='' elif s=='-.': a+='1' s='' if len(s)==1: a+='0' ...
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line. Unfortunately, from time to ti...
3
s=input() s=set(s) if len(s)<3: print(0) elif len(s)==3: print(1) else: print(len(s)-4)
You are given an array a consisting of n integers. Your task is to say the number of such positive integers x such that x divides each number from the array. In other words, you have to find the number of common divisors of all elements in the array. For example, if the array a will be [2, 4, 6, 2, 10], then 1 and 2 ...
3
from math import gcd, sqrt def findDivisors(n): l = [] for i in range(1, int(sqrt(n) + 1)): if (n%i==0): if (n==i*i): l.append(i) else : l.append(i) l.append(n//i) return l n = int(input()) A = list(map(int, input().split())) g = A[0] for i ...
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() if a[0].islower() == 1 and a[1:].isupper() == 1 or a[0].islower() == 1 and len(a) == 1: print(a[0].upper() + a[1:].lower()) elif a.isupper() == 1: print(a.lower()) else: print(a)
Count the pairs of length-N sequences consisting of integers between 1 and M (inclusive), A_1, A_2, \cdots, A_{N} and B_1, B_2, \cdots, B_{N}, that satisfy all of the following conditions: * A_i \neq B_i, for every i such that 1\leq i\leq N. * A_i \neq A_j and B_i \neq B_j, for every (i, j) such that 1\leq i < j\leq N...
3
N, M = map(int, input().split()) ans = 0 mod = 10**9+7 def modinv(a, mod=10**9+7): return pow(a, mod-2, mod) fac = [0]*(M+1) fac[0] = 1 fac[1] = 1 for i in range(2,M+1): fac[i] = fac[i-1] * i % mod #nCr (mod p) def combi(n,r,mod=10**9+7): return( ( fac[n] * modinv(fac[r]) )%mod * modinv(fac[n-r]) % mod) f...
The Fair Nut lives in n story house. a_i people live on the i-th floor of the house. Every person uses elevator twice a day: to get from the floor where he/she lives to the ground (first) floor and to get from the first floor to the floor where he/she lives, when he/she comes back home in the evening. It was decided ...
3
n=int(input()) a=[int(x) for x in input().split()] energy=0 min_energy=100000000000000 for i in range(1,n+1): k=1 for item in a: energy+=4*(max(i,k)-1)*item k+=1 if energy<min_energy: min_energy=energy print(min_energy)
A progress bar is an element of graphical interface that displays the progress of a process for this very moment before it is completed. Let's take a look at the following form of such a bar. A bar is represented as n squares, located in line. To add clarity, let's number them with positive integers from 1 to n from t...
3
from math import ceil, floor def main(): n, k, t = map(int, input().split()) s = t * n * k // 100 ans = [] cur_sum = s for _ in range(n): if cur_sum - k >= 0: ans.append(k) cur_sum -= k else: ans.append(cur_sum) cur_sum = 0 print...
One Sunday Petr went to a bookshop and bought a new book on sports programming. The book had exactly n pages. Petr decided to start reading it starting from the next day, that is, from Monday. Petr's got a very tight schedule and for each day of the week he knows how many pages he will be able to read on that day. Som...
3
n = int(input()) arr = list(map(int, input().split())) day = 0 #print(arr) while n > 0: day += 1 if day == 8: day = 1 #print("it's day", day) #print("we read", arr[day-1], "pages") n -= arr[day-1] #print("now there is ", n, "left") #print() print(day)
You are given an integer N. Consider all possible segments on the coordinate axis with endpoints at integer points with coordinates between 0 and N, inclusive; there will be <image> of them. You want to draw these segments in several layers so that in each layer the segments don't overlap (they might touch at the endp...
3
n = int(input()) res = 0 while n > 0: res += n n -= 2 print(res)
Vasya owns a cornfield which can be defined with two integers n and d. The cornfield can be represented as rectangle with vertices having Cartesian coordinates (0, d), (d, 0), (n, n - d) and (n - d, n). <image> An example of a cornfield with n = 7 and d = 2. Vasya also knows that there are m grasshoppers near the fie...
3
n,d = map(int,input().split()) m = int(input()) a = [] for i in range(m): x1,y1 = map(int,input().split()) t1 = x1+y1 t2 = x1-y1 if t1>=d and t1<=(2*n-d) and t2>=(-d) and t2<=d: a.append('YES') else: a.append('NO') for j in a: print(j)
Vanya is managed to enter his favourite site Codehorses. Vanya uses n distinct passwords for sites at all, however he can't remember which one exactly he specified during Codehorses registration. Vanya will enter passwords in order of non-decreasing their lengths, and he will enter passwords of same length in arbitrar...
3
[num_passwords, num_tries] = [int(item) for item in input().split()] passwords = [] for _ in range(num_passwords): passwords.append(len(input())) password_len = len(input()) passwords.sort() min = 0 max = len(passwords) count = 0 time = 0 for i in range(len(passwords)): time +=1 if passwords[i] == passwo...
Ivan has number b. He is sorting through the numbers a from 1 to 10^{18}, and for every a writes ([a, b])/(a) on blackboard. Here [a, b] stands for least common multiple of a and b. Ivan is very lazy, that's why this task bored him soon. But he is interested in how many different numbers he would write on the boa...
3
# lcm(a,b) / a = b / gcd(a,b) dividers = set() b, i = int(input()), 1 while i * i <= b: if b % i == 0: dividers.add(i) dividers.add(b // i) i += 1 print(len(dividers))
Print the K-th element of the following sequence of length 32: 1, 1, 1, 2, 1, 2, 1, 5, 2, 2, 1, 5, 1, 2, 1, 14, 1, 5, 1, 5, 2, 2, 1, 15, 2, 2, 5, 4, 1, 4, 1, 51 Constraints * 1 \leq K \leq 32 * All values in input are integers. Input Input is given from Standard Input in the following format: K Output Print ...
3
a=(1, 1, 1, 2, 1, 2, 1, 5, 2, 2, 1, 5, 1, 2, 1, 14, 1, 5, 1, 5, 2, 2, 1, 15, 2, 2, 5, 4, 1, 4, 1, 51) b=int(input())-1 print(a[b])
There are N cities numbered 1 to N, connected by M railroads. You are now at City 1, with 10^{100} gold coins and S silver coins in your pocket. The i-th railroad connects City U_i and City V_i bidirectionally, and a one-way trip costs A_i silver coins and takes B_i minutes. You cannot use gold coins to pay the fare....
3
N,M,S=map(int,input().split()) from heapq import heappop,heappush inf = 10**18 cost=[[] for _ in range(N)] exc=[] for _ in range(M): u,v,a,b=map(int,input().split()) u,v=u-1,v-1 cost[u].append((v,a,b)) cost[v].append((u,a,b)) for _ in range(N): c,d=map(int,input().split()) exc.append((c,d)) ...
Xenia lives in a city that has n houses built along the main ringroad. The ringroad houses are numbered 1 through n in the clockwise order. The ringroad traffic is one way and also is clockwise. Xenia has recently moved into the ringroad house number 1. As a result, she's got m things to do. In order to complete the i...
1
r=lambda:map(int, raw_input().split()) n,m=r() N=r() print sum(p>n for p,n in zip(N, N[1:]))*n + N[-1] - 1
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
x = 1 finalresult = [] num = int(input()) while x <= num: length = [] words = str(input()) if len(words)<=10: finalresult.append(words) else: for i in words: length.append(i) p = str(len(length)-2) del length[1:len(length)-1] length.insert(1,p) final = "".join(length) finalresu...
You are given an array A, consisting of n positive integers a_1, a_2, ..., a_n, and an array B, consisting of m positive integers b_1, b_2, ..., b_m. Choose some element a of A and some element b of B such that a+b doesn't belong to A and doesn't belong to B. For example, if A = [2, 1, 7] and B = [1, 3, 4], we can ...
3
from itertools import product n=int(input()) entries_A=list(map(int,input().split())) m=int(input()) entries_B=list(map(int,input().split())) prodct=list(product(entries_A,entries_B)) sum1=[] for i in range(len(prodct)): sum1.append(sum(prodct[i])) if(entries_A.__contains__(sum1[i])==False and entries_B.__conta...
Arkady bought an air ticket from a city A to a city C. Unfortunately, there are no direct flights, but there are a lot of flights from A to a city B, and from B to C. There are n flights from A to B, they depart at time moments a_1, a_2, a_3, ..., a_n and arrive at B t_a moments later. There are m flights from B to C...
3
from bisect import bisect_left as bl n,m,ta,tb,k = map(int ,input().split()) a = [int(i) for i in input().split()] b = [int(i) for i in input().split()] for i in range(n): a[i] += ta if(k >= n): print(-1) else: f = 0 time = 0 for i in range(0,k+1): x = bl(b,a[i]) pos = x + k-i ...
An infinitely long railway has a train consisting of n cars, numbered from 1 to n (the numbers of all the cars are distinct) and positioned in arbitrary order. David Blaine wants to sort the railway cars in the order of increasing numbers. In one move he can make one of the cars disappear from its place and teleport it...
1
n = int(raw_input()) p = map(int,raw_input().split()) order = list(enumerate(p)) order.sort(key=lambda x:x[1]) cnt = tmp_cnt = 0; here = -1 for i,v in order: if here < i: tmp_cnt += 1 else: cnt = max(cnt,tmp_cnt); tmp_cnt = 1 here = i print n - max(cnt,tmp_cnt)
You are given the array a consisting of n positive (greater than zero) integers. In one move, you can choose two indices i and j (i ≠ j) such that the absolute difference between a_i and a_j is no more than one (|a_i - a_j| ≤ 1) and remove the smallest of these two elements. If two elements are equal, you can remove a...
3
t=int(input()) for i in range (t) : x=0 y=0 l=int(input()) s=list(map(int,input().split())) if sum(s) % 2==1 : print('YES') else : for j in range (len(s)): if s[j] % 2 == 1 : y=y+1 else : x=x+1 if (x==0) or (y==0): ...
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
for _ in range(int(input())): n=int(input()) ans=['2']*(n-1)+['3'] if (2*(n-1)+3)%3==0: ans[0]='3' if n==1: print(-1) continue print(''.join(ans))
Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears. These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite — cookies. Ichihime decides to attend the contest. Now sh...
3
import math t=int(input()) for _ in range(t): a,b,c,d=map(int,input().split()) x=b y=c # z=int(math.sqrt(abs(int(b*b-c*c)))) # if z==0: # z=x # elif b==c: # z=x print(x,y,y)
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d...
1
def lucky(n): for d in n: if d not in '47': return False return True n = raw_input() cnt = 0 for c in n: if c in '47': cnt += 1 if lucky(str(cnt)): print 'YES' else: print 'NO'
A sequence of non-negative integers a_1, a_2, ..., a_n is called growing if for all i from 1 to n - 1 all ones (of binary representation) in a_i are in the places of ones (of binary representation) in a_{i + 1} (in other words, a_i \:\&\: a_{i + 1} = a_i, where \& denotes [bitwise AND](http://tiny.cc/xpy9uz)). If n = 1...
3
import sys,os,io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline # input = sys.stdin.readline from collections import deque t = int(input()) for _ in range (t): n = int(input()) a = [int(i) for i in input().split()] o = [a[0]] for i in a[1:]: o.append(o[-1]|i) ans = [] for ...
Write a program which reads a $n \times m$ matrix $A$ and a $m \times l$ matrix $B$, and prints their product, a $n \times l$ matrix $C$. An element of matrix $C$ is obtained by the following formula: \\[ c_{ij} = \sum_{k=1}^m a_{ik}b_{kj} \\] where $a_{ij}$, $b_{ij}$ and $c_{ij}$ are elements of $A$, $B$ and $C$ res...
1
n, m, l = map(int, raw_input().split()) A = [map(int, raw_input().split()) for i in range(n)] B = [map(int, raw_input().split()) for i in range(m)] C = [[sum(A[i][k]*B[k][j] for k in range(m)) for j in range(l)] for i in range(n)] for row in C: print " ".join(map(str, row))
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If...
3
a=str(input()) b=len(a) c=0 if b<8: print('NO') else: for i in range(0,b-6): if a[i:i+7] in ['1111111','0000000']: print("YES") c=1 break if c==0: print('NO')
This is the hard version of this problem. The only difference is the constraint on k — the number of gifts in the offer. In this version: 2 ≤ k ≤ n. Vasya came to the store to buy goods for his friends for the New Year. It turned out that he was very lucky — today the offer "k of goods for the price of one" is held in...
3
q = int(input()) def binarySearch(arr, l, r, x): if 1 <= len(arr[l:r + 1]) <= 2: return l if r >= l: mid = int(l + (r - l) / 2) if arr[mid] == x: return mid elif arr[mid] > x: return binarySearch(arr, l, mid - 1, x) else: return ...
A priority queue is a data structure which maintains a set $S$ of elements, each of with an associated value (key), and supports the following operations: * $insert(S, k)$: insert an element $k$ into the set $S$ * $extractMax(S)$: remove and return the element of $S$ with the largest key Write a program which perfo...
3
from sys import stdin from heapq import heappush, heappop def main(): Q = [] for line in stdin.readlines(): cmd = line.split() if cmd[0] == "insert": heappush(Q, -int(cmd[1])) elif cmd[0] == "extract": print(-heappop(Q)) else: break if __n...
You are given two integers b and w. You have a chessboard of size 10^9 × 10^9 with the top left cell at (1; 1), the cell (1; 1) is painted white. Your task is to find a connected component on this chessboard that contains exactly b black cells and exactly w white cells. Two cells are called connected if they share a s...
3
import sys t = int(input()) for _ in range(t): b, w= map(int, sys.stdin.readline().split()) if b > w: x = 2 y = 2 m1 = w m2 = b else: x = 2 y = 3 m1 = b m2 = w if m2 > m1 * 3 + 1: print('NO') else: print('YES') ...
A railroad running from west to east in Atcoder Kingdom is now complete. There are N stations on the railroad, numbered 1 through N from west to east. Tomorrow, the opening ceremony of the railroad will take place. On this railroad, for each integer i such that 1≤i≤N-1, there will be trains that run from Station i t...
3
n=int(input()) c=[] for i in range(n-1): x,y,z=map(int,input().split()) c.append((x,y,z)) for i in range(n-1): ans=0 for j in range(i,n-1): ans=[c[j][1]+((ans-c[j][1]+c[j][2]-1)//c[j][2])*c[j][2],c[j][1]][ans<c[j][1]] ans+=c[j][0] print(ans) ans=chk=0 print(ans)
Mishka is trying really hard to avoid being kicked out of the university. In particular, he was doing absolutely nothing for the whole semester, miraculously passed some exams so that just one is left. There were n classes of that subject during the semester and on i-th class professor mentioned some non-negative inte...
3
n = int(input()) // 2 a = [] l = 0 r = 1000000000000000000 xx = [int(num) for num in input().split()] for i in range(n): x = xx[i] if r >= x - l: r = x - l a.append(r) print(l, end = ' ') else: l = x - r a.append(r) print(l, end = ' ') for i in range(n): print(a[n - 1 - i], end = ' ')
After you had helped George and Alex to move in the dorm, they went to help their friend Fedor play a new computer game «Call of Soldiers 3». The game has (m + 1) players and n types of soldiers in total. Players «Call of Soldiers 3» are numbered form 1 to (m + 1). Types of soldiers are numbered from 0 to n - 1. Each ...
1
# -*- coding: utf-8 -*- if __name__ == '__main__': n, m, k = map(int, raw_input().split()) armies = [int(raw_input()) for i in range(m+1)] fedya = armies[-1] differences = [army ^ fedya for army in armies[:-1]] counts_diffs = [sum(map(int, bin(diff)[2:])) for diff in differenc...
Vasily exited from a store and now he wants to recheck the total price of all purchases in his bill. The bill is a string in which the names of the purchases and their prices are printed in a row without any spaces. Check has the format "name1price1name2price2...namenpricen", where namei (name of the i-th purchase) is ...
1
#!/usr/bin/env python # -*- coding: UTF-8 -*- import sys import re import math import itertools import collections import bisect #sys.stdin=file('input.txt') #sys.stdout=file('output.txt','w') #10**9+7 mod=1000000007 #mod=1777777777 pi=3.141592653589 IS=float('inf') xy=[(1,0),(-1,0),(0,1),(0,-1)] bs=[(-1,-1),(-1,1),(1,...
Gerald is very particular to eight point sets. He thinks that any decent eight point set must consist of all pairwise intersections of three distinct integer vertical straight lines and three distinct integer horizontal straight lines, except for the average of these nine points. In other words, there must be three int...
3
from collections import defaultdict maps = defaultdict(int) maps1 = defaultdict(int) arr = [] distinct_count = distinct_count1 = 0 for i in range(8): temp = list(map(int, input().split())) if temp[0] not in maps: distinct_count += 1 if temp[1] not in maps1: distinct_count1 += 1 maps[temp...
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
# -*- coding: utf-8 -*- import math, string, itertools, operator, fractions, heapq, collections, re, array, bisect, sys, functools def solve(line): n = int(line) s = sys.stdin.readline().rstrip() c = [] cs = 0 ans = 0 for i in s: if i == ')': cs -= 1 if i == '(': ...
There was an electronic store heist last night. All keyboards which were in the store yesterday were numbered in ascending order from some integer number x. For example, if x = 4 and there were 3 keyboards in the store, then the devices had indices 4, 5 and 6, and if x = 10 and there were 7 of them then the keyboards ...
3
USE_STDIO = False if not USE_STDIO: try: import mypc except: pass def main(): n, = map(int, input().split(' ')) a = list(map(int, input().split(' '))) a.sort() ans = a[-1] - a[0] + 1 - n print(ans) if __name__ == '__main__': main()
There is a building with n rooms, numbered 1 to n. We can move from any room to any other room in the building. Let us call the following event a move: a person in some room i goes to another room j~ (i \neq j). Initially, there was one person in each room in the building. After that, we know that there were exactl...
3
n, k = map(int, input().split()) # ①nCrの各項のmod(10^9+7)を事前計算 p = 10 ** 9 + 7 fact = [1, 1] # fact[n] = (n! mod p) factinv = [1, 1] # factinv[n] = ((n!)^(-1) mod p) inv = [0, 1] # factinv 計算用 for i in range(2, 2*n): fact.append((fact[-1] * i) % p) inv.append((-inv[p % i] * (p // i)) % p) factinv.append((factin...
Given a set of integers (it can contain equal elements). You have to split it into two subsets A and B (both of them can contain equal elements or be empty). You have to maximize the value of mex(A)+mex(B). Here mex of a set denotes the smallest non-negative integer that doesn't exist in the set. For example: * m...
3
t = int(input()) for _ in range(t): n = int(input()) s = list(map(int, input().split())) s.sort() a = [s[0]] b = [] if min(s) != 0: print(0) else: for i in range(1, n): if s[i] - a[-1] == 1: a.append(s[i]) else: b.appe...
Pavel made a photo of his favourite stars in the sky. His camera takes a photo of all points of the sky that belong to some rectangle with sides parallel to the coordinate axes. Strictly speaking, it makes a photo of all points with coordinates (x, y), such that x_1 ≤ x ≤ x_2 and y_1 ≤ y ≤ y_2, where (x_1, y_1) and (x...
3
n = int(input()) a = [] a = input().split() for i in range(len(a)): a[i] = int(a[i]) a.sort() c = 0 ans = (a[n - 1]-a[0])*(a[2*n-1]-a[n]) for i in range(n): ans = min(ans, (a[i+n-1]-a[i])*(a[2*n-1]-a[0])) print(ans)
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().lower() b = input().lower() if (a == b): print(0) else: if (a > b): print(1) else: print(-1)
ZS the Coder and Chris the Baboon arrived at the entrance of Udayland. There is a n × n magic grid on the entrance which is filled with integers. Chris noticed that exactly one of the cells in the grid is empty, and to enter Udayland, they need to fill a positive integer into the empty cell. Chris tried filling in ran...
1
def checkperfect(matrix): sumn = sum(matrix[0]) for i in range(0, len(matrix)): if sum(matrix[i]) != sumn: return False mt = map(list, zip(*matrix)) for i in range(0, len(mt)): if sum(mt[i]) != sumn: return False d1 = 0 d2 = 0 for i in range(0, len(matrix)): d1 += matrix[i][i] d2 += matrix[i][len...
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution....
3
count=0 for i in range (int(input())): a,b,c = map(int,input().split()) s=a+b+c if(s >= 2): count += 1 print(count)
In this problem we consider a special type of an auction, which is called the second-price auction. As in regular auction n bidders place a bid which is price a bidder ready to pay. The auction is closed, that is, each bidder secretly informs the organizer of the auction price he is willing to pay. After that, the auct...
3
n=int(input()) l=list(map(int,input().split())) i=l.index(max(l))+1 l.remove(max(l)) print(i,max(l))
n robots have escaped from your laboratory! You have to find them as soon as possible, because these robots are experimental, and their behavior is not tested yet, so they may be really dangerous! Fortunately, even though your robots have escaped, you still have some control over them. First of all, you know the locat...
3
import sys # sys.stdin = open('inp.txt', 'r') MAXN = 100005 MAX = 100000 q = 0 n = 0 pos = [[0, 0] for _ in range(MAXN)] dirs = [[0, 0, 0, 0] for _ in range(MAXN)] hx = [-1, 0, 1, 0] hy = [0, 1, 0, -1] rect = [[0, 0, 0, 0] for _ in range(MAXN)] def intersect(r1, r2): """Find intersection of two rectangles""" ...
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
q=int(input()) ans_list=[] for i in range(q): b,p,f=map(int,input().split()) h,c=map(int,input().split()) no_of_burger_possible=b//2 if(b==0) or (b==1): ans=0 ans_list.append(ans) else: if(c>h): if(no_of_burger_possible>p+f): ans=c*f+h*p ...
problem Mobiles are widely known as moving works of art. The IOI Japan Committee has decided to create mobiles to publicize JOI. JOI public relations mobiles are sticks, strings, and weights. It is constructed as follows using the three types of elements of. * One end of the bar is painted blue and the other end is p...
3
# AOJ0520 import sys def gcd(x, y): if x < y: x, y = y, x while x % y != 0: x, y = y, x % y return y class frac: def __init__(self, n, d): self.num = n self.den = d def mul(self, yn, yd): xn, xd = self.num, self.den xn *= yn xd *= y...
There is a data which provides heights (in meter) of mountains. The data is only for ten mountains. Write a program which prints heights of the top three mountains in descending order. Constraints 0 ≤ height of mountain (integer) ≤ 10,000 Input Height of mountain 1 Height of mountain 2 Height of mountain 3 . . He...
1
list=[] for i in range(0,10): n = int(raw_input()) list.append(n) #print'---------------------' list.sort(reverse=True) for i in range(0,3): print list[i]
You can obtain profits from foreign exchange margin transactions. For example, if you buy 1000 dollar at a rate of 100 yen per dollar, and sell them at a rate of 108 yen per dollar, you can obtain (108 - 100) × 1000 = 8000 yen. Write a program which reads values of a currency $R_t$ at a certain time $t$ ($t = 0, 1, 2,...
1
N = input() a = [input() for i in range(N)] maxv = a[-1] - a[0] minv = a[0] for i in range(1,N): maxv = max(maxv,a[i]-minv) minv = min(minv,a[i]) print maxv
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
n=int(input()) lst=list(map(int,input().strip().split(' '))) lst.sort() count=0 for j in lst: if j<lst[-1]: count+=lst[-1]-j print(count)
George woke up and saw the current time s on the digital clock. Besides, George knows that he has slept for time t. Help George! Write a program that will, given time s and t, determine the time p when George went to bed. Note that George could have gone to bed yesterday relatively to the current time (see the second...
1
s = raw_input() s1 = raw_input() h1 = int(s[0] + s[1]) m1 = int(s[3] + s[4]) h2 = int(s1[0] + s1[1]) m2 = int(s1[3] + s1[4]) if m2 <= m1: m3 = m1 - m2 else: h1 -= 1 m3 = m1 - m2 + 60 if m3 < 10: m3 = '0' + str(m3) else: m3 = str(m3) if h2 <= h1: h3 = h1 - h2 else: h3 = h1 - h2 + 24 if h3 < ...
There is a bookshelf which can fit n books. The i-th position of bookshelf is a_i = 1 if there is a book on this position and a_i = 0 otherwise. It is guaranteed that there is at least one book on the bookshelf. In one move, you can choose some contiguous segment [l; r] consisting of books (i.e. for each i from l to r...
3
# import sys # sys.stdin = open('in.txt') for _ in range(int(input())): cnt = int(input()) print(input().strip('0 ').count('0'))
Takahashi is a member of a programming competition site, ButCoder. Each member of ButCoder is assigned two values: Inner Rating and Displayed Rating. The Displayed Rating of a member is equal to their Inner Rating if the member has participated in 10 or more contests. Otherwise, the Displayed Rating will be their Inn...
3
n,r=map(int,input().split()) print(r+max([0,100*(10-n)]))
Hideo Kojima has just quit his job at Konami. Now he is going to find a new place to work. Despite being such a well-known person, he still needs a CV to apply for a job. During all his career Hideo has produced n games. Some of them were successful, some were not. Hideo wants to remove several of them (possibly zero)...
3
n = int(input()) s = [int(x) for x in input().split()] max_fails = [] fails = 0 for i in range(n): if s[i] == 0: fails += 1 max_fails.append(fails) max_successes = [] successes = 0 for i in range(n-1, -1, -1): if s[i] == 1: successes += 1 max_successes.append(successes) max_success...
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob. Right now, Limak and Bob weigh a and b respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight. Limak eats a lot and his weight is tripled after every year, while Bob's weight...
3
#791A a,b=map(int,input().split()) i=0 while(True): if(a>b): break a=a*3 b=b*2 i=i+1 print(i)
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them. Input The first line contains integ...
3
n=int(input("")) s=input("") c=0 for i in range(n-1): if s[i]==s[i+1]: c=c+1 print(c)
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
for f in [*open(0)][2::2]: i=g=0 for t in f: g+=2*ord(t)-81 i+=g>i print(i)
Given are N integers A_1,\ldots,A_N. We will choose exactly K of these elements. Find the maximum possible product of the chosen elements. Then, print the maximum product modulo (10^9+7), using an integer between 0 and 10^9+6 (inclusive). Constraints * 1 \leq K \leq N \leq 2\times 10^5 * |A_i| \leq 10^9 Input Inp...
3
n,k,*a=map(int,open(0).read().split()) a.sort() mod=10**9+7 ans=1 i=0 j=-1 kk=k while kk>1: if a[i]*a[i+1]>a[j]*a[j-1]: ans=ans*a[i]*a[i+1]%mod i+=2 kk-=2 else: ans=ans*a[j]%mod j-=1 kk-=1 if kk==1: ans=ans*a[j]%mod if a[-1]<0 and k%2==1: ans=1 for i ...
"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
numbers = input() scores = input() numbers = numbers.split() n = int(numbers[0]) k = int(numbers[1]) m = 0 scores = scores.split() for i in range(n): scores[i] = int(scores[i]) for l in range(n): if scores[l] >= scores[k - 1]: if scores[l] > 0: m = m + 1 print(m)
Vasya claims that he had a paper square. He cut it into two rectangular parts using one vertical or horizontal cut. Then Vasya informed you the dimensions of these two rectangular parts. You need to check whether Vasya originally had a square. In other words, check if it is possible to make a square using two given rec...
3
num_lines = int(input()) for _ in range(num_lines): dim_0 = input().split(" ") dim_0 = [int(ele) for ele in dim_0] dim_0 = sorted(dim_0) dim_1 = input().split(" ") dim_1 = [int(ele) for ele in dim_1] dim_1 = sorted(dim_1) if dim_0[1] != dim_1[1]: print("No") elif dim_0[0] + ...
You are given two integers x and y. You can perform two types of operations: 1. Pay a dollars and increase or decrease any of these integers by 1. For example, if x = 0 and y = 7 there are four possible outcomes after this operation: * x = 0, y = 6; * x = 0, y = 8; * x = -1, y = 7; * x = 1, y = ...
3
import math def inp_n(): return int(input()) def inp_list(): return list(map(int, input().split())) def inp_mul_num(): return map(int, input().split()) def is_odd(n): if n & 1: return True return False for _ in range(inp_n()): x, y = inp_mul_num() a, b = inp_mul_num() v = a...
Kate has a set S of n integers \{1, ..., n\} . She thinks that imperfection of a subset M ⊆ S is equal to the maximum of gcd(a, b) over all pairs (a, b) such that both a and b are in M and a ≠ b. Kate is a very neat girl and for each k ∈ \{2, ..., n\} she wants to find a subset that has the smallest imperfection am...
3
""" Author : thekushalghosh Team : CodeDiggers """ import sys,math,cmath,time start_time = time.time() ################# ---- USER DEFINED INPUT FUNCTIONS ---- ################# def inp(): return(int(input())) def inlt(): return(list(map(int,input().split()))) def insr(): s = input() return(s[...
n boys and m girls came to the party. Each boy presented each girl some integer number of sweets (possibly zero). All boys are numbered with integers from 1 to n and all girls are numbered with integers from 1 to m. For all 1 ≤ i ≤ n the minimal number of sweets, which i-th boy presented to some girl is equal to b_i an...
3
from collections import deque n, m = map(int, input().split()) b = list(map(int, input().split())) g = list(map(int, input().split())) b.sort(reverse = True) g.sort(reverse = True) g = deque(g) if max(b) > min(g): print(-1) else: t = 0 for e in b: t += e * m special = len(g) == m and g[-1] >= e i = 0 w...
Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw. The first player wrote number a, the second player wrote number b. How many ways ...
1
import sys def mod(n): if(n >= 0): return n else: return -n a, b = map(int,sys.stdin.readline().split()) adiff = [] bdiff = [] for x in range(1,7): adiff.append(mod(a-x)) bdiff.append(mod(b-x)) i = 0 awin = 0 bwin = 0 draw = 0 while(i < 6): if(adiff[i] > bdiff[i]): bwin += 1 ...
Yet another Armageddon is coming! This time the culprit is the Julya tribe calendar. The beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows: "May the Great Beaver bless you! May your chacres open ...
3
n = int(input()) ans = 0 while n>0: i = n s = 0 while i>0: s = max(s,i%10) i=i//10 ans+=1 n-=s print(ans)
It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two di...
3
def gcd (a,b): if (b == 0): return a else: return gcd (b, a % b) n=int(input()) A = list(map(int,input().split())) res = A[0] for c in A[1::]: res = gcd(res , c) e=(max(A)//res)-len(A) if e%2!=0: print('Alice') else: print('Bob')
Vasya has a non-negative integer n. He wants to round it to nearest integer, which ends up with 0. If n already ends up with 0, Vasya considers it already rounded. For example, if n = 4722 answer is 4720. If n = 5 Vasya can round it to 0 or to 10. Both ways are correct. For given n find out to which integer will Vasy...
3
n = int(input()) ans = round(n/10) print(ans*10)
We have a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and b_i. Additionally, each vertex is painted in a color, and the color of Vertex i is c_i. Here, the color of each vertex is represented by an integer between 1 and N (inclusive). The same integer corresponds to the same col...
3
import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines from collections import defaultdict N = int(readline()) C = (0,) + tuple(map(int, read...
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
w = input() if w[0].islower() and (w[1:].isupper() or len(w) == 1): print(w[0].upper() + w[1:].lower()) elif w.isupper(): print(w.lower()) else: print(w)
You are playing one RPG from the 2010s. You are planning to raise your smithing skill, so you need as many resources as possible. So how to get resources? By stealing, of course. You decided to rob a town's blacksmith and you take a follower with you. You can carry at most p units and your follower — at most f units. ...
3
R=lambda:map(int,input().split()) t,=R() for _ in[0]*t:p,f=R();a=R();b=R();(x,a),(y,b)=sorted(zip(b,a));a=min(a,p//x+f//x)*x;print(a//x+min(b,max((p-u)//y+(f-a+u)//y for u in range(a-min(a,f-f%x),min(a,p)+1,x))))
You are given an array a, consisting of n integers. Each position i (1 ≤ i ≤ n) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearra...
3
from math import * from bisect import * from collections import * from random import * from decimal import * import sys from itertools import product input=sys.stdin.readline def inp(): return int(input()) def st(): return input().rstrip('\n') def lis(): return list(map(int,input().split())) def ma(): r...
Polycarp knows that if the sum of the digits of a number is divisible by 3, then the number itself is divisible by 3. He assumes that the numbers, the sum of the digits of which is divisible by 4, are also somewhat interesting. Thus, he considers a positive integer n interesting if its sum of digits is divisible by 4. ...
1
def sumofdig(n) : s=0 while n : s+=n%10 n=n/10 return s if __name__ == "__main__" : a=input() while sumofdig(a)%4 != 0 : a=a+1 print a
There are n students in a university. The number of students is even. The i-th student has programming skill equal to a_i. The coach wants to form n/2 teams. Each team should consist of exactly two students, and each student should belong to exactly one team. Two students can form a team only if their skills are equa...
3
# The place between your comfort zone and your dream is where life takes place. Helen Keller # by : Blue Edge - Create some chaos n=int(input()) a=list(map(int,input().split())) a.sort() ans=0 for i in range(1,n,2): ans+=a[i]-a[i-1] print(ans)
You are given an array a consisting of n integers. Indices of the array start from zero (i. e. the first element is a_0, the second one is a_1, and so on). You can reverse at most one subarray (continuous subsegment) of this array. Recall that the subarray of a with borders l and r is a[l; r] = a_l, a_{l + 1}, ..., a_...
3
for _ in range(int(input())): n=int(input()) a=list(map(int,input().split())) ans=0 for i in range(0,n,2): ans+=a[i] a[i]*=-1 currmax=a[0] globmax=a[0] best=0 for x in range(2): y=x cur = 0 while y+2<= n: cur += a[y] + a[y+1] ...
Recently Vasya decided to improve his pistol shooting skills. Today his coach offered him the following exercise. He placed n cans in a row on a table. Cans are numbered from left to right from 1 to n. Vasya has to knock down each can exactly once to finish the exercise. He is allowed to choose the order in which he wi...
3
N = int(input()) L = list(map(int,input().split())) L2 = [] risultato = 0 for n in range(0,N): L2.append([L[n],n+1]) L2.sort(reverse = True) for n in range(N): risultato = risultato + (n * L2[n][0]+1) print (risultato) for n in range(N): print (L2[n][1], end = " ")
Pravin and Saddam are room-mates.They always solve aptitude questions together. Once, they came across a problem stated as: "Find the digit at the unit place that appears in sum of factorials of all numbers between A and B (both inclusive)." Though they are good at mathematics ,but this time they are scratching their...
1
import math for t in range(input()): a,b=map(int,raw_input().split()) summ=0 for i in range(a,b+1,1): summ=summ+math.factorial(i) print summ%10
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...
3
def convert(list): # Converting integer list to string list s = [str(i) for i in list] # Join list items using join() res = int("".join(s)) return(res) x = input() answer = [] for i in range(len(x)): if(9 - int(x[i]) <= int(x[i])): answer.append(9 - ...
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line. Unfortunately, from time to ti...
1
s=raw_input()[1:-1].split(', ') a=set() for i in s: if i!='': a.add(i) print len(a)
Write a program which calculates the area and perimeter of a given rectangle. Constraints * 1 ≤ a, b ≤ 100 Input The length a and breadth b of the rectangle are given in a line separated by a single space. Output Print the area and perimeter of the rectangle in a line. The two integers should be separated by a si...
1
b = raw_input() a = b.split() #print a[1] x = int(a[0]) y = int(a[1]) s = x * y l = 2 * x + 2 * y print s,l
One day Vasya painted a Cartesian coordinate system on a piece of paper and marked some set of points (x1, y1), (x2, y2), ..., (xn, yn). Let's define neighbors for some fixed point from the given set (x, y): * point (x', y') is (x, y)'s right neighbor, if x' > x and y' = y * point (x', y') is (x, y)'s left neighb...
3
#n, m = input().split() #n = int (n) #m = int (m) #k = int (k) n = int(input()) #a = list(map(int, input().split())) #a = list(map(int, input().split())) #x1, y1, x2, y2 =map(int,input().split()) #n = int(input()) f = [] #f = [0]*n #t = [0]*n #f = [] #h = [""] * n #f1 = sorted(f, key = lambda tup: tup[0]) #f1 = sorte...
Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't). q events are abou...
3
from heapq import * from collections import defaultdict, deque total = 0 N, Q = map(int, input().split()) q = deque() idx = 0 total = 0 A = [0] * N B = [0] * N ans = [] for _ in range(Q): t, x = map(int, input().split()) x -= 1 if t == 1: q.append(x) A[x] += 1 B[x] += 1 tot...
Mahmoud and Ehab play a game called the even-odd game. Ehab chooses his favorite integer n and then they take turns, starting from Mahmoud. In each player's turn, he has to choose an integer a and subtract it from n such that: * 1 ≤ a ≤ n. * If it's Mahmoud's turn, a has to be even, but if it's Ehab's turn, a has...
3
a = int(input()) k = 0 if a % 2 == 0: print("Mahmoud") else: print("Ehab")
"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
_input = list(map(int,input().split())) n = _input[0] k = _input[1] scores = list(map(int,input().split())) min = scores[k-1] passed = 0 for sc in scores: if(sc > 0 and sc >= min): passed +=1 print(passed)
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation. The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe...
3
n = input().split("+") n = sorted(n) print("+".join(n))
There are N balls in a two-dimensional plane. The i-th ball is at coordinates (x_i, y_i). We will collect all of these balls, by choosing two integers p and q such that p \neq 0 or q \neq 0 and then repeating the following operation: * Choose a ball remaining in the plane and collect it. Let (a, b) be the coordinates...
3
import itertools import collections n=int(input()) X=[] for i in range(n): X.append([int(i) for i in input().split()]) X.sort(key=lambda x:(x[0],x[1])) Y=[] for c in itertools.combinations(range(n),2): x1,y1,x2,y2=X[c[0]][0],X[c[0]][1],X[c[1]][0],X[c[1]][1] Y.append((x2-x1,y2-y1)) yy=collections.Counter(Y) print(...
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
x,y=(input().split()) x=int(x) y=int(y) while(y): if(x%10==0): x=x//10 else: x=x-1; y-=1 print(x)
Nastya owns too many arrays now, so she wants to delete the least important of them. However, she discovered that this array is magic! Nastya now knows that the array has the following properties: * In one second we can add an arbitrary (possibly negative) integer to all elements of the array that are not equal to z...
3
n=int(input()) a=set(input().split()) s=len(a) if '0' in a: s-=1 print(s)
Dreamoon is a big fan of the Codeforces contests. One day, he claimed that he will collect all the places from 1 to 54 after two more rated contests. It's amazing! Based on this, you come up with the following problem: There is a person who participated in n Codeforces rounds. His place in the first round is a_1, hi...
3
import math import string a= int(input()) for i in range (a): b=input().split(' ') n=int(b[0]) x=int(b[1]) c=input().split(' ') counter = 0 v=1 while (counter)<(x): if c.count(str(v))==0: counter = counter + 1 if counter>=x: while c.count(str(v+1))!=0: v=v+1 break v=v+1 else: ...
Given is a string S representing the day of the week today. S is `SUN`, `MON`, `TUE`, `WED`, `THU`, `FRI`, or `SAT`, for Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, and Saturday, respectively. After how many days is the next Sunday (tomorrow or later)? Constraints * S is `SUN`, `MON`, `TUE`, `WED`, `THU`,...
3
d={'SUN':7,'MON':6,'TUE':5,'WED':4,'THU':3,'FRI':2,'SAT':1} print(d[input()])
You are given a permutation p_1, p_2, ..., p_n. Recall that sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once. Find three indices i, j and k such that: * 1 ≤ i < j < k ≤ n; * p_i < p_j and p_j > p_k. Or say that there are no such indices. Input The first lin...
3
def sint(): return (int(input())) def sints(): return (map(int,input().split())) def sara(): return (list(map(int,input().split()))) def sstr(): s = input() return (list(s[:len(s)])) def main(): tt = sint() while tt: tt -= 1 n = sint() ara = sara() ...
Mike received an array a of length n as a birthday present and decided to test how pretty it is. An array would pass the i-th prettiness test if there is a way to get an array with a sum of elements totaling s_i, using some number (possibly zero) of slicing operations. <image> An array slicing operation is conducted...
3
from bisect import * from collections import * from math import gcd,ceil,sqrt,floor,inf from heapq import * from itertools import * from operator import add,mul,sub,xor,truediv,floordiv from functools import * #------------------------------------------------------------------------ import os import sys from io impo...
Ted has a pineapple. This pineapple is able to bark like a bulldog! At time t (in seconds) it barks for the first time. Then every s seconds after it, it barks twice with 1 second interval. Thus it barks at times t, t + s, t + s + 1, t + 2s, t + 2s + 1, etc. <image> Barney woke up in the morning and wants to eat the ...
3
import sys (T, S, X) = (map(int, sys.stdin.readline().split())) r1 = (X - T) % S r2 = (X - T - 1) % S if (X-T == 1) or X < T: print("NO") elif r1 == 0 or r2 == 0: print("YES") else: print("NO")
Polycarp has n coins, the value of the i-th coin is a_i. It is guaranteed that all the values are integer powers of 2 (i.e. a_i = 2^d for some non-negative integer number d). Polycarp wants to know answers on q queries. The j-th query is described as integer number b_j. The answer to the query is the minimum number of...
3
# aadiupadhyay import os.path from math import gcd, floor, ceil from collections import * import sys mod = 1000000007 INF = float('inf') def st(): return list(sys.stdin.readline().strip()) def li(): return list(map(int, sys.stdin.readline().split())) def mp(): return map(int, sys.stdin.readline().split()) def inp(): re...
Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options: 1. on this day the gym is closed and...
3
n = int(input()) a = [int(x) for x in input().split()] d0, d1, d2 = [0], [0], [0] for i in range(n): d0.append(max((d0[i], d1[i], d2[i]))) d1.append(max(d0[i], d2[i]) + (1 if a[i] & 1 else 0)) d2.append(max(d0[i], d1[i]) + (1 if a[i] & 2 else 0)) print(n - max((d0[-1], d1[-1], d2[-1])))
Snuke is standing on a two-dimensional plane. In one operation, he can move by 1 in the positive x-direction, or move by 1 in the positive y-direction. Let us define a function f(r, c) as follows: * f(r,c) := (The number of paths from the point (0, 0) to the point (r, c) that Snuke can trace by repeating the operati...
3
class Factorial: def __init__(self,n,mod): self.f=f=[0]*(n+1) f[0]=b=1 self.mod=mod for i in range(1,n+1):f[i]=b=b*i%mod self.inv=inv=[0]*(n+1) inv[0]=b=pow(self.f[n],mod-2,mod) for i in range(1,n+1):inv[i]=b=b*(n+1-i)%mod self.inv.reverse() def fa...
Kate has a set S of n integers \{1, ..., n\} . She thinks that imperfection of a subset M ⊆ S is equal to the maximum of gcd(a, b) over all pairs (a, b) such that both a and b are in M and a ≠ b. Kate is a very neat girl and for each k ∈ \{2, ..., n\} she wants to find a subset that has the smallest imperfection am...
1
import sys, collections range = xrange input = raw_input n = int(input()) P = [1]*(n + 1) smallest = [n + 2]*(n + 1) for i in range(2, n + 1): if P[i]: smallest[i] = min(i, smallest[i]) j = i + i while j <= n: P[j] = 0 smallest[j] = min(i, smallest[j]) j...
Ivan has an array consisting of n different integers. He decided to reorder all elements in increasing order. Ivan loves merge sort so he decided to represent his array with one or several increasing sequences which he then plans to merge into one sorted array. Ivan represent his array with increasing sequences with h...
3
n=int(input()) a=list(map(int,input().split())) ans=[] for i in range(n): l=0 r=len(ans) while l<r: mid=l+(r-l)//2 if ans[mid][-1]<a[i]: r=mid else: l=mid+1 if l==len(ans): ans.append([a[i]]) else: ans[l].append(a[i]) for x in ans: ...
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
for i in range(5): x=input().split() if "1" in x: fi=i fj=x.index("1") t1,t2=abs(fi-2),abs(fj-2) print(t1+t2) # fi=fj=0 # for i in range(5): # x=input().split() # k=0 # for j in x: # if j=="1": # fi=i # fj=k # k+=1 # t1,t2=abs(fi-2),abs(fj-2) # print(t1+t2)
Alexander is a well-known programmer. Today he decided to finally go out and play football, but with the first hit he left a dent on the new Rolls-Royce of the wealthy businessman Big Vova. Vladimir has recently opened a store on the popular online marketplace "Zmey-Gorynych", and offers Alex a job: if he shows his pro...
3
import sys, math tc = int(sys.stdin.readline()) for _ in range(tc): n = int(sys.stdin.readline()) arr = list(map(int, sys.stdin.readline().split())) check = [False] * n ans = [0] * n ans[0] = max(arr) check[arr.index(max(arr))] = True now = ans[0] for i in range(1, n): temp = []...
In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup...
3
lst=[] for _ in range(int(input())): lst.append(int(input())) if sum(lst)%len(lst)!=0: print("Unrecoverable configuration.") else: ave=sum(lst)//len(lst) lst=list(map(lambda x: x-ave,lst)) l1=list(filter(lambda x: x[1]>0,enumerate(lst))) l2=list(filter(lambda x: x[1]<0,enumerate(lst))) if l1...
You are given a range of positive integers from l to r. Find such a pair of integers (x, y) that l ≤ x, y ≤ r, x ≠ y and x divides y. If there are multiple answers, print any of them. You are also asked to answer T independent queries. Input The first line contains a single integer T (1 ≤ T ≤ 1000) — the number of...
3
n = int(input()) for _ in range(n): left, right = list(map(int, input().split())) for i in range(left,right): if 2 * i <= right: print(i, 2 * (i)) break