problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
There is a robot in a warehouse and n packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0, 0). The i-th package is at the point (x_i, y_i). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point ...
3
for _ in range(int(input())): a=[] b=[] x=0 y=0 n=int(input()) for i in range(0,n): a.append([*map(int,input().split())]) a=sorted(a) for i in range(0,n): if a[i][0]>=x: ans = "R"*(a[i][0]-x) b.append(ans) x=a[i][0] if (a[i]...
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: * Tetrahedron. Tetrahedron has 4 triangular faces. * Cube. Cube has 6 square faces. * Octahedron. Octahedron has 8 triangular faces. * Dodecahedron. Dodecahedron has 12 pentagonal faces. *...
3
n = int(input()) i = int(0) x = int (0) total = int(0) collection = [] while i < n: collection.append(input()) i += 1 while x < len(collection): if collection[x] == "Tetrahedron": total += 4 elif collection[x] == "Cube": total += 6 elif collection[x] == "Octahedron": total += 8 elif collection[x] == "Do...
The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has n students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times. The ...
3
z=list(map(int,input().split())) x=list(map(int,input().split())) a=0 for i in range(z[0]): if x[i]+z[1]<6: a+=1 print(a//3)
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended u...
1
p = [] for x in raw_input(): if not p or p[-1] != x: p.append(x) else: p.pop(-1) print p and "No" or "Yes"
The HR manager was disappointed again. The last applicant failed the interview the same way as 24 previous ones. "Do I give such a hard task?" — the HR manager thought. "Just raise number 5 to the power of n and get last two digits of the number. Yes, of course, n can be rather big, and one cannot find the power using ...
3
input() # At least wait for input print(25)
We have N dice arranged in a line from left to right. The i-th die from the left shows p_i numbers from 1 to p_i with equal probability when thrown. We will choose K adjacent dice, throw each of them independently, and compute the sum of the numbers shown. Find the maximum possible value of the expected value of this ...
3
n, k = list(map(int, input().split())) p = list(map(int, input().split())) s = [(sum(p[:k]))] for i in range(1, n-k+1): s.append((s[-1]-p[i-1]+p[i+k-1])) print((max(s)+k)/2)
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
# import sys # sys.stdin=open("input.in","r") # sys.stdout=open("output.out","w") x=list(map(str,input())) x=list(set(x)) if len(x)%2==0: print("CHAT WITH HER!") else: print("IGNORE HIM!")
One day Kefa found n baloons. For convenience, we denote color of i-th baloon as si — lowercase letter of the Latin alphabet. Also Kefa has k friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. Help Kefa to find out, can he give out all his baloons, ...
3
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Feb 15 12:19:40 2018 @author: karthikps """ line_1 = input().split() n = int(line_1[0]) k = int(line_1[1]) s = input() colour_dict = {} for balloon in s: if balloon in colour_dict.keys(): colour_dict[balloon] += 1 else: colou...
Three friends are going to meet each other. Initially, the first friend stays at the position x = a, the second friend stays at the position x = b and the third friend stays at the position x = c on the coordinate axis Ox. In one minute each friend independently from other friends can change the position x by 1 to the...
3
import sys from bisect import bisect if __name__ == '__main__': n = int(input()) for _ in range(n): a,b,c = map(int, input().split()) r = [-1,0,1] m = 10**19 for i in r: for j in r: for k in r: arr = [a + i, b + j, c + k] ...
Andrey thinks he is truly a successful developer, but in reality he didn't know about the binary search algorithm until recently. After reading some literature Andrey understood that this algorithm allows to quickly find a certain number x in an array. For an array a indexed from zero, and an integer x the pseudocode o...
3
from sys import stdin,stdout from collections import * 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 INF=float('inf') ma= 10**3 +1 fact=[0...
To improve the boomerang throwing skills of the animals, Zookeeper has set up an n × n grid with some targets, where each row and each column has at most 2 targets each. The rows are numbered from 1 to n from top to bottom, and the columns are numbered from 1 to n from left to right. For each column, Zookeeper will t...
1
import atexit, io, sys # A stream implementation using an in-memory bytes # buffer. It inherits BufferedIOBase. buffer = io.BytesIO() sys.stdout = buffer # print via here @atexit.register def write(): sys.__stdout__.write(buffer.getvalue()) for _ in range(1): n=input() a=map(int,raw_input().split()) ...
Your favorite shop sells n Kinder Surprise chocolate eggs. You know that exactly s stickers and exactly t toys are placed in n eggs in total. Each Kinder Surprise can be one of three types: * it can contain a single sticker and no toy; * it can contain a single toy and no sticker; * it can contain both a sing...
3
n=int(input()) for _ in range(n): a,b,c=map(int,input().split()) print(max((a-b),(a-c))+1)
Do you remember a kind cartoon "Beauty and the Beast"? No, no, there was no firing from machine guns or radiation mutants time-travels! There was a beauty named Belle. Once she had violated the Beast's order and visited the West Wing. After that she was banished from the castle... Everybody was upset. The beautiful ...
3
s = input() h = (int(s[:2]))%12 m = int(s[3:]) h += m/60 print(h*5*6, m*6)
You are given an array a consisting of n integers. Beauty of array is the maximum sum of some consecutive subarray of this array (this subarray may be empty). For example, the beauty of the array [10, -5, 10, -4, 1] is 15, and the beauty of the array [-3, -5, -1] is 0. You may choose at most one consecutive subarray o...
3
n, x = map(int, input().split()) a = list(map(int, input().split())) kq=pre=mid=suf=0 for i in a: pre=max(pre+i,0) mid=max(mid+(i*x),pre) suf=max(suf+i,mid) kq = max(kq, suf) print(kq)
Your friend Jeff Zebos has been trying to run his new online company, but it's not going very well. He's not getting a lot of sales on his website which he decided to call Azamon. His big problem, you think, is that he's not ranking high enough on the search engines. If only he could rename his products to have better ...
3
# A brute force implementation queries = int(input()) for i in range(queries): S,C = input().split() s = list(S) interim = 0 if S < C: print(S) else: Ssize =len(S) pick = sorted(S) # Genertaing the smallest possible string with one swap for i in range(Ssize): ...
Petya is preparing for his birthday. He decided that there would be n different dishes on the dinner table, numbered from 1 to n. Since Petya doesn't like to cook, he wants to order these dishes in restaurants. Unfortunately, all dishes are prepared in different restaurants and therefore Petya needs to pick up his ord...
3
import sys input=sys.stdin.readline from collections import defaultdict for _ in range(int(input())): n=int(input()) a=list(map(int,input().split())) b=list(map(int,input().split())) lis=list(zip(a,b)) lis.sort() suf=[0] lis.reverse() suf[0]=lis[0][1] for i,j in lis[1:]: suf...
Anton likes to play chess, and so does his friend Danik. Once they have played n games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie. Now Anton wonders, who won more games, he or Danik? Help him determine this. Input The first line of the input contains a...
3
n = input() a = input() d,c = 0,0 for i in range(len(a)): if a[i] == 'D': d+=1 if a[i] == 'A': c+=1 if d>c: print("Danik") elif d<c: print("Anton") else: print("Friendship")
You have a garland consisting of n lamps. Each lamp is colored red, green or blue. The color of the i-th lamp is s_i ('R', 'G' and 'B' — colors of lamps in the garland). You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garlan...
3
n=int(input()) s=str(input()) s=list(s) x=s[0] c=0 res=0 for i in range(1,n): if(s[i]!=x): y=i-c res=res+y//2 x=s[i] c=i if(y==2): if(s[i]=="R"): if(s[i-1]=="G"): s[i-1]="B" else: s[i-1]="G" ...
Door's family is going celebrate Famil Doors's birthday party. They love Famil Door so they are planning to make his birthday cake weird! The cake is a n × n square consisting of equal squares with side length 1. Each square is either empty or consists of a single chocolate. They bought the cake and randomly started t...
3
n= int(input()) matrix = [ [ 'c' for i in range(n) ] for j in range(n)] for i in range(n): matrix[i]=list(input()) #print(matrix) ans=0 for i in range(n): count=0 for j in range(n): if matrix[i][j]=='C': count=count+1 ans=ans+(count*(count-1))/2 for i in range(n): count=0 ...
Ted has a pineapple. This pineapple is able to bark like a bulldog! At time t (in seconds) it barks for the first time. Then every s seconds after it, it barks twice with 1 second interval. Thus it barks at times t, t + s, t + s + 1, t + 2s, t + 2s + 1, etc. <image> Barney woke up in the morning and wants to eat the ...
3
a, b, c = input().split( ) t = int(a) s = int(b) x = int(c) if x < t: print ("NO") else: x -= t; if x == 1: print ("NO") else: x %= s; if x == 0 or x == 1: print ("YES") else: print ("NO")
You are given an array of n integers a_1,a_2,...,a_n. You have to create an array of n integers b_1,b_2,...,b_n such that: * The array b is a rearrangement of the array a, that is, it contains the same values and each value appears the same number of times in the two arrays. In other words, the multisets \\{a_1,a_...
3
cases = input() for i in range(int(cases)): leng = input() nums = input().split() nums = [int(k) for k in nums] pos = [x for x in nums if x > 0] neg = [x for x in nums if x < 0] z = [x for x in nums if x == 0] if sum(pos) > -sum(neg): l = pos + neg + z print("YES") print(*l) elif -sum(neg)...
These days Arkady works as an air traffic controller at a large airport. He controls a runway which is usually used for landings only. Thus, he has a schedule of planes that are landing in the nearest future, each landing lasts 1 minute. He was asked to insert one takeoff in the schedule. The takeoff takes 1 minute it...
1
n,s = map(int,raw_input().split()) sh,sm = 0,0 flag = 0 for i in range(n): h,m = map(int,raw_input().split()) if m-sm >= 0: diff = (h - sh)*60 + (m-sm) else: diff = (h-sh-1)*60 + (60-sm + m) if not flag : if not i and diff >= (s + 1): print("0 0") flag = ...
The only difference between the easy and hard versions is that tokens of type O do not appear in the input of the easy version. Errichto gave Monogon the following challenge in order to intimidate him from taking his top contributor spot on Codeforces. In a Tic-Tac-Toe grid, there are n rows and n columns. Each cell ...
3
for _ in range(int(input())): n = int(input()) arrC = [] w = 0 for i in range(n): data = list(input()) w+=data.count("X") arrC.append(data) # for g in range(n): # if data[g] == "X": # d.append(1) # elif data[g] == "O": # ...
We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer t Т-prime, if t has exactly three distinct positive divisors. You are given an array of n positive integers. For each of them determine whether it is Т-prime or not. Input The f...
3
from math import sqrt n = int(input()) l = [int(j) for j in input().split()] big = int(1e6+2) pr = [True for i in range(big)] for i in range(2,big): if pr[i]==True: for j in range(i**2, big, i): pr[j] = False # print(pr) pr[1]=False pr[0]=False for i in range(n): m = sqrt(l[i]) if m==int(m): if pr[int(m)]==Tr...
You are given two arrays a and b, each contains n integers. You want to create a new array c as follows: choose some real (i.e. not necessarily integer) number d, and then for every i ∈ [1, n] let c_i := d ⋅ a_i + b_i. Your goal is to maximize the number of zeroes in array c. What is the largest possible answer, if y...
3
from math import gcd from collections import defaultdict def factor(x, y): if y < 0: x, y = -x, -y g = gcd(x, y) return x//g, y//g def solve(a, b): d = defaultdict(int) base = 0 for x, y in zip(a, b): if (x, y) == (0, 0): base += 1 elif y == 0: d...
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th...
3
s = input() noL = 0 for i in range(len(s)): if s[i].islower(): noL += 1 noU = len(s) - noL if noL >= noU: s = s.lower() else: s = s.upper() print(s)
A card pyramid of height 1 is constructed by resting two cards against each other. For h>1, a card pyramid of height h is constructed by placing a card pyramid of height h-1 onto a base. A base consists of h pyramids of height 1, and h-1 cards on top. For example, card pyramids of heights 1, 2, and 3 look as follows: ...
3
t=int(input()) for i in range(t): n=int(input()) ans=0 k=0 c=0 if(n==1): print("0") else: while(n>0): x=0 for j in range(1,n): x=x+2*j y=((j-1)*j)//2 # print(x+y) if(x+y==n): # print(x+y) ans+=1 c=1 break if(x+...
Search trees are data structures that support dynamic set operations including insert, search, delete and so on. Thus a search tree can be used both as a dictionary and as a priority queue. Binary search tree is one of fundamental search trees. The keys in a binary search tree are always stored in such a way as to sat...
3
class Node(): def __init__(self, key, p, l, r): self.key, self.p, self.l, self.r = key, p, l, r class BinarySearchTree(): def __init__(self): self.tree = [] self.root = -1 def insert(self, key): y = -1 # parent of x x = self.root while x != -1: ...
The Little Elephant loves numbers. He has a positive integer x. The Little Elephant wants to find the number of positive integers d, such that d is the divisor of x, and x and d have at least one common (the same) digit in their decimal representations. Help the Little Elephant to find the described number. Input ...
1
import math n=long(raw_input()); st=str(n); ctr=0; for i in range(1,long(math.sqrt(n))+1): d=n%i; flag=0;flag1=0; if d==0: s=str(n/i); s1=str(i); #print s+" "+s1; if(s!=s1): for j in range(len(s)): if s[j] in st and flag==0: flag=1; ctr=ctr+1; for j1 in range(len(s1)): if s1[j1] in st...
When preparing a tournament, Codeforces coordinators try treir best to make the first problem as easy as possible. This time the coordinator had chosen some problem and asked n people about their opinions. Each person answered whether this problem is easy or hard. If at least one of these n people has answered that th...
3
n = input() k = input().split() if '1' in k: print('HARD') else: print('EASY')
Let's call a list of positive integers a_0, a_1, ..., a_{n-1} a power sequence if there is a positive integer c, so that for every 0 ≤ i ≤ n-1 then a_i = c^i. Given a list of n positive integers a_0, a_1, ..., a_{n-1}, you are allowed to: * Reorder the list (i.e. pick a permutation p of \{0,1,...,n - 1\} and change...
3
def solve(): limit = 10**10 ans = 10**15 j = 1 while True: val = 0 power = 1 for i in range(N): if power > limit: val = -1 break val += abs(power-A[i]) power *= j if val == -1: break a...
There is a robot in a warehouse and n packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0, 0). The i-th package is at the point (x_i, y_i). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point ...
3
import io, sys, atexit, os import math as ma from sys import exit from decimal import Decimal as dec from itertools import permutations from itertools import combinations def li(): return list(map(int, sys.stdin.readline().split())) def num(): return map(int, sys.stdin.readline().split()) def nu(): re...
Mishka got an integer array a of length n as a birthday present (what a surprise!). Mishka doesn't like this present and wants to change it somehow. He has invented an algorithm and called it "Mishka's Adjacent Replacements Algorithm". This algorithm can be represented as a sequence of steps: * Replace each occurre...
3
input() a = map(int, input().split()) b = ((x+1) // 2 * 2 - 1 for x in a) print(*b)
Sereja and Dima play a game. The rules of the game are very simple. The players have n cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The ...
3
input() a=list(map(int,input().split())) l=0 r=len(a)-1 d={'s':0,'r':0} i=1 while l<=r: if a[l]>a[r]: if i%2!=0: d['s']+=a[l] else:d['r']+=a[l] l+=1 else: if i%2!=0: d['s']+=a[r] else: d['r']...
Snuke has an integer sequence, a, of length N. The i-th element of a (1-indexed) is a_{i}. He can perform the following operation any number of times: * Operation: Choose integers x and y between 1 and N (inclusive), and add a_x to a_y. He would like to perform this operation between 0 and 2N times (inclusive) so ...
3
N = int(input()) A = [int(x) for x in input().split()] cnt = 0 a_max = max(A + [0]) a_min = min(A + [0]) cnt = 0 S = [] if a_max + a_min >= 0: k = A.index(a_max) while A[0] < a_max: A[0] += a_max cnt += 1 S += [[k + 1, 1]] for i in range(N - 1): while A[i + 1] < A[i]: A[i + 1] += A[i] ...
There is a cave consisting of N rooms and M one-directional passages. The rooms are numbered 1 through N. Takahashi is now in Room 1, and Room N has the exit. The i-th passage connects Room s_i and Room t_i (s_i < t_i) and can only be traversed in the direction from Room s_i to Room t_i. It is known that, for each roo...
3
(n,m),*d = [list(map(int, s.split())) for s in open(0)] d.sort() l = [0] * n for i in range(m): d[i] = [d[i][0]-1, d[i][1]-1] l[d[i][0]] += 1 p = [0] * n p[0] = 1 for x in d: p[x[1]] += p[x[0]]/l[x[0]] e = [0] * n index = d[-1][0] max_in_index = 0 max_reduce_e = 0 for x in d[::-1] + [[-1, -1]]: if i...
Snuke has N integers. Among them, the smallest is A, and the largest is B. We are interested in the sum of those N integers. How many different possible sums there are? Constraints * 1 ≤ N,A,B ≤ 10^9 * A and B are integers. Input Input is given from Standard Input in the following format: N A B Output Print th...
3
n,a,b=map(int,input().split()) if(n==1 and a!=b) or a>b: print(0) else: print((n-2)*(b-a)+1)
Areas on the Cross-Section Diagram Your task is to simulate a flood damage. For a given cross-section diagram, reports areas of flooded sections. <image> Assume that rain is falling endlessly in the region and the water overflowing from the region is falling in the sea at the both sides. For example, for the abov...
3
from collections import deque s = input() g = deque() p = deque() for i in range(len(s)): if s[i] == "\\": g.append(i) elif s[i] == "/": a = 0 if len(g) > 0: while True: if len(p) > 0 and p[-1][0] > g[-1]: a += p[-1][1] ...
There are N towns on a line running east-west. The towns are numbered 1 through N, in order from west to east. Each point on the line has a one-dimensional coordinate, and a point that is farther east has a greater coordinate value. The coordinate of town i is X_i. You are now at town 1, and you want to visit all the ...
1
N,A,B = [int(i) for i in raw_input().split(' ')] X = [int(i) for i in raw_input().split(' ')] x_old = X[0] h = 0 for x in X: d = x - x_old if d*A>B: h += B else: h += d*A x_old = x print h
[Thanos sort](https://codegolf.stackexchange.com/questions/182221/implement-the-thanos-sorting-algorithm) is a supervillain sorting algorithm, which works as follows: if the array is not sorted, snap your fingers* to remove the first or the second half of the items, and repeat the process. Given an input array, what i...
3
def func(n, a): global res if n == 1: res = max(res, 1) return 0 else: a1 = a[:n // 2] if a1 == list(sorted(a1)): res = max(res, n // 2) a2 = a[n // 2:] if a2 == list(sorted(a2)): res = max(res, n // 2) func(n // 2, a1) ...
This is an interactive problem. In the output section below you will see the information about flushing the output. Bear Limak thinks of some hidden number — an integer from interval [2, 100]. Your task is to say if the hidden number is prime or composite. Integer x > 1 is called prime if it has exactly two distinct ...
1
#coding=utf-8 import sys primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53] cnt = 0 for prime in primes: print prime sys.stdout.flush() s = sys.stdin.readline().strip() cnt += (s == 'yes') if s == 'yes' and prime * prime <= 100: print prime * prime sys.stdou...
Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk. Empirically Polycarp learned that the dog needs at least k walks for any two consecutive days in order to feel good. For example, if k = 5 and yesterday Polycarp went for a...
3
n, k = [int(i) for i in input().split()] a = [int(i) for i in input().split()] b = [i for i in a] extraCount = 0 for i in range(n-1): theDiff = k - (b[i]+b[i+1]) if theDiff > 0: extraCount += theDiff b[i+1] += theDiff print(extraCount) for x in b: print(x, end=" ")
Today is Wednesday, the third day of the week. What's more interesting is that tomorrow is the last day of the year 2015. Limak is a little polar bear. He enjoyed this year a lot. Now, he is so eager to the coming year 2016. Limak wants to prove how responsible a bear he is. He is going to regularly save candies for ...
3
n = input() x = int(n[0]) a = x i = 5 if n[1] != ' ': y = int(n[1]) a = x * 10 + y i += 1 else: y = 0 if n[i] == 'w': if x == 5 or x == 6: print(53) else: print(52) else: if a <= 29: print(12) elif a == 30: print(11) elif a == 31: print(...
You are given an array of n integer numbers a0, a1, ..., an - 1. Find the distance between two closest (nearest) minimums in it. It is guaranteed that in the array a minimum occurs at least two times. Input The first line contains positive integer n (2 ≤ n ≤ 105) — size of the given array. The second line contains n ...
1
from sys import stdin,stdout from collections import defaultdict n = int(stdin.readline(),10) mini, pos, c, min_abs = 1000000001, defaultdict(list), 1, 1000000001 for j in stdin.readline().strip().split(): j = int(j,10) pos[j].append(c) mini = min(j, mini) c+=1 for i in xrange(len(pos[mini])-1): sub...
Recently Luba learned about a special kind of numbers that she calls beautiful numbers. The number is called beautiful iff its binary representation consists of k + 1 consecutive ones, and then k consecutive zeroes. Some examples of beautiful numbers: * 12 (110); * 1102 (610); * 11110002 (12010); * 111110...
3
#define beautiful num_bs import sys n = int(sys.stdin.readline()) k=1 beautnums = [0] num_b = 1 while num_b < 10 ** 5: num_b = (2**k - 1) * (2**(k-1)) beautnums.append(num_b) k += 1 for i in reversed(range(0,len(beautnums))): if n % beautnums[i]== 0: print(beautnums[i]) sys.exit(0)
It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, th...
3
n, m = map(int, input().split()) ans, ans_t = -1, 10000000000000 def update(i, t): global ans, ans_t if t < ans_t: ans = i ans_t = t for i in range(1, n + 1): u, v = map(int, input().split()) if m <= u: update(i, u) else: update(i, u + (int((m - u) / v) + int(bool(...
One company of IT City decided to create a group of innovative developments consisting from 5 to 7 people and hire new employees for it. After placing an advertisment the company received n resumes. Now the HR department has to evaluate each possible group composition and select one of them. Your task is to count the n...
1
import math def nCr(n,r): f = math.factorial return f(n) / f(r) / f(n-r) n=input() print nCr(n,5)+nCr(n,6)+nCr(n,7)
Alice has a lovely piece of cloth. It has the shape of a square with a side of length a centimeters. Bob also wants such piece of cloth. He would prefer a square with a side of length b centimeters (where b < a). Alice wanted to make Bob happy, so she cut the needed square out of the corner of her piece and gave it to ...
3
def isPrime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True t=int(input()) for i in range(t): a,b=map(int,input().split()) if(abs(a-b)==1 and (a+b)%2==1): ans=isPrime(a+b) if(ans == True): print("YES") else: pri...
There are N balls placed in a row. AtCoDeer the deer is painting each of these in one of the K colors of his paint cans. For aesthetic reasons, any two adjacent balls must be painted in different colors. Find the number of the possible ways to paint the balls. Constraints * 1≦N≦1000 * 2≦K≦1000 * The correct answer i...
3
N, K = map(int, input().split()) print((K-1)**(N-1)*K)
Little Chris knows there's no fun in playing dominoes, he thinks it's too random and doesn't require skill. Instead, he decided to play with the dominoes and make a "domino show". Chris arranges n dominoes in a line, placing each piece vertically upright. In the beginning, he simultaneously pushes some of the dominoes...
1
# -*- coding:utf-8 -*- #[n, m] = [int(x) for x in raw_input().split()] def some_func(): """ """ n = input() n_str = raw_input() cost = 0 temp = 0 flag = -1 for v in n_str: if flag == -1: if v == '.': temp +=1 elif v == 'R': ...
Someone gave Alyona an array containing n positive integers a1, a2, ..., an. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not ...
3
n = int(input()) nums = list(map(int, input().split())) nums.sort() nums[0] = 1 for i in range(n-1): if nums[i+1] - nums[i] > 1: nums[i+1] = nums[i] + 1 print(nums[-1] + 1)
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem. Pete and Bi...
3
var = int(input()) if var > 2 and not var % 2: print("YES") else: print("NO")
Statement Given N,A,B,C, find how many solutions exist to the equation : a + b + c ≤ N, such that 0 ≤ a ≤ A, 0 ≤ b ≤ B, 0 ≤ c ≤ C. Input The first line contains the number of test cases T. Each test case contains 4 integers, N,A,B,C. 0 ≤ N,A,B,C ≤ 2500 Output Output T lines, one for each test case. Sample I...
1
def f(n): if (n>=0): return ((n+3)*(n+2)*(n+1))/6 else: return 0 t=int(raw_input()) for df in range (t): n,a,b,c=map(int,raw_input().split()) print f(n)-f(n-a-1)-f(n-b-1)-f(n-c-1)+f(n-a-b-2)+f(n-b-c-2)+f(n-a-c-2)-f(n-a-b-c-3)
This problem is same as the next one, but has smaller constraints. Shiro's just moved to the new house. She wants to invite all friends of her to the house so they can play monopoly. However, her house is too small, so she can only invite one friend at a time. For each of the n days since the day Shiro moved to the n...
3
n=int(input()) a,b={},{} ans=1 t=[0]+list(map(int,input().split())) for i in range(1,n+1): x=t[i] a[x]=a.get(x,0)+1 b[a[x]]=b.get(a[x],0)+1 if a[x]*b[a[x]]==i and i!=n: ans=i+1 elif a[x]*b[a[x]]==i-1: ans=i print(ans)
Masha wants to open her own bakery and bake muffins in one of the n cities numbered from 1 to n. There are m bidirectional roads, each of whose connects some pair of cities. To bake muffins in her bakery, Masha needs to establish flour supply from some storage. There are only k storages, located in different cities nu...
3
if __name__ == '__main__' : n, m, k = map(int, input().split()) roads = [input().split() for _ in range(m)] storageCitys = {} if k > 0 : storageCitys = set(input().split()) minPay = -1 for road in roads : aCityOfThisRoad = road[0] anotherCityOfThisRoad = road[1] ...
You received a notebook which is called Death Note. This notebook has infinite number of pages. A rule is written on the last page (huh) of this notebook. It says: "You have to write names in this notebook during n consecutive days. During the i-th day you have to write exactly a_i names.". You got scared (of course yo...
3
n, m = map(int, input().split()) a = list(map(int, input().split())) cr = 0 for i in range(n): cnt = 0 # carry if cr > a[i]: cr -= a[i] a[i] = 0 elif cr > 0: cnt += 1 a[i] -= cr cr = 0 # in a fresh page if a[i]: cnt += a[i] // m cr = m -...
The math faculty of Berland State University has suffered the sudden drop in the math skills of enrolling students. This year the highest grade on the entrance math test was 8. Out of 100! Thus, the decision was made to make the test easier. Future students will be asked just a single question. They are given a sequen...
3
n = int(input()) l = list(map(int,input().split())) c=0 for i in range(1,n): if l[i-1]==1: if l[i]==2: c+=3 if i-2>=0 and l[i-2]==3: c-=1 else: c+=4 elif l[i-1]==2: if l[i]==1: c+=3 else: print('Infinite'...
The programming competition season has already started and it's time to train for ICPC. Sereja coaches his teams for a number of year and he knows that to get ready for the training session it's not enough to prepare only problems and editorial. As the training sessions lasts for several hours, teams become hungry. Thu...
3
##n = int(input()) ##a = list(map(int, input().split())) ##print(" ".join(map(str, res))) n = int(input()) a = list(map(int, input().split())) for i in range(n): if a[i]%2 != 0: if i == n-1: print('NO') exit(0) a[i] -= 1 a[i+1] -= 1 if a[i] < 0 or a[i+1] < 0...
You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") a and b. Then you try to turn a into b using two types of operations: * Write parity(a...
3
a = input() b = input() if ((a.count('1') + 1) // 2 * 2) >= b.count('1'): print("YES") else: print("NO")
Shubham has a binary string s. A binary string is a string containing only characters "0" and "1". He can perform the following operation on the string any amount of times: * Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa. ...
3
for _ in range(int(input())): s=input() n=len(s) suf=[0]*(n+1) s1=0 mi=10000000000 for i in range(1,n+1): if s[i-1]=="1": suf[i]+=suf[i-1]+1 s1+=1 else: suf[i]=suf[i-1] for i in range(1,n+1): mi=min(mi,s1-suf[i]+i-suf[i]) mi2=10...
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 = input() for i in range(t): st = "" j = 0 while(1): if (j >= n): break if (s[j:j+2] == 'BG'): st += 'GB' j += 1 else: st += s[j] j += 1 # print(st) # print(st) s = st print(s)
At Akabeko Elementary School, all the students participate in a slightly unusual jogging. Students run their own lap courses at their own pace. After going around each of your courses, you will be returned to elementary school. How many laps do they all meet at the same time in elementary school after they all start el...
1
def gcd(a,b): return a if b==0 else gcd(b,a%b) while 1: n=input() if n==0:break s=[map(int,raw_input().split()) for i in range(n)] t=c=1 for i in s:t=t*i[1]/gcd(t,i[1]) for i in range(n): s[i]=t*s[i][0]/s[i][1] c=c*s[i]/gcd(c,s[i]) for i in s:print c/i
There are n students in the first grade of Nlogonia high school. The principal wishes to split the students into two classrooms (each student must be in exactly one of the classrooms). Two distinct students whose name starts with the same letter will be chatty if they are put in the same classroom (because they must ha...
3
from collections import Counter n=int(input()) l=[] for i in range(n): l+=[list(input())] a=[i[0] for i in l] c=Counter(a) count=0 for i in c: if c[i]>2: if c[i]%2==0: c[i]=c[i]//2 count+=((c[i]*(c[i]-1))) else: r=(c[i]+1)//2 r1=(c[i]-1)//2 count+=(r*(r-1))//2+((r1*(r1-1))//2) print(count)
Phoenix is playing with a new puzzle, which consists of n identical puzzle pieces. Each puzzle piece is a right isosceles triangle as shown below. <image> A puzzle piece The goal of the puzzle is to create a square using the n pieces. He is allowed to rotate and move the pieces around, but none of them can overlap an...
3
t=int(input()) for i in range(t): n=int(input()) if not n%2: if (n//2)**0.5==int((n//2)**0.5): print('YES') continue if not n%4: if (n//4)**0.5==int((n//4)**0.5): print('YES') continue print("NO") else: ...
The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups. Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime. If there is no police offi...
3
n=int(input()) a=list(map(int,input().split())) t=0 p=0 for i in range(n): if a[i]==-1: if t==0: p+=1 else: t-=1 else: t+=a[i] print(p)
<image> There is a container that is bifurcated as shown in the figure. Drop 10 balls numbered from 1 to 10 through the opening A of the container and place the balls in the left cylinder B or the right cylinder C. Since plate D can rotate left and right around the fulcrum E, you can move plate D to decide whether to...
3
# -*- coding: utf-8 -*- import sys sys.setrecursionlimit(10**6) def dfs(balls,B=-1,C=-1,cp=0): if cp==len(balls): return True ball = balls[cp] if B<ball: is_find = dfs(balls,ball,C,cp+1) if is_find: return True if C<ball: is_find = dfs(balls,B,ball,cp+1) if is_find: return True return False def main():...
There is a frog staying to the left of the string s = s_1 s_2 … s_n consisting of n characters (to be more precise, the frog initially stays at the cell 0). Each character of s is either 'L' or 'R'. It means that if the frog is staying at the i-th cell and the i-th character is 'L', the frog can jump only to the left. ...
3
t = int(input()) for w in range(t): s = input() c = 0 mc = 0 for i in range(len(s)): if s[i] == 'L': c += 1 if c > mc: mc = c else: c = 0 print(mc+1)
There was once young lass called Mary, Whose jokes were occasionally scary. On this April's Fool Fixed limerick rules Allowed her to trip the unwary. Can she fill all the lines To work at all times? On juggling the words Right around two-thirds Sh...
3
def delitlist(k): q=[] for i in range(1, int(pow(k,0.5))+1): if k%i==0: q.append(i) s=len(q) for i in range(s): if k//q[s-i-1]!=q[-1]: q.append(k//q[s-i-1]) return q n=int(input()) s='' x=delitlist(n) if len(x)==3: s=2*str(x[1]) else: s=str(x[1])+str(...
You are given a sequence a consisting of n integers. You may partition this sequence into two sequences b and c in such a way that every element belongs exactly to one of these sequences. Let B be the sum of elements belonging to b, and C be the sum of elements belonging to c (if some of these sequences is empty, the...
3
n=int(input()) s=input().split() a=[] for i in s: a.append(int(i)) b=[] c=[] for i in a: if i>=0: b.append(i) else: c.append(i) print(sum(b)-sum(c))
You are given an array d_1, d_2, ..., d_n consisting of n integer numbers. Your task is to split this array into three parts (some of which may be empty) in such a way that each element of the array belongs to exactly one of the three parts, and each of the parts forms a consecutive contiguous subsegment (possibly, em...
3
import math as mt import sys from collections import * # try: # sys.stdin = open('a.in', 'r') # input = sys.stdin.readline # except: # pass n = int(input()) a = [int(x) for x in input().split()] sum1, sum2, res = 0, 0, 0 r = n for l in range(n): sum1 += a[l] while sum2 < sum1: r -= 1 ...
As you may know, MemSQL has American offices in both San Francisco and Seattle. Being a manager in the company, you travel a lot between the two cities, always by plane. You prefer flying from Seattle to San Francisco than in the other direction, because it's warmer in San Francisco. You are so busy that you don't rem...
3
# https://codeforces.com/problemset/problem/867/A input() s = input() # SF = travel Seattle to San Francisco # FS = travel San Francisco to Seattle print('YES' if s.count('SF') > s.count('FS') else 'NO')
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
import sys import math a,b=map(int,input().split()) for i in range(a): if i%2==0: print("#"*b) elif (i+1)%4==0: print("#"+"."*(b-1)) else: print("."*(b-1)+"#")
Lunar New Year is approaching, and Bob is struggling with his homework – a number division problem. There are n positive integers a_1, a_2, …, a_n on Bob's homework paper, where n is always an even number. Bob is asked to divide those numbers into groups, where each group must contain at least 2 numbers. Suppose the n...
3
n=int(input()) a=list(map(int,input().split())) a.sort() s=0 for i in range(n//2): s+=((a[i]+a[n-i-1])**2) print(s)
Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock. <image> The combination lock is represented by n rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has t...
3
a=int(input()) b=input() c=input() j=0 i=0 while i<a: x=(abs(int(b[i])-int(c[i]))) y=10-x j+=min(x,y) i+=1 print(j)
Slime has a sequence of positive integers a_1, a_2, …, a_n. In one operation Orac can choose an arbitrary subsegment [l … r] of this sequence and replace all values a_l, a_{l + 1}, …, a_r to the value of median of \\{a_l, a_{l + 1}, …, a_r\}. In this problem, for the integer multiset s, the median of s is equal to th...
3
def solve(): n, k = map(int, input().split()) a = list(map(int, input().split())) flg = False for x in a: if x==k: flg=True if flg==False: return "no" if n == 1: return "yes" for i in range(n): for dx in range(1, 3): ...
You are given an array a consisting of n integers. Indices of the array start from zero (i. e. the first element is a_0, the second one is a_1, and so on). You can reverse at most one subarray (continuous subsegment) of this array. Recall that the subarray of a with borders l and r is a[l; r] = a_l, a_{l + 1}, ..., a_...
3
t=int(input()) while(t>0): n,a=int(input()),list(map(int,input().split())) mx_n,mx=0,0 for i in range(0,n-1,2): mx_n+=(a[i+1]-a[i]) mx=max(mx_n,mx) mx_n=max(0,mx_n) mx_n=0 for i in range(1,n-1,2): mx_n+=(a[i]-a[i+1]) mx=max(mx_n,mx) mx_n=max(0,mx_n) ...
A bus moves along the coordinate line Ox from the point x = 0 to the point x = a. After starting from the point x = 0, it reaches the point x = a, immediately turns back and then moves to the point x = 0. After returning to the point x = 0 it immediately goes back to the point x = a and so on. Thus, the bus moves from ...
3
a,b,f,k=map(int,input().split()) req=0 live_fuel=b while(k>0): live_fuel-=f # print(live_fuel) k-=1 if(live_fuel<0): req=-1 break else: if(live_fuel>=2*(a-f) or (k==0 and live_fuel>=a-f)): live_fuel-=(a-f) else: live_fuel=b req+=1 live_fuel-=(a-f) # ...
Innokentiy decides to change the password in the social net "Contact!", but he is too lazy to invent a new password by himself. That is why he needs your help. Innokentiy decides that new password should satisfy the following conditions: * the length of the password must be equal to n, * the password should con...
3
import random def generatePass(conditions): alphabet = "abcdefghijklmnopqrstuvwxyz" alphabetList = list(alphabet) passLetters = [] password = "" index = 0 for i in range(int(conditions[1])): randomIndex = random.randint(0,len(alphabetList)-1) passLetters.append(alphabetList[rando...
There are b boys and g girls participating in Olympiad of Metropolises. There will be a board games tournament in the evening and n participants have accepted the invitation. The organizers do not know how many boys and girls are among them. Organizers are preparing red badges for girls and blue ones for boys. Vasya ...
3
b=int(input()) g=int(input()) n=int(input()) a=[i for i in range(n+1)] tot=0 # print(a) for i in a: if i>b or n-i>g: tot-=1 tot+=1 print(tot)
Monocarp has decided to buy a new TV set and hang it on the wall in his flat. The wall has enough free space so Monocarp can buy a TV set with screen width not greater than a and screen height not greater than b. Monocarp is also used to TV sets with a certain aspect ratio: formally, if the width of the screen is w, an...
3
import math a,b,x,y = list(map(int,input().strip().split())) ans = 0 g = math.gcd(x,y) x = x/g y = y/g ans = min(math.floor(a/x),math.floor(b/y)) # for w in range(1,a+1): # for h in range(1,b+1): # if (w/h) == (x/y): # ans += 1 print(ans)
Vova plans to go to the conference by train. Initially, the train is at the point 1 and the destination point of the path is the point L. The speed of the train is 1 length unit per minute (i.e. at the first minute the train is at the point 1, at the second minute — at the point 2 and so on). There are lanterns on the...
3
a = int(input()) for i in range(a): b, c, d, f = list(map(int, input().split())) print(b // c - (f // c - (d - 1) // c))
Polycarp plays "Game 23". Initially he has a number n and his goal is to transform it to m. In one move, he can multiply n by 2 or multiply n by 3. He can perform any number of moves. Print the number of moves needed to transform n to m. Print -1 if it is impossible to do so. It is easy to prove that any way to trans...
3
n,m = map(int,input().split(' ')) #print(n,m) #print(m%n) if(m%n==0): ans = 0 temp = m//n while(temp%2==0): temp = temp//2 ans = ans +1 while(temp%3==0): temp = temp//3 ans = ans+1 if(temp!=1): ans = -1 print(ans) else: ans = -1 print(ans)
We have a grid with H rows and W columns. At first, all cells were painted white. Snuke painted N of these cells. The i-th ( 1 \leq i \leq N ) cell he painted is the cell at the a_i-th row and b_i-th column. Compute the following: * For each integer j ( 0 \leq j \leq 9 ), how many subrectangles of size 3×3 of the gr...
3
def main(): from sys import stdin input = stdin.readline h, w, n = map(int, input().split()) ab = [list(map(int, input().split())) for _ in [0]*n] ans = [0]*10 d = {} for a, b in ab: for j in range(-1, 2): for k in range(-1, 2): d[(a+j, b+k)] = d.get((a+...
Bob has a string s consisting of lowercase English letters. He defines s' to be the string after removing all "a" characters from s (keeping all other characters in the same order). He then generates a new string t by concatenating s and s'. In other words, t=s+s' (look at notes for an example). You are given a string...
1
#! /usr/bin/python t = raw_input().strip() d = [c for c in t if c != 'a'] n = len(d) / 2 if d[:n] == d[n:] and t[len(t) - n:].count('a') == 0: print t[:len(t) - n] else: print ":("
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated. The language is that peculiar as it has exactly one variable, called x. Also, there are two operations: * Operation ++ increases the value of variable x by 1. * Operation -- decreases the value of variable x by 1....
1
x = 0 for i in range(input()): n = raw_input() if n[0] == '+' or n[1] == '+': x+=1 else: x-=1 print x
Find the number of integers between 1 and K (inclusive) satisfying the following condition, modulo 10^9 + 7: * The sum of the digits in base ten is a multiple of D. Constraints * All values in input are integers. * 1 \leq K < 10^{10000} * 1 \leq D \leq 100 Input Input is given from Standard Input in the following ...
3
# @author import sys class SDigitSum: def solve(self): MOD = 10 ** 9 + 7 k = input().strip() d = int(input()) s = len(k) dp = [[0] * d for _ in range(s + 1)] dp[0][0] = 1 for i in range(10): dp[1][i % d] += 1 # pre = [[0] * (d + 1) fo...
Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it ...
3
n=int(input()) a=[0]*(n+1) i=1 while i<n+1: k=input().split() k[0]=int(k[0]) k[1]=int(k[1]) a[i]=a[i-1]-k[0]+k[1] i+=1 print(max(a))
Snuke has N dogs and M monkeys. He wants them to line up in a row. As a Japanese saying goes, these dogs and monkeys are on bad terms. ("ken'en no naka", literally "the relationship of dogs and monkeys", means a relationship of mutual hatred.) Snuke is trying to reconsile them, by arranging the animals so that there a...
3
#犬同士 または 猿同士 #交互のみ mod = 10**9+7 """ def chs(k,i,mod): deno = 1 for j in range(k,k-i,-1): deno*=j deno%=mod nume = 1 for j in range(1,j+1): nume*=pow(j,mod-2,mod) nume%=mod return deno*nume%mod """ n,m = map(int, input().split( )) if abs(n-m)>1: print(0) exit...
You are given an array a of length n. You are also given a set of distinct positions p_1, p_2, ..., p_m, where 1 ≤ p_i < n. The position p_i means that you can swap elements a[p_i] and a[p_i + 1]. You can apply this operation any number of times for each of the given positions. Your task is to determine if it is poss...
3
t = int(input()) for _ in range(t): n,m = map(int,input().split()) a = list(map(int,input().split())) p = list(map(int,input().split())) l = a[::] l.sort() p.sort() flag = 0 start = p[0] arr = [] for j in range(1,len(p)+1): if(j==len(p) or p[j]-p[j-1]!=1): arr...
A string s of length n can be encrypted by the following algorithm: * iterate over all divisors of n in decreasing order (i.e. from n to 1), * for each divisor d, reverse the substring s[1 ... d] (i.e. the substring which starts at position 1 and ends at position d). For example, the above algorithm applied t...
3
n = int(input()) s = input() for i in range(2, n + 1): if n % i == 0: first = s[0:i] sec = s[i:] s = first[::-1] + sec print(s)
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits. Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has on...
3
num = int(input()) while True: num += 1 n = str(num) if (n[0] != n[1]) and (n[0] != n[2]) and (n[0] != n[3]) and (n[1] !=n[2]) and (n[1]!= n[3]) and (n[2] !=n[3]): break print(num)
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." — an excerpt from contest rules. A total of n participants took part in the contest (n ≥ k), and you already know their scores. Calculate how many ...
3
n, k = map(int, input().split(" ")) arr = list(map(int,input().split(" "))) count = 0 for i in arr: if (i > 0 and i >= arr[k-1]): count += 1 print(count)
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem. Pete and Bi...
3
def d(w): if w == 2: return 'NO' if w % 2 == 0: return 'YES' return 'NO' w = int(input()) print(d(w))
Tokitsukaze is playing a game derivated from Japanese mahjong. In this game, she has three tiles in her hand. Each tile she owns is a suited tile, which means it has a suit (manzu, pinzu or souzu) and a number (a digit ranged from 1 to 9). In this problem, we use one digit and one lowercase letter, which is the first c...
3
b=list(input().split()) a=b[0] c=b[1] d=b[2] p=[int(a[0]),int(c[0]),int(d[0])] p.sort() if a[1]==c[1]: if a[1]==d[1]: k=p[1]-p[0] q=p[2]-p[1] if k==0 and q==0: print(0) elif k==0 or q==0: print(1) elif k==1 and q==1: print(0) elif k...
Little Vasya has received a young builder’s kit. The kit consists of several wooden bars, the lengths of all of them are known. The bars can be put one on the top of the other if their lengths are the same. Vasya wants to construct the minimal number of towers from the bars. Help Vasya to use the bars in the best way ...
3
n=int(input()) bars=list(map(int,input().split())) high=max(list(map(lambda x:bars.count(x),bars))) towers=len(set(bars)) print(high,towers)
You are locked in a room with a door that has a keypad with 10 keys corresponding to digits from 0 to 9. To escape from the room, you need to enter a correct code. You also have a sequence of digits. Some keys on the keypad have fingerprints. You believe the correct code is the longest not necessarily contiguous subse...
1
n, m = map(int, raw_input().split()) ans = [] x = map(int, raw_input().split()) y = map(int, raw_input().split()) for num in x: if num in y: ans.append(num) for i in range(len(ans)): if i < len(ans) - 1: print ans[i], else: print ans[i]
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
t=int(input()) for i in range(t): n,k=map(int,input().split()) x=n//k y=n%k if(y>k//2): print(n-(y-k//2)) elif(y==k//2): print(n) elif(y<k//2): print(n)
M-kun is a student in Aoki High School, where a year is divided into N terms. There is an exam at the end of each term. According to the scores in those exams, a student is given a grade for each term, as follows: * For the first through (K-1)-th terms: not given. * For each of the K-th through N-th terms: the multipl...
3
n,k=map(int,input().split()) a=list(map(int,input().split())) s=sum(a[:k]) for i in range(n-k): t=s-a[i]+a[k+i] print('YNeos'[s>=t::2]) s=t
Olga came to visit the twins Anna and Maria and saw that they have many cookies. The cookies are distributed into bags. As there are many cookies, Olga decided that it's no big deal if she steals a bag. However, she doesn't want the sisters to quarrel because of nothing when they divide the cookies. That's why Olga wan...
3
from sys import stdin n = int(input()) k = [int(i) for i in stdin.readline().split()] ans = 0 t = sum(k) for i in k: if (t-i)%2==0: ans += 1 print(ans)
For the New Year, Polycarp decided to send postcards to all his n friends. He wants to make postcards with his own hands. For this purpose, he has a sheet of paper of size w × h, which can be cut into pieces. Polycarp can cut any sheet of paper w × h that he has in only two cases: * If w is even, then he can cut t...
3
t = int(input()) while t: w,h,n = list(map(int,input().split())) p = 0 while w%2==0 and w>1: p+=1 w=w//2 while h%2==0 and h>1: p+=1 h = h//2 # print(p) if (2**p)>=n: print("YES") else: print("NO") t-=1