problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
Given an integer x, find 2 integers a and b such that: * 1 ≀ a,b ≀ x * b divides a (a is divisible by b). * a β‹… b>x. * a/b<x. Input The only line contains the integer x (1 ≀ x ≀ 100). Output You should output two integers a and b, satisfying the given conditions, separated by a space. If no pair of in...
3
#!/usr/bin/env python3 import sys def rint(): return map(int, sys.stdin.readline().split()) #lines = stdin.readlines() x = int(input()) for b in range(1, x+1): for a in range(b, x+1): if a%b == 0 and a*b > x and a < b*x: print(a, b) exit() print(-1)
Jzzhu has invented a kind of sequences, they meet the following property: <image> You are given x and y, please calculate fn modulo 1000000007 (109 + 7). Input The first line contains two integers x and y (|x|, |y| ≀ 109). The second line contains a single integer n (1 ≀ n ≀ 2Β·109). Output Output a single integer...
3
x,y=map(int,input().split()) n=int(input()) l=[x-y,x,y,y-x,-x,-y] print(l[n%6]%1000000007)
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution....
3
n = int(input()) mas = [] s = 0 for i in range(n): mas = list(map(int, input().split())) if mas.count(0) < 2: s += 1 print(s)
Iahub and his friend Floyd have started painting a wall. Iahub is painting the wall red and Floyd is painting it pink. You can consider the wall being made of a very large number of bricks, numbered 1, 2, 3 and so on. Iahub has the following scheme of painting: he skips x - 1 consecutive bricks, then he paints the x-...
3
from math import * def gcd(x,y): if y==0: return x else: return gcd(y, x%y) def lcm(x,y): return (x*y)//gcd(x,y) x,y,a,b= map(int, input().split()) num=lcm(x,y) print(floor(b/num)-ceil(a/num) + 1)
After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer. At the start of the day they have x ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. Each person in the q...
3
a, b = input().split(" ") a = int(a) b = int(b) f=0 sum = 0 s=b e=0 for i in range(a): c,d = input().split(" ") d = int(d) if c == '+': s += d else: if s-d<0: f += 1 else: s= s-d print(s, f)
Find the number of ways to choose a pair of an even number and an odd number from the positive integers between 1 and K (inclusive). The order does not matter. Constraints * 2\leq K\leq 100 * K is an integer. Input Input is given from Standard Input in the following format: K Output Print the number of ways to...
3
K=int(input()) print(K//2*-(-K//2))
Notes Template in C Constraints * 1 ≀ n ≀ 100000 * 1 ≀ q ≀ 1000 * 1 ≀ timei ≀ 50000 * 1 ≀ length of namei ≀ 10 * 1 ≀ Sum of timei ≀ 1000000 Input n q name1 time1 name2 time2 ... namen timen In the first line the number of processes n and the quantum q are given separated by a single space. In the following n li...
3
answer = [] n, q = [int(i) for i in input().split(" ")] for i in range(n): name, time = input().split(" ") time = int(time) answer.append([name, time]) time = 0 while len(answer) > 0: p = answer.pop(0) if p[1] <= q: time += p[1] print(p[0], time) else: p[1] -= q ...
You are given two arrays a and b both consisting of n positive (greater than zero) integers. You are also given an integer k. In one move, you can choose two indices i and j (1 ≀ i, j ≀ n) and swap a_i and b_j (i.e. a_i becomes b_j and vice versa). Note that i and j can be equal or different (in particular, swap a_2 w...
1
t = input() for i in range(t): n,k = [int(nk) for nk in raw_input().split(" ")] a = [int(ai) for ai in raw_input().split(" ")] b = [int(bi) for bi in raw_input().split(" ")] a.sort(reverse=True) b.sort(reverse=True) ans = sum(a[:n-k]) c = a[n-k:] + b[:k] c.sort(reverse=True) ans += sum(c[:k]) print ans
Sean is trying to save a large file to a USB flash drive. He has n USB flash drives with capacities equal to a1, a2, ..., an megabytes. The file size is equal to m megabytes. Find the minimum number of USB flash drives needed to write Sean's file, if he can split the file between drives. Input The first line contai...
3
#coding:utf-8 n = int(input()) m = int(input()) a = [0] * n for i in range(n): a[i] = int(input()) b = sorted(a,reverse = True) s = 0 ans = 0 for i in range(n): if ans >= m: break s += 1 ans += b[i] print(s)
Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't). q events are abou...
3
n , q = map(int, input().split()) stacks = [[] for i in range(n + 1)] queue = [] q_start = 0 unread = 0 ans = [] for i in range(q): action, num = map(int, input().split()) if action == 1: queue.append(0) stacks[num].append(len(queue) - 1) unread += 1 elif action == 2: ...
Slime has a sequence of positive integers a_1, a_2, …, a_n. In one operation Orac can choose an arbitrary subsegment [l … r] of this sequence and replace all values a_l, a_{l + 1}, …, a_r to the value of median of \\{a_l, a_{l + 1}, …, a_r\}. In this problem, for the integer multiset s, the median of s is equal to th...
3
from sys import stdin, stdout t = int(stdin.readline()) while t!=0: t-=1 n,k = map(int, stdin.readline().split()) lt = [int(x) for x in stdin.readline().split()] aux = [0]*n ans = 'NO' for i in range(n): if lt[i]==k: aux[i]=1 elif lt[i]>k: aux[i]=2 i...
You are given two positive integers n (1 ≀ n ≀ 10^9) and k (1 ≀ k ≀ 100). Represent the number n as the sum of k positive integers of the same parity (have the same remainder when divided by 2). In other words, find a_1, a_2, …, a_k such that all a_i>0, n = a_1 + a_2 + … + a_k and either all a_i are even or all a_i ar...
3
for _ in range(int(input())): n, k = map(int, input().split()) if n <k: print("NO") elif n == k: print("YES") print((n* "1 ")[:-1]) else: if n%2 == 0 and k<= n/2: print("YES") print((k-1)*"2 " + str(n-(k-1)*2)) else: if (n-...
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 itertools import product X,Y,Z,K = map(int,input().split()) A = list(map(int,input().split())) B = list(map(int,input().split())) C = list(map(int,input().split())) AB = sorted([a+b for a,b in product(A,B)],reverse=True)[:K] ans = sorted([a+b for a,b in product(AB,C)],reverse=True)[:K] for i in ans: print(i)
You are given a positive integer x. Find any such 2 positive integers a and b such that GCD(a,b)+LCM(a,b)=x. As a reminder, GCD(a,b) is the greatest integer that divides both a and b. Similarly, LCM(a,b) is the smallest integer such that both a and b divide it. It's guaranteed that the solution always exists. If ther...
3
#EhAb_AnD_gCd t=int(input()) for i in range(t): n=int(input()) print(1,n-1)
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are r...
3
n,k = map(int,input().split()) s = input() a = (n-k)//2 s1 = s.replace('(','',a) s2 = s1.replace(')','',a) print(s2)
Leo has developed a new programming language C+=. In C+=, integer variables can only be changed with a "+=" operation that adds the right-hand side value to the left-hand side variable. For example, performing "a += b" when a = 2, b = 3 changes the value of a to 5 (the value of b does not change). In a prototype progr...
3
# Hey, there Stalker!!! # This Code was written by: # β–’β–’β–’β–’β–’β–’β–’β–’β–’β–’β–’β–’β–’β–’β–’β–’β–’β–’β–’β–’β–’ # ▒▒╔╗╔═══╦═══╗▒▒▒╔╗▒▒▒ # ▒╔╝║║╔═╗║╔═╗╠╗▒▒║║▒▒▒ # β–’β•šβ•—β•‘β•‘β•‘β•‘β•‘β•‘β•‘β•‘β•‘β• β•¬β•β•β•£β•‘β•”β•—β–’ # β–’β–’β•‘β•‘β•‘β•‘β•‘β•‘β•‘β•‘β•‘β•‘β• β•£β•‘β•β•£β•šβ•β•β–’ # β–’β•”β•β•šβ•£β•šβ•β•β•‘β•šβ•β•β•‘β•‘β•‘β•β•£β•”β•—β•—β–’ # β–’β•šβ•β•β•©β•β•β•β•©β•β•β•β•£β• β•β•β•©β•β•šβ•β–’ # ▒▒▒▒▒▒▒▒▒▒▒╔╝║▒▒▒▒▒▒▒ # β–’β–’β–’β–’β–’β–’β–’β–’β–’β–’β–’β•šβ•β•β–’β–’β–’β–’β–’β–’β–’ # β–’β–’β–’β–’β–’β–’β–’β–’β–’β–’β–’β–’β–’β–’β–’β–’β–’β–’β–’β–’β–’ from functools import reduce...
Write a program which reads an integer $S$ [second] and converts it to $h:m:s$ where $h$, $m$, $s$ denote hours, minutes (less than 60) and seconds (less than 60) respectively. Constraints * $0 \leq S \leq 86400$ Input An integer $S$ is given in a line. Output Print $h$, $m$ and $s$ separated by ':'. You do not n...
3
sec=int(input()) m=sec//60%60 h=sec//3600 s=sec%60 print(h,m,s,sep=":")
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
from math import * for i in range(int(input())): n=int(input()) l=list(map(int,input().split())) m=[l[0]] n=len(l) for i in range(1,n): if l[i]>0 and m[-1]>0 and l[i]>m[-1]: m.pop() m.append(l[i]) elif l[i]<0 and m[-1]>0: m.append(l[i]) eli...
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits. Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has on...
3
n = int(input()) for i in range(101) : n = n+1 kol = set((str(n))) if len(kol) == 4: print(n) break else : continue
A frog is currently at the point 0 on a coordinate axis Ox. It jumps by the following algorithm: the first jump is a units to the right, the second jump is b units to the left, the third jump is a units to the right, the fourth jump is b units to the left, and so on. Formally: * if the frog has jumped an even numb...
1
import sys n = int(sys.stdin.readline()) for i in range(0, n): line = sys.stdin.readline() abk = list(map(int, line.split())) a = abk[0] b = abk[1] k = abk[2] x = 0 ## k times x += a * ((k + 1) / 2) x -= b * (k / 2) print(x)
Input The input contains a single integer a (1 ≀ a ≀ 99). Output Output "YES" or "NO". Examples Input 5 Output YES Input 13 Output NO Input 24 Output NO Input 46 Output YES
3
n = int(input()) if (n == 1 or n == 7 or n == 9 or n == 10 or n == 11 or 12 < n < 30 or n == 31 or n == 37 or n == 39 or n == 41 or n == 47 or n == 49 or n == 51 or n == 57 or n == 59 or n == 61 or n == 67 or 68 < n < 80 or n == 81 or n == 87 or 88 < n < 100): print('NO') else: print('YES')...
Very soon there will be a parade of victory over alien invaders in Berland. Unfortunately, all soldiers died in the war and now the army consists of entirely new recruits, many of whom do not even know from which leg they should begin to march. The civilian population also poorly understands from which leg recruits beg...
3
n = int(input()) columns = [list(map(int, input().split())) for i in range(n)] difference_of_columns = [columns[i][0] - columns[i][1] for i in range(n)] min_beauty = max_beauty = difference_of_columns[0] min_beauty_index = max_beauty_index = 0 for i in range(n): if difference_of_columns[i] > max_beauty: ...
A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not. You are given a string s of length n, consisting of digits. In one operation you can delete any character from strin...
1
t=input() for _ in range(t): L=input() P=raw_input().find('8') print "NO" if P<0 or P+11>L else "YES"
How many multiples of d are there among the integers between L and R (inclusive)? Constraints * All values in input are integers. * 1 \leq L \leq R \leq 100 * 1 \leq d \leq 100 Input Input is given from Standard Input in the following format: L R d Output Print the number of multiples of d among the integers b...
3
l,r,d = map(int,input().split()) print((r)//d-(l-1)//d)
We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer t Π’-prime, if t has exactly three distinct positive divisors. You are given an array of n positive integers. For each of them determine whether it is Π’-prime or not. Input The f...
3
n = 2**20 mas = [1]*n r = {4} for i in range(2,n): if mas[i]: for j in range(i*i,n,i): mas[j] = 0 r.add(i*i) input() for d in map(int,input().split()): print (['NO','YES'][d in r])
We will call a string obtained by arranging the characters contained in a string a in some order, an anagram of a. For example, `greenbin` is an anagram of `beginner`. As seen here, when the same character occurs multiple times, that character must be used that number of times. Given are N strings s_1, s_2, \ldots, s...
1
#abc137c n=int(raw_input()) s=[''.join(sorted(raw_input())) for i in xrange(n)] h={} res=0 for si in s: if si in h: res+=h[si] h[si]+=1 else: h[si]=1 print res
Natasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the string β€” concatenation of letters, which correspond to the stages. There are n stages available. The rock...
3
n,k = list(map(int,input().split())) data = sorted(list(input())) data = list(map(lambda x:ord(x)-ord('a')+1,data)) result = 0 used = 0 idx =0 prev = -2 # print(data) for d in data: if d > prev+1: result+= d prev = d used += 1 if used == k: break if used < k: print(-...
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
a=int(input()) c=0 min=-9999999 for i in range(a): vih,vho=map(int,input().split()) c=c-vih+vho if c>min: min=c print(min)
After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≀ si ≀ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum nu...
3
# problem 158B n=input() a,b,c,d=map(input().count,('1','2','3','4')) # here d represents no. of 4's and will directly add # we will also add c no. of 3's # now b is no. of 2's so we multiply by 2 # max(0,a-c) tells whether we have more 1's than 3's # if this is true then no. of 1's = 3's has been counted in c # rest...
Alice and Bob have received three big piles of candies as a gift. Now they want to divide these candies as fair as possible. To do this, Alice takes one pile of candies, then Bob takes one of the other two piles. The last pile is split between Alice and Bob as they want: for example, it is possible that Alice takes the...
1
q = input() for i in range(q): a, b, c = map(int,raw_input().split()) ans = int((a+b+c)/2) print(ans)
The Monk wants to teach all its disciples a lesson about patience, since they are always in a hurry to do something crazy. To teach them this, he gives them a list of N numbers, which may or may not be distinct. The students are supposed to solve a simple Mathematical equation based on the array of these N numbers. g(x...
1
def mul(arr): length = len(arr) counter = 0 mul = 1 while(counter < length): mul = mul * arr[counter] counter += 1 return mul def gcd(k): k.sort() lowest = k[0] length = len(k) counter = 0 while(counter < length): if k[counter] % lowest != 0 : counter = 0 lowest = lowest - 1 continue counter ...
Kizahashi, who was appointed as the administrator of ABC at National Problem Workshop in the Kingdom of AtCoder, got too excited and took on too many jobs. Let the current time be time 0. Kizahashi has N jobs numbered 1 to N. It takes A_i units of time for Kizahashi to complete Job i. The deadline for Job i is time B...
3
N = int(input()) AB = list(list(map(int, input().split())) for _ in range(N)) AB.sort(key=lambda x: x[1]) now = 0 for a, b in AB: now += a if now > b: print("No") exit() print("Yes")
We start with a permutation a_1, a_2, …, a_n and with an empty array b. We apply the following operation k times. On the i-th iteration, we select an index t_i (1 ≀ t_i ≀ n-i+1), remove a_{t_i} from the array, and append one of the numbers a_{t_i-1} or a_{t_i+1} (if t_i-1 or t_i+1 are within the array bounds) to the r...
3
import sys readline = sys.stdin.readline T = int(readline()) MOD = 998244353 Ans = [None]*T for qu in range(T): N, K = map(int, readline().split()) A = [0] + list(map(int, readline().split())) + [0] B = list(map(int, readline().split())) C = [None]*(N+1) for i in range(1, N+1): C[A[i]] = i...
You are given some Tetris field consisting of n columns. The initial height of the i-th column of the field is a_i blocks. On top of these columns you can place only figures of size 2 Γ— 1 (i.e. the height of this figure is 2 blocks and the width of this figure is 1 block). Note that you cannot rotate these figures. Yo...
3
import sys sys.setrecursionlimit(10**9) from collections import defaultdict IA=lambda: map(int,input().split()) t=int(input()) for i in range(t): n=int(input()) vis=[int(-1) for i in range(n+1)] a=list(IA()) le=len(a) flag=1 t=a[0]&1 for i in range(1,le): if (a[i]&1)!=t: ...
Valera loves his garden, where n fruit trees grow. This year he will enjoy a great harvest! On the i-th tree bi fruit grow, they will ripen on a day number ai. Unfortunately, the fruit on the tree get withered, so they can only be collected on day ai and day ai + 1 (all fruits that are not collected in these two days,...
3
import sys input = lambda: sys.stdin.readline().strip("\r\n") n, v = map(int, input().split()) ls = [0] * 3005 for i in range(n): a, b = map(int, input().split()) ls[a] += b prev = 0 ans = 0 for i in range(1, 3005): curr = ls[i] if curr + prev <= v: ans += curr + prev curr = 0 else...
Ralph has a magic field which is divided into n Γ— m blocks. That is to say, there are n rows and m columns on the field. Ralph can put an integer in each block. However, the magic field doesn't always work properly. It works only if the product of integers in each row and each column equals to k, where k is either 1 or...
3
inp = input() (n, m, k) = map(int, inp.split()) if n%2 != m%2 and k == -1: print(0) else: ret = pow(2, (n-1)*(m-1), 10**9+7) print(ret)
There is a river of width n. The left bank of the river is cell 0 and the right bank is cell n + 1 (more formally, the river can be represented as a sequence of n + 2 cells numbered from 0 to n + 1). There are also m wooden platforms on a river, the i-th platform has length c_i (so the i-th platform takes c_i consecuti...
3
import math width , numofplanks , jump = input().split(" ") width = int(width) numofplanks = int(numofplanks) jump = int(jump) planks = [int(planks) for planks in input().split(" ")] #planks = [1 for i in range(1000)] tpl = sum(planks) tjl = width - tpl jumpleft = jump distleft = width manpos = 0 j= 0 k = 0 planksle...
You are given a string s consisting of n lowercase Latin letters. n is even. For each position i (1 ≀ i ≀ n) in string s you are required to change the letter on this position either to the previous letter in alphabetic order or to the next one (letters 'a' and 'z' have only one of these options). Letter in every posi...
3
t=int(input()) while(t): t=t-1 n=int(input()) s=input() c=0 for i in range(n//2): p=abs(ord(s[i])-ord(s[n-1-i])) if s[i]==s[n-1-i]: c=c+1; elif (p==2 ): c=c+1; if c==n/2: print("YES") else: print("NO") ...
You are given n numbers a_1, a_2, …, a_n. Is it possible to arrange them in a circle in such a way that every number is strictly less than the sum of its neighbors? For example, for the array [1, 4, 5, 6, 7, 8], the arrangement on the left is valid, while arrangement on the right is not, as 5β‰₯ 4 + 1 and 8> 1 + 6. <im...
3
# cook your dish here n=int(input()) a=list(map(int,input().split())) a.sort() max1=0 for i in range(n-2): if(a[i]+a[i+1]>max1): max1=a[i]+a[i+1] if(a[n-1]<max1): print("YES") for i in range(n-2): print(a[i],end=" ") print(a[n-1],end=" ") print(a[n-2]) else: print("NO")
Given is an integer x that is greater than or equal to 0, and less than or equal to 1. Output 1 if x is equal to 0, or 0 if x is equal to 1. Constraints * 0 \leq x \leq 1 * x is an integer Input Input is given from Standard Input in the following format: x Output Print 1 if x is equal to 0, or 0 if x is equal ...
3
n=int(input()) print('01'[n!=1])
Emily's birthday is next week and Jack has decided to buy a present for her. He knows she loves books so he goes to the local bookshop, where there are n books on sale from one of m genres. In the bookshop, Jack decides to buy two books of different genres. Based on the genre of books on sale in the shop, find the nu...
3
n,m=input().split() n,m=int(n),int(m) l=[0]*m s=input().split() for i in range(n): l[int(s[i])-1]+=1 r=0 for i in range(m): r+=l[i] p,q=0,0 for i in range(m): p+=l[i] q+=l[i]*(r-p) print(q)
Let's call a string adorable if its letters can be realigned in such a way that they form two consequent groups of equal symbols (note that different groups must contain different symbols). For example, ababa is adorable (you can transform it to aaabb, where the first three letters form a group of a-s and others β€” a gr...
3
# -*- coding: utf - 8 -*- """"""""""""""""""""""""""""""""""""""""""""" | author: mr.math - Hakimov Rahimjon | | e-mail: mr.math0777@gmail.com | | created: 23.03.2018 21:09 | """"""""""""""""""""""""""""""""""""""""""""" # inp = open("input.txt", "r"); input = inp.readline; out = open...
The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, n is always even, and in C2, n is always odd. You are given a regular polygon with 2 β‹… n vertices (it's convex and has equal sides and equal angles) and all its sides have length 1. Let's name it as 2n...
3
import math as jb for i in range (0,int(input())): n=int(input()) if n==2: print(1.000000000) else: print(jb.tan((.5-1/(n*2))*(jb.pi)))
Polycarpus loves hamburgers very much. He especially adores the hamburgers he makes with his own hands. Polycarpus thinks that there are only three decent ingredients to make hamburgers from: a bread, sausage and cheese. He writes down the recipe of his favorite "Le Hamburger de Polycarpus" as a string of letters 'B' (...
3
''' http://codeforces.com/contest/371/problem/C ''' from collections import Counter def calculate_burgers(number_of_burgers, extra_money): needed_ingredients = [0]*3 for ingredients, value in recipe.items(): if ingredients == 'B': needed_ingredients[0] = value * number_of_burgers el...
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...
1
num = raw_input().strip() fours = num.count('4') sevens = num.count('7') total = fours + sevens numbers = set(list(str(total))) if (numbers - {'4','7'}) == set() and '4' in numbers or '7' in numbers: print('YES') else: print('NO')
You are given a string s consisting of the characters 0, 1, and ?. Let's call a string unstable if it consists of the characters 0 and 1 and any two adjacent characters are different (i. e. it has the form 010101... or 101010...). Let's call a string beautiful if it consists of the characters 0, 1, and ?, and you can...
3
t=int(input()) def binary_search(arr, low, high, x): # Check base case if high >= low: mid = (high + low) // 2 # If element is present at the middle itself if arr[mid] == x: return mid # If element is smaller than mid, then it can only # be present in ...
Today Pari and Arya are playing a game called Remainders. Pari chooses two positive integer x and k, and tells Arya k but not x. Arya have to find the value <image>. There are n ancient numbers c1, c2, ..., cn and Pari has to tell Arya <image> if Arya wants. Given k and the ancient values, tell us if Arya has a winnin...
1
MAX = 10 ** 6 + 3 sqMAX = int(MAX ** 0.5) + 1 spf = [i for i in xrange(MAX)] for i in xrange(0, MAX, 2): spf[i] = 2 for i in xrange(3, sqMAX, 2): if spf[i] == i: for j in xrange(i, MAX, i): if spf[j] == j: spf[j] = i n, k = map(int, raw_input().strip().split()) c = map(int, raw_input().strip...
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
n = int(input()) for j in range(n): a = int(input()) mx = 0 c = [int(x) for x in input().split()] fl = False d = {} for i in c: d[i] = d.get(i, 0) + 1 if mx < d[i]: mx = d[i] if mx > len(d): print(len(d)) elif mx == len(d): print(mx - 1) el...
Innokentiy decides to change the password in the social net "Contact!", but he is too lazy to invent a new password by himself. That is why he needs your help. Innokentiy decides that new password should satisfy the following conditions: * the length of the password must be equal to n, * the password should con...
3
import string n,k = map(int,input().split()) alpha = list(string.ascii_lowercase)[0:k:] s = '' cur_alpha = 0 for i in range(n): s += alpha[cur_alpha] cur_alpha = (cur_alpha + 1) % k 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 = list(map(int, input().split())) a = [] for i in range(n): a.append(list(map(int, input().split()))) a = sorted(a) for i in range(len(a)): if a[i][0] < s: s = s + a[i][1] else: print('NO') exit() print('YES')
Long time ago Alex created an interesting problem about parallelogram. The input data for this problem contained four integer points on the Cartesian plane, that defined the set of vertices of some non-degenerate (positive area) parallelogram. Points not necessary were given in the order of clockwise or counterclockwis...
3
(x1, y1) = tuple(map(int, str(input()).split())) (x2, y2) = tuple(map(int, str(input()).split())) (x3, y3) = tuple(map(int, str(input()).split())) a = (x1 + (x3 - x2), y1 + (y3 - y2)) b = (x2 + (x1 - x3), y2 + (y1 - y3)) c = (x3 + (x2 - x1), y3 + (y2 - y1)) print(3) print(a[0], a[1]) print(b[0], b[1]) print(c[0], c[1])
In order to celebrate Twice's 5th anniversary, Tzuyu and Sana decided to play a game. Tzuyu gave Sana two integers a and b and a really important quest. In order to complete the quest, Sana has to output the smallest possible value of (a βŠ• x) + (b βŠ• x) for any given x, where βŠ• denotes the [bitwise XOR operation](http...
3
for tt in range(int(input())): a,b = map(int,input().split()) x = 0 for i in range(31): if (a & (1 << i)) or (b & (1 << i)): x += 2 ** i print((a ^ x) + (b ^ x))
Let's denote correct match equation (we will denote it as CME) an equation a + b = c there all integers a, b and c are greater than zero. For example, equations 2 + 2 = 4 (||+||=||||) and 1 + 2 = 3 (|+||=|||) are CME but equations 1 + 2 = 4 (|+||=||||), 2 + 2 = 3 (||+||=|||), and 0 + 1 = 1 (+|=|) are not. Now, you ha...
3
inp=input li=list iinp=lambda : int(inp()) ent=lambda : map(int,inp().split()) lient=lambda : li(ent()) q=iinp() res=[] for i in range(q): c=iinp() if c==2: res.append(2) else: c-=(c//2)*2 res.append(c) for i in res: print(i)
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()) i=1 while(i <= n): word = input() word_length = len(word) if word_length>10: print(word[0]+str((word_length-2))+word[word_length-1]) else: print(word) i = i+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
n = int(input()) for i in range(n): b=input() if len(b)<=10: print(b) else: print(b[0],len(b)-2,b[len(b)-1],sep='')
Sergey is testing a next-generation processor. Instead of bytes the processor works with memory cells consisting of n bits. These bits are numbered from 1 to n. An integer is stored in the cell in the following way: the least significant bit is stored in the first bit of the cell, the next significant bit is stored in ...
3
n=int(input()) li=list(input()) for i in range(n): if li[i]=="0": print(i+1) exit(0) else: print(n)
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr...
3
a = str(input()) b = str(input()) a = a.lower() b = b.lower() if a < b: print(-1) elif b < a: print(1) elif a == b: print(0)
You may have heard of the pie rule before. It states that if two people wish to fairly share a slice of pie, one person should cut the slice in half, and the other person should choose who gets which slice. Alice and Bob have many slices of pie, and rather than cutting the slices in half, each individual slice will be ...
1
import sys sys.setrecursionlimit(10**9) n = input() arr = map(int,raw_input().strip().split()) dp = [[0,0] for i in range(n)] dp[n-1][1] = arr[i] for i in range(n-2,-1,-1): dp[i][0] = min(dp[i+1][1],dp[i+1][0]+arr[i]) dp[i][1] = max(dp[i+1][1],dp[i+1][0]+arr[i]) bob = max(dp[0][0],dp[0][1]) print sum(arr)-bob,b...
RedDreamer has an array a consisting of n non-negative integers, and an unlucky integer T. Let's denote the misfortune of array b having length m as f(b) β€” the number of pairs of integers (i, j) such that 1 ≀ i < j ≀ m and b_i + b_j = T. RedDreamer has to paint each element of a into one of two colors, white and black...
3
#codeforces div-2 round 668 '''for i in range(int(input())): n=int(input()) arr=[int(i) for i in input().split()] print(*arr[::-1])''' '''for i in range(int(input())): n=int(input()) arr=[int(i) for i in input().split()] run=0 for i in range(n-1,-1,-1): if arr[i]<0: r...
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
def findlen(st): counter = 0 while st[counter:]: counter += 1 return counter for t in range(0, int(input())): i = input() if findlen(i) > 10: print(i[0], findlen(i)-2, i[-1], sep="") else: print(str(i))
There is a tree with N vertices, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N - 1), the i-th edge connects Vertex x_i and y_i. Taro has decided to paint each vertex in white or black. Here, it is not allowed to paint two adjacent vertices both in black. Find the number of ways in which the vertices can be pa...
3
from collections import defaultdict import sys sys.setrecursionlimit(10**6) N = int(input()) g = defaultdict(set) for x, y in [map(int, input().split()) for _ in range(N-1)]: g[x].add(y) g[y].add(x) M = 10**9 + 7 def dfs(u, p): w = 1 b = 1 for v in g[u]: if p == v: contin...
You are given two polynomials: * P(x) = a0Β·xn + a1Β·xn - 1 + ... + an - 1Β·x + an and * Q(x) = b0Β·xm + b1Β·xm - 1 + ... + bm - 1Β·x + bm. Calculate limit <image>. Input The first line contains two space-separated integers n and m (0 ≀ n, m ≀ 100) β€” degrees of polynomials P(x) and Q(x) correspondingly. The seco...
3
from sys import * from bisect import * from collections import * from itertools import * from fractions import * Input = [] #stdin = open('in', 'r') #stdout = open('out', 'w') ## for i, val in enumerate(array, start_i_value) def Out(x): stdout.write(str(x) + '\n') def In(): return stdin.readline().strip() ...
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
#! python3 # HQ9plus.py import re command_string = input() commands = ['H', 'Q', '9', '+'] num_regex = re.compile(r'\d') judge = 'NO' for i in range(len(command_string)): if command_string[i] in commands[:3]: judge = 'YES' break # elif command_string[i] == '+': # if i != len(command_...
This is a harder version of the problem. In this version n ≀ 500 000 The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the compan...
3
def do_solve(ns): n = len(ns) st = [] tot = [] res = [] for i, num in enumerate(ns): while st and ns[st[-1]] >= num: st.pop() tot.pop() pre = 0 if not tot else tot[-1] length = i + 1 if not st else i - st[-1] tot.append(pre + ns[i] * length) ...
Roy is looking for Wobbly Numbers. An N-length wobbly number is of the form "ababababab..." and so on of length N, where a != b. A 3-length wobbly number would be of form "aba". Eg: 101, 121, 131, 252, 646 etc But 111, 222, 999 etc are not 3-length wobbly number, because here a != b condition is not satisfied. ...
1
tc=int(raw_input()) while tc>0: tc=tc-1 N,K=map(int,raw_input().split()) s='' for I in xrange(N): if (I%2)==0: s+='a' else: s+='b' #print s s1=s[:] count=0 for i in xrange(1,10): s=s.replace(s[0],str(i)) for j in xrange(0,10): ...
Fox Ciel and her friends are in a dancing room. There are n boys and m girls here, and they never danced before. There will be some songs, during each song, there must be exactly one boy and one girl are dancing. Besides, there is a special rule: * either the boy in the dancing pair must dance for the first time (so...
1
n, m = map(int, raw_input().split()) print m + n - 1 for i in range(1,m+1): print "1 %d" %i for i in range(2,n+1): print "%d 1" %i
We have A cards, each of which has an integer 1 written on it. Similarly, we also have B cards with 0s and C cards with -1s. We will pick up K among these cards. What is the maximum possible sum of the numbers written on the cards chosen? Constraints * All values in input are integers. * 0 \leq A, B, C * 1 \leq K \l...
3
a, b, c, k = map(int, input().split()) if a+b >= k: print(min(a, k)) else: print(a-(k-a-b))
You are given two arrays of integers a_1,…,a_n and b_1,…,b_m. Your task is to find a non-empty array c_1,…,c_k that is a subsequence of a_1,…,a_n, and also a subsequence of b_1,…,b_m. If there are multiple answers, find one of the smallest possible length. If there are still multiple of the smallest possible length, f...
3
for _ in range(int(input())): a,b = list(map(int,input().split())) arr = set(map(int,input().split())) brr = set(map(int,input().split())) d = arr & brr if len(d) == 0: print('NO') else: d = list(d) print('YES') print(" ".join(['1',str(d[0])]))
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits. Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has on...
3
y=input() a=int(y) for i in range(a+1,9050): if len(set(list(str(i))))==4: print(i) break
In some other world, today is Christmas. Mr. Takaha decides to make a multi-dimensional burger in his party. A level-L burger (L is an integer greater than or equal to 0) is the following thing: * A level-0 burger is a patty. * A level-L burger (L \geq 1) is a bun, a level-(L-1) burger, a patty, another level-(L-1) b...
3
n,x=map(int,input().split()) a,p=[1],[1] for i in range(n): a.append(a[-1]*2+3) p.append(p[-1]*2+1) def f(n,x): if n==0:return+(x>0) elif x<=1+a[n-1]:return f(n-1,x-1) else:return p[n-1]+1+f(n-1,x-2-a[n-1]) print(f(n,x))
You and your friend are playing the game Mortal Kombat XI. You are trying to pass a challenge tower. There are n bosses in this tower, numbered from 1 to n. The type of the i-th boss is a_i. If the i-th boss is easy then its type is a_i = 0, otherwise this boss is hard and its type is a_i = 1. During one session, eith...
3
from sys import stdin,stdout import math from bisect import bisect_right from collections import Counter,deque L=lambda:list(map(int, stdin.readline().strip().split())) M=lambda:map(int, stdin.readline().strip().split()) I=lambda:int(stdin.readline().strip()) S=lambda:stdin.readline().strip() C=lambda:stdin.readline()...
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution....
3
number_of_questions = int(input()) number_of_answers = 0 while number_of_questions>0: if input().split().count('1')>=2: number_of_answers+=1 number_of_questions-=1 print(number_of_answers)
In order to celebrate Twice's 5th anniversary, Tzuyu and Sana decided to play a game. Tzuyu gave Sana two integers a and b and a really important quest. In order to complete the quest, Sana has to output the smallest possible value of (a βŠ• x) + (b βŠ• x) for any given x, where βŠ• denotes the [bitwise XOR operation](http...
3
""" pppppppppppppppppppp ppppp ppppppppppppppppppp ppppppp ppppppppppppppppppppp pppppppp pppppppppppppppppppppp pppppppppppppppppppppppppppppppp pppppppppppppppppppp...
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them. Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain nu...
3
x=input() r=0 w=3 for i in range(len(x)): if x[r:w]=='WUB': x=x.replace(x[r:w],' ') r+=1 w+=1 x=x.strip() print(x)
You are given an array a consisting of n integers. Each a_i is one of the six following numbers: 4, 8, 15, 16, 23, 42. Your task is to remove the minimum number of elements to make this array good. An array of length k is called good if k is divisible by 6 and it is possible to split it into k/6 subsequences 4, 8, 15...
3
import math import bisect import heapq from collections import defaultdict def egcd(a, b): if a == 0: return (b, 0, 1) else: g, x, y = egcd(b % a, a) return (g, y - (b // a) * x, x) def mulinv(b, n): g, x, _ = egcd(b, n) if g == 1: return x % n def isprime(n): f...
Alice and Bob are decorating a Christmas Tree. Alice wants only 3 types of ornaments to be used on the Christmas Tree: yellow, blue and red. They have y yellow ornaments, b blue ornaments and r red ornaments. In Bob's opinion, a Christmas Tree will be beautiful if: * the number of blue ornaments used is greater b...
1
import sys y,b,r=map(int,sys.stdin.readline().split(' ')) if b>=r: b=r-1 if y>=(r-2): print r*3-3 else: print 3*y+3 else: r=b+1 if y>=(b-1): print 3*b else: print 3*y+3
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them. Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain nu...
3
n = input() n = n.split("WUB") for each in n: if each: print(each, end=" ")
Nicholas has an array a that contains n distinct integers from 1 to n. In other words, Nicholas has a permutation of size n. Nicholas want the minimum element (integer 1) and the maximum element (integer n) to be as far as possible from each other. He wants to perform exactly one swap in order to maximize the distance...
3
n = int(input()) a = list(map(int, input().split())) mini = 0 maxi = 0 for i in range(n): if(a[i] < a[mini]): mini = i if(a[i] > a[maxi]): maxi = i dist0 = abs(maxi - mini) dist1 = abs(0 - mini) dist2 = abs(n - 1 - mini) dist3 = abs(0 - maxi) dist4 = abs(n - 1 - maxi) print(max((dist0, dist1, ...
You are given a string s consisting of n lowercase Latin letters. You have to type this string using your keyboard. Initially, you have an empty string. Until you type the whole string, you may perform the following operation: * add a character to the end of the string. Besides, at most once you may perform one...
3
n = int(input()) s = input() anw = n def calc(pos): x = s[:pos] + s[:pos] if x == s[:pos*2]: return 1+n-pos return 1e9 for i in range(n): anw = min(anw, calc(i)) print(anw)
Polycarp has just invented a new binary protocol for data transmission. He is encoding positive integer decimal number to binary string using following algorithm: * Each digit is represented with number of '1' characters equal to the value of that digit (for 0 it is zero ones). * Digits are written one by one in ...
3
n = input() s = input() for item in s.split('0'): item = item.strip() if not len(item): print('0', end='') else: print(len(item), end='')
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point x(x > 0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order ...
3
# import sys # sys.stdin=open('input.in','r') # sys.stdout=open('output.out','w') n=int(input()) k=0 while n>0: if n//5!=0: k+=n//5 n=n%5 elif n//4!=0: k+=n//4 n=n%4 elif n//3!=0: k+=n//3 n=n%3 elif n//2!=0: k+=n//2 n=n%2 else: k+=n//1 n=n%1 print(k)
Dreamoon wants to climb up a stair of n steps. He can climb 1 or 2 steps at each move. Dreamoon wants the number of moves to be a multiple of an integer m. What is the minimal number of moves making him climb to the top of the stairs that satisfies his condition? Input The single line contains two space separated i...
3
n,m = map(int,input().split()) i = n//2 j = n%2 if n<m: print(-1) else: while(i+j)%m !=0: i = i-1 j = j+2 print(i+j)
Consider the set of all nonnegative integers: {0, 1, 2, ...}. Given two integers a and b (1 ≀ a, b ≀ 10^4). We paint all the numbers in increasing number first we paint 0, then we paint 1, then 2 and so on. Each number is painted white or black. We paint a number i according to the following rules: * if i = 0, it ...
3
import math n = int(input()) for i in range(n): x , y = input().split(" ") x = int(x) y = int(y) if math.gcd(x,y) == 1: print("Finite") else: print("Infinite")
When preparing a tournament, Codeforces coordinators try treir best to make the first problem as easy as possible. This time the coordinator had chosen some problem and asked n people about their opinions. Each person answered whether this problem is easy or hard. If at least one of these n people has answered that th...
3
a = int(input()) m = input().split(' ') g = list(m) su = 0 for n in range(len(g)): su += int(g[n]) if su >= 1: print('HARD') else: print('EASY')
In some other world, today is Christmas. Mr. Takaha decides to make a multi-dimensional burger in his party. A level-L burger (L is an integer greater than or equal to 0) is the following thing: * A level-0 burger is a patty. * A level-L burger (L \geq 1) is a bun, a level-(L-1) burger, a patty, another level-(L-1) b...
3
n, x = map(int, input().split()) pate, slice = [1], [1] for _ in range(n + 1): pate.append(2 * pate[-1] + 1) slice.append(2 * slice[-1] + 3) ans = 0 for i in range(n)[::-1]: if x >= slice[i] + 2: ans += pate[i] + 1 x -= slice[i] + 2 elif x < slice[i] + 2: x -= 1 print(ans + (x ...
Dreamoon is a big fan of the Codeforces contests. One day, he claimed that he will collect all the places from 1 to 54 after two more rated contests. It's amazing! Based on this, you come up with the following problem: There is a person who participated in n Codeforces rounds. His place in the first round is a_1, hi...
3
t=int(input()) for i in range(t): n,x=map(int,input().strip().split()) a=list(map(int,input().strip().split())) r=list(sorted(set(a))) for i in range(1,100000): if x==0: break if i in a: continue else: a.append(i) x-=1 a=sorted(...
Polycarp knows that if the sum of the digits of a number is divisible by 3, then the number itself is divisible by 3. He assumes that the numbers, the sum of the digits of which is divisible by 4, are also somewhat interesting. Thus, he considers a positive integer n interesting if its sum of digits is divisible by 4. ...
3
n=int(input()) a=n def sum(n): c=0 while n>0: c+=n%10 n=n//10 return c while True: if sum(a)%4==0: print(a) break else: a+=1
Polycarp urgently needs a shovel! He comes to the shop and chooses an appropriate one. The shovel that Policarp chooses is sold for k burles. Assume that there is an unlimited number of such shovels in the shop. In his pocket Polycarp has an unlimited number of "10-burle coins" and exactly one coin of r burles (1 ≀ r ...
3
def shovel(k,r): count=0 sum=0 while True: sum+=k count+=1 if sum%10==0 or sum%10==r: return count if __name__=='__main__': kr=input().split() k=int(kr[0]) r=int(kr[1]) print(shovel(k,r))
Polycarp urgently needs a shovel! He comes to the shop and chooses an appropriate one. The shovel that Policarp chooses is sold for k burles. Assume that there is an unlimited number of such shovels in the shop. In his pocket Polycarp has an unlimited number of "10-burle coins" and exactly one coin of r burles (1 ≀ r ...
3
# Ammirhossein Alimirzaei # Email: Amirhosseiny76@ayhoo.com # Instagram : Amirhossein_Alimirzaei # Telegram : @HajLorenzo N=list(map(int,input().split())) C=0 PRICE=N[0] for _ in range(10): if (PRICE % 10 == 0) or (PRICE % 10) - N[1]==0: print(_ + 1) exit() PRICE=N[0]*(_+2)
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")". Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≀ li ≀ ri ≀ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of...
3
import sys import math input=sys.stdin.readline s=input().rstrip() n=len(s) q=int(input()) class segTree: def __init__(self): self.a=[0]*(2*n) self.b=[0]*(2*n) self.c=[0]*(2*n) def build(self,arr): for i in range(n): self.a[i+n]=0 self.b[i+n]=1 if arr[i]==...
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." β€” an excerpt from contest rules. A total of n participants took part in the contest (n β‰₯ k), and you already know their scores. Calculate how many ...
3
n, k = map(int, input().split()) Score = list(map(int, input().split())) Advanced = 0 for j in range(len(Score)): if Score[j] > 0 and Score[j] >= Score[k-1]: Advanced += 1 print(Advanced)
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If...
3
s=input() c=1 f=0 for i in range(1,len(s)): if(s[i-1]!=s[i]): c=0 c+=1 if(c>=7): f=1 break if(f==1): print('YES') else: print('NO')
You're given a row with n chairs. We call a seating of people "maximal" if the two following conditions hold: 1. There are no neighbors adjacent to anyone seated. 2. It's impossible to seat one more person without violating the first rule. The seating is given as a string consisting of zeros and ones (0 means...
1
x = int(raw_input()) y = raw_input() forbidden = [0,3,6,7] right = [1,2,4,5] for_dict = {x: 'No' for x in forbidden} for_dict.update({x:'Yes' for x in right}) #print(for_dict) if len(y) == 1: out = 'Yes' if y == '0': out = 'No' elif len(y) == 2: out = for_dict[int(y,2)] else: out = 'Yes' cur = ...
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
# Anuneet Anand T = int(input()) while T: L,R = map(int,input().split()) x = L y = 2*L if y>R: print(-1,-1) else: print(x,y) T = T - 1
Limak is a little polar bear. He loves connecting with other bears via social networks. He has n friends and his relation with the i-th of them is described by a unique integer ti. The bigger this value is, the better the friendship is. No two friends have the same value ti. Spring is starting and the Winter sleep is ...
3
import os import sys import math import heapq from decimal import * from io import BytesIO, IOBase from collections import defaultdict, deque def main(): n,k,q = rm() a = rl() b = [] for i in range(q): c,d=rm() if c==1: d-=1 b.append([a[d],d]) b.sort(...
There is a grid with H horizontal rows and W vertical columns. Let (i, j) denote the square at the i-th row from the top and the j-th column from the left. For each i and j (1 \leq i \leq H, 1 \leq j \leq W), Square (i, j) is described by a character a_{i, j}. If a_{i, j} is `.`, Square (i, j) is an empty square; if a...
3
h, w = map(int, input().split()) a=[ list(input()) for _ in range(h)] mod=int((1e9)+7) dp=[ [0]*w for _ in range(h+1)] dp[0][0]=1 for i in range(1,h+1): dp[i][0]=int(dp[i-1][0]==1)*int(a[i-1][0]=='.') for j in range(1,w): dp[i][j]=(dp[i-1][j]+dp[i][j-1])*int(not a[i-1][j]=='#') % mod print(dp[-1][-1])
Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor Β«TextpadΒ» decided to introduce this functionality into the fourth release of the product. You are to implement the alignment in the shortest possible time. Good luck! Input The input file c...
1
import sys f = sys.stdin width = 0 l = list() for line in f: l.append(line[:-1]) width = max(width, len(line[:-1])) print '*' * (width + 2) flag = 0 for s in l: indent = width - len(s) if indent % 2: indent = indent / 2 + flag flag = 1 - flag e...
You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum: <image> Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p). Input The single line of input contains two integers n and m (1 ≀ m ≀ cntn), where cntn...
1
import itertools n,m = map(int,raw_input().split()) a = [i+1 for i in xrange(n)] permut = list(itertools.permutations(a)) fp = [0 for i in xrange(len(permut))] for i in range(len(permut)): for j in range(n): for k in range(j,n): fp[i] += min(permut[i][j:(k+1)]) mxm = max(fp) ok = False refine = ...
It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices. It is known that the i-th contestant will eat si slices of pizza, and gain ai ...
1
n,s = map(int, raw_input().split()) a,b,c,d = [],[],[],[] ng,ps,zr = 0,0,0 nga,ngb,ngc = [],[],[] for i in range(n): x,y,z = map(int, raw_input().split()) a.append(x) b.append(y) c.append(z) d.append((y-z,x,y,z)) if y-z<0: ng+=x nga.append((-(y-z),x,z,y)) if y-z>0: ps+=x ngb.append((y-z,x,y,z)) if y-z==...
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
1
x = input() print (1 if x%2 else 0)