problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
There are n rectangles in a row. You can either turn each rectangle by 90 degrees or leave it as it is. If you turn a rectangle, its width will be height, and its height will be width. Notice that you can turn any number of rectangles, you also can turn all or none of them. You can not change the order of the rectangle... | 3 | n = int(input())
prev = 0
ans = True
for i in range(n):
w, h = map(int, input().split())
if i == 0:
prev = max(w, h)
else:
if h < w:
w, h = h, w
if h <= prev:
prev = h
elif w <= prev:
prev = w
else:
ans = False
... |
Alice is playing with some stones.
Now there are three numbered heaps of stones. The first of them contains a stones, the second of them contains b stones and the third of them contains c stones.
Each time she can do one of two operations:
1. take one stone from the first heap and two stones from the second heap (... | 3 | t = int(input())
for _ in range(t):
a, b, c = (int(x) for x in input().split())
x = min(b, c // 2)
print(3 * (x + min(a, (b - x) // 2))) |
In this task you need to process a set of stock exchange orders and use them to create order book.
An order is an instruction of some participant to buy or sell stocks on stock exchange. The order number i has price pi, direction di β buy or sell, and integer qi. This means that the participant is ready to buy or sell... | 3 | n, m = map(int, input().split())
s = {}
b = {}
for _ in range(n):
a = list(input().split())
if a[0] == 'S':
if int(a[1]) in s:
s[int(a[1])] += int(a[2])
else:
s[int(a[1])] = int(a[2])
else:
if int(a[1]) in b:
b[int(a[1])] += int(a[2])
else:... |
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that membe... | 3 |
from collections import deque , defaultdict
e = 0
vx = 0
def dfs(node):
global e , vx
q = deque()
q.append(node)
while q :
s = q.popleft()
if not visited[s]:
visited[s] = True
vx += 1
for j in g[s]:
if not visited[j]:
... |
You're given an array b of length n. Let's define another array a, also of length n, for which a_i = 2^{b_i} (1 β€ i β€ n).
Valerii says that every two non-intersecting subarrays of a have different sums of elements. You want to determine if he is wrong. More formally, you need to determine if there exist four integers... | 3 | t=int(input())
for i in range(t):
n=int(input())
#n,k = map(int, input().strip().split(' '))
b = list(map(int, input().strip().split(' ')))
a = list( dict.fromkeys(b) )
if len(a)==len(b):
print('NO')
else:
print('YES') |
Anton likes to play chess, and so does his friend Danik.
Once they have played n games in a row. For each game it's known who was the winner β Anton or Danik. None of the games ended with a tie.
Now Anton wonders, who won more games, he or Danik? Help him determine this.
Input
The first line of the input contains a... | 3 | input()
s=str(input())
if s.count("A")>s.count("D"):print("Anton")
elif s.count("D")>s.count("A"):print("Danik")
else:print("Friendship") |
There are N squares arranged in a row, numbered 1, 2, ..., N from left to right. You are given a string S of length N consisting of `.` and `#`. If the i-th character of S is `#`, Square i contains a rock; if the i-th character of S is `.`, Square i is empty.
In the beginning, Snuke stands on Square A, and Fnuke stand... | 3 | n,a,b,c,d=map(int,input().split());s=input();print('YNeos'[not'...'*(d<c)in s[b-2:d+1]or'##'in s[a:d]::2]) |
Tavak and Seyyed are good friends. Seyyed is very funny and he told Tavak to solve the following problem instead of longest-path.
You are given l and r. For all integers from l to r, inclusive, we wrote down all of their integer divisors except 1. Find the integer that we wrote down the maximum number of times.
Solve... | 3 | l, r = input().split()
if l != r:
print(2)
else:
print(l)
|
A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay iΒ·k dollars for the i-th banana).
He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas?
Input
The first lin... | 3 | def soldier_with_banana(k,w,n):
firstvalue=k
for i in range(2,n+1):
k=k+i*firstvalue
answer=k-w
if answer<0:
print(0)
else:
print(answer)
x,y,z=str(input()).split(" ")
soldier_with_banana(int(x),int(y),int(z))
|
Alice and Bob have received three big piles of candies as a gift. Now they want to divide these candies as fair as possible. To do this, Alice takes one pile of candies, then Bob takes one of the other two piles. The last pile is split between Alice and Bob as they want: for example, it is possible that Alice takes the... | 3 | n = int(input())
hasil = 0
for i in range(n):
angka = input().split()
for j in angka:
hasil += int(j)
print(hasil//2)
hasil = 0 |
Two boys decided to compete in text typing on the site "Key races". During the competition, they have to type a text consisting of s characters. The first participant types one character in v1 milliseconds and has ping t1 milliseconds. The second participant types one character in v2 milliseconds and has ping t2 millis... | 3 | s,v1,v2,t1,t2 =input().split(" ")
s=int(s)
v1=int(v1)
v2=int(v2)
t1=int(t1)
t2=int(t2)
if s*v1+t1*2>s*v2+t2*2:
print("Second")
if s*v1+t1*2<s*v2+t2*2:
print("First")
if s*v1+t1*2==s*v2+2*t2:
print("Friendship") |
We say that a odd number N is similar to 2017 when both N and (N+1)/2 are prime.
You are given Q queries.
In the i-th query, given two odd numbers l_i and r_i, find the number of odd numbers x similar to 2017 such that l_i β€ x β€ r_i.
Constraints
* 1β€Qβ€10^5
* 1β€l_iβ€r_iβ€10^5
* l_i and r_i are odd.
* All input values ... | 3 | from itertools import accumulate
q=int(input())
lr=[list(map(int,input().split())) for i in range(q)]
p=[2]
pc=[0]*100001
pc[2]=1
ans=[0]*100001
for i in range(3,100001):
for j in p:
if(i%j==0):
break
if(j*j>i):
p.append(i)
pc[i]=1
if(pc[i//2+1]==1):
ans[i]=1
break
ans=li... |
There are N slimes lining up from left to right. The colors of these slimes will be given as a string S of length N consisting of lowercase English letters. The i-th slime from the left has the color that corresponds to the i-th character of S.
Adjacent slimes with the same color will fuse into one larger slime withou... | 3 | from itertools import groupby
n=int(input())
print(len(list(groupby(input())))) |
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array a of n non-negative integers.
Dark created that array 1000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high... | 3 | for _ in range(int(input())):
n=int(input())
a=[int(i) for i in input().split()] ;summ=0 ; cnt=0; arr=[]
if a[1]==-1 and a[0]!=-1:
arr.append(a[0])
for i in range(1,n-1):
if a[i]!=-1:
if a[i-1]==-1 or a[i+1]==-1:
arr.append(a[i])
if a[-2]==-1 and a[-1]!=-1... |
A string is called a k-string if it can be represented as k concatenated copies of some string. For example, the string "aabaabaabaab" is at the same time a 1-string, a 2-string and a 4-string, but it is not a 3-string, a 5-string, or a 6-string and so on. Obviously any string is a 1-string.
You are given a string s, ... | 3 | k=int(input())
s=input()
largos=[]
while len(s)>0:
a=s.count(s[0])
largos.append((a,s[0]))
s=s.replace(s[0],"")
if any((f[0]%k!=0 for f in largos)):
print(-1)
else:
largos=[(f[0]//k)*f[1] for f in largos]
print("".join(largos)*k)
|
There exists an island called Arpaβs land, some beautiful girls live there, as ugly ones do.
Mehrdad wants to become minister of Arpaβs land. Arpa has prepared an exam. Exam has only one question, given n, print the last digit of 1378n.
<image>
Mehrdad has become quite confused and wants you to help him. Please hel... | 3 | import sys
def main():
print(power(1378, int(sys.stdin.readline()), mod=10))
def power(a, n, mod):
cur_power = a
ans = 1
for i in range(32):
if n & (1 << i):
ans *= cur_power
cur_power *= cur_power
cur_power %= mod
ans %= mod
return ans
if __name__ == '__main__':
main()
... |
Please notice the unusual memory limit of this problem.
Orac likes games. Recently he came up with the new game, "Game of Life".
You should play this game on a black and white grid with n rows and m columns. Each cell is either black or white.
For each iteration of the game (the initial iteration is 0), the color of... | 3 | import sys
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): retu... |
Ancient Egyptians are known to have used a large set of symbols <image> to write on the walls of the temples. Fafa and Fifa went to one of the temples and found two non-empty words S1 and S2 of equal lengths on the wall of temple written one below the other. Since this temple is very ancient, some symbols from the word... | 1 | p=10**9+7
n,m=raw_input().split()
n=int(n)
m=int(m)
a=raw_input().split()
b=raw_input().split()
a=[int(k) for k in a]
b=[int(k) for k in b]
invm=pow(m,p-2,p)
inv2=pow(2,p-2,p)
ans=0
for i in reversed(range(n)):
if a[i]==0 and b[i]==0:
ans=(((inv2*invm)%p)*(m-1)+invm*ans)%p
if a[i]==0 and b[i]!=0:
ans= ((m-b[i])*i... |
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." β an excerpt from contest rules.
A total of n participants took part in the contest (n β₯ k), and you already know their scores. Calculate how many ... | 3 | n,k=[int(x)for x in input().split()]
a=[int(x)for x in input().split()]
d=a[k-1]
ka=0
se=0
if(a[k-1]==0):
for e in a:
if(e>d):
ka+=1
print(ka)
else:
for e in a:
if(e>=d):
ka+=1
print(ka)
|
New Year is coming and you are excited to know how many minutes remain before the New Year. You know that currently the clock shows h hours and m minutes, where 0 β€ hh < 24 and 0 β€ mm < 60. We use 24-hour time format!
Your task is to find the number of minutes before the New Year. You know that New Year comes when the... | 3 | T = int(input())
L = []
for i in range(T): L.append([int(n) for n in input().split()])
for i in L: print(1440 - (60*i[0]) - i[1])
|
La Confiserie d'ABC sells cakes at 4 dollars each and doughnuts at 7 dollars each. Determine if there is a way to buy some of them for exactly N dollars. You can buy two or more doughnuts and two or more cakes, and you can also choose to buy zero doughnuts or zero cakes.
Constraints
* N is an integer between 1 and 10... | 3 | N=int(input())
for i in range(N//7+1):
if (N-7*i)%4==0:
print("Yes")
break
else:
print("No") |
You are locked in a room with a door that has a keypad with 10 keys corresponding to digits from 0 to 9. To escape from the room, you need to enter a correct code. You also have a sequence of digits.
Some keys on the keypad have fingerprints. You believe the correct code is the longest not necessarily contiguous subse... | 3 | import os,sys
n,m = list(map(int , input().split()))
N = list(input().split())
M = list(input().split())
op = ""
for i in range(n):
for j in range(m):
if N[i] == M[j]:
op += N[i]
continue
# print(op)
print(" ".join(list(op))) |
There are n children, who study at the school β41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.
Children can do the following: in one second several pairs of neighboring... | 3 |
"""
NTC here
"""
import sys
inp = sys.stdin.readline
def input(): return inp().strip()
flush= sys.stdout.flush
# import threading
# sys.setrecursionlimit(10**6)
# threading.stack_size(2**26)
def iin(): return int(input())
def lin(): return list(map(int, input().split()))
def lts(a, sep=''): return '{}'.format(sep... |
You are given two strings s and t. In a single move, you can choose any of two strings and delete the first (that is, the leftmost) character. After a move, the length of the string decreases by 1. You can't choose a string if it is empty.
For example:
* by applying a move to the string "where", the result is the s... | 3 | s = input()
t = input()
cnt = 0
if len(s) > len(t):
cnt += len(s) - len(t)
s = s[len(s) - len(t):]
else:
cnt += len(t) - len(s)
t = t[len(t) - len(s):]
s = s[::-1]
t = t[::-1]
for i in range(len(s)):
if s[i] != t[i]:
cnt += (len(s) - i) * 2
break
print(cnt) |
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 | S=input().split('WUB')
l=[ x for x in S if x!='']
print(*l)
|
Takahashi has a water bottle with the shape of a rectangular prism whose base is a square of side a~\mathrm{cm} and whose height is b~\mathrm{cm}. (The thickness of the bottle can be ignored.)
We will pour x~\mathrm{cm}^3 of water into the bottle, and gradually tilt the bottle around one of the sides of the base.
Whe... | 3 | import math
a,b,x = map(int,input().split())
if a*a*b/2 >= x:
print(math.degrees(math.atan(a*b*b/(2*x))))
else:
print(math.degrees(math.atan((2*b*a*a-2*x)/(a**3))))
|
Twilight Sparkle once got a crystal from the Crystal Mine. A crystal of size n (n is odd; n > 1) is an n Γ n matrix with a diamond inscribed into it.
You are given an odd integer n. You need to draw a crystal of size n. The diamond cells of the matrix should be represented by character "D". All other cells of the matr... | 3 | n = int(input())
j = 1
mid = False
for i in range(n):
if i == (n-1)//2 :
mid = True
a = '*' * ((n-j)//2)
d = 'D' * j
print(a,d,a,sep='')
if mid:
j -= 2
else :
j += 2
|
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Bi... | 3 |
a = int(input())
def Arbuz(arb):
if a==2:
print("NO")
return 0
if a%2==0:
print("YES")
else:
print("NO")
Arbuz(a) |
Iahub is very proud of his recent discovery, propagating trees. Right now, he invented a new tree, called xor-tree. After this new revolutionary discovery, he invented a game for kids which uses xor-trees.
The game is played on a tree having n nodes, numbered from 1 to n. Each node i has an initial value initi, which ... | 3 | # 429A
__author__ = 'artyom'
def read_int():
return int(input())
def read_int_ary():
return map(int, input().split())
n = read_int()
g = [[] for x in range(n + 1)]
for i in range(n - 1):
u, v = read_int_ary()
g[u].append(v)
g[v].append(u)
init = [0] + list(read_int_ary())
goal = [0] + list(read_int_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 | w=abs(int(input()))
if w==1:
print("NO")
if w==2:
print("NO")
if w%2==0 and (w>=3 and w<=100):
print("YES")
if w%2==1 and (w>=3 and w<=100):
print("NO")
|
We have a tree with N vertices. The i-th edge connects Vertex A_i and B_i bidirectionally.
Takahashi is standing at Vertex u, and Aoki is standing at Vertex v.
Now, they will play a game of tag as follows:
* 1. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Takahashi moves to a vert... | 3 | from collections import deque
n, u, v = map(int, input().split())
u -= 1
v -= 1
edges = [[] for i in range(n)]
for i in range(n - 1):
a, b = map(int, input().split())
edges[a - 1].append(b - 1)
edges[b - 1].append(a - 1)
def bfs(u):
visited = [-1] * n
Q = deque()
visited[u] = 0
Q.append(u)
... |
Anton likes to play chess, and so does his friend Danik.
Once they have played n games in a row. For each game it's known who was the winner β Anton or Danik. None of the games ended with a tie.
Now Anton wonders, who won more games, he or Danik? Help him determine this.
Input
The first line of the input contains a... | 3 | n = int(input())
Anton, Danik = (0, 0)
r = input()
for i in range(0, n):
if r[i] == 'A':
Anton = Anton+1
else:
Danik = Danik+1
if Anton > Danik:
print("Anton")
elif Anton < Danik:
print("Danik")
else:
print("Friendship")
|
Carol is currently curling.
She has n disks each with radius r on the 2D plane.
Initially she has all these disks above the line y = 10100.
She then will slide the disks towards the line y = 0 one by one in order from 1 to n.
When she slides the i-th disk, she will place its center at the point (xi, 10100). She w... | 1 | '''input
2 2
1 5
'''
from math import sqrt
n,r = map(int,raw_input().split())
arr = map(int,raw_input().split())
ans = [r]
for i in range(1,n):
j = i-1
tmp = r
while j >= 0:
if abs(arr[i]-arr[j]) <= 2*r:
tmp = max(tmp,ans[j]+sqrt((4*r*r)-(abs(arr[i]-arr[j]))**2))
j = j-1
else:
j = j-1
continue
ans.a... |
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 | q=int(input())
while(q>0):
q=q-1
l1=list(map(int,input().split()))
l1.sort()
if(l1[0]==l1[1]==l1[2]):
print(0)
elif(l1[0]==l1[1]):
if(l1[2]-l1[0]>1):
print(2*(l1[2]-l1[0]-2))
else:
print(0)
elif(l1[1]==l1[2]):
if(l1[2]-l1[0]>1):
... |
You are given two arrays of integers a_1,β¦,a_n and b_1,β¦,b_m.
Your task is to find a non-empty array c_1,β¦,c_k that is a subsequence of a_1,β¦,a_n, and also a subsequence of b_1,β¦,b_m. If there are multiple answers, find one of the smallest possible length. If there are still multiple of the smallest possible length, f... | 3 |
def solve(n, m, a, b):
a_logs = set()
b_logs = set()
for i in a:
a_logs.add(i)
arr = []
for i in b:
if i in a_logs:
arr.append(i)
break
if len(arr):
print('YES')
print(len(arr), *arr)
else:
print('NO')
if ... |
β Hey folks, how do you like this problem?
β That'll do it.
BThero is a powerful magician. He has got n piles of candies, the i-th pile initially contains a_i candies. BThero can cast a copy-paste spell as follows:
1. He chooses two piles (i, j) such that 1 β€ i, j β€ n and i β j.
2. All candies from pile i are... | 3 | import sys
from sys import stdin, stdout, setrecursionlimit
T = int(stdin.readline())
for _ in range(T):
n, k = list(map(int, stdin.readline().rstrip().split()))
# n = int(stdin.readline())
a = list(map(int, stdin.readline().rstrip().split()))
a.sort()
# print(a)
ans = 0
for i in range(1, n... |
Kuroni has n daughters. As gifts for them, he bought n necklaces and n bracelets:
* the i-th necklace has a brightness a_i, where all the a_i are pairwise distinct (i.e. all a_i are different),
* the i-th bracelet has a brightness b_i, where all the b_i are pairwise distinct (i.e. all b_i are different).
Kuro... | 3 | def sol():
t=int(input())
for tt in range(t):
n=int(input())
A=[int(item) for item in input().split()]
B=[int(item) for item in input().split()]
A.sort()
B.sort()
print(*A)
print(*B)
if(__name__=='__main__'):
sol()
|
Neko loves divisors. During the latest number theory lesson, he got an interesting exercise from his math teacher.
Neko has two integers a and b. His goal is to find a non-negative integer k such that the least common multiple of a+k and b+k is the smallest possible. If there are multiple optimal integers k, he needs ... | 3 | a, b = list(map(int,input().split()))
def gcd(x,y):
if x == 0:
return y
if y == 0:
return x
if y > x:
y,x = x,y
return gcd(x%y, y)
if a > b:
a, b = b, a
k = b - a
dzielniki = []
i = 1
while i ** 2 <= k:
if k % i == 0:
dzielniki.append(i)
dzielniki.append(k // i)
i+= 1
gcdd = a * b / gcd(a,b)
wynik = 0
... |
In 1862, the lord of Aizu was ordered to serve as a guardian of Kyoto. The Kyoto Shugoshoku is an important role to protect Kyoto at the end of the Edo period when security has deteriorated. You have to patrol the city by sharing it with the shogunate and other clan. However, when it came time to decide the sharing rou... | 3 | # -*- coding: utf-8 -*-
import sys
import os
import math
# adjacent list
M = []
for i in range(105):
M.append([])
def solve(M):
odd_num = 0
even_num = 0
for m in M:
if len(m) % 2 == 0:
even_num += 1
else:
odd_num += 1
# semi-Eulerlian graph
if odd_num... |
Having learned the multiplication table, Takahashi can multiply two integers between 1 and 9 (inclusive) together.
Given an integer N, determine whether N can be represented as the product of two integers between 1 and 9. If it can, print `Yes`; if it cannot, print `No`.
Constraints
* 1 \leq N \leq 100
* N is an int... | 3 | n=int(input())
ans=0
for i in range(1,10):
if n%i==0 and n/i<10:
ans=1
print("Yes" if ans==1 else "No") |
Input
The input contains a single integer a (0 β€ a β€ 35).
Output
Output a single integer.
Examples
Input
3
Output
8
Input
10
Output
1024 | 3 | d = list("And after happily lived ever they".split())
n = bin(int(input()))[2:]
n = "0" * (6 - len(n)) + n
m = n[0] + n[5] + n[3] + n[2] + n[4] + n[1]
print(int('0b'+m, 2)) |
Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of length k have the same sum. A subarray of an array is any sequence of consecutive elements.
Phoenix currently has an array a of length n. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautifu... | 3 | import sys
input = sys.stdin.readline
'''
'''
t = int(input())
from collections import Counter
from math import ceil
def rep(lst, length):
new = []
seen = set()
for item in lst:
if item in seen:
continue
else:
new.append(item)
seen.add(item)
while... |
Chandu is weak in maths. His teacher gave him homework to find maximum possible pair XOR in a matrix of size N x M with some conditions. Condition imposed is that, the pair can be formed between sum of elements in a column and sum of elements in a row.
See sample explanation for more details.
Input:
First line consis... | 1 | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
print 'Hello World!'
'''
import operator
N, M = raw_input().split()
n = int(N)
m = int(M)
rowcount = 0
matrix = []
rowsum = []
while rowcount < n:
row = [int(i) for i in raw_input().split()... |
A binary string is a string where each character is either 0 or 1. Two binary strings a and b of equal length are similar, if they have the same character in some position (there exists an integer i such that a_i = b_i). For example:
* 10010 and 01111 are similar (they have the same character in position 4);
* 10... | 3 | test_case=int(input())
for i in range(test_case):
n=int(input())
arr=list(input())
arr=list(map(int,arr))
x=arr.count(1)
y=arr.count(0)
if (2*n)-1==x:
l=['1']*n
elif (2*n)-1==y:
l=['0']*n
else:
if x>y:
l=['1']*n
else:
l=['0']*n
s=''.join(l)
print(s)
|
Takahashi and Aoki will play a game on a tree. The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.
At the beginning of the game, each vertex contains a coin. Starting from Takahashi, he and Aoki will alternately perform the following operation:
* Choose a vertex ... | 3 | #!usr/bin/env python3
from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS():return list(map(list, sys.stdin.... |
You are given three integers x, y and n. Your task is to find the maximum integer k such that 0 β€ k β€ n that k mod x = y, where mod is modulo operation. Many programming languages use percent operator % to implement it.
In other words, with given x, y and n you need to find the maximum possible integer from 0 to n tha... | 3 | from sys import stdin
import math
A = int(stdin.readline())
for t in range(0,A):
B = list(map(int,stdin.readline().split()))
x = B[0]
y = B[1]
n = B[2]
ans = (n//x)*x+y
if ans>n:
print(ans-x)
else:
print(ans) |
There is a special offer in Vasya's favourite supermarket: if the customer buys a chocolate bars, he or she may take b additional bars for free. This special offer can be used any number of times.
Vasya currently has s roubles, and he wants to get as many chocolate bars for free. Each chocolate bar costs c roubles. He... | 3 | t=int(input())
for o in range(t):
s,a,b,c=list(map(int,input().split()))
ans=s//c
ans+=b*(ans//a)
print(ans) |
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them.
Input
The first line contains integ... | 3 | n=input()
list=input()
counter=0
for i in range(int(n)-1):
if list[i]==list[i+1]:
counter+=1
print(counter)
|
The only difference between easy and hard versions is the number of elements in the array.
You are given an array a consisting of n integers. In one move you can choose any a_i and divide it by 2 rounding down (in other words, in one move you can set a_i := β(a_i)/(2)β).
You can perform such an operation any (possibl... | 3 | """
Code of Ayush Tiwari
Codechef: ayush572000
Codeforces: servermonk
"""
import sys
input = sys.stdin.buffer.readline
def solution():
n,k=map(int,input().split())
l=list(map(int,input().split()))
l.sort()
val=[0]*1000001
op=[0]*1000001
m=2e9
for i in range(n):
val[l[i]]+=1
for... |
Twilight Sparkle once got a crystal from the Crystal Mine. A crystal of size n (n is odd; n > 1) is an n Γ n matrix with a diamond inscribed into it.
You are given an odd integer n. You need to draw a crystal of size n. The diamond cells of the matrix should be represented by character "D". All other cells of the matr... | 3 | N = int(input())
M = N
k = 1
while True:
for i in range((N-1)//2):
d = (N-1)//2
print('*' * d + 'D' * k + '*' * d)
N -= 2
k += 2
d -= 2
d+=2
k-=2
print('D'*M)
for i in range((M-1)//2):
print('*' * d + 'D' * k + '*' * d)
M += 2
k -= 2
... |
Two bored soldiers are playing card war. Their card deck consists of exactly n cards, numbered from 1 to n, all values are different. They divide cards between them in some manner, it's possible that they have different number of cards. Then they play a "war"-like card game.
The rules are following. On each turn a fi... | 1 | import sys
from collections import defaultdict, Counter
from itertools import permutations, combinations
from math import sin, cos, asin, acos, tan, atan, pi
sys.setrecursionlimit(10 ** 6)
def pyes_no(condition, yes = "YES", no = "NO", none = "-1") :
if condition == None:
print (none)
elif condition :
pri... |
Recently Polycarp noticed that some of the buttons of his keyboard are malfunctioning. For simplicity, we assume that Polycarp's keyboard contains 26 buttons (one for each letter of the Latin alphabet). Each button is either working fine or malfunctioning.
To check which buttons need replacement, Polycarp pressed som... | 3 | def solution(chars):
if len(chars) == 1:
return chars
n = len(chars)
result = []
for i in range(n -1):
if chars[i] != chars[i +1]:
if i == 0:
result.append(chars[i])
else:
if chars[i] != chars[i-1]:
result... |
Everybody knows that the Berland citizens are keen on health, especially students. Berland students are so tough that all they drink is orange juice!
Yesterday one student, Vasya and his mates made some barbecue and they drank this healthy drink only. After they ran out of the first barrel of juice, they decided to pl... | 3 | def drink(s, n):
j, res = n, 0
while j < len(s):
if s[j - 1] == s[j - 2] and s[j - 2] == s[j - 3]:
res += 1
j += n
return res
m = int(input())
t = input()
print(drink(t, m))
|
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 | n=input()
m=input()
n=n.lower()
m=m.lower()
if n<m:
print("-1")
elif n==m:
print("0")
else:
print(1)
|
You've been in love with Coronavirus-chan for a long time, but you didn't know where she lived until now. And just now you found out that she lives in a faraway place called Naha.
You immediately decided to take a vacation and visit Coronavirus-chan. Your vacation lasts exactly x days and that's the exact number of d... | 3 | #: Author - Soumya Saurav
from collections import defaultdict
from collections import OrderedDict
from collections import deque
from itertools import combinations
from itertools import permutations
from itertools import accumulate
import bisect
import math
import heapq
import sys
import io, os
input = io.BytesIO(os.re... |
You are given three strings A, B and C. Each of these is a string of length N consisting of lowercase English letters.
Our objective is to make all these three strings equal. For that, you can repeatedly perform the following operation:
* Operation: Choose one of the strings A, B and C, and specify an integer i betwe... | 3 | n=int(input())
a=input()
b=input()
c=input()
print( sum( len( set( (a[i],b[i],c[i])) )-1 for i in range(n) ) ) |
This is an interactive problem. In the output section below you will see the information about flushing the output.
Bear Limak thinks of some hidden number β an integer from interval [2, 100]. Your task is to say if the hidden number is prime or composite.
Integer x > 1 is called prime if it has exactly two distinct ... | 3 | import os
import sys
if os.path.exists('/mnt/c/Users/Square/square/codeforces'):
f = iter(open('A.txt').readlines())
def input():
return next(f)
input = lambda: sys.stdin.readline().strip()
else:
input = lambda: sys.stdin.readline().strip()
def primes(n):
A = [1] * (n+1)
A[0] = A[1] = 1
primes = []
lenA = l... |
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.
The language is that peculiar as it has exactly one variable, called x. Also, there are two operations:
* Operation ++ increases the value of variable x by 1.
* Operation -- decreases the value of variable x by 1.... | 3 | n = int(input())
a = 0
while int(n)>0:
s = input()
if s[0]=='+' or s[2]=='+':
a+=1
else:
a-=1
n-=1
print(a)
|
When preparing a tournament, Codeforces coordinators try treir best to make the first problem as easy as possible. This time the coordinator had chosen some problem and asked n people about their opinions. Each person answered whether this problem is easy or hard.
If at least one of these n people has answered that th... | 3 | input()
print("HARD" if 1 in list(map(int, input().split())) else "EASY") |
You are policeman and you are playing a game with Slavik. The game is turn-based and each turn consists of two phases. During the first phase you make your move and during the second phase Slavik makes his move.
There are n doors, the i-th door initially has durability equal to a_i.
During your move you can try to br... | 3 | import math
n,x,y=input().split()
n=int(n)
x=int(x)
y=int(y)
l=list(map(int,input().split()))
if(x>y):
print(n)
else:
count1=0
for i in range(len(l)):
if(l[i]<=x):
count1=count1+1
print(math.ceil(count1/2)) |
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word s. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if... | 3 | s = input()
t = 0
for i in range(len(s)):
if t == 0 and s[i] == 'h':
s1 = i
t += 1
if t == 1 and s1 < i and s[i] == 'e':
s2 = i
t += 1
if t == 2 and s2 < i and s[i] == 'l':
s3 = i
t += 1
if t == 3 and s3 < i and s[i] == 'l':
s4 = i
t +=... |
Our good friend Mole is trying to code a big message. He is typing on an unusual keyboard with characters arranged in following way:
qwertyuiop
asdfghjkl;
zxcvbnm,./
Unfortunately Mole is blind, so sometimes it is problem for him to put his hands accurately. He accidentally move... | 3 | u_keybord = "qwertyuiop"
m_keybord = "asdfghjkl;"
l_keybord = "zxcvbnm,./"
def s(k, shift, a):
if shift == 'R':
if k.find(a) == 0:
return a
else:
return k[k.find(a)-1]
if shift == 'L':
if k.find(a) == len(k)-1:
return a
else:
retu... |
There are N students living in the dormitory of Berland State University. Each of them sometimes wants to use the kitchen, so the head of the dormitory came up with a timetable for kitchen's usage in order to avoid the conflicts:
The first student starts to use the kitchen at the time 0 and should finish the cooking n... | 1 | t = int( raw_input( "" ) )
for i in range( t ):
n = int( raw_input( "" ) )
A = [ int( i ) for i in raw_input( "" ).split( " " ) ]
B = [ int( i ) for i in raw_input( "" ).split( " " ) ]
if A[0] >= B[0]:
count = 1
else:
count = 0
for i in range( 1 , n ):
if A[i... |
It has been decided that a programming contest sponsored by company A will be held, so we will post the notice on a bulletin board.
The bulletin board is in the form of a grid with N rows and N columns, and the notice will occupy a rectangular region with H rows and W columns.
How many ways are there to choose where ... | 3 | def inint(): return int(input())
n, h, w = inint(), inint(), inint()
print((n-h+1)*(n-w+1)) |
Tom loves vowels, and he likes long words with many vowels. His favorite words are vowelly words. We say a word of length k is vowelly if there are positive integers n and m such that nβ
m = k and when the word is written by using n rows and m columns (the first row is filled first, then the second and so on, with each... | 3 | n = int(input())
if(n<25):
print(-1)
else:
m = 5
k = n//m
while n%m !=0:
m+=1
if(m>n): break
if(n//m < 5 or n%m !=0):
print(-1)
else:
k = n//m
mat = ['aeiou','eioua','iouae','ouaei','uaeio']
for i in range(0,k):
for j in range(0,m):
... |
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 | input()
string = input()
a = string.count('0')
b = string.count('1')
print(abs(a-b))
|
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 | def solve(n, arr):
if n < 2:
return 0
j = 0
while j < n:
if not arr[j]:
j += 1
else:
break
if j == n:
return 0
z = 0
ans = 0
for i in range(j + 1, n):
if arr[i] == 1 and arr[i - 1] == 0:
ans += z
z = 0
... |
There are n students in a school class, the rating of the i-th student on Codehorses is a_i. You have to form a team consisting of k students (1 β€ k β€ n) such that the ratings of all team members are distinct.
If it is impossible to form a suitable team, print "NO" (without quotes). Otherwise print "YES", and then pri... | 3 | n, k = (int(x) for x in input().split())
students = list(map(int, input().split()))
team_index = []
team = []
for i in range(len(students)):
if not(students[i] in team):
team.append(students[i])
team_index.append(i+1)
if len(team) >= k:
print("YES")
print(' '.join(map(str, team_index[:k]))... |
Recently, Norge found a string s = s_1 s_2 β¦ s_n consisting of n lowercase Latin letters. As an exercise to improve his typing speed, he decided to type all substrings of the string s. Yes, all (n (n + 1))/(2) of them!
A substring of s is a non-empty string x = s[a β¦ b] = s_{a} s_{a + 1} β¦ s_{b} (1 β€ a β€ b β€ n). For e... | 3 | from collections import defaultdict as dd
n,d=map(int,input().split())
di=dd(int)
s=input()
l=list(input().split())
for i in l:
di[i]=1
ll=[]
cou=0
res=0
i=0
while (i<n):
if(di[s[i]]==1):
cou+=1
else:
res+=(cou*(cou+1))//2
cou=0
i+=1
res+=(cou*(cou+1))//2
print(res) |
Jamie loves sleeping. One day, he decides that he needs to wake up at exactly hh: mm. However, he hates waking up, so he wants to make waking up less painful by setting the alarm at a lucky time. He will then press the snooze button every x minutes until hh: mm is reached, and only then he will wake up. He wants to kno... | 3 | def main():
X = int(input())
HH, MM = map(int, input().split())
m = MM
h = HH
snooze = 0
while 1:
if m % 10 == 7 or h % 10 == 7:
break
m -= X
if m < 0:
m += 60
h -= 1
if h < 0:
h += 24
snooze += 1
print... |
Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot.
He wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fence corners at a single angle a.
Will the robot be able to build the fence Emuskald... | 3 | t = int(input())
for i in range(t):
a = int(input())
n = 360 / (180 - a)
if n == int(n):
print('YES')
else:
print('NO')
|
Snuke stands on a number line. He has L ears, and he will walk along the line continuously under the following conditions:
* He never visits a point with coordinate less than 0, or a point with coordinate greater than L.
* He starts walking at a point with integer coordinate, and also finishes walking at a point with ... | 3 | import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")
l = int(input())
a = [None]*l
for i in range(l):
a[i] = int(input())
dp = [[float("inf")]*(l+1) for _ in range(5)]
for i in range(5):
dp[i][0] = 0
def c1(v):
if v==0... |
Adilbek was assigned to a special project. For Adilbek it means that he has n days to run a special program and provide its results. But there is a problem: the program needs to run for d days to calculate the results.
Fortunately, Adilbek can optimize the program. If he spends x (x is a non-negative integer) days opt... | 3 | import math
t=int(input())
for _ in range(t):
n,d=map(int , input().split(' '))
i=0
j=n
flag=0
while i<j :
m=(i+j)//2
if m+math.ceil(d/(m+1)) <= n :
flag=1
print("YES")
break
else :
i=m+1
if not flag :
print("... |
You have an integer variable x. Initially, x=0.
Some person gave you a string S of length N, and using the string you performed the following operation N times. In the i-th operation, you incremented the value of x by 1 if S_i=`I`, and decremented the value of x by 1 if S_i=`D`.
Find the maximum value taken by x duri... | 3 | N = int(input())
ans = x = 0
for c in input():
x += 1 if c=='I' else -1
ans = max(ans, x)
print(ans) |
Kefa decided to celebrate his first big salary by going to the restaurant.
He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the ver... | 3 |
def go_child(node, path_cat, parent):
# check if too more cat
m_cat = 0
if cat[node] == 0:
m_cat = 0
else:
m_cat = path_cat + cat[node]
# too more cat then leaves are not achievable
if m_cat > m:
return 0
isLeaf = True
sums = 0
# traverse edges belongs to nod... |
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement.
UCDHP stores some secret information about meteors as an n Γ m table with integers in its cells. The order of meteors in... | 3 |
n,m,k=map(int,input().split())
a=[input().split() for _ in ' '*n]
r={str(i):i-1 for i in range(1,n+1)}
c={str(i):i-1 for i in range(1,m+1)}
ans=[]
for _ in range(k):
ch,x,y=input().split()
if ch=='c':
c[x],c[y]=c[y],c[x]
elif ch=='r':
r[x], r[y] = r[y], r[x]
else:
ans.append(a[r... |
You are given an array a consisting of n integers.
Your task is to say the number of such positive integers x such that x divides each number from the array. In other words, you have to find the number of common divisors of all elements in the array.
For example, if the array a will be [2, 4, 6, 2, 10], then 1 and 2 ... | 3 | from math import sqrt,ceil
from collections import defaultdict as dd
from math import gcd
n=int(input())
l=list(map(int,input().split()))
g=l[0]
d=dd(int)
for i in range(1,n):
g=gcd(g,l[i])
#print(g)
while g%2==0:
d[2]+=1
g=g//2
for i in range(3,int(sqrt(g))+1,2):
while g%i==0:
d[i]+=1
... |
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them.
Input
The first line contains integ... | 3 | def main():
stoneCount = int(input())
stones = input()
removalCount = 0
for i in range(1, stoneCount):
if stones[i] == stones[i-1]:
removalCount += 1
print(removalCount)
if __name__ == '__main__': main()
|
You are given an array of n integers a_1, a_2, ..., a_n, and a set b of k distinct integers from 1 to n.
In one operation, you may choose two integers i and x (1 β€ i β€ n, x can be any integer) and assign a_i := x. This operation can be done only if i does not belong to the set b.
Calculate the minimum number of opera... | 3 | import sys
import math
from bisect import bisect_right
def II():
return int(sys.stdin.readline())
def LI():
return list(map(int, sys.stdin.readline().split()))
def MI():
return map(int, sys.stdin.readline().split())
def SI():
return sys.stdin.readline().strip()
n,k = MI()
a = LI()
a = [float('-inf')]+a+[float... |
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on n - 2 intermediate planets. Formally: we number all the planets from 1 to n. 1 is Earth, n is Mars. Natasha will make exactly n flights: 1 β 2 β β¦ n β 1.
Flight from x to y consists of two phases: take-off from ... | 1 |
def solve():
n = int(raw_input())
m = int(raw_input())
a = map(int, raw_input().split())
b = map(int, raw_input().split())
a.append(a[0])
b.append(b[0])
a.reverse()
b.reverse()
ans = float(m)
for i in xrange(len(a)):
if a[i] <= 1 or b[i] <= 1:
print -1
... |
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 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 25 16:54:08 2020
@author: pinky
"""
n=int(input())
x=0
for i in range (n):
s=input()
if '++' in s:
x=x+1
elif '--' in s:
x=x-1
else:
x=x
print(x)
|
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 | import math
n,m,a = map(int, input().split())
if a == 1:
print(n*m)
else: print(math.ceil(n / a) * math.ceil(m / a))
|
You have two integers l and r. Find an integer x which satisfies the conditions below:
* l β€ x β€ r.
* All digits of x are different.
If there are multiple answers, print any of them.
Input
The first line contains two integers l and r (1 β€ l β€ r β€ 10^{5}).
Output
If an answer exists, print any of them. Oth... | 3 | l,r=map(int,input().split())
for i in range(l,r+1):
j=str(i)
t=True
for c in j:
if j.count(c)>1:
t=False
if t:
print(i)
break
else:print(-1)
|
You are given an integer N. Among the integers between 1 and N (inclusive), how many Shichi-Go-San numbers (literally "Seven-Five-Three numbers") are there?
Here, a Shichi-Go-San number is a positive integer that satisfies the following condition:
* When the number is written in base ten, each of the digits `7`, `5` ... | 3 | N = int(input())
def dfs(s:str):
if int(s) > N: return 0
cnt = 1 if all(s.count(c) > 0 for c in "753") else 0
for c in "753":
cnt += dfs(s + c)
return cnt
print(dfs("0")) |
You are given a positive integer x. Find any such 2 positive integers a and b such that GCD(a,b)+LCM(a,b)=x.
As a reminder, GCD(a,b) is the greatest integer that divides both a and b. Similarly, LCM(a,b) is the smallest integer such that both a and b divide it.
It's guaranteed that the solution always exists. If ther... | 3 | for _ in range(int(input())):
d = int(input())
print(1, (d-1)) |
The only difference between easy and hard versions is a number of elements in the array.
You are given an array a consisting of n integers. The value of the i-th element of the array is a_i.
You are also given a set of m segments. The j-th segment is [l_j; r_j], where 1 β€ l_j β€ r_j β€ n.
You can choose some subset of... | 3 | import sys
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
n,m = inpl()
a = inpl()
mx = max(a)
a = [-(x-mx) for x in a]
s = [inpl() for _ in range(m)]
res = 0
Q = []
for i in range(n):
for j in range(n):
if i == j:... |
Today, Yasser and Adel are at the shop buying cupcakes. There are n cupcake types, arranged from 1 to n on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type i is an integer a_i. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.
Yasser, ... | 3 | def de(s,n):
n-=1
max_local = 0
max_global = 0
for i in range(n):
if max_local+s[i]<0:
max_local = 0
else:
max_local+=s[i]
max_global = max(max_local,max_global)
return max_global
for _ in range(int(input())):
n = int(input())
a = [int(i) for i in input().split()]
yasser = sum(a)
adel = max(de(a[1... |
Let's consider all integers in the range from 1 to n (inclusive).
Among all pairs of distinct integers in this range, find the maximum possible greatest common divisor of integers in pair. Formally, find the maximum value of gcd(a, b), where 1 β€ a < b β€ n.
The greatest common divisor, gcd(a, b), of two positive integ... | 3 | N = int(input())
for _ in range(N):
t = int(input())
if t%2 == 0:
print(t//2)
else:
print((t-1)//2) |
For an array b of length m we define the function f as
f(b) = \begin{cases} b[1] & if m = 1 \\\ f(b[1] β b[2],b[2] β b[3],...,b[m-1] β b[m]) & otherwise, \end{cases}
where β is [bitwise exclusive OR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
For example, f(1,2,4,8)=f(1β2,2β4,4β8)=f(3,6,12)=f(3β6... | 1 | n = int(raw_input())
a = map(int, raw_input().split())
q = int(raw_input())
max_n = 5007
dp = [[0] * 5007 for i in xrange(5007)]
for i in xrange(n):
dp[0][i] = a[i]
for i in xrange(1, n):
for j in xrange(n-i+1):
dp[i][j] = dp[i-1][j+1] ^ dp[i-1][j]
for i in xrange(1, n):
for j in xrange(n-i):
... |
Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (xβ1, y), (x, y + 1) and (x, yβ1).
Iahub wants to know how many ... | 3 | # ===============================
# (c) MidAndFeed aka ASilentVoice
# ===============================
import math, fractions
# ===============================
n = int(input())
s = "C."*(pow(n,2))
if n%2==0:
print(n*(n//2))
else:
print((n*(n+1)//2) - n//2)
for i in range(n):
if i%2==0:
print(s[:n])
else:
print(s... |
Vanya got n cubes. He decided to build a pyramid from them. Vanya wants to build the pyramid as follows: the top level of the pyramid must consist of 1 cube, the second level must consist of 1 + 2 = 3 cubes, the third level must have 1 + 2 + 3 = 6 cubes, and so on. Thus, the i-th level of the pyramid must have 1 + 2 + ... | 3 | a = int(input())
d = 0
c = 0
b = 0
while d <= a:
b = b + 1
c = c + b
d = d + c
print(b - 1) |
Input
The input contains two integers a1, a2 (0 β€ ai β€ 109), separated by a single space.
Output
Output a single integer.
Examples
Input
3 14
Output
44
Input
27 12
Output
48
Input
100 200
Output
102 | 1 | a,b=raw_input().split();print int(a)+int(b[::-1]) |
Polycarp wants to cook a soup. To do it, he needs to buy exactly n liters of water.
There are only two types of water bottles in the nearby shop β 1-liter bottles and 2-liter bottles. There are infinitely many bottles of these two types in the shop.
The bottle of the first type costs a burles and the bottle of the se... | 3 | for _ in range(int(input())):
cost = 0
n, a, b = map(int, input().split())
cost+=(n%2)*a
if a*2>b:
#use b
cost+=(n//2)*b
else:
cost+=(n//2)*2*a
print(cost) |
Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot.
He wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fence corners at a single angle a.
Will the robot be able to build the fence Emuskald... | 3 | t=int(input())
for k in range(t):
a=int(input())
ans=360/(180-a)
if ans-int(ans)==0 and int(ans)!=0:
print("YES")
else:
print("NO") |
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution.... | 1 | n = int(raw_input())
cnt = 0
while(n > 0):
n = n - 1
line = raw_input()
a, b, c, = line.split(' ')
if int(a) + int(b) + int(c) > 1:
cnt = cnt + 1
print cnt
|
Maxim wants to buy some games at the local game shop. There are n games in the shop, the i-th game costs c_i.
Maxim has a wallet which can be represented as an array of integers. His wallet contains m bills, the j-th bill has value a_j.
Games in the shop are ordered from left to right, Maxim tries to buy every game i... | 3 | # A. Game Shopping
n, m = map(int, input().split())
c = list(map(int, input().split()))
a = list(map(int, input().split()))
ans = 0
i = 0
for bill in a:
try:
i += next(ind for ind, el in enumerate(c[i:]) if el <= bill) + 1
ans += 1
except StopIteration:
break
print(ans)
|
Friends are going to play console. They have two joysticks and only one charger for them. Initially first joystick is charged at a1 percent and second one is charged at a2 percent. You can connect charger to a joystick only at the beginning of each minute. In one minute joystick either discharges by 2 percent (if not c... | 3 | m,n=map(int,input().split())
flag=m>n
count=0
flag1=True
while (m!=0 or n!=0 ) and flag1==True:
if m==1 and n==1:
break
if flag==True:
while m!=1:
n+=1
m-=2
count+=1
if m-2==0 and n>m:
flag=False
break
i... |
Mike is trying rock climbing but he is awful at it.
There are n holds on the wall, i-th hold is at height ai off the ground. Besides, let the sequence ai increase, that is, ai < ai + 1 for all i from 1 to n - 1; we will call such sequence a track. Mike thinks that the track a1, ..., an has difficulty <image>. In othe... | 3 | n = int(input())
L = list(map(int, input().split()))
print(max(max(L[i + 1] - L[i] for i in range(n - 1)),
min(L[i + 2] - L[i] for i in range(n - 2)))) |
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second.
One day in 230 AD Shapur was trying to find out if any one can possibly do... | 3 | n1=input()
n=len(n1)
n1=int(n1,2)
n2=input()
n2=int(n2,2)
s=str((bin(n1^n2)))
print("0"*(n-len(s)+2),end="")
print(s[2:])
|
Fennec and Snuke are playing a board game.
On the board, there are N cells numbered 1 through N, and N-1 roads, each connecting two cells. Cell a_i is adjacent to Cell b_i through the i-th road. Every cell can be reached from every other cell by repeatedly traveling to an adjacent cell. In terms of graph theory, the g... | 3 | # -*- coding: utf-8 -*-
from collections import deque
n = int(input())
edge = [[] for _ in range(n+1)]
for _ in range(n-1):
a,b = map(int, input().split())
edge[a].append(b)
edge[b].append(a)
inf = 10**6
fvisited = [inf for _ in range(n+1)]
fvisited[1] = 0
q = deque([1])
while len(q)>0:
s = q.popleft... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.