problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
You are given a rectangular board of M Γ— N squares. Also you are given an unlimited number of standard domino pieces of 2 Γ— 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions: 1. Each domino completely covers two squa...
3
m, n = input().split() mul = int(m)*int(n) print(mul//2)
You are given some Tetris field consisting of n columns. The initial height of the i-th column of the field is a_i blocks. On top of these columns you can place only figures of size 2 Γ— 1 (i.e. the height of this figure is 2 blocks and the width of this figure is 1 block). Note that you cannot rotate these figures. Yo...
3
def ans(a): k=0 for i in a: k=k+i%2 if k==0 or k==len(a): return "YES" else: return "NO" for i in range(int(input())): n=int(input()) a=list(map(int,input().split())) print(ans(a))
Shaass has decided to hunt some birds. There are n horizontal electricity wires aligned parallel to each other. Wires are numbered 1 to n from top to bottom. On each wire there are some oskols sitting next to each other. Oskol is the name of a delicious kind of birds in Shaass's territory. Supposed there are ai oskols ...
1
n = int(raw_input()) w = [0] + map(int, raw_input().split()) + [0] for _ in range(int(raw_input())): i, p = map(int, raw_input().split()) w[i - 1] += p - 1 w[i + 1] += w[i] - p w[i] = 0 for i in w[1:n + 1]: print i
You're given an undirected graph with n nodes and m edges. Nodes are numbered from 1 to n. The graph is considered harmonious if and only if the following property holds: * For every triple of integers (l, m, r) such that 1 ≀ l < m < r ≀ n, if there exists a path going from node l to node r, then there exists a pat...
3
def main(): n, m = map(int, input().split()) a = [] for i in range(n + 1): a.append([]) for i in range(m): u, v = map(int, input().split()) a[u].append(v) a[v].append(u) used = [0] * (n + 1) ans = 0 con = 1 for i in range(1, n + 1): if not used[i]: b = [i] if i < con: ans += 1 while len(b...
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were 2n jars of strawberry and blueberry jam. All the 2n jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exa...
3
def inp(ai): cur = sum(ai) * 2 - n * 3 yield cur for aii in ai: if aii == 1: cur += 1 else: cur -= 1 yield cur def inp2(ii): ans = {} for i, iii in enumerate(ii): if iii not in ans: ans[iii] = i return ans for _ in range(int...
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
n=input() if len(n)==1: if n.isupper(): print(n.lower()) else: print(n.upper()) quit() if n[1:].isupper(): if n[0].isupper(): print(n.lower()) else: print(n[0].upper()+n[1:].lower()) else: print(n)
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
# -*- coding: utf-8 -*- """ Created on Sat May 23 17:34:20 2020 @author: user """ import sys input = sys.stdin.readline output=sys.stdout def inp(): return(int(input())) def inlt(): return(list(map(int,input().split()))) def insr(): s = input() return(list(s[:len(s) - 1])) def invr(): return(map(i...
Very soon Berland will hold a School Team Programming Olympiad. From each of the m Berland regions a team of two people is invited to participate in the olympiad. The qualifying contest to form teams was held and it was attended by n Berland students. There were at least two schoolboys participating from each of the m ...
1
def top_two_indices(s): if len(s) == 2: return [0, 1, -1] # s = list(scores) first = second = third = 0 i = [-1, -1, -1] for j in range (len(s)): if s[j] >= first: third = second second = first first = s[j] i[2] = i[1] i[1] = i[0] i[0] = j elif s[j] >= second: third = second second =...
Let's define the following recurrence: $$$a_{n+1} = a_{n} + minDigit(a_{n}) β‹… maxDigit(a_{n}).$$$ Here minDigit(x) and maxDigit(x) are the minimal and maximal digits in the decimal representation of x without leading zeroes. For examples refer to notes. Your task is calculate a_{K} for given a_{1} and K. Input The ...
3
t = int(input()) for i in range(t): a,k = map(int,input().split()) for i in range(k-1): a += int(min(list(str(a))))*int(max(list(str(a)))) #print(a,i) if int(min(list(str(a)))) == 0: break print(a)
You are given a string s consisting of n lowercase Latin letters. You have to type this string using your keyboard. Initially, you have an empty string. Until you type the whole string, you may perform the following operation: * add a character to the end of the string. Besides, at most once you may perform one...
3
N = int(input()) S = input() copied = 1 for i in range(1,N//2+1): # print(i, "\"{}\"".format(S[:i]), "\"{}\"".format(S[i:2*i])) if S[:i] == S[i:2*i]: copied = i print(N-copied+1)
There are n students in a school class, the rating of the i-th student on Codehorses is a_i. You have to form a team consisting of k students (1 ≀ k ≀ n) such that the ratings of all team members are distinct. If it is impossible to form a suitable team, print "NO" (without quotes). Otherwise print "YES", and then pri...
3
a,b=map(int,input().split()) array=list(map(int,input().split())) output = [] index = [] for x in range(a): if array[x] not in output : output.append(array[x]) index.append(x) if len(index)>= b : print("YES") for i in range(b): print("%d "%(index[i]+1),end='') else : print("NO",end='')
Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game. Rules of the game are very simple: at first number of rounds n is defined. I...
3
n = int(input()) c1 = c2 = 0 for i in range(n) : m, c = input().split(" ") if(m > c) : c1 += 1 elif(m < c) : c2 += 1 if(c1 > c2) : print("Mishka") elif(c1 == c2) : print("Friendship is magic!^^") else : print("Chris")
Taro's summer vacation starts tomorrow, and he has decided to make plans for it now. The vacation consists of N days. For each i (1 \leq i \leq N), Taro will choose one of the following activities and do it on the i-th day: * A: Swim in the sea. Gain a_i points of happiness. * B: Catch bugs in the mountains. Gain b_i...
3
N = int(input()) dp = [[0] * 3 for _ in range(N + 1)] for i in range(N): a, b, c = list(map(int, input().split())) dp[i+1][0] = a + max(dp[i][1:]) dp[i+1][1] = b + max(dp[i][::2]) dp[i+1][2] = c + max(dp[i][:2]) print(max(dp[N]))
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...
1
n=input() s=raw_input() print 'Friendship' if s.count('A')==s.count('D') else 'Anton' if s.count('A')>s.count('D') else 'Danik'
Gaius Julius Caesar, a famous general, loved to line up his soldiers. Overall the army had n1 footmen and n2 horsemen. Caesar thought that an arrangement is not beautiful if somewhere in the line there are strictly more that k1 footmen standing successively one after another, or there are strictly more than k2 horsemen...
3
def main(): n, m, a, b = map(int, input().split()) dp = [[[-1] * (m + 1) for _ in range(n + 1)] for _ in (0, 1)] if n and a: dp[0][0][0] = 1 if m and b: dp[1][0][0] = 1 def solve(n, m, fg): res = dp[fg][n][m] if res == -1: res = dp[fg][n][m] = (sum(so...
Vanya loves playing. He even has a special set of cards to play with. Each card has a single integer. The number on the card can be positive, negative and can even be equal to zero. The only limit is, the number on each card doesn't exceed x in the absolute value. Natasha doesn't like when Vanya spends a long time pla...
1
n,x = map(int, raw_input().split()) v = map(int, raw_input().split()) s = abs(sum(v)) if s%x==0: print s/x else: print s/x +1
Your friend recently gave you some slimes for your birthday. You have n slimes all initially with value 1. You are going to play a game with these slimes. Initially, you put a single slime by itself in a row. Then, you will add the other n - 1 slimes one by one. When you add a slime, you place it at the right of all a...
1
# -*- coding: utf-8 -*- import sys,copy,math,heapq,itertools as it,fractions,re,bisect,collections as coll n = int(raw_input()) k = 0 a = [] for i in xrange(n): a.append(1) k += 1 while k >= 2 and a[-1] == a[-2]: a.pop() a[-1] += 1 k -= 1 print " ".join(map(str, a))
So, the New Year holidays are over. Santa Claus and his colleagues can take a rest and have guests at last. When two "New Year and Christmas Men" meet, thear assistants cut out of cardboard the letters from the guest's name and the host's name in honor of this event. Then the hung the letters above the main entrance. O...
1
from collections import Counter st1=raw_input() st2=raw_input() st3=raw_input() ans=st1+st2 if Counter(ans) == Counter(st3): print "YES" else: print "NO"
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network. Bu...
3
def split(word): return [char for char in word] user_name = str(input("")) userlist = list(set(split(user_name))) t = len(userlist) if(t%2 == 0): print('CHAT WITH HER!') else: print('IGNORE HIM!')
Every superhero has been given a power value by the Felicity Committee. The avengers crew wants to maximize the average power of the superheroes in their team by performing certain operations. Initially, there are n superheroes in avengers team having powers a_1, a_2, …, a_n, respectively. In one operation, they can r...
3
from math import ceil,sqrt,gcd,log,floor from collections import deque def ii(): return int(input()) def si(): return input() def mi(): return map(int,input().strip().split(" ")) def li(): return list(mi()) def msi(): return map(str,input().strip().split(" ")) def lsi(): return list(msi()) #for _ in range(ii()): n,k,m=...
You are given array consisting of n integers. Your task is to find the maximum length of an increasing subarray of the given array. A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray strictly greater than previous. Input The first line cont...
3
def f(n,arr): m,l=1,1 for i in range(1,n): if arr[i]>arr[i-1]: l=l+1 else: if m<l: m=l l=1 if m<l: m=l return m n=int(input()) arr=list(map(int,input().split())) print(f(n,arr))
A PIN code is a string that consists of exactly 4 digits. Examples of possible PIN codes: 7013, 0000 and 0990. Please note that the PIN code can begin with any digit, even with 0. Polycarp has n (2 ≀ n ≀ 10) bank cards, the PIN code of the i-th card is p_i. Polycarp has recently read a recommendation that it is bette...
3
from math import* t=int(input()) for _ in range(t): n=int(input()) a=[0]*9999 ans_list=[] ans=0 for i in range(n): pin=int(input()) a[pin]+=1 ans_list.append(pin) for roentail in range(len(ans_list)): i=ans_list[roentail] if a[i]>1: ans+=1 ...
Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are n drinks in his fridge, the volume fraction of orange juice in the i-th drink equals pi percent. One day Vasya decided to make himself an orange cocktail. He took equal proportions of ea...
3
n = int(input()) p = [int(i) for i in input().split()] m = 0 for i in range(len(p)): if p[i] > 0: m += p[i]/100 else: pass a = (m/n)*100 print(f'{a:.12f}')
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
import math n = int(input()) x = math.ceil(n / 2) if n%2==0: print(x) else: print(x*-1)
Once again Tavas started eating coffee mix without water! Keione told him that it smells awful, but he didn't stop doing that. That's why Keione told his smart friend, SaDDas to punish him! SaDDas took Tavas' headphones and told him: "If you solve the following problem, I'll return it to you." <image> The problem is:...
3
n = input() position = 2*(2**(len(n)-1) - 1) n = n.replace('4','0') n = n.replace('7','1') position += int(n,2) + 1 print(position)
Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor Β«TextpadΒ» decided to introduce this functionality into the fourth release of the product. You are to implement the alignment in the shortest possible time. Good luck! Input The input file c...
1
import sys lines=[] m=0 for line in sys.stdin: lines.append(line.strip()) m=max(m,len(lines[-1])) print '*'*(m+2) l=1 for i in lines: u=m-len(i) if u%2: if l: u/=2 else: u+=1 u/=2 l^=1 else:u/=2 print '*'+u*' '+i+(m-u-len(i))*' '+'*' pr...
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
count = int(input()) res = int(count / 2); if count % 2 == 1: res -= count print(res)
Ujan decided to make a new wooden roof for the house. He has n rectangular planks numbered from 1 to n. The i-th plank has size a_i Γ— 1 (that is, the width is 1 and the height is a_i). Now, Ujan wants to make a square roof. He will first choose some of the planks and place them side by side in some order. Then he will...
3
T = int(input()) for _ in range(T): num = int(input()) s = sorted(list(map(int,input().split()))) s = s[::-1] for i in range(max(s),0,-1): count = 0 for j in s: if j>=i: count +=1 if count >= i: print(i) break
There are two standard ways to represent a graph $G = (V, E)$, where $V$ is a set of vertices and $E$ is a set of edges; Adjacency list representation and Adjacency matrix representation. An adjacency-list representation consists of an array $Adj[|V|]$ of $|V|$ lists, one for each vertex in $V$. For each $u \in V$, th...
3
if __name__ == '__main__': n = int(input()) for i in range(n): u, k, *v = map(int, input().split()) a = [0] * n for i_v in v: index_v = i_v -1 a[index_v] = 1 print(*a)
Nauuo is a girl who loves writing comments. One day, she posted a comment on Codeforces, wondering whether she would get upvotes or downvotes. It's known that there were x persons who would upvote, y persons who would downvote, and there were also another z persons who would vote, but you don't know whether they woul...
3
x, y, z=map(int, input().split()) if x+z>y and x>y+z: print("+") elif x+z<y and x<y+z: print("-") elif(x+z==y and x==y+z): print(0) else: print("?")
A line on the plane is described by an equation Ax + By + C = 0. You are to find any point on this line, whose coordinates are integer numbers from - 5Β·1018 to 5Β·1018 inclusive, or to find out that such points do not exist. Input The first line contains three integers A, B and C ( - 2Β·109 ≀ A, B, C ≀ 2Β·109) β€” corres...
1
def egcd(a, b): if not b: return 1, 0, a y, x, g = egcd(b, a % b) return x, y - a / b * x, g a, b, c = map(int, raw_input().split()) x, y, g = egcd(a, b) if c % g: print '-1' else: c /= g print -x * c, -y * c
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. Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find ...
1
def isLucky (n): n = str(n) for i in n: if (not i in "74"): return False return True vec = [] for i in xrange(4, 778): if (isLucky(i)): vec.append(i) vec.sort() n = int(raw_input()) t = False for i in vec: if(n % i == 0): t = True if(t == True): print ("YES") else: print ("NO")
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation. The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe...
3
s = input() ones = s.count("1") twos = s.count("2") threes = s.count("3") digits = [] for i in range(ones): digits.append("1") for i in range(twos): digits.append("2") for i in range(threes): digits.append("3") print("+".join(digits))
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
res = 0 a, b = map(int, input().split()) while a <=b: a, b = a*3, b*2 res+=1 print(res)
Valera has got n domino pieces in a row. Each piece consists of two halves β€” the upper one and the lower one. Each of the halves contains a number from 1 to 6. Valera loves even integers very much, so he wants the sum of the numbers on the upper halves and the sum of the numbers on the lower halves to be even. To do t...
3
n = int(input()) a = [list(map(int, input().split())) for i in range(n)] flg = 0 x = 0 y = 0 for e in a: x += e[0] y += e[1] if e[0] % 2 != e[1] % 2: flg = 1 if (x + y) % 2 == 1: print(-1) elif x % 2 == 0: print(0) elif flg > 0: print(1) else: print(-1)
The city park of IT City contains n east to west paths and n north to south paths. Each east to west path crosses each north to south path, so there are n2 intersections. The city funded purchase of five benches. To make it seems that there are many benches it was decided to place them on as many paths as possible. Ob...
1
#!/usr/bin/env python # -*- coding: utf-8 -*- # # 1122.py # # Copyright 2016 Akshay Miterani <akshay@akshayMiterani> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 o...
Mislove had an array a_1, a_2, β‹…β‹…β‹…, a_n of n positive integers, but he has lost it. He only remembers the following facts about it: * The number of different numbers in the array is not less than l and is not greater than r; * For each array's element a_i either a_i = 1 or a_i is even and there is a number (a_i)/(...
3
n, l, r = map(int, input().split()) mini = n-l j = 1 for i in range(l): mini += j j *= 2 maxi = 2**(r-1) * (n-r) j = 1 for i in range(r): maxi += j j *= 2 print(mini, maxi)
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
useless1 = input() input1 = input() useless2 = input() input2 = input() firstlist = input1.split( ) secondlist = input2.split( ) counter = 0 for number in firstlist: (firstlist[counter])=int(number) counter = counter+1 counter=0 for number in secondlist: (secondlist[counter])=int(number) counter = counter+1 cou...
The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: * d1 is the distance between the 1-st and the 2-nd station; * d2 is the distance between the 2-nd and the 3-rd station; ... * dn - 1 is the distance between the n - 1-th and the n-th station; ...
1
import sys stations = int(sys.stdin.readline()) dists = [int(x) for x in sys.stdin.readline().split()] [s, t] = [int(x) for x in sys.stdin.readline().split()] mini = min(s,t) - 1 maxi = max(s,t) - 1 first_d = sum(dists[mini:maxi]) second_d = sum(dists[maxi:]) + sum(dists[0:mini]) print min(first_d, second_d)
You are given an array a consisting of n integers a_1, a_2, ... , a_n. In one operation you can choose two elements of the array and replace them with the element equal to their sum (it does not matter where you insert the new element). For example, from the array [2, 1, 4] you can obtain the following arrays: [3, 4],...
3
t = int(input()) for i in range(t): n = int(input()) x = list(map(int, input().split())) cnt, remainders = 0, 0 a = [] for j in range(n): if x[j] % 3 == 0: cnt += 1 else: a.append(x[j] % 3) if a.count(1) >= a.count(2): cnt += a.count(2) cnt...
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() check=0 c7=n.count('7') c4=n.count('4') if c7+c4 ==7 or c7+c4==4: print('YES') else: print("NO")
JATC and his friend Giraffe are currently in their room, solving some problems. Giraffe has written on the board an array a_1, a_2, ..., a_n of integers, such that 1 ≀ a_1 < a_2 < … < a_n ≀ 10^3, and then went to the bathroom. JATC decided to prank his friend by erasing some consecutive elements in the array. Since he...
3
n= int(input()) l= list(map(int,input().split())) ma =0 s=0 for i in range(n-1): for j in range(i+1,n): if(l[j]-l[i]==j-i): s= j-i-1 if(l[i]==1): s=s+1 if(l[j]==1000): s=s+1 ma = max(ma,s) print(ma)
One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are n lines in that description each of which described one goal. Eve...
3
# cook your dish here n=int(input()) #lst=list(map(int,input().rstrip().split())) dictt=dict() for i in range (n): team=input() dictt.setdefault(team,0) dictt[team]+=1 print(max(dictt, key=dictt.get))
Your task is to calculate the number of arrays such that: * each array contains n elements; * each element is an integer from 1 to m; * for each array, there is exactly one pair of equal elements; * for each array a, there exists an index i such that the array is strictly ascending before the i-th element a...
3
from bisect import bisect_left as bl from bisect import bisect_right as br import heapq import math from collections import * from functools import reduce,cmp_to_key import sys input = sys.stdin.readline M = mod = 998244353 def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0....
A word or a sentence in some language is called a pangram if all the characters of the alphabet of this language appear in it at least once. Pangrams are often used to demonstrate fonts in printing or test the output devices. You are given a string consisting of lowercase and uppercase Latin letters. Check whether thi...
3
n = int(input()) s = input().upper()[:n] isPangram = True arr = ['Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Z', 'X', 'C', 'V', 'B', 'N', 'M'] for c in arr: if c not in s: isPangram = False break if isPangram: print('YES') else: print('NO')
You are given some Tetris field consisting of n columns. The initial height of the i-th column of the field is a_i blocks. On top of these columns you can place only figures of size 2 Γ— 1 (i.e. the height of this figure is 2 blocks and the width of this figure is 1 block). Note that you cannot rotate these figures. Yo...
3
for _ in range(int(input())): n=int(input()) a=list(map(int,input().split())) x=a[0]%2 for i in range(n): if a[i]%2!=x: print('NO') break if i==n-1: print('YES')
Consider a conveyor belt represented using a grid consisting of n rows and m columns. The cell in the i-th row from the top and the j-th column from the left is labelled (i,j). Every cell, except (n,m), has a direction R (Right) or D (Down) assigned to it. If the cell (i,j) is assigned direction R, any luggage kept o...
3
# -*- coding: utf-8 -*- """ Created on Sun Aug 9 20:22:29 2020 @author: Paras """ t = int(input()) while t>0: n,m = map(int, input().split()) mat = [None]*n cnt = 0 for i in range(n): mat[i] = input() if i!=(n-1): if mat[i][m-1]=="R": cnt+=1 else: ...
Let s(x) be sum of digits in decimal representation of positive integer x. Given two integers n and m, find some positive integers a and b such that * s(a) β‰₯ n, * s(b) β‰₯ n, * s(a + b) ≀ m. Input The only line of input contain two integers n and m (1 ≀ n, m ≀ 1129). Output Print two lines, one for decimal...
3
n,m = map(int, input().split()) x=2230 print('4'*(x-1)+'5') print('5'*x)
After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≀ si ≀ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum nu...
1
n = int(raw_input()) rq = raw_input() q = rq.split() data = [] cars = 0 for e in range(0,10): data.append(0) for e in q: data[int(e)]+=1 cars += data[4] cars += data[3] data[1] = max(data[1]-data[3],0) cars += data[2]/2 if data[2]%2!=0: data[1] = max(data[1]-2,0) cars += 1 if data[1]>0: cars+=data[1]/4 if data[1...
Alexandra has an even-length array a, consisting of 0s and 1s. The elements of the array are enumerated from 1 to n. She wants to remove at most n/2 elements (where n β€” length of array) in the way that alternating sum of the array will be equal 0 (i.e. a_1 - a_2 + a_3 - a_4 + ... = 0). In other words, Alexandra wants s...
3
testcases=int(input()) for _ in range(testcases): n=int(input()) arr=list(map(int,input().split())) o=0 z=0 for i in arr: if i==0: z+=1 else: o+=1 if z>=o: print(z) answer='0 '*(z) else: if o%2==0: print(o) ...
Recently Petya walked in the forest and found a magic stick. Since Petya really likes numbers, the first thing he learned was spells for changing numbers. So far, he knows only two spells that can be applied to a positive integer: 1. If the chosen number a is even, then the spell will turn it into 3a/2; 2. If t...
3
tc = int(input()) for ii in range(tc): x,y = map(int, input().split()) c = 0 if x==1: if y<=1: c = 1 elif x==2: if y<=3: c = 1 elif x==3: if y<=3: c = 1 else: c = 1 if c==1: print("YES") else: print("NO")
Monk has to visit a land where strange creatures, known as Pokemons, roam around in the wild. Each Pokemon in the land will attack any visitor. They can only be pacified by feeding them their favorite food. The Pokemon of type X eats one food item of type X. Monk knows that he will encounter N ponds on the way. At ea...
1
from collections import defaultdict for T in range(input()): n=input() fi=defaultdict(int) item=0 for i in range(n): x,y=map(int,raw_input().split(' ')) fi[x] +=1 if fi[y] != 0: fi[y] -=1 else: item += 1 print item
There exists an island called Arpa’s land, some beautiful girls live there, as ugly ones do. Mehrdad wants to become minister of Arpa’s land. Arpa has prepared an exam. Exam has only one question, given n, print the last digit of 1378n. <image> Mehrdad has become quite confused and wants you to help him. Please hel...
3
n=int(input()) if n==0: print(1) else: n=n%4 print([6, 8, 4, 2][n])
Andrew is very fond of Maths.He has N boxes with him,in each box there is some value which represents the Strength of the Box.The ith box has strength A[i]. He wants to calculate the Overall Power of the all N Boxes. Overall Power here means Sum of Absolute Difference of the strengths of the boxes(between each pair of...
1
t = int(raw_input()) while t: r = int(raw_input()) arr = map(int, raw_input().split()) arr.sort() s = 0 i = r - 1 while i >= 0: s += arr[i] * i - arr[i] * (r - i - 1) i -= 1 s %= 1000000007 m = max(arr) % 1000000007 print ((s * m) % 1000000007) t -= 1
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
a , b = map(int,input().split()) ans = 0 while True: ans +=1 a *= 3 b *= 2 if a > b : break print(ans)
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()) a=list(map(int,input().split())) c=1 l=[] for i in range(n-1): if(a[i]<=a[i+1]): c+=1 else: l.append(c) c=1 l.append(c) print(max(l)) #6 #2 2 1 3 4 1 #3 #2 2 9 #10 #1 2 3 4 1 2 3 4 5 6
"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 ...
1
n,k = [int(x) for x in raw_input().split()] list1 = [int(x) for x in raw_input().split()] if list1[k-1] == 0: t = list1.index(0) print t else: print n-list1[::-1].index(list1[k-1])
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
t=int(input()) for i in range(t): n=int(input()) r=int(n%2) d=int(n/2) if r==0: print(d-1) elif r==1: print(d)
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 Γ— n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells. So, user tncks0121 has ...
3
from collections import deque from collections import OrderedDict import math import sys import os import threading import bisect import operator import heapq from atexit import register from io import BytesIO #sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size)) #sys.stdout = BytesIO() #register(lambda: os.wri...
You are given a long decimal number a consisting of n digits from 1 to 9. You also have a function f that maps every digit from 1 to 9 to some (possibly the same) digit from 1 to 9. You can perform the following operation no more than once: choose a non-empty contiguous subsegment of digits in a, and replace each digi...
3
import math n = int(input().lstrip()) number = input().lstrip() mapping = ['0'] + input().lstrip().split() start_swap = False end_swap = False res = '' for i, num in enumerate(number): digit = int(num) i += 1 if not start_swap: if mapping[digit] > num: start_swap = True res...
Alice and Bob play a game. They have a binary string s (a string such that each character in it is either 0 or 1). Alice moves first, then Bob, then Alice again, and so on. During their move, the player can choose any number (not less than one) of consecutive equal characters in s and delete them. For example, if the...
3
mod = 10**9 + 7 def solve(): s = input() + '0' ret = [] tmp = 0 for i in range(len(s)): if s[i] == '1': tmp += 1 else: if tmp > 0: ret.append(tmp) tmp = 0 ret.sort(reverse = True) ans = 0 for i in range(0, len(ret), 2): ...
Boboniu likes playing chess with his employees. As we know, no employee can beat the boss in the chess game, so Boboniu has never lost in any round. You are a new applicant for his company. Boboniu will test you with the following chess question: Consider a nΓ— m grid (rows are numbered from 1 to n, and columns are nu...
3
import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write...
You have decided to watch the best moments of some movie. There are two buttons on your player: 1. Watch the current minute of the movie. By pressing this button, you watch the current minute of the movie and the player automatically proceeds to the next minute of the movie. 2. Skip exactly x minutes of the movi...
3
def fun(m,b,z): while m<=z:m=m+b return m-b x,y=input().split() a,b=int(x),int(y) list,list1,list2=[],[],[] for i in range(a): x,y=input().split() c,d=int(x),int(y) list.append((c,d)) list1.append(d-c) for i in range(a): if i==0:n=fun(1,b,list[i][0]) else:n=fun(((list[i-1][1])+1),b,list[...
Little Vaishnavi is bored during the vacation which is going on. Being the only little girl in the neighbourhood she did not have any one else to play with. Her parents are so strict that they will not let her out of the house even to see what the kids from the other houses are playing. So she decided to make a game o...
1
t=int(raw_input()) for i in range(t): m,k=map(int,raw_input().split()) steps=0 mid=0 if m==1 or m==5: steps=8 mid=8 elif m==2 or m==4: steps=6 mid=2 elif m==3: steps=4 mid=4 temp=0 count=0 if k & 1: temp=k/2 k-=temp if m==4: print m+(k*mid)+(temp*steps)-1 else: print m+(temp*mid)+(k*s...
So, the New Year holidays are over. Santa Claus and his colleagues can take a rest and have guests at last. When two "New Year and Christmas Men" meet, thear assistants cut out of cardboard the letters from the guest's name and the host's name in honor of this event. Then the hung the letters above the main entrance. O...
3
s1=input() s2=input() a=list(s1+s2) b=list(input()) a.sort() b.sort() n1=len(a) ans= n1==len(b) if ans: for i in range(n1): if(a[i]!=b[i]): ans=False print(["NO","YES"][ans])
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second. One day in 230 AD Shapur was trying to find out if any one can possibly do...
3
# https://codeforces.com/problemset/problem/61/A def main(): n1 = input() n2 = input() n = [] i = 0 while i < len(n1): if n1[i] == n2[i]: n.append('0') i += 1 else: n.append('1') i += 1 print(''.join(n)) if __name__ == '__mai...
You are given a positive integer n, it is guaranteed that n is even (i.e. divisible by 2). You want to construct the array a of length n such that: * The first n/2 elements of a are even (divisible by 2); * the second n/2 elements of a are odd (not divisible by 2); * all elements of a are distinct and positi...
3
for _ in range(int(input())): n = int(input()) pivot = n//2 if pivot%2==1: print('NO') else: print('YES') even_sum = pivot*(pivot+1) for i in range(1,pivot+1): print(2*i,end=' ') odd_sum = (pivot-1)**2 for i...
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them. Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain nu...
3
import sys def checkIfWUB(string): return string == 'WUB'or string == 'UB' def stripStartEnd(string): #strip starting / ending WUBs i = 0 j = len(string) - 1 while True: #starting WUBs startChar = string[i] if startChar == 'W' and checkIfWUB(string[i:i...
A penguin Rocher has n sticks. He has exactly one stick with length i for all 1 ≀ i ≀ n. He can connect some sticks. If he connects two sticks that have lengths a and b, he gets one stick with length a + b. Two sticks, that were used in the operation disappear from his set and the new connected stick appears in his se...
3
input1 = input() for i in range(int(input1)): sticks = input() print (str(1 + (int(sticks)-1)//2))
Kevin Sun wants to move his precious collection of n cowbells from Naperthrill to Exeter, where there is actually grass instead of corn. Before moving, he must pack his cowbells into k boxes of a fixed size. In order to keep his collection safe during transportation, he won't place more than two cowbells into a single ...
3
t = input() temp = t.split() n = int(temp[0]) k = int(temp[1]) s = input() temp = s.split() cowbells = [int(i) for i in temp] if (k >= n): print(cowbells[n-1]) else: singleBoxes = 2*k - n doubleBoxes = 2*(n-k) j = doubleBoxes - 1 maximum = 0 for i in range(doubleBoxes - 1): if (i == j)...
You are given the array a consisting of n positive (greater than zero) integers. In one move, you can choose two indices i and j (i β‰  j) such that the absolute difference between a_i and a_j is no more than one (|a_i - a_j| ≀ 1) and remove the smallest of these two elements. If two elements are equal, you can remove a...
3
for i in range(int(input())): n = int(input()) l = list(map(int, input().split())) l.sort() if (len(l) == 1): print("YES") else: count=0 for j in range(len(l)): if (j == len(l) - 1): break elif(abs(l[j] - l[j + 1]) > 1): ...
Zane the wizard had never loved anyone before, until he fell in love with a girl, whose name remains unknown to us. <image> The girl lives in house m of a village. There are n houses in that village, lining in a straight line from left to right: house 1, house 2, ..., house n. The village is also well-structured: hou...
3
n,m,k=map(int,input().split()) a=list(map(int,input().split())) i=m l=[] u=0 while i<n: if a[i]!=0 and a[i]<=k: r1=i+1 u=1 break i=i+1 i=m-2 while i>=0 : if a[i]!=0 and a[i]<=k: l.append(i+1) break i=i-1 if len(l)==0: print((r1-m)*10) elif u==0: ...
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm: * if the last digit of the number is non-zero, she decreases the number by one; * if the last digit of the number is ze...
3
n,k = map(int,input().split()) for i in range(k): n = str(n) if n[-1]!='0': n = int(n)-1 else: n = int(n)//10 print(n)
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves. We know that several boy&girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair m...
3
n = int(input()) a = sorted([int(x) for x in input().split()]) m = int(input()) b = sorted([int(x) for x in input().split()]) s = 0 for i in a: for j in b: if j in [i-1, i, i+1]: s = s+1 b.remove(j) break print(s)
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()) result = 0; for i in range(n): if input().count('1')>=2: result = result+1 print(result)
Boboniu likes bit operations. He wants to play a game with you. Boboniu gives you two sequences of non-negative integers a_1,a_2,…,a_n and b_1,b_2,…,b_m. For each i (1≀ i≀ n), you're asked to choose a j (1≀ j≀ m) and let c_i=a_i\& b_j, where \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise...
3
import sys def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)] def ceil(x, y=1): retu...
Recently, Norge found a string s = s_1 s_2 … s_n consisting of n lowercase Latin letters. As an exercise to improve his typing speed, he decided to type all substrings of the string s. Yes, all (n (n + 1))/(2) of them! A substring of s is a non-empty string x = s[a … b] = s_{a} s_{a + 1} … s_{b} (1 ≀ a ≀ b ≀ n). For e...
3
t,k = map(int,input().split()) string = input() chars = input().split() combo = 0 count = 0 for x in string: if(x in chars): count += 1 else: combo += (count * (count+1))//2 count = 0 combo += (count * (count+1))//2 print(combo)
After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≀ si ≀ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum nu...
3
import math l = [0]*4 n = int(input()) for i in list(map(int, input().split())): l[i-1]+=1 res = l[3] ##res+= l[2] ##l[0]-= l[2] ##res+= l[1]//2 ##l[1] = l[1]%2 ##res+= l[1] ##l[0]-= l[1] ##if l[0] > 0: ## res+=math.ceil(l[0]/4) ##print(res) while l[2] != 0 and l[0] != 0: res+=1 l[2]-=1 l[0]-=1 ...
Small, but very brave, mouse Brain was not accepted to summer school of young villains. He was upset and decided to postpone his plans of taking over the world, but to become a photographer instead. As you may know, the coolest photos are on the film (because you can specify the hashtag #film for such). Brain took a ...
1
def main(): n, m = map(int, raw_input().split()) mat = [raw_input().split() for i in xrange(n)] for i in xrange(n): for j in xrange(m): if mat[i][j] == 'C' or mat[i][j] == 'M' or mat[i][j] == 'Y': return '#Color' return '#Black&White' if __name__ == '__main__': p...
Fox Ciel starts to learn programming. The first task is drawing a fox! However, that turns out to be too hard for a beginner, so she decides to draw a snake instead. A snake is a pattern on a n by m table. Denote c-th cell of r-th row as (r, c). The tail of the snake is located at (1, 1), then it's body extends to (1,...
3
x, y = [int(x) for x in input().strip().split()] str_out = ['#'*y, '.'*(y-1)+'#', '#'*y, '#'+'.'*(y-1)] for z in range(x): print(str_out[z % 4])
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
from sys import * from math import * from string import * from operator import * from functools import * from fractions import * from collections import * setrecursionlimit(10**7) dX= [-1, 1, 0, 0,-1, 1,-1, 1] dY= [ 0, 0,-1, 1, 1,-1,-1, 1] RI=lambda: list(map(int,input().split())) RS=lambda: input().rstrip().split() ##...
After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≀ si ≀ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum nu...
3
n = int(input()) l = list(map(int, input().split())) c1 = l.count(1) c2 = l.count(2) c3 = l.count(3) c4 = l.count(4) res = 0 res += c4 + c2 // 2 c2 %= 2 k = min(c1, c3) res += k c1 -= k c3 -= k if c3 != 0: res += c3 if c1 != 0: res += c1 // 4 c1 %= 4 k = c1 + c2 * 2 if k <= 4 and k != 0: res += 1 elif ...
This problem is actually a subproblem of problem G from the same contest. There are n candies in a candy box. The type of the i-th candy is a_i (1 ≀ a_i ≀ n). You have to prepare a gift using some of these candies with the following restriction: the numbers of candies of each type presented in a gift should be all di...
3
from collections import Counter import sys def main(): input = sys.stdin.readline q = int(input()) for l in range(q): n = int(input()) a = list(map(int,input().split())) b = sorted(Counter(a).values())[::-1] t = b[0] ans = b[0] for k in range(1,len(b)): ...
Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS: You are given two integers d, m, find the number of arrays a, satisfying the following constraints: * The length of a is n, n β‰₯ 1 * 1 ≀ a_1 < a_2 < ... < a_n ≀ d * Define an array b of length n as foll...
3
for _ in range(int(input())): d,m=map(int,input().split()) ans=1 for i in range(30): if d<(1<<i): break ans*=(min(d,(1<<(i+1))-1)-(1<<i)+2) ans-=1 print(ans%m)
Kyoya Ootori is selling photobooks of the Ouran High School Host Club. He has 26 photos, labeled "a" to "z", and he has compiled them into a photo booklet with some photos in some order (possibly with some photos being duplicated). A photo booklet can be described as a string of lowercase letters, consisting of the pho...
3
s = input().strip() ls = len(s) insertion_pts = ls + 1 ideal_num = 26 * insertion_pts ct = 1 for i in range(ls-1): if s[i] == s[i+1]: ct += 1 else: ideal_num -= ct ct = 1 ideal_num -= ct print(ideal_num)
Recall that string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly zero or all) characters. For example, for the string a="wowwo", the following strings are subsequences: "wowwo", "wowo", "oo", "wow", "", and others, but the following are not subsequences: "owoo", "owwwo", ...
3
s = input() a = [] i1 = 0 while i1 < len(s): pos = s.find('v', i1) if pos < 0: break ocount = pos - i1 + 1 i1 = s.find('o', pos + 1) if i1 < 0: i1 = len(s) d = i1 - pos a.append((d - 1, ocount)) i1 += 1 b = 0 c = [0] * len(a) for i in range(len(a)): b += a[i][1] ...
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
from math import * n, m, a = map(int, input().split()) x = ceil(n/a)*ceil(m/a); print(x)
Santa has n candies and he wants to gift them to k kids. He wants to divide as many candies as possible between all k kids. Santa can't divide one candy into parts but he is allowed to not use some candies at all. Suppose the kid who recieves the minimum number of candies has a candies and the kid who recieves the max...
3
import sys from random import choice,randint inp=sys.stdin.readline out=sys.stdout.write flsh=sys.stdout.flush sys.setrecursionlimit(10**9) inf = 10**20 eps = 1.0 / 10**10 mod = 10**9+7 dd = [(-1,0),(0,1),(1,0),(0,-1)] ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def MI(): return map(int, inp().str...
Little girl Margarita is a big fan of competitive programming. She especially loves problems about arrays and queries on them. Recently, she was presented with an array a of the size of 10^9 elements that is filled as follows: * a_1 = -1 * a_2 = 2 * a_3 = -3 * a_4 = 4 * a_5 = -5 * And so on ... ...
3
from sys import stdin def sum(n): if n < 1: return 0 temp = int((n+1)/2) if n%2!=0: temp = temp*(-1) return temp firstLine = stdin.readline() if len(firstLine) < 2: print("Invalid Input") else: queries = int(firstLine) arr = [] for i in range (0,queries): arr.append([int...
You are given a rectangular board of M Γ— N squares. Also you are given an unlimited number of standard domino pieces of 2 Γ— 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions: 1. Each domino completely covers two squa...
3
#input from user (board size) m, n = [int(x) for x in input().split()] #find total number of squares total = (m * n) // 2 # print total num dominoes that can fit on board print(total)
Petya loves lucky numbers. Everybody knows that positive integers are lucky if their decimal representation doesn't contain digits other than 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Lucky number is super lucky if it's decimal representation contains equal amount of digits 4 and 7. Fo...
3
import itertools n = int(input()) def very_happy(num): banned = '01235689' for c in banned: if c in str(num): return False if not str(num).count('4') == str(num).count('7'): return False else: return True '''for i in range(n, (n**2)**2): if very_happy(i): ...
During the break the schoolchildren, boys and girls, formed a queue of n people in the canteen. Initially the children stood in the order they entered the canteen. However, after a while the boys started feeling awkward for standing in front of the girls in the queue and they started letting the girls move forward each...
3
### Queue at school Elo:800 ### len_q, t = list(map(int,input().split())) q = list(input()) for a in range(t): current = 0 while current < len_q-1: if q[current] == "B" and q[current+1] == "G": q[current], q[current+1] = q[current + 1], q[current] current += 2 else: current += 1 print("".join(q))
Bimal decided to join a non Hill'ffair club because he is not interested in cultural activities at all. He thought that joining a technical club would help him in gaining technical prowess. However, on joining the most technical club that he could find, he realised that most of the work in all technical clubs is not te...
1
def modulo(): for _ in range(input()): digit = raw_input() N = int(raw_input()) print N%1000000007 if __name__ == "__main__": modulo()
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()) p=list(map(int,input().strip().split()[:n])) k=p.index(max(p))+1 p.remove(max(p)) print(k,max(p))
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point x(x > 0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order ...
3
dist = int(input()) temp = dist%5 ans = dist//5 if temp>0: ans += 1 print(ans)
We have N points numbered 1 to N arranged in a line in this order. Takahashi decides to make an undirected graph, using these points as the vertices. In the beginning, the graph has no edge. Takahashi will do M operations to add edges in this graph. The i-th operation is as follows: * The operation uses integers L_i ...
3
n, m, *t = map(int, open(0).read().split()) inf = float('inf') dp = [inf] * -~n dp[1] = 0 import heapq mn = [] path = eval('[],' * -~n) for l, r, c in zip(*[iter(t)] * 3): path[l].append((r, c)) def ins(v, r): heapq.heappush(mn, (v, r)) for i in range(1, n + 1): while len(mn) and mn[0][1] < i: ...
Lee is going to fashionably decorate his house for a party, using some regular convex polygons... Lee thinks a regular n-sided (convex) polygon is beautiful if and only if he can rotate it in such a way that at least one of its edges is parallel to the OX-axis and at least one of its edges is parallel to the OY-axis a...
3
import math num=int(input()) for i in range(num): n=int(input()) if n%4==0: print("YES") else: print("NO")
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
n = int(input()) a = list(map(int, input().split())) count = {} for x in a: count[x] = count.get(x, 0) + 1 candidates = [key for key in count if count[key] == max(count.values())] for x in a[::-1]: if x in candidates: if len(candidates) == 1: print(x) break else: candidates.remove(x)
Write a program which reads a sequence A of n elements and an integer M, and outputs "yes" if you can make M by adding elements in A, otherwise "no". You can use an element only once. You are given the sequence A and q questions where each question contains Mi. Notes You can solve this problem by a Burte Force appro...
3
n = int(input()) a = list(map(int,input().split())) q = int(input()) m = list(map(int,input().split())) s = [list(map(int,bin(x)[2:].zfill(n))) for x in range(2**n)] anset=set() for j in s: ans=0 for k in range(n): ans+=a[k]*j[k] anset.add(ans) for i in range(q): if m[i] in anset: pri...
Carol is currently curling. She has n disks each with radius r on the 2D plane. Initially she has all these disks above the line y = 10100. She then will slide the disks towards the line y = 0 one by one in order from 1 to n. When she slides the i-th disk, she will place its center at the point (xi, 10100). She w...
3
import math n, r = map(int, input().split()) x = list(map(int, input().split())) y = [r] for i in range(1, n): _y = r for j in range(i): if 4 * r * r >= (x[i] - x[j]) * (x[i] - x[j]): _y = max(_y, y[j] + math.sqrt(4 * r * r - (x[i] - x[j]) * (x[i] - x[j]))) y.append(round(_y, 6)) ...