problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
Let \mathrm{popcount}(n) be the number of `1`s in the binary representation of n. For example, \mathrm{popcount}(3) = 2, \mathrm{popcount}(7) = 3, and \mathrm{popcount}(0) = 0.
Let f(n) be the number of times the following operation will be done when we repeat it until n becomes 0: "replace n with the remainder when n... | 3 | n = int(input())
s = input()
x = int(s, 2)
pcx = s.count("1")
pc1 = x % (pcx - 1) if pcx > 1 else 0
pc2 = x % (pcx + 1)
def f(j):
cnt = 0
while j:
j %= bin(j).count("1")
cnt += 1
return cnt
for i, y in enumerate(s):
k = n - 1 - i
if y == "0":
print(f((pc2 + pow(2, k, pcx + ... |
Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity.
There are n columns of toy cubes in the box arranged in a line. The i-th column contains ai cubes. At first, the gravity in the box is pulling... | 3 | n = int(input())
lis = list(map(int,input().split()))
lis.sort()
print(*lis) |
Given is a sequence of integers A_1, A_2, ..., A_N. If its elements are pairwise distinct, print `YES`; otherwise, print `NO`.
Constraints
* 2 ≤ N ≤ 200000
* 1 ≤ A_i ≤ 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 ... A_N
Output
If the elements... | 3 | N=int(input())
A=input().split()
l=len(set(A))
print('YES' if N==l else 'NO') |
Given an array a of length n, find another array, b, of length n such that:
* for each i (1 ≤ i ≤ n) MEX(\\{b_1, b_2, …, b_i\})=a_i.
The MEX of a set of integers is the smallest non-negative integer that doesn't belong to this set.
If such array doesn't exist, determine this.
Input
The first line contains an ... | 3 | from queue import Queue
def main():
test = 1
for _ in range(test):
n = int(input())
ara = [int(num) for num in input().split()]
mark = [True for _ in range(n + 1)]
for num in ara:
mark[num] = False
take_from = Queue()
for index in range(n + 1):
... |
In the 2022 year, Mike found two binary integers a and b of length n (both of them are written only by digits 0 and 1) that can have leading zeroes. In order not to forget them, he wanted to construct integer d in the following way:
* he creates an integer c as a result of bitwise summing of a and b without transfe... | 3 | from __future__ import division, print_function
# import threading
# threading.stack_size(2**27)
# import sys
# sys.setrecursionlimit(10**7)
# sys.stdin = open('inpy.txt', 'r')
# sys.stdout = open('outpy.txt', 'w')
from sys import stdin, stdout
import bisect # c++ upperbound
import math
import heapq
i_m = 922337203685... |
Devu is a renowned classical singer. He is invited to many big functions/festivals. Recently he was invited to "All World Classical Singing Festival". Other than Devu, comedian Churu was also invited.
Devu has provided organizers a list of the songs and required time for singing them. He will sing n songs, ith song wi... | 3 | buf = input().split(" ")
n = int(buf[0])
k = int(buf[1])
czas = 0
buf = input().split(" ")
for i in range(n):
t = int(buf[i])
czas += t
czas += (n-1)*10
#print(czas)
if czas > k:
print(-1)
else:
print((k-czas) // 5 + 2*(n-1)) |
Max wants to buy a new skateboard. He has calculated the amount of money that is needed to buy a new skateboard. He left a calculator on the floor and went to ask some money from his parents. Meanwhile his little brother Yusuf came and started to press the keys randomly. Unfortunately Max has forgotten the number which... | 3 | #calcula quantas substring são divisíveis por 4
s = input()
count = 0
for num in s:
if int(num)%4 == 0:
count +=1
for i in range(len(s)-1):
if int(s[i:i+2])%4 == 0:
count += i+1
print(count)
|
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.
We know that several boy&girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair m... | 3 | n, boys, m, girls, paired = int(input()), sorted([int(i) for i in input().split()]), int(input()), sorted([int(i) for i in input().split()]), 0
longest, shortest = (boys, girls) if len(boys) > len(girls) else (girls, boys)
for s in shortest:
for index, l in enumerate(longest):
if s - l in [-1, 0, 1]:
paired... |
Given is a sequence of N integers A_1, \ldots, A_N.
Find the (multiplicative) inverse of the sum of the inverses of these numbers, \frac{1}{\frac{1}{A_1} + \ldots + \frac{1}{A_N}}.
Constraints
* 1 \leq N \leq 100
* 1 \leq A_i \leq 1000
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 \... | 3 | n=int(input())
a=list(map(int,input().split()))
x=[1/i for i in a]
print(1/sum(x)) |
You have a statistic of price changes for one product represented as an array of n positive integers p_0, p_1, ..., p_{n - 1}, where p_0 is the initial price of the product and p_i is how the price was increased during the i-th month.
Using these price changes you are asked to calculate the inflation coefficients for ... | 3 | for _ in range(int(input())):
n,k=[*map(int,input().split())]
a=[*map(int,input().split())]
su=0
count=0
final=0
ans=k/100
for i in range(1,n):
su+=a[i-1]
op=a[i]/su
if op>ans:
ml=su
x=(a[i]/ans)-ml
x=int(x)
if a[i]/(ml+... |
Little girl Susie went shopping with her mom and she wondered how to improve service quality.
There are n people in the queue. For each person we know time ti needed to serve him. A person will be disappointed if the time he waits is more than the time needed to serve him. The time a person waits is the total time wh... | 3 | n = int(input())
a = list(map(int, input().split()))
a = sorted(a)
s = 0
c = 0
for i in range(n):
if s <= a[i]:
c += 1
s += a[i]
print(c) |
For years, the Day of city N was held in the most rainy day of summer. New mayor decided to break this tradition and select a not-so-rainy day for the celebration. The mayor knows the weather forecast for the n days of summer. On the i-th day, a_i millimeters of rain will fall. All values a_i are distinct.
The mayor k... | 3 | n, x, y = map(int, input().split())
a = list(map(int, input().split()))
for i in range(n):
if a[i] == min(a[max(i - x, 0):min(i + y + 1, n):1]):
print(i + 1)
exit()
|
n children are standing in a circle and playing the counting-out game. Children are numbered clockwise from 1 to n. In the beginning, the first child is considered the leader. The game is played in k steps. In the i-th step the leader counts out ai people in clockwise order, starting from the next person. The last one ... | 3 | nn,k=map(int,input().split())
n=nn
a=list(map(int,input().split()))
c=list(range(1,n+1))
s=0
ans=[]
for j in a:
x=j%n
m=0
while m<x:
s+=1;s%=nn
while c[s]==-1:s+=1;s%=nn
m+=1
ans.append(str(c[s]))
c[s]=-1
n-=1
if n>0:
while c[s]==-1:s+=1;s%=nn
print(' '.join(... |
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given n numbers finds one that is di... | 1 | n = input()
l = map(int, raw_input().split())
odd, odd_i, even, even_i = 0, 0, 0, 0
for i in xrange(n):
if l[i] % 2 == 0:
even += 1
even_i = i + 1
else:
odd += 1
odd_i = i + 1
if even != 0 and odd != 0 and (even > 1 or odd > 1):
if even > 1:
print odd_i
... |
What joy! Petya's parents went on a business trip for the whole year and the playful kid is left all by himself. Petya got absolutely happy. He jumped on the bed and threw pillows all day long, until...
Today Petya opened the cupboard and found a scary note there. His parents had left him with duties: he should water... | 3 | k = int(input())
a = sorted(list(map(int, input().split())), reverse=True)
ans = 0
if k != 0:
for i in a:
k -= i
ans += 1
if k <= 0:
break
if k > 0:
ans = -1
print(ans)
|
Wabbit is trying to move a box containing food for the rest of the zoo in the coordinate plane from the point (x_1,y_1) to the point (x_2,y_2).
He has a rope, which he can use to pull the box. He can only pull the box if he stands exactly 1 unit away from the box in the direction of one of two coordinate axes. He will... | 3 | t = int(input().rstrip())
while t > 0:
t -= 1
x1,y1,x2,y2 = map(int,input().strip().split())
ans = 0
if (y1 == y2) or (x1 == x2):
ans = abs(x1 - x2) + abs(y1 - y2)
else:
ans = abs(x1 - x2) + abs(y1 - y2) + 2
print(ans) |
Nowadays all circuses in Berland have a round arena with diameter 13 meters, but in the past things were different.
In Ancient Berland arenas in circuses were shaped as a regular (equiangular) polygon, the size and the number of angles could vary from one circus to another. In each corner of the arena there was a spec... | 1 | import sys
import math
DEBUG = False
########################################
def solve():
''' Solution here '''
p = [ map( float, s.split() ) for s in fin.read().strip().split("\n") ]
a = distance(p[0], p[1])
b = distance(p[1], p[2])
c = distance(p[2], p[0])
pp = (a + b + c) / 2
s = math.sqrt( pp * (pp - ... |
This is the hard version of the problem. The difference between the versions is the constraint on n and the required number of operations. You can make hacks only if all versions of the problem are solved.
There are two binary strings a and b of length n (a binary string is a string consisting of symbols 0 and 1). In ... | 3 | # cook your dish here
for _ in range(int(input())):
n=int(input())
a=input()
b=input()
l=[]
a=list(a)
b=list(b)
i=0
if a==b:
print(0)
continue
while(i<n-1):
if a[i]!=a[i+1]:
l.append(i+1)
i+=1
if a[-1]=="1":
l.append(n)
... |
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 | a,b=input().split()
a=int(a)
b=int(b)
p=a;
for i in range(1,10):
if a%10==0 :
print(i)
exit()
elif a%10==b :
print(i)
exit()
a=a+p
print(1)
|
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 | from sys import stdin, stdout
from sys import maxsize
input = stdin.readline
# def print(n):
# stdout.write(str(n)+'\n')
def solve():
pass
test = 1
test = int(input().strip())
for t in range(0, test):
# n = int(input().strip())
# s = list(input().strip()) ... |
You are given an array of integers. Vasya can permute (change order) its integers. He wants to do it so that as many as possible integers will become on a place where a smaller integer used to stand. Help Vasya find the maximal number of such integers.
For instance, if we are given an array [10, 20, 30, 40], we can pe... | 3 | #!/usr/bin/env python3
from sys import stdin
def solve(tc):
n = int(stdin.readline().strip())
li = list(map(int, stdin.readline().split()))
li.sort()
cnt = 0
p = 0
for i in range(1,n):
if li[i]>li[p]:
cnt += 1
p += 1
print(cnt)
return
LOCAL_TEST = not... |
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:
* Tetrahedron. Tetrahedron has 4 triangular faces.
* Cube. Cube has 6 square faces.
* Octahedron. Octahedron has 8 triangular faces.
* Dodecahedron. Dodecahedron has 12 pentagonal faces.
*... | 3 | n = int(input())
ans = 0
for i in range(n):
s = input()
if s[0] == "T":
ans += 4
elif s[0] == "C":
ans += 6
elif s[0] == "O":
ans += 8
elif s[0] == "D":
ans += 12
else:
ans += 20
print(ans)
|
Polycarp is preparing the first programming contest for robots. There are n problems in it, and a lot of robots are going to participate in it. Each robot solving the problem i gets p_i points, and the score of each robot in the competition is calculated as the sum of p_i over all problems i solved by it. For each prob... | 3 | n = int(input())
mas1 = [int(k) for k in input().split()]
mas2 = [int(k) for k in input().split()]
m1 = 0
m2 = 0
for i in range(n):
if mas1[i] == 1 and mas2[i] == 0:
m1 +=1
elif mas1[i] == 0 and mas2[i] == 1:
m2 +=1
if m1 == 0:
print(-1)
else:
print(m2//m1 + 1) |
Bob is decorating his kitchen, more precisely, the floor. He has found a prime candidate for the tiles he will use. They come in a simple form factor — a square tile that is diagonally split into white and black part as depicted in the figure below.
<image>
The dimension of this tile is perfect for this kitchen, as h... | 3 | print(pow(2, sum(list(map(int, input().split()))), 998244353)) |
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).
For a positive integer n, we call a... | 3 | for _ in range(int(input())):
n=int(input())
arr=[int(x) for x in range(1,n+1)]
print(*arr)
|
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 | list = 26*[0]
def function(Number):
if(Number % 2 == 0):
a = Number/2
return(a*(a-1)/2*2)
else:
a = (Number+1)/2
return(a*(a-1)/2+(a-1)*(a-2)/2)
N = int(input())
for i in range(N):
S= input()
list[ord(S[0])-97] += 1
count =0
for i in list:
count += function(i)
print(int(count))
|
One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:
a1, a2, ..., an → an, a1, a2, ..., an - 1.
Help Twi... | 1 | def main():
n=int(input())
numbers=map(int,raw_input().split(" "))
#print numbers
i_stop=None
isBreak=False
for i in range(1,n):
i_stop=i
if numbers[i]<numbers[i-1]:
isBreak=True
break
if not isBreak:
print 0
else:
checkBreak=False
... |
Manao has invented a new mathematical term — a beautiful set of points. He calls a set of points on a plane beautiful if it meets the following conditions:
1. The coordinates of each point in the set are integers.
2. For any two points from the set, the distance between them is a non-integer.
Consider all poi... | 3 |
l = [int(i) for i in input().split()]
n = l[0]; m = l[1]
a = min(n,m)
if a==0:
print(1,0)
else:
print(a+1)
for i in range(a+1):
print(a-i,i)
|
You are given array a_1, a_2, ..., a_n. Find the subsegment a_l, a_{l+1}, ..., a_r (1 ≤ l ≤ r ≤ n) with maximum arithmetic mean (1)/(r - l + 1)∑_{i=l}^{r}{a_i} (in floating-point numbers, i.e. without any rounding).
If there are many such subsegments find the longest one.
Input
The first line contains single integer... | 3 | from itertools import groupby
nb_elements = int(input())
elements = [int(x) for x in input().split()]
maxs = max(elements)
ele_Group = groupby(elements)
max_len = 0
for k, g in ele_Group:
if k == maxs:
max_len = max(max_len, len(list(g)))
print(max_len) |
Guy-Manuel and Thomas have an array a of n integers [a_1, a_2, ..., a_n]. In one step they can add 1 to any element of the array. Formally, in one step they can choose any integer index i (1 ≤ i ≤ n) and do a_i := a_i + 1.
If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and T... | 3 | t=int(input())
for i in range(t):
n=int(input())
a=list(map(int,input().split()))
noz=a.count(0)
s=sum(a)
if(noz==0):
if(s==0):
print(1)
else:
print(0)
else:
s=s+noz
if(s==0):
print(1+noz)
else:
print(noz) |
As you know, Bob's brother lives in Flatland. In Flatland there are n cities, connected by n - 1 two-way roads. The cities are numbered from 1 to n. You can get from one city to another moving along the roads.
The «Two Paths» company, where Bob's brother works, has won a tender to repair two paths in Flatland. A path ... | 1 | import sys
n = int(sys.stdin.readline().strip())
adj = [None] * n
edges = []
for i in xrange(n - 1):
t = sys.stdin.readline().strip().split()
s = int(t[0]) - 1
d = int(t[1]) - 1
if adj[s] == None:
adj[s] = []
if adj[d] == None:
adj[d] = []
adj[s].append(d)
adj[d].append(s)
edges.append((s, d))
v1 = [False... |
Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first n. He writes down the followin... | 3 | def read_ints():
return map(int, input().split(' '))
n = list(read_ints())
x = n[0]//2 + n[0]%2
if n[1]<=x:
print(2*(n[1]-1)+1)
else:
print((n[1]-x)*2)
|
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Bi... | 3 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 19 10:43:43 2017
@author: Andy Chen
"""
a = int(input())
if a % 2 == 0 and a > 2:
print('YES')
else:
print('NO')
|
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 | a=int(input())
j=0
c=0
arr=[]
for i in range(a):
w=input().split(" ")
for i in w:
if i=='1':
j+=1
if j>=2:
c+=1
j=0
print(c)
|
Today is Wednesday, the third day of the week. What's more interesting is that tomorrow is the last day of the year 2015.
Limak is a little polar bear. He enjoyed this year a lot. Now, he is so eager to the coming year 2016.
Limak wants to prove how responsible a bear he is. He is going to regularly save candies for ... | 3 | s=input()
if 'week' in s:
x=int(s[:1])
if(x==6)or(x==5):
print(53)
else:
print(52)
else:
x=int(s[:2])
if(x<=29):
print(12)
elif(x==30):
print(11)
else:
print(7) |
Polycarp is going to participate in the contest. It starts at h_1:m_1 and ends at h_2:m_2. It is guaranteed that the contest lasts an even number of minutes (i.e. m_1 \% 2 = m_2 \% 2, where x \% y is x modulo y). It is also guaranteed that the entire contest is held during a single day. And finally it is guaranteed tha... | 3 | t1=input()
t2=input()
h1, m1=[int (x) for x in t1.split(':')]
h2, m2=[int(x) for x in t2.split(':')]
hour_diff=h2-h1
min_diff=m2-m1
a=int((60*hour_diff+m2-m1)/2)
if m1+a>=60:
p=(m1+a)%60
p=str(p)
h1+=int((m1+a)/60)
h1=str(h1)
h1=h1.zfill(2)
print("{}:{}".format(h1, p.zfill(2)))
else:
p=m1+a
... |
You are given a string S consisting of lowercase English letters. Another string T is initially empty. Determine whether it is possible to obtain S = T by performing the following operation an arbitrary number of times:
* Append one of the following at the end of T: `dream`, `dreamer`, `erase` and `eraser`.
Constrain... | 3 | s=input().replace("eraser","").replace("erase","").replace("dreamer","").replace("dream","")
if s in "":
print("YES")
else:
print("NO") |
Devu is a renowned classical singer. He is invited to many big functions/festivals. Recently he was invited to "All World Classical Singing Festival". Other than Devu, comedian Churu was also invited.
Devu has provided organizers a list of the songs and required time for singing them. He will sing n songs, ith song wi... | 3 | R = lambda:map(int, input().split())
n, d = R()
t = list(R())
if sum(t) + 10 * (n - 1) > d:
print(-1)
else:
print((d - sum(t)) // 5) |
Given an integer N, Chef wants to find the smallest positive integer M such that the bitwise XOR of M and M+1 is N. If no such M exists output -1.
Input
The first line of input contain an integer T denoting the number of test cases. Each of the following T lines contains an integer N for that test case.
Output
For ea... | 1 | t=input()
for i in range(0,t):
n=input()
if(n==1):
print '2'
continue
k=0
y=1
x=(pow(2,k))-1
while(x<n):
k+=1
x=(pow(2,k))-1
if(x==n):
print n/2
y=0
break
if(y):
print '-1' |
An integer sequence is called beautiful if the difference between any two consecutive numbers is equal to 1. More formally, a sequence s_1, s_2, …, s_{n} is beautiful if |s_i - s_{i+1}| = 1 for all 1 ≤ i ≤ n - 1.
Trans has a numbers 0, b numbers 1, c numbers 2 and d numbers 3. He wants to construct a beautiful sequenc... | 3 | a,b,c,d=map(int,input().split())
ans=[]
for i in range(a):
ans.append(0)
if(b):
ans.append(1)
b-=1
if(len(ans) and b and ans[-1]==0):
ans.append(1)
b-=1
tan=[]
for i in range(d):
tan.append(3)
if(c):
tan.append(2)
c-=1
flag=0
if(len(tan) and c and tan[-1... |
Vasya has n pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every m-th day (at days with numbers m, 2m, 3m, ...) mom buys a pair of socks to Vasya. She does it late in the eve... | 1 | n, m = map(int, raw_input().split())
out = 0
i = 0
while (n > 0):
n = n - 1
out = out + 1
if (i % m == 0):
n = n + 1
i = i + 1
print out - 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):
s = input()
if(len(s) >= 11):
print(s[0]+str(len(s)-2)+s[len(s)-1])
else:
print(s) |
For a given weighted graph $G = (V, E)$, find the shortest path from a source to each vertex. For each vertex $u$, print the total weight of edges on the shortest path from vertex $0$ to $u$.
Constraints
* $1 \leq n \leq 10,000$
* $0 \leq c_i \leq 100,000$
* $|E| < 500,000$
* All vertices are reachable from vertex $0... | 3 | import heapq
INFINITY = 10 ** 10
WHITE = 0
GRAY = 1
BLACK = 2
n = int(input())
dict_adjacency = {}
for _ in range(n):
u, k, *list_num = map(int, input().split())
list_temp = []
dict_adjacency[str(u)] = {}
for i in range(0, k * 2, 2):
dict_adjacency[str(u)][str(list_num[i])] = list_num[i ... |
There are n students standing in a circle in some order. The index of the i-th student is p_i. It is guaranteed that all indices of students are distinct integers from 1 to n (i. e. they form a permutation).
Students want to start a round dance. A clockwise round dance can be started if the student 2 comes right after... | 3 | import sys
rounds = int(sys.stdin.readline())
for x in range(rounds):
n = int(sys.stdin.readline())
nums = [int(x) for x in sys.stdin.readline().split()]
result = True
if n != 1:
last = nums[0]
dir = nums[1] == nums[0] + 1 or (nums[0] == n and nums[1] == 1)
# print("right" if di... |
Caisa solved the problem with the sugar and now he is on the way back to home.
Caisa is playing a mobile game during his path. There are (n + 1) pylons numbered from 0 to n in this game. The pylon with number 0 has zero height, the pylon with number i (i > 0) has height hi. The goal of the game is to reach n-th pylon... | 3 | n = int(input())
arr = list(map(int, input().split()))
print(max(arr)) |
Little penguin Polo has an n × m matrix, consisting of integers. Let's index the matrix rows from 1 to n from top to bottom and let's index the columns from 1 to m from left to right. Let's represent the matrix element on the intersection of row i and column j as aij.
In one move the penguin can add or subtract number... | 3 | from collections import Counter
I = lambda: map(int, input().split())
n, _, d = I()
c = Counter()
for _ in range(n):
c.update(I())
if len(set(a % d for a in c)) > 1:
print(-1)
else:
w, s = 0, sum(c.values()) / 2
for x, k in sorted(c.items()):
w += k
if w >= s:
print(sum(k... |
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())
while (1):
n += 1
flag = 1
s = str(n)
for i in range(0, 4):
for j in range(i + 1, 4):
if (s[i] == s[j]):
flag = 0
break
if (flag == 1):
print(n)
break
|
Dima got into number sequences. Now he's got sequence a1, a2, ..., an, consisting of n positive integers. Also, Dima has got a function f(x), which can be defined with the following recurrence:
* f(0) = 0;
* f(2·x) = f(x);
* f(2·x + 1) = f(x) + 1.
Dima wonders, how many pairs of indexes (i, j) (1 ≤ i < j ≤... | 1 | from sys import stdin
#stdin = open("p.in","r")
R = lambda : int(stdin.readline())
RM = lambda : [int(x) for x in stdin.readline().split()]
R()
a = [0]*40
for x in RM():
a[ str(bin(x)).count('1') ] += 1
p = 0
for x in a:
p += x * (x-1) / 2
print p
|
Being stuck at home, Ray became extremely bored. To pass time, he asks Lord Omkar to use his time bending power: Infinity Clock! However, Lord Omkar will only listen to mortals who can solve the following problem:
You are given an array a of n integers. You are also given an integer k. Lord Omkar wants you to do k ope... | 1 | # cook your code here
for _ in range(input()):
n,k=map(int,raw_input().split())
a=map(int,raw_input().split())
l=[]
d=max(a)
for i in range(n):
l.append(d-a[i])
dd=max(l)
c=[]
for i in range(n):
c.append(dd-l[i])
if k%2==1:
for i in range(n):
print... |
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 | n=int(input())
X=0
codelist = []
for i in range (n):
codelist.append(input())
for i in range (n):
if codelist[i]=="X++":
X += 1;
else:
if codelist[i] =="++X":
X += 1
else:
X -= 1
print(X) |
Three friends are going to meet each other. Initially, the first friend stays at the position x = a, the second friend stays at the position x = b and the third friend stays at the position x = c on the coordinate axis Ox.
In one minute each friend independently from other friends can change the position x by 1 to the... | 3 | for i in range(int(input())):
a=list(map(int,input().strip().split()))
a.sort()
if a[1]-a[0]>1:
if a[2]-a[1]>1:
a[1]-=1
a[0]+=1
a[2]-=1
elif a[2]-a[1]==1:
a[2]-=1
a[1]-=1
a[0]+=1
else:
a[1]-=1
... |
You are given a permutation of length n. Recall that the permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2, 3, 1, 5, 4] is a permutation, but [1, 2, 2] is not a permutation (2 appears twice in the array) and [1, 3, 4] is also not a permutation (n=3 but there is 4 ... | 3 | from collections import *
import sys
# "". join(strings)
def ri():
return int(input())
def rl():
return list(map(int, input().split()))
t=ri()
for _ in range(t):
n=ri()
p=rl()
p=[x-1 for x in p]
move_done=[1]+[0]*(n-1)
pos=[-1]*n
for i in range(n):
pos[p[i]]=i
# print("pos", pos)
... |
Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity.
There are n columns of toy cubes in the box arranged in a line. The i-th column contains ai cubes. At first, the gravity in the box is pulling... | 3 | #!/usr/bin/env python3
import fileinput
import sys
def main():
i = int(input(''))
x = input('')
x = x.split(" ")
x = sorted(x, key=lambda e: int(e)) #sorts as integers
#x=sorted(x)
#print(x)
for n in x:
#if(n != " "):
print(n, end = " ")
"""
x = str(x).replace(' ','')
output = ' '.join(x)
print(' ... |
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 | string=input()
arr=string.split("WUB")
for each in range(len(arr)):
if(arr[each]!=""):
print(arr[each],end=" ") |
What joy! Petya's parents went on a business trip for the whole year and the playful kid is left all by himself. Petya got absolutely happy. He jumped on the bed and threw pillows all day long, until...
Today Petya opened the cupboard and found a scary note there. His parents had left him with duties: he should water... | 3 | k = int(input())
lst = [int(i) for i in input().split()]
lst = sorted(lst)
lst = lst[::-1]
count = 0
if sum(lst) < k:
print(-1)
else:
for i in range(0,len(lst)):
if k > 0:
k -= lst[i]
count += 1
else:
break
print(count) |
You are given n strings s_1, s_2, …, s_n consisting of lowercase Latin letters.
In one operation you can remove a character from a string s_i and insert it to an arbitrary position in a string s_j (j may be equal to i). You may perform this operation any number of times. Is it possible to make all n strings equal?
In... | 3 | # cook your dish here
from collections import Counter
for ad in range(int(input())):
n=int(input())
l=[];s=""
for i in range(n):
s+=input()
c=Counter(s)
val=c.values()
t=0
for i in val:
if i%n==0:
continue
else:
t=1
break
if t==... |
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 | from sys import stdin
input()
ans = 0
for line in stdin:
if line.count('1') >= 2:
ans += 1
print(ans)
|
Chef had an interesting dream last night. He dreamed of a new revolutionary chicken recipe. When he woke up today he tried very hard to reconstruct the ingredient list. But, he could only remember certain ingredients. To simplify the problem, the ingredient list can be represented by a string of lowercase characters 'a... | 1 | for i in xrange(int(raw_input())):
s = raw_input()
ctr = 1
for j in range((len(s)+1)//2):
if s[j]=="?" and s[-j-1]=="?":
ctr=ctr*26%10000009
elif s[j]!=s[-j-1] and s[j]!="?" and s[-j-1]!="?":
ctr=0
break
print ctr |
It's a walking tour day in SIS.Winter, so t groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.
Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P":
* "A" corresponds to an angry... | 3 | t=int(input())
while(t):
n=int(input())
s=input()
s1=list(s)
m=0
l=[]
for i in range(len(s1)):
if(s1[i]=='A'):
l.append(i)
l.append(n)
#print(l)
if(len(l)==1):
print(0)
else:
for i in range(1,len(l)):
m=max(m,(l[i]-l[i-1]))
... |
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network.
Bu... | 3 |
if __name__ == '__main__':
s = set(input())
if len(s)%2 == 0:
print('CHAT WITH HER!')
else:
print('IGNORE HIM!')
|
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... | 3 | if __name__ == "__main__":
s = input()
line = list(s.split())
s1 = int(line[0])
s2 = int(line[1])
print((s1*s2)//2) |
Mr.X, who the handle name is T, looked at the list which written N handle names, S_1, S_2, ..., S_N.
But he couldn't see some parts of the list. Invisible part is denoted `?`.
Please calculate all possible index of the handle name of Mr.X when you sort N+1 handle names (S_1, S_2, ..., S_N and T) in lexicographical ord... | 3 | N=int(input())
S=[input() for i in range(N)]
T=input()
L=1
H=N+1
for i in range(N):
A=S[i].replace("?","a")
Z=S[i].replace("?","z")
if T<A:
H-=1
if Z<T:
L+=1
st=""
for i in range(L,H+1):
st+=str(i)
if i==H:
continue
st+=" "
print(st)
|
A word or a sentence in some language is called a pangram if all the characters of the alphabet of this language appear in it at least once. Pangrams are often used to demonstrate fonts in printing or test the output devices.
You are given a string consisting of lowercase and uppercase Latin letters. Check whether thi... | 3 | from collections import Counter
n = input()
print("YES" if len(Counter(input().lower()))==26 else "NO") |
There is a polyline going through points (0, 0) – (x, x) – (2x, 0) – (3x, x) – (4x, 0) – ... - (2kx, 0) – (2kx + x, x) – ....
We know that the polyline passes through the point (a, b). Find minimum positive value x such that it is true or determine that there is no such x.
Input
Only one line containing two positiv... | 3 | a,b=map(int,input().split())
if b > a:
print(-1)
elif b == a:
print(a)
else:
print(( (a+b) / 2 ) / ( (a+b) // (2*b) )) |
Ghosts live in harmony and peace, they travel the space without any purpose other than scare whoever stands in their way.
There are n ghosts in the universe, they move in the OXY plane, each one of them has its own velocity that does not change in time: \overrightarrow{V} = V_{x}\overrightarrow{i} + V_{y}\overrightarr... | 3 | from collections import defaultdict
n, a, b = map(int, input().split())
lit = [[0 for i in range(3)] for j in range(n)]
ans = 0
deft = defaultdict(int)
sim = defaultdict(int)
for i in range(n):
x, vx, vy = map(int, input().split())
tmp = str(vx) + " " + str(vy)
ans += deft[a * vx - vy] - sim[tmp]
deft... |
You have a positive integer m and a non-negative integer s. Your task is to find the smallest and the largest of the numbers that have length m and sum of digits s. The required numbers should be non-negative integers written in the decimal base without leading zeroes.
Input
The single line of the input contains a pa... | 3 | def F1(m, z):
s1 = ""
m1 = 0
z1 = 0
o = 0
while True:
if o == 1:
break
if m1 == m:
if z1 < z:
return "-1"
break
else:
s1 = s1[::-1]
return s1
break
else:
... |
The only difference between easy and hard versions is the size of the input.
You are given a string s consisting of n characters, each character is 'R', 'G' or 'B'.
You are also given an integer k. Your task is to change the minimum number of characters in the initial string s so that after the changes there will be ... | 3 | from __future__ import division, print_function
def main():
t = int(input())
s1 = "RGB"
s2 = "BRG"
s3 = "GBR"
for test_case in range(t):
n,k = map(int,input().split())
s = input()
ans = 1e9
diff = [0]*n
cur = 0
for i in range(n):
if(s[i]!=s1[i%3]):
diff[i]=1;
cur+=diff[i]
if(i>=k):
cu... |
A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not.
Ahcl wants to construct a beautiful string. He has a string s, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each c... | 3 | for _ in[0]*int(input()):
s=input()
if any(x+x in s for x in'abc'):print(-1)
else:
s=[0,*s,0]
for i in range(len(s)):
if s[i]=='?':s[i]=(set('abc')-{s[i-1],s[i+1]}).pop()
print(''.join(s[1:-1])) |
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.
The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe... | 3 | s = input()
l = []
for c in s:
if c.isdigit():
l.append(c)
l.sort()
print('+'.join(l)) |
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like.
Now let's imagine a typical morning in your family. You haven't w... | 3 | n= int(input())
a= sorted(list(map(int,input().split())))
b=s=0
while b<=sum(a):
b+=a.pop()
s+=1
print(s)
|
Takahashi, Aoki and Snuke love cookies. They have A, B and C cookies, respectively. Now, they will exchange those cookies by repeating the action below:
* Each person simultaneously divides his cookies in half and gives one half to each of the other two persons.
This action will be repeated until there is a person ... | 1 | A, B, C = map(int, raw_input().split())
a = abs(A - B)
b = abs(B - C)
c = abs(C - A)
count = 0
if ((A | B | C) & 1 == 0):
while((a | b | c) & 1 == 0):
if(a + b + c) == 0:
count = -1
break
a /= 2
b /= 2
c /= 2
count = count + 1
print count
|
This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.
Pikachu is a cute and friendly pokémon living in the wild pikachu herd.
But it has become known recently that infamous team R... | 3 | from sys import stdin, stdout
import math
import heapq
import collections
input = stdin.readline
def inputnum():
return(int(input()))
def inputnums():
return(map(int,input().split()))
def inputlist():
return(list(map(int,input().split())))
def inputstring():
return([x for x in input()])
def inputstrings... |
Today, Wet Shark is given n integers. Using any of these integers no more than once, Wet Shark wants to get maximum possible even (divisible by 2) sum. Please, calculate this value for Wet Shark.
Note, that if Wet Shark uses no integers from the n integers, the sum is an even integer 0.
Input
The first line of the ... | 3 | def solve(arr,n):
arr = sorted(arr)
res = sum(arr)
if res%2 ==0 :
return res
for i in range(n):
if arr[i] %2 != 0:
res -= arr[i]
if res %2 == 0 :
return res
return 0
def main() :
# na,nb = list(map(int, input().split(' ')))
# k,m = list(map(int, input().split(' ')))
... |
Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number a and Antisimon receives number b. They also have a heap of n stones. The players take turns to make a move and Simon starts. During a move a player should take from ... | 3 | a,b,n = list(map(int,input().split()))
simon = True
anti = False
while n > -1:
if simon:
num = 1
while num <= a:
if a%num == 0 and n%num == 0:
greatest = num
num += 1
else:
num += 1
n -= greatest
if n == 0:
... |
Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.
Reliable sources have informed the financier Anton of some information about the exchange rate of... | 3 | s = list(input())
ans = -1
n = len(s)
last = -1
for i in range(n):
if (ord(s[i]) - ord('0'))&1 == 0:
last = i
if s[i] < s[-1]:
s[i], s[-1] = s[-1], s[i]
print(''.join(s))
exit(0)
if last == -1:
print(last)
exit(0)
s[last], s[-1] = s[-1], s[last]
print(''.join(s)) |
Igor K. always used to trust his favorite Kashpirovsky Antivirus. That is why he didn't hesitate to download the link one of his groupmates sent him via QIP Infinium. The link was said to contain "some real funny stuff about swine influenza". The antivirus had no objections and Igor K. run the flash application he had ... | 3 | n=input()
a=[]
for i in range(10):
a.append(input())
s=''
for i in range(8):
for g in range(len(a)):
if a[g]==n[10*i:10*(i+1)]:
s+=str(g)
print(s)
|
You have array of n numbers a_{1}, a_{2}, …, a_{n}.
Rearrange these numbers to satisfy |a_{1} - a_{2}| ≤ |a_{2} - a_{3}| ≤ … ≤ |a_{n-1} - a_{n}|, where |x| denotes absolute value of x. It's always possible to find such rearrangement.
Note that all numbers in a are not necessarily different. In other words, some numb... | 1 | from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
def main():
pass
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = ... |
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Bi... | 3 | w=int(input())
flg=0
if w%2!=0 or w==1 or w==2 or w==3:
print("NO")
else:
for i in range(2,w-1):
j=w-i
if i%2==0 and j%2==0:
flg=1
break
if flg==0:
print("NO")
else:
print("YES")
|
Snuke built an online judge to hold a programming contest.
When a program is submitted to the judge, the judge returns a verdict, which is a two-character string that appears in the string S as a contiguous substring. (The judge can return any two-character substring of S.)
Determine whether the judge can return the ... | 3 | s=input()
if(s.find('AC')!=-1):
print("Yes")
else:
print("No") |
New Year is coming and you are excited to know how many minutes remain before the New Year. You know that currently the clock shows h hours and m minutes, where 0 ≤ hh < 24 and 0 ≤ mm < 60. We use 24-hour time format!
Your task is to find the number of minutes before the New Year. You know that New Year comes when the... | 3 | i = int(input())
minuts = []
for i in range(i):
h, m = [int(i) for i in input().split()]
minuts.append((24 - h - 1)*60 + 60 - m)
for elem in minuts:
print(elem)
|
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();print('YNEOS'[s.count('1'*7)<1and s.count('0'*7)<1::2]) |
Every Codeforces user has rating, described with one integer, possibly negative or zero. Users are divided into two divisions. The first division is for users with rating 1900 or higher. Those with rating 1899 or lower belong to the second division. In every contest, according to one's performance, his or her rating ch... | 3 | n=int(input())
mx=10**9
mn=-mx
p=0
for i in range(n):
c,d=[int(i) for i in input().split()]
if d==1:
mn=max(mn,1900-p)
else:
mx=min(mx,1899-p)
p+=c
if mx==10**9:
print('Infinity')
elif mx>=mn:
print(mx+p)
else:
print('Impossible')
|
A little boy Laurenty has been playing his favourite game Nota for quite a while and is now very hungry. The boy wants to make sausage and cheese sandwiches, but first, he needs to buy a sausage and some cheese.
The town where Laurenty lives in is not large. The houses in it are located in two rows, n houses in each r... | 1 | #!/bin/sh
# -*- coding: utf-8 -*-
''''which python2 >/dev/null && exec python2 "$0" "$@" # '''
''''which python >/dev/null && exec python "$0" "$@" # '''
# raw_input
n = int(raw_input())
a1 = map(int, raw_input().split())
a2= map(int, raw_input().split())
b = map(int, raw_input().split())
ans = 10**9
for i in x... |
Takahashi wants to print a document with N pages double-sided, where two pages of data can be printed on one sheet of paper.
At least how many sheets of paper does he need?
Constraints
* N is an integer.
* 1 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
Print the a... | 3 | N = int(input())
a = int((N + 1)/2)
print(a) |
As you know, majority of students and teachers of Summer Informatics School live in Berland for the most part of the year. Since corruption there is quite widespread, the following story is not uncommon.
Elections are coming. You know the number of voters and the number of parties — n and m respectively. For each vote... | 3 | import sys
import os
def solve(m, candidates):
n = len(candidates)
candidates.sort(key=lambda x: x[1])
party = dict()
granted = 0
for i in range(len(candidates)):
p = candidates[i][0]
c = candidates[i][1]
if p == 1:
granted += 1
continue
if ... |
One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are n lines in that description each of which described one goal. Eve... | 3 | n=int(input())
x,y=0,0
for i in range(n):
d=input()
if i==0:
t=d
if d==t:
x+=1
else:
k=d
y+=1
if x>y:
print(t)
else:
print(k)
|
Pashmak has fallen in love with an attractive girl called Parmida since one year ago...
Today, Pashmak set up a meeting with his partner in a romantic garden. Unfortunately, Pashmak has forgotten where the garden is. But he remembers that the garden looks like a square with sides parallel to the coordinate axes. He al... | 3 | import sys
x1, y1, x2, y2 = map(int, sys.stdin.readline().split())
if abs(x1-x2) == 0:
d = abs(y1-y2)
print(x1+d, y1, x1+d, y2, sep=' ')
elif abs(y1-y2) == 0:
d = abs(x1-x2)
print(x1, y1+d, x2, y2+d, sep=' ')
elif abs(x1-x2) == abs(y1-y2):
print(x1, y2, x2, y1, sep=' ')
else:
print("-1")
|
Try guessing the statement from this picture:
<image>
You are given a non-negative integer d. You have to find two non-negative real numbers a and b such that a + b = d and a ⋅ b = d.
Input
The first line contains t (1 ≤ t ≤ 10^3) — the number of test cases.
Each test case contains one integer d (0 ≤ d ≤ 10^3).
... | 1 | # Fall 7, Stand 8...
# !/ankit_SM/bin/env python
from __future__ import division, print_function
import os;
import sys;
from io import BytesIO, IOBase
import math
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
def main():
te... |
Allen has a LOT of money. He has n dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are 1, 5, 10, 20, 100. What is the minimum number of bills Allen could receive after withdrawing his entire balance?
Input
The first... | 3 | import sys,math
try:sys.stdin,sys.stdout=open('input.txt','r'),open('out.txt','w')
except:pass
from sys import stdin,stdout;mod=int(1e9 + 7);from statistics import mode
from collections import *;from math import ceil,floor,inf,factorial,gcd,log2,sqrt,log
ii1=lambda:int(stdin.readline().strip())
is1=lambda:stdin.readlin... |
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 | def colorStones(numberStones,orderStones,count):
#placeHolder = ""
stoneList = []
# if current index is R and the next index isnt continue
# if current index is R and next index is also R remove that next index
for y in orderStones:
stoneList.append(y)
for x in range(len(stoneList)-1):
... |
Write a program which calculates the area and perimeter of a given rectangle.
Constraints
* 1 ≤ a, b ≤ 100
Input
The length a and breadth b of the rectangle are given in a line separated by a single space.
Output
Print the area and perimeter of the rectangle in a line. The two integers should be separated by a si... | 3 | h, w = map(int, input().split())
print(h*w, 2*h+2*w)
|
You are given n chips on a number line. The i-th chip is placed at the integer coordinate x_i. Some chips can have equal coordinates.
You can perform each of the two following types of moves any (possibly, zero) number of times on any chip:
* Move the chip i by 2 to the left or 2 to the right for free (i.e. replace... | 3 | from sys import stdin, stdout
from collections import Counter
import math
def rsingle_int():
return int(stdin.readline().rstrip())
def rmult_int():
return [ int(x) for x in stdin.readline().rstrip().split() ]
def rmult_str():
return stdin.readline().rstrip().split()
def r_str():
return stdin.rea... |
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 | t = int(input())
for i in range(t):
n = int(input())
print('1 {}'.format(n-1)) |
Tom loves vowels, and he likes long words with many vowels. His favorite words are vowelly words. We say a word of length k is vowelly if there are positive integers n and m such that n⋅ m = k and when the word is written by using n rows and m columns (the first row is filled first, then the second and so on, with each... | 3 | k=int(input())
check=False
a=-1
for i in range(5,k+1):
if k%i==0:
if k//i>=5 and i>=5:
check=True
a=i
break
if not check:
print(-1)
else:
n=a
m=k//a
ans=""
x="aeiou"
for i in range(n):
s=""
for j in range(m):
s+=x[(i+j)... |
If you have ever interacted with a cat, you have probably noticed that they are quite particular about how to pet them. Here is an approximate map of a normal cat.
<image>
However, some cats won't tolerate this nonsense from the humans. Here is a map of a grumpy cat.
<image>
You have met a cat. Can you figure out w... | 3 | print(9)
print("grumpy" if input() in ["go die in a hole", "are you serious?", "terrible", "worse", "no way", "don't even"] else "normal")
|
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 | #In The Name of GOD#
input()
a, b ,c, d = map(input().count,('1', '2', '3', '4'))
ans = d
a = max(0, a-c); ans += c+b//2; b%=2
a = max(0, a-b*2); ans += b+(a+3)//4
print(ans) |
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 ... | 1 | n = int(input())
commands = []
for i in range(n):
s = map(int, raw_input().split())
commands.append(s)
cnt = 0
for i in range(n):
home = commands[i]
for j in range(n):
if j != i:
guest = commands[j]
if home[0] == guest[1]:
cnt += 1
print cnt
|
You are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Your task is to choose at most ⌊n/2⌋ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at l... | 3 | class Union:
def __init__(self):
self.parent = -1
self.rank = 1
def Find(self):
if self.parent == -1: return self
return self.parent.Find()
def Unite(self, Node):
L, R = self.Find(), Node.Find()
if L == R: return 0
if L.... |
We have a string S of length N consisting of `R`, `G`, and `B`.
Find the number of triples (i,~j,~k)~(1 \leq i < j < k \leq N) that satisfy both of the following conditions:
* S_i \neq S_j, S_i \neq S_k, and S_j \neq S_k.
* j - i \neq k - j.
Constraints
* 1 \leq N \leq 4000
* S is a string of length N consisting of... | 3 | n=int(input())
s=input()
r=s.count('R')
g=s.count('G')
b=s.count('B')
ans=r*g*b
for i in range(1,(n+1)//2):
for j in range(n-2*i):
if len(set([s[j],s[j+i],s[j+2*i]]))==3:
ans-=1
print(ans) |
Two students of AtCoder Kindergarten are fighting over candy packs.
There are three candy packs, each of which contains a, b, and c candies, respectively.
Teacher Evi is trying to distribute the packs between the two students so that each student gets the same number of candies. Determine whether it is possible.
Not... | 3 | a,b,c=sorted(list(map(int,input().split())))
print("Yes" if a+b==c else "No") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.