problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
For a given sequence A = {a0, a1, ... , an-1}, find the length of the longest increasing subsequnece (LIS) in A. An increasing subsequence of A is defined by a subsequence {ai0, ai1, ... , aik} where 0 ≀ i0 < i1 < ... < ik < n and ai0 < ai1 < ... < aik. Constraints * 1 ≀ n ≀ 100000 * 0 ≀ ai ≀ 109 Input n a0 a1 : ...
3
#!/usr/bin/env python # -*- coding: utf-8 -*- """ input: 8 4 1 6 2 8 5 7 3 or 3 1 1 1 output: 4 or 1 """ import sys from bisect import bisect_left def solve(): dis_rec = [float('inf')] * array_length dis_rec[0] = array[0] length = 1 for ele in array: if dis_rec[length - 1] < ele: ...
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
string = str(input()); length = len(string); a = int(0); b = int(0); c = int(0); if string[0] == string[0].lower() and length > 1 and string[1] == string[1].upper(): for i in range(length): if i == 0: c = c + 1; else: if string[0] == string[0].lower() and string[i] == string[i].upper(): c = c + 1; if...
Today Johnny wants to increase his contribution. His plan assumes writing n blogs. One blog covers one topic, but one topic can be covered by many blogs. Moreover, some blogs have references to each other. Each pair of blogs that are connected by a reference has to cover different topics because otherwise, the readers ...
3
import os import sys from io import BytesIO, IOBase def main(): input=sys.stdin.buffer.readline I = lambda : list(map(int,input().split())) n,m = I() g=[[] for i in range(n)] for i in range(m): a,b = I() g[a-1].append(b-1) g[b-1].append(a-1) rc = I() c=[i for i in range(1,n+1)] c.sort(key = lambda x :...
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. ...
3
n=input() sum=0 while True: for i in range(len(n)): sum+=int(n[i]) if sum%4 == 0: print(n) break; else: n=int(n) n+=1 n=str(n) sum=0
The map of the capital of Berland can be viewed on the infinite coordinate plane. Each point with integer coordinates contains a building, and there are streets connecting every building to four neighbouring buildings. All streets are parallel to the coordinate axes. The main school of the capital is located in (s_x, ...
3
# import sys # sys.stdin = open("test.txt", 'r') n, sx, sy = list(map(int, input().split())) a = [list(map(int, input().split())) for _ in range(n)] pairs = [0, 0, 0, 0] for x, y in a: x -= sx y -= sy if x == 0: pairs[2*(y < 0)] += 1 elif y == 0: pairs[1+2*(x > 0)] += 1 else: ...
Dima worked all day and wrote down on a long paper strip his favorite number n consisting of l digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf. To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive inte...
3
l=int(input()) n=input() def solve(ind,d): global ans if ind<1 or ind>=l: return if n[ind]=='0': if d==0: return while 1<=ind<l and n[ind]=='0': ind+=d if ind<1 or ind>=l: return if n[ind]=='0': return res=int(n[:ind])+int(n[ind:])...
Orac is studying number theory, and he is interested in the properties of divisors. For two positive integers a and b, a is a divisor of b if and only if there exists an integer c, such that aβ‹… c=b. For n β‰₯ 2, we will denote as f(n) the smallest positive divisor of n, except 1. For example, f(7)=7,f(10)=2,f(35)=5. ...
1
t = int(raw_input()) for _ in xrange(t): n, k = map(int, raw_input().split()) if n % 2 == 0: print n + 2 * k else: fd = n for d in xrange(3, n+1): if d * d > n: break if n % d == 0: fd = d break print n +...
Your task in this problem is to create a program that finds the shortest path between two given locations on a given street map, which is represented as a collection of line segments on a plane. <image> Figure 4 is an example of a street map, where some line segments represent streets and the others are signs indicat...
3
from heapq import heappush, heappop import sys readline = sys.stdin.readline write = sys.stdout.write def dot3(O, A, B): ox, oy = O; ax, ay = A; bx, by = B return (ax - ox) * (bx - ox) + (ay - oy) * (by - oy) def cross3(O, A, B): ox, oy = O; ax, ay = A; bx, by = B return (ax - ox) * (by - oy) - (bx - o...
Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. For example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. When a team plays as ...
1
a = int(raw_input()) b = [] c = [] for i in range(a): line = raw_input().split() b.append(line[0]) c.append(line[1]) count = 0 for j in b: for k in c: if j == k: count+=1 print count
You are given one integer number n. Find three distinct integers a, b, c such that 2 ≀ a, b, c and a β‹… b β‹… c = n or say that it is impossible to do it. If there are several answers, you can print any. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 100)...
3
import math for _ in range(int(input())): n=int(input()) a=[] s=round(math.sqrt(n)) for i in range(2,s+1): if len(a)==2: if n not in a: a.append(n) break else: if n%i==0: a.append(i) ...
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...
3
n=input() a=[] cnt=0 for _ in n: a.append(_) for i in a: if int(i)%10==4 or int(i)%10==7: cnt+=1 if cnt==4 or cnt==7: print('YES') else: print('NO')
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 i in range(n): w = input() if len(w) > 10: c = len(w[1:-1]) print(w[0] + str(c) + w[-1]) else: print(w)
Absent-minded Masha got set of n cubes for her birthday. At each of 6 faces of each cube, there is exactly one digit from 0 to 9. Masha became interested what is the largest natural x such she can make using her new cubes all integers from 1 to x. To make a number Masha can rotate her cubes and put them in a row. Aft...
3
table=[str(i) for i in range(1, 1000)] n=int(input()) num=[] res=[] for i in range(n): s=input() s=s.split() num.append(s) #print(num) for i in num[0]: res.append(i) if n>1: for i in num[0]: for j in num[1]: res.append(str(int(i+j))) res.append(str(int(j+i))) for i in num[1]: res.append(str(int(i))) if ...
Mishka wants to buy some food in the nearby shop. Initially, he has s burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1 ≀ x ≀ s, buy food that costs exactly x burles and obtain ⌊x/10βŒ‹ burles as a cashback (in other words, Mishka ...
3
def main(): s = int(input()) a = 0 while s > 9: x = s // 10 s -= (x * 10) a += (x * 10) s += x print(a + s) # main() for _ in range(int(input())): main()
You are given two integers n and m (m < n). Consider a convex regular polygon of n vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length). <image> Examples of convex regular polygons Your task is to say if it is poss...
3
def func(n,m): if n%m==0: return 'YES' else: return 'NO' t=int(input()) l=[] for i in range(t): n,m=map(int,input().split()) l.append(func(n,m)) for i in l: print(i)
For the given integer n (n > 2) let's write down all the strings of length n which contain n-2 letters 'a' and two letters 'b' in lexicographical (alphabetical) order. Recall that the string s of length n is lexicographically less than string t of length n, if there exists such i (1 ≀ i ≀ n), that s_i < t_i, and for a...
3
import math t = int(input()) for _ in range(t): n, k = map(int, input().split()) p1 = math.floor((1 + (1 + 8 * (k - 1)) ** 0.5) / 2) p2 = k - (p1 * (p1 - 1) // 2) ans = "a" * (n - p1 - 1) + "b" + "a" * (p1 - p2) + "b" + "a" * (p2 - 1) print(ans)
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
a, b = input().split(' ') a = int(a) b = int(b) while b>0: if a%10==0: a = a/10 b -= 1 elif b >= a%10: b -= a%10 a -= a%10 else: a -= b b = 0 print(int(a))
Suppose you are performing the following algorithm. There is an array v_1, v_2, ..., v_n filled with zeroes at start. The following operation is applied to the array several times β€” at i-th step (0-indexed) you can: * either choose position pos (1 ≀ pos ≀ n) and increase v_{pos} by k^i; * or not choose any posit...
3
t = int(input()) for case_num in range(t): n, k = map(int, input().split(' ')) a = list(map(int, input().split(' '))) d = dict() for i in a: num = i level = 0 while num > 0: if not level in d: d[level] = 0 d[level] += num % k nu...
The HR manager was disappointed again. The last applicant failed the interview the same way as 24 previous ones. "Do I give such a hard task?" β€” the HR manager thought. "Just raise number 5 to the power of n and get last two digits of the number. Yes, of course, n can be rather big, and one cannot find the power using ...
3
def main(n): return 25 if __name__ == "__main__": # str = input() # n, m = map(int, str.split(" ")) n = int(input()) ans = main(n) print(ans)
Let's call left cyclic shift of some string t_1 t_2 t_3 ... t_{n - 1} t_n as string t_2 t_3 ... t_{n - 1} t_n t_1. Analogically, let's call right cyclic shift of string t as string t_n t_1 t_2 t_3 ... t_{n - 1}. Let's say string t is good if its left cyclic shift is equal to its right cyclic shift. You are given str...
3
import sys readline = sys.stdin.readline readlines = sys.stdin.readlines ns = lambda: readline().rstrip() ni = lambda: int(readline().rstrip()) nm = lambda: map(int, readline().split()) nl = lambda: list(map(int, readline().split())) prn = lambda x: print(*x, sep='\n') def solve(): s = list(map(int, list(ns())))...
Guy-Manuel and Thomas have an array a of n integers [a_1, a_2, ..., a_n]. In one step they can add 1 to any element of the array. Formally, in one step they can choose any integer index i (1 ≀ i ≀ n) and do a_i := a_i + 1. If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and T...
3
import sys import math import heapq import collections def inputnum(): return(int(input())) def inputnums(): return(map(int,input().split())) def inputlist(): return(list(map(int,input().split()))) def inputstring(): return([x for x in input()]) def inputstringnum(): return([ord(x)-ord('a') for x in...
Shubham has a binary string s. A binary string is a string containing only characters "0" and "1". He can perform the following operation on the string any amount of times: * Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa. ...
3
# from future import print_function,division # range = xrange import sys input = sys.stdin.readline # sys.setrecursionlimit(10**9) from sys import stdin, stdout def main(): for _ in range(int(input())): s = input().strip() n = len(s) count0 = [0]*(n +1) count1 = [0]*(n+1) c ...
Appleman and Toastman play a game. Initially Appleman gives one group of n numbers to the Toastman, then they start to complete the following tasks: * Each time Toastman gets a group of numbers, he sums up all the numbers and adds this sum to the score. Then he gives the group to the Appleman. * Each time Applema...
3
import copy n=int(input()) a=input().split() for i in range(n): a[i]=int(a[i]) a.sort() ma=n*a[n-1] for i in range(n-1): ma+=(i+2)*a[i] print(ma)
Adilbek was assigned to a special project. For Adilbek it means that he has n days to run a special program and provide its results. But there is a problem: the program needs to run for d days to calculate the results. Fortunately, Adilbek can optimize the program. If he spends x (x is a non-negative integer) days opt...
3
t = int(input()) def up(x): if x > x // 1: x = x // 1 + 1 return x for i in range(t): a = str(input()).split(' ') n = int(a[0]) d = int(a[1]) x = 0 for i in range(n // 2 + 1): r = x + up(d / (x + 1)) if n >= r: print('YES') break x += 1...
A string is a palindrome if it reads the same from the left to the right and from the right to the left. For example, the strings "kek", "abacaba", "r" and "papicipap" are palindromes, while the strings "abb" and "iq" are not. A substring s[l … r] (1 ≀ l ≀ r ≀ |s|) of a string s = s_{1}s_{2} … s_{|s|} is the string s_...
1
s = raw_input().strip() if len(set(s)) == 1: print 0 elif s == s[::-1]: print len(s) - 1 else: print len(s)
You are going out for a walk, when you suddenly encounter N monsters. Each monster has a parameter called health, and the health of the i-th monster is h_i at the moment of encounter. A monster will vanish immediately when its health drops to 0 or below. Fortunately, you are a skilled magician, capable of causing expl...
3
n,a,b=map(int,input().split()) h=[int(input()) for i in range(n)] l=0;r=max(h)//b+1 while abs(l-r)>1: x=(l+r)//2 ct=0 for i in range(n): ct+=((a-b-1)+max(0,h[i]-b*x))//(a-b) if ct<=x: r=x else: l=x print(r)
Manao has invented a new mathematical term β€” a beautiful set of points. He calls a set of points on a plane beautiful if it meets the following conditions: 1. The coordinates of each point in the set are integers. 2. For any two points from the set, the distance between them is a non-integer. Consider all poi...
1
n, m = map(int, raw_input().split()) print min(n, m) + 1 for i in range(min(n, m) + 1): print "%d %d" %(i, (m - i))
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 = map(int, input().split()) a=[int(x) for x in input().split()] b=[int(x) for x in input().split()] even1= [] odd1=[] even2=[] odd2=[] for i in range(n): if a[i]%2==0: even1.append(a[i]) else: odd1.append(a[i]) for i in range(m): if b[i]%2==0: even2.append(b[i]) else: ...
You are given two positive integer numbers a and b. Permute (change order) of the digits of a to construct maximal number not exceeding b. No number in input and/or output can start with the digit 0. It is allowed to leave a as it is. Input The first line contains integer a (1 ≀ a ≀ 1018). The second line contains i...
3
#Code by Sounak, IIESTS #------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase from fractions import Fraction from collections import defaultdict from itertools import permutations BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 ...
Mary has just graduated from one well-known University and is now attending celebration party. Students like to dream of a beautiful life, so they used champagne glasses to construct a small pyramid. The height of the pyramid is n. The top level consists of only 1 glass, that stands on 2 glasses on the second level (co...
3
full = 0 n, t = (int(v) for v in input().strip().split()) g = [t] for i in range(n): g2 = [0] * (len(g)+1) for j,l in enumerate(g): if l<1: continue full += 1 g2[j] += (l-1)/2 g2[j+1] += (l-1)/2 #print(g) g = g2 print(full) # Made By Mostafa_Khaled
You still have partial information about the score during the historic football match. You are given a set of pairs (a_i, b_i), indicating that at some point during the match the score was "a_i: b_i". It is known that if the current score is Β«x:yΒ», then after the goal it will change to "x+1:y" or "x:y+1". What is the l...
3
from sys import stdin,stdout from math import gcd,sqrt from collections import deque input=stdin.readline R=lambda:map(int,input().split()) I=lambda:int(input()) S=lambda:input().rstrip('\n') P=lambda x:stdout.write(x) hg=lambda x,y:((y+x-1)//x)*x pw=lambda x:1 if x==1 else 1+pw(x//2) chk=lambda x:chk(x//2) if not x%2 ...
Anton likes to play chess, and so does his friend Danik. Once they have played n games in a row. For each game it's known who was the winner β€” Anton or Danik. None of the games ended with a tie. Now Anton wonders, who won more games, he or Danik? Help him determine this. Input The first line of the input contains a...
3
k=int(input()) n=input() c=0 d=0 for i in n: if i=="A": c+=1 else: d+=1 if c>d: print("Anton") elif d>c: print("Danik") else: print("Friendship")
You are given an array of integers. Vasya can permute (change order) its integers. He wants to do it so that as many as possible integers will become on a place where a smaller integer used to stand. Help Vasya find the maximal number of such integers. For instance, if we are given an array [10, 20, 30, 40], we can pe...
1
from collections import deque input = raw_input read_ints = lambda: map(int, input().split()) n, a, ans = int(input()), sorted(read_ints()), 0 a1 = deque(a) for i in range(n): while a1: tem = a1.popleft() if tem > a[i]: ans += 1 break print(ans)
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob β€” to check his answers, he needs a program that among the given n numbers finds one that is di...
3
input() nums = list(map(int, input().split())) odd = [] even = [] for i,num in enumerate(nums): nums = odd if num % 2 else even nums.append(i) index = odd.pop() if len(odd) == 1 else even.pop() print(index + 1)
For a positive integer n let's define a function f: f(n) = - 1 + 2 - 3 + .. + ( - 1)nn Your task is to calculate f(n) for a given integer n. Input The single line contains the positive integer n (1 ≀ n ≀ 1015). Output Print f(n) in a single line. Examples Input 4 Output 2 Input 5 Output -3 Note f(4)...
3
n = int(input()) print(str((n%2)*(-(n//2)-1)+((n+1)%2)*(n//2)))
You are given three positive integers n, a and b. You have to construct a string s of length n consisting of lowercase Latin letters such that each substring of length a has exactly b distinct letters. It is guaranteed that the answer exists. You have to answer t independent test cases. Recall that the substring s[l ...
3
A= "abcdefghilmnopqrstuvzxyjkw" T=int(input()) for t in range(T): n,a,b=map(int,input().split()) s="" s=A[0:b] s=s*((n//b)+1) s=s[:n] print(s)
Bizon the Champion is called the Champion for a reason. Bizon the Champion has recently got a present β€” a new glass cupboard with n shelves and he decided to put all his presents there. All the presents can be divided into two types: medals and cups. Bizon the Champion has a1 first prize cups, a2 second prize cups an...
3
import math if __name__ == '__main__': cups = list(map(int, input().split())) medals = list(map(int, input().split())) n = int(input()) number_cups = sum(cups) number_medals = sum(medals) shelves_cups = math.ceil(number_cups/5) shelves_medals = math.ceil(number_medals/10) if shelves_cu...
Let a and b be two arrays of lengths n and m, respectively, with no elements in common. We can define a new array merge(a,b) of length n+m recursively as follows: * If one of the arrays is empty, the result is the other array. That is, merge(βˆ…,b)=b and merge(a,βˆ…)=a. In particular, merge(βˆ…,βˆ…)=βˆ…. * If both arrays a...
3
t=int(input()) def isSubsetSum(set, n, sum): subset = ([[False for i in range(sum + 1)] for i in range(n + 1)]) for i in range(n + 1): subset[i][0] = True for i in range(1, sum + 1): subset[0][i] = False for i in range(1, n + 1): for j in range(1, sum + 1): ...
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
import sys import collections input = sys.stdin.readline r = input ir = int for _ in range(int(input())): n = ir(r()) a = list(map(ir, r().split())) l = list(map(ir, r().split())) unlocked_el = [] unlocked = [] locked = [] ans = [0] * n for i in range(n): if l[i]: locked += [i] else: unlocked += [i]...
You are given two strings a and b consisting of lowercase English letters, both of length n. The characters of both strings have indices from 1 to n, inclusive. You are allowed to do the following changes: * Choose any index i (1 ≀ i ≀ n) and swap characters a_i and b_i; * Choose any index i (1 ≀ i ≀ n) and sw...
1
N = int(raw_input()) A = raw_input().strip() B = raw_input().strip() changes = 0 def canSolve(a1, a2, b1, b2): chars = [a1, a2, b1, b2] chars.sort() # print(chars) return chars[0] == chars[1] and chars[2] == chars[3] def case1(a1, a2, b1, b2): bset = [b1, b2] return a1 in bset or a2 in bset def...
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Let next(x) be the minimum lucky number which is larger than or equals x. Petya is interested what i...
3
S = sorted M = lambda : map(int,input().split()) a = [] l,r = M() def F(x): a.append(x) if x>r*10: return F(10*x+4) F(10*x+7) F(0) a=S(a) def luckysum(p): s = 0 for i in range(1, len(a)): s+= a[i]*(min(a[i],p)-min(a[i-1],p)) if not (min(a[i],p)-min(a[i-1],p)): break return s print(luckysum(r)-luckysum...
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." β€” an excerpt from contest rules. A total of n participants took part in the contest (n β‰₯ k), and you already know their scores. Calculate how many ...
3
n, k = map(int,input().split()) a = list(map(int,input().split())) l = 0 for i in a: if i > 0 and i >= a[k-1]: l += 1 print(l)
You received a notebook which is called Death Note. This notebook has infinite number of pages. A rule is written on the last page (huh) of this notebook. It says: "You have to write names in this notebook during n consecutive days. During the i-th day you have to write exactly a_i names.". You got scared (of course yo...
3
n,m=map(int,input().split()) l=list(map(int,input().split())) c=0 for i in range(n): l[i]+=c print(l[i]//m) c=l[i]%m
Omkar is building a waterslide in his water park, and he needs your help to ensure that he does it as efficiently as possible. Omkar currently has n supports arranged in a line, the i-th of which has height a_i. Omkar wants to build his waterslide from the right to the left, so his supports must be nondecreasing in he...
3
t=int(input()) for i in range(0,t): m=int(input()) arr=list(map(int,input().strip().split()))[:m] big=0 for j in range(0,m-1): y=max((arr[j]-arr[j+1]),0) big=big+y print(big)
HQ9+ is a joke programming language which has only four one-character instructions: * "H" prints "Hello, World!", * "Q" prints the source code of the program itself, * "9" prints the lyrics of "99 Bottles of Beer" song, * "+" increments the value stored in the internal accumulator. Instructions "H" and "Q"...
3
p=input() str1=list(p) str2=['H','Q','9'] for i in str2: if i in str1: x=1 break else: x=0 if(x==1): print("YES") else: print("NO")
When preparing a tournament, Codeforces coordinators try treir best to make the first problem as easy as possible. This time the coordinator had chosen some problem and asked n people about their opinions. Each person answered whether this problem is easy or hard. If at least one of these n people has answered that th...
3
input() print('EASY' if all(x == '0' for x in input().split()) else 'HARD')
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
import sys, os def main(): n = int(raw_input()) if n <= 2: print "NO" elif n % 2 != 0: print "NO" else: print "YES" return if __name__ == "__main__": main()
While playing with geometric figures Alex has accidentally invented a concept of a n-th order rhombus in a cell grid. A 1-st order rhombus is just a square 1 Γ— 1 (i.e just a cell). A n-th order rhombus for all n β‰₯ 2 one obtains from a n-1-th order rhombus adding all cells which have a common side with it to it (look ...
3
n=int(input()) print(2*(n-1)*(n-1)+2*(n-1)+1)
There are n students in the first grade of Nlogonia high school. The principal wishes to split the students into two classrooms (each student must be in exactly one of the classrooms). Two distinct students whose name starts with the same letter will be chatty if they are put in the same classroom (because they must ha...
3
from collections import Counter n = int(input()) letters = [] for _ in range(n): letters.append(input()[0]) l = list(Counter(letters).values()) def som(m): return m * (m-1) / 2 s = 0 for i in l: s += som(i//2) + som(i - i//2) print("%d" %s)
You are given a string s consisting of the characters 0, 1, and ?. Let's call a string unstable if it consists of the characters 0 and 1 and any two adjacent characters are different (i. e. it has the form 010101... or 101010...). Let's call a string beautiful if it consists of the characters 0, 1, and ?, and you can...
3
""" ID: happyn61 LANG: PYTHON3 PROB: loan """ from itertools import product import itertools #from collections import defaultdict import sys import math import heapq from collections import deque MOD=1000000000007 #fin = open ('loan.in', 'r') #fout = open ('loan.out', 'w') #print(dic["4734"]) def find(parent,i): ...
Based on some criterion, Snuke divided the integers from 1 through 12 into three groups as shown in the figure below. Given two integers x and y (1 ≀ x < y ≀ 12), determine whether they belong to the same group. b4ab979900ed647703389d4349eb84ee.png Constraints * x and y are integers. * 1 ≀ x < y ≀ 12 Input Input i...
3
S=[0, 2, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0] a,b=[int(x) for x in input().split()] if(S[a-1]==S[b-1]): print("Yes") else: print("No")
You are given an integer n. In one move, you can either multiply n by two or divide n by 6 (if it is divisible by 6 without the remainder). Your task is to find the minimum number of moves needed to obtain 1 from n or determine if it's impossible to do that. You have to answer t independent test cases. Input The fi...
3
t = int(input()) b = 0 for i in range(t): n = int(input()) while n > 1: if (n % 6) == 0: n = n / 6 b += 1 else: if (n % 3) == 0: n = (n * 2) / 6 b += 2 else: n = -1 if n == 1: print(b) ...
This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved. Pikachu is a cute and friendly pokΓ©mon living in the wild pikachu herd. But it has become known recently that infamous team R...
3
for _ in range(int(input())): n,q = list(map(int,input().split())) a = list(map(int,input().split())) b = [] s = 0 if n==1: print(a[0]) continue for i in range(len(a)-1): if a[i]>a[i+1] and s==0: b.append(a[i]) s+=1 elif a[i+1]>a[i] and s==...
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." β€” an excerpt from contest rules. A total of n participants took part in the contest (n β‰₯ k), and you already know their scores. Calculate how many ...
3
n, k = [int(x) for x in input().split()] string = input() scores = [int(x) for x in string.split()] nrp = 0 for score in scores: if score > 0: if score >= scores[k-1]: nrp = nrp+1 print(nrp)
Roma (a popular Russian name that means 'Roman') loves the Little Lvov Elephant's lucky numbers. Let us remind you that lucky numbers are positive integers whose decimal representation only contains lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Roma's got n positive integers....
1
n,k=map(int,raw_input().split()) lst=raw_input().split() result=0 for j in lst: if j.count("4")+j.count("7")>k: result+=1 print n-result
There are N people standing in a queue from west to east. Given is a string S of length N representing the directions of the people. The i-th person from the west is facing west if the i-th character of S is `L`, and east if that character of S is `R`. A person is happy if the person in front of him/her is facing the...
3
n,k=map(int,input().split()) s=input() ct=0 for i in range(n-1): if s[i]==s[i+1]:ct+=1 print(min(ct+2*k,n-1))
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word s. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if...
3
word = 'hello' inp = input() index = 0 count = 0 for i in inp: if index == len(word): break if i == word[index]: count += 1 index += 1 if count == len(word): print("YES") else: print("NO")
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
s,v,w,t,y=map(int,input().split(' ')) if (2*t+s*v)<(2*y+s*w): print('First') elif (2*t+s*v)>(2*y+s*w): print('Second') else: print('Friendship')
In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it...
1
raw_input() seq = raw_input() print len(seq)*2 - len(seq.lstrip('<')) - len(seq.rstrip('>'))
Guy-Manuel and Thomas have an array a of n integers [a_1, a_2, ..., a_n]. In one step they can add 1 to any element of the array. Formally, in one step they can choose any integer index i (1 ≀ i ≀ n) and do a_i := a_i + 1. If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and T...
3
t = int(input()) for _ in range(t): ops = 0 n = int(input()) arr = [int(i) for i in input().split()] for i in range(n): if arr[i] == 0: arr[i] = 1 ops += 1 if sum(arr) == 0: ops += 1 print(ops)
Omkar is playing his favorite pixelated video game, Bed Wars! In Bed Wars, there are n players arranged in a circle, so that for all j such that 2 ≀ j ≀ n, player j - 1 is to the left of the player j, and player j is to the right of player j - 1. Additionally, player n is to the left of player 1, and player 1 is to the...
3
from sys import stdin input=lambda:stdin.readline().rstrip() for _ in range(int(input())): n=int(input()) s=input() ans=0 f=[1] for i in range(1,n): if s[i]==s[i-1]:f[-1]+=1 else:f.append(1) if s[0]==s[-1] and len(f)>1:f[0]+=f[-1];f.pop() if len(f)==1:f[0]+=2 for i in f:a...
Cengiz recently learned Fibonacci numbers and now he is studying different algorithms to find them. After getting bored of reading them, he came with his own new type of numbers that he named XORinacci numbers. He defined them as follows: * f(0) = a; * f(1) = b; * f(n) = f(n-1) βŠ• f(n-2) when n > 1, where βŠ• de...
3
def main(): import sys input = sys.stdin.readline for _ in range(int(input())): a, b, n = map(int, input().split()) n %= 3 if n == 0: print(a) elif n == 1: print(b) else: print(a^b) return 0 main()
In Takahashi Kingdom, there is a east-west railroad and N cities along it, numbered 1, 2, 3, ..., N from west to east. A company called AtCoder Express possesses M trains, and the train i runs from City L_i to City R_i (it is possible that L_i = R_i). Takahashi the king is interested in the following Q matters: * The ...
3
import sys input=lambda: sys.stdin.readline().rstrip() n,m,q=map(int,input().split()) T=[[0]*(n+2) for _ in range(n+2)] for _ in range(m): l,r=map(int,input().split()) T[l][r]+=1 for i in range(1,n+1)[::-1]: for j in range(1,n+1): T[i][j+1]+=T[i][j] for j in range(1,n+1): for i in range(1,n+1)[::-1]: T...
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 z in range(t): n = int(input()) l = list(map(int, input().split())) max_index = max(l) + 1 freq = [0]*102 for i in l: freq[i] += 1 first = 0 while(freq[first]>1): first += 1 sec = first while(freq[sec]>0): sec += 1 print(sec+first) ...
A group of n dancers rehearses a performance for the closing ceremony. The dancers are arranged in a row, they've studied their dancing moves and can't change positions. For some of them, a white dancing suit is already bought, for some of them β€” a black one, and for the rest the suit will be bought in the future. On ...
1
from sys import stdin, stdout ti = lambda : stdin.readline().strip() ma = lambda fxn, ti : map(fxn, ti.split()) ol = lambda arr : stdout.write(' '.join(str(i) for i in arr) + '\n') os = lambda i : stdout.write(str(i) + '\n') olws = lambda arr : stdout.write(''.join(str(i) for i in arr) + '\n') import math import copy ...
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()) A = list(map(int,input().split())) A.sort() mini = abs(A[1] - A[0]) for j in range(2,n,1): mini = min(abs(A[j]-A[j-1]),mini) print(mini)
There are n monsters standing in a row numbered from 1 to n. The i-th monster has h_i health points (hp). You have your attack power equal to a hp and your opponent has his attack power equal to b hp. You and your opponent are fighting these monsters. Firstly, you and your opponent go to the first monster and fight it...
3
def solve(n,a,b,k,ar): for i in range(n): ar[i] = ar[i] % (a+b) if ar[i] == 0: ar[i] += a+b ar[i] = int(((ar[i] + a - 1)//a) - 1) ar.sort() ans = 0 for i in range(n): if k - ar[i] < 0: break ans += 1 k -= ar[i] print(ans) if __name__ == '__mai...
When preparing a tournament, Codeforces coordinators try treir best to make the first problem as easy as possible. This time the coordinator had chosen some problem and asked n people about their opinions. Each person answered whether this problem is easy or hard. If at least one of these n people has answered that th...
3
def main(): n=int(input()) k=map(int,input().split()) if(sum(k)>0): return("HARD") else: return("EASY") print(main())
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two...
3
from collections import defaultdict def log2(i): c = 0 while i > 0: i >>= 1 c += 1 return c q = int(input()) t = defaultdict(int) def add(u, v, w): lu = int(log2(u)) lv = int(log2(v)) if lv > lu: u, lu, v, lv = v, lv, u, lu for _ in range(lu - lv): t[u] += ...
Theatre Square in the capital city of Berland has a rectangular shape with the size n Γ— m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a Γ— a. What is the least number of flagstones needed to pave the Square? It'...
3
import math n, m, a = [int(i) for i in input().split(" ")] num = math.ceil(n / a) * math.ceil(m / a) print(num)
You are given a string s, consisting of n lowercase Latin letters. A substring of string s is a continuous segment of letters from s. For example, "defor" is a substring of "codeforces" and "fors" is not. The length of the substring is the number of letters in it. Let's call some string of length n diverse if and o...
1
n = int(raw_input()) s = raw_input() ans = None for i in xrange(1, n): if s[i-1] != s[i]: ans = s[i-1:i+1] if ans is None: print 'NO' else: print 'YES' print ans
Anya has bought a new smartphone that uses Berdroid operating system. The smartphone menu has exactly n applications, each application has its own icon. The icons are located on different screens, one screen contains k icons. The icons from the first to the k-th one are located on the first screen, from the (k + 1)-th ...
1
I=lambda:map(int, raw_input().split()) n,m,k=I() a=I() b=I() move = 0 count = {j: i for i, j in enumerate(a)} for x in b: move += (count[x] / k)+1 if count[x] > 0: prev = a[count[x]-1] a[count[x]], a[count[x]-1] = a[count[x]-1], a[count[x]] count[x] -= 1 count[prev] += 1 print move
Leo has developed a new programming language C+=. In C+=, integer variables can only be changed with a "+=" operation that adds the right-hand side value to the left-hand side variable. For example, performing "a += b" when a = 2, b = 3 changes the value of a to 5 (the value of b does not change). In a prototype progr...
3
for i in range(int(input())): a,b,n=map(int,input().split()) count=0 while n>=a and n>=b: if a<b: a+=b count+=1 else: b+=a count+=1 print(count)
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≀ i ≀ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is it...
3
n = int(input()) s =[int(i) for i in input().split()] next_max = 1 last_max = 0 for i in range(n-1): if last_max < next_max: last_max = next_max if s[i] <= s[i+1]: next_max +=1 else: next_max = 1 print(max(last_max,next_max))
You are given a system of pipes. It consists of two rows, each row consists of n pipes. The top left pipe has the coordinates (1, 1) and the bottom right β€” (2, n). There are six types of pipes: two types of straight pipes and four types of curved pipes. Here are the examples of all six types: <image> Types of pipes ...
3
for t in range(int(input())): n = int(input()) tubes = [input(), input()] i = 0; error = False; for j in range(n): if tubes[i][j] >= '3': if tubes[i^1][j] < '3': error = True; break; else: i ^= 1; if not(error) ...
A permutation of length n is an array p=[p_1,p_2,...,p_n], which contains every integer from 1 to n (inclusive) and, moreover, each number appears exactly once. For example, p=[3,1,4,2,5] is a permutation of length 5. For a given number n (n β‰₯ 2), find a permutation p in which absolute difference (that is, the absolut...
3
t = int(input()) for _ in range(t): n = int(input()) if n<=3: print(-1) else: wow = [2, 4, 1, 3] for i in range(5, n+1): if i%2==1: wow.append(i) else: wow = [i] + wow print(*wow)
You have r red, g green and b blue balloons. To decorate a single table for the banquet you need exactly three balloons. Three balloons attached to some table shouldn't have the same color. What maximum number t of tables can be decorated if we know number of balloons of each color? Your task is to write a program tha...
3
a=map(int,input().split()) a=sorted(a) if a[2] > (a[0]+a[1])*2: print(a[0]+a[1]) else: print((int(sum(a)/3)))
Let N be a positive odd number. There are N coins, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N), when Coin i is tossed, it comes up heads with probability p_i and tails with probability 1 - p_i. Taro has tossed all the N coins. Find the probability of having more heads than tails. Constraints * N is an od...
3
N = int(input()) *P, = map(float, input().split()) dp = [[0]*(N+1) for i in range(N+1)] for i in range(N+1): if N <= 2*i: dp[N][i] = 1. for c in range(N-1, -1, -1): p = P[c] for k in range(N-1, -1, -1): dp[c][k] = r = p * dp[c+1][k+1] + (1.-p) * dp[c+1][k] print("%.10f" % dp[0][0])
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
s=input() a=s.count("Danil",0,len(s))+s.count("Olya",0,len(s))+s.count("Slava",0,len(s))+s.count("Ann",0,len(s))+s.count("Nikita",0,len(s)) if(a==1): print("YES") elif(a!=1): print("NO")
You are given a binary string s consisting of n zeros and ones. Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should no...
3
n = int(input()) for _ in range(n): nn = int(input()) ls = [[], []] s = input() last = 0 ans = [0 for x in range(nn)] for i, c in enumerate(s): c = int(c) if len(ls[c ^ 1]) == 0: last += 1 ls[c].append(last) ans[i] = last else: ...
Ilya is a very clever lion, he lives in an unusual city ZooVille. In this city all the animals have their rights and obligations. Moreover, they even have their own bank accounts. The state of a bank account is an integer. The state of a bank account can be a negative number. This means that the owner of the account ow...
3
n = input() if n[0] != '-': print(n) else: l = len(n) print(max(int(n[:l-1]),int(n[:l-2]+n[-1])))
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution....
3
n=int(input()) Contador=0 k=0 while k<n: k=k+1 t=[int(x) for x in input().split()] s=t[0]+t[1]+t[2] if s>=2: Contador=Contador+1 print (Contador)
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob β€” to check his answers, he needs a program that among the given n numbers finds one that is di...
3
input() nums = [int(x) for x in input().split()] n_even = len([x for x in nums if x % 2 == 0]) if n_even > len(nums) // 2: for index, x in enumerate(nums): if x % 2 == 1: print(index + 1) else: for index, x in enumerate(nums): if x % 2 == 0: print(index + 1)
Vanya has a table consisting of 100 rows, each row contains 100 cells. The rows are numbered by integers from 1 to 100 from bottom to top, the columns are numbered from 1 to 100 from left to right. In this table, Vanya chose n rectangles with sides that go along borders of squares (some rectangles probably occur mult...
1
import sys, math def rs(): return sys.stdin.readline().strip() def ri(): return int(sys.stdin.readline().strip()) def ras(): return list(sys.stdin.readline().strip()) def rai(): return map(int,sys.stdin.readline().strip().split()) def raf(): return map(float,sys.stdin.readline().strip().split()) de...
Given a matrix (H Γ— W) which contains only 1 and 0, find the area of the largest square matrix which only contains 0s. Constraints * 1 ≀ H, W ≀ 1,400 Input H W c1,1 c1,2 ... c1,W c2,1 c2,2 ... c2,W : cH,1 cH,2 ... cH,W In the first line, two integers H and W separated by a space character are given. In the follo...
3
import sys # import re import math import collections # import decimal import bisect import itertools import fractions # import functools import copy # import heapq import decimal # import statistics import queue # import numpy as np sys.setrecursionlimit(10000001) INF = 10 ** 16 MOD = 10 ** 9 + 7 # MOD = 998244353 ...
Petr has just bought a new car. He's just arrived at the most known Petersburg's petrol station to refuel it when he suddenly discovered that the petrol tank is secured with a combination lock! The lock has a scale of 360 degrees and a pointer which initially points at zero: <image> Petr called his car dealer, who in...
3
'''input 3 10 20 30 ''' from sys import stdin def myfunction(n, arr): flag = False for i in range(1 << n): sumi = 0 for j in range(n): if (1 << j) & i: sumi += arr[j] else: sumi -= arr[j] sumi = sumi % 360 if sumi == 0: flag = True if flag: return "YES" else: return "NO" # main ...
There are two sisters Alice and Betty. You have n candies. You want to distribute these n candies between two sisters in such a way that: * Alice will get a (a > 0) candies; * Betty will get b (b > 0) candies; * each sister will get some integer number of candies; * Alice will get a greater amount of candie...
3
def find_combo(): numeri = [] inp = input() for x in range(int(inp)): numeri.append(input()) for i in numeri: print((int(i)-1) // 2) find_combo()
You're given a row with n chairs. We call a seating of people "maximal" if the two following conditions hold: 1. There are no neighbors adjacent to anyone seated. 2. It's impossible to seat one more person without violating the first rule. The seating is given as a string consisting of zeros and ones (0 means...
3
input() s = '0' + input() + '0' if '11' in s: print('No') exit() if '000' in s: print('No') exit() print('Yes')
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings. Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, seco...
3
n=int(input()) words=[] if n==1: print("I hate it") else: for i in range(n): words.append("I") if i%2==0: words.append("hate") else: words.append("love") words.append("that") words[3*n-1]="it" print(" ".join(words))
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." β€” an excerpt from contest rules. A total of n participants took part in the contest (n β‰₯ k), and you already know their scores. Calculate how many ...
3
n, k = map(int, input().split()) scores = list(map(int,input().split())) standard_score = scores[k-1] for i in range(n): if scores[i] >= standard_score and scores[i] > 0: scores[i] = 1 else: scores[i] = 0 print(sum(scores))
Volodya has recently visited a very odd town. There are N tourist attractions in the town and every two of them are connected by a bidirectional road. Each road has some travel price (natural number) assigned to it and all prices are distinct. But the most striking thing about this town is that each city sightseeing to...
1
a = [0, 1, 3, 7, 12, 20, 30, 44, 65, 80, 96, 122, 147, 181, 203, 251, 289, 360, 400, 474] n = input() for i in range(n): for j in range(n): if i == j: print 0, else: print a[i] + a[j], print
In number world, two different numbers are friends if they have a lot in common, but also each one has unique perks. More precisely, two different numbers a and b are friends if gcd(a,b), (a)/(gcd(a,b)), (b)/(gcd(a,b)) can form sides of a triangle. Three numbers a, b and c can form sides of a triangle if a + b > c, b...
3
import os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def findprime(): n = 1000000 prime = [1 for i in range(n + 1)] prime[0] = 0 prime[1] = 0 p = 2 while p * p <= n: if prime[p]: for i in range(p * p, n + 1, p): prime[i] = 0 p ...
After celebrating the midcourse the students of one of the faculties of the Berland State University decided to conduct a vote for the best photo. They published the photos in the social network and agreed on the rules to choose a winner: the photo which gets most likes wins. If multiple photoes get most likes, the win...
3
num = input() line = input() line = line + ' '; temp = '' dictt = {} maxx = 0 maxxid = None for char in line: if char == ' ': if temp in dictt: dictt[temp] = dictt[temp] + 1 else: dictt[temp] = 1 if dictt[temp] > maxx: maxx = dictt[temp] maxxid = temp temp = '' else: tem...
Misha and Vasya participated in a Codeforces contest. Unfortunately, each of them solved only one problem, though successfully submitted it at the first attempt. Misha solved the problem that costs a points and Vasya solved the problem that costs b points. Besides, Misha submitted the problem c minutes after the contes...
3
a,b,c,d = list(map(int,input().split())) a = max(3*a /10, a- (a/250 * c)) ; b = max (3*b /10, b- (b/250 * d)) if(a == b): print("Tie") elif(a > b): print("Misha") else: print("Vasya")
Notes Template in C Constraints 2 ≀ the number of operands in the expression ≀ 100 1 ≀ the number of operators in the expression ≀ 99 -1 Γ— 109 ≀ values in the stack ≀ 109 Input An expression is given in a line. Two consequtive symbols (operand or operator) are separated by a space character. You can assume that +...
3
l=list(input().split()) l=l[::-1] stack=[] while len(l)>0: n=l.pop() if n in ["+","-","*"]: a=int(stack.pop()) b=int(stack.pop()) if n=="+": stack.append(a+b) elif n=="-": stack.append(b-a) else: stack.append(a*b) else: stack.append(n) print(stack[-1])
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem. Pete and Bi...
3
w = int(input("")) if w%2 == 1: print("no") elif w == 2: print("no") else: print("yes")
Write a program which reads a $n \times m$ matrix $A$ and a $m \times l$ matrix $B$, and prints their product, a $n \times l$ matrix $C$. An element of matrix $C$ is obtained by the following formula: \\[ c_{ij} = \sum_{k=1}^m a_{ik}b_{kj} \\] where $a_{ij}$, $b_{ij}$ and $c_{ij}$ are elements of $A$, $B$ and $C$ res...
3
n, m, l = [int(i) for i in input().split()] a = [[int(i) for i in input().split()] for j in range(n)] b = [[int(i) for i in input().split()] for j in range(m)] ans = [[0]*l for i in range(n)] for i in range(n): for j in range(l): for k in range(m): ans[i][j] += a[i][k]*b[k][j] print("\n".join(" ...
After a probationary period in the game development company of IT City Petya was included in a group of the programmers that develops a new turn-based strategy game resembling the well known "Heroes of Might & Magic". A part of the game is turn-based fights of big squadrons of enemies on infinite fields where every cel...
3
a = int(input()) print(6 * (a + a * (a - 1) // 2) + 1)
Vasya has started watching football games. He has learned that for some fouls the players receive yellow cards, and for some fouls they receive red cards. A player who receives the second yellow card automatically receives a red card. Vasya is watching a recorded football match now and makes notes of all the fouls tha...
3
def main(): home = input() away = input() n = int(input()) cards = {} teams = {} teams['h'] = home teams['a'] = away for i in range(n): t,team,m,card = map(str,input().split()) t = int(t) m = int(m) curr = (team,m) if curr not in cards.keys(): ...
Many years ago Berland was a small country where only n people lived. Each person had some savings: the i-th one had a_i burles. The government considered a person as wealthy if he had at least x burles. To increase the number of wealthy people Berland decided to carry out several reforms. Each reform looked like that...
3
import sys import math def get_array(): return list(map(int,sys.stdin.readline().strip().split())) def get_ints(): return map(int,sys.stdin.readline().strip().split()) def input(): return sys.stdin.readline().strip() for _ in range(int(input())): a,b=get_ints() c=get_array() d=sorted(c) sumi=c[0] co...