problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
Iahub isn't well prepared on geometry problems, but he heard that this year there will be a lot of geometry problems on the IOI selection camp. Scared, Iahub locked himself in the basement and started thinking of new problems of this kind. One of them is the following.
Iahub wants to draw n distinct points and m segme... | 3 | import sys
read = lambda t=int:list(map(t,sys.stdin.readline().split()))
_, M = read()
xs = read()
for _ in range(M):
_ = read()
xs = sorted((x,i) for i,x in enumerate(xs))
xs = sorted((i,j) for j,(x,i) in enumerate(xs))
print(" ".join(str(j%2) for _,j in xs))
|
After the contest in comparing numbers, Shapur's teacher found out that he is a real genius and that no one could possibly do the calculations faster than him even using a super computer!
Some days before the contest, the teacher took a very simple-looking exam and all his n students took part in the exam. The teacher... | 1 | import string
import sys
s = []
s2 = []
for i in range(0, 3):
buf = raw_input().translate(string.maketrans('', ''), '-;_').lower()
s.append(buf)
n = int(raw_input())
for i in range(0, 3):
for j in range(0, 3):
if i is j:
continue
for k in range(0, 3):
if i is k or j is k:
continue
s2.append(s[i]+s[... |
For a given array a consisting of n integers and a given integer m find if it is possible to reorder elements of the array a in such a way that ∑_{i=1}^{n}{∑_{j=i}^{n}{(a_j)/(j)}} equals m? It is forbidden to delete elements as well as insert new elements. Please note that no rounding occurs during division, for exampl... | 3 | for i in range(int(input())):
n, k = map(int, input().split())
ans = list(map(int, input().split()))
print(('YES', 'NO')[sum(ans) != k])
|
Vasya is a school PE teacher. Unlike other PE teachers, Vasya doesn't like it when the students stand in line according to their height. Instead, he demands that the children stand in the following order: a1, a2, ..., an, where ai is the height of the i-th student in the line and n is the number of students in the line... | 3 | n = int(input())
start = []
end = []
s1 = input().split(' ')
s2 = input().split(' ')
for i in range(n):
start.append(int(s1[i]))
end.append(int(s2[i]))
q = 0
string = ""
for i in range(n):
if start[i]!=end[i]:
for j in range(i+1, n):
if end[j]==start[i]:
for k in range(... |
When registering in a social network, users are allowed to create their own convenient login to make it easier to share contacts, print it on business cards, etc.
Login is an arbitrary sequence of lower and uppercase latin letters, digits and underline symbols («_»). However, in order to decrease the number of frauds ... | 3 | s = list(input())
n = int(input())
lst = []
for i in range(n):
lst.append(list(input()))
def change(elem):
if elem in {'1', 'i', 'I', 'l', 'L'}:
elem = '['
elif elem in {'0', 'o', 'O'}:
elem = ']'
else:
elem = elem.upper()
return elem
def check(one, two):
if len(on... |
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 | s = list(input().lower())
gl = ["a", "o", "y", "e", "u", "i"]
s_new = []
for i in s:
if i not in gl:
s_new.append(i)
print('.'+'.'.join(s_new)) |
It was decided in IT City to distinguish successes of local IT companies by awards in the form of stars covered with gold from one side. To order the stars it is necessary to estimate order cost that depends on the area of gold-plating. Write a program that can calculate the area of a star.
A "star" figure having n ≥ ... | 3 | from math import *
N, R = map(int, input().split())
def get(i):
theta = 2 * pi / N * i
return R * cos(theta), R * sin(theta)
def line(p, q):
m = (q[1] - p[1]) / (q[0] - p[0])
b = p[1] - m * p[0]
return (m, b)
def intersect(l1, l2):
x = (l1[1] - l2[1]) / (l2[0] - l1[0])
y = l1[0] * x + l1... |
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())
s = 0
for i in range(n):
x = input().split()
m = map(int, x)
if sum(m) >= 2:
s += 1
print(s) |
A positive integer number n is written on a blackboard. It consists of not more than 105 digits. You have to transform it into a beautiful number by erasing some of the digits, and you want to erase as few digits as possible.
The number is called beautiful if it consists of at least one digit, doesn't have leading zer... | 3 | s=input()
n=len(s)
dp,leadingzero,camefrom,erasepos=[],0,[],[]
for i in range(3):
dp.append([int(1e9)]*(n+1))
camefrom.append([int(-1)]*(n+1))
dp[0][n]=0
#delete one number
for i in range(n-1,-1,-1):
for j in range(3):
dp[j][i]=min(dp[j][i],min(1+dp[j][i+1],dp[(int(j)-int(s[i]))%3][i+1]))
#... |
Luba thinks about watering her garden. The garden can be represented as a segment of length k. Luba has got n buckets, the i-th bucket allows her to water some continuous subsegment of garden of length exactly ai each hour. Luba can't water any parts of the garden that were already watered, also she can't water the gro... | 3 |
number_of_buckets, length = map(int, input().split(' '))
buckets = list(map(int, input().split(' ')))
buckets = sorted(buckets, reverse=True)
for i in range(0, len(buckets)):
if length% buckets[i] == 0:
print(length // buckets[i])
break |
You are playing one RPG from the 2010s. You are planning to raise your smithing skill, so you need as many resources as possible. So how to get resources? By stealing, of course.
You decided to rob a town's blacksmith and you take a follower with you. You can carry at most p units and your follower — at most f units.
... | 3 | import sys
input = sys.stdin.buffer.readline
T = int(input())
for testcase in range(T):
p,f = map(int,input().split())
Cs,Cw = map(int,input().split())
s,w = map(int,input().split())
if s > w:
s,w = w,s
Cs,Cw = Cw,Cs
res = 0
for i in range(Cs+1):
if i*s > p:
... |
You are given two integers a and b.
In one move, you can choose some integer k from 1 to 10 and add it to a or subtract it from a. In other words, you choose an integer k ∈ [1; 10] and perform a := a + k or a := a - k. You may use different values of k in different moves.
Your task is to find the minimum number of mo... | 3 | for _ in range(int(input())) :
a , b = map(int , input().split())
if a== b :
print(0)
elif a%2 == 0 and b%2 == 0 :
if a < b :
print(2)
else :
print(1)
elif a%2 == 1 and b%2 == 0 :
if a< b :
print(1)
else:
print(2)
... |
There are N robots numbered 1 to N placed on a number line. Robot i is placed at coordinate X_i. When activated, it will travel the distance of D_i in the positive direction, and then it will be removed from the number line. All the robots move at the same speed, and their sizes are ignorable.
Takahashi, who is a misc... | 3 | def main():
n = int(input())
xd = [map(int, input().split()) for _ in range(n)]
mod = 998244353
INF = 10 ** 10
xx = [(x, x + d, i) for i, (x, d) in enumerate(xd, 1)]
xx.sort()
adj = [[] for _ in range(n + 1)]
stack = [(INF, 0)]
for l, r, i in xx:
while stack[-1][0] <= l:
... |
You are given a string s=s_1s_2... s_n of length n, which only contains digits 1, 2, ..., 9.
A substring s[l ... r] of s is a string s_l s_{l + 1} s_{l + 2} … s_r. A substring s[l ... r] of s is called even if the number represented by it is even.
Find the number of even substrings of s. Note, that even if some subs... | 3 | hm = int(input())
s = input()
c = 0
for i in range(hm):
if int(s[i])%2==0:
c+=(i+1)
print(c) |
Problem description
You will be given a zero-indexed array A. You need to rearrange its elements in such a way that the following conditions are satisfied:
A[i] ≤ A[i+1] if i is even.
A[i] ≥ A[i+1] if i is odd.
In other words the following inequality should hold: A[0] ≤ A[1] ≥ A[2] ≤ A[3] ≥ A[4], and so on. Operation... | 1 | from sys import stdin,exit
if __name__ == "__main__":
t = input()
while t:
n = map(int,stdin.readline().split())[0]
a = sorted(map(int,stdin.readline().split()))
a_f = a[:n/2]
a_s = a[n/2:]
#print a_f,a_s
if n % 2:
for i in xrange(n/2):
print a_f[i],a_s[-1-i],
print a_s[0]
else:
for i i... |
You are given a permutation p=[p_1, p_2, …, p_n] of integers from 1 to n. Let's call the number m (1 ≤ m ≤ n) beautiful, if there exists two indices l, r (1 ≤ l ≤ r ≤ n), such that the numbers [p_l, p_{l+1}, …, p_r] is a permutation of numbers 1, 2, …, m.
For example, let p = [4, 5, 1, 3, 2, 6]. In this case, the numb... | 3 | for step in range(int(input())):
n=int(input())
A=[int(i) for i in input().split()]
index=[0]*(n+1)
for i in range(n):
index[A[i]]=i
Ans=""
pos_min=index[1]
pos_max=index[1]
for i in range(1,n+1):
pos_m=index[i]
pos_min=min(pos_min, pos_m)
pos_max=max(pos_... |
Find the minimum area of a square land on which you can place two identical rectangular a × b houses. The sides of the houses should be parallel to the sides of the desired square land.
Formally,
* You are given two identical rectangles with side lengths a and b (1 ≤ a, b ≤ 100) — positive integers (you are given ... | 3 |
# from math import factorial as fac
from collections import defaultdict
# from copy import deepcopy
import sys, math
f = None
try:
f = open('q1.input', 'r')
except IOError:
f = sys.stdin
if 'xrange' in dir(__builtins__):
range = xrange
# print(f.readline())
# sys.setrecursionlimit(10**5)
def print_case_iterable... |
Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone.
In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules o... | 3 | a,b,c,d=map(int,input().split())
s=input()
k=0
for i in s:
if i=='1':k+=a
elif i=='2':k+=b
elif i=='3':k+=c
else:k+=d
print(k) |
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.
Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, seco... | 1 | a,b,c,d,e,f,s=input(),'I','hate','love','that','it',' '
z=[]
if 1<=a<=100:
for x in xrange(1,a+1):
if x%2!=0:
z+=b+s+c
if x==a:z+=s+f
else:
z+=s+e+s+b+s+d
if x==a:z+=s+f
else:z+=s+e+s
print ''.join(z)
|
You are given an integer n. In one move, you can either multiply n by two or divide n by 6 (if it is divisible by 6 without the remainder).
Your task is to find the minimum number of moves needed to obtain 1 from n or determine if it's impossible to do that.
You have to answer t independent test cases.
Input
The fi... | 1 |
from __future__ import division
import sys
input = sys.stdin.readline
import math
from math import sqrt, floor, ceil
from collections import Counter
############ ---- Input Functions ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input... |
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 ... | 1 | import math
str1 = int(raw_input())
def isPrime(n):
if n < 2:
return False
sq = int(math.sqrt(n)+1)
for i in range(2, sq):
if n % i == 0:
return False
return True
for i in range(3, str1):
x = i
y = str1 - i
if not isPrime(x) and not isPrime(y):
print '... |
Two players decided to play one interesting card game.
There is a deck of n cards, with values from 1 to n. The values of cards are pairwise different (this means that no two different cards have equal values). At the beginning of the game, the deck is completely distributed between players such that each player has a... | 3 | for _ in range(int(input())):
n, k1, k2 = map(int, input().split())
arr1 = [*map(int, input().split())]
arr2 = [*map(int, input().split())]
print("YES" if max(arr1) > max(arr2) else "NO") |
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 |
l = list(map(int, input().split()))
su = 0
final = []
lp = list(map(int, input().split()))
for i in range(l[0]):
li = []
su = 0
n = 0
for j in range(i+1):
su += lp[j]
if su <= l[1]:
final.append(n)
else:
for j in range(i):
li.append(lp[j])
li.sort(reverse = True)
while su > l[1]:
su -= li[0]
... |
An array of integers p_1, p_2, ..., p_n is called a permutation if it contains each number from 1 to n exactly once. For example, the following arrays are permutations: [3, 1, 2], [1], [1, 2, 3, 4, 5] and [4, 3, 1, 2]. The following arrays are not permutations: [2], [1, 1], [2, 3, 4].
Polycarp invented a really cool p... | 3 | from collections import *
n = int(input())
a = list(map(int,input().split()))
m = 0
p = 0
for i in range(n-2,-1,-1):
p += a[i]
m = min(m,p)
ans = [0 for i in range(n)]
ans[-1] = n+m
p = 0
for i in range(n-2,-1,-1):
p += a[i]
ans[i] = ans[-1]-p
vis = [0 for i in range(n+1)]
for i in range(n):
if(ans[i] < 1 or ans[i... |
There are n districts in the town, the i-th district belongs to the a_i-th bandit gang. Initially, no districts are connected to each other.
You are the mayor of the city and want to build n-1 two-way roads to connect all districts (two districts can be connected directly or through other connected districts).
If two... | 3 | for _ in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
if len(set(a))==1:
print("NO")
else:
print("YES")
k=a[0]
for i in range(n):
if a[i]!=k:
k1=a[i]
pos=i
break
for i in range(1,n... |
One day, the Grasshopper was jumping on the lawn and found a piece of paper with a string. Grasshopper became interested what is the minimum jump ability he should have in order to be able to reach the far end of the string, jumping only on vowels of the English alphabet. Jump ability is the maximum possible length of ... | 3 | s = input()
curr = -1
vow = ['A', 'E', 'I', 'O', 'U', 'Y']
mn = 0
i = 0
l = len(s)
while i < l:
if s[i] in vow:
if i - curr > mn:
mn = i - curr
curr = i
i += 1
mn = max(mn, l - curr)
print(mn)
|
You have unlimited number of coins with values 1, 2, …, n. You want to select some set of coins having the total value of S.
It is allowed to have multiple coins with the same value in the set. What is the minimum number of coins required to get sum S?
Input
The only line of the input contains two integers n and S ... | 3 | s=input()
s=s.split(" ")
result=((int(s[0])+int(s[1])-1)//int(s[0]))
print(result)
|
Chef is playing a game on a sequence of N positive integers, say A1, A2, ... AN. The game is played as follows.
If all the numbers are equal, the game ends.
Otherwise
Select two numbers which are unequal
Subtract the smaller number from the larger number
Replace the larger number with the result from above (see the e... | 1 | t=int(raw_input())
def gcd(a,b):
if a==0:
return b
return gcd(b%a,a)
while t>0:
t-=1
n=int(raw_input())
a=map(int,raw_input().split())
b=gcd(a[0],a[1])
if n>2:
for i in range(2,n):
b=gcd(b,a[i])
print b |
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.
The language is that peculiar as it has exactly one variable, called x. Also, there are two operations:
* Operation ++ increases the value of variable x by 1.
* Operation -- decreases the value of variable x by 1.... | 3 | r=0
t = int(input())
for _ in range(t):
s = input()
if "+" in s:
r+=1
else:
r-=1
print(r) |
An integer X is called a Harshad number if X is divisible by f(X), where f(X) is the sum of the digits in X when written in base 10.
Given an integer N, determine whether it is a Harshad number.
Constraints
* 1?N?10^8
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output... | 3 | N=input()
print(['Yes','No'][int(N)%sum(map(int,N))>0]) |
You are given two n × m matrices containing integers. A sequence of integers is strictly increasing if each next number is greater than the previous one. A row is strictly increasing if all numbers from left to right are strictly increasing. A column is strictly increasing if all numbers from top to bottom are strictly... | 3 | from sys import stdin
from math import gcd,sqrt
from collections import deque
input=stdin.readline
R=lambda:map(int,input().split())
I=lambda:int(input())
S=lambda:input().rstrip('\n')
hg=lambda x,y:((y+x-1)//x)*x
chk=lambda r,c:True if a[r][c]>=a[r+1][c]<=b[r][c] or a[r][c]>=b[r+1][c]<=b[r][c] or a[r][c]>=a[r][c+1]<=b... |
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.
Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with number... | 3 | from bisect import bisect_left
n=int(input())
ai=[int(x) for x in input().split()]
m=int(input())
mi=[int(x) for x in input().split()]
for i in range(1,n):
ai[i]=ai[i-1]+ai[i]
def getPile(m):
low=0
high=n-1
while low<=high:
mid=(low+high)//2
if m<ai[mid]:
high=mid-1
elif m>ai[mid]:
lo... |
The recent All-Berland Olympiad in Informatics featured n participants with each scoring a certain amount of points.
As the head of the programming committee, you are to determine the set of participants to be awarded with diplomas with respect to the following criteria:
* At least one participant should get a dip... | 3 | import sys,math
input=sys.stdin.readline
L=lambda : list(map(int,input().split()))
M=lambda : map(int,input().split())
n=int(input())
l=L()
l=list(set(l))
print(len(l)-l.count(0))
|
Your favorite shop sells n Kinder Surprise chocolate eggs. You know that exactly s stickers and exactly t toys are placed in n eggs in total.
Each Kinder Surprise can be one of three types:
* it can contain a single sticker and no toy;
* it can contain a single toy and no sticker;
* it can contain both a sing... | 3 | T = int(input())
for i in range(T):
n, s, t = map(int, input().split(' '))
sticker = n-t
toy = n-s
sticker_toy = s-n+t
if(sticker==0 and toy==0):
print(1)
else:
print(max(sticker,toy)+1)
|
DZY has a hash table with p buckets, numbered from 0 to p - 1. He wants to insert n numbers, in the order they are given, into the hash table. For the i-th number xi, DZY will put it into the bucket numbered h(xi), where h(x) is the hash function. In this problem we will assume, that h(x) = x mod p. Operation a mod b d... | 1 | def fun():
p,n = map(int,raw_input().split())
h = [0]*p
for i in xrange(n):
a = input()
if h[a%p]:
return i+1
else:
h[a%p] = 1
return -1
print fun()
|
There are 2N squares arranged from left to right. You are given a string of length 2N representing the color of each of the squares.
The color of the i-th square from the left is black if the i-th character of S is `B`, and white if that character is `W`.
You will perform the following operation exactly N times: choo... | 3 | import sys
n=int(input())
s=input()
MOD=10**9+7
if s[0]=='W' or s[-1]=='W':
print(0)
sys.exit()
a=[-1]*(2*n)
current=1
for i in range(2*n-1):
a[i]=current
if s[i]==s[i+1]:
current=1-current
if current==1:
print(0)
sys.exit()
a[2*n-1]=0
if sum(a)!=n:
print(0)
sys.exit()
ans=1
current=0
for i in range... |
Little Sofia is in fourth grade. Today in the geometry lesson she learned about segments and squares. On the way home, she decided to draw n squares in the snow with a side length of 1. For simplicity, we assume that Sofia lives on a plane and can draw only segments of length 1, parallel to the coordinate axes, with ve... | 3 | import math
c=int(input())
b=int(math.sqrt(c))
if c==b*b:
print(2*b)
elif c<=b*(b+1):
print(b+b+1)
else :print(b+b+2)
|
Give a pair of integers (A, B) such that A^5-B^5 = X. It is guaranteed that there exists such a pair for the given integer X.
Constraints
* 1 \leq X \leq 10^9
* X is an integer.
* There exists a pair of integers (A, B) satisfying the condition in Problem Statement.
Input
Input is given from Standard Input in the fo... | 3 | x=int(input())
[i**5-x-j**5or print(i,j)+exit()for i in range(200)for j in range(-i,i)] |
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 | def s(x):
summ = 0
for i in str(x):
summ += int(i)
return summ
n, m = map(int, input().split())
if m == 0:
print('0')
print('0')
exit()
cnt = 1499
a = '5' * 1500
b = '4' * cnt + '5' * (1500 - cnt)
while s(int(a) + int(b)) > m:
cnt -= 1
b = '4' * cnt + '5'
print(a)
print(b) |
Alicia has an array, a_1, a_2, …, a_n, of non-negative integers. For each 1 ≤ i ≤ n, she has found a non-negative integer x_i = max(0, a_1, …, a_{i-1}). Note that for i=1, x_i = 0.
For example, if Alicia had the array a = \{0, 1, 2, 0, 3\}, then x = \{0, 0, 1, 2, 2\}.
Then, she calculated an array, b_1, b_2, …, b_n: ... | 3 | from sys import stdin
inf=stdin
#inf=open("data1.txt",'rt')
n=int(inf.readline())
arr=list(map(int,inf.readline().split(" ")))
ans=[0]*(n)
ans[0]=arr[0]
x=0
for i in range(1,n):
x=max(ans[i-1],x)
ans[i]=(arr[i]+x)
print(*ans)
# for i in dicti:
# temp=0
# for j in helper:
# if(j[0]<=i[0] and j[1]<=i[1]):
# ... |
Amugae has a hotel consisting of 10 rooms. The rooms are numbered from 0 to 9 from left to right.
The hotel has two entrances — one from the left end, and another from the right end. When a customer arrives to the hotel through the left entrance, they are assigned to an empty room closest to the left entrance. Similar... | 3 | n = int(input())
roomset = list(input())
hotel = [0] * 10
for i in roomset:
if i == 'L':
k = 0
while hotel[k] == 1:
k += 1
hotel[k] = 1
elif i == 'R':
k = 9
while hotel[k] == 1:
k -= 1
hotel[k] = 1
else:
hotel[int(i)] = 0
sol =... |
Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone.
In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules o... | 3 | pt=list(map(int,input().split()))
s=input()
sum=0
for i in range(len(s)):
sum=sum+pt[int(s[i])-1]
print(sum)
|
Let's call a positive integer composite if it has at least one divisor other than 1 and itself. For example:
* the following numbers are composite: 1024, 4, 6, 9;
* the following numbers are not composite: 13, 1, 2, 3, 37.
You are given a positive integer n. Find two composite integers a,b such that a-b=n.
I... | 3 | n = int(input())
if n == 1:
print(21, 20)
else:
print(3*n, 2*n) |
You are given a bracket sequence s of length n, where n is even (divisible by two). The string s consists of n/2 opening brackets '(' and n/2 closing brackets ')'.
In one move, you can choose exactly one bracket and move it to the beginning of the string or to the end of the string (i.e. you choose some index i, remov... | 3 | t=int(input())
while t>0:
t-=1
n=int(input())
s=input()
c=0
d=0
ans=0
for i in range(len(s)):
if s[i]=='(':
c+=1
elif s[i]==')':
if c<=d:
ans+=1
else:
d+=1
print(ans)
|
Vladik and Chloe decided to determine who of them is better at math. Vladik claimed that for any positive integer n he can represent fraction <image> as a sum of three distinct positive fractions in form <image>.
Help Vladik with that, i.e for a given n find three distinct positive integers x, y and z such that <image... | 3 | n = int(input())
if n == 1:
print(-1)
exit()
print(n, n + 1, n * n + n) |
Pikachu had an array with him. He wrote down all the non-empty subsequences of the array on paper. Note that an array of size n has 2n - 1 non-empty subsequences in it.
Pikachu being mischievous as he always is, removed all the subsequences in which Maximum_element_of_the_subsequence - Minimum_element_of_subsequence... | 3 | #!/usr/bin/python3
x, d = map(int, input().split())
ans = []
cur = 1
while x > 0:
k = 1
while (2 ** k) - 1 <= x:
k += 1
k -= 1
for i in range(k):
ans.append(cur)
x -= (2 ** k) - 1
cur += d
print(len(ans))
print(*ans)
|
Orac is studying number theory, and he is interested in the properties of divisors.
For two positive integers a and b, a is a divisor of b if and only if there exists an integer c, such that a⋅ c=b.
For n ≥ 2, we will denote as f(n) the smallest positive divisor of n, except 1.
For example, f(7)=7,f(10)=2,f(35)=5.
... | 3 | import math
t = int(input())
for _ in range(t):
n,k = map(int, input().split())
num = -1
for i in range(2,math.ceil(math.sqrt(n))+1):
if(n%i == 0):
num = i
break
k -= 1
if(num == -1):
num = n
# print(num)
n = n+num
q = k*2
print(n+q)
|
The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her n students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often oddl... | 1 | #to be optimized
case1=raw_input()
case2=raw_input()
l=[]
n,m=case1.split()
n=int(n)
m=int(m)
s=case2.split()
s=[int(x) for x in s]
s=sorted(s)
if m==n:
dif=s[n-1]-s[0]
l.append(dif)
else:
for i in range (m-n+1):
dif=s[i+n-1]-s[i]
l.append(dif)
ans=min(l)
print ans
|
Write a program which reads a sequence of integers $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and reverse specified elements by a list of the following operation:
* reverse($b, e$): reverse the order of $a_b, a_{b+1}, ..., a_{e-1}$
Constraints
* $1 \leq n \leq 1,000$
* $-1,000,000,000 \leq a_i \leq 1,000,000,000$
* $1 \leq ... | 3 | n=int(input())
a=list(map(int,input().split( )))
q=int(input())
for i in range(q):
b,e=map(int,input().split( ))
tmp=[]
for j in range((e-b)//2):
a[b+j],a[e-j-1]=a[e-j-1],a[b+j]
print(*a)
|
Ternary numeric notation is quite popular in Berland. To telegraph the ternary number the Borze alphabet is used. Digit 0 is transmitted as «.», 1 as «-.» and 2 as «--». You are to decode the Borze code, i.e. to find out the ternary number given its representation in Borze alphabet.
Input
The first line contains a nu... | 3 | s = str(input())
ans=""
i=0
while i < len(s):
if s[i]=='.':
ans=ans+"0"
elif s[i]=='-':
i = i + 1
if s[i]=='.':
ans=ans+"1"
elif s[i]=='-':
ans=ans+"2"
i = i + 1
print(ans)
|
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line.
Unfortunately, from time to ti... | 3 | a=input()
t=list(a)
if(len(t)>2):
t.remove(t[0])
l=len(t)
t.remove(t[l-1])
b=''.join(t)
list=b.split(', ')
li=[]
for i in list:
li.append(i)
print(len(set(li)))
else:
print(0) |
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N), the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to Stone i + 1 or Stone i + 2. Here, a cost of |... | 1 | from sys import maxint
N = input()
stones = map(int,raw_input().split())
costs = [maxint] * N
costs[0] = 0
for n in range(N) :
if n+1 < N : costs[n+1] = min(costs[n+1], costs[n] + abs(stones[n]-stones[n+1]))
if n+2 < N : costs[n+2] = min(costs[n+2], costs[n] + abs(stones[n]-stones[n+2]))
print costs[-1] |
Once upon a time a child got a test consisting of multiple-choice questions as homework. A multiple-choice question consists of four choices: A, B, C and D. Each choice has a description, and the child should find out the only one that is correct.
Fortunately the child knows how to solve such complicated test. The chi... | 3 | if __name__ == '__main__':
lines = list()
for i in range(4):
lines.append([len(str(input())) - 2, i])
lines.sort(key=lambda x: x[0])
values = list()
if lines[0][0] * 2 <= lines[1][0]:
values.append(lines[0][1])
if lines[2][0] * 2 <= lines[3][0]:
values.append(lines[3][1])... |
Given any integer x, Aoki can do the operation below.
Operation: Replace x with the absolute difference of x and K.
You are given the initial value of an integer N. Find the minimum possible value taken by N after Aoki does the operation zero or more times.
Constraints
* 0 ≤ N ≤ 10^{18}
* 1 ≤ K ≤ 10^{18}
* All valu... | 3 | N, K = map(int, input().split())
print(min(-N%K, N%K)) |
You are given a positive integer n, it is guaranteed that n is even (i.e. divisible by 2).
You want to construct the array a of length n such that:
* The first n/2 elements of a are even (divisible by 2);
* the second n/2 elements of a are odd (not divisible by 2);
* all elements of a are distinct and positi... | 3 | for i in range(int(input())):
number = int(input())
if number%4!= 0:
print("NO")
else:
print("YES")
for x in range(2,number+1,2):
print(x,end=" ")
for y in range(1,number-2,2):
print(y,end = " ")
print(number+number//2-1)
|
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 | import math
с = int(input())
numbers = list(map(int, input().split()))
PRIME_COUNT = 10 ** 6
is_prime = [True] * PRIME_COUNT
is_prime[0] = False
is_prime[1] = False
primes = []
for i in range(2, 1000):
if is_prime[i]:
for j in range(i * i, PRIME_COUNT, i):
is_prime[j] = False
for elem in number... |
We say that a odd number N is similar to 2017 when both N and (N+1)/2 are prime.
You are given Q queries.
In the i-th query, given two odd numbers l_i and r_i, find the number of odd numbers x similar to 2017 such that l_i ≤ x ≤ r_i.
Constraints
* 1≤Q≤10^5
* 1≤l_i≤r_i≤10^5
* l_i and r_i are odd.
* All input values ... | 3 | import sys
input = sys.stdin.readline
q = int(input())
fact = [1]*(10**5+7)
fa_sum = [0]*(10**5+7)
fact[0] = 0
fact[1] = 0
for i in range(2,10**5+7):
if fact[i]:
for j in range(i*2,10**5+7,i):
fact[j] = 0
if fact[i] and fact[(i+1)//2]:
fa_sum[i] = fa_sum[i-1] + 1
else:
fa_sum[i] = fa_sum[i-1]
... |
Toad Zitz has an array of integers, each integer is between 0 and m-1 inclusive. The integers are a_1, a_2, …, a_n.
In one operation Zitz can choose an integer k and k indices i_1, i_2, …, i_k such that 1 ≤ i_1 < i_2 < … < i_k ≤ n. He should then change a_{i_j} to ((a_{i_j}+1) mod m) for each chosen integer i_j. The i... | 3 | import sys
import math as mt
input=sys.stdin.buffer.readline
t=1
def check(x1):
prev=0
#print(x1,m)
for i in range(n):
#print(111,prev,i,arr[i],)
if arr[i]>prev:
x=m-(arr[i]-prev)
if x>x1:
prev=arr[i]
if arr[i]<prev:
x=(prev-arr[i... |
The whole world got obsessed with robots,and to keep pace with the progress, great Berland's programmer Draude decided to build his own robot. He was working hard at the robot. He taught it to walk the shortest path from one point to another, to record all its movements, but like in many Draude's programs, there was a ... | 3 | from collections import Counter
i, j, p, s = 0, 0, {(0, 0)}, input()
for ch in s:
i += [0, 0, -1, 1]['LRUD'.index(ch)]
j += [-1, 1, 0, 0]['LRUD'.index(ch)]
p.add((i, j))
c = Counter(((x-1,y) in p)+((x+1,y) in p)+((x,y-1) in p)+((x,y+1) in p) for x,y in p)
print('OK' if c[1] == 2 and c[2] == len(s) - 1 else ... |
Vasya has his favourite number n. He wants to split it to some non-zero digits. It means, that he wants to choose some digits d_1, d_2, …, d_k, such that 1 ≤ d_i ≤ 9 for all i and d_1 + d_2 + … + d_k = n.
Vasya likes beauty in everything, so he wants to find any solution with the minimal possible number of different d... | 1 | m = int(input())
print(m)
print(' '.join(['1' for i in range(m)])) |
There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane.
Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0, y0). In one shot it can can ... | 3 | n, x0, y0 = map(int, input().split())
s = set()
for _ in range(n):
x, y = map(int, input().split())
if x == x0:
s.add(float('inf'))
else:
s.add((y - y0) / (x - x0))
print(len(s)) |
There are N cities on a number line. The i-th city is located at coordinate x_i.
Your objective is to visit all these cities at least once.
In order to do so, you will first set a positive integer D.
Then, you will depart from coordinate X and perform Move 1 and Move 2 below, as many times as you like:
* Move 1: tr... | 3 | from fractions import gcd
n,d=map(int,input().split())
x=sorted(list(map(int,input().split()))+[d])
r=x[1]-x[0]
for i in range(n):
r=gcd(x[i+1]-x[i],r)
print(r) |
You a captain of a ship. Initially you are standing in a point (x_1, y_1) (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point (x_2, y_2).
You know the weather forecast — the string s of length n, consisting only of letters U, D, L and R. The letter corresponds t... | 3 | def inpl(): return list(map(int, input().split()))
def mhd(a, b):
return abs(a) + abs(b)
dx, dy = [j - i for i, j in zip(inpl(), inpl())]
N = int(input())
Di = {'U': (0, 1), 'D': (0, -1), 'R': (1, 0), 'L': (-1, 0)}
Wind = [(0, 0)]
for s in input():
nx, ny = Wind[-1]
x, y = Di[s]
Wind.append((nx+x, ny+y... |
In order to pass the entrance examination tomorrow, Taro has to study for T more hours.
Fortunately, he can leap to World B where time passes X times as fast as it does in our world (World A).
While (X \times t) hours pass in World B, t hours pass in World A.
How many hours will pass in World A while Taro studies fo... | 3 | T,X = (map(int, input().split()))
print(T/X) |
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 | n = int(input())
ans = 0
while n > 0:
for i in range(0, 100):
if 2 * (2 ** i) > n:
ans+=1
n -= (2 ** i)
break
print(ans) |
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them.
Input
The first line contains integ... | 3 | n=int(input())
s=str(input())
s2=s
ncount=0
for i in range(n-1):
if s[i]==s[i+1]:
s=s[:i]+" "+s[i+1:]
ncount+=1
s3=s.replace(" ",'')
print(ncount)
#print(s3)
#print(s2)
|
You are given a rectangular board of M × N squares. Also you are given an unlimited number of standard domino pieces of 2 × 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squa... | 1 | M, N = [int(num) for num in raw_input().split()]
print (M * N) / 2 |
There are n students in the first grade of Nlogonia high school. The principal wishes to split the students into two classrooms (each student must be in exactly one of the classrooms). Two distinct students whose name starts with the same letter will be chatty if they are put in the same classroom (because they must ha... | 3 | n = int(input())
mass = []
a = [0 for _ in range(26)]
sumi = 0
for i in range(n):
tmp = ord(input()[0])-97
a[tmp]+=1
for i in range(26):
if a[i]==3:
sumi+=1
elif a[i]>3:
tmp = a[i]//2
a[i]-=tmp
sumi+=sum(list(range(tmp)) + list(range(a[i])))
print(sumi)
|
Daruma Otoshi
You are playing a variant of a game called "Daruma Otoshi (Dharma Block Striking)".
At the start of a game, several wooden blocks of the same size but with varying weights are stacked on top of each other, forming a tower. Another block symbolizing Dharma is placed atop. You have a wooden hammer with it... | 3 | import sys
input = lambda: sys.stdin.readline().rstrip()
def resolve():
while True:
n = int(input())
w = list(map(int, input().split()))
if n==0:
break
else:
dp = [[0]*(n+1) for _ in range(n+2)]
# 幅
for i in range(2, n+1):
... |
Little Tanya decided to present her dad a postcard on his Birthday. She has already created a message — string s of length n, consisting of uppercase and lowercase English letters. Tanya can't write yet, so she found a newspaper and decided to cut out the letters and glue them into the postcard to achieve string s. The... | 3 | import math
s = input()
t = input()
lenS = len(s)
lenT = len(t)
yes = 0
no = 0
def change_register(l):
if ord(l) > 96:
return chr(ord(l) - 32)
else:
return chr(ord(l) + 32)
map1 = {}
for i in s:
if map1.get(i, None) is None:
map1[i] = 1
else:
map1[i] += 1
map2 = {... |
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 | t=int(input())
for i in range(t):
a,b,c=map(int,input().split())
if c<a or c>b:
print(c)
else:
d=b//c
print(c*(d+1)) |
During the winter holidays, the demand for Christmas balls is exceptionally high. Since it's already 2018, the advances in alchemy allow easy and efficient ball creation by utilizing magic crystals.
Grisha needs to obtain some yellow, green and blue balls. It's known that to produce a yellow ball one needs two yellow ... | 1 |
a = raw_input()
a = list(map(int,a.split(' ')))
y,b = a[0],a[1]
d = raw_input()
d = list(map(int,d.split(' ')))
a,v,c = d[0],d[1],d[2]
q = a*2+v
e = v
r = c*3
y = y-q
b = b-(e+r)
ans=0
if y<0:
ans=ans+abs(y)
if b<0:
ans=ans+abs(b)
print ans
|
Alice and Bob are fighting over who is a superior debater. However they wish to decide this in a dignified manner.
So they decide to fight in the Battle of Words.
In each game both get to speak a sentence. Because this is a dignified battle, they do not fight physically, the alphabets in their words do so for them. ... | 1 | for _ in range(int(raw_input())):
arr1 = raw_input()
arr2 = raw_input()
n1 = len(arr1)
n2 = len(arr2)
dic1 = [0]*26
dic2 = [0]*26
for i in range(n1):
if arr1[i] != " ":
dic1[ord(arr1[i])-ord('a')] += 1
for i in range(n2):
if arr2[i] != " ":
dic2[ord(arr2[i])-ord('a')] += 1
flag1 = 0
flag2 = 0
fo... |
We guessed some integer number x. You are given a list of almost all its divisors. Almost all means that there are all divisors except 1 and x in the list.
Your task is to find the minimum possible integer x that can be the guessed number, or say that the input data is contradictory and it is impossible to find such n... | 3 | def init():
global sieve
sieve = [0, 0, 1] + [1, 0] * 500000
for i in range(3, 1000, 2):
if sieve[i]:
sieve[i * i:1000000:2 * i] = [0] * (1 + (1000000 - i * i) // (2 * i))
def gcd(a, b):
while b:
a, b = b, a % b
return a
def solve():
n = int(input())
arr = sorte... |
Ayoub thinks that he is a very smart person, so he created a function f(s), where s is a binary string (a string which contains only symbols "0" and "1"). The function f(s) is equal to the number of substrings in the string s that contains at least one symbol, that is equal to "1".
More formally, f(s) is equal to the ... | 3 | from sys import stdin
input = stdin.readline
from math import ceil
def answer():
total = (n * (n + 1))//2
x = n - m
div = (x // (m + 1))
ans = total - (div * (div + 1)//2) * (m + 1) - (div + 1) * (x % (m + 1))
return ans
for T in range(int(input())):
n , m = map(int,input().split... |
Dima worked all day and wrote down on a long paper strip his favorite number n consisting of l digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf.
To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive inte... | 3 | def fun(s,l):
if l==1:
return int(s)
else :
i=l//2
j=i
a=s[:i]
b=s[j:]
front=int(s)
while 1:
if b[0]=='0':
j+=1
i+=1
a=s[:i]
b=s[j:]
if a=="" or b=="":
... |
<image>
It's the end of July – the time when a festive evening is held at Jelly Castle! Guests from all over the kingdom gather here to discuss new trends in the world of confectionery. Yet some of the things discussed here are not supposed to be disclosed to the general public: the information can cause discord in th... | 3 | #!/usr/bin/env python
from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
class FastI(BytesIO):
newlines = 0
def __init__... |
Duff is addicted to meat! Malek wants to keep her happy for n days. In order to be happy in i-th day, she needs to eat exactly ai kilograms of meat.
<image>
There is a big shop uptown and Malek wants to buy meat for her from there. In i-th day, they sell meat for pi dollars per kilogram. Malek knows all numbers a1, .... | 3 | a=int(input())
b=[input() for i in range(a)]
costs=[]
req=[]
for i in b:
costs.append(int(i.split()[1]))
req.append(int(i.split()[0]))
min_cost=costs[0]
total=0
i=0
while i<a:
if min_cost<=costs[i]:
total+=min_cost*req[i]
i+=1
else:
min_cost=costs[i]
else:
print(total)
|
In a Berland's zoo there is an enclosure with camels. It is known that camels like to spit. Bob watched these interesting animals for the whole day and registered in his notepad where each animal spitted. Now he wants to know if in the zoo there are two camels, which spitted at each other. Help him to solve this task.
... | 3 | n=int(input())
dis={}
for i in range(n):
a,b=(int(i) for i in input().split())
dis[a]=b
if a+b in dis:
if dis[a+b]+a+b==a:
print('YES')
break
else:
print('NO')
|
"Pizza At", a fast food chain, offers three kinds of pizza: "A-pizza", "B-pizza" and "AB-pizza". A-pizza and B-pizza are completely different pizzas, and AB-pizza is one half of A-pizza and one half of B-pizza combined together. The prices of one A-pizza, B-pizza and AB-pizza are A yen, B yen and C yen (yen is the curr... | 3 | a,b,c,x,y=map(int,input().split())
chk=min(x,y)
ans=max(x,y)*c*2
ans=min(ans,a*x+b*y,chk*c*2+a*(x-chk)+b*(y-chk))
print(ans) |
Little boy Gerald studies at school which is quite far from his house. That's why he has to go there by bus every day. The way from home to school is represented by a segment of a straight line; the segment contains exactly n + 1 bus stops. All of them are numbered with integers from 0 to n in the order in which they f... | 1 | from sys import stdin
from collections import *
def fast2():
import os, sys, atexit
range = xrange
from cStringIO import StringIO as BytesIO
sys.stdout = BytesIO()
atexit.register(lambda: os.write(1, sys.stdout.getvalue()))
return BytesIO(os.read(0, os.fstat(0).st_size)).readline
class segme... |
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... | 1 | n = input()
a = 0
for i in range(n):
c, d = map(int, raw_input().split())
if d - c >= 2:
a += 1
print a |
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the oppo... | 3 | count=1
k=int(input())
l=input()
for _ in range(k-1):
o=input()
if o==l:
l=o
else:
count+=1
l=o
print(count) |
After playing Neo in the legendary "Matrix" trilogy, Keanu Reeves started doubting himself: maybe we really live in virtual reality? To find if this is true, he needs to solve the following problem.
Let's call a string consisting of only zeroes and ones good if it contains different numbers of zeroes and ones. For exa... | 3 | import math
a1=0
a0=0
q = int(input())
q1=q-1
b=str(input())
for i in range(q):
if b[i]=="0":
a0=a0+1
else:
a1=a1+1
if a1==a0:
print("2")
print(b[:q1],b[q-1],end="")
if a1!=a0:
print("1")
print(b) |
Let's denote that some array b is bad if it contains a subarray b_l, b_{l+1}, ..., b_{r} of odd length more than 1 (l < r and r - l + 1 is odd) such that ∀ i ∈ \{0, 1, ..., r - l\} b_{l + i} = b_{r - i}.
If an array is not bad, it is good.
Now you are given an array a_1, a_2, ..., a_n. Some elements are replaced by -... | 3 | input1 = input('').split(' ')
k = int(input1.pop())
n = int(input1.pop())
input2 = input('').split(' ')
lis11 = []
lis12 = []
lis21 = []
lis22 = []
lisk = []
long = 0
op = 1
for i in range(n):
if i % 2 == 0:
lis11.append(int(input2[i]))
else:
lis12.append(int(input2[i]))
tong = [0,1,k-1]
yi = [0... |
You are given one integer number n. Find three distinct integers a, b, c such that 2 ≤ a, b, c and a ⋅ b ⋅ c = n or say that it is impossible to do it.
If there are several answers, you can print any.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 100)... | 3 | '''
5
64
32
97
2
12345
'''
def mi():
return map(int, input().split())
for _ in range(int(input())):
n = int(input())
i = 2
found=0
while i*i<=n:
if (n % i == 0):
n1 = n//i
j=2
comp=0
while j*j<=n1:
if n1%j==0:
... |
You are given a set of points x_1, x_2, ..., x_n on the number line.
Two points i and j can be matched with each other if the following conditions hold:
* neither i nor j is matched with any other point;
* |x_i - x_j| ≥ z.
What is the maximum number of pairs of points you can match with each other?
Input
T... | 3 | # aadiupadhyay
import os.path
from math import gcd, floor, ceil
from collections import *
import sys
mod = 1000000007
INF = float('inf')
def st(): return list(sys.stdin.readline().strip())
def li(): return list(map(int, sys.stdin.readline().split()))
def mp(): return map(int, sys.stdin.readline().split())
def inp(): re... |
There are N balls in a two-dimensional plane. The i-th ball is at coordinates (x_i, y_i).
We will collect all of these balls, by choosing two integers p and q such that p \neq 0 or q \neq 0 and then repeating the following operation:
* Choose a ball remaining in the plane and collect it. Let (a, b) be the coordinates... | 3 | n=int(input())
s=[list(map(int, input().split())) for i in range(n)]
x=[]
if n==1:
print(1)
exit(0)
for i in range(n):
for j in range(n):
if i==j:
continue
t=(s[i][0]-s[j][0],s[i][1]-s[j][1])
x.append(t)
ans = [x.count(i) for i in set(x)]
print(n-max(ans)) |
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.
* `0 p x`: a_p \gets a_p + x
* `1 l r`: Print \sum_{i = l}^{r - 1}{a_i}.
Constraints
* 1 \leq N, Q \leq 500,000
* 0 \leq a_i, x \leq 10^9
* 0 \leq p < N
* 0 \leq l_i < r_i \leq N
* All values in Input are integer.
I... | 3 | def main():
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq ... |
Balph is learning to play a game called Buma. In this game, he is given a row of colored balls. He has to choose the color of one new ball and the place to insert it (between two balls, or to the left of all the balls, or to the right of all the balls).
When the ball is inserted the following happens repeatedly: if so... | 3 | s = list(input())
lst = []
i = 0
n = len(s)
while i < n:
char = s[i]
count = 0
while i < n and char == s[i]:
i += 1
count += 1
lst.append( (s[i-1], count) )
# print(lst)
if len(lst)%2 == 0 or lst[len(lst)//2][1] < 2:
print(0)
else:
n = len(lst)
valid_neighbour = True
for i in range(n//2):
if lst[i][1] ... |
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.
Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of o... | 1 | from __future__ import division, print_function
import collections as c
import math
import string
import sys
import os
debug = os.getenv('SHSH')
if debug:
sys.stdin = open('in.txt')
def readInt(f=None):
f = f or sys.stdin
return int(f.readline().strip())
def readInts(f=None):
f = f or sys.stdin
... |
A positive (strictly greater than zero) integer is called round if it is of the form d00...0. In other words, a positive integer is round if all its digits except the leftmost (most significant) are equal to zero. In particular, all numbers from 1 to 9 (inclusive) are round.
For example, the following numbers are roun... | 3 | t = int(input())
for _ in range(t):
n = int(input())
ans = []
s = str(n)
for i in range(len(s)):
if s[i] != "0":
ans.append(int(s[i]) * pow(10, len(s)-i-1))
print(len(ans))
print(*ans) |
There are N integers, A_1, A_2, ..., A_N, arranged in a row in this order.
You can perform the following operation on this integer sequence any number of times:
Operation: Choose an integer i satisfying 1 \leq i \leq N-1. Multiply both A_i and A_{i+1} by -1.
Let B_1, B_2, ..., B_N be the integer sequence after your ... | 3 | N = int(input())
A = list(map(int, input().split()))
B = sorted(map(abs, A))
if sum(x < 0 for x in A) % 2 == 0:
print(sum(B))
else:
print(sum(B[1:])-B[0]) |
Santa has to send presents to the kids. He has a large stack of n presents, numbered from 1 to n; the topmost present has number a_1, the next present is a_2, and so on; the bottom present has number a_n. All numbers are distinct.
Santa has a list of m distinct presents he has to send: b_1, b_2, ..., b_m. He will send... | 3 | # from math import abs
if __name__ == "__main__":
for _ in range(int(input())):
n, m = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
index = [0] * 100001
for i in range(n):
index[a[i]] = i
sorted_pt... |
Our world is one-dimensional, and ruled by two empires called Empire A and Empire B.
The capital of Empire A is located at coordinate X, and that of Empire B is located at coordinate Y.
One day, Empire A becomes inclined to put the cities at coordinates x_1, x_2, ..., x_N under its control, and Empire B becomes incli... | 3 | N,M,X,Y,*H=map(int,open(0).read().split());print('NWoa rW a r'[max(max(H[:N]),X)>=min(min(H[N:]),Y)::2]) |
The length of the longest common prefix of two strings s = s_1 s_2 … s_n and t = t_1 t_2 … t_m is defined as the maximum integer k (0 ≤ k ≤ min(n,m)) such that s_1 s_2 … s_k equals t_1 t_2 … t_k.
Koa the Koala initially has n+1 strings s_1, s_2, ..., s_{n+1}.
For each i (1 ≤ i ≤ n) she calculated a_i — the length of ... | 3 | t = int(input())
for i in range(t):
n = int(input())
arr = list(map(int, input().split()))
x = max(arr)
if(x==0):
x = 1
out = ["a"*x]
for j in range(n):
a = out[j][:arr[j]]
b = out[j][arr[j]:arr[j]+1]
if(x!=arr[j]):
c = chr((ord(b)+1-ord('a'))%26 + ord('a'))
else:
c = ''
out.append(a + c*(x-ar... |
Some days ago, I learned the concept of LCM (least common multiple). I've played with it for several times and I want to make a big number with it.
But I also don't want to use many numbers, so I'll choose three positive integers (they don't have to be distinct) which are not greater than n. Can you help me to find th... | 1 | FILE = "P1"
try:
inFile = open(FILE+".txt")
except:
pass
def read():
try:
return inFile.readline().strip()
except:
return raw_input().strip()
n = int(read())
if n == 1:
print 1
elif n == 2:
print 2
elif n == 4:
print 12
else:
if n%2 == 1:
print n*(n-1)*(n-2)
... |
Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. For example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. When a team plays as ... | 3 | t=int(input())
c=0
l=[]
for _ in range(t):
l.append(list(map(int,input().split())))
for x in l:
for y in l:
if l.index(x)==l.index(y):
continue
if x[0]==y[1]:
c+=1
print(c) |
There are n pillars aligned in a row and numbered from 1 to n.
Initially each pillar contains exactly one disk. The i-th pillar contains a disk having radius a_i.
You can move these disks from one pillar to another. You can take a disk from pillar i and place it on top of pillar j if all these conditions are met:
... | 3 | #_________________ Mukul Mohan Varshney _______________#
#Template
import sys
import os
import math
import copy
from math import gcd
from bisect import bisect
from io import BytesIO, IOBase
from math import sqrt,floor,factorial,gcd,log,ceil
from collections import deque,Counter,defaultdict
from itertools import permu... |
You're given two arrays a[1 ... n] and b[1 ... n], both of the same length n.
In order to perform a push operation, you have to choose three integers l, r, k satisfying 1 ≤ l ≤ r ≤ n and k > 0. Then, you will add k to elements a_l, a_{l+1}, …, a_r.
For example, if a = [3, 7, 1, 4, 1, 2] and you choose (l = 3, r = 5, ... | 3 | def function(a, b, n) :
pointer = 0
difference = 0
count = 0
while pointer < n :
if ( b[pointer] - a[pointer] ) == difference :
pointer += 1
elif a[pointer] > b[pointer] :
return "NO"
else :
if count == 0 :
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.