problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
Kolya is very absent-minded. Today his math teacher asked him to solve a simple problem with the equation a + 1 = b with positive integers a and b, but Kolya forgot the numbers a and b. He does, however, remember that the first (leftmost) digit of a was d_a, and the first (leftmost) digit of b was d_b. Can you reconst...
3
d1, d2 =map(int, input().split()) if d1 == d2: print(str(d1) + '4', str(d2) + '5') elif d2 - d1 == 1: print(str(d1) + '99', str(d2) + '00') elif d1 == 9 and d2 == 1: print('99 100') else: print(-1)
Sonya decided that having her own hotel business is the best way of earning money because she can profit and rest wherever she wants. The country where Sonya lives is an endless line. There is a city in each integer coordinate on this line. She has n hotels, where the i-th hotel is located in the city with coordinate ...
3
def hotels(lst, d): kol = 2 x, y = 0, 0 for i in range(len(lst) - 1): x = lst[i] + d y = lst[i + 1] - d if x < y: kol += 2 elif x == y: kol += 1 return kol N, D = [int(j) for j in input().split()] a = [int(z) for z in input().split()] print(hotel...
Petya is having a party soon, and he has decided to invite his n friends. He wants to make invitations in the form of origami. For each invitation, he needs two red sheets, five green sheets, and eight blue sheets. The store sells an infinite number of notebooks of each color, but each notebook consists of only one co...
3
#https://codeforces.com/problemset/problem/1080/A import math f, numSheet = map(int, input().split()) r = 2 g = 5 b = 8 numR = math.ceil((r * f)/numSheet) numG = math.ceil((g * f)/numSheet) numB = math.ceil((b * f)/numSheet) print(numR + numG + numB)
k people want to split n candies between them. Each candy should be given to exactly one of them or be thrown away. The people are numbered from 1 to k, and Arkady is the first of them. To split the candies, Arkady will choose an integer x and then give the first x candies to himself, the next x candies to the second ...
3
n, k, m, d = map(int, input().split()) ans = -1 for i in range(1, d+1): cur = n // (k*i - k + 1) ans = max(ans, min(cur, m) * i) print(ans)
[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
n = input() _array = input() new_array = _array.split(" ") a=[] for i in new_array: a.append(int(i)) count = 1 b=1 def snap(list1,list2): _list1 = 1 _list2 = 1 count1=1 count2 = 1 for i in range(0,len(list1)-1): if(list1[i] <= list1[i+1]): ...
It's a walking tour day in SIS.Winter, so t groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another. Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P": * "A" corresponds to an angry...
3
for i in [0]*int(input()): n = int(input()) auff = False k, max_k = 0, 0 for j in input(): if j == 'A': auff = True max_k = max(max_k, k) k = 0 elif auff == True: k += 1 print(max(max_k, k))
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
def get_num_decks(b, g, n): mxb = min(b, n) mxg = min(g, n) mnb = n - mxg mng = n - mxb s = set() for i in range(mnb, mxb + 1): s.add((i, n - i)) for i in range(mng, mxg + 1): s.add((n - i, i)) return len(s) if __name__ == '__main__': ins = [] for _ in rang...
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
def main(): inp = input() output = "" for char in inp: if char.upper() in "AEIOUY": continue else: output += "." + char.lower() print(output) main()
Polycarp and his friends want to visit a new restaurant. The restaurant has n tables arranged along a straight line. People are already sitting at some tables. The tables are numbered from 1 to n in the order from left to right. The state of the restaurant is described by a string of length n which contains characters ...
3
def helper(n, k, s): prev, count = -k - 1, 0 for i in range(n): if s[i] == '0': if i - prev - 1 >= k: count += 1 prev = i else: if i - prev - 1 < k: count -= 1 prev = i return count for _ in range(int(input...
We have N balls. The i-th ball has an integer A_i written on it. For each k=1, 2, ..., N, solve the following problem and print the answer. * Find the number of ways to choose two distinct balls (disregarding order) from the N-1 balls other than the k-th ball so that the integers written on them are equal. Constraint...
1
n = raw_input() a = map(int, raw_input().split(' ')) import collections q = 0 cc = collections.Counter(a) for k in cc: q += cc[k] * (cc[k]-1) /2 for e in a: print q - cc[e] * (cc[e]-1) /2 + (cc[e]-1)*(cc[e]-2)/2
Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game. Rules of the game are very simple: at first number of rounds n is defined. I...
3
k=0 for _ in range(int(input())): m,c=map(int,input().split()) k+=m>c;k-=m<c print('Mishka' if k>0 else ['Friendship is magic!^^','Chris'][k<0])
One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are n lines in that description each of which described one goal. Eve...
3
n=int(input()) d=dict() for i in range(n): s=input() if s in d: d[s]+=1 else: d[s]=1 ans=[0] maxg = float("-inf") for i,j in d.items(): if j > maxg: maxg=j ans[0]=i print(ans[0])
The New Year is coming! That's why many people today are busy preparing New Year presents. Vasily the Programmer is no exception. Vasily knows that the best present is (no, it's not a contest) money. He's put n empty wallets from left to right in a row and decided how much money to put in what wallet. Vasily decided t...
3
# Description of the problem can be found at http://codeforces.com/problemset/problem/379/B n = int(input()) l_n = list(map(int, input().split())) s = "" for i in range(n): if l_n[i] == 0: if i + 1 == n: print("".join(c for c in s)) quit() else: s += "R" els...
The round carousel consists of n figures of animals. Figures are numbered from 1 to n in order of the carousel moving. Thus, after the n-th figure the figure with the number 1 follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal...
3
# Enter your code here. Read input from STDIN. Print output to STDOUT# =============================================================================================== # importing some useful libraries. from __future__ import division, print_function from fractions import Fraction import sys import os from io import Byt...
Santa Claus has n candies, he dreams to give them as gifts to children. What is the maximal number of children for whose he can give candies if Santa Claus want each kid should get distinct positive integer number of candies. Santa Class wants to give all n candies he has. Input The only line contains positive integ...
1
#------------------------------------------------------------------------------- # Name: module1 # Purpose: seems easy # # Author: nobody # # Created: 05-01-2017 # Copyright: (c) nobody 2017 # Licence: <your licence> #---------------------------------------------------------------------------...
Pasha has two hamsters: Arthur and Alexander. Pasha put n apples in front of them. Pasha knows which apples Arthur likes. Similarly, Pasha knows which apples Alexander likes. Pasha doesn't want any conflict between the hamsters (as they may like the same apple), so he decided to distribute the apples between the hamste...
3
n,a,b=[int(x) for x in input().split()] l=[2]*n for i in [int(x)-1 for x in input().split()]: l[i]=1 print(*l)
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
n=int(input()) for o in range(n): n=int(input()) s=input() if "8" in s: for i in range(n): if s[i]=="8": s=s[i:n+1] break if len(s)>=11: print("YES") else: print("NO") else: print("NO")
Calvin the robot lies in an infinite rectangular grid. Calvin's source code contains a list of n commands, each either 'U', 'R', 'D', or 'L' — instructions to move a single square up, right, down, or left, respectively. How many ways can Calvin execute a non-empty contiguous substrings of commands and return to the sam...
3
#!/usr/bin/env python n = int(input()) s = input() su = 0 for i in range(0, n - 1): for i1 in range(i + 1, n): x = 0 y = 0 for c in s[i : i1 + 1]: if c == 'U': y += 1 elif c == 'D': y -= 1 elif c == 'R': x +=...
After playing Neo in the legendary "Matrix" trilogy, Keanu Reeves started doubting himself: maybe we really live in virtual reality? To find if this is true, he needs to solve the following problem. Let's call a string consisting of only zeroes and ones good if it contains different numbers of zeroes and ones. For exa...
3
a=int(input()) t=input() u=t.count('1') v=t.count('0') if u==v: print(2) print(t[0:len(t)-1]+ ' ' +t[len(t)-1]) else: print(1) print(t)
Takahashi is a teacher responsible for a class of N students. The students are given distinct student numbers from 1 to N. Today, all the students entered the classroom at different times. According to Takahashi's record, there were A_i students in the classroom when student number i entered the classroom (including...
3
N=int(input()) A=list(map(int,input().split())) O=[0]*N for i in range(N): O[A[i]-1]=i+1 print(*O)
PolandBall is a young, clever Ball. He is interested in prime numbers. He has stated a following hypothesis: "There exists such a positive integer n that for each positive integer m number n·m + 1 is a prime number". Unfortunately, PolandBall is not experienced yet and doesn't know that his hypothesis is incorrect. Co...
3
def is_prime(adad): if adad==2: return True else: saquare = int(adad**(0.5))+1 counter=2 while(counter<saquare): if adad%counter!=0: counter+=1 else: return False return True vurudi_asli = int(input()) prime_check = True zarib = 1 while(prime_check): vurudi = vurudi_asli*zarib + 1 #Is ...
In this problem you will write a simple generator of Brainfuck (<https://en.wikipedia.org/wiki/Brainfuck>) calculators. You are given an arithmetic expression consisting of integers from 0 to 255 and addition/subtraction signs between them. Output a Brainfuck program which, when executed, will print the result of eval...
1
s = input() s %= 256 cur = 0 ans = '+' * ord('0') s = str(s) for c in s: num = int(c) while cur < num: cur += 1 ans += '+' while cur > num: cur -= 1 ans += '-' ans += '.' print ans
Mishka wants to buy some food in the nearby shop. Initially, he has s burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1 ≤ x ≤ s, buy food that costs exactly x burles and obtain ⌊x/10⌋ burles as a cashback (in other words, Mishka ...
3
t = int(input()) for _ in range(t): n = int(input()) res = 0 while n >= 10: x = n//10*10 res += x n -= x n += x//10 print(res+n)
Takahashi has A cookies, and Aoki has B cookies. Takahashi will do the following action K times: * If Takahashi has one or more cookies, eat one of his cookies. * Otherwise, if Aoki has one or more cookies, eat one of Aoki's cookies. * If they both have no cookies, do nothing. In the end, how many cookies will Taka...
3
a,b,k=map(int,input().split()) t=min(a,k) s=min(b,k-t) print(a-t,b-s)
You have integer n. Calculate how many ways are there to fully cover belt-like area of 4n-2 triangles with diamond shapes. Diamond shape consists of two triangles. You can move, rotate or flip the shape, but you cannot scale it. 2 coverings are different if some 2 triangles are covered by the same diamond shape in ...
3
t,*x=open(0);print(*x)
There are three friend living on the straight line Ox in Lineland. The first friend lives at the point x1, the second friend lives at the point x2, and the third friend lives at the point x3. They plan to celebrate the New Year together, so they need to meet at one point. What is the minimum total distance they have to...
3
import sys f = [int(i) for i in input().split()] f.sort() result = 0 result += f[1] - f[0] result += f[2] - f[1] print(result)
You are given two integers A and B as the input. Output the value of A + B. However, if A + B is 10 or greater, output `error` instead. Constraints * A and B are integers. * 1 ≤ A, B ≤ 9 Input Input is given from Standard Input in the following format: A B Output If A + B is 10 or greater, print the string `e...
3
A, B = map(int, input().split()) print(A+B if A+B < 10 else 'error')
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her. Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain ...
3
t, p = input(), input() indices = tuple(map(int, input().split())) n = len(t) np = len(p) l = 0 right = n ans = 0 while n - l > 1: m = (l + right) // 2 if l == m: break tu = list(t) for i in range(l, m): tu[indices[i] - 1] = "0" pos = 0 yes = 0 for i in tu: if i == p[...
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()) r=0 for i in range(n): ch=input() if ch=='Tetrahedron':r+=4 if ch=='Cube': r+=6 if ch=='Octahedron':r+=8 if ch=='Dodecahedron':r+=12 if ch=='Icosahedron':r+=20 print(r)
We call a 4-digit integer with three or more consecutive same digits, such as 1118, good. You are given a 4-digit integer N. Answer the question: Is N good? Constraints * 1000 ≤ N ≤ 9999 * N is an integer. Input Input is given from Standard Input in the following format: N Output If N is good, print `Yes`; ot...
3
n=input() print('Yes'if len(set(n[1:]))==1 or len(set(n[:-1]))==1 else'No')
You are given positive integers A and B. Find the K-th largest positive integer that divides both A and B. The input guarantees that there exists such a number. Constraints * All values in input are integers. * 1 \leq A, B \leq 100 * The K-th largest positive integer that divides both A and B exists. * K \geq 1 In...
3
a, b, k=map(int, input().split()) c=0 p=min(a,b) while (c!=k): if a%p==0 and b%p==0: x=p c+=1 p-=1 print(x)
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." — an excerpt from contest rules. A total of n participants took part in the contest (n ≥ k), and you already know their scores. Calculate how many ...
3
n, k = [int(item) for item in input().split()] partners = [int(item) for item in input().split()] count = 0 for partner in partners: if partner > 0 and partner >= partners[k - 1]: count += 1 print(count)
Little Jhool always wanted to have some psychic powers so that he could showoff his skills, and magic to people and impress them. (Specially, his girlfriend Big Jhool!) But, in spite all his efforts, hardwork, dedication, Googling, watching youtube videos he couldn't garner any psychic abilities! He knew everyone was ...
1
s = raw_input() if '111111' in s or '000000' in s: print 'Sorry, sorry!' else: print 'Good luck!'
Let's call a positive integer composite if it has at least one divisor other than 1 and itself. For example: * the following numbers are composite: 1024, 4, 6, 9; * the following numbers are not composite: 13, 1, 2, 3, 37. You are given a positive integer n. Find two composite integers a,b such that a-b=n. I...
3
def isPrime(n) : if (n <= 1) : return True if (n <= 3) : return False if (n % 2 == 0 or n % 3 == 0) : return True i = 5 while(i * i <= n) : if (n % i == 0 or n % (i + 2) == 0) : return True i = i + 6 return False n=int(input()) a=b=-1 f...
Input The only line of the input contains a string of digits. The length of the string is between 1 and 10, inclusive. Output Output "Yes" or "No". Examples Input 373 Output Yes Input 121 Output No Input 436 Output Yes
3
mirror = [8, -1, -1, 3, 6, 9, 4, 7, 0, 5] def dg(n): if n: res = [] while n: res.append(n%10) n //= 10 else: res = [0] return res n = int(input()) dg1 = dg(n) dg2 = [mirror[d] for d in reversed(dg1)] if dg1 == dg2: 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
#!/usr/bin/env python3 T = int(input()) def cost_01(N, prefix_0, prefix_1, suffix_0, suffix_1): ans = float("inf") for i in range(N+1): if i > 0: front_cost = prefix_1[i-1] else: front_cost = 0 if i < N: back_cost = suffix_0[i] else: ...
You are given an array a consisting of n integers. Your task is to say the number of such positive integers x such that x divides each number from the array. In other words, you have to find the number of common divisors of all elements in the array. For example, if the array a will be [2, 4, 6, 2, 10], then 1 and 2 ...
3
n=int(input()) l=[int(i) for i in input().split()] l.sort() l1=[l[i]-l[i-1] for i in range(1,n)] def gcd(a,b): if b==0: return a return gcd(b,a%b) g=0 from math import sqrt as S for i in l1: g=gcd(g,i) def count_div(g): if g ==1: return 1 c=2 for i in range(2,int(S(g))+1): ...
Write a program to simulate rolling a dice, which can be constructed by the following net. <image> <image> As shown in the figures, each face is identified by a different label from 1 to 6. Write a program which reads integers assigned to each face identified by the label and a sequence of commands to roll the d...
1
class Dice(object): def __init__(self, top, south, east, west, north, bottom): self.top = top self.south = south self.east = east self.west = west self.north = north self.bottom = bottom def rollN(self): prevN = self.north prevB = self.bottom ...
Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be n problems, sorted by difficulty, i.e. problem 1 is the easiest and problem n is the hardest. Limak knows it will take him 5·i minutes to solve the i-th...
1
#stdin.readline() #int(stdin.readline()) #stdout.write() #raw_input() #map(int,raw_input().split()) #map(int,stdin.readline().split()) def main(): n,k=map(int,stdin.readline().split()) q=0 if q+k>=240: print 0 exit() for i in xrange(1,n+1): q+=i*5 if q+k>240: ...
Mishka is trying really hard to avoid being kicked out of the university. In particular, he was doing absolutely nothing for the whole semester, miraculously passed some exams so that just one is left. There were n classes of that subject during the semester and on i-th class professor mentioned some non-negative inte...
3
n = int(input()) b = list(map(int, input().split())) a = [0 for i in range(n)] a[-1] = b[0] for i in range(1, n//2): if b[i] > a[-i]: a[i] = max(a[i-1], b[i]-a[-i]) else: a[i] = a[i-1] a[-i-1] = b[i]-a[i] print(*a)
n students are taking an exam. The highest possible score at this exam is m. Let a_{i} be the score of the i-th student. You have access to the school database which stores the results of all students. You can change each student's score as long as the following conditions are satisfied: * All scores are integers ...
3
t = int(input()) for _ in range(t): n,m = map(int, input().split()) a = list(map(int, input().split())) assert len(a) == n print(min(m, sum(a)))
A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all n squad soldiers to line up on the parade ground. By the military charter the soldiers should stand in the order of non-increasing of their h...
3
n = int(input()) ls = list(map(int, input().split())) mx = 0 for i in range(n): if ls[i] > ls[mx]: mx = i mn = 0 for i in range(n): if ls[i] <= ls[mn]: mn = i cnt = mx + (n - 1 - mn) if mx > mn: cnt -=1 print(cnt)
Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths a, b, and c. Now he needs to find out some possible integer length d of the fourth straight fence segment so that he can build the fence using these four...
3
def main(a, b, c): return max(a, b, c) ts = [] t = int(input()) for _ in range(t): ts.append(map(int, input().split())) for el in ts: print(main(*el))
One day Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won. Alex has grown up since then, so he easily wins the most difficu...
3
def fun(c,x,y,l,n,m): if c==".": for k in range(max(0,y-1),min(m,y+2)): for b in range(max(0,x-1),min(x+2,n)): if l[b][k]=="*": return False return True elif c=="*": for k in range(max(0,y-1),min(m,y+...
Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor «Textpad» decided to introduce this functionality into the fourth release of the product. You are to implement the alignment in the shortest possible time. Good luck! Input The input file c...
1
import sys length = 0 left = True lines = [] for s in sys.stdin: length = max(length, len(s) - 1) lines.append(s[:-1]) print '*' * (length + 2) for s in lines: if (length - len(s)) % 2 == 0: a = (length - len(s)) / 2 b = (length - len(s)) / 2 else: ...
This is the easy version of the problem. The difference between the versions is that in the easy version all prices a_i are different. You can make hacks if and only if you solved both versions of the problem. Today is Sage's birthday, and she will go shopping to buy ice spheres. All n ice spheres are placed in a row ...
3
n=int(input()) ai=list(map(int,input().split())) ai.sort() out=[] i=0 j=n//2 while i<n//2 and j<n: out.append(ai[j]) out.append(ai[i]) j+=1 i+=1 # print(int(n/2)) if n%2!=0 else print(int(n/2)-1) if n%2: out.append(ai[n-1]) ct=0 for i in range(1,n-1): if out[i]<out[i-1] and out[i]<out[i+1]: ...
You are given a set of n segments on the axis Ox, each segment has integer endpoints between 1 and m inclusive. Segments may intersect, overlap or even coincide with each other. Each segment is characterized by two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ m) — coordinates of the left and of the right endpoints. Consider...
3
s = list(map(int, input().split())) n, m = s[0], s[1] cl = [] def check(x): res = True for r in cl: if x>=r[0] and x<=r[1]: res = False break return res for i in range(n): cl.append(list(map(int, input().split()))) res = [] for i in range(1, m+1): if check(i): res.app...
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() l = 0 u = 0 for i in s: if i>='a' and i<='z': l += 1 else : u += 1 if l == u: print(s.lower()) elif l>u: print(s.lower()) else: print(s.upper())
Recently a Golden Circle of Beetlovers was found in Byteland. It is a circle route going through n ⋅ k cities. The cities are numerated from 1 to n ⋅ k, the distance between the neighboring cities is exactly 1 km. Sergey does not like beetles, he loves burgers. Fortunately for him, there are n fast food restaurants on...
3
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # """ 549 D """ from math import gcd n, k = map(int, input().split()) a, b = map(int, input().split()) nk = n*k cand = [] for i in range(n): cand.append(gcd(nk, abs((i*k+b-a)))) cand.append(gcd(nk, abs((i*k-b-a)))) cand.append(gcd(nk, abs...
Anton likes to play chess, and so does his friend Danik. Once they have played n games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie. Now Anton wonders, who won more games, he or Danik? Help him determine this. Input The first line of the input contains a...
1
x,a=input(),raw_input() if a.count("A") > x/2:print"Anton" elif a.count("A") == x/2.0:print"Friendship" else:print"Danik"
You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment [0, n] on OX axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval (x, x + 1) with integer x. So we can represent the road as a binary string consist...
3
t = int(input()) for _ in range(t): n, a, b = map(int, input().rstrip().split()) s = input() + '0' m1, m2 = b, float('inf') for i in range(n): m3 = min(m1 + 2 * a + 2 * b, m2 + a + b * 2) if s[i + 1] == '0' and s[i] == '0': m1 = min(m1 + a + b, m2 + 2 * a + b) else: ...
You are asked to watch your nephew who likes to play with toy blocks in a strange way. He has n boxes and the i-th box has a_i blocks. His game consists of two steps: 1. he chooses an arbitrary box i; 2. he tries to move all blocks from the i-th box to other boxes. If he can make the same number of blocks in ...
3
for t in range(int(input())): n=int(input()) a=[int(_) for _ in input().split()] s=sum(a) m=max(a) temp=(n-1)*m if temp>s: print(temp-s) elif s==temp: print(0) else: if s%(n-1)==0: print(0) else: print((n-1)-s%(n-1))
A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all n squad soldiers to line up on the parade ground. By the military charter the soldiers should stand in the order of non-increasing of their h...
1
n=input() a=map(int,raw_input().split()) x=a.index(max(a))+a[::-1].index(min(a)) print x-(x>=n)
There are n boys and m girls attending a theatre club. To set a play "The Big Bang Theory", they need to choose a group containing exactly t actors containing no less than 4 boys and no less than one girl. How many ways are there to choose a group? Of course, the variants that only differ in the composition of the trou...
3
from math import factorial def binomial(n, k): try: binom = factorial(n) // factorial(k) // factorial(n - k) except ValueError: binom = 0 return binom temp = list(map(int, input().split())) n = temp[0] m = temp[1] t = temp[2] result = 0 for i in range(1, t-3): result += binomial(...
Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first n. He writes down the followin...
3
import math n,k=map(int,input().split()) if k>int(math.ceil(n/2)): k-=int(math.ceil(n/2)) print(2*k) else: print(2*k-1)
A coordinate line has n segments, the i-th segment starts at the position li and ends at the position ri. We will denote such a segment as [li, ri]. You have suggested that one of the defined segments covers all others. In other words, there is such segment in the given set, which contains all other ones. Now you want...
3
n = l = r = minl = maxr = 0 number = 1 n = int(input("")) minl, maxr = map(int, input().split()) for i in range(2,n+1): l, r = map(int, input().split()) if (l <= minl and r >= maxr): number = i elif (l < minl or r > maxr): number = -1 minl = min(minl, l) maxr = max(maxr, r) print(n...
You are given an integer N. Find the number of the positive divisors of N!, modulo 10^9+7. Constraints * 1≤N≤10^3 Input The input is given from Standard Input in the following format: N Output Print the number of the positive divisors of N!, modulo 10^9+7. Examples Input 3 Output 4 Input 6 Output 3...
3
n = int(input()) t = [0] * (n+1) for j in range(2, n+1): y = j for i in range(2, n+1): while y % i == 0: t[i] += 1 y = y//i ans = 1 p = 10**9 + 7 for i in t: if i != 0: ans *= (i+1) ans %= p print(ans)
When new students come to the Specialized Educational and Scientific Centre (SESC) they need to start many things from the beginning. Sometimes the teachers say (not always unfairly) that we cannot even count. So our teachers decided to teach us arithmetics from the start. And what is the best way to teach students add...
3
s = input().split('=') a = s[0].count('|') b = s[1].count('|') if(a == b): print(s[0]+"="+s[1]) elif(abs(a-b) == 2): if(a<b): print(s[0]+"|="+s[1][:-1]) else: if(s[0][-2] != '+'): print(s[0][:-1]+"=|"+s[1]) else: print(s[0][1:]+"=|"+s[1]) else: print("Impo...
Let's call a string a phone number if it has length 11 and fits the pattern "8xxxxxxxxxx", where each "x" is replaced by a digit. For example, "80123456789" and "80000000000" are phone numbers, while "8012345678" and "79000000000" are not. You have n cards with digits, and you want to use them to make as many phone n...
3
""" instagram : essipoortahmasb2018 telegram channel : essi_python """ n = int(input()) s = input() a = s.count("8") #number of 8 if a==0: print(0) exit() nn = n - a # number of digit without 8 b = a*10 if b <= nn: print(a) else: h = nn // 10 #number of code with one 8 h+=((nn%10)+(a-h))//11 pr...
Running with barriers on the circle track is very popular in the country where Dasha lives, so no wonder that on her way to classes she saw the following situation: The track is the circle with length L, in distinct points of which there are n barriers. Athlete always run the track in counterclockwise direction if you...
3
n, L = map(int, input().split()) a = list(map(int, input().split())) b = list(map(int, input().split())) for i in range(len(b)): c = b[i:] + b[:i] d = map(lambda x, y: abs(x - y), a, c) s = set(d) if len(s) == 2 and sum(s) == L or len(s) == 1: print("YES") exit(0) print("NO")...
Famous Brazil city Rio de Janeiro holds a tennis tournament and Ostap Bender doesn't want to miss this event. There will be n players participating, and the tournament will follow knockout rules from the very first game. That means, that if someone loses a game he leaves the tournament immediately. Organizers are stil...
3
def games(m): lst = [2] while lst[-1] <= m - 1: if len(lst) == 1: lst += [4] else: lst += [lst[-1] + lst[-2] + 1] return len(lst) print(games(int(input())))
This contest, AtCoder Beginner Contest, is abbreviated as ABC. When we refer to a specific round of ABC, a three-digit number is appended after ABC. For example, ABC680 is the 680th round of ABC. What is the abbreviation for the N-th round of ABC? Write a program to output the answer. Constraints * 100 ≤ N ≤ 999 I...
3
N = input() print("ABC"+str(N))
Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be n problems, sorted by difficulty, i.e. problem 1 is the easiest and problem n is the hardest. Limak knows it will take him 5·i minutes to solve the i-th...
3
s=[int(n) for n in input().split()] n=s[0] k=s[1] actualTime=240-k probTime=0 for i in range(1,n+2): probTime+=i*5 if(probTime>actualTime): break print(i-1)
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 = int(input()) a = [int(x) for x in input().split()] if(sum(a) > 0): print('HARD') elif(sum(a) == 0): print('EASY')
We have held a popularity poll for N items on sale. Item i received A_i votes. From these N items, we will select M as popular items. However, we cannot select an item with less than \dfrac{1}{4M} of the total number of votes. If M popular items can be selected, print `Yes`; otherwise, print `No`. Constraints * 1 \...
3
N,M=map(int,input().split()) A = list(map(int,input().split())) b=sum(A) s=sorted(A) if s[-M]>=(b/(4*M)): print("Yes") else: print("No")
Arpa is taking a geometry exam. Here is the last problem of the exam. You are given three points a, b, c. Find a point and an angle such that if we rotate the page around the point by the angle, the new position of a is the same as the old position of b, and the new position of b is the same as the old position of c....
3
from fractions import Fraction xa, ya, xb, yb, xc, yc = map(int, input().split()) if xa * (yb - yc) + xb * (yc - ya) + xc * (ya - yb) == 0: print('NO') elif (xa - xb)**2 + (ya - yb)**2 == (xb - xc)**2 + (yb - yc)**2: print('YES') else: print('NO')
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition. Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character...
3
def clock_distance(string): distance = 0 last_place = 0 for letter in string: value = ord(letter) - 97 normal_distance = abs(value - last_place) cross_distance = abs(last_place - value + 26) if value > last_place else abs(last_place - value - 26) distance += min(normal_distan...
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr...
3
a=list(input().lower()) b=list(input().lower()) co=0 cu=0 for i in range(len(a)): if ord(a[i])<ord(b[i]): print("-1") co=1 break if ord(a[i])>ord(b[i]): print("1") cu=1 break if co!=1 and cu!=1: print("0")
Limak and Radewoosh are going to compete against each other in the upcoming algorithmic contest. They are equally skilled but they won't solve problems in the same order. There will be n problems. The i-th problem has initial score pi and it takes exactly ti minutes to solve it. Problems are sorted by difficulty — it'...
3
n,c=map(int,input().split()) l=list(map(int,input().split())) t=list(map(int,input().split())) for i in range(len(t)): k=[] w=[] for j in range (i+1): w.append(t[j]) s=sum(w) k.append(s) for i in range(len(t)): K=[] W=[] for j in range(i+1): W.append(t[-(j+1)]) S=sum(W) K.append(S) doubt=0 for i in r...
You are given a string s[1 ... n] consisting of lowercase Latin letters. It is guaranteed that n = 2^k for some integer k ≥ 0. The string s[1 ... n] is called c-good if at least one of the following three conditions is satisfied: * The length of s is 1, and it consists of the character c (i.e. s_1=c); * The lengt...
3
global ans ans = [] def printer_rec(s,cost,character): l = len(s) fh_cost = sh_cost = 0 for i in range(l): if(s[i]!=character): if(i<int(l/2)): fh_cost +=1 else: sh_cost+=1 # print(cost,fh_cost,s[:int(l/2)],sh_cost,s[int(l/2):]) chara...
Finally, a basketball court has been opened in SIS, so Demid has decided to hold a basketball exercise session. 2 ⋅ n students have come to Demid's exercise session, and he lined up them into two rows of the same size (there are exactly n people in each row). Students are numbered from 1 to n in each row in order from ...
3
n = int(input()) s1= list(map(int, input().split())) s2 = list( map(int, input().split())) dp =[] for i in range(2): dp.append([0] + [0 for i in range(n)]) for i in range(1,n+1): dp[0][i] = max(dp[0][i-1], dp[1][i-1] + s1[i-1]) dp[1][i] = max(dp[1][i-1], dp[0][i-1] + s2[i-1]) print(max(dp[1][n], dp[0][n]))
It is November 18 now in Japan. By the way, 11 and 18 are adjacent Lucas numbers. You are given an integer N. Find the N-th Lucas number. Here, the i-th Lucas number L_i is defined as follows: * L_0=2 * L_1=1 * L_i=L_{i-1}+L_{i-2} (i≥2) Constraints * 1≤N≤86 * It is guaranteed that the answer is less than 10^{18}. ...
3
N = int(input()) a = 2 b = 1 for i in range(N-1): a, b = b, a + b print(b)
Jon fought bravely to rescue the wildlings who were attacked by the white-walkers at Hardhome. On his arrival, Sam tells him that he wants to go to Oldtown to train at the Citadel to become a maester, so he can return and take the deceased Aemon's place as maester of Castle Black. Jon agrees to Sam's proposal and Sam s...
3
from sys import stdin import math #从这里的calnum打表判断出num[n] = n # def calnum(n): # if n == 0 or n == 1: # return n # return 2 * calnum(n // 2) + calnum(n % 2) #python的math.log函数不精确。。。 def Log(n): for i in range(52): num = int(math.pow(2, i)) if n < num: return i - 1 def d...
Allen has a LOT of money. He has n dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are 1, 5, 10, 20, 100. What is the minimum number of bills Allen could receive after withdrawing his entire balance? Input The first...
3
t = int(input()) d = [100,20,10,5,1] c, i = 0, 0 while t: if t >= d[i]: c = c + (t//d[i]) t = t%d[i] else: i = i+1 print(c)
Dreamoon is a big fan of the Codeforces contests. One day, he claimed that he will collect all the places from 1 to 54 after two more rated contests. It's amazing! Based on this, you come up with the following problem: There is a person who participated in n Codeforces rounds. His place in the first round is a_1, hi...
3
def DreammoonAndRankingColection(n, x, data): idRoom = 0 while(x > 0): idRoom += 1 if(idRoom not in data): x -= 1 while(idRoom + 1 in data): idRoom += 1 return idRoom t = int(input()) for i in range(t): n, x = input().split() data = input().split() n = ...
For a dynamic list $L$ of integers, perform a sequence of the following operations. $L$ has a special element called END at the end of the list and an element of $L$ is indicated by a cursor. * insert($x$): Insert $x$ before the element indicated by the cursor. After this operation, the cursor points the inserted elem...
3
from collections import deque dll = [[-1,-1, None]] first = 0 cursor = 0 def insert(x): global cursor, first dll.append([dll[cursor][0],cursor,x]) new_cursor = len(dll) - 1 if dll[cursor][0] != -1: dll[dll[cursor][0]][1] = new_cursor dll[cursor][0] = new_cursor if cursor == first: ...
In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either inc...
1
#In the name of ALLAH n, k = map(int, raw_input().split()) a = map(int, raw_input().split()) num = 0 while a[0] != k: for i in range(0, n-1): if a[i] < a[i+1]: a[i] += 1 if a[n-1] != k: a[n-1] += 1 num += 1 print num
There is a square field of size n × n in which two cells are marked. These cells can be in the same row or column. You are to mark two more cells so that they are the corners of a rectangle with sides parallel to the coordinate axes. For example, if n=4 and a rectangular field looks like this (there are asterisks in ...
3
for _ in range(int(input())): n = int(input()) s = [list(input().strip()) for i in range(n)] cand = [] for i in range(n): for j in range(n): if s[i][j] == '*': cand.append([i,j]) if cand[0][0] != cand[1][0] and cand[0][1] != cand[1][1]: s[cand[1][0]][can...
Vasiliy lives at point (a, b) of the coordinate plane. He is hurrying up to work so he wants to get out of his house as soon as possible. New app suggested n available Beru-taxi nearby. The i-th taxi is located at point (xi, yi) and moves with a speed vi. Consider that each of n drivers will move directly to Vasiliy ...
3
x0,y0 = list(map(int,input().split())) n = int(input()) x = [] y = [] v = [] for i in range(n): x1,y1,v1 = list(map(int,input().split())) x.append(x1) y.append(y1) v.append(v1) zipped = zip(x,y,v) t = [] for i in zipped: s = ((i[0]-x0)**2 + (i[1]-y0)**2)**(1/2) t.append(s/i[2]) print(min(t))
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point x(x > 0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order ...
3
n = int(input());print((n+4)//5)
Let's write all the positive integer numbers one after another from 1 without any delimiters (i.e. as a single string). It will be the infinite sequence starting with 123456789101112131415161718192021222324252627282930313233343536... Your task is to print the k-th digit of this sequence. Input The first and only lin...
3
n=int(input()) l=''.join(list(map(str,range(1,n+1)))) print(l[n-1])
Appleman and Toastman play a game. Initially Appleman gives one group of n numbers to the Toastman, then they start to complete the following tasks: * Each time Toastman gets a group of numbers, he sums up all the numbers and adds this sum to the score. Then he gives the group to the Appleman. * Each time Applema...
1
#!/usr/bin/env python n=input() a=map(int, raw_input().split(' ')) a=sorted(a, reverse=True) maxi=sum(a) summ=maxi for i in range(len(a)-1): out=a.pop() summ-=out maxi+=out maxi+=summ print maxi
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
s = input() if "1"*7 in s or '0'*7 in s: print("YES") else: print("NO")
You are given a huge decimal number consisting of n digits. It is guaranteed that this number has no leading zeros. Each digit of this number is either 0 or 1. You may perform several (possibly zero) operations with this number. During each operation you are allowed to change any digit of your number; you may change 0...
3
n,x,y = map(int,input().split()) num = list(input()) l = len(num) - 1 x10 = 10 ** x y10 = 10 ** y count = 0 ans = 1 while ans % x10 != y10: ans = ans*10 ans_str = list('0'*(x-y-1) + str(ans)) smalll = len(ans_str) - 1 while smalll > -1: if ans_str[smalll] != num[l]: count = count + 1 sma...
For a positive integer n let's define a function f: f(n) = - 1 + 2 - 3 + .. + ( - 1)nn Your task is to calculate f(n) for a given integer n. Input The single line contains the positive integer n (1 ≤ n ≤ 1015). Output Print f(n) in a single line. Examples Input 4 Output 2 Input 5 Output -3 Note f(4)...
3
n=int(input()) if n%2 == 0:print(n//2) else:print("-"+f"{n//2+1}")
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm: * if the last digit of the number is non-zero, she decreases the number by one; * if the last digit of the number is ze...
3
num, iters = map(int, input().split()) for i in range(0,iters): if num % 10 == 0: num = num // 10 else : num = num - 1 print(num)
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()) ret = list(S) for x in range(t): nexts = [ret[0]] for y in range(1,n): nexts.append(ret[y]) if ret[y-1] == "B" and ret[y]=="G": nexts[y-1], nexts[y] = 'G', 'B' ret = nexts RET = '' for x in ret: RET += x print(RET)...
One day Misha and Andrew were playing a very simple game. First, each player chooses an integer in the range from 1 to n. Let's assume that Misha chose number m, and Andrew chose number a. Then, by using a random generator they choose a random integer c in the range between 1 and n (any integer from 1 to n is chosen w...
3
from sys import stdin import math n, m = map(int, stdin.readline().split()) k = n - m if n == 1: print (1) elif m <= k: print(m + 1) else: print(m - 1)
Today the kindergarten has a new group of n kids who need to be seated at the dinner table. The chairs at the table are numbered from 1 to 4n. Two kids can't sit on the same chair. It is known that two kids who sit on chairs with numbers a and b (a ≠ b) will indulge if: 1. gcd(a, b) = 1 or, 2. a divides b or b d...
3
from sys import stdin, stdout input = stdin.readline print = lambda x:stdout.write(str(x)+'\n') for _ in range(int(input())): n = int(input()) ans = list(range(4*n, 4*n-(n-1)*2-1, -2)) ans = ' '.join(map(str, ans)) print(ans)
Finally, a basketball court has been opened in SIS, so Demid has decided to hold a basketball exercise session. 2 ⋅ n students have come to Demid's exercise session, and he lined up them into two rows of the same size (there are exactly n people in each row). Students are numbered from 1 to n in each row in order from ...
1
from __future__ import division import sys input = sys.stdin.readline import math from math import sqrt, floor, ceil from collections import Counter from copy import deepcopy as dc # from statistics import median, mean ############ ---- Input Functions ---- ############ def inp(): return(int(input())) def inlt()...
Ehab loves number theory, but for some reason he hates the number x. Given an array a, find the length of its longest subarray such that the sum of its elements isn't divisible by x, or determine that such subarray doesn't exist. An array a is a subarray of an array b if a can be obtained from b by deletion of several...
3
def f(): n = int(input()) A = [int(s) for s in input().split()] a = set(A) print(len(a)) T = int(input()) for t in range(T): f()
A sequence a_1, a_2, ..., a_n is called good if, for each element a_i, there exists an element a_j (i ≠ j) such that a_i+a_j is a power of two (that is, 2^d for some non-negative integer d). For example, the following sequences are good: * [5, 3, 11] (for example, for a_1=5 we can choose a_2=3. Note that their sum ...
3
import math from collections import defaultdict n=int(input()) l=list(map(int,input().split())) l1=[] c=0 d=defaultdict(int) for i in l: d[i]+=1 #print(d) for i in range(32): l1.append(int(math.pow(2,i))) for i in range(n): for j in range(32): check=l1[j]-l[i] if(check>0): if(che...
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()) a=[0]*k for x in map(int,input().split()): a[x%k]+=1 ans,l,r=a[0]//2,1,k-1 while l<r: ans+=min(a[l],a[r]) l+=1 r-=1 if k%2==0: ans+=a[k//2]//2 print(ans*2)
During the quarantine, Sicromoft has more free time to create the new functions in "Celex-2021". The developers made a new function GAZ-GIZ, which infinitely fills an infinite table to the right and down from the upper left corner as follows: <image> The cell with coordinates (x, y) is at the intersection of x-th row ...
3
import math def nck(n, k): return math.factorial(n)//(math.factorial(n-k)*math.factorial(k)) t = int(input()) for _ in range(t): x1, y1, x2, y2 = map(int, input().split()) if x1 == x2 or y1 == y2: print(1) else: x = x2-x1 y = y2-y1 #(y-1+x-2) choose (x-2) + (y-1+x...
Kolya is very absent-minded. Today his math teacher asked him to solve a simple problem with the equation a + 1 = b with positive integers a and b, but Kolya forgot the numbers a and b. He does, however, remember that the first (leftmost) digit of a was d_a, and the first (leftmost) digit of b was d_b. Can you reconst...
3
a, b = map(int, input().split()) # for a in range(1, 10): # for b in range(1, 10): # print(a, b, end=' - ') if a + 1 == b: print(a, 9, ' ', b, 0, sep='') elif a == b: print(a, 0, 1, ' ', b, 0, 2, sep='') elif a == 9 and b == 1: print(99, 100) else: print(-1)
You are given a sequence of length N: A_1, A_2, ..., A_N. For each integer i between 1 and N (inclusive), answer the following question: * Find the maximum value among the N-1 elements other than A_i in the sequence. Constraints * 2 \leq N \leq 200000 * 1 \leq A_i \leq 200000 * All values in input are integers. Inp...
3
N=int(input()) A=[int(input()) for _ in range(N)] B=sorted(A,reverse=True) for a in A: print(B[1] if B[0]==a else B[0])
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point x(x > 0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order ...
1
def step(distance, options, currentSteps): while distance >= options[0]: distance = distance - options[0] currentSteps = currentSteps + 1 if distance == 0: return currentSteps else: return step(distance, options[1:], currentSteps) possible_steps = [5, 4, 3, 2, 1] distance = int(raw_input()) print step(dista...
Polycarp has recently created a new level in this cool new game Berlio Maker 85 and uploaded it online. Now players from all over the world can try his level. All levels in this game have two stats to them: the number of plays and the number of clears. So when a player attempts the level, the number of plays increases...
3
def checklevel(a): currp = 0 currc = 0 for i in a: if currp > i[0]: return 'NO' if currc > i[1]: return 'NO' if i[1]-currc > i[0]-currp: return 'NO' currp = i[0] currc = i[1] return 'YES' cases = int(input()) for _ in range(cas...
There is an empty array. The following N operations will be performed to insert integers into the array. In the i-th operation (1≤i≤N), b_i copies of an integer a_i are inserted into the array. Find the K-th smallest integer in the array after the N operations. For example, the 4-th smallest integer in the array \\{1,2...
3
N,K = map(int,input().split()) A = [list(map(int,input().split())) for _ in range(N)] A.sort() sums=0 for i in range(N): sums+=A[i][1] if sums>=K: print(A[i][0]) break
Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they ...
3
n=int(input()) a=[] for i in range(n): b=input() if (b in a): print ("YES") else: print ("NO") a.append(b)