problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
You are given an array a of length n, which initially is a permutation of numbers from 1 to n. In one operation, you can choose an index i (1 ≤ i < n) such that a_i < a_{i + 1}, and remove either a_i or a_{i + 1} from the array (after the removal, the remaining parts are concatenated). For example, if you have the ar...
3
import sys T = int(sys.stdin.readline()) for _ in range(T): n = int(sys.stdin.readline()) list_num = list(map(int, sys.stdin.readline().split())) if list_num[0] > list_num[-1]: print("NO") else: print("YES") """ now_n = list(range(1,n+1)) now_max = [0]*n now_min = [100000...
International Women's Day is coming soon! Polycarp is preparing for the holiday. There are n candy boxes in the shop for sale. The i-th box contains d_i candies. Polycarp wants to prepare the maximum number of gifts for k girls. Each gift will consist of exactly two boxes. The girls should be able to share each gift ...
3
n,k=map(int,input().split()) l=list(map(int,input().split())) cnt=[0]*k for i in l: cnt[i%k]+=1 ans=0 for i in range(k): for j in range(i,k): if (i+j)%k==0: if i==j: x=cnt[i]//2 cnt[i]-=2*x ans+=2*x else: x=min(cnt[i...
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
k = int(input()) for da in range(k): n = int(input()) cs = [0] * (n+10) a = list(map(int,input().split())) for i in a: cs[i] += 1 cc = 0 for i in range(len(cs)-1, 0, -1): cc += cs[i] if cc >= i: print(i) break
On a two-dimensional plane, there are N red points and N blue points. The coordinates of the i-th red point are (a_i, b_i), and the coordinates of the i-th blue point are (c_i, d_i). A red point and a blue point can form a friendly pair when, the x-coordinate of the red point is smaller than that of the blue point, an...
3
n = int(input()) ab = [ list(map(int, input().split())) for _ in range(n) ] cd = [ list(map(int, input().split())) for _ in range(n) ] ab = sorted(ab, key=lambda x:x[1]*(-1)) cd = sorted(cd) ans = 0 for q in cd: for p in ab: if q[0] > p[0] and q[1] > p[1]: ans += 1 ab.remove(p) ...
There are two rival donut shops. The first shop sells donuts at retail: each donut costs a dollars. The second shop sells donuts only in bulk: box of b donuts costs c dollars. So if you want to buy x donuts from this shop, then you have to buy the smallest number of boxes such that the total number of donuts in them ...
3
for _ in range(int(input())): a,b,c=map(int,input().split()) d,e=-1,-1 if a<c:d=1 if a*b>c:e=b print(d,e)
Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree. A k-tree is an infinite rooted tree where: * each vertex has exactly k children; * each edge has some weight; * if we look at the edges that goes ...
3
mod=1000000007 n,k,d=list(map(int,input().split())) dp=[[0 for _ in range(2)] for _ in range(n+1)] dp[0][0]=1 dp[0][1]=0 dp[1][0]=1 dp[1][1]=0 if d>1 else 1 for i in range(2,n+1): # print("---------%s----------"%i) for j in range(min(i,k),0,-1): # print(j) if j<d: dp[i][1]+=dp[i-j][...
You are given a positive integer x. Find any such 2 positive integers a and b such that GCD(a,b)+LCM(a,b)=x. As a reminder, GCD(a,b) is the greatest integer that divides both a and b. Similarly, LCM(a,b) is the smallest integer such that both a and b divide it. It's guaranteed that the solution always exists. If ther...
3
from sys import stdin def main(): input = lambda: stdin.readline()[:-1] T = int(input()) for _ in [0] * T: X = int(input()) print(1, X - 1) main()
High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters. Vasya can change no more than k characters of the original string. W...
3
import sys f = sys.stdin n, k = map(int, f.readline().strip().split()) s = f.readline() i = 0 j = 0 curmx = k a = 0 b = 0 count = [0]*26 while i<len(s): while j<len(s) and min(a,b)<=k: if s[j] == 'a': a += 1 else: b += 1 j += 1 curmx = max(curmx, a+b-1) if j==...
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc....
3
a, b = list(input()), list(input()) print('YES' if a == list(reversed(b)) else 'NO')
You're given an array a of length 2n. Is it possible to reorder it in such way so that the sum of the first n elements isn't equal to the sum of the last n elements? Input The first line contains an integer n (1 ≤ n ≤ 1000), where 2n is the number of elements in the array a. The second line contains 2n space-separat...
3
a = int(input()) szamok = [int(x) for x in input().split()] szamok = sorted(szamok) kis = 0 nagy = 0 for x in range(a): kis = szamok[x] + kis nagy = szamok[a + x] + nagy if kis != nagy: for x in range(len(szamok)): print(szamok[x], end = " ") else: print(-1)
You are given an array of positive integers. While there are at least two equal elements, we will perform the following operation. We choose the smallest value x that occurs in the array 2 or more times. Take the first two occurrences of x in this array (the two leftmost occurrences). Remove the left of these two occur...
3
n = int(input()) line = input().split() dic = {} ans = [0] * n how_many = 0 index = 0 for word in line: num = int(word) while num in dic: if dic[num] == -1: break else: how_many += 1 ans[dic[num]] = 0 dic[num] = -1 num *= 2 dic[num...
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy...
3
k = [0,0,0] n = int(input()) for i in range(n): l = [int(i) for i in input().split()] k = [k[0]+l[0],k[1]+l[1],k[2]+l[2]] if k.count(0)==3: print("YES") else: print("NO")
Vasya will fancy any number as long as it is an integer power of two. Petya, on the other hand, is very conservative and only likes a single integer p (which may be positive, negative, or zero). To combine their tastes, they invented p-binary numbers of the form 2^x + p, where x is a non-negative integer. For example,...
3
a, b = map(lambda x: int(x), input().split()) k = 0 s = 1 f = True while k < s: a = a - b if a <= 0: break c = a k += 1 s = 1 while c != 1: s += c % 2 c = c // 2 q = k - s q1 = k for i in range(q): a = a - b if a <= 0: break c = a k += 1 s = 1...
Now you get Baby Ehab's first words: "Given an integer n, find the longest subsequence of [1,2, …, n-1] whose product is 1 modulo n." Please solve the problem. A sequence b is a subsequence of an array a if b can be obtained from a by deleting some (possibly all) elements. The product of an empty subsequence is equal ...
3
import math n=int(input()) a=[] b=1 for i in range(1,n): if math.gcd(n,i)==1: a.append(i) for i in range(len(a)): b=(b*a[i])%n if b!=1: a.remove(b) print(len(a)) print(*a)
You are given a string s consisting of `A`, `B` and `C`. Snuke wants to perform the following operation on s as many times as possible: * Choose a contiguous substring of s that reads `ABC` and replace it with `BCA`. Find the maximum possible number of operations. Constraints * 1 \leq |s| \leq 200000 * Each char...
3
s = input() s = s.replace('BC', 'D') a = 0 cnt = 0 for x in s: if x == 'A': a += 1 elif x == 'D': cnt += a else: a = 0 print(cnt)
Can you imagine our life if we removed all zeros from it? For sure we will have many problems. In this problem we will have a simple example if we removed all zeros from our life, it's the addition operation. Let's assume you are given this equation a + b = c, where a and b are positive integers, and c is the sum of a...
3
a = int(input()) b = int(input()) def dao_nguoc_so_remove_0(n): number = 0 while n > 0: r = n % 10 if r != 0: number = number * 10 + r n = n // 10 return number number_remove_0 = dao_nguoc_so_remove_0(dao_nguoc_so_remove_0(a)) + dao_nguoc_so_remove_0(dao_nguoc_so_rem...
Mike received an array a of length n as a birthday present and decided to test how pretty it is. An array would pass the i-th prettiness test if there is a way to get an array with a sum of elements totaling s_i, using some number (possibly zero) of slicing operations. <image> An array slicing operation is conducted...
3
from bisect import bisect_right t = int(input()) def transitions(start, end, a, hashmap, prefix_sum): # print(start,end,a) if start == 0: hashmap.add(prefix_sum[end]) else: hashmap.add(prefix_sum[end]-prefix_sum[start-1]) # print(hashmap) if start == end: return else:...
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
n = int(input()) a = list(map(int, input().split())) ans = 0 l = 1 for i in range(1, n): if a[i] > a[i - 1]: l += 1 else: ans = max(ans, l) l = 1 print(max(ans, l))
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
# -*- coding: utf-8 -*- if __name__ == '__main__': stack = [] line = input().split(" ") for s in line: if s.isdigit(): stack.append(s) else: v2 = stack.pop() v1 = stack.pop() stack.append(str(eval(v1 + s + v2))) print(stack.pop())
Your task is to write a program which reads a text and prints two words. The first one is the word which is arise most frequently in the text. The second one is the word which has the maximum number of letters. The text includes only alphabetical characters and spaces. A word is a sequence of letters which is separate...
3
# -*- coding: utf-8 -*- import sys import os import datetime d = {} words = input().split() longest_word = '' for word in words: if len(word) > len(longest_word): longest_word = word if word not in d: d[word] = 1 else: d[word] += 1 max_value = max(d.values()) for key in d.keys()...
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected. The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog...
3
def main(): R,C=map(int,input().split()) arr=[] for _ in range(R): arr.append(list(input())) flag=True for i in range(R): for j in range(C): if arr[i][j]=='S': if i>=1: if arr[i-1][j]=='W': flag=False ...
You've got a rectangular parallelepiped with integer edge lengths. You know the areas of its three faces that have a common vertex. Your task is to find the sum of lengths of all 12 edges of this parallelepiped. Input The first and the single line contains three space-separated integers — the areas of the parallelepi...
1
a, b, c = map(int, raw_input().split()) val = (a*b*c) ** .5 u = val / a v = val / b w = val / c print int(4 * (u + v + w))
In order to make the "Sea Battle" game more interesting, Boris decided to add a new ship type to it. The ship consists of two rectangles. The first rectangle has a width of w_1 and a height of h_1, while the second rectangle has a width of w_2 and a height of h_2, where w_1 ≥ w_2. In this game, exactly one ship is used...
3
a, b, c, d = [int(i) for i in input().split()] print((2*(b+d))+4+a+c+(a-c))
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...
1
lines = input() array = [] for x in range(0,lines): currentStr = raw_input() # print "String is " + currentStr currentLen = len(currentStr) # print "Length is " + str(currentLen) if currentLen > 10: currentStr = currentStr[0] + str(currentLen-2) + currentStr[currentLen-1] array.append(currentStr) for n in ...
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
n, t = map(int, input().split()) s = list(input()) for _ in range(t): i = 0 while i < len(s) - 1: if s[i] == 'B' and s[i + 1] == 'G': s[i], s[i + 1] = s[i + 1], s[i] i += 2 else: i += 1 print(''.join(x for x in s))
Recently Vova found n candy wrappers. He remembers that he bought x candies during the first day, 2x candies during the second day, 4x candies during the third day, ..., 2^{k-1} x candies during the k-th day. But there is an issue: Vova remembers neither x nor k but he is sure that x and k are positive integers and k >...
3
for _ in range(int(input())): n=int(input()) ans=0 count=0 for i in range(2,n): ans=(n/((2**i)-1)) if ans%int(ans)==0: print(int(ans)) break
Fox Ciel has a robot on a 2D plane. Initially it is located in (0, 0). Fox Ciel code a command to it. The command was represented by string s. Each character of s is one move operation. There are four move operations at all: * 'U': go up, (x, y) → (x, y+1); * 'D': go down, (x, y) → (x, y-1); * 'L': go left...
1
def neg (a): return (-a[0],-a[1]) def vplus(a,b): return (a[0]+b[0],a[1]+b[1]) def vecmult(n,v): return (n*v[0],n*v[1]) def decide(origin,target,step): movement = vplus(target,neg(origin)) if step[0]==0: return ((movement[1] % step[1]) == 0) and (movement[0] ==0 ) and (movement[...
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....
1
n = raw_input() a=0 for i in range (int(n)): p = raw_input() p = p.split() p = [int(i) for i in p] if sum(p) >1: a+= 1 print a
Polycarp is writing the prototype of a graphic editor. He has already made up his mind that the basic image transformations in his editor will be: rotate the image 90 degrees clockwise, flip the image horizontally (symmetry relative to the vertical line, that is, the right part of the image moves to the left, and vice ...
3
import sys #sys.stdin = open('A.in', 'r') w, h = (int(x) for x in input().split()) #print(w, h) pic = [['']*2*h for _ in range(2*w)] for (i, row) in enumerate(sys.stdin): # Just in case if not row.strip() or i >= h: break for (j, c) in enumerate(row[:-1]): if j >= w: contin...
You are given an undirected graph with N vertices and 0 edges. Process Q queries of the following types. * `0 u v`: Add an edge (u, v). * `1 u v`: Print 1 if u and v are in the same connected component, 0 otherwise. Constraints * 1 \leq N \leq 200,000 * 1 \leq Q \leq 200,000 * 0 \leq u_i, v_i \lt N Input Input is ...
3
import sys input = sys.stdin.buffer.readline class UnionFind: """素集合を木構造として管理する。""" def __init__(self, n): self.parent = [-1] * n self.n = n self.cnt = n def root(self, x): """要素xの代表元を求める。O(α(N))""" if self.parent[x] < 0: return x else: ...
Polycarp has spent the entire day preparing problems for you. Now he has to sleep for at least a minutes to feel refreshed. Polycarp can only wake up by hearing the sound of his alarm. So he has just fallen asleep and his first alarm goes off in b minutes. Every time Polycarp wakes up, he decides if he wants to sleep...
3
import math t = int(input()) for _ in range(t): a, b, c, d = map(int, input().split()) time = b if b < a: a -= b if d >= c: print(-1) continue else: t1 = math.ceil(a / (c - d)) time += c * t1 print(time)
A permutation of length n is a sequence of integers from 1 to n of length n containing each number exactly once. For example, [1], [4, 3, 5, 1, 2], [3, 2, 1] are permutations, and [1, 1], [0, 1], [2, 2, 1, 4] are not. There was a permutation p[1 ... n]. It was merged with itself. In other words, let's take two instanc...
3
""" A permutation of length n is a sequence of integers from 1 to n of length n containing each number exactly once. For example, [1], [4,3,5,1,2], [3,2,1] are permutations, and [1,1], [0,1], [2,2,1,4] are not. There was a permutation p[1…n]. It was merged with itself. In other words, let's take two instances of p and...
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 ...
3
x=(input()) def solve(x): for i in range(2,int(int(x)/2)): if int(x)%i==0 : if str(i).count('4')+str(i).count('7')==len(str(i)) or str(int(int(x)/2)).count('4')+str(int(int(x)/2)).count('7')==len(str(int(int(x)/2))): return True break a=x.count('4') b=x.count('7')...
The Little Elephant has an integer a, written in the binary notation. He wants to write this number on a piece of paper. To make sure that the number a fits on the piece of paper, the Little Elephant ought to delete exactly one any digit from number a in the binary record. At that a new number appears. It consists of ...
3
a=str(input()) s=list(a) l=len(s) if(s.count("1")==l): print(a[1:]) else: for i in range(l): if(s[i]=='0'): s.pop(i) print("".join(map(str,s))) break
Rng has a connected undirected graph with N vertices. Currently, there are M edges in the graph, and the i-th edge connects Vertices A_i and B_i. Rng will add new edges to the graph by repeating the following operation: * Operation: Choose u and v (u \neq v) such that Vertex v can be reached by traversing exactly thr...
3
N, M = map(int, input().split()) graph = [[] for i in range(N)] for i in range(M): a, b = map(int, input().split()) graph[a-1].append(b-1); graph[b-1].append(a-1) dist = [2] * N dist[0] = 0 d = [[0, -1]] num = {0:1, 1:0} while d: node, par = d.pop() children = graph[node] for child in children: if child ...
Alice guesses the strings that Bob made for her. At first, Bob came up with the secret string a consisting of lowercase English letters. The string a has a length of 2 or more characters. Then, from string a he builds a new string b and offers Alice the string b so that she can guess the string a. Bob builds b from a...
3
t = int(input()) for _ in range(t): string = input() ans = [string[0]] for i in range(1, len(string), 2): ans.append(string[i]) print("".join(ans))
Find the smallest possible sum of the digits in the decimal notation of a positive multiple of K. Constraints * 2 \leq K \leq 10^5 * K is an integer. Input Input is given from Standard Input in the following format: K Output Print the smallest possible sum of the digits in the decimal notation of a positive mu...
3
from collections import deque k = int(input()) d = deque() mat = [] for i in range(k): mat.append([]) #mark = [False]*k dis = [10**18]*k dis[1] = 0 for i in range(k): mat[i].append(((i+1)%k,True)) if (10*i)%k != i: mat[i].append(((10*i)%k,False)) #bfs 1->0 d.append(1) res = 0 while d: left = d...
When you asked some guy in your class his name, he called himself S, where S is a string of length between 3 and 20 (inclusive) consisting of lowercase English letters. You have decided to choose some three consecutive characters from S and make it his nickname. Print a string that is a valid nickname for him. Constra...
3
i = input() print(i[:3])
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
string = input() li = unique_list = [ e for i, e in enumerate(string) if string.index(e) == i] l= len(li) if l % 2 : print("IGNORE HIM!") else : print("CHAT WITH HER!")
You are given two sequences a_1, a_2, ..., a_n and b_1, b_2, ..., b_n. Each element of both sequences is either 0, 1 or 2. The number of elements 0, 1, 2 in the sequence a is x_1, y_1, z_1 respectively, and the number of elements 0, 1, 2 in the sequence b is x_2, y_2, z_2 respectively. You can rearrange the elements i...
3
from sys import stdin import math inp = lambda : stdin.readline().strip() t = int(inp()) for _ in range(t): x1, y1, z1 = [int(x) for x in inp().split()] x2, y2, z2 = [int(x) for x in inp().split()] ans = 0 ans += 2*min(z1, y2) z1 -= min(z1, y2) y2 -= min(z1, y2) z2 -= min(z2, x1) z2 -=...
Let's call an array t dominated by value v in the next situation. At first, array t should have at least 2 elements. Now, let's calculate number of occurrences of each number num in t and define it as occ(num). Then t is dominated (by v) if (and only if) occ(v) > occ(v') for any other number v'. For example, arrays [1...
3
t = int(input()) while t!=0: t-=1 n = int(input()) arr = list(map(int,input().split(' '))) lst = [-1 for i in range(n+1)] ans = n+5 for i in range(n): if lst[arr[i]] != -1: ans = min(ans,i - lst[arr[i]]+1) lst[arr[i]] = i if ans>n: print(-1) else: ...
You are playing a new famous fighting game: Kortal Mombat XII. You have to perform a brutality on your opponent's character. You are playing the game on the new generation console so your gamepad have 26 buttons. Each button has a single lowercase Latin letter from 'a' to 'z' written on it. All the letters on buttons ...
3
#!/usr/bin/env python3 #-*- encoding: utf-8 -*- import sys import bisect from collections import Counter read_int = lambda : int(sys.stdin.readline()) read_ints = lambda : map(int,sys.stdin.readline().split()) read_int_list = lambda : list(read_ints()) read = lambda : sys.stdin.readline().strip() read_list = lambda :...
Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1). Iahub wants to know how many ...
3
n=int(input()) l=[] nb=0 for i in range(n): l.append([]) if i%2==0: for k in range(n): if k%2==0: l[i].insert(k,"C") nb+=1 else: l[i].insert(k,".") else: for k in range(n): if k%2==0: l[i].insert(k,".") else: l[i].insert(k,"C") nb+=1 print(nb) for i in range(n): print('...
A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it! You are given integers n,k. Construct a grid A with size n × n consisting of integers 0 and 1. The very important condition should be satisfied: the sum of all elements in the grid is exactly k. In other words, the number of 1 in the gr...
3
for _ in range(0,int(input())) : n,k= map( int, input().strip().split()) res = 2 if k % (n) == 0: res = 0 m = [[0 for a in range(0, n)] for b in range(0, n)] offset = 1 x = 0 y = 0 counter = 0 while counter < k: m[x][y] = 1 x = (x + 1) % n y = (y + 1) % n if counter % n == n - 1: x = 0 y ...
Devu is a renowned classical singer. He is invited to many big functions/festivals. Recently he was invited to "All World Classical Singing Festival". Other than Devu, comedian Churu was also invited. Devu has provided organizers a list of the songs and required time for singing them. He will sing n songs, ith song wi...
3
n, d = map(int, input().split()) time = [int(i) for i in input().split()] devu = sum(time) + (n - 1)*10 if devu > d: print(-1) else: print((n - 1)*2 + (d - devu) // 5)
You are given two lists of non-zero digits. Let's call an integer pretty if its (base 10) representation has at least one digit from the first list and at least one digit from the second list. What is the smallest positive pretty integer? Input The first line contains two integers n and m (1 ≤ n, m ≤ 9) — the length...
3
INF = int(10000000009) while True: try: n,m = map(int,input().split()) a = [] b = [] mina = int(INF) minb = int(INF) for i in input().split(): a.append(int(i)) mina = min(mina,int(i)) for i in input().split(): b.append(i...
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
i = int(raw_input()) if i&1 == 1 or i == 2: print 'NO' else: print 'YES'
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
countorig, countnew = {}, {} for ch in list(input() + input()): if ch in countorig: countorig[ch] += 1 else: countorig[ch] = 0 for ch in list(input()): if ch in countnew: countnew[ch] += 1 else: countnew[ch] = 0 if countnew == countorig: print("YES") else: pr...
Maria participates in a bicycle race. The speedway takes place on the shores of Lake Lucerne, just repeating its contour. As you know, the lake shore consists only of straight sections, directed to the north, south, east or west. Let's introduce a system of coordinates, directing the Ox axis from west to east, and th...
3
pontos = int(input()) x = [] y = [] cont = 0 for i in range(pontos+1): ponto = input().split(' ') x.append(int(ponto[0])) y.append(int(ponto[1])) for i in range(1, pontos-1): if (x[i-1] < x[i]) and (y[i] < y[i+1]): cont += 1 # LESTE -> NORTE elif (y[i-1] < y[i]) and (x[i] > x[i+1]): cont += 1...
Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in n different shops in the city. It's known that the price of one bottle in the shop i is equal to xi coins. Vasiliy plans to buy his favorite drink fo...
3
from bisect import bisect # bisect, will give you the position after the last element # bisect_left, will give you the position before if equal # bisect(s, item) n = int(input()) shops = [int(c) for c in input().rstrip().split(' ')] # q = int(input()) # for _ in range(q): # m = int(input()) # print(len([s ...
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
n,m,a=map(int,input().split()) na=n//a if n % a > 0: na+=1 ma=m//a if m % a > 0: ma+=1 print(na*ma)
A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not. You are given a string s of length n, consisting of digits. In one operation you can delete any character from strin...
3
for i in range(int(input())): n=int(input()) li=input() li=list(li) if(n>=11): flag=1 for i in range(0,n-10): if li[i]=='8': print("YES") flag=0 break if(flag): print("NO") else: ...
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()) count=0 for i in range(n): list = [int(x) for x in input().split()] if list.count(1) >= 2: count = count+1 print(count)
Mike is the president of country What-The-Fatherland. There are n bears living in this country besides Mike. All of them are standing in a line and they are numbered from 1 to n from left to right. i-th bear is exactly ai feet high. <image> A group of bears is a non-empty contiguous segment of the line. The size of ...
3
n = int(input().strip()) a=list(map(int,input().strip().split())) ans=[0]*(n+1) #labirentin cevresine attigim 0lar gibi indexOut yememek icin a=[0]+a+[0] s=[] for index,value in enumerate(a): #print('SS -> ',s) #print('ANS -> ',ans,'\n') #buyuk oldukca devam et while s and value<s[-1][0]: ...
Obesity is cited as the cause of many adult diseases. In the past, with a few exceptions, it was unrelated to high school students. However, it is no longer unrealistic to suffer from lack of exercise due to excessive studying for entrance exams, or to become bulimia nervosa due to stress. It may be a problem that high...
3
import sys for e in sys.stdin: s,w,h=e.split(',') float(w)/float(h)**2<25 or print(s)
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() c=0 for i in p: if i=='H' or i=='Q' or i=='9': print('YES') c=1 break if c==0: print('NO')
Young Timofey has a birthday today! He got kit of n cubes as a birthday present from his parents. Every cube has a number ai, which is written on it. Timofey put all the cubes in a row and went to unpack other presents. In this time, Timofey's elder brother, Dima reordered the cubes using the following rule. Suppose t...
3
import copy n = int(input()) arr = list(map(int, input().split(' '))) narr = copy.copy(arr) mid = (n+1)//2 for i in range(0, mid, 2): narr[i] = arr[n-1-i] narr[n-1-i] = arr[i] print(' '.join(map(str, narr)))
In this problem you are to calculate the sum of all integers from 1 to n, but you should take all powers of two with minus in the sum. For example, for n = 4 the sum is equal to - 1 - 2 + 3 - 4 = - 4, because 1, 2 and 4 are 20, 21 and 22 respectively. Calculate the answer for t values of n. Input The first line of...
3
import math t = int(input()) for _ in range(t): num=int(input()) gpn=math.floor((math.log(num)/math.log(2))+1) #print(num,gpn) nsum=(num*(num+1))//2 gpsum=(pow(2,gpn)-1) print(int(nsum-2*(gpsum))) #print(nsum,gpsum)
After you had helped George and Alex to move in the dorm, they went to help their friend Fedor play a new computer game «Call of Soldiers 3». The game has (m + 1) players and n types of soldiers in total. Players «Call of Soldiers 3» are numbered form 1 to (m + 1). Types of soldiers are numbered from 0 to n - 1. Each ...
3
def f(a): return (str(bin(a))[2:]).count('1') n,m,k=map(int,input().split()) a=[0]*(m+1) a=[int(input()) for x in range(m+1)] ans=0 i=m for j in range(m): if(f(a[i]^a[j])<=k): ans+=1 print(ans)
Given are N positive integers A_1,...,A_N. Consider positive integers B_1, ..., B_N that satisfy the following condition. Condition: For any i, j such that 1 \leq i < j \leq N, A_i B_i = A_j B_j holds. Find the minimum possible value of B_1 + ... + B_N for such B_1,...,B_N. Since the answer can be enormous, print t...
3
import sys input=sys.stdin.buffer.readline n=int(input()) l=list(map(int,input().split())) f=1 from fractions import gcd for i in l: f=f*i//gcd(f,i) mod=10**9+7 ans=0 for i in l: ans+=f//i print(ans%mod)
You can find anything whatsoever in our Galaxy! A cubical planet goes round an icosahedral star. Let us introduce a system of axes so that the edges of the cubical planet are parallel to the coordinate axes and two opposite vertices lay in the points (0, 0, 0) and (1, 1, 1). Two flies live on the planet. At the moment ...
3
def cubicalplanet(r,p): result = False for i in range(0, 3): result |= r[i] == p[i] print("YES")if(result) else print("NO") r = list(map(int, input().split())) p = list(map(int, input().split())) cubicalplanet(r,p)
A binary string is a string where each character is either 0 or 1. Two binary strings a and b of equal length are similar, if they have the same character in some position (there exists an integer i such that a_i = b_i). For example: * 10010 and 01111 are similar (they have the same character in position 4); * 10...
3
t = int(input()) res = [] q = 0 while q < t: n = int(input()) similar = ['0'] * n string = list(input()) i = 1 while i <= n: similar[n - i] = string[n - 1] i += 1 res.append(similar) q += 1 for e in res: print("".join(e))
Acacius is studying strings theory. Today he came with the following problem. You are given a string s of length n consisting of lowercase English letters and question marks. It is possible to replace question marks with lowercase English letters in such a way that a string "abacaba" occurs as a substring in a resulti...
1
from sys import stdin T=int(stdin.readline()) for _ in range(T): fail=True n=int(stdin.readline()) s=stdin.readline()[:n] if s.count("abacaba")<2: for i in range(n-6): sample="abacaba" for j in range(7): if s[i+j]=="?": sample=sample[:j...
New Year is coming and you are excited to know how many minutes remain before the New Year. You know that currently the clock shows h hours and m minutes, where 0 ≤ hh < 24 and 0 ≤ mm < 60. We use 24-hour time format! Your task is to find the number of minutes before the New Year. You know that New Year comes when the...
3
t = int(input()) rem = 0 for i in range(t): rem = 0 h, m = input().split(' ') rem+= 60-int(m) rem+= (23-int(h))*60 print(str(rem))
Your security guard friend recently got a new job at a new security company. The company requires him to patrol an area of the city encompassing exactly N city blocks, but they let him choose which blocks. That is, your friend must walk the perimeter of a region whose area is exactly N blocks. Your friend is quite lazy...
3
import math def find_perim(x, y, n): curr_area = x * y if curr_area == n or curr_area - x < n or curr_area - y < n: return 2 * x + 2 * y elif curr_area - x >= n: return find_perim(x - 1, y, n) elif curr_area - y >= n: return find_perim(x, y - 1, n) else: for i in range(n): curr_area -= i if curr_are...
There is a 120 minute videotape with standard recording. When I set the VCR counter to 00:00:00 with the tape completely rewound and recorded in standard recording mode, I got a certain counter value. Enter this counter value (hours, minutes, seconds), find the length of the remaining tape (recordable time), and create...
3
while 1: t, h, s = map(int, input().split()) if t == -1: break n = 7200 - (3600 * t + 60 * h + s) m = n * 3 print('{:02d}:{:02d}:{:02d}'.format(n // 3600, (n % 3600) // 60, n % 60)) print('{:02d}:{:02d}:{:02d}'.format(m // 3600, (m % 3600) // 60, m % 60))
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like. Now let's imagine a typical morning in your family. You haven't w...
3
#!/bin/python3 import string x = int(input()) coins = [int(i) for i in input().split()] coins.sort(reverse= True) for i in range(x): if sum(coins[:i+1]) > sum(coins[i+1:]): print(i+1) break
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...
1
def process_string(a): if a.upper() == a: return a.lower() if a[0].lower() == a[0] and a[1:].upper() == a[1:]: return a[0].upper() + a[1:].lower() return a a = raw_input() print process_string(a)
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
if __name__ == '__main__': key_input = input().split(' ') print(int((int(key_input[0])*int(key_input[1]))/2))
After the mysterious disappearance of Ashish, his two favourite disciples Ishika and Hriday, were each left with one half of a secret message. These messages can each be represented by a permutation of size n. Let's call them a and b. Note that a permutation of n elements is a sequence of numbers a_1, a_2, …, a_n, in ...
3
from collections import deque n = int(input()) a = list(map(int,input().split())) b = list(map(int,input().split())) pos = [0 for x in range(n+1)] mmax = 0 offset = [0 for x in range(n+1)] for i in range(n): pos[a[i]]=i for i in range(n): cur = pos[b[i]] - i if cur <0: cur += n offset[cur]+=1...
Kalila and Dimna are two jackals living in a huge jungle. One day they decided to join a logging factory in order to make money. The manager of logging factory wants them to go to the jungle and cut n trees with heights a1, a2, ..., an. They bought a chain saw from a shop. Each time they use the chain saw on the tree...
1
def cross(x, y): ax, bx = hull[x]; ay, by = hull[y] return (by-bx) / (ax-ay) def insert(a, b): hull.append((a,b)) while len(hull) > 2 and cross(-2,-3) > cross(-1,-2): hull.pop(-2) input = raw_input range = xrange n = int(input()) a = list(map(int,input().split())) b = list(map(int,input().split())) p ...
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it: * deletes all the vowels, * inserts a character "." before each consonant, * repl...
3
x=str(input()) x=x.lower() y= ['a','e','i','o','u','y'] w= ' ' for i in range(0, len(x)): if x[i] not in y: w += '.' w += x[i] print(w)
A + B is often used as an example of the easiest problem possible to show some contest platform. However, some scientists have observed that sometimes this problem is not so easy to get accepted. Want to try? Input The input contains two integers a and b (0 ≤ a, b ≤ 103), separated by a single space. Output Output ...
3
#6 (a, b) = input().split(" "); print(int(a) + int(b))
AtCoder's head office consists of N rooms numbered 1 to N. For any two rooms, there is a direct passage connecting these rooms. For security reasons, Takahashi the president asked you to set a level for every passage, which is a positive integer and must satisfy the following condition: * For each room i\ (1 \leq i \...
3
n=int(input()) def f(x,y): ret=1 while True: if x%2!=y%2: return ret break else: x//=2 y//=2 ret+=1 for i in range(n-1): Ans=[] for j in range(n-1-i): Ans.append(f(i+1,i+j+2)) print(*Ans)
Blake is a CEO of a large company called "Blake Technologies". He loves his company very much and he thinks that his company should be the best. That is why every candidate needs to pass through the interview that consists of the following problem. We define function f(x, l, r) as a bitwise OR of integers xl, xl + 1, ...
1
n = int(input()) a = [int(x) for x in raw_input().split()] b = [int(x) for x in raw_input().split()] f1 = 0 for x in a: f1 |= x f2 = 0 for x in b: f2 |= x print f1 + f2
Tomorrow Peter has a Biology exam. He does not like this subject much, but d days ago he learnt that he would have to take this exam. Peter's strict parents made him prepare for the exam immediately, for this purpose he has to study not less than minTimei and not more than maxTimei hours per each i-th day. Moreover, th...
1
def schedule(minTime, maxTime, sumTime): res = [] for t in minTime: res.append(t) sumTime -= t i = 0 while (sumTime > 0): auxt = min(sumTime, maxTime[i] - minTime[i]) res[i] += auxt sumTime -= auxt i += 1 return " ".join(map(str, res)) minTime = [] maxTime = [] d, sumTime = map(int, raw_input()....
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the oppo...
3
def main(): n = int(input()) lst = [] for it in range(n): m = input() lst.append(m) g = 1 for it in range(1, n): if lst[it] == lst[it - 1]: continue else: g = g + 1 print(g) if __name__ == "__main__": main()
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If...
3
count = 0 stelle = 0 line = input() while stelle+1 < len(line): if count == 7: break if count != 0: stelle += count if stelle+1 >= len(line): break count = 0 if line[stelle] == "0": for a in line[stelle:]: if a == "0": count += 1 ...
Vasya has his favourite number n. He wants to split it to some non-zero digits. It means, that he wants to choose some digits d_1, d_2, …, d_k, such that 1 ≤ d_i ≤ 9 for all i and d_1 + d_2 + … + d_k = n. Vasya likes beauty in everything, so he wants to find any solution with the minimal possible number of different d...
1
n = input() k = n print k print '1 '*k
Vasya is reading a e-book. The file of the book consists of n pages, numbered from 1 to n. The screen is currently displaying the contents of page x, and Vasya wants to read the page y. There are two buttons on the book which allow Vasya to scroll d pages forwards or backwards (but he cannot scroll outside the book). F...
3
t = int(input()) while t > 0: t = t - 1 n, x, y, d = map(int, input().split()) ans = 10 ** 9 + 2 if abs(y - x) % d == 0: ans = min(abs(y - x) // d, ans) if (y - 1) % d == 0: ans = min((y - 1) // d + (x - 1 + d - 1) // d, ans) if (n - y) % d == 0: ans = min((n - y) // d + ...
A recently found Ancient Prophesy is believed to contain the exact Apocalypse date. The prophesy is a string that only consists of digits and characters "-". We'll say that some date is mentioned in the Prophesy if there is a substring in the Prophesy that is the date's record in the format "dd-mm-yyyy". We'll say tha...
3
from operator import itemgetter def var(a): sim = 0 mes = {1:31,2:28,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31} dia = 0 if a[2] >= 2013 and a[2] <= 2015: sim += 1 if a[1] in mes: sim += 1 dia = mes[a[1]] if a[0] <= dia and a[0] > 0: sim += 1 return sim data = input() tam = len(data)...
Let's call an array a_1, a_2, ..., a_m of nonnegative integer numbers good if a_1 + a_2 + ... + a_m = 2⋅(a_1 ⊕ a_2 ⊕ ... ⊕ a_m), where ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR). For example, array [1, 2, 3, 6] is good, as 1 + 2 + 3 + 6 = 12 = 2⋅ 6 = 2⋅ (1⊕ 2 ⊕ 3 ⊕ 6). A...
3
T = int(input()) for t in range(T): n = int(input()) a = [int(x) for x in input().split()] print(2) x = sum(a) y = a[0] for i in range(1,n): y = y^a[i] x += y print(x,y)
Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1). Iahub wants to know how many ...
1
n = int(input()) oc = sum([1 if i % 2 else 0 for i in range(1, n+1)]) ec = sum([1 if i % 2 == 0 else 0 for i in range(1, n+1)]) c = sum([oc if i % 2 else ec for i in range(1, n+1)]) print c sc = 'C' nc = '.' os = "" for i in range(1, n+1): if i % 2: os += sc else: os += nc sc = '.' nc = 'C' es =...
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
n = int(input()) x = max(list(map(int, input().split()))) n = int(input()) print(x, max(list(map(int, input().split()))))
Right now she actually isn't. But she will be, if you don't solve this problem. You are given integers n, k, A and B. There is a number x, which is initially equal to n. You are allowed to perform two types of operations: 1. Subtract 1 from x. This operation costs you A coins. 2. Divide x by k. Can be performed...
3
n = int(input()); k = int(input()); a = int(input()); b = int(input()); #inf = 100000000000000000000000000000; ost = 0; res = 0; while a * (n // k) + b + (n % k) * a < n * a: ost = ost + (n % k) * a; res = res + b; n = n // k; #print(n); #print(res); #print(ost); res = res + (n - 1) * a + ost; print(res);
You are given a string s of even length n. String s is binary, in other words, consists only of 0's and 1's. String s has exactly n/2 zeroes and n/2 ones (n is even). In one operation you can reverse any substring of s. A substring of a string is a contiguous subsequence of that string. What is the minimum number of...
3
# ---------------------------iye ha aam zindegi--------------------------------------------- import math import random import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys import threading from collections import defaultdict #threading.stack_size(10**8) mo...
A burglar got into a matches warehouse and wants to steal as many matches as possible. In the warehouse there are m containers, in the i-th container there are ai matchboxes, and each matchbox contains bi matches. All the matchboxes are of the same size. The burglar's rucksack can hold n matchboxes exactly. Your task i...
3
n,m=map(int,input().split()) d={} for i in range(m): a,b=map(int,input().split()) if b in d: d[b]+=a else: d[b]=a ans=0 m=len(d) while(n>0): #print(d,ans) if n==0 or m==0: break a=max(d) if n>d[a]: n-=d[a] ans+=a*d[a] eli...
Vanya got n cubes. He decided to build a pyramid from them. Vanya wants to build the pyramid as follows: the top level of the pyramid must consist of 1 cube, the second level must consist of 1 + 2 = 3 cubes, the third level must have 1 + 2 + 3 = 6 cubes, and so on. Thus, the i-th level of the pyramid must have 1 + 2 + ...
3
n = int(input()) lvl = 1 if n == 1: print(1) else: while n >= 0: a = int(0.5 * lvl ** 2 + 0.5 * lvl) n -= a if n >= 0: lvl += 1 else: lvl = lvl - 1 break print(lvl)
Monk has a very good friend, Puchi. As weird as his name, are the games he plays. One fine day, they decided to play a game to test how diverse their choices are. Both of them choose exactly one integer each. Monk chooses an integer M and Puchi chooses an integer P. The diversity of their choices is defined as the nu...
1
test_cases=int(raw_input()) for test in range(test_cases): numbers=raw_input() P=numbers.split(" ")[0] M=numbers.split(" ")[1] xor=int(P)^int(M) print bin(xor).count('1')
Problem statement JOI decided to start a new social game from tomorrow. In this social game, you can log in up to once a day, and you will get A coins each time you log in. Also, if you log in for 7 consecutive days from Monday to Sunday, you will get an additional B coins each time. No other coins will be given. ...
3
a,b,c=input().split() d = int(a)*7+int(b) #一週間で手に入るコイン e = int(c)//d #必要な週の数 f = int(c)-d*e #残りのコイン if f<=6*int(a) and f%int(a)>0 : g=f//int(a)+1 elif f<=6*int(a) and f%int(a)<=0 : g=f/int(a) else : g=7 print(int(e*7+g))
Little Syed loves brute force. He thinks that brute force can be the solution to any problem in the world. You give him any question, and he'll have a brute force answer ready for you, almost all the time. His good friend Little Jhool (Like, always!) decides to teach him a lesson, by giving him problems which cannot be...
1
from collections import Counter p3 = [i ** 3 for i in xrange(1, 90)] c = Counter(x + y for x in p3 for y in p3) c[-1] = 3 for t in xrange(int(raw_input())): n = int(raw_input()) print max(k for k in c if k < n and c[k] > 2)
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once. The appointed Judge was the most experienced member — Pavel. But since he was the wi...
3
from sys import stdin,stdout from collections import * from math import ceil, floor , log, gcd st=lambda:list(stdin.readline().strip()) li=lambda:list(map(int,stdin.readline().split())) mp=lambda:map(int,stdin.readline().split()) inp=lambda:int(stdin.readline()) pr=lambda n: stdout.write(str(n)+"\n") mod=1000000007...
You have a plate and you want to add some gilding to it. The plate is a rectangle that we split into w× h cells. There should be k gilded rings, the first one should go along the edge of the plate, the second one — 2 cells away from the edge and so on. Each ring has a width of 1 cell. Formally, the i-th of these rings ...
3
a = [int (i) for i in input().split()] d = 0 for i in range(a[2]): d += a[0]*2 + (a[1] - 2)*2 a[0] -= 4 a[1] -= 4 print(d)
Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears. These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite — cookies. Ichihime decides to attend the contest. Now sh...
3
for _ in range(int(input())): a,b,c,d = map(int,input().split()) x = b z = c y = max(c-b + 1,b+1) if(b==c): x,y,z = b,b,b print(x,y,z)
Duff is addicted to meat! Malek wants to keep her happy for n days. In order to be happy in i-th day, she needs to eat exactly ai kilograms of meat. <image> There is a big shop uptown and Malek wants to buy meat for her from there. In i-th day, they sell meat for pi dollars per kilogram. Malek knows all numbers a1, ....
3
n = int(input()) ans = 0 mn = 200 for i in range(n): a, p = map(int,input().split(' ')) mn = min(mn, p) ans += a * mn print(ans)
You are given two arrays a and b both consisting of n positive (greater than zero) integers. You are also given an integer k. In one move, you can choose two indices i and j (1 ≤ i, j ≤ n) and swap a_i and b_j (i.e. a_i becomes b_j and vice versa). Note that i and j can be equal or different (in particular, swap a_2 w...
3
t=int(input()) for _ in range(t): n,k=map(int,input().split()) a=list(map(int,input().split())) b=list(map(int,input().split())) a.sort() b.sort(reverse=True) s=0 i=0 while(i<n): if i<k: if b[i]>a[i]: s=s+b[i] else: s=s+a[i]...
A programming competition site AtCode regularly holds programming contests. The next contest on AtCode is called ABC, which is rated for contestants with ratings less than 1200. The contest after the ABC is called ARC, which is rated for contestants with ratings less than 2800. The contest after the ARC is called AG...
3
a=int(input()) print("ABC" if a < 1200 else "ARC" if a <2800 else "AGC")
The following problem is well-known: given integers n and m, calculate <image>, where 2n = 2·2·...·2 (n factors), and <image> denotes the remainder of division of x by y. You are asked to solve the "reverse" problem. Given integers n and m, calculate <image>. Input The first line contains a single integer n (1 ...
3
''' # CodeForce Equalize Prices 900 points # a = old price / b = new price / k =value input def Computer_Game(): for _ in range(int(input())): k, n, a, b = map(int, input().split()) # init charge, num turns in game, a,b bat value max_turns=0 for turns in range(n): if k/b > n ...
[3R2 - Standby for Action](https://www.youtube.com/watch?v=P2ZVC9aoiKo) Our dear Cafe's owner, JOE Miller, will soon take part in a new game TV-show "1 vs. n"! The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The sho...
3
n = int(input()) ans = 1 for i in range(n, 1, -1): ans += 1/i print(ans)
Let us call a pair of integer numbers m-perfect, if at least one number in the pair is greater than or equal to m. Thus, the pairs (3, 3) and (0, 2) are 2-perfect while the pair (-1, 1) is not. Two integers x, y are written on the blackboard. It is allowed to erase one of them and replace it with the sum of the number...
1
import math def fun(a,b,n): #print a,b,n if a>=n: return 0; if b>=n: return 0; if a>b: a,b=b,a; if b<=0: return -1; t=math.fabs(a-b); t2=int(math.floor(t/b)+1); return t2+fun(a+t2*b,b,n); a,b,n=map(int,raw_input().split()); print fun(a, b, n);