problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not.
The next prime number after x is the smallest prime number greater than x. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that ... | 3 | n, m = list(map(int, input().split(' ')))
not_prime = False
for i in range(n + 1, n * n):
for j in range(i - 1, 1, -1):
if i % j == 0:
not_prime = True
break
if not_prime:
not_prime = False
else:
print("YES") if i == m else print("NO")
break
|
On the well-known testing system MathForces, a draw of n rating units is arranged. The rating will be distributed according to the following algorithm: if k participants take part in this event, then the n rating is evenly distributed between them and rounded to the nearest lower integer, At the end of the drawing, an ... | 3 | import os, sys, math
# copy unique numbers to new array
# for each non-unique:
# increment lowest digit (with starting from 0 if neccesary) until number becomes unique
def solve(n):
solved = [ n ]
for k in range(2, int(n ** 0.5 + 2), 1):
v = int(math.floor(n / k))
if v != solved[-1]:
solved.append(v)
v =... |
You are going to eat X red apples and Y green apples.
You have A red apples of deliciousness p_1,p_2, \dots, p_A, B green apples of deliciousness q_1,q_2, \dots, q_B, and C colorless apples of deliciousness r_1,r_2, \dots, r_C.
Before eating a colorless apple, you can paint it red or green, and it will count as a red o... | 3 | tmp = list(map(int, input().split()))
x, y, a, b, c = tmp
p = list(map(int, input().split()))
q = list(map(int, input().split()))
r = list(map(int, input().split()))
p.sort()
q.sort()
p = p[a-x:]
q = q[b-y:]
p.extend(q)
p.extend(r)
p.sort()
print(sum(p[len(p)-x-y:])) |
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 | input_1=str(input())
input_2=str(input())
l=input_1.lower()
k=input_2.lower()
s=0
q=0
w=0
for i in range(len(input_1)):
if l[i]==k[i]:
s+=1
elif l[i]!= k[i]:
if ord(l[i])<ord(k[i]):
q+=1
else:
w+=1
break
if s==len(input_1):
print(0)
elif q==1:
prin... |
Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into two pieces so that the sum of numbers from one piece is equal to the sum of numbers from the other piece, an... | 1 | n = input()
arr = map(int, raw_input().split())
ans, s, s2 = 0, 0, sum(arr)
for i in xrange(n-1):
s += arr[i]
if s == s2 - s:
ans += 1
print ans
|
The round carousel consists of n figures of animals. Figures are numbered from 1 to n in order of the carousel moving. Thus, after the n-th figure the figure with the number 1 follows. Each figure has its own type β the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal... | 3 | from sys import stdin
def func():
return
for _ in range(int(stdin.readline())):
n = int(stdin.readline())
arr = list(map(int,stdin.readline().split()))
ans = [1]*n
m = 1
for i in range(n-1):
if arr[i] != arr[i+1]:
if m%2 == 0:
ans[i+1] = ans[i] - 1
... |
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory.
George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living... | 3 | if __name__ == '__main__':
n=int(input())
a=0
for i in range(n):
pi,qi=input().split()
if pi!=qi and int(qi)-int(pi)>=2:
a+=1
print(a)
|
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... | 1 | print raw_input().replace('WUB',' ') |
After winning gold and silver in IOI 2014, Akshat and Malvika want to have some fun. Now they are playing a game on a grid made of n horizontal and m vertical sticks.
An intersection point is any point on the grid which is formed by the intersection of one horizontal stick and one vertical stick.
In the grid shown be... | 3 | a = min([int(x) for x in input().split()])
if a%2 == 0:
print('Malvika')
else:
print('Akshat') |
You are given an array a consisting of n integer numbers.
You have to color this array in k colors in such a way that:
* Each element of the array should be colored in some color;
* For each i from 1 to k there should be at least one element colored in the i-th color in the array;
* For each i from 1 to k al... | 3 | n,k = map(int,input().split())
thewalls = list(map(int,input().split()))
wall_index = {}
for i,wall in enumerate(thewalls):
tmp = wall_index.get(wall,[])
tmp.append(i)
wall_index[wall] = tmp
if max(map(len,wall_index.values()))<=k and n>=k:
print("YES")
res,color = ['1']*n,1
for wall in wall_in... |
Write a program which computes the area of a shape represented by the following three lines:
$y = x^2$
$y = 0$
$x = 600$
It is clear that the area is $72000000$, if you use an integral you learn in high school. On the other hand, we can obtain an approximative area of the shape by adding up areas of many rectangles... | 3 | while True:
try:
d = eval(input())
integral = 0
for i in range(1, int(600 / d)):
integral += (i * d) ** 2
print(integral * d)
except EOFError:
break |
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 | T = int(input())
for t in range(T):
n, m = map(int, input().split())
arr = [list(map(int, input().split())) for i in range(n)]
occrows = set([])
occols = set([])
for i in range(n):
for j in range(m):
if(arr[i][j] == 1):
occrows.add(i)
occols.add(j... |
Dima worked all day and wrote down on a long paper strip his favorite number n consisting of l digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf.
To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive inte... | 3 | def f(s):
if s == '':
return 0
else:
return int(s)
l = int(input())
s = input()
x = l // 2
y = x + 1
while 0 <= y + 1 < l and s[y + 1] == '0':
y -= 1
z = x - 1
while 0 <= z + 1 < l and s[z + 1] == '0':
z += 1
p = x
while 0 <= p + 1 < l and s[p + 1] == '0':
p -= 1
q = x
while 0 <= q... |
Once upon a time, there was a traveler.
He plans to travel using stagecoaches (horse wagons). His starting point and destination are fixed, but he cannot determine his route. Your job in this problem is to write a program which determines the route for him.
There are several cities in the country, and a road network ... | 3 | while True:
N, M, P, A, B = map(int, input().split())
if not (N | M | P | A | B):
break
A, B = A - 1, B - 1
T = [int(x) for x in input().split()]
dp = [[float("inf")] * M for _ in range(1 << N)]
dp[0][A] = 0
edges = []
for _ in range(P):
s, t, c = map(int, input().split()... |
There is a rectangular grid of n rows of m initially-white cells each.
Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and... | 3 | n, m = map(int, input().split())
array, Columns, count = [], [], 1
for i in range(n):
array.append(list(input()))
while array!=[]:
if array.count(array[0])>1:
elem = array[0]
for i in range(array.count(elem)):
array.remove(elem)
for k in range(elem.count('#')):
index = elem.index('#')
Columns.append(in... |
You are given a tree consisting of n vertices. A tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a color assigned to it (a_v = 1 if the vertex v is white and 0 if the vertex v is black).
You have to solve the following problem for each vertex v: what is the maximum difference betwee... | 1 | from collections import deque
import sys,threading
sys.setrecursionlimit(200010)
threading.stack_size(20480000)
input = sys.stdin.readline
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
... |
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.
She starts with 0 money on her account.
In the evening of i-th day a transaction ai occurs. If ai > 0, then ai bourles are deposited to Luba's account. If ai < 0, then ai bourles are withdrawn. And if ai = 0, ... | 3 | n, d = [int(x) for x in input().split()]
tr = [int(x) for x in input().split()]
cash = 0
flag = False
gr = []
for i in tr:
if i != 0:
cash += i
gr.append(cash)
if cash > d:
flag = True
break
if flag:
print(-1)
else:
mx = [-1] * n
mx[-1] = gr[-1]
for i in range(n - 2, ... |
Eleven wants to choose a new name for herself. As a bunch of geeks, her friends suggested an algorithm to choose a name for her. Eleven wants her name to have exactly n characters.
<image>
Her friend suggested that her name should only consist of uppercase and lowercase letters 'O'. More precisely, they suggested th... | 3 | def seqFib():
ret=[]
ret=[1,1]
for i in range(100):
ret.append(ret[-1]+ret[-2])
return ret
l = seqFib()
num=input()
num=int(num)
ans=''
for i in range(num):
if i+1 in l:
ans += 'O'
else :
ans += 'o'
print(ans) |
Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him.
One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For e... | 3 | # i=input
# i()
# m,*s=map(int,i().split())
# n=m
# x=0
# for c in s:
# if c>m:
# x+=1
# m=c
# if c<n:
# x+=1
# n=c
# print(x)
n = int(input())
s = list(map(int,input().split()))[:n]
c = 0
x = s[0]
x2 = s[0]
for i in range(1,n+1):
if (s[i-1]>x):
c+=1
x = s[i-1]
if (s[i - 1] < x2):... |
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like [walls](https://www.youtube.com/watch?v=YR5ApYxkU-U), he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.
Roger Waters has a square grid of size nΓ n and he wants to traverse his grid f... | 3 | t=int(input())
while(t):
t=t-1
n=int(input())
for i in range(n):
s=input()
if(i==0):
ur=s[1]
if(i==1):
ud=s[0]
if(i==n-2):
du=s[-1]
if(i==n-1):
dl=s[-2]
if(ur=='1' and ud=='1'):
if(du=='0' and dl=='0'):
... |
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 | arr = input().split()
k = int(arr[0])
r = int(arr[1])
pay = k
while pay % 10 != r and pay % 10 != 0:
pay += k
print(int(pay / k)) |
Comrade Dujikov is busy choosing artists for Timofey's birthday and is recieving calls from Taymyr from Ilia-alpinist.
Ilia-alpinist calls every n minutes, i.e. in minutes n, 2n, 3n and so on. Artists come to the comrade every m minutes, i.e. in minutes m, 2m, 3m and so on. The day is z minutes long, i.e. the day cons... | 1 | n,m,z=map(int, raw_input().split(' '))
call_arrivals=[n*i for i in range(1,z/n+1)]
cnt=0
for call in call_arrivals:
if call%m==0 and call/m<=z:
# print call,call/m
cnt+=1
print cnt
|
You are given two positive integers n (1 β€ n β€ 10^9) and k (1 β€ k β€ 100). Represent the number n as the sum of k positive integers of the same parity (have the same remainder when divided by 2).
In other words, find a_1, a_2, β¦, a_k such that all a_i>0, n = a_1 + a_2 + β¦ + a_k and either all a_i are even or all a_i ar... | 3 | for _ in range(int(input())):
n,k=map(int,input().split())
l=[]
l1=[]
f1,f2=0,0
a,b=k-1,k-1
s1,s2=0,0
while(a>0):
l.append(2)
s1+=2
a-=1
if (n-s1)%2==0 and n-s1>0:
l.append(n-s1)
f1=1
while(b>0):
l1.append(1)
s2+=1
b-=1... |
You are given integers N and M.
Consider a sequence a of length N consisting of positive integers such that a_1 + a_2 + ... + a_N = M. Find the maximum possible value of the greatest common divisor of a_1, a_2, ..., a_N.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* N \leq M \leq 10^9
Input... | 3 | def calc():
N,M = map(int,input().split())
for gcd in range(M // N,0,-1):
if M % gcd == 0:
break
return(gcd)
print(calc()) |
Shubham has a binary string s. A binary string is a string containing only characters "0" and "1".
He can perform the following operation on the string any amount of times:
* Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa.
... | 3 | t=int(input())
for _ in range(t):
s=list(map(int,list(input())))
c0=0
c1=0
pre=[]
ans=len(s)+1
for i in s:
pre.append([c0,c1])
if i==0:
c0+=1
else:
c1+=1
c0=0
c1=0
post=[]
for i in s[::-1]:
post.append([c0,c1])
if i==0:
c0+=1
else:
c1+=1
post=post[::-1]
for i in range(len(s)):
ans=... |
Andryusha is an orderly boy and likes to keep things in their place.
Today he faced a problem to put his socks in the wardrobe. He has n distinct pairs of socks which are initially in a bag. The pairs are numbered from 1 to n. Andryusha wants to put paired socks together and put them in the wardrobe. He takes the sock... | 3 | #!/usr/bin/env python3
n = int(input())
socks = list(map(int, input().split()))
visited = {}
count = 0
result = []
for val in socks:
visited[val] = 0
for val in socks:
if visited[val] == 1:
visited[val] = 0
count -= 1
result.append(count)
else:
visited[val] = 1
count... |
Robot Doc is located in the hall, with n computers stand in a line, numbered from left to right from 1 to n. Each computer contains exactly one piece of information, each of which Doc wants to get eventually. The computers are equipped with a security system, so to crack the i-th of them, the robot needs to collect at ... | 3 | n=int(input())
l=list(map(int,input().split()))[::-1]
k=0
p=-1
while k!=n:
l=l[::-1]
p+=1
for i in range(n):
if l[i]!=-1 and l[i]<=k:
k+=1
l[i]=-1
print(p) |
For a given array a consisting of n integers and a given integer m find if it is possible to reorder elements of the array a in such a way that β_{i=1}^{n}{β_{j=i}^{n}{(a_j)/(j)}} equals m? It is forbidden to delete elements as well as insert new elements. Please note that no rounding occurs during division, for exampl... | 3 | for i in range(int(input())):
x,y=map(int,input().split())
a=list(map(int,input().split()))
s=sum(a)
if(s==y):
print("YES")
else:
print("NO")
|
You are given two strings s and t. The string s consists of lowercase Latin letters and at most one wildcard character '*', the string t consists only of lowercase Latin letters. The length of the string s equals n, the length of the string t equals m.
The wildcard character '*' in the string s (if any) can be replace... | 3 | n = input()
s = input()
t = input()
p = s.find('*')
if (p == -1):
if (s == t):
print("YES")
else:
print("NO")
exit(0)
sl = len(s) - p - 1
if (s[:p] == t[:p] and t[len(t) - sl:] == s[p + 1:] and len(t) >= len(s) - 1):
print("YES")
else:
print("NO") |
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob.
Right now, Limak and Bob weigh a and b respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight.
Limak eats a lot and his weight is tripled after every year, while Bob's weight... | 3 | l,b = map(int,input().split())
#given b >= l
n = 0
while l <= b:
l=3*l
b=2*b
n+=1
print(n) |
Petr stands in line of n people, but he doesn't know exactly which position he occupies. He can say that there are no less than a people standing in front of him and no more than b people standing behind him. Find the number of different positions Petr can occupy.
Input
The only line contains three integers n, a and ... | 1 | import sys
n,a,b=map(int, sys.stdin.readline().strip().split())
print min(n-a,b+1)
|
Mishka got an integer array a of length n as a birthday present (what a surprise!).
Mishka doesn't like this present and wants to change it somehow. He has invented an algorithm and called it "Mishka's Adjacent Replacements Algorithm". This algorithm can be represented as a sequence of steps:
* Replace each occurre... | 3 | n=int(input())
l=[int(x) for x in input().split()]
for i in range(n):
if l[i]%2==0:
l[i]-=1
print(*l,sep=' ')
|
Little penguin Polo adores strings. But most of all he adores strings of length n.
One day he wanted to find a string that meets the following conditions:
1. The string consists of n lowercase English letters (that is, the string's length equals n), exactly k of these letters are distinct.
2. No two neighbouring... | 1 | line = raw_input().split()
n = int(line[0])
k = int(line[1])
ans = ""
if n < k or k == 1 and n > 1:
print str(-1)
elif n == k:
for i in range(n):
ans += chr(ord('a') + i)
else:
repeat = n - k + 2
for i in range(1, repeat + 1):
if i % 2 == 0:
ans += 'b'
else:
... |
Today Patrick waits for a visit from his friend Spongebob. To prepare for the visit, Patrick needs to buy some goodies in two stores located near his house. There is a d1 meter long road between his house and the first shop and a d2 meter long road between his house and the second shop. Also, there is a road of length ... | 3 | def main():
numbers = input().split()
(d1, d2, d3) = (int(x) for x in numbers)
print(bestRoute(d1, d2, d3))
def bestRoute(d1, d2, d3):
r1 = 2 * d2 + 2 * d3
r2 = 2 * d1 + 2 * d3
r3 = 2 * d1 + 2 * d2
r4 = d1 + d2 + d3
return min(r1, r2, r3, r4)
main()
#print(bestRoute(1, 1, 5)) |
You are given a grid of squares with H horizontal rows and W vertical columns, where each square is painted white or black. HW characters from A_{11} to A_{HW} represent the colors of the squares. A_{ij} is `#` if the square at the i-th row from the top and the j-th column from the left is black, and A_{ij} is `.` if t... | 3 | from collections import deque
H, W = [int(i) for i in input().split()]
A = [list(input()) for _ in range(H)]
Q = deque((i, j, 0) for i in range(H) for j in range(W) if A[i][j] == "#")
ans = 0
while Q:
i, j, dist = Q.popleft()
ans = max(ans, dist)
for di, dj in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
... |
Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play t matches of a digit game...
In each of t matches of the digit game, a positive integer is generated. It consists of n digits. The digits of this integer are numerated f... | 3 | for i in range(int(input())):
n=int(input())
m=input()
a,b,c,d=0,0,0,0
for i in range(n):
if(i%2==0):
if((int(m[i])))%2==0:
a=a+1
else:
b=b+1
else:
if((int(m[i]))%2)==0:
c=c+1
else:
... |
Mike has n strings s1, s2, ..., sn each consisting of lowercase English letters. In one move he can choose a string si, erase the first character and append it to the end of the string. For example, if he has the string "coolmike", in one move he can transform it into the string "oolmikec".
Now Mike asks himself: what... | 1 | def cdist(s1,s2):
ans = 0
while s1 != s2 and ans < len(s1):
ans +=1
s1 = s1[1:] + s1[0]
if ans == len(s1):
return -1
else:
return ans
n = int(raw_input())
ss = []
for i in range(n):
ss.append(raw_input())
t = ss[0]
ans = len(ss)*len(t)
for i in range(len(t)):
... |
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 β€ i β€ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is it... | 3 | n = input()
v = list(map(int, input().split()))
best = 1
current = 1
for i in range(1, len(v)):
if v[i-1] <= v[i]:
current += 1
else:
current = 1
best = max(best, current)
print(best)
|
In order to celebrate Twice's 5th anniversary, Tzuyu and Sana decided to play a game.
Tzuyu gave Sana two integers a and b and a really important quest.
In order to complete the quest, Sana has to output the smallest possible value of (a β x) + (b β x) for any given x, where β denotes the [bitwise XOR operation](http... | 3 | # -*- coding: utf-8 -*-
"""
@author: coding_don
"""
import math
import sys
if __debug__==None:
sys.stdin = open('ip.txt', 'r')
sys.stdout = open('op.txt', 'w')
try:
def main():
t=1
t=int(sys.stdin.readline())
while(t):
a,b=[int(x) for x in sys.stdin.readline().spli... |
Anastasia loves going for a walk in Central Uzhlyandian Park. But she became uninterested in simple walking, so she began to collect Uzhlyandian pebbles. At first, she decided to collect all the pebbles she could find in the park.
She has only two pockets. She can put at most k pebbles in each pocket at the same time.... | 3 | from math import *
n,k = map(int,input().split())
*m,=map(int,input().split())
d=0.0
for i in m:
d+=ceil(i/k)
print(ceil(d/2))
|
Bishwock is a chess figure that consists of three squares resembling an "L-bar". This figure can be rotated by 90, 180 and 270 degrees so it can have four possible states:
XX XX .X X.
X. .X XX XX
Bishwocks don't attack any squares and can even occupy on the adjacent square... | 3 | from sys import stdin, stdout
INF = float('-inf')
a = [stdin.readline().strip(), stdin.readline().strip()]
n = len(a[0])
dp = [[INF, INF, INF, INF] for i in range(n)]
if a[0][0] + a[1][0] == '00':
dp[0][0] = 0
if a[0][0] + a[1][0] == 'X0':
dp[0][1] = 0
if a[0][0] + a[1][0] == '0X':
dp[0][2] = 0
i... |
There was once young lass called Mary,
Whose jokes were occasionally scary.
On this April's Fool
Fixed limerick rules
Allowed her to trip the unwary.
Can she fill all the lines
To work at all times?
On juggling the words
Right around two-thirds
Sh... | 3 | def get_factors(number):
factors = []
str_factors = ''
for i in range(2, number):
if number % i == 0:
factors.append(i)
factors.append(number//i)
str_factors = str(factors[0]) + str(factors[1])
return str_factors
number = int(input())
results = get_factors(number)... |
You are given two arrays of integers a_1,β¦,a_n and b_1,β¦,b_m.
Your task is to find a non-empty array c_1,β¦,c_k that is a subsequence of a_1,β¦,a_n, and also a subsequence of b_1,β¦,b_m. If there are multiple answers, find one of the smallest possible length. If there are still multiple of the smallest possible length, f... | 3 | for _ in range(int(input())):
n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
fl = 0
for i in a:
if i in b:
print("YES")
print(1, i)
fl = 1
break
if fl == 0:
print("NO") |
You are given the array a consisting of n positive (greater than zero) integers.
In one move, you can choose two indices i and j (i β j) such that the absolute difference between a_i and a_j is no more than one (|a_i - a_j| β€ 1) and remove the smallest of these two elements. If two elements are equal, you can remove a... | 3 | for _ in range(int(input())):
num = int(input())
a = list(map(int, input().split()))
a.sort()
count = 0
for i in range(1, num):
if a[i] - a[i - 1] > 1:
count += 1
if count:
print('NO')
else:
print('YES') |
After winning gold and silver in IOI 2014, Akshat and Malvika want to have some fun. Now they are playing a game on a grid made of n horizontal and m vertical sticks.
An intersection point is any point on the grid which is formed by the intersection of one horizontal stick and one vertical stick.
In the grid shown be... | 3 | # -*- coding: utf-8 -*-
import sys
import math
import os
import itertools
import string
import heapq
import _collections
from collections import Counter
from collections import defaultdict
from functools import lru_cache
import bisect
import re
import queue
class Scanner():
@staticmethod
def int():
re... |
Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are n drinks in his fridge, the volume fraction of orange juice in the i-th drink equals pi percent.
One day Vasya decided to make himself an orange cocktail. He took equal proportions of ea... | 3 | n = int(input())
p = map(int, input().split())
s = 0
for each in p:
s += each
print(s/n) |
During the quarantine, Sicromoft has more free time to create the new functions in "Celex-2021". The developers made a new function GAZ-GIZ, which infinitely fills an infinite table to the right and down from the upper left corner as follows:
<image> The cell with coordinates (x, y) is at the intersection of x-th row ... | 1 | t = int(raw_input())
for _ in xrange(t):
x1, y1, x2, y2 = map(int, raw_input().split())
dx = x2 - x1
dy = y2 - y1
ans = None
if dx == 0 or dy == 0:
ans = 1
else:
ans = dx * dy + 1
print ans |
Manao is trying to open a rather challenging lock. The lock has n buttons on it and to open it, you should press the buttons in a certain order to open the lock. When you push some button, it either stays pressed into the lock (that means that you've guessed correctly and pushed the button that goes next in the sequenc... | 3 | el = int(input())
ans = 0
kn = 0
for i in range(el):
ans += el - i
ans += kn * (el - i)
kn += 1
ans -= el - i - 1
print(ans) |
You are given an array a_1, a_2, ..., a_n, consisting of n positive integers.
Initially you are standing at index 1 and have a score equal to a_1. You can perform two kinds of moves:
1. move right β go from your current index x to x+1 and add a_{x+1} to your score. This move can only be performed if x<n.
2. mo... | 3 | t = int(input())
for i in range(t):
n, k, z = map(int, input().split())
arr = list(map(int, input().split()))
arr_sum = [arr[a] + arr[a + 1] for a in range(n - 1)]
maximum = 0
for j in range(min(z + 1, k // 2 + 1)):
maximum = max(sum(arr[:k - 2 * j + 1]) + max(arr_sum[:k - 2 * j + 1]) * j,... |
You are given two positive integers A and B. Compare the magnitudes of these numbers.
Constraints
* 1 β€ A, B β€ 10^{100}
* Neither A nor B begins with a `0`.
Input
Input is given from Standard Input in the following format:
A
B
Output
Print `GREATER` if A>B, `LESS` if A<B and `EQUAL` if A=B.
Examples
Input
3... | 3 | a = int(input())
b = int(input())
print('EQUAL' if a == b else 'GREATER' if a > b else 'LESS')
|
You are given two binary strings x and y, which are binary representations of some two integers (let's denote these integers as f(x) and f(y)). You can choose any integer k β₯ 0, calculate the expression s_k = f(x) + f(y) β
2^k and write the binary representation of s_k in reverse order (let's denote it as rev_k). For e... | 3 | t=int(input())
for i in range(t):
x=input()
y=input()
y=int(y,2)
# print(x,y)
i=0
while(y%2==0):
y//=2
i+=1
f=len(x)
x=x[0:f-i]
j=0
m=0
for i in x:
if(i=='1'):
m=j
j+=1
print(len(x)-m-1) |
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word.
Note, that during capitalization all the letters except the first one remains unchanged.
Input
A single line contains a non-empty word. This word consists of lowercase and uppercase English letters.... | 3 | word=input()
print(word[0].upper()+(word[1:])) |
Alice and Bob are playing chess on a huge chessboard with dimensions n Γ n. Alice has a single piece left β a queen, located at (a_x, a_y), while Bob has only the king standing at (b_x, b_y). Alice thinks that as her queen is dominating the chessboard, victory is hers.
But Bob has made a devious plan to seize the vic... | 3 | '''
Auther: ghoshashis545 Ashis Ghosh
College: jalpaiguri Govt Enggineerin College
Date:12/04/2020
'''
from math import ceil,sqrt,log,gcd
def ii():return int(input())
def si():return input()
def mi():return map(int,input().split())
def li():return list(mi())
dx=[-1,-1,1,1,0,0,-1,1]
dy=[0,-1,1,0,-1,1,1,-1]
... |
There is a rooted tree (see Notes) with N vertices numbered 1 to N. Each of the vertices, except the root, has a directed edge coming from its parent. Note that the root may not be Vertex 1.
Takahashi has added M new directed edges to this graph. Each of these M edges, u \rightarrow v, extends from some vertex u to it... | 3 | from collections import deque
N,M = map(int,input().split())
side = [[]for _ in range(N)]
counts = [0]*N
ans = [0]*N
for i in range(N+M-1):
a,b = map(int,input().split())
side[a-1].append(b-1)
counts[b-1]+=1
queue = deque([counts.index(0)])
while queue:
q = queue.popleft()
for i in side[q]:
... |
Sean is trying to save a large file to a USB flash drive. He has n USB flash drives with capacities equal to a1, a2, ..., an megabytes. The file size is equal to m megabytes.
Find the minimum number of USB flash drives needed to write Sean's file, if he can split the file between drives.
Input
The first line contai... | 3 | n = int(input())
m = int(input())
lista = []
for i in range(n):
l = int(input())
lista.append(l)
lista = sorted(lista, reverse = True)
res = 0
cont = 0
for i in lista:
if res >= m:
break
res += i
cont+=1
print(cont)
|
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 | ans = input().split("WUB")
for i in range(len(ans) - 1, -1, -1):
if ans[i] == "":
ans.pop(i)
print(" ".join(ans))
|
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):
word = input()
print(word if len(word) <= 10 else f'{word[0]}{len(word) - 2}{word[len(word)-1]}') |
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 | from sys import stdin, stdout
import math
input = stdin.readline().split()
n = float(input[0])
m = float(input[1])
a = float(input[2])
stdout.write(str(int(math.ceil(n/a) * math.ceil(m/a)))) |
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 | # weight = int(input())
# if ((weight / 2) % 2 == 0) and weight > 2:
# print('YES')
# else:
# print('NO')
w = int(input())
if(w<=2):
print("NO")
elif((w-2)%2==0):
print("YES")
else:
print("NO") |
Ehab loves number theory, but for some reason he hates the number x. Given an array a, find the length of its longest subarray such that the sum of its elements isn't divisible by x, or determine that such subarray doesn't exist.
An array a is a subarray of an array b if a can be obtained from b by deletion of several... | 1 | __author__ = 'Devesh Bajpai'
'''
https://codeforces.com/problemset/problem/1325/B
Solution: Since we can make n copies of the array, we can pick the smallest element in first
copy, second smallest in second copy and so on. This way we can construct the longest strictly
increasing sub-sequence from the copy array. The... |
You are given three integers A, B and C. Determine whether C is not less than A and not greater than B.
Constraints
* -100β€A,B,Cβ€100
* A, B and C are all integers.
Input
Input is given from Standard Input in the following format:
A B C
Output
If the condition is satisfied, print `Yes`; otherwise, print `No`.
... | 3 | a,b,c=map(int,input().split())
if c < a or b < c:
print('No')
else:
print('Yes') |
Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are n drinks in his fridge, the volume fraction of orange juice in the i-th drink equals pi percent.
One day Vasya decided to make himself an orange cocktail. He took equal proportions of ea... | 3 | n=int(input())
arr = list(map(int, input().split()))
if(n==1):
print(arr[0])
else:
s=sum(arr)
tp=100*n
print (float((s/tp)*100)) |
Olga came to visit the twins Anna and Maria and saw that they have many cookies. The cookies are distributed into bags. As there are many cookies, Olga decided that it's no big deal if she steals a bag. However, she doesn't want the sisters to quarrel because of nothing when they divide the cookies. That's why Olga wan... | 3 | x = int(input())
t = 0
a = list(map(int,input().split()))
for i in range(len(a)):
if a[i]%2 == 1:
t = t + 1
s = len(a) - t
if t%2 == 0:
print(s)
else:
print(t) |
You received a notebook which is called Death Note. This notebook has infinite number of pages. A rule is written on the last page (huh) of this notebook. It says: "You have to write names in this notebook during n consecutive days. During the i-th day you have to write exactly a_i names.". You got scared (of course yo... | 3 | n, m = map(int, input().split())
s = 0
a = list(map(int, input().split()))
for i in range(n):
s += a[i]
print(s // m, end=' ')
s %= m
|
We have a grid with H horizontal rows and W vertical columns. Let (i,j) denote the square at the i-th row from the top and the j-th column from the left.
The square (i, j) has two numbers A_{ij} and B_{ij} written on it.
First, for each square, Takahashi paints one of the written numbers red and the other blue.
Then... | 3 | def fold(x,m):
y = 0
for _ in range(m):
y |= x&1
y <<= 1
x >>= 1
return x|y
lmi = lambda: list(map(int, input().split()))
h,w = lmi()
a = [lmi() for _ in range(2*h)]
g = [[abs(a[i][j] - a[i+h][j]) for j in range(w)] for i in range(h)]
m = 12801
mask = (1<<m) - 1
dp = [0]*(w+1)
dp[... |
Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold:
1. The product of all numbers in the first set is less than zero ( < 0).
2. The product of all numbers in the second set is greater than zero ( > 0).
3. The product of a... | 3 | n=int(input())
m=list(map(int, input().split()))
q=list(filter(lambda x:x>0,m))
w=list(filter(lambda x:x<0,m))
I=lambda x:' '.join(map(str,x))
if len(q):print(1,w[0],'\n1',q[0],'\n'+str(n-2),I(q[1:]+[0]+w[1:]))
else:print(1,w[0],'\n2',w[1],w[2],'\n'+str(n-3),I(w[3:]+[0])) |
Holidays have finished. Thanks to the help of the hacker Leha, Noora managed to enter the university of her dreams which is located in a town Pavlopolis. It's well known that universities provide students with dormitory for the period of university studies. Consequently Noora had to leave ViΔkopolis and move to Pavlopo... | 3 | a,b=map(int,input().split())
ans =1
for i in range (1,min(a,b)+1):
ans=ans*i
print(ans)
|
Dreamoon wants to climb up a stair of n steps. He can climb 1 or 2 steps at each move. Dreamoon wants the number of moves to be a multiple of an integer m.
What is the minimal number of moves making him climb to the top of the stairs that satisfies his condition?
Input
The single line contains two space separated i... | 3 | n,m=map(int,input().split())
if n<m:
print("-1")
else:
t=n//2 + n%2
while t%m!=0:
t+=1
if t%m==0:
print(t) |
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 | x = input().split("+")
x.sort()
s = ""
i = 0
while i < len(x):
s += x[i] + "+"
i+=1
print(s[:-1]) |
You have three tasks, all of which need to be completed.
First, you can complete any one task at cost 0.
Then, just after completing the i-th task, you can complete the j-th task at cost |A_j - A_i|.
Here, |x| denotes the absolute value of x.
Find the minimum total cost required to complete all the task.
Constrain... | 1 | x = map(int,raw_input().split())
print max(x) - min(x) |
You might have remembered Theatre square from the [problem 1A](https://codeforces.com/problemset/problem/1/A). Now it's finally getting repaved.
The square still has a rectangular shape of n Γ m meters. However, the picture is about to get more complicated now. Let a_{i,j} be the j-th square in the i-th row of the pav... | 3 | import sys
import math
import collections
isOnline=not False
istest=not False
if not isOnline:
sys.stdin=open('input.txt','r')
sys.stdout=open('output.txt','w')
inp= lambda : sys.stdin.readline()
m=10**9+7
def nCr(n,r):
if n-r<0:
return 0
return math.factorial(n)//(math.factorial(n-r)*math.factorial(r... |
Gildong was hiking a mountain, walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?
Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wan... | 3 | def lca(u, v):
if h[u] < h[v]:
u, v = v, u
for i in range(h[u].bit_length() - 1, -1, -1):
if par[u][i] != -1 and h[par[u][i]] >= h[v]:
u = par[u][i]
if u == v:
return u
for i in range(h[u].bit_length() - 1, -1, -1):
if par[u][i] != par[v][i]:
u = p... |
You are given a string S consisting of lowercase English letters. We will write down this string, starting a new line after every w letters. Print the string obtained by concatenating the letters at the beginnings of these lines from top to bottom.
Constraints
* 1 \leq w \leq |S| \leq 1000
* S consists of lowercase E... | 3 | #!/usr/bin/env python3
s = input()
w = int(input())
print(s[::w]) |
Using the given four integers from 1 to 9, we create an expression that gives an answer of 10. When you enter four integers a, b, c, d, write a program that outputs an expression that gives an answer of 10 according to the following conditions. Also, if there are multiple answers, only the first answer found will be ou... | 1 | import itertools
def calc(a,op,b):
if op=="+":
return a+b
if op=="-":
return a-b
if op=="*":
return a*b
while True:
nums=map(int,raw_input().split())
if nums==[0,0,0,0]:
break
ans="0"
for a,b,c,d in itertools.permutations(nums,4):
if ans=="0":
... |
Chouti was doing a competitive programming competition. However, after having all the problems accepted, he got bored and decided to invent some small games.
He came up with the following game. The player has a positive integer n. Initially the value of n equals to v and the player is able to do the following operatio... | 3 | v = int(input())
print(v if v==2 else 1) |
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.
Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all custo... | 3 | def solve():
line1 = list(map(lambda x:int(x),input().split()))
n = line1[0]
initial_temp =line1[1]
temp_low = initial_temp
temp_high = initial_temp
time = 0
possible = True
for i in range(0,n):
if possible == False:
input()
continue
linei = list(... |
Today Patrick waits for a visit from his friend Spongebob. To prepare for the visit, Patrick needs to buy some goodies in two stores located near his house. There is a d1 meter long road between his house and the first shop and a d2 meter long road between his house and the second shop. Also, there is a road of length ... | 3 | a,b,c = map(int,input().split(" "))
print(min(2*a+2*b,a+b+c,2*a+2*c,2*b+2*c)) |
There are two standard ways to represent a graph $G = (V, E)$, where $V$ is a set of vertices and $E$ is a set of edges; Adjacency list representation and Adjacency matrix representation.
An adjacency-list representation consists of an array $Adj[|V|]$ of $|V|$ lists, one for each vertex in $V$. For each $u \in V$, th... | 3 | n=int(input())
m=[[0]*n for i in range(n)]
for i in range(n):
tmp=list(map(int,input().split()))
for j in tmp[2:]:
m[i][j-1]=1
for i in range(n):
print(" ".join(list(map(str,m[i]))))
|
You are given a range of positive integers from l to r.
Find such a pair of integers (x, y) that l β€ x, y β€ r, x β y and x divides y.
If there are multiple answers, print any of them.
You are also asked to answer T independent queries.
Input
The first line contains a single integer T (1 β€ T β€ 1000) β the number of... | 3 | t=int(input())
for _ in range(t):
a,b=map(int,input().split())
print(a,2*a)
|
Vanya walks late at night along a straight street of length l, lit by n lanterns. Consider the coordinate system with the beginning of the street corresponding to the point 0, and its end corresponding to the point l. Then the i-th lantern is at the point ai. The lantern lights all points of the street that are at the ... | 3 | #n=int(input());
n=1;
while(n):
n-=1;
t,l=map(int,input().split(" "));
a=list(map(int,input().split(" ")));
a.sort();
res=2*max(a[0],l-a[-1]);
for i in range(1,t):
res=max(res,a[i]-a[i-1]);
print("{0:0.9f}".format(res/2.0));
|
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 |
for _ in range(int(input())):
#word input
word = input()
if len(word)>10: print(word[0]+str(len(word)-2)+word[-1])
else: print(word) |
You are given an array a_1, a_2, ..., a_n where all a_i are integers and greater than 0.
In one operation, you can choose two different indices i and j (1 β€ i, j β€ n). If gcd(a_i, a_j) is equal to the minimum element of the whole array a, you can swap a_i and a_j. gcd(x, y) denotes the [greatest common divisor (GCD)](... | 3 | import sys
for i in range(0,int(sys.stdin.readline())):
leng = sys.stdin.readline()
l =list(map(int,sys.stdin.readline().split()))
l2 = [j for j in l]
l2.sort()
minl = min(l)
works = True
for k in range(0,len(l)):
if l[k]%minl != 0:
works = (l[k] == l2[k])
if works == False:
brea... |
You are given an array a consisting of n positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 2) or determine that there is no such subset.
Both the given array and required subset may contain equal values.
Input
The first line contains a single integer t (1 β€ t β€... | 3 | def main():
t = int(input())
while t:
t -= 1
_ = int(input())
a = list(map(int, input().split()))
even = []
odd = []
for i, e in enumerate(a):
if e % 2 == 0:
even.append(i+1)
else:
odd.append(i+1)
if ... |
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... | 1 | l = raw_input().split('+')
c = {'1': 0, '2': 0, '3': 0}
for i in l:
c[i] += 1
s = []
for key in ['1', '2', '3']:
s += [key] * c[key]
print '+'.join(s)
|
A new airplane SuperPuperJet has an infinite number of rows, numbered with positive integers starting with 1 from cockpit to tail. There are six seats in each row, denoted with letters from 'a' to 'f'. Seats 'a', 'b' and 'c' are located to the left of an aisle (if one looks in the direction of the cockpit), while seats... | 1 | x=raw_input()
l=x[len(x)-1]
n=int(x[0:len(x)-1])
res=n-1
if (l=='f'):
res+=1
elif (l=='e'):
res+=2
elif (l=='d'):
res+=3
elif (l=='a'):
res+=4
elif (l=='b'):
res+=5
elif (l=='c'):
res+=6
if (n%4==1):
res+=(n/4)*2*6
elif(n%4==2):
res+=6
res+=(n/4)*2*6
elif(n%4==3):
res-=2
res+=(n/4)*2*6
elif(n%4==0):
res+=4... |
A positive integer x is called a power of two if it can be represented as x = 2^y, where y is a non-negative integer. So, the powers of two are 1, 2, 4, 8, 16, ....
You are given two positive integers n and k. Your task is to represent n as the sum of exactly k powers of two.
Input
The only line of the input contain... | 3 | def get_bit(n):
count_shifts = 0
while (n > 1):
n = n >> 1
count_shifts += 1
return pow(2, count_shifts)
str_input = input().split()
array = []
n = int(str_input[0])
k = int(str_input[1])
eh_possivel = True
if (k > n):
print("NO")
eh_possivel = False
else:
if (n % 2 != 0)... |
Anton has the integer x. He is interested what positive integer, which doesn't exceed x, has the maximum sum of digits.
Your task is to help Anton and to find the integer that interests him. If there are several such integers, determine the biggest of them.
Input
The first line contains the positive integer x (1 β€ ... | 1 | def solve(x):
base = 1
n = 0
d = 9
last = -1
while d > 0:
if n + base * d <= x:
n = n + base * d
last = d
base = base * 10
else:
d = d - 1
if last == 9:
base = base * 10
if base > 10:
base = base / 10
... |
You are given two strings s and t. Both strings have length n and consist of lowercase Latin letters. The characters in the strings are numbered from 1 to n.
You can successively perform the following move any number of times (possibly, zero):
* swap any two adjacent (neighboring) characters of s (i.e. for any i = ... | 3 | import sys
sys.setrecursionlimit(2000)
from collections import Counter
from functools import reduce
# sys.stdin.readline()
def swap(s, ind):
ind -= 1
s = s[:ind] + s[ind+1] + s[ind] + s[ind+2:]
return s
if __name__ == "__main__":
# single variables
n = [int(val) for val in sys.stdin.readline().sp... |
You have a garland consisting of n lamps. Each lamp is colored red, green or blue. The color of the i-th lamp is s_i ('R', 'G' and 'B' β colors of lamps in the garland).
You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garlan... | 3 | n = int(input())
s = list(input())
minn = 0
if n != 1:
for i in range(n - 2):
if s[i] == s[i + 1] == s[i + 2]:
if s[i] == 'R':
s[i + 1] = 'G'
elif s[i] == 'G':
s[i + 1] = 'B'
else:
s[i + 1] = 'R'
minn += 1
... |
You are given a board of size n Γ n, where n is odd (not divisible by 2). Initially, each cell of the board contains one figure.
In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell (i, j) you can move... | 3 | for i in range(int(input())):
n=int(input())
if n==1:
print(0)
else:
ans=0
for i in range(1,n//2+1):
ans+=i*((2*i+1)**2-(2*i-1)**2)
print(ans)
|
One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of n passwords β strings, consists of small Latin letters.
Hacker went home and started preparing to... | 3 | # by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
def find(dsu,x):
if x == dsu[x]:
return x
dsu[x] = find(dsu,dsu[x])
return dsu[x]
def union_by_rank(dsu,a,b,rank):
a,b = find(dsu,a),find(dsu,b)
if rank[a] > rank[b]:
dsu[b] =... |
Top-model Izabella participates in the competition. She wants to impress judges and show her mathematical skills.
Her problem is following: for given string, consisting of only 0 and 1, tell if it's possible to remove some digits in such a way, that remaining number is a representation of some positive integer, divisi... | 3 |
a = input()
sz = len(a)
flg = 0
cnt = 0
for i in range (0,sz):
k = a[i]
if(int(k)==1) :
flg = 1
continue
if(flg==1 and int(k)==0) :
cnt+=1
if(cnt>=6) :
print("yes")
else :
print("no")
|
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc.... | 3 | a=input()
b=input()
a=a[::-1]
if(a==b):
print("YES")
else:
print("NO") |
Quickly after finishing the tutorial of the online game ATChat, you have decided to visit a particular place with N-1 players who happen to be there. These N players, including you, are numbered 1 through N, and the friendliness of Player i is A_i.
The N players will arrive at the place one by one in some order. To ma... | 3 | n = int(input())
A = list(map(int,input().split()))
A.sort(reverse=True)
ans = 0
for i in range(1,n):
ans+=A[i//2]
print(ans) |
Takahashi became a pastry chef and opened a shop La Confiserie d'ABC to celebrate AtCoder Beginner Contest 100.
The shop sells N kinds of cakes.
Each kind of cake has three parameters "beauty", "tastiness" and "popularity". The i-th kind of cake has the beauty of x_i, the tastiness of y_i and the popularity of z_i.
Th... | 3 | N,M = map(int,input().split())
l = []
for i in range(N):
l.append(list(map(int,input().split())))
ans = 0
for i in range(2**3):
bs = format(i,"03b")
lsum = []
for j in range(N):
lsum.append(sum([l[j][_]*(2*int(bs[_])-1) for _ in range(3)]))
lsum.sort(reverse=True)
ans = max(ans,sum(lsum[:M]))
print(ans... |
You received a notebook which is called Death Note. This notebook has infinite number of pages. A rule is written on the last page (huh) of this notebook. It says: "You have to write names in this notebook during n consecutive days. During the i-th day you have to write exactly a_i names.". You got scared (of course yo... | 1 | n,m=map(int,raw_input().split())
a=map(int,raw_input().split())
p=m
for i in a:
if i<p:
print 0,
p-=i
else:
cnt=1
cnt+=(i-p)/m
print cnt,
p=m-(i-p)%m
|
A permutation of length n is a sequence of integers from 1 to n of length n containing each number exactly once. For example, [1], [4, 3, 5, 1, 2], [3, 2, 1] are permutations, and [1, 1], [0, 1], [2, 2, 1, 4] are not.
There was a permutation p[1 ... n]. It was merged with itself. In other words, let's take two instanc... | 3 | def findarr(x):
arr = []
for i in range(len(x)):
if str(x[i]) not in arr:
arr.append(str(x[i]))
return arr
t = int(input())
for i in range(t):
n = int(input())
a = list(map(int,input().strip().split()))[:2*n]
result = findarr(a)
print(" ".join(result)) |
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 | t = int(input())
for i in range(t):
n = int(input())
lst =[]
dct = dict()
count=0
for i in range(n):
st = input()
for i in range(len(st)):
dct[st[i]]=dct.get(st[i],0)+1
count=count+1
if(count%n!=0):print('NO')
else:
flag=0
for i in dct:... |
Barney is standing in a bar and starring at a pretty girl. He wants to shoot her with his heart arrow but he needs to know the distance between him and the girl to make his shot accurate.
<image>
Barney asked the bar tender Carl about this distance value, but Carl was so busy talking to the customers so he wrote the ... | 3 | def main():
s = input()
print(solver(s))
def solver(s):
(baseS, expS) = s.split('e')
exp = int(expS)
nS = baseS[:firstTrailingZero(baseS)]
if len(nS) - 2 > exp:
nS = nS[0] + nS[2:exp + 2] + \
'.' + nS[exp + 2:]
#if len(baseS) - 2 != exp:
#nS += '.' + baseS[exp + 2:]
#(wholePart, decPart) = nS.split... |
n soldiers stand in a circle. For each soldier his height ai is known. A reconnaissance unit can be made of such two neighbouring soldiers, whose heights difference is minimal, i.e. |ai - aj| is minimal. So each of them will be less noticeable with the other. Output any pair of soldiers that can form a reconnaissance u... | 1 | n=int(raw_input())
A=[int(x) for x in raw_input().split()]
indexi=-1
mini=10000
for i in range(0,n):
if(abs(A[i]-A[(i+1)%n])<mini):
index=i
mini=abs(A[i]-A[(i+1)%n])
print index+1,(index+1)%n+1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.