problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
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 | a=input().split('+')
b=sorted(a)
print('+'.join(b)) |
One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality ... | 3 | n = int(input())
tups = []
for i in range(n):
ai,bi = [int(x) for x in input().split()]
tups.append((ai,bi))
tups.sort(key=lambda x:x[0])
good = True
for i in range(n-1):
_,b0 = tups[i]
_,b1 = tups[i+1]
if b0 > b1:
good = False
if good:
print('Poor Alex')
else:
print('Happy Alex')
... |
There is a box containing N balls. The i-th ball has the integer A_i written on it. Snuke can perform the following operation any number of times:
* Take out two balls from the box. Then, return them to the box along with a new ball, on which the absolute difference of the integers written on the two balls is written.... | 3 | f = lambda: map(int,input().split())
def gcd(a, b):
while b:
a, b = b, a % b
return a
n,k = f()
a = list(f())
g = a[0]
for i in range(1,n):
g = gcd(g,a[i])
print('POSSIBLE' if k<=max(a) and gcd(k,g)==g else 'IMPOSSIBLE')
|
Depth-first search (DFS) follows the strategy to search βdeeperβ in the graph whenever possible. In DFS, edges are recursively explored out of the most recently discovered vertex $v$ that still has unexplored edges leaving it. When all of $v$'s edges have been explored, the search βbacktracksβ to explore edges leaving ... | 3 | from sys import stdin
n = int(stdin.readline())
M = [None] + [list(map(int, stdin.readline().split()[2:])) for i in range(n)]
sndf = [None] + [[False, i] for i in range(1, n + 1)]
tt = 0
def dfs(u):
global tt
sndf[u][0] = True
tt += 1
sndf[u].append(tt)
for v in M[u]:
if not sndf[v][0]:
... |
This problem is same as the next one, but has smaller constraints.
Shiro's just moved to the new house. She wants to invite all friends of her to the house so they can play monopoly. However, her house is too small, so she can only invite one friend at a time.
For each of the n days since the day Shiro moved to the n... | 1 | n=input()
a,b={},{}
ans=1
t=[0]+(map(int,raw_input().split()))
for i in range(1,n+1):
x=t[i]
# print x,a.get(x,0)
a[x]=a.get(x,0)+1
b[a[x]]=b.get(a[x],0)+1
if a[x]*b[a[x]]==i and i!=n:
ans=i+1
elif a[x]*b[a[x]]==i-1:
ans=i
print ans |
The police department of your city has just started its journey. Initially, they donβt have any manpower. So, they started hiring new recruits in groups.
Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime.
If there is no police offi... | 1 | f = lambda: map(int, raw_input().split())
n = raw_input()
n = int(n)
s = f()
rec = 0
ans = 0
for i in range(n):
if s[i] == -1 and rec > 0 :
rec = rec - 1
elif s[i] == -1 and rec == 0 :
ans = ans + 1
else :
rec = rec + s[i]
print ans |
Arpa is researching the Mexican wave.
There are n spectators in the stadium, labeled from 1 to n. They start the Mexican wave at time 0.
* At time 1, the first spectator stands.
* At time 2, the second spectator stands.
* ...
* At time k, the k-th spectator stands.
* At time k + 1, the (k + 1)-th specta... | 3 | n,k,t=map(int,input().split())
if t<k:
print(t)
elif t<n+1:
print(k)
elif t>n:
print(n+k-t)
|
You are given two integers x and y. You can perform two types of operations:
1. Pay a dollars and increase or decrease any of these integers by 1. For example, if x = 0 and y = 7 there are four possible outcomes after this operation:
* x = 0, y = 6;
* x = 0, y = 8;
* x = -1, y = 7;
* x = 1, y = ... | 3 | for _ in range(int(input())):
x,y=map(int,input().split())
a,b=map(int,input().split())
print(min(b*(min(x,y))+a*(abs(x-y)), a*(x+y))) |
Takahashi is going to set a 3-character password.
How many possible passwords are there if each of its characters must be a digit between 1 and N (inclusive)?
Constraints
* 1 \leq N \leq 9
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output
Print the number of possibl... | 1 | #!/usr/bin/env python
from collections import deque, defaultdict
import itertools as ite
import sys
import math
import decimal
sys.setrecursionlimit(1000000)
INF = 10 ** 18
MOD = 10 ** 9 + 7
N = input()
print N * N * N |
Ashish and Vivek play a game on a matrix consisting of n rows and m columns, where they take turns claiming cells. Unclaimed cells are represented by 0, while claimed cells are represented by 1. The initial state of the matrix is given. There can be some claimed cells in the initial state.
In each turn, a player must ... | 3 | from sys import stdin, stdout
import math
n = int(stdin.readline())
for i in range(n):
size = [int(x) for x in stdin.readline().split()]
data = []
for i in range(size[0]):
data.append([int(x) for x in stdin.readline().split()])
least = 0
if size[0] > size[1]:
least = 1
col = ... |
Recently Adaltik discovered japanese crosswords. Japanese crossword is a picture, represented as a table sized a Γ b squares, and each square is colored white or black. There are integers to the left of the rows and to the top of the columns, encrypting the corresponding row or column. The number of integers represents... | 3 | input()
i=[*map(len,filter(None,input().split('W')))]
print(len(i))
print(*i) |
We have an integer sequence A, whose length is N.
Find the number of the non-empty contiguous subsequences of A whose sums are 0. Note that we are counting the ways to take out subsequences. That is, even if the contents of some two subsequences are the same, they are counted individually if they are taken from differ... | 3 | from itertools import accumulate
from collections import Counter
n = input()
c = Counter(accumulate(map(int, input().split())))
c[0]+=1
ans = 0
for x in c:
ans += c[x]*(c[x]-1)//2
print(ans) |
Ivan recently bought a detective book. The book is so interesting that each page of this book introduces some sort of a mystery, which will be explained later. The i-th page contains some mystery that will be explained on page a_i (a_i β₯ i).
Ivan wants to read the whole book. Each day, he reads the first page he didn'... | 3 | n=int(input())
ar=list(map(int,input().split()))
e=1
cnt=0
mx=0
for x in ar:
mx=max(mx,x)
if(e==x and mx==x):
cnt+=1
e+=1
print(cnt)
|
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr... | 3 | s1 = input()
s1 = s1.lower()
s2 = input()
s2 = s2.lower()
s1 = list(s1)
s2 = list(s2)
answer = 0
for i in range(len(s1)):
if s1[i] < s2[i]:
print('-1')
answer = -1
break
if s1[i] > s2[i]:
print('1')
answer = 1
break
else:
continue
if answer == 0:
p... |
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 | #http://codeforces.com/problemset/problem/4/A
import sys
input = sys.stdin.readline
def inp():
return(int(input()))
def halfOrNot(w):
if(w%2 == 0 and w>2):
return 'YES'
else:
return 'NO'
print(halfOrNot(inp())) |
Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be.
... | 3 | s = input()
s1 = input()
d = dict()
f = True
for i in range(len(s)):
a = min(s[i], s1[i])
b = max(s[i], s1[i])
if a != b:
if (a in d and d[a] != b) or (b in d and d[b] != a):
f = False
break
else:
d[a] = b
d[b] = a
else:
if a in d a... |
Gennady owns a small hotel in the countryside where he lives a peaceful life. He loves to take long walks, watch sunsets and play cards with tourists staying in his hotel. His favorite game is called "Mau-Mau".
To play Mau-Mau, you need a pack of 52 cards. Each card has a suit (Diamonds β D, Clubs β C, Spades β S, or ... | 3 | s=input()
a=s[0]
b=s[1]
l=list(map(str,input().split()))
for i in l:
if i[0]==a or i[1]==b:
print('YES')
break
else:
print('NO')
|
Polycarp knows that if the sum of the digits of a number is divisible by 3, then the number itself is divisible by 3. He assumes that the numbers, the sum of the digits of which is divisible by 4, are also somewhat interesting. Thus, he considers a positive integer n interesting if its sum of digits is divisible by 4.
... | 3 | number=int(input())
temp=number
def interesting(number):
addition=0
remainder=0
temp=number
while(number!=0):
remainder=number%10
addition=addition+remainder
number=number//10
return addition%4
for i in range(temp,1100):
if interesting(i)==0:
print... |
Theatre Square in the capital city of Berland has a rectangular shape with the size n Γ m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a Γ a.
What is the least number of flagstones needed to pave the Square? It'... | 3 | m,n,a=input().split()
m=int(m)
n=int(n)
a=int(a)
if m/a!=m//a:
row1=m//a+1
else:
row1=m//a
if n/a!=n//a:
row2=n//a+1
else:
row2=n//a
print(row1*row2) |
A positive integer is called a palindrome if its representation in the
decimal system is the same when read from left to right and from right
to left. For a given positive integer K of not more than 5 digits,
write the value of the smallest palindrome larger than K to output.
Numbers are always displayed withou... | 1 | for t in xrange(int(raw_input())):
n = int(raw_input())+1
while (str(n) != str(n)[::-1]):
n+=1
print n |
Petya and Vasya are competing with each other in a new interesting game as they always do.
At the beginning of the game Petya has to come up with an array of N positive integers. Sum of all elements in his array should be equal to S. Then Petya has to select an integer K such that 0 β€ K β€ S.
In order to win, Vasya ha... | 3 | import sys
try:
sys.stdin = open('Input.txt', 'r')
sys.stdout = open('Output.txt', 'w')
except:
pass
input = sys.stdin.readline
# for testCases in range(int(input())):
n,s = map(int,input().split())
if n<s-n+1:
print("YES")
print(*([1]*(n-1)+[s-n+1]))
print(n)
else:
print("NO") |
A frog is about to return to the burrow. The burrow is D centimeters ahead of the frog, and the frog goes straight toward the burrow. There are only two actions that a frog can do:
* Large jump (go forward L centimeters)
* Small jump (go 1 cm forward)
The frog aims to just land in the burrow without jumping over it... | 3 | d,l = map(int,input().split())
if d % l == 0:
ans = d // l
print(ans)
else:
a1 = d // l
a2 = d % l
print(a1+a2)
|
There are n emotes in very popular digital collectible card game (the game is pretty famous so we won't say its name). The i-th emote increases the opponent's happiness by a_i units (we all know that emotes in this game are used to make opponents happy).
You have time to use some emotes only m times. You are allowed t... | 3 | n,m,k=map(int,input().split())
l=list(map(int,input().split()))
a1=max(l)
l.remove(a1)
a2=max(l)
claw=(m-(m//(k+1)))*a1
claw+=(m//(k+1))*a2
print(claw)
|
Victor tries to write his own text editor, with word correction included. However, the rules of word correction are really strange.
Victor thinks that if a word contains two consecutive vowels, then it's kinda weird and it needs to be replaced. So the word corrector works in such a way: as long as there are two consec... | 3 | def corec(s):
s = list(s)
a = ['a','e','i','o','u','y']
for j in range(len(s)-1):
if(s[j] in a and s[j+1] in a):
del s[j+1]
break
return str(''.join(s))
n = int(input())
s = input()
for i in range(100):
s = corec(s)
print(s)
|
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 | for test in range(int(input())):
n, k = map(int, input().split())
for i in range(2, n + 1):
if n % i == 0:
break
print(n + i + (k - 1) * 2)
|
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... | 1 | print 'CIHGANTO RWEI THHI MH!E\nR\n! '[len(set(raw_input()))%2::2]
|
Snuke stands on a number line. He has L ears, and he will walk along the line continuously under the following conditions:
* He never visits a point with coordinate less than 0, or a point with coordinate greater than L.
* He starts walking at a point with integer coordinate, and also finishes walking at a point with ... | 3 | L = int(input())
A = [int(input()) for i in range(L)]
X = [[0] * 5 for _ in range(L+1)]
X[0] = [0] * 5
for i in range(L):
X[i+1][0] = X[i][0] + A[i]
X[i+1][1] = min(X[i][0], X[i][1]) + (A[i] % 2 if A[i] > 0 else 2)
X[i+1][2] = min(X[i][0], X[i][1], X[i][2]) + ((A[i]+1) % 2)
X[i+1][3] = min(X[i][0], X[i... |
You are given an array a consisting of n integers. You have to find the length of the smallest (shortest) prefix of elements you need to erase from a to make it a good array. Recall that the prefix of the array a=[a_1, a_2, ..., a_n] is a subarray consisting several first elements: the prefix of the array a of length k... | 1 | #####################################
import atexit, io, sys, collections, math, heapq,fractions
buffer = io.BytesIO()
sys.stdout = buffer
@atexit.register
def write(): sys.__stdout__.write(buffer.getvalue())
#####################################
for _ in range(int(raw_input())):
n = int(raw_input())
xis ... |
<image>
One morning the Cereal Guy found out that all his cereal flakes were gone. He found a note instead of them. It turned out that his smart roommate hid the flakes in one of n boxes. The boxes stand in one row, they are numbered from 1 to n from the left to the right. The roommate left hints like "Hidden to the l... | 1 | n,m = map(int, raw_input().split())
l = 1
r = n
for i in range(m):
s = raw_input().split()
if s[2] == 'left':
r = min((r, int(s[4])-1));
else:
l = max((l, int(s[4])+1));
print r-l+1 if l<=r else -1 |
Dawid has four bags of candies. The i-th of them contains a_i candies. Also, Dawid has two friends. He wants to give each bag to one of his two friends. Is it possible to distribute the bags in such a way that each friend receives the same amount of candies in total?
Note, that you can't keep bags for yourself or thro... | 3 | a = [int(x) for x in input().split()]
a.sort()
if a[0] + a[1] + a[2] == a[3] or a[0] + a[3] == a[1] + a[2]:
print('YES')
else:
print('NO')
|
You are given an array a[0 β¦ n-1] of length n which consists of non-negative integers. Note that array indices start from zero.
An array is called good if the parity of each index matches the parity of the element at that index. More formally, an array is good if for all i (0 β€ i β€ n - 1) the equality i mod 2 = a[i] m... | 3 | a=int(input())
for i in range(a):
z=int(input())
c=0
c1=0
k=list(map(int,input().split()))
for j in range(len(k)):
if j%2==0 and k[j]%2!=0:
c+=1
elif j%2!=0 and k[j]%2==0:
c1+=1
if c==c1:print(c)
else:print(-1)
|
Alica and Bob are playing a game.
Initially they have a binary string s consisting of only characters 0 and 1.
Alice and Bob make alternating moves: Alice makes the first move, Bob makes the second move, Alice makes the third one, and so on. During each move, the current player must choose two different adjacent char... | 3 | #872
for _ in range(int(input())):
ss=input()
x=0
y=0
for i in ss:
if(i=='1'):
x+=1
else:
y+=1
if(min(x,y)%2==1):
print("DA")
else:
print("NET")
|
For a positive integer n let's define a function f:
f(n) = - 1 + 2 - 3 + .. + ( - 1)nn
Your task is to calculate f(n) for a given integer n.
Input
The single line contains the positive integer n (1 β€ n β€ 1015).
Output
Print f(n) in a single line.
Examples
Input
4
Output
2
Input
5
Output
-3
Note
f(4)... | 3 | n = int(input())
if n % 2 != 0: print('-',n//2+1, sep='')
else: print(n//2) |
Snuke has N dogs and M monkeys. He wants them to line up in a row.
As a Japanese saying goes, these dogs and monkeys are on bad terms. ("ken'en no naka", literally "the relationship of dogs and monkeys", means a relationship of mutual hatred.) Snuke is trying to reconsile them, by arranging the animals so that there a... | 3 | import math
N, M = input().split()
N = int(N)
M = int(M)
if abs(N - M) > 1:
print(0)
elif N == M:
res = math.factorial(N) * math.factorial(M) * 2
print(res % int(1e9 + 7))
else:
res = math.factorial(N) * math.factorial(M)
print(res % int(1e9 + 7))
|
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 | x = str(input())
y=x[1:-1]
z=set(y.split(', '))
if len(x)==2:
print(0)
else:
p = list(z)
print(len(p)) |
Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot.
He wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fence corners at a single angle a.
Will the robot be able to build the fence Emuskald... | 3 | def main():
test_case = int(input())
for i in range(test_case):
n = int(input())
if 360%(180-n) == 0:
print("YES")
else:
print("NO")
main()
|
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find ... | 3 | n = input()
l = [x for x in n]
c = 0
for i in l:
if(i == '4' or i =='7'):
c+=1
if(c==len(l)):
print("YES")
elif(int(n)%4 == 0 or int(n)%7==0 or int(n)%47 == 0):
print("YES")
else:
print("NO") |
You are given a string s, consisting of brackets of two types: '(', ')', '[' and ']'.
A string is called a regular bracket sequence (RBS) if it's of one of the following types:
* empty string;
* '(' + RBS + ')';
* '[' + RBS + ']';
* RBS + RBS.
where plus is a concatenation of two strings.
In one move... | 3 | t = int(input())
for _ in range(t):
s = input()
zso = kso = sum = 0
for i in range(len(s)):
if s[i] == "(":
zso += 1
elif s[i] == "[":
kso += 1
elif s[i] == ")" and zso > 0:
zso -= 1
sum += 1
elif s[i] == "]" and kso > 0:
... |
Each day in Berland consists of n hours. Polycarp likes time management. That's why he has a fixed schedule for each day β it is a sequence a_1, a_2, ..., a_n (each a_i is either 0 or 1), where a_i=0 if Polycarp works during the i-th hour of the day and a_i=1 if Polycarp rests during the i-th hour of the day.
Days go ... | 3 | n=eval(input())
s=input().split(" ")
arr=list(map(int,s))
count=0
max=0
for i in range(n):
if(arr[i]==0):
if(max<count):
max=count
count=0
else:
count+=1
i=0
if count!=0:
while(arr[i]!=0 and i<n):
count+=1
i+=1
if(count>max):
max=count
print(max)
|
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 |
num = int(input(""));
if num > 2:
if num % 2 == 0:
print("YES")
else:
print("NO")
else:
print("NO")
|
Nikolay has a lemons, b apples and c pears. He decided to cook a compote. According to the recipe the fruits should be in the ratio 1: 2: 4. It means that for each lemon in the compote should be exactly 2 apples and exactly 4 pears. You can't crumble up, break up or cut these fruits into pieces. These fruits β lemons, ... | 1 | a = int(raw_input())
b = int(raw_input())
c = int(raw_input())
cnt = 0
for i in range(1,251):
if i<=a and 2*i<=b and 4*i<=c:
cnt += 1
else:
break
print cnt*7
|
One day Vitaly was going home late at night and wondering: how many people aren't sleeping at that moment? To estimate, Vitaly decided to look which windows are lit in the house he was passing by at that moment.
Vitaly sees a building of n floors and 2Β·m windows on each floor. On each floor there are m flats numbered ... | 3 | # Description of the problem can be found at http://codeforces.com/problemset/problem/595/A
r, c = map(int, input().split())
t = 0
for _ in range(r):
l_w = list(map(int, input().split()))
for i in range(len(l_w) // 2):
if l_w[i * 2] == 1 or l_w[i * 2 + 1] == 1:
t += 1
print(t) |
Caisa is going to have a party and he needs to buy the ingredients for a big chocolate cake. For that he is going to the biggest supermarket in town.
Unfortunately, he has just s dollars for sugar. But that's not a reason to be sad, because there are n types of sugar in the supermarket, maybe he able to buy one. But t... | 3 | pl,k=list(map(int,input().split()))
jam=[]
for x in range(pl):
fa,p=list(map(int,input().split()))
if fa>k:
pass
elif fa==k and p==0:
jam.append(0)
elif fa==k and p>0:
pass
else:
if p==0:
jam.append(0)
else:
jam.append(100-p)
if jam==li... |
Revised
The current era, Heisei, will end on April 30, 2019, and a new era will begin the next day. The day after the last day of Heisei will be May 1, the first year of the new era.
In the system developed by the ACM-ICPC OB / OG Association (Japanese Alumni Group; JAG), the date uses the Japanese calendar (the Japa... | 3 | while True:
input_data = input()
if input_data == "#":
break
g, y, m, d = input_data.split()
y = int(y)
m = int(m)
d = int(d)
if y < 31 or (y == 31 and m <= 4):
print(g, y, m, d)
else:
print("?", str(y - 30), str(m), str(d))
|
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d... | 3 | n=int(input())
s=str(n)
c=0
for i in s:
if i=="4" or i=="7":
c=c+1
f=str(c)
p=0
for i in f:
if i !="4":
if i!="7":
p=1
print("NO")
break
if p==0:
print("YES")
|
Vasya has a pile, that consists of some number of stones. n times he either took one stone from the pile or added one stone to the pile. The pile was non-empty before each operation of taking one stone from the pile.
You are given n operations which Vasya has made. Find the minimal possible number of stones that can b... | 3 | n = int(input())
s = list(input())
f = 0
for i in s:
if(i=='+'):
f+=1
elif(i=='-' and f!=0):
f-=1
print(f)
|
Little X used to play a card game called "24 Game", but recently he has found it too easy. So he invented a new game.
Initially you have a sequence of n integers: 1, 2, ..., n. In a single step, you can pick two of them, let's denote them a and b, erase them from the sequence, and append to the sequence either a + b, ... | 1 | def solve4(n):
ans = ['1 * 2 = 2',
'2 * 3 = 6',
'6 * 4 = 24']
return '\n'.join((ans))
def solve5_odd(n):
ans = []
if n > 5:
for i in xrange(5, n, 2):
ans.append('{} - {} = {}'.format(i+2, i+1, 1))
ans.append('1 * 1 = 1')
ans.extend(['5 - 3 = 2',
'1 + 2 = 3',
'2 * 3 = 6',
'6 * 4 = ... |
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 | str1=input()
if(len(set(str1))%2==0):
print("CHAT WITH HER!")
else:
print("IGNORE HIM!")
|
You are given a set of 2n+1 integer points on a Cartesian plane. Points are numbered from 0 to 2n inclusive. Let P_i be the i-th point. The x-coordinate of the point P_i equals i. The y-coordinate of the point P_i equals zero (initially). Thus, initially P_i=(i,0).
The given points are vertices of a plot of a piecewis... | 3 | n,k = map(int,input().split())
c = 0
c = k//n
if n*c!=k:
c+=1
print(c) |
Given a tree T with non-negative weight, find the height of each node of the tree. For each node, the height is the distance to the most distant leaf from the node.
Constraints
* 1 β€ n β€ 10,000
* 0 β€ wi β€ 1,000
Input
n
s1 t1 w1
s2 t2 w2
:
sn-1 tn-1 wn-1
The first line consists of an integer n which represents th... | 3 | import sys
from operator import itemgetter
sys.setrecursionlimit(200000)
def dfs(u, prev):
global post_order, pre_order
pre_order.append((u, prev))
for w, t in edges[u]:
if t != prev:
dfs(t, u)
post_order.append(u)
n = int(input())
edges = [set() for _ in range(n)]
for _ in ra... |
Theatre Square in the capital city of Berland has a rectangular shape with the size n Γ m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a Γ a.
What is the least number of flagstones needed to pave the Square? It'... | 3 | '''
Theatre Square in the capital city of Berland has a rectangular shape with the size nβΓβm meters.
On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones.
Each flagstone is of the size aβΓβa.
What is the least number of flagstones needed to pave the Square?... |
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 | n=int(input())
l=[]
for i in range(n):
s=input()
l.append(s)
g=1
for i in range(n-1):
if l[i]!=l[i+1]:
g=g+1
print(g)
|
Vus the [Cossack](https://en.wikipedia.org/wiki/Cossacks) holds a programming competition, in which n people participate. He decided to award them all with pens and notebooks. It is known that Vus has exactly m pens and k notebooks.
Determine whether the Cossack can reward all participants, giving each of them at leas... | 3 | n, m, k=[int(n) for n in input().split()]
if(min(m,k)>=n):
print("Yes")
else:
print("No") |
Polycarp wants to train before another programming competition. During the first day of his training he should solve exactly 1 problem, during the second day β exactly 2 problems, during the third day β exactly 3 problems, and so on. During the k-th day he should solve k problems.
Polycarp has a list of n contests, th... | 3 | n = int(input())
a = list(map(int, input().split()))
a.sort()
c = 1
for i in range (n) :
if c <= a[i]:
c +=1
c -= 1
print (c) |
You are given an array a_1, a_2, ... , a_n, which is sorted in non-decreasing order (a_i β€ a_{i + 1}).
Find three indices i, j, k such that 1 β€ i < j < k β€ n and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to a_i, a_j and a_k (for example it is possible to... | 3 | t=int(input())
for i in range(t):
n=int(input())
a=[int(i) for i in input().split()]
v=a[0]+a[1]
a=a[2:]
f=0
for i in range(len(a)):
if(v<=a[i]):
print("1 2",i+3,end='\n')
f=1
break
if(not f):
print("-1",end='\n') |
Phoenix has n coins with weights 2^1, 2^2, ..., 2^n. He knows that n is even.
He wants to split the coins into two piles such that each pile has exactly n/2 coins and the difference of weights between the two piles is minimized. Formally, let a denote the sum of weights in the first pile, and b denote the sum of weigh... | 3 | for _ in range(int(input())):
n = int(input())
cnt = (n/2)-1
mx, mn= 2**(n), 0
for i in range(1, n):
if(cnt):
mx += 2**i
cnt-=1
else:
mn+= 2**i
print(abs(mn-mx)) |
Ilya is a very clever lion, he lives in an unusual city ZooVille. In this city all the animals have their rights and obligations. Moreover, they even have their own bank accounts. The state of a bank account is an integer. The state of a bank account can be a negative number. This means that the owner of the account ow... | 3 | ################### <---------------------- QuickSilver_ ---------------------> ####################
s=input()
n=int(s)
if n>=0:
print(s)
elif n>=-10:
print(0)
else:
a=s[-1]
b=s[-2]
if a>b:
print(int(s[0:-2]+b))
else:
print(int(s[0:-2]+a))
|
Zane the wizard had never loved anyone before, until he fell in love with a girl, whose name remains unknown to us.
<image>
The girl lives in house m of a village. There are n houses in that village, lining in a straight line from left to right: house 1, house 2, ..., house n. The village is also well-structured: hou... | 3 | n,m,k=map(int,input().split())
a=list(map(int,input().split()))
b=[]
for y in range(0,n):
if k>=a[y] and a[y]!=0:
b.append(abs(y-(m-1)))
l=min(b)
print(l*10)
|
Snuke has decided to construct a string that starts with `A` and ends with `Z`, by taking out a substring of a string s (that is, a consecutive part of s).
Find the greatest length of the string Snuke can construct. Here, the test set guarantees that there always exists a substring of s that starts with `A` and ends w... | 3 | import re
s = input()
print(len(re.findall("A(.+)Z", s)[0]) + 2) |
Young boy Artem tries to paint a picture, and he asks his mother Medina to help him. Medina is very busy, that's why she asked for your help.
Artem wants to paint an n Γ m board. Each cell of the board should be colored in white or black.
Lets B be the number of black cells that have at least one white neighbor adja... | 3 | t=int(input())
for _ in range(t):
n,m=map(int,input().split())
for i in range(n-1):
print('B'*m)
print('B'*(m-1)+'W') |
Mishka got a six-faced dice. It has integer numbers from 2 to 7 written on its faces (all numbers on faces are different, so this is an almost usual dice).
Mishka wants to get exactly x points by rolling his dice. The number of points is just a sum of numbers written at the topmost face of the dice for all the rolls M... | 1 | n = int(raw_input())
for i in range(n):
m = int(raw_input())
if (m >= 2 and m <= 7):
print 1
else:
k = m/7
if (m%7 != 0):
k += 1
print k
|
You are given a string s of length n consisting only of lowercase Latin letters.
A substring of a string is a contiguous subsequence of that string. So, string "forces" is substring of string "codeforces", but string "coder" is not.
Your task is to calculate the number of ways to remove exactly one substring from thi... | 1 | a=int(raw_input())
s=raw_input()
s1=s[0]
s2=s[-1]
cont=0
cont2=0
for i in xrange(a):
if s[i]!=s1:
break
cont+=1
for i in xrange(1,a+1):
if s[-i]!=s2:
break
cont2+=1
res=0
if s1!=s2:
res= 1+cont+cont2
else:
if cont+cont2<a:
res= (cont+1)*(cont2+1)
else:
res= (1+a)*a/2
print res%998244353
|
You are given two integers n and m. You have to construct the array a of length n consisting of non-negative integers (i.e. integers greater than or equal to zero) such that the sum of elements of this array is exactly m and the value β_{i=1}^{n-1} |a_i - a_{i+1}| is the maximum possible. Recall that |x| is the absolut... | 3 | for _ in range(int(input())):
n,m=map(int,input().split())
if n==1:
print("0")
elif n==2:
print(m)
else:
print(2*m)
|
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.... | 1 | n = int(raw_input())
aantal = 0
for x in range(n):
if sum([int(y) for y in raw_input().split()]) > 1:
aantal += 1
print aantal |
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... | 3 | input()
L=[int(x)%2 for x in input().split()]
print(L.index(sum(L)==1)+1)
|
There are n friends who want to give gifts for the New Year to each other. Each friend should give exactly one gift and receive exactly one gift. The friend cannot give the gift to himself.
For each friend the value f_i is known: it is either f_i = 0 if the i-th friend doesn't know whom he wants to give the gift to or... | 3 | #-----------------------------------------------------------------------
# Richard Mello
# C - Friends and Gifts
#-----------------------------------------------------------------------
# Recebe
n = int(input())
ganhou = [0] + [int(i) for i in input().split()]
conjunto = set(ganhou)
# VΓͺ quem tΓ‘ sem e quem tΓ‘ indecis... |
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... | 3 | from sys import stdin
input = stdin.readline
def main():
test = int(input())
for _ in range(test):
n = int(input())
# l = [int(i) for i in input().split(" ")]
# x,y,n = [int(i) for i in input().split(" ")]
# a,b,c,d = [int(i) for i in input().split(" ")]
#
# l... |
AtCoder's head office consists of N rooms numbered 1 to N. For any two rooms, there is a direct passage connecting these rooms.
For security reasons, Takahashi the president asked you to set a level for every passage, which is a positive integer and must satisfy the following condition:
* For each room i\ (1 \leq i \... | 3 | n=int(input())
ans=[i&-i for i in range(1,n+1)]
def position_zip(a,flag):
j=1
d={}
for i in sorted(a):
if i in d:continue
d[i]=j
j+=1
if flag==1:return d
return [d[i] for i in a]
ans=position_zip(ans,0)
for i in range(n-1,-1,-1):print(*ans[:i]) |
DZY loves chemistry, and he enjoys mixing chemicals.
DZY has n chemicals, and m pairs of them will react. He wants to pour these chemicals into a test tube, and he needs to pour them in one by one, in any order.
Let's consider the danger of a test tube. Danger of an empty test tube is 1. And every time when DZY pour... | 3 | from collections import defaultdict
g = defaultdict(list)
def dfs(i,visited):
visited.add(i)
for j in g[i]:
if j not in visited:
dfs(j,visited)
n,e = map(int,input().split())
for _ in range(e):
x,y = map(int,input().split())
g[x].append(y)
g[y].append(x)
visited=set()
count=0
for i in g:
if i not in visite... |
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 | x=input()
x=list(x)
y=[]
i=0
while(1):
if(x[i]!="a" and x[i]!="e" and x[i]!="i" and x[i]!="Y" and x[i]!="y" and x[i]!="o" and x[i]!="u" and x[i]!="A" and x[i]!="E" and x[i]!="I" and x[i]!="O" and x[i]!="U"):
y.append(".")
y.append(x[i].lower())
i=i+1
if(i==len(x)):
break
for i in ran... |
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find ... | 3 | import sys
c=0
x=[4,7,47,477,74,744,747,474,447,774]
N=input()
n=[]
for i in N:
n.append(i)
for i in n:
if int(i)==4 or int(i)==7:
c+=1
if c==len(N):
print("YES")
sys.exit()
else:
for i in x:
if int(N)%i==0:
print("YES")
sys.exit()
print("NO")
|
Let's call a string good if and only if it consists of only two types of letters β 'a' and 'b' and every two consecutive letters are distinct. For example "baba" and "aba" are good strings and "abb" is a bad string.
You have a strings "a", b strings "b" and c strings "ab". You want to choose some subset of these strin... | 3 | a,b,ab=[int(i) for i in input().split(' ')]
n=0
ab=2*ab
if a > b:
n=a-b
n=n-1
elif b > a:
n=b-a
n=n-1
if n == 0:
print(ab+a+b)
elif n > 0:
print(a+b+ab-n) |
Ilya is a very clever lion, he lives in an unusual city ZooVille. In this city all the animals have their rights and obligations. Moreover, they even have their own bank accounts. The state of a bank account is an integer. The state of a bank account can be a negative number. This means that the owner of the account ow... | 3 | s = input()
print(int(max(s, s[:-1], s[:-2] + s[-1], key = int))) |
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())
if n==1:
print(1)
exit()
l=[list(map(int,input().split())) for _ in range(n)]
d=[]
for i in range(n):
for j in range(n):
if i!=j:
d.append((l[i][0]-l[j][0],l[i][1]-l[j][1]))
from collections import Counter as c
print(n-c(d).most_common()[0][1]) |
Every day, N passengers arrive at Takahashi Airport. The i-th passenger arrives at time T_i.
Every passenger arrived at Takahashi airport travels to the city by bus. Each bus can accommodate up to C passengers. Naturally, a passenger cannot take a bus that departs earlier than the airplane arrives at the airport. Also... | 3 | n,c,k = map(int,input().split())
t = list(int(input()) for i in range(n))
t.sort()
ans = 0
x = t[0]
y = 1
for i in range(1,n):
if x+k < t[i] or y >= c:
ans += 1
x = t[i]
y = 1
else:
y += 1
print(ans+1) |
Two players play a game.
Initially there are n integers a_1, a_2, β¦, a_n written on the board. Each turn a player selects one number and erases it from the board. This continues until there is only one number left on the board, i. e. n - 1 turns are made. The first player makes the first move, then players alternate t... | 3 | n = int(input())
x = list(map(int,input().split()))
while len(x)!=1:
x.remove(max(x))
if len(x)!=1:
x.remove(min(x))
print(x[0]) |
A new delivery of clothing has arrived today to the clothing store. This delivery consists of a ties, b scarves, c vests and d jackets.
The store does not sell single clothing items β instead, it sells suits of two types:
* a suit of the first type consists of one tie and one jacket;
* a suit of the second type ... | 3 | a,b,c,d,e,f = [int(input()) for i in range(6)]
print(min(a,d)*e+min(b,c,d-min(a,d))*f if e>f else min(b,c,d)*f+min(a,d-min(b,c,d))*e)
#Khoda && me : Hame chi ,Mitune hata doros Beshe ^_^:)
|
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 | str=input("")
str=str.replace("WUB"," ")
print(str) |
Iahub helps his grandfather at the farm. Today he must milk the cows. There are n cows sitting in a row, numbered from 1 to n from left to right. Each cow is either facing to the left or facing to the right. When Iahub milks a cow, all the cows that see the current cow get scared and lose one unit of the quantity of mi... | 3 | n = int(input())
s = k = 0
for i in input()[::2]:
if i == '1':
k += 1
else:
s += k
print(s)
# Made By Mostafa_Khaled |
Theatre Square in the capital city of Berland has a rectangular shape with the size n Γ m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a Γ a.
What is the least number of flagstones needed to pave the Square? It'... | 3 | # 2019-9-28
from sys import stdin, stdout
n, m, a = [int(_.strip()) for _ in stdin.read().split(" ")]
answer = ((n+a-1) // a) * ((m+a-1) // a)
stdout.write("{}\n".format(str(answer))) |
Bob is a pirate looking for the greatest treasure the world has ever seen. The treasure is located at the point T, which coordinates to be found out.
Bob travelled around the world and collected clues of the treasure location at n obelisks. These clues were in an ancient language, and he has only decrypted them at hom... | 3 |
def main():
n = int(input())
points = []
for i in range(n):
points.append([int(x) for x in input().split(' ')])
vectors = []
for i in range(n):
vectors.append([int(x) for x in input().split(' ')])
points = sorted(points,key=lambda x:x[0])
pnts = [points[0]]
for i in... |
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 | l=raw_input().split(' ')
t=int(l[0])
a=int(l[1])
ans=(t*a)/2
print ans
|
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 | s=input()
s=set(s)
k=len(s)
if(k%2==0):
print("CHAT WITH HER!")
else:
print("IGNORE HIM!") |
The only difference between easy and hard versions is constraints.
If you write a solution in Python, then prefer to send it in PyPy to speed up execution time.
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 ... | 3 | import sys, os, io
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
... |
Vector Willman and Array Bolt are the two most famous athletes of Byteforces. They are going to compete in a race with a distance of L meters today.
<image>
Willman and Bolt have exactly the same speed, so when they compete the result is always a tie. That is a problem for the organizers because they want a winner.
... | 1 | import fractions
n, a, b = map(int, raw_input().split(' '))
x = a * b / fractions.gcd(a, b)
k = n / x
kx = k * x
good = k * min(a,b) - 1
last = min(n, kx + min(a,b) - 1)
good += last - kx + 1
g = fractions.gcd(good, n)
print '{}/{}'.format(good / g, n / g)
|
Masha has three sticks of length a, b and c centimeters respectively. In one minute Masha can pick one arbitrary stick and increase its length by one centimeter. She is not allowed to break sticks.
What is the minimum number of minutes she needs to spend increasing the stick's length in order to be able to assemble a ... | 3 | a,b,c=map(int,input().split())
print(max(0,c-a-b+1,b-a-c+1,a-c-b+1))
|
Write a program which reads a sequence of $n$ integers $a_i (i = 1, 2, ... n)$, and prints the minimum value, maximum value and sum of the sequence.
Constraints
* $0 < n \leq 10000$
* $-1000000 \leq a_i \leq 1000000$
Input
In the first line, an integer $n$ is given. In the next line, $n$ integers $a_i$ are given in... | 3 | n = int(input())
a = sorted(list(map(int,input().split())))
print(a[0],a[-1],sum(a))
|
Misha and Vasya participated in a Codeforces contest. Unfortunately, each of them solved only one problem, though successfully submitted it at the first attempt. Misha solved the problem that costs a points and Vasya solved the problem that costs b points. Besides, Misha submitted the problem c minutes after the contes... | 3 | a, b, c, d = [int(x) for x in input().split(' ')]
misha = max([3 * a/10, a - a/250 * c])
vasya = max([3 * b/10, b - b/250 * d])
if misha == vasya:
print('Tie')
else:
print("Misha") if misha > vasya else print("Vasya") |
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.
Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, seco... | 3 | n = int(input())
if n > 1:
for x in range(n-1):
if (x + 1) % 2 == 0:
print("I love that", end=" ")
else:
print("I hate that", end=" ")
else:
print("I hate it")
exit()
if n % 2 == 0:
print("I love it")
else:
print("I hate it")
exit() |
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr... | 3 | x = input().lower()
y = input().lower()
if x == y:
print(0)
elif (x>y):
print(1)
elif (x<y):
print(-1) |
Let's call a string good if and only if it consists of only two types of letters β 'a' and 'b' and every two consecutive letters are distinct. For example "baba" and "aba" are good strings and "abb" is a bad string.
You have a strings "a", b strings "b" and c strings "ab". You want to choose some subset of these strin... | 3 | import math
a, b, c = map(int, input().split())
if abs(b - a) == 0 or abs(b - a) == 1:
print(2 * c + b + a)
else:
if b > a:
b = (a + 1)
else:
a = b + 1
print(2 * c + a + b)
|
Recently, you found a bot to play "Rock paper scissors" with. Unfortunately, the bot uses quite a simple algorithm to play: he has a string s = s_1 s_2 ... s_{n} of length n where each letter is either R, S or P.
While initializing, the bot is choosing a starting index pos (1 β€ pos β€ n), and then it can play any numbe... | 3 | from collections import Counter
opp={"S":"R","R":"P","P":"S"}
for i in range(int(input())):
s=input()
d=Counter(s)
print(opp[d.most_common(1)[0][0]]*len(s)) |
In Republic of Atcoder, there are N prefectures, and a total of M cities that belong to those prefectures.
City i is established in year Y_i and belongs to Prefecture P_i.
You can assume that there are no multiple cities that are established in the same year.
It is decided to allocate a 12-digit ID number to each ci... | 3 | n,m = map(int,input().split())
PY = [list(map(int,input().split()))+[_] for _ in range(m)]
from operator import itemgetter
I = [0]*(n+1)
Ans = [""]*m
PY.sort(key = itemgetter(1))
for py in PY:
I[py[0]] += 1
Ans[py[2]] = str(format(py[0],"06d"))+str(format(I[py[0]],"06d"))
print(*Ans,sep="\n") |
Fedya studies in a gymnasium. Fedya's maths hometask is to calculate the following expression:
(1n + 2n + 3n + 4n) mod 5
for given value of n. Fedya managed to complete the task. Can you? Note that given number n can be extremely large (e.g. it can exceed any integer type of your programming language).
Input
The si... | 1 | n=int(raw_input())
exp=n%4
ans=pow(1,exp)+pow(2,exp)+pow(3,exp)+pow(4,exp)
ans%=5
print ans |
You are given two integers n and m. You have to construct the array a of length n consisting of non-negative integers (i.e. integers greater than or equal to zero) such that the sum of elements of this array is exactly m and the value β_{i=1}^{n-1} |a_i - a_{i+1}| is the maximum possible. Recall that |x| is the absolut... | 3 | for _ in range(int(input())):
X = list(map(int, input().split()))
if X[0]==1:
print(0)
elif X[0]==2:
print(X[1])
else:
print(X[1]*2)
# Hope the best for Ravens
# Never give up
|
You've got a 5 Γ 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix:
1.... | 3 | for i in range(5):
s = input().split(' ')
if '1' in s:
print(abs(i - 2) + abs(s.index('1') - 2))
|
Write a program which computes the greatest common divisor (GCD) and the least common multiple (LCM) of given a and b.
Constraints
* 0 < a, b β€ 2,000,000,000
* LCM(a, b) β€ 2,000,000,000
* The number of data sets β€ 50
Input
Input consists of several data sets. Each data set contains a and b separated by a single spa... | 3 | import math
while True:
try:
a, b = map(int, input().split(" "))
print(math.gcd(max(a, b), min(a, b)), int(max(a, b) * min(a, b) / math.gcd(max(a, b), min(a, b))))
except:
break
|
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [... | 3 | import math
LI = lambda: list(map(int,input().split()))
MI = lambda: map(int,input().split())
yes = lambda: print("YES")
no = lambda: print("NO")
I = lambda: list(input())
J = lambda x: "".join(x)
II = lambda: int(input())
SI = lambda: input()
#---khan17---template
t = II()
mi = -10**9
for q in range(t):
n = II()
a =... |
Polycarpus is the director of a large corporation. There are n secretaries working for the corporation, each of them corresponds via the famous Spyke VoIP system during the day. We know that when two people call each other via Spyke, the Spyke network assigns a unique ID to this call, a positive integer session number.... | 1 | import sys
n = int(sys.stdin.readline())
data = {}
cnt = 0
sessions = map(int, sys.stdin.readline().split())
for session in sessions:
if session == 0:
continue
val = data.get(session, 0) + 1
if val == 2:
cnt += 1
elif val > 2:
print '-1'
quit()
data[session... |
Petya works as a PR manager for a successful Berland company BerSoft. He needs to prepare a presentation on the company income growth since 2001 (the year of its founding) till now. Petya knows that in 2001 the company income amounted to a1 billion bourles, in 2002 β to a2 billion, ..., and in the current (2000 + n)-th... | 1 | import sys
n = sys.stdin.readline()
rises = sys.stdin.readline()
nextrise = 1
nextyear = 2001
years = []
for rise in rises.split(" "):
if int(rise) == nextrise:
years.append(str(nextyear))
nextrise += 1
nextyear += 1
print len(years)
print (' ').join(years)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.