problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
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
for _ in range(int(input())): a,b,c=map(int, input().split()) x=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"] h=[]*c for i in range(c): h.append(x[i]) x=[]*a p=a//c p1=a%c x=h*p for e1 in range(p1): x.append...
N persons are standing in a row. The height of the i-th person from the front is A_i. We want to have each person stand on a stool of some heights - at least zero - so that the following condition is satisfied for every person: Condition: Nobody in front of the person is taller than the person. Here, the height of a ...
3
n = int(input()) a = list(map(int,input().split())) res = 0 mx = 0 for i in range(n): res+=max(0,mx-a[i]) mx = max(mx,a[i]) print(res)
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like. Now let's imagine a typical morning in your family. You haven't w...
3
n = int(input()) lst = list(map(int, input().split())) lst.sort() lst.reverse() count = 0 money = 0 for i in lst: if money <= sum(lst) - money: money += i count += 1 else: break print(count)
You are given a sequence a_1, a_2, ..., a_n consisting of n non-zero integers (i.e. a_i β‰  0). You have to calculate two following values: 1. the number of pairs of indices (l, r) (l ≀ r) such that a_l β‹… a_{l + 1} ... a_{r - 1} β‹… a_r is negative; 2. the number of pairs of indices (l, r) (l ≀ r) such that a_l β‹… a...
3
import sys input = sys.stdin.readline def One(type): return (type(input())) def List(type): return list(map(type,input().split())) def Str(): return (list(input())) def Many(type): return map(type,input().split()) def main(): n = One(int) m = List(int) ansp = ansn = 0 neg = [] for i,nxt in enumerate(m): ...
A triangular number is the number of dots in an equilateral triangle uniformly filled with dots. For example, three dots can be arranged in a triangle; thus three is a triangular number. The n-th triangular number is the number of dots in a triangle with n dots on a side. <image>. You can learn more about these numbers...
1
n = int(raw_input()) from math import sqrt def is_integer(c): return True if ((-1 + sqrt(1 - (4*1*c)))/2.0)%1.0 == 0.0 or ((-1 - sqrt(1 - (4*1*c)))/2.0)%1.0 == 0.0 else False if is_integer(-2*n): print "YES" else: print "NO"
In this problem we consider a very simplified model of Barcelona city. Barcelona can be represented as a plane with streets of kind x = c and y = c for every integer c (that is, the rectangular grid). However, there is a detail which makes Barcelona different from Manhattan. There is an avenue called Avinguda Diagonal...
3
import math a,b,c = [float(i) for i in input().split()] xy = [float(i) for i in input().split()] A =[xy[0],xy[1]] B =[xy[2],xy[3]] distances = [] def get_distance(K, M): return math.sqrt((K[0]-M[0])*(K[0]-M[0]) + (K[1]- M[1])*(K[1] - M[1])) def get_point_h(K): x = (-b*K[1]-c) / a point = (x, K[1]) d...
You have n students under your control and you have to compose exactly two teams consisting of some subset of your students. Each student had his own skill, the i-th student skill is denoted by an integer a_i (different students can have the same skills). So, about the teams. Firstly, these two teams should have the s...
3
from bisect import * from collections import * from itertools import * import functools import sys import math from decimal import * from copy import * from heapq import * from fractions import * getcontext().prec = 30 MAX = sys.maxsize MAXN = 1000010 MOD = 10**9+7 spf = [i for i in range(MAXN)] spf[0]=spf[1] = -1 def ...
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
def strcmp(s1,s2): for x in range(0,len(s1)): if(s1.lower()[x]>s2.lower()[x]): return(1) elif(s1.lower()[x]<s2.lower()[x]): return(-1) return(0) s1=input() s2=input() print(strcmp(s1,s2))
Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed d. Note that the order of the points inside the group of three chosen point...
1
#################################################### # -*- coding: utf-8 -*- import sys w = sys.stdout.write read = sys.stdin.readline reads = sys.stdin.read def r(f=None): if f: return map(f, read().split()) else: return read().split() def rs(t,f=None): result = [] result_append = re...
Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers a, b, c on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting e...
3
a=int(input()) b=int(input()) c=int(input()) t=a*b*c r=a*(b+c) e=a+b+c u=(a+b)*c print(max(t,r,e,u))
Harry Potter and He-Who-Must-Not-Be-Named engaged in a fight to the death once again. This time they are located at opposite ends of the corridor of length l. Two opponents simultaneously charge a deadly spell in the enemy. We know that the impulse of Harry's magic spell flies at a speed of p meters per second, and the...
1
c = int(raw_input()) h = int(raw_input()) v = int(raw_input()) print h * c*1.0/(h+v)
You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4β‹… LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D. You believe that only some part of the ...
3
n,m=map(int,input().split()) a=input() b=input() dp=[[0 for i in range(m+1)] for i in range(n+1) ] ans=0 for i in range(1,n+1): for j in range(1,m+1): if a[i-1]==b[j-1]: dp[i][j]=max(dp[i][j],dp[i-1][j-1]+2) ans=max(ans,dp[i][j]) else: dp[i][j]=max(dp[i-1][j], dp[...
Nikolay has a lemons, b apples and c pears. He decided to cook a compote. According to the recipe the fruits should be in the ratio 1: 2: 4. It means that for each lemon in the compote should be exactly 2 apples and exactly 4 pears. You can't crumble up, break up or cut these fruits into pieces. These fruits β€” lemons, ...
3
while True: try: a = int(input()) // 1 b = int(input()) // 2 c = int(input()) // 4 fruit = [a, b, c] m = min(fruit) print(m*7) except EOFError: break
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [...
3
n = int(input()) while(n>0): n-=1 t=int(input()) arr = list(map(int,input().split())) stor =[] l=0 while(l<t): m=0;val=0 if(arr[l]>0): val = arr[l] k=l+1 l=l+1 while(k<t and arr[k]>0): if(arr[k]>val): ...
You are a lover of bacteria. You want to raise some bacteria in a box. Initially, the box is empty. Each morning, you can put any number of bacteria into the box. And each night, every bacterium in the box will split into two bacteria. You hope to see exactly x bacteria in the box at some moment. What is the minimu...
3
k=int(input()) n=bin(k) s=0 for i in range(2,len(n)): s=s+int(n[i]) print(s)
You are given a regular polygon with n vertices labeled from 1 to n in counter-clockwise order. The triangulation of a given polygon is a set of triangles such that each vertex of each triangle is a vertex of the initial polygon, there is no pair of triangles such that their intersection has non-zero area, and the tota...
1
n = int(input()) ans = 100000000000000000000000 for i in range(n): val = i+1 arr = [] x = i for j in range(n-2): x=(x+1)%n #print(i,x) y = (x+1)%n arr.append((i+1)*(x+1)*(y+1)) #print(arr) s = sum(arr) ans = min(ans,s) print(ans)
A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay iΒ·k dollars for the i-th banana). He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas? Input The first lin...
3
a=list(map(int,input().strip().split())) k=a[0] n=a[1] w=a[2] b= int(w*(w+1)*0.5*k)-n if b>0: print(b) else : print(0)
There are n students standing in a circle in some order. The index of the i-th student is p_i. It is guaranteed that all indices of students are distinct integers from 1 to n (i. e. they form a permutation). Students want to start a round dance. A clockwise round dance can be started if the student 2 comes right after...
3
import copy #i don't know how it worked. i have copied it def func(a): b=copy.deepcopy(a) b.sort() return a==b or a==b[::-1] t=int(input()) while t: n=int(input()) a=list(map(int,input().split())) i=a[0] j=n-1-a[0] c=[(x-i)%n+1 for x in a] d=[(x+j)%n+1 for x in a] if func(c) or func(d): print("YES") else...
Let's say string s has period k if s_i = s_{i + k} for all i from 1 to |s| - k (|s| means length of string s) and k is the minimum positive integer with this property. Some examples of a period: for s="0101" the period is k=2, for s="0000" the period is k=1, for s="010" the period is k=2, for s="0011" the period is k=...
3
for _ in range(int(input())): s=input() print( '01'*len(s) if '0' in s and '1' in s else s)
Having written another programming contest, three Rabbits decided to grab some lunch. The coach gave the team exactly k time units for the lunch break. The Rabbits have a list of n restaurants to lunch in: the i-th restaurant is characterized by two integers fi and ti. Value ti shows the time the Rabbits need to lunch...
3
n, k = map(int, input().split()) joy = -10000000000 for i in range(n): f, t = map(int, input().split()) if t > k: joy = max(joy, f-(t-k)) else: joy = max(joy, f) print(joy)
"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
x,y=map(int,input().split()) arr=[int(x) for x in input().split()] l=arr[y-1] c=0 for i in range(x): if arr[i]>=l and arr[i]>0: c=c+1 print(c)
You have n gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The i-th gift consists of a_i candies and b_i oranges. During one move, you can choose some gift 1 ≀ i ≀ n and do one of the following operations: * eat exactly...
3
# from bisect import bisect_left TC = int(input()) for tc in range(TC): N = int(input()) A = list(map(int, input().split())) B = list(map(int, input().split())) mA = min(A) mB = min(B) result = 0 # print(A,B,mA,mB) for i in range(N): a = A[i] - mA b = B[i] - mB r...
Peter Parker wants to play a game with Dr. Octopus. The game is about cycles. Cycle is a sequence of vertices, such that first one is connected with the second, second is connected with third and so on, while the last one is connected with the first one again. Cycle may consist of a single isolated vertex. Initially t...
3
n,s = input(),1 for val in map(lambda x:int(x)-1, input().split()): s^=(val&1) print(s+1)
Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it ...
3
n=int(input()) l=[list(map(int,input().split())) for i in range(n)] s=l[0][1] c=l[0][1] for i in range(1,n): s=s-l[i][0]+l[i][1] c=max(s,c) print(c)
Gennady owns a small hotel in the countryside where he lives a peaceful life. He loves to take long walks, watch sunsets and play cards with tourists staying in his hotel. His favorite game is called "Mau-Mau". To play Mau-Mau, you need a pack of 52 cards. Each card has a suit (Diamonds β€” D, Clubs β€” C, Spades β€” S, or ...
3
card = str(input()) arr = list(map(str, input().split())) half1=card[:1] half2=card[1:] es = 0 for i in range(len(arr)): word=arr[i] if word[:1] == half1 or word[1:] == half2: es = 1 if es == 1 : print("YES") if es == 0:print("NO")
Takahashi is participating in a programming contest, AXC001. He has just submitted his code to Problem A. The problem has N test cases, all of which must be passed to get an AC verdict. Takahashi's submission has passed M cases out of the N test cases. Determine whether Takahashi's submission gets an AC. Constraints ...
1
N, M = map(int, raw_input().split()) if N > M: print "No" else: print "Yes"
You are given an array a consisting of n positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 2) or determine that there is no such subset. Both the given array and required subset may contain equal values. Input The first line contains a single integer t (1 ≀ t ≀...
3
t = int(input()) sol = [] while t: t -= 1 n = int(input()) a = [int(i) for i in input().split()] d = [i for i in a if i & 1 == False] if len(d): sol.append([1,a.index(d[0])+ 1]) else: if len(a) == 1: sol.append(['-1']) else: sol.append([2,[1,2]...
Recently, Norge found a string s = s_1 s_2 … s_n consisting of n lowercase Latin letters. As an exercise to improve his typing speed, he decided to type all substrings of the string s. Yes, all (n (n + 1))/(2) of them! A substring of s is a non-empty string x = s[a … b] = s_{a} s_{a + 1} … s_{b} (1 ≀ a ≀ b ≀ n). For e...
3
n, k = map(int, input().split()) s=list(input()) ak=list(input()) ind=[] for i in range(len(s)): if s[i] in ak: ind.append(i) count=0 t=1 for i in range(len(ind)): count+=1 if ind[i]==ind[i-1]+1: t+=1 if (i-1>=0 and ind[i]!=ind[i-1]+1) or i==len(ind)-1: count+=((t*(t-1))//2) ...
Here is a very simple variation of the game backgammon, named β€œMinimal Backgammon”. The game is played by only one player, using only one of the dice and only one checker (the token used by the player). The game board is a line of (N + 1) squares labeled as 0 (the start) to N (the goal). At the beginning, the checker ...
1
while 1: N,T,L,B = map(int,raw_input().split()) if N == 0: break lose = [int(raw_input()) for i in xrange(L)] back = [int(raw_input()) for i in xrange(B)] dp = [[0.0]*(N+1) for i in xrange(T+2)] dp[0][0] = 1.0 ans = 0.0 p = 1.0/6.0 for t in xrange(T): for i in xrange(N): ...
Β«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 ...
3
k=int(input()) l=int(input()) m=int(input()) n=int(input()) d=int(input()) a=set(range(k,d+1,k)) b=set(range(l,d+1,l)) c=set(range(m,d+1,m)) e=set(range(n,d+1,n)) print(len(a.union(b,c,e)))
A tutorial for this problem is now available on our blog. Click here to read it. The following problem appeared in the CodeChef March '09 Challenge In the mysterious country of Byteland, everything is quite different from what you'd normally expect. In most places, if you were approached by two mobsters in a dark al...
1
def check(a,m): # a - list of banknotes, sorted in reverse order # m - the remaining amount, we need to obtain from banknotes in a # remove this comment to see the values for each recursion # print a, m # if (len(a)>0) is false -- means "no banknotes left" # if (m<a[-1]) is false --- means print "required ...
You've got array a[1], a[2], ..., a[n], consisting of n integers. Count the number of ways to split all the elements of the array into three contiguous parts so that the sum of elements in each part is the same. More formally, you need to find the number of such pairs of indices i, j (2 ≀ i ≀ j ≀ n - 1), that <image>...
3
n=int(input()) arr=list(map(int,input().split())) req=sum(arr)//3 if(len(arr)<3 or sum(arr)%3!=0): print(0) else: pref=[0]*n pref[0]=arr[0] for i in range(1,n): pref[i]=arr[i]+pref[i-1] prefsum=[] suff=[0]*n suff[n-1]=arr[n-1] for i in range(n-2,-1,-1): suff[i]=arr[i]+suf...
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word s. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if...
3
m = "hello" def chat(): y = 0 s = input() for i in range(len(s)): if s[i] == m[y]: y += 1 if y == 5: return "YES" return "NO" print(chat())
Polycarp has spent the entire day preparing problems for you. Now he has to sleep for at least a minutes to feel refreshed. Polycarp can only wake up by hearing the sound of his alarm. So he has just fallen asleep and his first alarm goes off in b minutes. Every time Polycarp wakes up, he decides if he wants to sleep...
3
t=int(input()) for i in range(t): a,b,c,d = list(map(int,input().split())) sl = b chk = True tot = b if(sl>=a): print(tot) continue if(c<=d): print(-1) continue else: # print(a-tot) # print(c-d) if(((a-tot)%abs(c-d))==0): # print('yo') ct = (a-tot)//abs(c-d) else: ct = ((a-tot)//abs(c-d)...
You are given an integer N. Build an undirected graph with N vertices with indices 1 to N that satisfies the following two conditions: * The graph is simple and connected. * There exists an integer S such that, for every vertex, the sum of the indices of the vertices adjacent to that vertex is S. It can be proved t...
3
n=int(input()) m=n-n%2+1 d=[[i+j+2!=m and i!=j for i in range(n)] for j in range(n)] print(sum([sum(i) for i in d])//2) for i in range(n): for j in range(i+1,n): if d[i][j]:print(i+1,j+1)
Happy new year! The year 2020 is also known as Year Gyeongja (κ²½μžλ…„, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years. There are two sequences of n strings s_1, s_2, s_3, …, s_{n} and m strings t_1, t_2, t_3, …, t_{m}. ...
3
# map(int, input().split()) # list(map(int, input().split())) # for _ in range(int(input())): # print(' '.join([str(x) for x in ans])) n,m=map(int, input().split()) s = input().split() t = input().split() for _ in range(int(input())): y = int(input()) print(s[(y-1)%n]+t[(y-1)%m])
Let's call a number k-good if it contains all digits not exceeding k (0, ..., k). You've got a number k and an array a containing n numbers. Find out how many k-good numbers are in a (count each number every time it occurs in array a). Input The first line contains integers n and k (1 ≀ n ≀ 100, 0 ≀ k ≀ 9). The i-th ...
3
def main(): n, k = map(int, input().split()) k += 1 tot = 0 for _ in range(n): l = [False] * 10 for c in input(): l[ord(c) - 48] = True if all(l[:k]): tot += 1 print(tot) if __name__ == '__main__': main()
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
import sys input = sys.stdin.readline ############ ---- Input Functions ---- ############ def inp(): return(int(input())) def inlt(): return(list(map(int,input().split()))) def insr(): s = input().strip().lower() return(list(s[:len(s)])) def invr(): return(map(int,input().split())) s1, s2, s3 = 0,...
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d...
3
x = int(input()) LUCKY_NUMBERS = [4, 7] def get_n_lucky_numbers(x): n_lucky_numbers = 0 while x != 0: n_lucky_numbers += (x % 10) in LUCKY_NUMBERS x //= 10 return n_lucky_numbers def is_good(x): n = get_n_lucky_numbers(x) return n in LUCKY_NUMBERS if is_good(x): print("YES"...
Dima has a hamsters farm. Soon N hamsters will grow up on it and Dima will sell them in a city nearby. Hamsters should be transported in boxes. If some box is not completely full, the hamsters in it are bored, that's why each box should be completely full with hamsters. Dima can buy boxes at a factory. The factory pr...
3
k, n = map(int, input().split()) a = list(map(int, input().split())) count = 0 ans = 1 for i in range(n): if (k // a[i] * a[i] > count): count = k // a[i] * a[i] ans = i + 1 print(ans, count // a[ans - 1])
You are given two integers n and k. Your task is to find if n can be represented as a sum of k distinct positive odd (not divisible by 2) integers or not. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. The next t lines...
3
t = int(input()) while t : n,k = map(int,input().split()) if (k*k > n): print('NO') elif (n%2 != k%2): print('NO') else: print("YES") t -= 1
Adilbek was assigned to a special project. For Adilbek it means that he has n days to run a special program and provide its results. But there is a problem: the program needs to run for d days to calculate the results. Fortunately, Adilbek can optimize the program. If he spends x (x is a non-negative integer) days opt...
3
import math t = int(input()) for i in range(t): n, d = list(map(float, input().split())) data = [] data.append(d) x = 1 while (True): curr = x + math.ceil(d/(x+1)) if (curr > data[-1]): break data.append(curr) x = x + 1 if (data[-1] > n): print("NO") else: print("YES")
Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you? You are given a set of digits, your task is to find the maximum integer that you can mak...
1
a=input() m=map(int,raw_input().split()) if 0 not in m: print -1 exit() t=sum(m)%3 def sd(x): global m if x in m: m.pop(m.index(x)) return True return False if t==1: tt=0 if sd(1): tt=1 elif sd(4): tt=1 elif sd(7): tt=1 if tt==0 and sd(2): if sd(2): tt=1 elif sd(5): tt=1 elif sd(8): ...
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()) print("\n".join(map(lambda s: '%s%d%s' % (s[0], len(s)-2, s[-1]) if (len(s) > 10) else s, [input() for _ in range(n)])))
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had a red socks and b blue socks. According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot. Every day Vasya puts on new socks in the morning and ...
3
import math q=input().split() a=int(q[0]) b=int(q[1]) x=max(a,b) z=min(a,b) m=z n=int(math.floor((x-z)/2)) print(m,n)
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 solve(stringin): s = '' for su in stringin.lower(): if su != 'a' and su != 'y' and su != 'o' and su != 'e' and su != 'u' and su != 'i': s += '.' + su return s if __name__ == '__main__': string = str(input()) print(solve(string))
Valera's finally decided to go on holiday! He packed up and headed for a ski resort. Valera's fancied a ski trip but he soon realized that he could get lost in this new place. Somebody gave him a useful hint: the resort has n objects (we will consider the objects indexed in some way by integers from 1 to n), each obje...
1
from collections import Counter n = input() obj = [int(i) for i in raw_input().split()] paths = [int(i) for i in raw_input().split()] candidates = [] d = {} forb = Counter(paths) for i in range(len(paths)): if obj[i] == 1: candidates.append(i+1) if paths[i] != 0: d[i+1] = d.get(i+1, []) ...
Input The input contains a single integer a (0 ≀ a ≀ 35). Output Output a single integer. Examples Input 3 Output 8 Input 10 Output 1024
3
n = int(input()) print(0 if n % 2 == 0 else 1)
After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third ro...
3
n = int(input()) s = input() abc = 'abcdefghijklmnopqrstuvwxyz' c = 0 d = {} for letra in abc: d[letra] = 0 for i in range(len(s)): if(i%2 == 0):#chave d[s[i]]+=1 else: h = s[i].lower() if(d[h] != 0): d[h]-=1 else: c+=1 print(c)
There is a sequence of colorful stones. The color of each stone is one of red, green, or blue. You are given a string s. The i-th (1-based) character of s represents the color of the i-th stone. If the character is "R", "G", or "B", the color of the corresponding stone is red, green, or blue, respectively. Initially S...
3
string = input() instruction = input() currentchar = string[0] currentpos = 0 for char in instruction: if char == currentchar: currentpos += 1 currentchar = string[currentpos] print(str(currentpos + 1))
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n Γ— n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: * Elements of the main diagonal. * Elements of the secondary diagonal. * Elements of the "middle" row β€” the row which has exac...
3
n=int(input()) a=[] for i in range(n): a.append(list(map(int,input().split()[:n]))) s=0 for i in range(n): for j in range(n): if i==j or i+j==n-1 or i==(n-1)/2 or j==(n-1)/2: s+=a[i][j] print(s)
There is a kangaroo at coordinate 0 on an infinite number line that runs from left to right, at time 0. During the period between time i-1 and time i, the kangaroo can either stay at his position, or perform a jump of length exactly i to the left or to the right. That is, if his coordinate at time i-1 is x, he can be a...
3
x = int(input()) a = 0 for i in range(x+1): d = (i*(i+1))//2 if(d>=x): a = i break print(a)
You are given a regular polygon with n vertices labeled from 1 to n in counter-clockwise order. The triangulation of a given polygon is a set of triangles such that each vertex of each triangle is a vertex of the initial polygon, there is no pair of triangles such that their intersection has non-zero area, and the tota...
3
import atexit import io import sys _I_B = sys.stdin.read().splitlines() input = iter(_I_B).__next__ _O_B = io.StringIO() sys.stdout = _O_B @atexit.register def write(): sys.__stdout__.write(_O_B.getvalue()) n=int(input()) print((((n**3)-n)//3)-2)
An n Γ— n table a is defined as follows: * The first row and the first column contain ones, that is: ai, 1 = a1, i = 1 for all i = 1, 2, ..., n. * Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the remaining elements are defin...
3
n=int(input()) lst=[] for i in range(n): lst.append([1]*n) for i in range(1,n): for j in range(1,n): lst[i][j]=lst[i-1][j]+lst[i][j-1] print(lst[n-1][n-1])
Johnny has recently found an ancient, broken computer. The machine has only one register, which allows one to put in there one variable. Then in one operation, you can shift its bits left or right by at most three positions. The right shift is forbidden if it cuts off some ones. So, in fact, in one operation, you can m...
3
import math for _ in range(int(input())): a,b=sorted(map(int,input().split())) count=0 while(a<b): a=a*2 count+=1 if a==b: print(math.ceil(count/3)) else: print(-1)
For god's sake, you're boxes with legs! It is literally your only purpose! Walking onto buttons! How can you not do the one thing you were designed for? Oh, that's funny, is it? Oh it's funny? Because we've been at this for twelve hours and you haven't solved it either, so I don't know why you're laughing. You've got ...
3
for i in range(int(input())): n =int(input()) lst = list(map(int , input().split())) tmp = False for j in range(1,n): if lst[j-1] <= lst[j]: tmp = True print(['NO','YES'][tmp])
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of n students doing yet another trick. Let's assume that all these students are numbered from 1 to n. The teacher came to student a and put a hole in his badge. The student, ...
3
n=int(input()) a=list(map(int,input().split())) for i in range(n): s=set() while True: if i+1 in s: flag=1 break s.add(i+1) i=a[i]-1 print(i+1,end=" ")
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that. For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two ...
3
'''input 12 ''' n = int(input()) if n % 2 == 0: print(4, n-4) else: print(9, n-9)
Today's morning was exceptionally snowy. Meshanya decided to go outside and noticed a huge snowball rolling down the mountain! Luckily, there are two stones on that mountain. Initially, snowball is at height h and it has weight w. Each second the following sequence of events happens: snowball's weights increases by i,...
3
entrada1 = str(input()) entrada1 = entrada1.split() w = int(entrada1[0]) #peso h = int(entrada1[1]) #altura entrada2 = str(input()) entrada2 = entrada2.split() u1 = int(entrada2[0])#peso roca 1 d1 = int(entrada2[1])#altura roca 1 entrada3 = str(input()) entrada3 = entrada3.split() u2 = int(entrada3[0]) #peso roca 2 d2 ...
Theatre Square in the capital city of Berland has a rectangular shape with the size n Γ— m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a Γ— a. What is the least number of flagstones needed to pave the Square? It'...
1
from sys import stdin, stdout n, m, a = [int(x) for x in stdin.readline().rstrip().split()] output = (n // a) + int((n % a) != 0) output *= (m // a) + int((m % a) != 0) stdout.write(str(output) + "\n")
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
""" A91nrp Problem 556A 23/10/2018 """ from sys import stdin n = int(stdin.readline()) seqstr = stdin.readline() ocounter = 0 zcounter = 0 for i in range(n): if int(seqstr[i]) == 0: ocounter += 1 else: zcounter += 1 print(abs(ocounter - zcounter))
"Hey, it's homework time" β€” thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him. The sequence of n integers is calle...
1
n = int(raw_input()) data = map(int, raw_input().split()) count = (5010)*[0] ret = int(0) for i in range(n): if data[i] > n or data[i] < 1 or count[data[i]] >= 1: ret+=1 count[data[i]]+=1 print ret
Everybody knows of [spaghetti sort](https://en.wikipedia.org/wiki/Spaghetti_sort). You decided to implement an analog sorting algorithm yourself, but as you survey your pantry you realize you're out of spaghetti! The only type of pasta you have is ravioli, but you are not going to let this stop you... You come up with...
3
n = int(input()) a = [int(i) for i in input().split()] while len(a)!=1: m = a[0] im = 0 for i in range(1,len(a)): if abs(a[i] - a[i-1])>=2: print("NO") exit() if a[i]>m: m = a[i] im = i a.pop(im) print("YES")
There are N people standing in a row from west to east. Each person is facing east or west. The directions of the people is given as a string S of length N. The i-th person from the west is facing east if S_i = `E`, and west if S_i = `W`. You will appoint one of the N people as the leader, then command the rest of the...
3
n = int(input()) s = input() w = [0] e = [0] for i in range(1,n+1): w.append(w[i-1] + (s[i-1]=='W')) e.append(e[i-1] + (s[i-1]=='E')) ans = n for i in range(1,n+1): ans = min(ans, w[i-1]+e[n]-e[i]) print(ans)
Ohana Matsumae is trying to clean a room, which is divided up into an n by n grid of squares. Each square is initially either clean or dirty. Ohana can sweep her broom over columns of the grid. Her broom is very strange: if she sweeps over a clean square, it will become dirty, and if she sweeps over a dirty square, it ...
3
n = int(input()) a = [] for i in range (n): a.append(list(input())) ans = 0 for i in range (n): tmp = 1 for j in range(i+1,n): if (a[i] == a[j]): tmp += 1 ans = max(ans,tmp) print(ans)
Valera had two bags of potatoes, the first of these bags contains x (x β‰₯ 1) potatoes, and the second β€” y (y β‰₯ 1) potatoes. Valera β€” very scattered boy, so the first bag of potatoes (it contains x potatoes) Valera lost. Valera remembers that the total amount of potatoes (x + y) in the two bags, firstly, was not gerater ...
1
myin = map(int, raw_input().split()) place = 1 count = 0 myout = '' while myin[1] * place <= myin[2]: if myin[1] * place - myin[0] > 0: count += 1 myout += str(myin[1] * place - myin[0]) + ' ' place += 1 if count != 0: myout = myout[:len(myout) - 1] print myout else: print -1
Recently Oz has found a magical string consisting of single digit "1". After experimenting on the string, Oz found a weird magical property of the string that is whenever he touches the string then each digit "1" of string changed to digit "0" and each digit "0" of string changed to "01". Oz found this property intere...
1
t = input() l=[[1,0]] o=[] for i in range(0,t): n = input() if n >= len(l): for j in range(len(l),n+1): zero = l[len(l)-1][0]+l[len(l)-1][1] one = l[len(l)-1][1] l.append([one,zero]) o.append(l[n]) for i in o: s = str(i[0])+" "+str(i[1]) print s
Kirito is stuck on a level of the MMORPG he is playing now. To move on in the game, he's got to defeat all n dragons that live on this level. Kirito and the dragons have strength, which is represented by an integer. In the duel between two opponents the duel's outcome is determined by their strength. Initially, Kirito'...
3
s, n = map(int, input().split()) for strength, bonus in sorted(tuple(map(int, input().split())) for _ in range(n)): if strength >= s: print('NO') break s += bonus else: print('YES')
Tokitsukaze is playing a game derivated from Japanese mahjong. In this game, she has three tiles in her hand. Each tile she owns is a suited tile, which means it has a suit (manzu, pinzu or souzu) and a number (a digit ranged from 1 to 9). In this problem, we use one digit and one lowercase letter, which is the first c...
3
a=input().split() a.sort() b=[int(a[0][0]),int(a[1][0]),int(a[2][0])] e=[a[0][1],a[1][1],a[2][1]] if(len(set(a))==1): print(0) elif a[0]==a[1] or a[1]==a[2]: print(1) elif(len(set(e))==3): print(2) elif(len(set(e))==1): b.sort() k=2 o=0 if b[1]-b[0]==1: k-=1 o=1 if b[2]-b...
The only difference between easy and hard versions is constraints. A session has begun at Beland State University. Many students are taking exams. Polygraph Poligrafovich is going to examine a group of n students. Students will take the exam one-by-one in order from 1-th to n-th. Rules of the exam are following: *...
3
n, m = map(int, input().strip().split()) arr = list(map(int, input().strip().split())) ans = [0]*n curr_sum = 0 for i in range(len(arr)): curr_sum += arr[i] if curr_sum > m: c = 0 temp = curr_sum sub = sorted(arr[:i]) for j in range(i-1, -1, -1): temp -= sub[j] c += 1 if temp <= m: break ans[i]...
The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups. Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime. If there is no police offi...
3
n=int(input()) a=list(map(int,input().split())) c=0 d=0 for i in a: if i == -1 and d!=0: d=d-1 elif i == -1 and d==0: c=c+i elif i != -1: d=d+i print(-c)
Naruto has sneaked into the Orochimaru's lair and is now looking for Sasuke. There are T rooms there. Every room has a door into it, each door can be described by the number n of seals on it and their integer energies a_1, a_2, ..., a_n. All energies a_i are nonzero and do not exceed 100 by absolute value. Also, n is e...
3
n = int(input()) for i in range(n): a = int(input()) massiv = list(map(int, input().split())) for j in range(1, len(massiv), 2): massiv[j - 1], massiv[j] = massiv[j] * -1, massiv[j - 1] print(" ".join([str(j) for j in massiv]))
Being tired of participating in too many Codeforces rounds, Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other. He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits ...
3
n = int(input()) for ii in range(n): x, y, a, b = map(int, input().split()) x = y - x a = a + b print((x//a,-1)[x%a>0])
There is always an integer in Takahashi's mind. Initially, the integer in Takahashi's mind is 0. Takahashi is now going to eat four symbols, each of which is `+` or `-`. When he eats `+`, the integer in his mind increases by 1; when he eats `-`, the integer in his mind decreases by 1. The symbols Takahashi is going t...
1
import sys import math num = 0 op = raw_input().strip() for a in op: if a == "-": num -= 1 elif a == "+": num += 1 print(str(num))
Ringo is giving a present to Snuke. Ringo has found out that Snuke loves yakiniku (a Japanese term meaning grilled meat. yaki: grilled, niku: meat). He supposes that Snuke likes grilled things starting with `YAKI` in Japanese, and does not like other things. You are given a string S representing the Japanese name of ...
3
S=input() if len(S)>=4: if S[:4]=='YAKI': print('Yes') exit() print('No')
Array of integers is unimodal, if: * it is strictly increasing in the beginning; * after that it is constant; * after that it is strictly decreasing. The first block (increasing) and the last block (decreasing) may be absent. It is allowed that both of this blocks are absent. For example, the following th...
3
I = lambda: list(map(int, input().split())) def sign(x): if x==0: return 0 return x//abs(x) n = int(input()) a = I() d = [sign(i-j) for i, j in zip(a[1:], a[:-1])] md = 2 for i in d: if i<=md: md = i else: md = -2 print("NO" if md==-2 else "YES")
Polycarp loves ciphers. He has invented his own cipher called repeating. Repeating cipher is used for strings. To encrypt the string s=s_{1}s_{2} ... s_{m} (1 ≀ m ≀ 10), Polycarp uses the following algorithm: * he writes down s_1 ones, * he writes down s_2 twice, * he writes down s_3 three times, * ... ...
3
s=list(input()) s2=[] if len(s)%2==0: for i in range(len(s)): if i%2==0: s2.append(s[-1]) del s[-1] else: s2.append(s[0]) del s[0] else: for i in range(len(s)): if i%2==1: s2.append(s[-1]) del s[-1] else: ...
Little Artem likes electronics. He can spend lots of time making different schemas and looking for novelties in the nearest electronics store. The new control element was delivered to the store recently and Artem immediately bought it. That element can store information about the matrix of integers size n Γ— m. There a...
1
import os def row_operation(row_num): #print 'row',row_num #print matrix first_val = matrix[row_num][-1] for i in xrange(len(matrix[row_num])-1,0,-1): matrix[row_num][i] = matrix[row_num][i-1] matrix[row_num][0] = first_val #print matrix def col_operation(col_num): #print 'col',col_num #print matrix first_...
Vasya thinks that lucky tickets are the tickets whose numbers are divisible by 3. He gathered quite a large collection of such tickets but one day his younger brother Leonid was having a sulk and decided to destroy the collection. First he tore every ticket exactly in two, but he didn’t think it was enough and Leonid a...
1
def sum_digit(s): return sum(int(c) for c in list(s)) import sys n=int(sys.stdin.readline()) nums=sys.stdin.readline().strip().split(" ") X=[0,0,0] #0,1,2 for part in nums: x=sum_digit(part) % 3 X[x]+=1 S=0 S+=X[0]/2 #0 S+=min(X[1],X[2]) #1,2 print(S)
Polycarp has created his own training plan to prepare for the programming contests. He will train for n days, all days are numbered from 1 to n, beginning from the first. On the i-th day Polycarp will necessarily solve a_i problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first...
3
n=int(input());s=input().split();k=[];ans=1;p=0 for i in range(0,n): k.append(int(s[i])) q=sum(k)/2 for j in range(0,n): p+=k[j] if p>=q: break ans+=1 print(ans)
Snuke, a water strider, lives in a rectangular pond that can be seen as a grid with H east-west rows and W north-south columns. Let (i,j) be the square at the i-th row from the north and j-th column from the west. Some of the squares have a lotus leaf on it and cannot be entered. The square (i,j) has a lotus leaf on i...
3
import sys from collections import deque h,w,k = map(int, sys.stdin.readline().rstrip("\n").split()) sx,sy,gx,gy = map(int, sys.stdin.readline().rstrip("\n").split()) sx,sy,gx,gy = sx-1,sy-1,gx-1,gy-1 labyrinth = [line.rstrip("\n") for line in sys.stdin] INF = float('inf') footprint = [ [[(INF,INF)]*4 for j in range(w)...
Sheldon, Leonard, Penny, Rajesh and Howard are in the queue for a "Double Cola" drink vending machine; there are no other people in the queue. The first one in the queue (Sheldon) buys a can, drinks it and doubles! The resulting two Sheldons go to the end of the queue. Then the next in the queue (Leonard) buys a can, d...
3
n=int(input()) i=5 k=0 p=5 while p<n: i=2*i k+=1 p+=i t=n-p+i if t<=2**(k): print("Sheldon") elif 2**(k)<t<=2**(k)*2: print("Leonard") elif 2**(k+1)<t<=2**(k)*3: print("Penny") elif 2**(k)*3<t<=2**(k)*4: print("Rajesh") else: print("Howard")
Because of budget cuts one IT company established new non-financial reward system instead of bonuses. Two kinds of actions are rewarded: fixing critical bugs and suggesting new interesting features. A man who fixed a critical bug gets "I fixed a critical bug" pennant on his table. A man who suggested a new interesting...
3
def w3(n): # num of ways n num sum to 3 return (n+3-1)*(n+3-2)*(n+3-3)//2//3 def w5(n): # num of ways n num sum to 3 return (n+5-1)*(n+5-2)*(n+5-3)*(n+5-4)*(n+5-5)//2//3//4//5 n=int(input()) print(w3(n)*w5(n))
Let LCM(x, y) be the minimum positive integer that is divisible by both x and y. For example, LCM(13, 37) = 481, LCM(9, 6) = 18. You are given two integers l and r. Find two integers x and y such that l ≀ x < y ≀ r and l ≀ LCM(x, y) ≀ r. Input The first line contains one integer t (1 ≀ t ≀ 10000) β€” the number of tes...
3
for _ in range(int(input())) : l, r = map(int,input().split()) if 2*l <= r : print(l,2*l,sep=" ") else : print(-1,-1,sep=" ")
Today is Wednesday, the third day of the week. What's more interesting is that tomorrow is the last day of the year 2015. Limak is a little polar bear. He enjoyed this year a lot. Now, he is so eager to the coming year 2016. Limak wants to prove how responsible a bear he is. He is going to regularly save candies for ...
1
a = raw_input() l = [] l = a.split() num = int(l[0]) if((l[2])=='week'): if(num == 5 or num == 6): print 53 else: print 52 if(l[2] == 'month'): if(num == 30): print 11 elif(num == 31): print 7 else: print 12
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below. There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each ...
3
x,h=[],[] n=int(input()) for i in range(n): arr=[int(x) for x in input().split()] xi,hi=arr[0],arr[1] x.append(xi) h.append(hi) ans=2 flag=0 for i in range(1,n-1): gap1=x[i]-x[i-1] gap2=x[i+1]-x[i] if(gap1>h[i]): ans+=1 elif(gap2>h[i]): x[i]+=h[i] ans+=1 ...
You are given q queries in the following form: Given three integers l_i, r_i and d_i, find minimum positive integer x_i such that it is divisible by d_i and it does not belong to the segment [l_i, r_i]. Can you answer all the queries? Recall that a number x belongs to segment [l, r] if l ≀ x ≀ r. Input The first l...
3
q = int(input()) result = [] for _ in range(q): l, r, d = map(int, input().strip().split()) # between l and r if d < l or d > r: result.append(d) continue m = r // d res = d * (m + 1) result.append(res) for i in result: print(i)
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s. You have to answer t independent test cases. Input The first line of the input co...
3
t = int(input()) for _ in range(t): a,b = map(int,input().split()) if a%b != 0:print(b-(a%b)) else: print(0)
We just discovered a new data structure in our research group: a suffix three! It's very useful for natural language processing. Given three languages and three suffixes, a suffix three can determine which language a sentence is written in. It's super simple, 100% accurate, and doesn't involve advanced machine learni...
3
N = int(input()) for _ in range(N): string = input() if (string[-1]=="o"): print("FILIPINO") elif (string[-1]=="u"): print("JAPANESE") elif (string[-1]=="a"): print("KOREAN")
Let s(x) be sum of digits in decimal representation of positive integer x. Given two integers n and m, find some positive integers a and b such that * s(a) β‰₯ n, * s(b) β‰₯ n, * s(a + b) ≀ m. Input The only line of input contain two integers n and m (1 ≀ n, m ≀ 1129). Output Print two lines, one for decimal...
3
n,m = map(int,input().split()) print(200 * '9' + 199 * '0' + '1') print(200 * '9')
n participants of the competition were split into m teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends. Your task is to write a program that will find the minimum and the maximum number of pairs of friends that could ha...
3
n, m = map(int, input().split()) k_min = (n % m) * (n//m + 1) * (n//m) // 2 + (m - n % m) * (n // m - 1) * (n//m) // 2 k_max = (n - m) * (n - m + 1) // 2 print(k_min, k_max)
Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot. He wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fence corners at a single angle a. Will the robot be able to build the fence Emuskald...
3
n = int(input()) for i in range(0, n): a = float(input()) if 360.0 % (180.0-a) == 0: print("YES") else: print("NO")
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network. Bu...
3
name = input() first = ord("a") counters = [0 for _ in range(26)] result = 0 for symbol in name: index = ord(symbol) - first if counters[index] == 0: counters[index] = 1 result +=1 print("CHAT WITH HER!" if result % 2 == 0 else "IGNORE HIM!")
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob. Right now, Limak and Bob weigh a and b respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight. Limak eats a lot and his weight is tripled after every year, while Bob's weight...
3
x = input() y = x.split() z = [int(d) for d in y] x = 0 while z[0]*(3**x) <= z[1]*(2**x): x += 1 print(x)
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory. George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living...
3
#!/usr/bin/env python3 n = int(input()) count = 0 p_i = 0 q_i = 0 for _ in range(n): p_i, q_i = map( int, input().split()) if p_i == q_i or q_i - p_i == 1: continue else: count += 1 print(count)
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
team=input(); one=0; zero=0; flag=False; if(len(team)>7): for i in range(len(team)): if(team[i]=="0"): if(one>0): one=0; zero+=1; else: if(zero>0): zero=0; one+=1; if(one>=7 or zero>=7): flag=True; ...
Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it ...
3
n=int(input()) s=0 l1=[] for n1 in range(n): l=[] l=[int(x) for x in input().split()] s=s+l[1]-l[0] l1.append(s) print(max(l1))
You are given three integers a, b, k. Find two binary integers x and y (x β‰₯ y) such that 1. both x and y consist of a zeroes and b ones; 2. x - y (also written in binary form) has exactly k ones. You are not allowed to use leading zeros for x and y. Input The only line contains three integers a, b, and k (...
3
from sys import stdin,stdout input = stdin.readline def main(inp): a,b,k=inp if b == 1: if k != 0: print("No") else: print("Yes") print("1"*b+"0"*a) print("1"*b+"0"*a) return if a == 0: if k != 0: print("No") ...
Due to the coronavirus pandemic, city authorities obligated citizens to keep a social distance. The mayor of the city Semyon wants to light up Gluharniki park so that people could see each other even at night to keep the social distance. The park is a rectangular table with n rows and m columns, where the cells of the...
3
for _ in range(int(input())): n, m = map(int, input().split()) if n % 2 == 0 or m % 2 == 0: print((n*m) // 2) else: print(((n*m) + 1) // 2)
Polycarp has spent the entire day preparing problems for you. Now he has to sleep for at least a minutes to feel refreshed. Polycarp can only wake up by hearing the sound of his alarm. So he has just fallen asleep and his first alarm goes off in b minutes. Every time Polycarp wakes up, he decides if he wants to sleep...
3
import random import math LI = lambda: list(map(int,input().split())) MI = lambda: map(int,input().split()) yes = lambda: print("Yes") no = lambda: print("No") I = lambda: list(input()) J = lambda x: "".join(x) II = lambda: int(input()) SI = lambda: input() #---khan17---template t = II() for q in range(t): a,b,c,d = M...