problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
You are given an undirected tree of n vertices.
Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex.
You choose an edge and remove it from the tree. Tree falls apart into two connected components. Le... | 3 | import sys
input=sys.stdin.readline
n = int(input())
a = [int(t) for t in input().split(' ')]
mx = [[] for _ in range(n)]
for i in range(n-1):
v1, v2 = map(int,input().split())
mx[v1-1].append(v2-1)
mx[v2-1].append(v1-1)
count = [[0, 0] for _ in range(n)]
total = [a.count(1), a.count(2)]
answer = 0
OBSERVE ... |
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm:
* if the last digit of the number is non-zero, she decreases the number by one;
* if the last digit of the number is ze... | 3 | x=input().split()
for i in range(int(x[1])):
if int(x[0])%10==0:
x[0]=int(x[0])/10
else:
x[0]=int(x[0])-1
print(int(x[0]))
|
You are given an array a consisting of n integers.
You can remove at most one element from this array. Thus, the final length of the array is n-1 or n.
Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.
Recall that the contiguous subarray a wi... | 3 | n=int(input())
a=list(map(int,input().split()))
dp1=[0 for i in range(n+1)]
dp2=[0 for i in range(n+1)]
dp1[1]=1
for i in range(2,n+1):
if(a[i-1]>a[i-2]):
dp1[i]=dp1[i-1]+1
else:
dp1[i]=1
dp2[n]=1
for i in range(n-1,0,-1):
if (a[i-1]<a[i]):
dp2[i]=dp2[i+1]+1
else:
dp2[i... |
There are n candies in a row, they are numbered from left to right from 1 to n. The size of the i-th candy is a_i.
Alice and Bob play an interesting and tasty game: they eat candy. Alice will eat candy from left to right, and Bob — from right to left. The game ends if all the candies are eaten.
The process consists o... | 3 | T = int(input())
for t in range(T):
n = int(input())
A = list(map(int, input().split()))
i = 1
j = n - 1
alice_total_size = A[0]
bob_total_size = 0
prev_size_i = A[0]
prev_size_j = -1
alice_playing = False
moves = 1
while i <= j:
if alice_playing:
s = 0
... |
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 | a, b, c = input().split()
a, b, c = int(a), int(b), int(c)
print(((a + c - 1) // c) * ((b + c - 1) // c)) |
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... | 3 | no=int(input())
a=input().split()
for e in range(len(a)):
a[e]=int(a[e])
ans=0
temp = 0
for each in a:
temp+=each
if temp<0:
ans+=1
temp=0
print(ans)
|
Orac is studying number theory, and he is interested in the properties of divisors.
For two positive integers a and b, a is a divisor of b if and only if there exists an integer c, such that a⋅ c=b.
For n ≥ 2, we will denote as f(n) the smallest positive divisor of n, except 1.
For example, f(7)=7,f(10)=2,f(35)=5.
... | 3 |
t=int(input())
i=0
while i<t:
n,k=map(int,input().split())
for x in range(2,n+1):
if n%x==0:
print(n+x+(2*(k-1)))
break
... |
Today Johnny wants to increase his contribution. His plan assumes writing n blogs. One blog covers one topic, but one topic can be covered by many blogs. Moreover, some blogs have references to each other. Each pair of blogs that are connected by a reference has to cover different topics because otherwise, the readers ... | 3 | import sys
r=sys.stdin.buffer.readline
n,m=map(int,r().split())
network=[[] for _ in range(n)]
for _ in range(m):
a,b=map(int,r().split())
network[a-1].append(b-1)
network[b-1].append(a-1)
lst=list(map(int,r().split()))
arr=list(range(n))
arr.sort(key=lambda x: lst[x])
ret=[1]*n
res=[]
for i in arr:
t=l... |
An integer N is a multiple of 9 if and only if the sum of the digits in the decimal representation of N is a multiple of 9.
Determine whether N is a multiple of 9.
Constraints
* 0 \leq N < 10^{200000}
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output
If N is a multi... | 3 | n=input()
x=0
for i in n:
x+=int(i)
print("Yes" if x%9==0 else "No") |
An X-layered kagami mochi (X ≥ 1) is a pile of X round mochi (rice cake) stacked vertically where each mochi (except the bottom one) has a smaller diameter than that of the mochi directly below it. For example, if you stack three mochi with diameters of 10, 8 and 6 centimeters from bottom to top in this order, you have... | 3 | *a,=map(int,open(0))
print(len(set(a[1:]))) |
Lee is going to fashionably decorate his house for a party, using some regular convex polygons...
Lee thinks a regular n-sided (convex) polygon is beautiful if and only if he can rotate it in such a way that at least one of its edges is parallel to the OX-axis and at least one of its edges is parallel to the OY-axis a... | 3 | #Anuneet Anand
T = int(input())
while T:
n = int(input())
if n%4==0:
print("YES")
else:
print("NO")
T = T - 1
|
Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone.
In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules o... | 3 | l=list(map(int,input().split()))
s=input()
print(s.count('1')*l[0]+s.count('2')*l[1]+s.count('3')*l[2]+s.count('4')*l[3]) |
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).
For a positive integer n, we call a... | 1 | for u in range(int(raw_input())):
print ' '.join(map(str,range(1, int(raw_input()) + 1)[::-1])) |
The only difference between easy and hard versions is constraints.
The BerTV channel every day broadcasts one episode of one of the k TV shows. You know the schedule for the next n days: a sequence of integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ k), where a_i is the show, the episode of which will be shown in i-th day.
The... | 3 | def func(a):
a.sort()
p = a[0]
res = 1
for i in range(len(a)):
if a[i] != p:
p = a[i]
res += 1
return res
t = int(input())
for i in range(t):
n, k, d = map(int, input().split())
a = list(map(int, input().split()))
s = a[:d]
for i in range(1, n-d+1):
... |
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:
* Tetrahedron. Tetrahedron has 4 triangular faces.
* Cube. Cube has 6 square faces.
* Octahedron. Octahedron has 8 triangular faces.
* Dodecahedron. Dodecahedron has 12 pentagonal faces.
*... | 3 | n=int(input())
s={'T':4,'C':6,'O':8,'D':12,'I':20}
print(sum(s[input()[0]] for i in range(n)))
|
There are N slimes lining up in a row. Initially, the i-th slime from the left has a size of a_i.
Taro is trying to combine all the slimes into a larger slime. He will perform the following operation repeatedly until there is only one slime:
* Choose two adjacent slimes, and combine them into a new slime. The new sli... | 3 | N = int(input())
a = list(map(int, input().split()))
if N == 2:
print(sum(a))
exit()
a_cum = [0, a[0]]
for i in range(1,N):
a_cum.append(a_cum[-1] + a[i])
def a_sum(i,j):
return a_cum[j] - a_cum[i]
INF = 10**15
dp = [[INF]*(N+1) for _ in range(N+1)]
for i in range(N):
dp[i][i+1] = 0
if i !=... |
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 | import sys
import math
import bisect
from sys import stdin, stdout
from math import gcd, floor, sqrt, log2, ceil
from collections import defaultdict
from bisect import bisect_left as bl, bisect_right as br
from collections import Counter
from collections import deque
from heapq import heappush,heappop
ip = lambda : i... |
Sereja owns a restaurant for n people. The restaurant hall has a coat rack with n hooks. Each restaurant visitor can use a hook to hang his clothes on it. Using the i-th hook costs ai rubles. Only one person can hang clothes on one hook.
Tonight Sereja expects m guests in the restaurant. Naturally, each guest wants to... | 1 | '''
Time Started :
Fri Jan 24 15:15:00 PST 2014
Time Ended :
'''
def get_profit(hooks, m, d):
hooks = sorted(hooks)
profit, fine = 0, 0
for i in xrange(min(len(hooks),m)):
profit += hooks[i]
fine = max(0, (m-len(hooks))*d)
return profit - fine
nums = map(int, raw_input('').split())
hooks = ... |
Alice has a cute cat. To keep her cat fit, Alice wants to design an exercising walk for her cat!
Initially, Alice's cat is located in a cell (x,y) of an infinite grid. According to Alice's theory, cat needs to move:
* exactly a steps left: from (u,v) to (u-1,v);
* exactly b steps right: from (u,v) to (u+1,v); ... | 3 | t = int(input())
for _ in range(t):
a, b, c, d = map(int, input().split())
x, y, x1, y1, x2, y2 = map(int, input().split())
x += b - a
y += d - c
# if a + b > 0 and x1 == x2:
# print("No")
# elif c + d > 0 and y1 == y2:
# print("No")
if x1 <= x <= x2 and y1 <= y <= y2 and (x2>x1 or a+b==0) and (y2>y1 or c+d=... |
There are N integers, A_1, A_2, ..., A_N, written on the blackboard.
You will choose one of them and replace it with an integer of your choice between 1 and 10^9 (inclusive), possibly the same as the integer originally written.
Find the maximum possible greatest common divisor of the N integers on the blackboard afte... | 3 | import math
import itertools
n = int(input())
a = list(map(int, input().split()))
pf = [0] + list(itertools.accumulate(a, math.gcd))
pb = [0] + list(itertools.accumulate(reversed(a), math.gcd))
pb.reverse()
ans = [0]*n
for i in range(n):
ans[i] = math.gcd(pf[i], pb[i+1])
print(max(ans)) |
There are N squares aligned in a row. The i-th square from the left contains an integer a_i.
Initially, all the squares are white. Snuke will perform the following operation some number of times:
* Select K consecutive squares. Then, paint all of them white, or paint all of them black. Here, the colors of the squares... | 3 | n,k = map(int,input().split())
a = list(map(int, input().split()))
al = [0]*(n+1)
pl = [0]*(n+1)
ans = 0
for i in range(n):
al[i+1] = al[i] + a[i]
pl[i+1] = pl[i]
if a[i] > 0: pl[i+1] += a[i]
for r in range(k-1,n):
l = r-k+1
cur = pl[l] + max(0, al[r+1] - al[l]) + pl[n] - pl[r+1]
if ans < cur: ans = cur
pri... |
Mishka wants to buy some food in the nearby shop. Initially, he has s burles on his card.
Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1 ≤ x ≤ s, buy food that costs exactly x burles and obtain ⌊x/10⌋ burles as a cashback (in other words, Mishka ... | 3 | for _ in range(int(input())):
s = int(input())
if(s<10):
print(s)
else:
temp = s
po = len(str(s))-1
while(s>=10):
curr = (s%(10**po))
val = 10**po - curr
if(val*10 <= s):
s-=(val*10)
temp+=val
... |
Kitahara Haruki has bought n apples for Touma Kazusa and Ogiso Setsuna. Now he wants to divide all the apples between the friends.
Each apple weights 100 grams or 200 grams. Of course Kitahara Haruki doesn't want to offend any of his friend. Therefore the total weight of the apples given to Touma Kazusa must be equal ... | 3 | n=int(input())
s=list(map(int,input().split()))
a=sum(s)
s.count(100)
s.count(200)
if (a//2)%100==0:
if s.count(100)%2==0 and s.count(200)%2==0:
print('YES')
exit()
if s.count(100)>1 and s.count(200)%2==1:
print('YES')
exit()
print('NO')
|
After finishing eating her bun, Alyona came up with two integers n and m. She decided to write down two columns of integers — the first column containing integers from 1 to n and the second containing integers from 1 to m. Now the girl wants to count how many pairs of integers she can choose, one from the first column ... | 3 | n, m = map(int, input().split())
a = [n // 5 + (n % 5 > i) for i in range(5)]
b = [m // 5 + (m % 5 > i) for i in range(5)]
ans = 0
for i in range(4): ans += a[i] * b[3 - i]
print(ans + a[4] * b[4]) |
A new e-mail service "Berlandesk" is going to be opened in Berland in the near future. The site administration wants to launch their project as soon as possible, that's why they ask you to help. You're suggested to implement the prototype of site registration system. The system should work on the following principle.
... | 3 | try:
n = int(input())
l = []
freq = {}
for _ in range(n):
a = input()
if a not in l:
l.append(a)
freq[a] = 1
print("OK")
else:
if a in freq:
freq[a] += 1
b = a+str(freq[a]-1)
print(b)
except:... |
There are n houses along the road where Anya lives, each one is painted in one of k possible colors.
Anya likes walking along this road, but she doesn't like when two adjacent houses at the road have the same color. She wants to select a long segment of the road such that no two adjacent houses have the same color.
H... | 3 | c=input().split()
n=int(c[0])
m=int(c[1])
l2=[]
l3=[]
l=[int(i) for i in input().split()]
l2=[l[0]]
x=0
for i in l[1::]:
if i!=l2[-1]:
l2.append(i)
else:
x=1
l3.append(len(l2))
l2=[l[l.index(i)]]
l3.append(len(l2))
if x==0:
... |
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 | string = [i for i in input().split("+")]
string.sort()
print("+".join(string)) |
A positive (strictly greater than zero) integer is called round if it is of the form d00...0. In other words, a positive integer is round if all its digits except the leftmost (most significant) are equal to zero. In particular, all numbers from 1 to 9 (inclusive) are round.
For example, the following numbers are roun... | 3 | num = int(input())
x = []
for j in range(num):
z = int(input())
x.append(z)
for j in range(num):
y = len(str(x[j]))
z = []
for i in range(y):
if x[j] % 10 != 0:
z.append((x[j] % 10) * (10 ** (i)))
x[j] = x[j] // 10
print(len(z))
print(*z, sep=' ') |
You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes.
You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consi... | 3 | n, m = map(int, input().split())
dict = {}
for i in range(m):
str1, str2 = input().split()
dict[str1] = str2
prof = input().split()
res = []
for i in prof:
if len(dict[i]) < len(i):
res.append(dict[i])
else:
res.append(i)
res = " ".join(res)
print(res)
|
wHAT DO WE NEED cAPS LOCK FOR?
Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage.
Let's consider that a word has been typed with the Caps lock key accidentall... | 1 | s = raw_input()
if len(s) == 1 or s[1:].isupper():
print s.swapcase()
else:
print s
|
Given N integers A_1, ..., A_N, compute A_1 \times ... \times A_N.
However, if the result exceeds 10^{18}, print `-1` instead.
Constraints
* 2 \leq N \leq 10^5
* 0 \leq A_i \leq 10^{18}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 ... A_N
Output
P... | 3 | n=int(input())
ret=1
a=list(map(int,input().split()))
if 0 in a:
print(0)
exit()
for x in a:
ret*=x
if ret>10**18:
print(-1)
exit()
print(ret)
|
Ujan decided to make a new wooden roof for the house. He has n rectangular planks numbered from 1 to n. The i-th plank has size a_i × 1 (that is, the width is 1 and the height is a_i).
Now, Ujan wants to make a square roof. He will first choose some of the planks and place them side by side in some order. Then he will... | 3 | d = int(input())
while d:
_ = input()
A = map(int, input().split())
value=0
for i in sorted(A)[::-1]:
if value >= i:
break
value += 1
print(value)
d -= 1
|
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If... | 3 | n = input()
l = list(n)
l = list(map(int, l))
l1 = [1]*7
l0 = [0]*7
flag = 0
for i in range(0, len(l)-6):
if l[i:i+7] == l0 or l[i:i+7] == l1:
print('YES')
flag = 1
break
if flag == 0:
print('NO')
|
You are given three words s_1, s_2 and s_3, each composed of lowercase English letters, with spaces in between. Print the acronym formed from the uppercased initial letters of the words.
Constraints
* s_1, s_2 and s_3 are composed of lowercase English letters.
* 1 ≤ |s_i| ≤ 10 (1≤i≤3)
Input
Input is given from Stan... | 3 | print("".join([x[0] for x in input().split()]).upper()) |
Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to th... | 3 | a = list(map(int, input().split(" "))) # 4 3 2 1
for i in range(4):
minimum = i
for j in range(i+1, 4):
if a[minimum] > a[j]:
minimum = j
temp = a[i]
a[i] = a[minimum]
a[minimum] = temp
count = 0
for i in range(3):
if a[i] == a[i+1]:
count += 1
print(count)
|
You are given a sequence a, initially consisting of n integers.
You want to transform this sequence so that all elements in it are equal (i. e. it contains several occurrences of the same element).
To achieve this, you choose some integer x that occurs at least once in a, and then perform the following operation any ... | 3 | import sys
input = sys.stdin.readline
############ ---- Input Functions ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(list(s[:len(s) - 1]))
def invr():
return(map(int,input().split()))
t=inp()
for _ in range(t):
... |
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 ... | 3 | l = list(map(int, input().split()))
print(l[0]-max(l[1]+1,l[0]-l[2])+1) |
Bob is playing with 6-sided dice. A net of such standard cube is shown below.
<image>
He has an unlimited supply of these dice and wants to build a tower by stacking multiple dice on top of each other, while choosing the orientation of each dice. Then he counts the number of visible pips on the faces of the dice.
Fo... | 3 | s=int(input())
li=list(map(int,input().split()))
for i in range(s):
if li[i]%14<=6 and li[i]>14 and li[i]%14!=0:
print("YES")
else:
print("NO") |
You are given a rectangular cake, represented as an r × c grid. Each cell either has an evil strawberry, or is empty. For example, a 3 × 4 cake may look as follows:
<image>
The cakeminator is going to eat the cake! Each time he eats, he chooses a row or a column that does not contain any evil strawberries and contain... | 3 | import sys
rc = [int(x) for x in (sys.stdin.readline()).split()]
result = 0
col = []
row = []
ccol = 0
for i in range(rc[0]):
t = list(sys.stdin.readline())
for j in range(len(t) - 1):
if(t[j] == 'S'):
ccol += 1
col.append(j)
if(ccol > 0):
r... |
There is a bookshelf which can fit n books. The i-th position of bookshelf is a_i = 1 if there is a book on this position and a_i = 0 otherwise. It is guaranteed that there is at least one book on the bookshelf.
In one move, you can choose some contiguous segment [l; r] consisting of books (i.e. for each i from l to r... | 3 | t = int(input())
for _ in range(t):
n = int(input())
A = list(map(int, input().split()))
l = 0
cnt = 0
flag = True
for a in A:
if a == 0:
cnt += 1
else:
if flag:
cnt = 0
flag = False
else:
l += cn... |
Mahmoud has n line segments, the i-th of them has length ai. Ehab challenged him to use exactly 3 line segments to form a non-degenerate triangle. Mahmoud doesn't accept challenges unless he is sure he can win, so he asked you to tell him if he should accept the challenge. Given the lengths of the line segments, check ... | 1 | n=int(raw_input())
N=map(int,raw_input().split())
N.sort()
for i in range(n-2):
if N[i+2]<N[i+1]+N[i]:
print "YES"
exit(0)
print "NO" |
n students are taking an exam. The highest possible score at this exam is m. Let a_{i} be the score of the i-th student. You have access to the school database which stores the results of all students.
You can change each student's score as long as the following conditions are satisfied:
* All scores are integers ... | 3 | import statistics
q = int(input())
for i in range(q):
n , m = map(int , input().split())
a = list(map(int ,input().split()))
maxpossible = min(sum(a) , m)
mean = statistics.mean(a)
print(maxpossible) |
There is a rectangle in the xy-plane, with its lower left corner at (0, 0) and its upper right corner at (W, H). Each of its sides is parallel to the x-axis or y-axis. Initially, the whole region within the rectangle is painted white.
Snuke plotted N points into the rectangle. The coordinate of the i-th (1 ≦ i ≦ N) po... | 3 | # 入力
W,H,N=map(int,input().split())
# 左下の座標
X=Y=0
for i in range(N):
# 入力
x,y,a=map(int,input().split())
if a==1:
X=max(X,x)
elif a==2:
W=min(W,x)
elif a==3:
Y=max(Y,y)
else:
H=min(H,y)
# 出力
print(max(W-X,0)*max(H-Y,0)) |
You are given n strings. Each string consists of lowercase English letters. Rearrange (reorder) the given strings in such a way that for every string, all strings that are placed before it are its substrings.
String a is a substring of string b if it is possible to choose several consecutive letters in b in such a way... | 3 | import sys
def Len(n):
return len(n)
n = int(input())
strings = []
for i in range(n):
s = input()
strings.append(s)
for i in range(len(strings)):
for j in range(i, len(strings)):
a = strings[i]
b = strings[j]
if len(a) > len(b):
a, b = b, a
if a not in b:
... |
Recently Vova found n candy wrappers. He remembers that he bought x candies during the first day, 2x candies during the second day, 4x candies during the third day, ..., 2^{k-1} x candies during the k-th day. But there is an issue: Vova remembers neither x nor k but he is sure that x and k are positive integers and k >... | 3 | for i in range(int(input())):
num = int(input())
s = 3
i = 1
while(num%s!=0):
i+=1
s+=pow(2,i)
print(num//s) |
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 | solved=0
n=input()
for i in range (n):
temp=raw_input()
if temp.count('1')>=2:
solved+=1
print solved |
Given a string s of length n and integer k (1 ≤ k ≤ n). The string s has a level x, if x is largest non-negative integer, such that it's possible to find in s:
* x non-intersecting (non-overlapping) substrings of length k,
* all characters of these x substrings are the same (i.e. each substring contains only one ... | 1 | lenStr, lenSub = map(int, raw_input().strip().split())
strAct = list(raw_input().strip())
for i in xrange(lenStr):
strAct[i] = ord(strAct[i]) - 97
strSimple = []
lastVal = strAct[0]
valCount = 1
for i in xrange(1, lenStr):
if strAct[i] == lastVal:
valCount += 1
else:
new = (lastVal, valCount... |
Valera is a lazy student. He has m clean bowls and k clean plates.
Valera has made an eating plan for the next n days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can eat d... | 3 | def main():
l=input().split(' ')
n,m,k=int(l[0]),int(l[1]),int(l[2])
j=input().split(' ')
buff=0
for x in range(0,n):
j[x]=int(j[x])
if j[x]==1:
if m>=1:
m=m-1
else:
m=m-1
buff=buff+1
else:
if k>=1:
k=k-1
elif m>=1:
m=m-1
else:
buff=buff+1
print(buff)
if __name__ == '... |
As AtCoder Beginner Contest 100 is taking place, the office of AtCoder, Inc. is decorated with a sequence of length N, a = {a_1, a_2, a_3, ..., a_N}.
Snuke, an employee, would like to play with this sequence.
Specifically, he would like to repeat the following operation as many times as possible:
For every i satisfy... | 3 | n=int(input())
a=[int(x) for x in input().split()]
c=0
for i in range(n):
while a[i]%2==0:
a[i] /= 2
c += 1
print(c)
|
You are given a set of n segments on the axis Ox, each segment has integer endpoints between 1 and m inclusive. Segments may intersect, overlap or even coincide with each other. Each segment is characterized by two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ m) — coordinates of the left and of the right endpoints.
Consider... | 3 | n,m=map(int,input().split())
l=[]
r=[]
for i in range(n):
a,b=map(int,input().split())
for w in range(a,b+1):
l.append(w)
for i in range(1,m+1):
if i not in l:
r.append(str(i))
print(m-len(set(l)))
print(' '.join(r)) |
Polycarpus is a system administrator. There are two servers under his strict guidance — a and b. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program re... | 3 | #Jai Hanuman
#Om Nama Shivai
#Jai Shree Krisha
#Jai Shree Ram
#Jai Maa BuriThakram
#Jai Maa Kali
#Jai Maa Durga
#Radha-Krisha
a = list()
b = list()
for _ in range(int(input())):
t,x,y = map(int, input().split())
if(t == 1):
a.append(x)
else:
b.append(x)
sm = sum(a)
smh = (len(a)*10)//2
if(sm... |
Last week, Hamed learned about a new type of equations in his math class called Modular Equations. Lets define i modulo j as the remainder of division of i by j and denote it by <image>. A Modular Equation, as Hamed's teacher described, is an equation of the form <image> in which a and b are two non-negative integers a... | 3 | a,b = map(int,input().split())
if a == b:
print("infinity")
elif a < b:
print(0)
else:
res = set()
n = a - b
for i in range(1,int(n** 0.5) + 1):
if n % i == 0 :
if i > b:
res.add(i)
if n // i > b:
res.add(n//i)
print(len(res))
... |
You have n barrels lined up in a row, numbered from left to right from one. Initially, the i-th barrel contains a_i liters of water.
You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels x and y (the x-th barrel shouldn't be empty) and pour any possible amount of wa... | 3 | for t in range(int(input())):
n , k = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
p = a[::-1]
print(sum(p[:k+1])) |
Limak and Radewoosh are going to compete against each other in the upcoming algorithmic contest. They are equally skilled but they won't solve problems in the same order.
There will be n problems. The i-th problem has initial score pi and it takes exactly ti minutes to solve it. Problems are sorted by difficulty — it'... | 3 | n,c = map(int,input().split())
l,r = 0,0
p = list(map(int,input().split()))
t = list(map(int,input().split()))
x1 = 0
p1 = sorted(p, reverse=True)
t1 = sorted(t, reverse=True)
x2 = 0
for i in range(n):
x1+=t[i]
l+=max(0,p[i]-c*x1)
x2+=t1[i]
r+=max(0,p1[i]-c*x2)
if l>r:
print("Limak")
elif l<r:
print("Radewoosh")
... |
Many years ago Berland was a small country where only n people lived. Each person had some savings: the i-th one had a_i burles.
The government considered a person as wealthy if he had at least x burles. To increase the number of wealthy people Berland decided to carry out several reforms. Each reform looked like that... | 3 | for _ in range(int(input())):
n,x = map(int,input().split())
l = list(map(int,input().split()))
l.sort(reverse=True)
c,s,av=0,0,0
for i in range(n):
s+=l[i]
av = s/(i+1)
if av>=x:
c+=1
else:
break
print(c) |
AtCoDeer the deer found two rectangles lying on the table, each with height 1 and width W. If we consider the surface of the desk as a two-dimensional plane, the first rectangle covers the vertical range of [0,1] and the horizontal range of [a,a+W], and the second rectangle covers the vertical range of [1,2] and the ho... | 3 |
x, a, b = map(int, input().split())
print(a - (b + x) if a > b else max(0, b - (a + x))) |
There is a building consisting of 10~000 apartments numbered from 1 to 10~000, inclusive.
Call an apartment boring, if its number consists of the same digit. Examples of boring apartments are 11, 2, 777, 9999 and so on.
Our character is a troublemaker, and he calls the intercoms of all boring apartments, till someone... | 3 | t = int(input())
for _ in range(t):
digit = input()
num = int(digit[0])
sum = (num-1) * 10
for x in range(len(digit)):
sum += x+1
print(sum)
|
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 | t = int(input())
for _ in range(t):
n = int(input())
array = sorted(list(map(int, input().split())))
count = 0
flag = 0
for i in range(len(array) - 1):
if array[i+1] - array[i] <= 1:
count += 1
if n - count == 1:
flag = 1
break
if flag:
... |
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 | # https://codeforces.com/problemset/problem/155/A
kol = int(input())
scores = [int(i) for i in input().split()]
counter = 0
maxim = scores[0]
minim = scores[0]
for elem in scores:
if elem > maxim:
counter +=1
maxim = elem
elif elem < minim:
counter +=1
minim = elem
print(coun... |
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.
Misha has a list of handle change requests. After completing the re... | 1 | n = input()
a = {}
b = {}
for i in xrange(0, n):
x, y = (raw_input().split(' '))
prev = b.get(x)
if prev:
a[prev] = y
b[y] = prev
else:
a[x] = y
b[y] = x
print len(a)
for i in a:
print i, a[i] |
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:
* Tetrahedron. Tetrahedron has 4 triangular faces.
* Cube. Cube has 6 square faces.
* Octahedron. Octahedron has 8 triangular faces.
* Dodecahedron. Dodecahedron has 12 pentagonal faces.
*... | 3 | array = ["Tetrahedron" , "Cube" , "Octahedron" , "Dodecahedron" , "Icosahedron"]
faces = [4 , 6 , 8 , 12 , 20]
n=int(input())
array2=list()
c=0
for i in range(n):
array2.append(input())
c = c + faces[array.index(array2[i])]
print(c) |
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... | 3 | # coding: utf-8
n = int(input())
t = 0
cnt = 0
for i in input().split():
if i == '-1':
if t == 0:
cnt += 1
else:
t -= 1
else:
t += int(i)
print(cnt)
|
There are N people in a group. The personality of each person is denoted by A[i] from the set A, where A[i] denotes the personality of the ith person.
Your task is to find the total persons of different personalities.
INPUT:
First line contains the total number of test cases T, for each test cases, first line deno... | 1 | for i in range(int(raw_input())):
n = int(raw_input())
l = [int(i) for i in raw_input().split()]
print len(set(l)) |
Naman has two binary strings s and t of length n (a binary string is a string which only consists of the characters "0" and "1"). He wants to convert s into t using the following operation as few times as possible.
In one operation, he can choose any subsequence of s and rotate it clockwise once.
For example, if s = ... | 3 | import sys
input = sys.stdin.readline
inputr = lambda: input().rstrip('\n')
n = int(input())
S = inputr()
T = inputr()
if S.count('1') != T.count('1'):
print(-1)
sys.exit(0)
needz = []
needo = []
for i in range(n):
if S[i] == T[i]: continue
if S[i] == '1':
if needo:
needz.append(needo.pop())
else:
... |
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 | a,b = map(int, input().split())
print(next(i for i in range(10000000000) if 3 ** i * a > 2 ** i * b)) |
We have a grid with N rows and M columns of squares. Initially, all the squares are white.
There is a button attached to each row and each column. When a button attached to a row is pressed, the colors of all the squares in that row are inverted; that is, white squares become black and vice versa. When a button attach... | 3 | n, m, k = map(int, input().split())
for i in range(n + 1):
for j in range(m + 1):
if i * (m - j) + (n - i) * j == k:
print('Yes')
exit()
print('No')
|
You are given a broken clock. You know, that it is supposed to show time in 12- or 24-hours HH:MM format. In 12-hours format hours change from 1 to 12, while in 24-hours it changes from 0 to 23. In both formats minutes change from 0 to 59.
You are given a time in format HH:MM that is currently displayed on the broken ... | 3 | #Codeforces 722A
format = input()
time = list(input().split(':'))
if format == '12':
if time[0] == '00':
time[0] = '01'
elif int(time[0]) > 12:
r = '0'
if int(time[0])%10 == 0:
r = '1'
time[0] = r + time[0][-1]
elif format == '24':
if int(time[0]) > 23:
time[0] = '1' + time[0][-1]
if int(time[1]) > 59... |
You are given a 4x4 grid. You play a game — there is a sequence of tiles, each of them is either 2x1 or 1x2. Your task is to consequently place all tiles from the given sequence in the grid. When tile is placed, each cell which is located in fully occupied row or column is deleted (cells are deleted at the same time in... | 3 | s = input()
i, j, k = 0, 0, 0
while i < len(s):
if s[i] == '0':
if j == 0:
print("1 1")
j = 1
else:
print("3 1")
j = 0
else:
if k == 0:
print("4 3")
k = 1
else:
print("4 1")
k = 0
... |
Ridhiman challenged Ashish to find the maximum valued subsequence of an array a of size n consisting of positive integers.
The value of a non-empty subsequence of k elements of a is defined as ∑ 2^i over all integers i ≥ 0 such that at least max(1, k - 2) elements of the subsequence have the i-th bit set in their bin... | 3 | from sys import stdin
from collections import Counter
n = int(stdin.readline())
a = list(map(int, stdin.readline().split()))
ans = 1
for i in range(n):
for j in range(i, n):
for k in range(j, n):
ans = max(ans, (a[i] | a[j] | a[k]))
print(ans)
|
Dreamoon is standing at the position 0 on a number line. Drazil is sending a list of commands through Wi-Fi to Dreamoon's smartphone and Dreamoon follows them.
Each command is one of the following two types:
1. Go 1 unit towards the positive direction, denoted as '+'
2. Go 1 unit towards the negative direction, ... | 3 | def dv(n):
m = n
p = 1
d1 = 0
while m > 0:
d1 = d1 + m % 2 * p
p = p * 10
m = m // 2
return (d1)
a=list(input())
b=list(input())
cord1=a.count('+')-a.count('-')
cord2=b.count('+')-b.count('-')
kol=b.count('?')
if kol !=0:
ll=0
for i in range(0,2**kol+1):
cord... |
n participants of the competition were split into m teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends.
Your task is to write a program that will find the minimum and the maximum number of pairs of friends that could ha... | 3 | from math import ceil
n, m = [ int(x) for x in input().split() ]
max_pares = ((n - m + 1) * (n - m)) // 2
min_pares = 0
mod = n % m
c = ceil(n / m)
aux = mod * ((c * (c - 1)) // 2)
min_pares += aux
a = (n - (c * mod)) / (m - mod)
min_pares += (m - mod) * (a * (a - 1)) // 2
print(int(min_pares), max_pares) |
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... | 1 | # encoding=utf-8
def solve():
n=int(raw_input())
a=map(int,raw_input().split())
cur,res=1,1
for i in range(1,n):
if a[i]>=a[i-1]:
cur+=1
else:
cur=1
res=max(res,cur)
print res
if __name__=='__main__':
solve()
|
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.
The language is that peculiar as it has exactly one variable, called x. Also, there are two operations:
* Operation ++ increases the value of variable x by 1.
* Operation -- decreases the value of variable x by 1.... | 3 | n, x = int(input()), 0
for i in range(n):
s = input()
if s[0] == '+' or s[-1] == '+':
x += 1
else:
x -= 1
print(x) |
Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options:
1. on this day the gym is closed and... | 3 | n=int(input())
x=list(map(int,input().split()))
r=[[0]*n for _ in [0,1,2]]
if x[0]&1==1: r[1][0]=1
if x[0]&2==2: r[2][0]=1
for i in range(1,n):
r[0][i]=max(r[0][i-1],r[1][i-1],r[2][i-1])
if x[i]&1==1: r[1][i]=max(r[0][i-1],r[2][i-1])+1
if x[i]&2==2: r[2][i]=max(r[0][i-1],r[1][i-1])+1
print(n-max(r[0][n-1],r... |
There are n benches in the Berland Central park. It is known that a_i people are currently sitting on the i-th bench. Another m people are coming to the park and each of them is going to have a seat on some bench out of n available.
Let k be the maximum number of people sitting on one bench after additional m people c... | 3 | import heapq
def benches(l,m):
ln=list(l)
heapq.heapify(ln)
i=0
while i <m:
tmp=heapq.heappop(ln)
tmp+=1
heapq.heappush(ln,tmp)
i+=1
print(max(ln),max(l)+m)
n=int(input())
m=int(input())
lt=[]
for _ in range(n):
lt.append(int(input()))
benches(lt,m) |
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 | import sys
input=sys.stdin.buffer.readline
from collections import defaultdict as d
t=int(input())
for _ in range(t):
n,m=[int(x) for x in input().split()]
lh=d(list) #d[temp]:[(l1,h1),(l2,h2)]...
times=[]
for _a in range(n):
t,l,h=[int(x) for x in input().split()]
lh[t].append((l,h))
... |
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==1:
print("-1")
if (n>1 and n%2==0):
print(n//2)
if (n>1 and (n%2)!=0):
print((n//2)-n)
|
You have a large electronic screen which can display up to 998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 7 segments which can be turned on and off to compose different digits. The following picture describes how you can dis... | 3 | t = int (input())
for i in range(t):
n = int(input())
k = n // 2
r = n%2
if r % 2 !=0:
dig = int("7" + "1"*(k-1))
else:
dig = int("1"*k)
print(dig) |
There is a directed graph with N vertices numbered 1 to N and M edges. The i-th edge is directed from Vertex A_i to Vertex B_i, and there are C_i coins placed along that edge. Additionally, there is a button on Vertex N.
We will play a game on this graph. You start the game on Vertex 1 with zero coins, and head for V... | 3 | n, m, p = [int(i) for i in input().split()]
e = [[int(i) for i in input().split()] for _ in range(m)]
for i in e:
i[0] -= 1
i[1] -= 1
i[2] -= p
d = [-10**18] * n
ok1 = [False] * n
ok2 = [False] * n
d[0] = 0
ok1[0] = True
ok2[-1] = True
for _ in range(n):
for a, b, c in e:
if ok1[a]:
... |
On a random day, Neko found n treasure chests and m keys. The i-th chest has an integer a_i written on it and the j-th key has an integer b_j on it. Neko knows those chests contain the powerful mysterious green Grapes, thus Neko wants to open as many treasure chests as possible.
The j-th key can be used to unlock the ... | 3 | n,m=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
ae=0
ao=0
be=0
bo=0
for i in range(n):
if(a[i]%2==0):
ae+=1
else:
ao+=1
for i in range(m):
if(b[i]%2==0):
be+=1
else:
bo+=1
#print(ae,bo)
p=min(ae,bo)+min(ao,be... |
You are given a string s consisting only of lowercase Latin letters.
You can rearrange all letters of this string as you wish. Your task is to obtain a good string by rearranging the letters of the given string or report that it is impossible to do it.
Let's call a string good if it is not a palindrome. Palindrome is... | 3 | for _ in range(int(input())):
s=input()
if len(set(list(s)))==1:
print(-1)
else:
print("".join(sorted(s)))
|
Polycarpus analyzes a string called abracadabra. This string is constructed using the following algorithm:
* On the first step the string consists of a single character "a".
* On the k-th step Polycarpus concatenates two copies of the string obtained on the (k - 1)-th step, while inserting the k-th character of ... | 3 | aaa =0
def f(l1,r1,l2,r2,top):
global aaa
if (l1>r1 or l2> r2):
return 0
if (top-1<=aaa) or (r1-l1+1<=aaa) or (r2-l2+1<=aaa):
return 0
if top==2:
return 1
if (l1>top):
l1 -=top
r1 -= top
if (l2>top):
l2-=top
r2-=top
#print(l1,r1,l2,r2,top)
if (l1==l2 and r1==r2):
return... |
Polycarp has recently created a new level in this cool new game Berlio Maker 85 and uploaded it online. Now players from all over the world can try his level.
All levels in this game have two stats to them: the number of plays and the number of clears. So when a player attempts the level, the number of plays increases... | 3 | for t_ in range(int(input())):
n = int(input())
pc = []
for i in range(n):
pc.append([*map(int, input().split())])
valid = pc[0][0] >= pc[0][1]
if valid:
for i in range(1, n):
d0 = pc[i][0] - pc[i - 1][0]
d1 = pc[i][1] - pc[i - 1][1]
if not (d1 >= ... |
Three friends are going to meet each other. Initially, the first friend stays at the position x = a, the second friend stays at the position x = b and the third friend stays at the position x = c on the coordinate axis Ox.
In one minute each friend independently from other friends can change the position x by 1 to the... | 3 | t=int(input())
for _ in range(t):
ar = list(map(int, input().strip().split()))
ar.sort()
if (ar[0] == ar[1] and ar[1] == ar[2]):
ar[0]=ar[0]
elif(ar[0]==ar[1]):
if ar[1]+1<ar[2]:
ar[0]+=1
ar[1]+=1
ar[2]-=1
elif ar[1]==ar[2]:
if(ar[1]-1>ar[0]... |
You are given a prime number p, n integers a_1, a_2, …, a_n, and an integer k.
Find the number of pairs of indexes (i, j) (1 ≤ i < j ≤ n) for which (a_i + a_j)(a_i^2 + a_j^2) ≡ k mod p.
Input
The first line contains integers n, p, k (2 ≤ n ≤ 3 ⋅ 10^5, 2 ≤ p ≤ 10^9, 0 ≤ k ≤ p-1). p is guaranteed to be prime.
The se... | 3 | from collections import Counter
def pr(a):return (a*(a-1))//2
n,p,k=map(int,input().split())
a=map(int,input().split())
a=Counter([(x**4-x*k+p)%p for x in a])
print(sum(pr(a[x]) for x in a)) |
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 | c = int(input())
a = list(map(int, input().split()))
s = 0
for i in a:
s = s + i
print(s/c) |
Today, the memorable AtCoder Beginner Contest 100 takes place. On this occasion, Takahashi would like to give an integer to Ringo.
As the name of the contest is AtCoder Beginner Contest 100, Ringo would be happy if he is given a positive integer that can be divided by 100 exactly D times.
Find the N-th smallest intege... | 3 | D,N = map(int, input().split())
a=100
print(a**D*N if N<a else a**D*101) |
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 | a=input().split()
b=input().split()
a=list(map(int,a))
b=list(map(int,b))
m=a[1]
k=a[2]
M=max(b)
b.remove(M)
n=max(b)
l=m//(k+1)
mod=m%(k+1)
sum=l*(k*M+n) + mod*M
print (int(sum)) |
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.
We know that several boy&girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair m... | 3 | n=int(input())
b=[int(x) for x in input().split()]
b.sort()
m=int(input())
g=[int(x) for x in input().split()]
g.sort()
i=0;j=0;c=0
while(1):
if abs(b[i]-g[j])<=1:
i+=1;j+=1
c+=1
if i>=n or j>=m:
break
else:
if b[i]>g[j]:
i+=0;j=j+1
elif b[i]<g[j]:... |
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())
str1=""
for i in range(n):
str1+=input()
L=list(str1)
groups=1
x=len(L)
for i in range(x-1):
if L[i]==L[i+1]:
groups+=1
print(groups) |
We have a canvas divided into a grid with H rows and W columns. The square at the i-th row from the top and the j-th column from the left is represented as (i, j).
Initially, all the squares are white. square1001 wants to draw a picture with black paint. His specific objective is to make Square (i, j) black when s_{i, ... | 3 | H,W = map(int,input().split())
S = ["."*(W+2)]+["."+input()+"." for h in range(H)]+["."*(W+2)]
for h in range(1,H+1):
for w in range(1,W+1):
if S[h][w]=="#" and S[h-1][w]=="." and S[h+1][w]=="." and S[h][w-1]=="." and S[h][w+1]==".":
print("No")
exit()
print("Yes")
|
Phoenix has n blocks of height h_1, h_2, ..., h_n, and all h_i don't exceed some value x. He plans to stack all n blocks into m separate towers. The height of a tower is simply the sum of the heights of its blocks. For the towers to look beautiful, no two towers may have a height difference of strictly more than x.
P... | 1 | #####################################
import atexit, io, sys, collections, math, heapq
buffer = io.BytesIO()
sys.stdout = buffer
@atexit.register
def write(): sys.__stdout__.write(buffer.getvalue())
#####################################
def f(his,m,x):
heap = [(0,i+1) for i in range(m)]
heapq.heapify(he... |
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... | 3 | t = int(input())
for j in range(t):
n = int(input())
arr = list(map(int,input().split()))
temp = 0
idx = 0
for i in range(n-2,-1,-1):
if arr[i]<arr[i+1]:
idx = i
break
#print(idx)
while idx>0:
if arr[idx-1]<=arr[idx]:
idx-=1
else:
... |
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... | 1 | n = input()
a = map(int, raw_input().split())
c = 0
M = m = a[0]
for i in a[1:]:
if i > M:
c += 1
M = i
if i < m:
c += 1
m = i
print c |
Two players play a simple game. Each player is provided with a box with balls. First player's box contains exactly n1 balls and second player's box contains exactly n2 balls. In one move first player can take from 1 to k1 balls from his box and throw them away. Similarly, the second player can take from 1 to k2 balls f... | 3 | # You lost the game.
n1,n2,k1,k2 = map(int, input().split())
if n1 > n2:
print("First")
else:
print("Second")
|
Let's call some square matrix with integer values in its cells palindromic if it doesn't change after the order of rows is reversed and it doesn't change after the order of columns is reversed.
For example, the following matrices are palindromic:
<image>
The following matrices are not palindromic because they change... | 3 | n = int(input())
a = list(map(int, input().split()))
s = {}
for q in a:
s[q] = s.get(q, 0)+1
if n % 2 == 0:
if all(q % 4 == 0 for q in s.values()):
print('YES')
keys1 = []
for q in s:
keys1.extend([q]*(s[q]//4))
ans1 = []
for q in range(len(keys1)):
... |
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 a<=c and b>=c:
print("Yes")
else:
print("No") |
Recently a new building with a new layout was constructed in Monocarp's hometown. According to this new layout, the building consists of three types of apartments: three-room, five-room, and seven-room apartments. It's also known that each room of each apartment has exactly one window. In other words, a three-room apar... | 3 | t = int(input())
for i in range(t):
n = int(input())
if n % 10 == 0:
print(0, n // 5, 0)
elif n % 10 == 1:
if n == 1:
print(-1)
else:
print(2, (n - 6) // 5, 0)
elif n % 10 == 2:
if n == 2:
print(-1)
else:
print(0, (n... |
Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones.
Once he thought about a string of length n consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and ... | 3 | n = input()
inp = input()
a = []
a.append(inp[0])
lenA = 1
for i in range(1, len(inp)):
if lenA - 1 < 0:
a.append(inp[i])
lenA = lenA + 1
continue
if a[lenA - 1] != inp[i]:
a.pop()
lenA = lenA - 1
else:
a.append(inp[i])
lenA = lenA + 1
print(len(a))... |
Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the f... | 3 | import sys
input = sys.stdin.readline
from collections import deque
class Graph(object):
"""docstring for Graph"""
def __init__(self,n,d): # Number of nodes and d is True if directed
self.n = n
self.graph = [[] for i in range(n)]
self.parent = [-1 for i in range(n)]
self.directed = d
def addEdge(self,x,y... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.