problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
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...
1
n,m = map(int,raw_input().split()) if n == 1: print 1 elif m <= n/2: print m + 1 elif m > n/2: print m - 1
You are given three positive (i.e. strictly greater than zero) integers x, y and z. Your task is to find positive integers a, b and c such that x = max(a, b), y = max(a, c) and z = max(b, c), or determine that it is impossible to find such a, b and c. You have to answer t independent test cases. Print required a, b a...
3
t=int(input()) for ele in range(t): arr=[int(x) for x in input().split()] m=max(arr) count=0 for ele in arr: if ele==m: count+=1 if count>=2: print("YES") print(min(arr),min(arr),m) else: print("NO")
You all know the Dirichlet principle, the point of which is that if n boxes have no less than n + 1 items, that leads to the existence of a box in which there are at least two items. Having heard of that principle, but having not mastered the technique of logical thinking, 8 year olds Stas and Masha invented a game. T...
1
import sys #sys.stdin = open('game.in', 'r') #sys.stdout = open('game.out', 'w') line = raw_input().split(' ') A, B, N = int(line[0]), int(line[1]), int(line[2]) N -= 1 nl = 0 list = [0]*100 while 1 == 1: curb = nl + 1 le, ri = 1, N while le < ri: cura = (le+ri+1)//2 if (cura**curb <=N): le = cura else: ...
The Fair Nut likes kvass very much. On his birthday parents presented him n kegs of kvass. There are v_i liters of kvass in the i-th keg. Each keg has a lever. You can pour your glass by exactly 1 liter pulling this lever. The Fair Nut likes this drink very much, so he wants to pour his glass by s liters of kvass. But ...
3
n = input().split(" ") data= [int(i) for i in input().split(" ")] s=sum(data) #print(s) if s<int(n[1]): s=-1 else: s-=int(n[1]) s//=int(n[0]) if min(data) <s: s= min(data) print(s)
Write a program which reverses a given string str. Input str (the size of str ≀ 20) is given in a line. Output Print the reversed str in a line. Example Input w32nimda Output admin23w
3
STR = input() a = STR[::-1] print(a)
Β«One dragon. Two dragon. Three dragonΒ», β€” the princess was counting. She had trouble falling asleep, and she got bored of counting lambs when she was nine. However, just counting dragons was boring as well, so she entertained herself at best she could. Tonight she imagined that all dragons were here to steal her, and ...
1
import sys k,l,m,n,d = [int(sys.stdin.readline().strip()) for i in range(5)] x = (d//k + d//l + d//m + d//n) \ - (d//(k*l) + d//(k*m) + d//(k*n) + d//(d*m) + d//(d*n) + d//(m*m)) \ + (d//(k*l*m) + d//(k*l*n) + d//(k*m*n) + d//(d*m*n)) \ - (d//(k*l*m*n)) print sum(1 if i%k==0 or i%l==0 or i%m==0 ...
HQ9+ is a joke programming language which has only four one-character instructions: * "H" prints "Hello, World!", * "Q" prints the source code of the program itself, * "9" prints the lyrics of "99 Bottles of Beer" song, * "+" increments the value stored in the internal accumulator. Instructions "H" and "Q"...
3
s=input() print("YES") if(s.find('H')!=-1 or s.find('Q')!=-1 or s.find('9')!=-1 ) else print("NO")
A triple of numbers is said to be poor when two of those numbers are equal but the other number is different from those two numbers. You will be given three integers A, B, and C. If this triple is poor, print `Yes`; otherwise, print `No`. Constraints * A, B, and C are all integers between 1 and 9 (inclusive). Input...
3
s = set(input().split()) if len(s) == 2: print("Yes") else: print("No")
You are given an array a_1, a_2, ..., a_n, consisting of n positive integers. Initially you are standing at index 1 and have a score equal to a_1. You can perform two kinds of moves: 1. move right β€” go from your current index x to x+1 and add a_{x+1} to your score. This move can only be performed if x<n. 2. mo...
3
# Author: S Mahesh Raju # Username: maheshraju2020 # Date: 29/07/2020 from sys import stdin,stdout from math import gcd, ceil, sqrt from collections import Counter from bisect import bisect_left, bisect_right ii1 = lambda: int(stdin.readline().strip()) is1 = lambda: stdin.readline().strip() iia = lambda: list(map(int,...
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation. The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe...
3
n=input() l=['0','1','2','3','4','5','6','7','8','9'] lst=[] l1=[] if n in l: print(n) else: for i in n: if(i in l): lst.append(i) k=sorted(lst) for i in range(len(k)): l1.append(k[i]) l1.append("+") for i in(l1[0:len(l1)-1]): print(i,end='') ...
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
3
n = int(input()) while(n): s = input() l = len(s) if l>10: print(s[0]+str(l-2)+s[l-1]) else: print(s) n = n-1
After making bad dives into swimming pools, Wilbur wants to build a swimming pool in the shape of a rectangle in his backyard. He has set up coordinate axes, and he wants the sides of the rectangle to be parallel to them. Of course, the area of the rectangle must be positive. Wilbur had all four vertices of the planned...
3
import sys n = int(input()) arr = [] c = 0 if n == 1: print(-1) sys.exit() for i in range(n): x,y = map(int,input().split()) arr.append((x,y)) for i in range(n): for j in range(i+1): if arr[i][0] != arr[j][0] and arr[i][1] != arr[j][1]: print(abs(arr[i][0] - arr[j][0]) * abs(abs(...
Alice guesses the strings that Bob made for her. At first, Bob came up with the secret string a consisting of lowercase English letters. The string a has a length of 2 or more characters. Then, from string a he builds a new string b and offers Alice the string b so that she can guess the string a. Bob builds b from a...
3
t = int(input()) for tp in range(t): s = input() ans = "" ans += s[0] for i in range(1,len(s)-1,2): ans += s[i] ans += s[len(s)-1] print(ans)
Given a connected undirected graph with n vertices and an integer k, you have to either: * either find an independent set that has exactly ⌈k/2βŒ‰ vertices. * or find a simple cycle of length at most k. An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a...
3
import sys from array import array # noqa: F401 from typing import List, Tuple, TypeVar, Generic, Sequence, Union # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') def solve1(n, k, adj): color = [-1, 0] + [-1] * n group = [[1], []] stack = [1] while stack: v...
You are given an array a[0 … n-1] of length n which consists of non-negative integers. Note that array indices start from zero. An array is called good if the parity of each index matches the parity of the element at that index. More formally, an array is good if for all i (0 ≀ i ≀ n - 1) the equality i mod 2 = a[i] m...
3
for t in range(int(input())): n=int(input()) lst=list(map(int,input().split())) even,odd=0,0 for i in range(len(lst)): if(i%2==0 and lst[i]%2!=0): even+=1 elif(i%2!=0 and lst[i]%2==0): odd+=1 if(even==odd): print(even) else: print(-1) ...
"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 = 0 k = 0 list = [] def op(): cont = 0 for i in range(len(list)): if int(list[i]) > 0: if int(list[i]) >= int(list[int(k)-1]): cont += 1 return cont if __name__ == '__main__': n, k = input().split() list = input().split() print(op())
Given are a positive integer N and a string S of length N consisting of lowercase English letters. Determine whether the string is a concatenation of two copies of some string. That is, determine whether there is a string T such that S = T + T. Constraints * 1 \leq N \leq 100 * S consists of lowercase English letter...
3
n = int(input()) s = input() if s == s[:n//2]*2: print("Yes") else: print("No")
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not ...
3
s=input() cnt=0 res=0 for i in range(len(s)): if s[i]==s[i-1]: cnt+=1 else: res=res+((cnt+4)//5) cnt=1 res+=(cnt+4)//5 print(res)
Please note the non-standard memory limit. There are n problems numbered with integers from 1 to n. i-th problem has the complexity c_i = 2^i, tag tag_i and score s_i. After solving the problem i it's allowed to solve problem j if and only if IQ < |c_i - c_j| and tag_i β‰  tag_j. After solving it your IQ changes and be...
3
import sys input = sys.stdin.readline t=int(input()) for tests in range(t): n=int(input()) Tag=list(map(int,input().split())) S=list(map(int,input().split())) DP=[0]*n ANS=0 for i in range(1,n): MAX=0 for j in range(i-1,-1,-1): temp=DP[j] ...
Vanya got n cubes. He decided to build a pyramid from them. Vanya wants to build the pyramid as follows: the top level of the pyramid must consist of 1 cube, the second level must consist of 1 + 2 = 3 cubes, the third level must have 1 + 2 + 3 = 6 cubes, and so on. Thus, the i-th level of the pyramid must have 1 + 2 + ...
1
def cubesPer(n): cubesPerRow = 1 rowNum = 1 while n>=0: n-=cubesPerRow rowNum+=1 cubesPerRow+=rowNum return rowNum-2 print str(cubesPer(int(raw_input())))
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings. Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, seco...
3
#705A n = int(input()) if n%2 == 0: end = "I love it" else: end = "I hate it" i = 1 result = "" while i < n: if i%2==0: result = result + "I love that " else: result += "I hate that " i += 1 print(result + end)
You are given n positive integers a_1, …, a_n, and an integer k β‰₯ 2. Count the number of pairs i, j such that 1 ≀ i < j ≀ n, and there exists an integer x such that a_i β‹… a_j = x^k. Input The first line contains two integers n and k (2 ≀ n ≀ 10^5, 2 ≀ k ≀ 100). The second line contains n integers a_1, …, a_n (1 ≀ a_...
3
import math def sieve_of_eratosthenes(n=100000): prime = [True for i in range(n + 1)] prime[0] = False prime[1] = False p = 2 while (p * p <= n): if (prime[p] == True): for i in range(p * 2, n + 1, p): prime[i] = False p += 1 return prime def prime...
You are looking at the floor plan of the Summer Informatics School's new building. You were tasked with SIS logistics, so you really care about travel time between different locations: it is important to know how long it would take to get from the lecture room to the canteen, or from the gym to the server room. The bu...
3
n_tower,h_floor,a,b,k_way=map(int ,input().split()) for i in range (k_way) : ta,fa,tb,fb=map(int ,input().split ()) if ta==tb : x=abs(fb-fa) print(x) else: if a<=fa<=b : x=abs(fb-fa) y=abs(tb-ta) z=x+y print(z) ...
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 main(): w = int(input()) if w % 2 == 0 and w > 2: print("YES") if w % 2 != 0 : print("NO") if w == 2: print("NO") if __name__ == "__main__": main()
Mahmoud was trying to solve the vertex cover problem on trees. The problem statement is: Given an undirected tree consisting of n nodes, find the minimum number of vertices that cover all the edges. Formally, we need to find a set of vertices such that for each edge (u, v) that belongs to the tree, either u is in the ...
1
n = int(raw_input()) if n <= 5: print "-1" else: print "1 2\n2 3\n2 4\n4 5\n4 6" for i in range(7, n+1): print 4,i for i in range(n-1): print (i+1),(i+2)
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
n = int(input()) a = input().strip() b = input().strip() c = 0 for i in range(n): if a[i] == b[i]: continue a0 = int(a[i]) b0 = int(b[i]) c += min(abs(a0 - b0), 10 - max(a0, b0) + min(a0, b0)) print(c)
A smelt fishing tournament was held at Lake Hibara. The winner is the one who wins the most smelt. Create a program that reads the list of participant numbers and the number of fish caught and outputs the number of winners and the number of fish caught. If there are multiple winners, output the one with the lowest par...
3
n = int(input()) fish = [] for i in range(n) : a, v = map(int, input().split()) fish.append([a, v]) fish.sort(key = lambda val: val[0]) fish.sort(reverse = True, key = lambda val: val[1]) print(*fish[0])
Try guessing the statement from this picture: <image> You are given a non-negative integer d. You have to find two non-negative real numbers a and b such that a + b = d and a β‹… b = d. Input The first line contains t (1 ≀ t ≀ 10^3) β€” the number of test cases. Each test case contains one integer d (0 ≀ d ≀ 10^3). ...
3
from math import sqrt def main(): t = int(input()) for i in range(t): d = int(input()) if d*d - 4*d < 0: print('N') else: diskr = round(sqrt(d*d - 4*d), 9) b = (d + diskr)/2 a = d - b if a < 0 or b < 0: print('N...
Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol). For example, as a result of typing the word "hello", the follo...
3
T = int(input()) for _ in range(T): word = input() fail = input() wordCounts = [] failCounts = [] prevChar = None for c in word: if prevChar == c: wordCounts[-1][1] += 1 else: wordCounts.append([c, 1]) prevChar = c prevChar = None fo...
Recently Adaltik discovered japanese crosswords. Japanese crossword is a picture, represented as a table sized a Γ— b squares, and each square is colored white or black. There are integers to the left of the rows and to the top of the columns, encrypting the corresponding row or column. The number of integers represents...
3
number = int(input()) first = input() gp = 0 second = [] counter = 0 for i in range(number): if first[i] == "B": counter += 1 elif counter > 0: gp += 1 second.append(counter) counter = 0 if counter > 0: second.append(counter) gp += 1 print(gp) print(*second)
Lee was cleaning his house for the party when he found a messy string under the carpets. Now he'd like to make it clean accurately and in a stylish way... The string s he found is a binary string of length n (i. e. string consists only of 0-s and 1-s). In one move he can choose two consecutive characters s_i and s_{i...
3
T=int(input()) for _ in range(T): n=int(input()) s=input() a="" i=0 oc,zc=0,0 while(i<n): if (s[i]=='0'): a=a+s[i] else: break i=i+1 while(i<n-1): if (s[i]=='1' and s[i+1]=='0'): a=a+'0' break i=i+...
At the children's day, the child came to Picks's house, and messed his house up. Picks was angry at him. A lot of important things were lost, in particular the favorite set of Picks. Fortunately, Picks remembers something about his set S: * its elements were distinct integers from 1 to limit; * the value of <ima...
1
st = raw_input() st = st.split(" ") s = int(st[0]) l = int(st[1]) def maxsum(l): c=1 k=1 ans=0 while c>0: c=((l+k)/(k*2))*k k=k*2 ans+=c return ans def lowbit(l): k=1 while k*2<=l: k=k*2 return k cur = 0 k = lowbit(l) lag =0 if maxsum(l)<s: print -...
You can not just take the file and send it. When Polycarp trying to send a file in the social network "Codehorses", he encountered an unexpected problem. If the name of the file contains three or more "x" (lowercase Latin letters "x") in a row, the system considers that the file content does not correspond to the socia...
3
n = int(input()) s = str(input()) count = 0 tot = 0 for i in s: if i == "x": count = count+1 if count > 2: while count > 2: tot = tot+1 count = count-1 if i != "x": count = 0 print(tot)
You are given a range of positive integers from l to r. Find such a pair of integers (x, y) that l ≀ x, y ≀ r, x β‰  y and x divides y. If there are multiple answers, print any of them. You are also asked to answer T independent queries. Input The first line contains a single integer T (1 ≀ T ≀ 1000) β€” the number of...
3
# !/usr/bin/env python3 # encoding: UTF-8 # Modified: <01/Jan/2019 01:54:49 PM> # βœͺ H4WK3yEδΉ‘ # Mohd. Farhan Tahir # Indian Institute Of Information Technology (IIIT),Gwalior # Question Link # # # ///==========Libraries, Constants and Functions=============/// import sys from atexit import register from io import ...
You are given four positive integers n, m, a, b (1 ≀ b ≀ n ≀ 50; 1 ≀ a ≀ m ≀ 50). Find any such rectangular matrix of size n Γ— m that satisfies all of the following conditions: * each row of the matrix contains exactly a ones; * each column of the matrix contains exactly b ones; * all other elements are zeros....
3
def solve(n, m, a, b): if n * a != m * b: print("NO") return arr = [[0 for j in range(0, m)] for i in range(0, n)] start = 0 for i in range(0, n): for j in range(0, a): idx = (start + j) % m arr[i][idx] = 1 start += a print("YES") for i in ...
Petya works as a PR manager for a successful Berland company BerSoft. He needs to prepare a presentation on the company income growth since 2001 (the year of its founding) till now. Petya knows that in 2001 the company income amounted to a1 billion bourles, in 2002 β€” to a2 billion, ..., and in the current (2000 + n)-th...
1
n=input() a=map(int,raw_input().split()) x,y=1,[] for i in xrange(n): if x==a[i]: x+=1 y.append(2001+i) print len(y) print ' '.join(map(str,y))
The Patisserie AtCoder sells cakes with number-shaped candles. There are X, Y and Z kinds of cakes with 1-shaped, 2-shaped and 3-shaped candles, respectively. Each cake has an integer value called deliciousness, as follows: * The deliciousness of the cakes with 1-shaped candles are A_1, A_2, ..., A_X. * The deliciousn...
3
from heapq import nlargest x,y,z,k=map(int,input().split()) A,B,C=[list(map(int,input().split()))for _ in[0]*3] D=nlargest(k,(a+b for a in A for b in B)) E=nlargest(k,(d+c for d in D for c in C)) print('\n'.join(map(str,E)))
Gerald has n younger brothers and their number happens to be even. One day he bought n2 candy bags. One bag has one candy, one bag has two candies, one bag has three candies and so on. In fact, for each integer k from 1 to n2 he has exactly one bag with k candies. Help him give n bags of candies to each brother so th...
3
n = int(input()) vec = [x + 1 for x in range(n * n)] m = n // 2; for i in range(n): for j in range(m): print(vec[i * m + j], end = " ") print(vec[-(i * m + j + 1)], end = " "); print();
You like playing chess tournaments online. In your last tournament you played n games. For the sake of this problem, each chess game is either won or lost (no draws). When you lose a game you get 0 points. When you win you get 1 or 2 points: if you have won also the previous game you get 2 points, otherwise you get 1 ...
3
for _ in " "*int(input()): n,k=map(int,input().split()) s=list(input()) if "W" not in s: print(max((min(k,n)*2)-1,0)) elif k >= s.count("L"): print((n*2)-1) else: cnt,sm,ind=list(),s.count("W"),s.index("W") for i in range(ind+1,n): if s[i] == "W": cnt.append(i-ind-1) ind=...
Vasya owns a cornfield which can be defined with two integers n and d. The cornfield can be represented as rectangle with vertices having Cartesian coordinates (0, d), (d, 0), (n, n - d) and (n - d, n). <image> An example of a cornfield with n = 7 and d = 2. Vasya also knows that there are m grasshoppers near the fie...
3
n,d = [int(x) for x in input().split()] m = int(input()) # (0,d) (d,0) (n,n-d), (n-d,n) # given (x,y) check # x - d <= y <= x + d # -x + d <= y <= -x + (2n-d) for i in range(m): x,y = [int(x) for x in input().split()] if x-d <= y and y <= x+d and -x+d <= y and y <= 2*n-d-x: print("YES") else: print("NO")
Takahashi is now competing in a programming contest, but he received TLE in a problem where the answer is `YES` or `NO`. When he checked the detailed status of the submission, there were N test cases in the problem, and the code received TLE in M of those cases. Then, he rewrote the code to correctly solve each of th...
3
n,m=map(int,input().split()) print((2**m)*((n-m)*100+1900*m))
Write a program which finds the greatest common divisor of two natural numbers a and b Hint You can use the following observation: For integers x and y, if x β‰₯ y, then gcd(x, y) = gcd(y, x%y) Constrants 1 ≀ a, b ≀ 109 Input a and b are given in a line sparated by a single space. Output Output the greatest comm...
3
m, n = map(int, input().split()) x = max(m, n) y = min(m, n) while y > 0: temp = y y = x % y x = temp print(x)
A breakthrough among computer games, "Civilization XIII", is striking in its scale and elaborate details. Let's take a closer look at one of them. The playing area in the game is split into congruent cells that are regular hexagons. The side of each cell is equal to 1. Each unit occupies exactly one cell of the playin...
3
from math import sqrt # t = int(input()) t = 1 rList = [int(i) for i in input().split(' ')] for i in range(t): r = rList[i] r2 = r * r sums = 0 b = 1 sig = True while(b <= r): a = b - 0.5 n1 = sqrt((r2 - a * a) * 4 / 3) n2 = sqrt((r2 - b * b) * 4 / 3) if sig: ...
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(map(int, input())) k = 0 l = len(num) for i in range(l - 1, l - 1 - x, -1): if l - i - 1 != y: if num[-(l - i)] == 1: k += 1 else: if num[-(l - i)] == 0: k += 1 print(k)
Katie, Kuro and Shiro are best friends. They have known each other since kindergarten. That's why they often share everything with each other and work together on some very hard problems. Today is Shiro's birthday. She really loves pizza so she wants to invite her friends to the pizza restaurant near her house to cele...
3
n=int(input())+1 if n==1: print(0) elif n%2==0: print(n//2) else: print(n) ##//////////////// ////// /////// // /////// // // // ##//// // /// /// /// /// // /// /// //// // ##//// //// /// /// /// /// // ...
Arya has n opponents in the school. Each day he will fight with all opponents who are present this day. His opponents have some fighting plan that guarantees they will win, but implementing this plan requires presence of them all. That means if one day at least one of Arya's opponents is absent at the school, then Arya...
3
nd = list(map(int, input().split())) school = [] maximum = 0 temp = 0 accept = 1 for k in range(nd[1]): school.append(list(map(int, input()))) accept = 1 for i in range(nd[0]): if school[k][i] == 0: temp += 1 accept = 0 break if accept == 1: accept = 0 maximum = max(maximum, temp) temp = 0 maximum ...
You may know that Euclid was a mathematician. Well, as it turns out, Morpheus knew it too. So when he wanted to play a mean trick on Euclid, he sent him an appropriate nightmare. In his bad dream Euclid has a set S of n m-dimensional vectors over the Z_2 field and can perform vector addition on them. In other words h...
3
import sys input = sys.stdin.buffer.readline def _find(s, u): p = [] while s[u] != u: p.append(u) u = s[u] for v in p: s[v] = u return u def _union(s, u, v): su, sv = _find(s, u), _find(s, v) if su != sv: s[su] = sv return su != sv n, m = map(int, input().split()) s, solo ...
New Year is coming! Vasya has prepared a New Year's verse and wants to recite it in front of Santa Claus. Vasya's verse contains n parts. It takes a_i seconds to recite the i-th part. Vasya can't change the order of parts in the verse: firstly he recites the part which takes a_1 seconds, secondly β€” the part which take...
3
t = int(input()) while (t): t = t-1 n , s = map(int , input().split()) arr = list(map(int , input().split())) sum = 0 ans =0 max = 0 for i in range (0, len(arr)) : sum = sum+ arr[i] if (max < arr[i]) : max = arr[i] if (sum <=s and i == len(arr)-1) : ...
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy...
3
n=int(input()) suma = 0 sumb=0 sumc=0 for i in range (n): a,b,c = map (int,input().strip().split(" ")) suma +=a sumb +=b sumc+=c if suma==0 and sumc==0 and sumb==0 : print("YES") else: print("NO")
There is a square box 6 Γ— 6 in size. It contains 36 chips 1 Γ— 1 in size. Those chips contain 36 different characters β€” "0"-"9" and "A"-"Z". There is exactly one chip with each character. You are allowed to make the following operations: you may choose one of 6 rows or one of 6 columns and cyclically shift the chips th...
3
ls="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" s,cnt,a1,a2=[],0,[],[] for i in range(6): s.append(list(input())) def add(c,i): global cnt cnt+=1 a1.append(c) a2.append(i) def right(i): add('R',i+1) tmp=s[i][5] for j in range(5,0,-1): s[i][j]=s[i][j-1] s[i][0]=tmp def left(i): add('L',i+1) tmp=s[i][0] for j ...
Write a program which reads an integer n and identifies the number of combinations of a, b, c and d (0 ≀ a, b, c, d ≀ 9) which meet the following equality: a + b + c + d = n For example, for n = 35, we have 4 different combinations of (a, b, c, d): (8, 9, 9, 9), (9, 8, 9, 9), (9, 9, 8, 9), and (9, 9, 9, 8). Input ...
3
while True: try: n = int(input()) c = 0 for i in range(10): for j in range(10): for k in range(10): for l in range(10): if i+j+k+l == n : c+=1 print(c) except: break
Nastya just made a huge mistake and dropped a whole package of rice on the floor. Mom will come soon. If she sees this, then Nastya will be punished. In total, Nastya dropped n grains. Nastya read that each grain weighs some integer number of grams from a - b to a + b, inclusive (numbers a and b are known), and the wh...
3
t = int(input()) for _ in range(t): n, a, b, c, d = map(int,input().split()) if (n*(a-b) <= c+d) and (n*(a+b) >= c-d): print("Yes") else: print("No")
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem. Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of o...
1
#!/usr/bin/env python def main(): # n = int(raw_input()) # map(int, raw_input().split()) s1 = raw_input() s2 = raw_input() if s1 == s2: return -1 return max(len(s1), len(s2)) print main()
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...
1
a=raw_input() b=raw_input() a=a.lower() b=b.lower() if a<b: print -1 elif a==b: print 0 else: print 1
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....
3
x=0 n=int(input()) for i in range(n): i=input() if i=='++X' or i=='X++': x+=1 else: x-=1 print(x)
Pashmak has fallen in love with an attractive girl called Parmida since one year ago... Today, Pashmak set up a meeting with his partner in a romantic garden. Unfortunately, Pashmak has forgotten where the garden is. But he remembers that the garden looks like a square with sides parallel to the coordinate axes. He al...
3
line=input().split() for i in range(len(line)): line[i]=int(line[i]) x1=line[0] y1=line[1] x2=line[2] y2=line[3] if x1==x2: x3=x1+y1-y2 x4=x3 y3=y1 y4=y2 print(x3,y3,x4,y4) elif y1==y2: y3=y1+x2-x1 y4=y3 x3=x1 x4=x2 print(x3,y3,x4,y4) elif (x1-x2)==(y1-y2): x3=x1 x4=x...
Two neighboring kingdoms decided to build a wall between them with some gates to enable the citizens to go from one kingdom to another. Each time a citizen passes through a gate, he has to pay one silver coin. The world can be represented by the first quadrant of a plane and the wall is built along the identity line (...
3
n = int(input()) s = str(input()) x = 0 y = 0 previous = 0 ans = 0 for i in range(n): if s[i:i+1] == 'U': y += 1 elif s[i:i+1] == 'R': x += 1 if i > 0: if previous == 1: if y > x and s[i-1:i] == 'U': ans += 1 if y < x and s[i-1:i] == 'R': ...
You are given three positive integers n, a and b. You have to construct a string s of length n consisting of lowercase Latin letters such that each substring of length a has exactly b distinct letters. It is guaranteed that the answer exists. You have to answer t independent test cases. Recall that the substring s[l ...
3
import math import sys t = int(sys.stdin.readline()) for _ in range(t): n, a, b = map(int, sys.stdin.readline().split()) s = "a" for i in range(1, b): s += chr(ord('a') + i) n_times = math.ceil(n / b) s = s * n_times s = s[:n] print(s)
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array. According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the requ...
3
n=int(input()) lst=list(map(int,input().split())) d={} for i in range(1,n+1): d[lst[i-1]]=i q=input() que=list(map(int,input().split())) l=0 r=0 for i in que: a=d[i] b=n-d[i]+1 l+=a r+=b print(l,r)
Petya and Vasya are competing with each other in a new interesting game as they always do. At the beginning of the game Petya has to come up with an array of N positive integers. Sum of all elements in his array should be equal to S. Then Petya has to select an integer K such that 0 ≀ K ≀ S. In order to win, Vasya ha...
3
n,s=map(int,input().split()) a=s//n if a<=1: print("NO") else: b=s%n c=[a]*n c[-1]=c[-1]+b m=min(c) print("YES") print(*c,sep=" ") print(m-1)
wHAT DO WE NEED cAPS LOCK FOR? Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage. Let's consider that a word has been typed with the Caps lock key accidentall...
1
origin = raw_input() n = len(origin) convert="" invert = True for i in xrange(n): if i > 0 and origin[i].islower(): invert = False break if origin[i].isupper(): convert += origin[i].lower() else: convert += origin[i].upper() print convert if invert else origin
HQ9+ is a joke programming language which has only four one-character instructions: * "H" prints "Hello, World!", * "Q" prints the source code of the program itself, * "9" prints the lyrics of "99 Bottles of Beer" song, * "+" increments the value stored in the internal accumulator. Instructions "H" and "Q"...
1
for c in raw_input(): if c in 'HQ9': print "YES" exit() print "NO"
The School β„–0 of the capital of Berland has n children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value ti: * ti = 1, if the i-th child is good at programming, *...
3
input() a = [int(x) for x in input().split()] x = a.count(1) y = a.count(2) z = a.count(3) n = min(x,y,z) l = len(a) print(n) m = -1 p = -1 o = -1 for i in range(n): while 1: m += 1 if a[m] == 1: print(m+1, end = ' ') break while 1: p += 1 if a[p] == 2: ...
Ilya is a very clever lion, he lives in an unusual city ZooVille. In this city all the animals have their rights and obligations. Moreover, they even have their own bank accounts. The state of a bank account is an integer. The state of a bank account can be a negative number. This means that the owner of the account ow...
3
a=input() b=a k=len(a) a=int(a) if(a>=0): print(a) else: c=int(b[0:k-1]) d=int(b[:k-2]+b[k-1:]) if(c>d): print(c) else: print(d)
Monocarp and Polycarp are learning new programming techniques. Now they decided to try pair programming. It's known that they have worked together on the same file for n + m minutes. Every minute exactly one of them made one change to the file. Before they started, there were already k lines written in the file. Ever...
3
for _ in range(int(input())): input() k, m, n = map(int, input().split()) l = list(map(int, input().split())) r = list(map(int, input().split())) i = j = 0 ans = [] flag = True while i<len(l) and j<len(r): if l[i] == 0: ans.append(0) k+=1 i+=1 ...
You are given an array a of n integers and an integer s. It is guaranteed that n is odd. In one operation you can either increase or decrease any single element by one. Calculate the minimum number of operations required to make the median of the array being equal to s. The median of the array with odd length is the ...
1
#coding:utf-8 one = raw_input().split() n = int(one[0]) s = int(one[1]) idx = n/2 data = [int(i) for i in raw_input().split()] newdata = sorted(data) # print(newdata) cnt = 0 if newdata[idx] == s: print(0) exit() elif newdata[idx] < s: for i in range(idx,n): if newdata[i] < s: cnt += s - newdata[i] else: for i...
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word. Note, that during capitalization all the letters except the first one remains unchanged. Input A single line contains a non-empty word. This word consists of lowercase and uppercase English letters....
3
ent = input() sol = ent[0].upper() + ent[1:] print(sol)
User ainta has a stack of n red and blue balls. He can apply a certain operation which changes the colors of the balls inside the stack. * While the top ball inside the stack is red, pop the ball from the top of the stack. * Then replace the blue ball on the top with a red ball. * And finally push some blue ba...
3
n = input() print(int(input().replace('B', '1').replace('R', '0')[::-1] , 2))
You are given three integers x, y and n. Your task is to find the maximum integer k such that 0 ≀ k ≀ n that k mod x = y, where mod is modulo operation. Many programming languages use percent operator % to implement it. In other words, with given x, y and n you need to find the maximum possible integer from 0 to n tha...
3
t = int(input()) for test in range(t): x,y,n = map(int,input().split()) rem = n%x if rem==y: print(n) elif rem>y: n -= (rem-y) print(n) else: n -= rem n -= (x-y) print(n)
Arpa is researching the Mexican wave. There are n spectators in the stadium, labeled from 1 to n. They start the Mexican wave at time 0. * At time 1, the first spectator stands. * At time 2, the second spectator stands. * ... * At time k, the k-th spectator stands. * At time k + 1, the (k + 1)-th specta...
1
n,k,t = raw_input().split() n = int(n) k = int(k) t = int(t) if t <= k: print t elif t <= n: print k else: t = t - n print k - t
Two integer sequences existed initially β€” one of them was strictly increasing, and the other one β€” strictly decreasing. Strictly increasing sequence is a sequence of integers [x_1 < x_2 < ... < x_k]. And strictly decreasing sequence is a sequence of integers [y_1 > y_2 > ... > y_l]. Note that the empty sequence and th...
3
import math from collections import defaultdict, Counter, deque def primeFactor(n): if n % 2 == 0: return 2 i = 3 while (i ** 2) <= n: if n % i == 0: return i i += 1 return n def main(): n = int(input()) arr = list(map(int, input().split())) inc = [] dec = [] count = defaultdict(int) for i in r...
You have two integers l and r. Find an integer x which satisfies the conditions below: * l ≀ x ≀ r. * All digits of x are different. If there are multiple answers, print any of them. Input The first line contains two integers l and r (1 ≀ l ≀ r ≀ 10^{5}). Output If an answer exists, print any of them. Oth...
3
l,r=map(int, input().split()) flag=1 for i in range(l,r+1): s=set() st=str(i) for j in st: s.add(j) if len(s) == len(st): print(i) flag=0 break if flag == 1: print(-1)
Polycarp likes to play with numbers. He takes some integer number x, writes it down on the board, and then performs with it n - 1 operations of the two kinds: * divide the number x by 3 (x must be divisible by 3); * multiply the number x by 2. After each operation, Polycarp writes down the result on the boar...
3
import sys import math import collections import bisect def get_ints(): return map(int, sys.stdin.readline().strip().split()) def get_list(): return list(map(int, sys.stdin.readline().strip().split())) def get_string(): return sys.stdin.readline().strip() for t in range(1): n=int(input()) arr=get_list() for...
wHAT DO WE NEED cAPS LOCK FOR? Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage. Let's consider that a word has been typed with the Caps lock key accidentall...
1
from sys import stdin,stdout,setrecursionlimit,maxint,exit #setrecursionlimit(2*10**5) def listInput(): return map(long,stdin.readline().split()) def printBS(li): for i in xrange(len(li)-1): stdout.write("%d "%li[i]) stdout.write("%d\n"%li[-1]) s=stdin.readline().strip() iscap=False for i in xrange(len(s)): if 97...
The Berland Armed Forces System consists of n ranks that are numbered using natural numbers from 1 to n, where 1 is the lowest rank and n is the highest rank. One needs exactly di years to rise from rank i to rank i + 1. Reaching a certain rank i having not reached all the previous i - 1 ranks is impossible. Vasya ha...
3
# -*- coding: utf-8 -*- """ Created on Fri Jun 28 06:47:42 2019 @author: avina """ n = int(input()) d = list(map(int, input().split())) a,b = map(int, input().split()) c = sum(d[a-1:b-1]) print(c)
Vadim loves decorating the Christmas tree, so he got a beautiful garland as a present. It consists of n light bulbs in a single row. Each bulb has a number from 1 to n (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland....
3
'''input 8 1 2 6 13 14 3620 10000 1000000000000000000 ''' # A coding delight from sys import stdin, stdout import gc gc.disable() import array def get_count(): aux = set(arr) odd, even = 0, 0 for i in range(1, n + 1): if i not in aux: if i % 2: odd += 1 else: even += 1 return odd, even def pol(n...
Shubham has an array a of size n, and wants to select exactly x elements from it, such that their sum is odd. These elements do not have to be consecutive. The elements of the array are not guaranteed to be distinct. Tell him whether he can do so. Input The first line of the input contains a single integer t (1≀ t ≀...
3
T = int(input()) for _ in range (T): n,x = map(int, input().split()) A = list(map(int, input().split())) odd,even = 0,0 for a in A: if a%2 == 0: even += 1 else: odd +=1 if odd == 0: print ("no") continue if x%2 == 1: ...
When Valera has got some free time, he goes to the library to read some books. Today he's got t free minutes to read. That's why Valera took n books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to n. Valera needs ai minutes to read the ...
3
def solve(arr,n,time): sum1,count = 0,0 j = -1 for i in range(n): if sum1+arr[i]<=time: sum1 += arr[i] else: sum1 += arr[i] while(sum1>time): j += 1 sum1 -= arr[j] count = max(count,i-j) return count n,t = map(...
Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones. Once he thought about a string of length n consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and ...
3
input() a = list(input()) print(abs(a.count('0') - a.count('1')))
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
3
t=input() while(True): try: a=input() n=len(a) x=0 if n<=10: print(a) else: for i in range(0,len(a)-2): x=i+1 print(a[0],end="") print(x,end="") print(a[n-1]) except EOFError: ...
In the city of Ultima Thule job applicants are often offered an IQ test. The test is as follows: the person gets a piece of squared paper with a 4 Γ— 4 square painted on it. Some of the square's cells are painted black and others are painted white. Your task is to repaint at most one cell the other color so that the p...
3
grid = [] for _ in range(4): s = list(input()) grid.append(s) f = False for i in range(3): for j in range(3): cb, cw = 0, 0 for k in range(i, i+2): for l in range(j, j+2): if(grid[k][l] == "#"): cb += 1 else: cw += 1 if(cb >= 3 or cw >= 3): f = True if(f): print("YES") else: print("...
Little girl Tanya climbs the stairs inside a multi-storey building. Every time Tanya climbs a stairway, she starts counting steps from 1 to the number of steps in this stairway. She speaks every number aloud. For example, if she climbs two stairways, the first of which contains 3 steps, and the second contains 4 steps,...
1
""" import atexit, io, sys buffer = io.BytesIO() sys.stdout = buffer @atexit.register def write(): sys.__stdout__.write(buffer.getvalue()) """ n = input() L = [int(x) for x in raw_input().split()] L.append(1) V = [] for i in range(len(L)): if L[i] == 1: V.append(i) print len(V)-1 for i in range(len(V)-1...
There are N cities on a 2D plane. The coordinate of the i-th city is (x_i, y_i). Here (x_1, x_2, \dots, x_N) and (y_1, y_2, \dots, y_N) are both permuations of (1, 2, \dots, N). For each k = 1,2,\dots,N, find the answer to the following question: Rng is in City k. Rng can perform the following move arbitrarily many t...
3
import sys input = sys.stdin.readline from operator import itemgetter N=int(input()) T=[list(map(int,input().split()))+[i] for i in range(N)] YtoN=[-1]*(N+1) for x,y,n in T: YtoN[y]=n T.sort(key=itemgetter(0)) MAX=N MAXUSE=0 MIN=10**6 left=0 ANS=[-1]*N for i in range(N): x,y,n=T[i] if y==MAX: ...
Eleven wants to choose a new name for herself. As a bunch of geeks, her friends suggested an algorithm to choose a name for her. Eleven wants her name to have exactly n characters. <image> Her friend suggested that her name should only consist of uppercase and lowercase letters 'O'. More precisely, they suggested th...
1
arr = [0,1] for x in xrange(1,20): arr.append(arr[len(arr)-1]+arr[len(arr)-2]) n = input() s = "" for x in xrange(1,n+1): if x in arr: s+='O' else: s+='o' print s
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm: * if the last digit of the number is non-zero, she decreases the number by one; * if the last digit of the number is ze...
3
n, k = map(int, input().split()) count = 0 for item in range(k): if str(n)[-1] != '0': n -= 1 else: n //= 10 count += 1 if count == k: print(n)
Did you ever hear about 'Dragon Food' ? Its used to refer to the chocolates bought for your loved ones :). Po offers dragon food to master Shifu, who is a famous cook in the valley of food. In return, Shifu hands over the dragon scroll to Po, which is said to hold the ingredients of the secret recipe. To open the drago...
1
import sys t = int(raw_input()) while t: (n,a,b) = map(int, raw_input().split()) zeroes = abs(n-bin(a).count('1')-bin(b).count('1')) print int('1'*(n-zeroes)+'0'*zeroes,2) t-=1
Pashmak has fallen in love with an attractive girl called Parmida since one year ago... Today, Pashmak set up a meeting with his partner in a romantic garden. Unfortunately, Pashmak has forgotten where the garden is. But he remembers that the garden looks like a square with sides parallel to the coordinate axes. He al...
3
a,b,c,d=map(int,input().split()) if a!=c and b!=d and abs(a-c)!=abs(b-d): print(-1) else: if a==c: t=abs(b-d) print(a+t,b,c+t,d) elif b==d: t=abs(a-c) print(a,b-t,c,d-t) else: if a<c and b<d: print(c,b,a,d) elif c<a and d<b: print(a...
In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup...
1
''' ||Sri:|| __| ______________|_________________________ | | ___| | | ___| | | |___ /\ /\ | |___ | | |___| | | |___| / \/ \ | ___| | | |_/ |___| |___ I am a...
Alice's hair is growing by leaps and bounds. Maybe the cause of it is the excess of vitamins, or maybe it is some black magic... To prevent this, Alice decided to go to the hairdresser. She wants for her hair length to be at most l centimeters after haircut, where l is her favorite number. Suppose, that the Alice's he...
3
n,m,l=map(int,input().split()) a=list(map(int,input().split())) c=0 if a[0]>l: c+=1 a[0]=0 for i in range(1,n): if a[i]>l: a[i]=0 if a[i-1]!=0: c+=1 for i in range(m): s=input() if s[0]=='0': print(c) else: _,x,y=map(int,s.split()) if a[x-1]<=l...
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word. Note, that during capitalization all the letters except the first one remains unchanged. Input A single line contains a non-empty word. This word consists of lowercase and uppercase English letters....
3
s=input() a=s[0].upper() print(a,end="") for i in range(1,len(s)): print(s[i],end="")
The only difference between easy and hard versions are constraints on n and k. You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most k most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals 0...
3
n, k = map(int, input().split(' ')) id_ = list(map(int, input().split(' '))) answer = [] for id_i in id_: if len(answer) < k and id_i not in answer: answer.insert(0, id_i) elif id_i not in answer: answer.pop(len(answer) - 1) answer.insert(0, id_i) answer = [str(i) for i in answer] print(...
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...
1
n = input() lst = [] for i in xrange(n): l,r = map(int,raw_input().split(' ')) lst.append((l,r)) max_r = max([x[1] for x in lst]) l2 = sorted(lst) i = 0 counter = 0 while(l2[i][0]==l2[0][0]): if (l2[i][1] == max_r): counter = 1 break i = i + 1 if (counter == 1): print (lst.index((l2[0][0],max_r)) + 1) else : pr...
Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options: 1. on this day the gym is closed and...
3
#!/usr/bin/python3 "B. Students and Shoelaces" "Codeforces Beta Round #94 (Div. 2 Only)" # n,m=map(int,input().split()) # d={} # for i in range(m): # z,x=map(int,input().split()) # d.setdefault(z,[]) # d.setdefault(x,[]) # d[z].append(x) # d[x].append(z) # k=0 # while True: # f=0 # t=[F...
Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus. She has n friends who are also grannies (Maria is not included in this number). The i-th granny is ready to attend the ceremony, provided that at the time of her appearance in t...
3
I=lambda:list(map(int,input().split())) t=I()[0] while(t): t-=1 n=I()[0] arr=I() arr.sort() c=1 ans=0 for i in range(n): if(c>=arr[i]): ans=i+1 c+=1 print(ans+1)
You are given an array a[0 … n-1] of length n which consists of non-negative integers. Note that array indices start from zero. An array is called good if the parity of each index matches the parity of the element at that index. More formally, an array is good if for all i (0 ≀ i ≀ n - 1) the equality i mod 2 = a[i] m...
3
test_case = int(input()) while test_case: n = int(input()) a = list(map(int, input().split())) odd = [] even = [] for i in range(n): if i % 2 != a[i] % 2: odd.append(i) if a[i] % 2 else even.append(i) print(-1 if (len(odd) != len(even)) else len(odd)) test_case -= 1
Vasya has n pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every m-th day (at days with numbers m, 2m, 3m, ...) mom buys a pair of socks to Vasya. She does it late in the eve...
3
[n, m] = list(map(int, input().split())) day = n + 1 cnt = n // m while(cnt): if(day % m): cnt -= 1 day += 1 print(day - 1, end = '')
You are playing a variation of game 2048. Initially you have a multiset s of n integers. Every integer in this multiset is a power of two. You may perform any number (possibly, zero) operations with this multiset. During each operation you choose two equal integers from s, remove them from s and insert the number eq...
3
'''input 6 4 1024 512 64 512 1 2048 3 64 512 2 2 4096 4 7 2048 2 2048 2048 2048 2048 2048 2 2048 4096 ''' from collections import defaultdict as dd from collections import Counter as ccd from itertools import permutations as pp from itertools import combinations as cc from random import randint as rd from bisect impor...
Sherlock Holmes and Dr. Watson played some game on a checkered board n Γ— n in size. During the game they put numbers on the board's squares by some tricky rules we don't know. However, the game is now over and each square of the board contains exactly one number. To understand who has won, they need to count the number...
3
n = int(input()) board = [] for i in range(n): board.append(list(map(int,input().split()))) win = 0 row_len = len(board[0]) for i in range(len(board)): for j in range(row_len): element = board[i][j] row_sum = 0 col_sum = 0 for x in range(row_len): row_sum += board[i]...
Vasya and Petya are playing a simple game. Vasya thought of number x between 1 and n, and Petya tries to guess the number. Petya can ask questions like: "Is the unknown number divisible by number y?". The game is played by the following rules: first Petya asks all the questions that interest him (also, he can ask no ...
3
n = int(input()) def is_prime(n): p = 2 while p * p <= n: if n % p == 0: return False p += 1 return True asks = [] prime = 2 while prime <= n: k = 1 while prime ** k <= n: asks.append(prime ** k) k += 1 prime += 1 while not is_prime(prime): ...
Recently a new building with a new layout was constructed in Monocarp's hometown. According to this new layout, the building consists of three types of apartments: three-room, five-room, and seven-room apartments. It's also known that each room of each apartment has exactly one window. In other words, a three-room apar...
3
import math import sys import collections import bisect #sys.setrecursionlimit(1000000000) input = sys.stdin.readline flush = sys.stdout.flush readint =lambda: int(input()) readintm =lambda: map(int,input().strip().split()) readintl =lambda: list(map(int,input().strip().split())) readfloatm =lambda: map(...