problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
There are N cities numbered 1 to N, connected by M railroads.
You are now at City 1, with 10^{100} gold coins and S silver coins in your pocket.
The i-th railroad connects City U_i and City V_i bidirectionally, and a one-way trip costs A_i silver coins and takes B_i minutes. You cannot use gold coins to pay the fare.... | 3 | n,m,s = map(int, input().split())
uvab=[list(map(int,input().split())) for i in range(m)]
cd=[list(map(int,input().split())) for i in range(n)]
chg=10**5
from collections import defaultdict
link = defaultdict(list)
for node in range(n):
cmai,dmin = cd[node]
for frm in range(2600):
link[node*chg + frm]... |
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... | 1 | def min_rest(n,a):
dp = [[0 for x in range(0,3)]for y in range(0,n+1)]
i=0
while i<n:
if a[i]==1:
dp[i+1][1]=1000
dp[i+1][2]=min(dp[i][0],dp[i][1])
elif a[i]==2:
dp[i+1][2]=1000
dp[i+1][1]=min(dp[i][0],dp[i][2])
elif a[i]==0:
dp[i+1][1]=1000
dp[i+1][2]=1000
else:
dp[i+1][1]=min(dp[i][... |
International Women's Day is coming soon! Polycarp is preparing for the holiday.
There are n candy boxes in the shop for sale. The i-th box contains d_i candies.
Polycarp wants to prepare the maximum number of gifts for k girls. Each gift will consist of exactly two boxes. The girls should be able to share each gift ... | 3 | n, k = map(int,input().split())
di = list(map(int,input().split()))
ai = [0] * k
for i in di:
ai[i % k] += 1
ans = ai[0] // 2
ai[0] = 0
for i in range(1,k):
num = i
num2 = k - i
if num != num2:
ans += min(ai[num], ai[num2])
else:
ans += ai[num] // 2
ai[num] = 0
ai[num2] = 0
... |
On a strip of land of length n there are k air conditioners: the i-th air conditioner is placed in cell a_i (1 β€ a_i β€ n). Two or more air conditioners cannot be placed in the same cell (i.e. all a_i are distinct).
Each air conditioner is characterized by one parameter: temperature. The i-th air conditioner is set to ... | 3 | import math
import sys
inp=int(input())
for _ in range(inp):
input()
temp=float('inf')
n,k=map(int,input().split(" "))
a=list(map(int,input().split(" ")))
t=list(map(int,input().split(" ")))
c=[temp]*n
for i in range(k):
c[a[i]-1]=t[i]
L=[temp]*n
R=[temp]*n
p=temp*n
for i in range(n):
p=min(p+1,c[i])
... |
Sonya decided to organize an exhibition of flowers. Since the girl likes only roses and lilies, she decided that only these two kinds of flowers should be in this exhibition.
There are n flowers in a row in the exhibition. Sonya can put either a rose or a lily in the i-th position. Thus each of n positions should cont... | 1 | print('01'*500)[:int(raw_input().split()[0])]
|
The recent All-Berland Olympiad in Informatics featured n participants with each scoring a certain amount of points.
As the head of the programming committee, you are to determine the set of participants to be awarded with diplomas with respect to the following criteria:
* At least one participant should get a dip... | 3 | firstLine = input()
scores = list(map(int, input().split()))
noZeros = list(filter(lambda x: x>0 ,scores))
print(len(set(noZeros)))
|
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())
while t:
t += -1
n = int(input())
l = list(map(int, input().split()))
l.sort()
ch = 1
for i in range(1, n):
if l[i] - l[i - 1] > 1:
ch = 0
break
if ch: print('YES')
else: print('NO') |
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 | k,n,w=map(int,input().split())
money=int(.5*w*(w+1)*k)
if money>=n:
print(money-n)
else:
print(0)
|
Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings a and b of equal length are called equivalent in one of the two cases:
1. They are equal.
2. If we split string a into two halves of the same size a1 and a2, and string b into two halves of the same size b1 and b2... | 3 | def stringPass(palavra):
if len(palavra) % 2 != 0: return palavra
corte1 = slice(0, int(len(palavra)/2), 1)
corte2 = slice(int(len(palavra)/2), len(palavra), 1)
p1 = stringPass(palavra[corte1])
p2 = stringPass(palavra[corte2])
if p1 < p2: return p1+p2
else: return p2+p1
a = input()
b = input()
if s... |
A PIN code is a string that consists of exactly 4 digits. Examples of possible PIN codes: 7013, 0000 and 0990. Please note that the PIN code can begin with any digit, even with 0.
Polycarp has n (2 β€ n β€ 10) bank cards, the PIN code of the i-th card is p_i.
Polycarp has recently read a recommendation that it is bette... | 3 |
def main():
n = int(input())
d = []
s = set()
for i in range(n):
k = input()
d.append(k)
s.add(k[3])
t = 0
z = 0
ans = []
for i in range(n):
T = True
for j in range(n):
if j > i:
if d[i] == d[j] and T:
... |
One day Vasya painted a Cartesian coordinate system on a piece of paper and marked some set of points (x1, y1), (x2, y2), ..., (xn, yn). Let's define neighbors for some fixed point from the given set (x, y):
* point (x', y') is (x, y)'s right neighbor, if x' > x and y' = y
* point (x', y') is (x, y)'s left neighb... | 1 | n = input()
l1 = []
for i in range(0, n):
l1.append(map(int, raw_input().split()))
list1 = []
list2 = []
list3 = []
list4 = []
sum1 = 0
for i in range(0, len(l1)):
for j in range(0, len(l1)):
if l1[i][0] > l1[j][0] and l1[i][1] == l1[j][1]:
list1.append(l1[i])
for j in range(0, len(l1)):... |
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 | from itertools import combinations_with_replacement
t = input()
t = int(t)
while t > 0:
n = input()
n = int(n)
s = input()
combs = combinations_with_replacement(["0", "1"], n)
for comb in combs:
count = 0
x = "".join(comb)
for i in range(n):
ss = s[i: i + n]
... |
You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak zombies, you arrived at a square room consisting of tiles forming an n Γ n grid. The rows are numbered 1 through n from top to bottom, and the columns are numbered 1 through n from left to right. At the far side of the ro... | 1 | import sys
def main():
line = sys.stdin.readline().strip()
n = int(line)
eline = set()
ecol = set()
lines = []
cols = []
for i in xrange(n):
line = sys.stdin.readline().strip()
lines.append(line)
if i == 0:
for j in xrange(n):
cols.append(... |
A penguin Rocher has n sticks. He has exactly one stick with length i for all 1 β€ i β€ n.
He can connect some sticks. If he connects two sticks that have lengths a and b, he gets one stick with length a + b. Two sticks, that were used in the operation disappear from his set and the new connected stick appears in his se... | 3 | from sys import stdin
import math
def main():
tc = int(stdin.readline().strip())
for i in range(tc):
n = int(stdin.readline().strip())
print(math.ceil(n/2))
main()
|
Happy PMP is freshman and he is learning about algorithmic problems. He enjoys playing algorithmic games a lot.
One of the seniors gave Happy PMP a nice game. He is given two permutations of numbers 1 through n and is asked to convert the first one to the second. In one move he can remove the last number from the perm... | 1 | n = int(raw_input())
a = map(int,raw_input().split())
b = map(int,raw_input().split())
bindex = [0]*(n+1)
for i in range(n):
bindex[b[i]] = i
aindex = [0]*(n+1)
for i in range(n):
aindex[a[i]] = i
#print a
#print b,"\n"
'''#here indices refers to bindex
moves = 0
i = 0
while i < n:
if a[i] == b[i]:
... |
There are n monsters standing in a row numbered from 1 to n. The i-th monster has h_i health points (hp). You have your attack power equal to a hp and your opponent has his attack power equal to b hp.
You and your opponent are fighting these monsters. Firstly, you and your opponent go to the first monster and fight it... | 3 | from bisect import bisect_left as bl
from bisect import bisect_right as br
import heapq
import math
from collections import *
from functools import reduce,cmp_to_key
import sys
input = sys.stdin.readline
# M = mod = 998244353
def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.... |
Polycarp has n coins, the value of the i-th coin is a_i. Polycarp wants to distribute all the coins between his pockets, but he cannot put two coins with the same value into the same pocket.
For example, if Polycarp has got six coins represented as an array a = [1, 2, 4, 3, 3, 2], he can distribute the coins into two ... | 3 | import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return [int(x) for x in sys.stdin.... |
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 | # You lost the game.
ch = str(input())
code = str(input())
A = "qwertyuiopasdfghjkl;zxcvbnm,./"
r = ""
for k in range(len(code)):
e = A.index(code[k])
if ch == "R":
r += A[e-1]
else:
r += A[e+1]
print(r)
|
Kuriyama Mirai has killed many monsters and got many (namely n) stones. She numbers the stones from 1 to n. The cost of the i-th stone is vi. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions:
1. She will tell you two numbers, l and r (1 β€ l β€ r β€ n), and you should... | 3 | n = int(input())
v = list(map(int,input().split()))
vs = sorted(v)
prefv = [0] * (n + 1)
prefvs = [0] * (n + 1)
for i in range(n):
prefv[i + 1] = prefv[i] + v[i]
prefvs[i + 1] = prefvs[i] + vs[i]
m = int(input())
for i in range(m):
t, l, r = map(int,input().split())
if t == 1:
print(prefv[r] - p... |
Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock.
<image>
The combination lock is represented by n rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has t... | 3 | disk_num = int(input())
starting_code = input()
ending_code = input()
moves = 0
for i in range(disk_num):
if starting_code[i] > ending_code[i] and (int(starting_code[i]) - int(ending_code[i])) <=5:
moves = (int(starting_code[i]) - int(ending_code[i])) + moves
elif ending_code[i] > starting_code[i] and (int(e... |
You are given a sequence b_1, b_2, β¦, b_n. Find the lexicographically minimal permutation a_1, a_2, β¦, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 β€ t β€ 100).
The first line of... | 3 | t=int(input())
while(t>0):
n=int(input())
C=list(map(int,input().split()))
A=[]
for i in range(0,n):
A.append(C[i])
for j in range(C[i]+1,1000):
if(j not in A and j not in C):
A.append(j)
break
D=[]
s=2*n
for i in range(0,s):
... |
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it:
* deletes all the vowels,
* inserts a character "." before each consonant,
* repl... | 3 | s = input()
s = s.lower()
vow =['a','o','e','i','y','u']
for v in vow:
s = s.replace(v,'')
ans = ''
for i in s:
ans = ans + '.' + i
print(ans)
|
Young boy Artem tries to paint a picture, and he asks his mother Medina to help him. Medina is very busy, that's why she asked for your help.
Artem wants to paint an n Γ m board. Each cell of the board should be colored in white or black.
Lets B be the number of black cells that have at least one white neighbor adja... | 3 |
t = int(input())
for _ in range(t):
n, m = map(int, input().split())
l = [["B" for _ in range(m)] for _ in range(n)]
l[0][0] = 'W'
for i in l:
print(''.join(i))
|
You have integer n. Calculate how many ways are there to fully cover belt-like area of 4n-2 triangles with diamond shapes.
Diamond shape consists of two triangles. You can move, rotate or flip the shape, but you cannot scale it.
2 coverings are different if some 2 triangles are covered by the same diamond shape in ... | 3 | for num in range(int(input())):
print(input()) |
There are N people standing on the x-axis. Let the coordinate of Person i be x_i. For every i, x_i is an integer between 0 and 10^9 (inclusive). It is possible that more than one person is standing at the same coordinate.
You will given M pieces of information regarding the positions of these people. The i-th piece of... | 3 | def inpl(): return [int(i) for i in input().split()]
def find(x):
if par[x] == x:
return x
else:
par[x],dist[x] = find(par[x]),dist[x]+dist[par[x]]
return par[x]
N, M = inpl()
par = list(range(N+1))
dist = [0 for _ in range(N+1)]
for _ in range(M):
l, r, d = inpl()
fl = find(l)
... |
User ainta is making a web site. This time he is going to make a navigation of the pages. In his site, there are n pages numbered by integers from 1 to n. Assume that somebody is on the p-th page now. The navigation will look like this:
<< p - k p - k + 1 ... p - 1 (p) p + 1 ... p + k - 1 p + k >>
When someone clicks... | 1 | n,p,k = map(int,raw_input().split())
s = max(p-k,1)
e = min(p+k,n)
ans = ""
if s != 1:
ans += "<< "
flist = [str(x) for x in range(s,e+1)]
ind = flist.index(str(p))
flist[ind] = "(" + flist[ind] + ")"
ans += " ".join(flist)
if e!= n:
ans += " >>"
print ans
|
Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. For example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. When a team plays as ... | 1 | n = input()
k = 0
i = 0
home = []
guest = []
while i < n:
(h, g) = map(int, raw_input().strip().split())
home.append(h)
guest.append(g)
i = i + 1
for h in range(n):
for g in range(n):
if home[h] == guest[g]:
k = k+1
print k |
You are given a sorted array a_1, a_2, ..., a_n (for each index i > 1 condition a_i β₯ a_{i-1} holds) and an integer k.
You are asked to divide this array into k non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray.
Let max(i) be equal to the maximum in the i-th subar... | 1 | n,k=map(int,raw_input().split())
l=map(int,raw_input().split(" "))
l1=[]
s=0
for i in range(len(l)):
s+=l[i]
l1.append(s)
c=s*k
l1.pop()
l1.sort()
for i in range(0,k-1):
c=c-l1[i]
print c |
Today, Mezo is playing a game. Zoma, a character in that game, is initially at position x = 0. Mezo starts sending n commands to Zoma. There are two possible commands:
* 'L' (Left) sets the position x: =x - 1;
* 'R' (Right) sets the position x: =x + 1.
Unfortunately, Mezo's controller malfunctions sometimes. ... | 3 | from collections import Counter
n = int(input())
c = input()
a = Counter(c)
print(a['L'] + a['R'] + 1)
|
You are given an array a. Some element of this array ai is a local minimum iff it is strictly less than both of its neighbours (that is, ai < ai - 1 and ai < ai + 1). Also the element can be called local maximum iff it is strictly greater than its neighbours (that is, ai > ai - 1 and ai > ai + 1). Since a1 and an have ... | 1 | x = input()
n = map(int,raw_input().split())
count=0
for i in range(len(n)):
if len(n)==1:
break
if i + 2 == len(n):
break
if n[i+1] > n[i] and n[i + 1] > n[i + 2] or n[i+1] < n[i] and n[i + 1] < n[i + 2]:
count +=1
print count |
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution.... | 3 | N = int(input())
ans = 0
for n in range(N):
ans += (sum([int(s) for s in input().split()]) > 1)
print(ans) |
Try guessing the statement from this picture <http://tiny.cc/ogyoiz>.
You are given two integers A and B, calculate the number of pairs (a, b) such that 1 β€ a β€ A, 1 β€ b β€ B, and the equation a β
b + a + b = conc(a, b) is true; conc(a, b) is the concatenation of a and b (for example, conc(12, 23) = 1223, conc(100, 11)... | 3 | t = int(input())
for temp in range(t) :
temp = input().split()
n, d = int(temp[0]), int(temp[1])
sz = len(str(d+1)) -1
print(n*sz)
|
You are given two integers n and k. Your task is to find if n can be represented as a sum of k distinct positive odd (not divisible by 2) integers or not.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 10^5) β the number of test cases.
The next t lines... | 3 | s=int(input())
for i in range (1,s+1):
n,k=map(int,input().split())
if n<k*k:
print('no')
elif n%2==0 and k%2==0 or n%2!=0 and k%2!=0:
print('yes')
else:
print('no')
|
You are given two positive integers n (1 β€ n β€ 10^9) and k (1 β€ k β€ 100). Represent the number n as the sum of k positive integers of the same parity (have the same remainder when divided by 2).
In other words, find a_1, a_2, β¦, a_k such that all a_i>0, n = a_1 + a_2 + β¦ + a_k and either all a_i are even or all a_i ar... | 3 | t = int(input())
for i in range(t):
n, k = map(int, input().split())
if (n % 2 == 0 and k % 2 == 0) or (k % 2 == 1 and n % 2 == 1):
if n >= k:
print('YES')
print('1 ' * (k-1) + str(n-k+1))
else:
print('NO')
elif n % 2 == 0 and k % 2 == 1:
if n >= 2... |
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 | # author: violist
# created: 19.04.2021 07:52:27
import sys
input = sys.stdin.readline
n = int(input())
for i in range(1, n + 1):
for j in range(1, n + 1):
if (abs(i - (n // 2 + 1)) + abs(j - (n // 2 + 1)) <= n // 2):
print("D", end = "")
else:
print("*", end = "")
p... |
This task will exclusively concentrate only on the arrays where all elements equal 1 and/or 2.
Array a is k-period if its length is divisible by k and there is such array b of length k, that a is represented by array b written exactly <image> times consecutively. In other words, array a is k-periodic, if it has period... | 3 | R = lambda :map(int,input().split())
n,m= R()
s = list(R())
r = 0
a = n//m
for i in range(m):
b1,b2 = 0,0
for j in range(a):
#print(s[i+j*m])
if s[i+j*m]==1:
b1+=1
else:
b2+=1
#print(b1,b2)
r+=min(b1,b2)
print(r)
|
We have sticks numbered 1, \cdots, N. The length of Stick i (1 \leq i \leq N) is L_i.
In how many ways can we choose three of the sticks with different lengths that can form a triangle?
That is, find the number of triples of integers (i, j, k) (1 \leq i < j < k \leq N) that satisfy both of the following conditions:
... | 3 | n=int(input())
ar=[int(x) for x in input().split()]
ar.sort()
ans=0
for i in range(n):
for j in range(i+1,n):
for k in range(j+1,n):
if(ar[i]!=ar[j] and ar[j]!=ar[k] and ar[i]+ar[j]>ar[k]):
ans+=1
print(ans) |
Bob programmed a robot to navigate through a 2d maze.
The maze has some obstacles. Empty cells are denoted by the character '.', where obstacles are denoted by '#'.
There is a single robot in the maze. Its start position is denoted with the character 'S'. This position has no obstacle in it. There is also a single ex... | 3 | n,m=input().split()
n=int(n)
m=int(m)
iS=list()
iE=list()
maze=list()
for i in range(n):
x=input()
if 'S' in x:
for j in range(len(x)):
if 'S'==x[j]:
iS.append(i)
iS.append(j)
if 'E' in x:
for j in range(len(x)):
if 'E'==x[j]:
... |
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 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import sys, math, random, operator
from string import ascii_lowercase, ascii_uppercase
from fractions import Fraction, gcd
#from decimal import Decimal, getcontext
from itertools import product, permutations, combinations
from Queue import Queue, PriorityQueue
from collectio... |
There are three friend living on the straight line Ox in Lineland. The first friend lives at the point x1, the second friend lives at the point x2, and the third friend lives at the point x3. They plan to celebrate the New Year together, so they need to meet at one point. What is the minimum total distance they have to... | 3 | ip = input()
p = ip.split(' ')
for i in range(3):
p[i] = int(p[i])
Min = 99999
for i in range(max(p)):
now = abs(p[0]-i) + abs(p[1]-i) + abs(p[2]-i)
Min = min(Min, now)
print(Min)
|
There are N observatories in AtCoder Hill, called Obs. 1, Obs. 2, ..., Obs. N. The elevation of Obs. i is H_i. There are also M roads, each connecting two different observatories. Road j connects Obs. A_j and Obs. B_j.
Obs. i is said to be good when its elevation is higher than those of all observatories that can be r... | 3 | n,m = map(int, input().split())
hs = list(map(int, input().split()))
d = [1]*n
for i in range(m):
a,b = map(int, input().split())
if hs[a-1] <= hs[b-1]:
d[a-1] = 0
if hs[a-1] >= hs[b-1]:
d[b-1] = 0
print(d.count(1)) |
A necklace can be described as a string of links ('-') and pearls ('o'), with the last link or pearl connected to the first one.
<image>
You can remove a link or a pearl and insert it between two other existing links or pearls (or between a link and a pearl) on the necklace. This process can be repeated as many times... | 3 | a=input();from math import ceil as c
if a.count("o")==0:print("YES");exit()
print("YES" if a.count("-")//a.count('o')==c(a.count("-")/a.count('o')) else "NO") |
You are given a string s consisting of lowercase Latin letters and q queries for this string.
Recall that the substring s[l; r] of the string s is the string s_l s_{l + 1} ... s_r. For example, the substrings of "codeforces" are "code", "force", "f", "for", but not "coder" and "top".
There are two types of queries:
... | 3 | from math import log2
class SegmentTree:
def __init__(self, array, func= lambda a,b: a|b):
self.n = len(array)
self.size = 2**(int(log2(self.n-1))+1) if self.n != 1 else 1
self.func = func
self.default = 0
self.data = [self.default] * (2 * self.size)
self.process(arra... |
Your favorite shop sells n Kinder Surprise chocolate eggs. You know that exactly s stickers and exactly t toys are placed in n eggs in total.
Each Kinder Surprise can be one of three types:
* it can contain a single sticker and no toy;
* it can contain a single toy and no sticker;
* it can contain both a sing... | 3 | n = int(input())
for i in range(n):
inp = input().split()
n2 = int(inp[0])
s = int(inp[1])
t = int(inp[2])
print(max(s,t)-(t+s-n2)+1)
|
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it... | 1 | from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import permutations, combinations
from bisect import bisect
raw_input = stdin.readline
pr = stdout.write
import math
def in_num():
return int(raw_input())
def in_arr():
return map(int,raw_input().split())
def pr_num(n... |
There are n piranhas with sizes a_1, a_2, β¦, a_n in the aquarium. Piranhas are numbered from left to right in order they live in the aquarium.
Scientists of the Berland State University want to find if there is dominant piranha in the aquarium. The piranha is called dominant if it can eat all the other piranhas in the... | 3 | for _ in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
if a.count(a[0])==n:
print(-1)
else:
i=0
m=max(a)
while i<n:
am=False
if a[i]==m:
if i>0:
if a[i]>a[i-1]:
am=T... |
You're given a row with n chairs. We call a seating of people "maximal" if the two following conditions hold:
1. There are no neighbors adjacent to anyone seated.
2. It's impossible to seat one more person without violating the first rule.
The seating is given as a string consisting of zeros and ones (0 means... | 3 | n = int(input())
s = input()
flag = True
if len(s) > 1:
if s[0] == "1" and s[1] == "1":
flag = False
if s[len(s) - 1] == "1" and s[len(s) - 2] == "1":
flag = False
if flag:
for i in range(1, n - 1):
if s[i] == "1" and (s[i - 1] == "1" or s[i + 1] == "1"):
flag = False
... |
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made lik... | 3 | n = int(input())
for i in range(n):
st = input()
if(len(st)>10):
li = list(st)
print(li[0]+str(len(st)-2)+li[-1])
else:
print(st) |
Evi has N integers a_1,a_2,..,a_N. His objective is to have N equal integers by transforming some of them.
He may transform each integer at most once. Transforming an integer x into another integer y costs him (x-y)^2 dollars. Even if a_i=a_j (iβ j), he has to pay the cost separately for transforming each of them (See ... | 1 | input()
A = map(int, raw_input().split())
print min(sum((e-x)**2 for e in A) for x in range(-100,101)) |
A magic number is a number formed by concatenation of numbers 1, 14 and 144. We can use each of these numbers any number of times. Therefore 14144, 141414 and 1411 are magic numbers but 1444, 514 and 414 are not.
You're given a number. Determine if it is a magic number or not.
Input
The first line of input contains ... | 3 | n=input()
l=[int(i) for i in n]
while 1 in l:
l.remove(1)
while 4 in l:
l.remove(4)
if '444' in n or len(l)>0 or n[0]!='1':
print("NO")
else:
print("YES") |
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 | inp = input().split()
t = 0
for num in range(1, int(inp[2]) + 1):
t += int(inp[0]) * num
if t > int(inp[1]):
print(abs(int(inp[1]) - t))
else:
print(0) |
One day little Vasya found mom's pocket book. The book had n names of her friends and unusually enough, each name was exactly m letters long. Let's number the names from 1 to n in the order in which they are written.
As mom wasn't home, Vasya decided to play with names: he chose three integers i, j, k (1 β€ i < j β€ n, ... | 3 | n, m = map(int, input().split())
mod = 10**9 + 7
a = [set() for _ in range(m)]
for _ in range(n):
s = input()
for i in range(m):
a[i].add(s[i])
ans = 1
for i in a:
ans = ans * len(i) % mod
print(ans)
|
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution.... | 3 | n=int(input())
d=0
for i in range(n):
a, n, c = map(int, input().split())
if a + n+ c >=2:
d+=1
print(d) |
This contest is `CODEFESTIVAL`, which can be shortened to the string `CF` by deleting some characters.
Mr. Takahashi, full of curiosity, wondered if he could obtain `CF` from other strings in the same way.
You are given a string s consisting of uppercase English letters. Determine whether the string `CF` can be obtai... | 1 | # -*- coding: utf-8 -*-
st = str(raw_input())
if st.find('C') != -1:
i = st.find('C')
if st.find('F',i) != -1:
print 'Yes'
else:
print 'No'
else:
print 'No' |
Given is an integer x that is greater than or equal to 0, and less than or equal to 1. Output 1 if x is equal to 0, or 0 if x is equal to 1.
Constraints
* 0 \leq x \leq 1
* x is an integer
Input
Input is given from Standard Input in the following format:
x
Output
Print 1 if x is equal to 0, or 0 if x is equal ... | 3 | x = int(input())
x ^= 1
print(x)
|
Search trees are data structures that support dynamic set operations including insert, search, delete and so on. Thus a search tree can be used both as a dictionary and as a priority queue.
Binary search tree is one of fundamental search trees. The keys in a binary search tree are always stored in such a way as to sat... | 3 | import copy
class Node():
def __init__(self, parent = -1, left = -1, right = -1):
self.parent = parent
self.left = left
self.right = right
def __eq__(self, other):
if self.num == other.num:
return True
else:
return False
def insert(node, ... |
DZY has a hash table with p buckets, numbered from 0 to p - 1. He wants to insert n numbers, in the order they are given, into the hash table. For the i-th number xi, DZY will put it into the bucket numbered h(xi), where h(x) is the hash function. In this problem we will assume, that h(x) = x mod p. Operation a mod b d... | 3 | p,n=map(int,input().split())
x=[0 for i in range(n)]
for i in range(n):
x[i]=int(input())
was=[0 for i in range(p)]
k=-1
for i in range(n):
if was[x[i]%p]:
k=i+1
break
else:
was[x[i]%p]=1
print(k) |
You are given matrix with n rows and n columns filled with zeroes. You should put k ones in it in such a way that the resulting matrix is symmetrical with respect to the main diagonal (the diagonal that goes from the top left to the bottom right corner) and is lexicographically maximal.
One matrix is lexicographically... | 3 |
s = input()
n = int(s.split(' ')[0])
k = int(s.split(' ')[1])
arr = []
for i in range(n):
arr.append([0]*n)
if k > n*n:
print(-1)
else:
l = 0
for i in range(n):
for j in range(n):
if arr[i][j] == 0:
if l < k:
if i == j:
ar... |
Pasha loves to send strictly positive integers to his friends. Pasha cares about security, therefore when he wants to send an integer n, he encrypts it in the following way: he picks three integers a, b and c such that l β€ a,b,c β€ r, and then he computes the encrypted value m = n β
a + b - c.
Unfortunately, an adversa... | 3 | '''
Auther: ghoshashis545 Ashis Ghosh
College: jalpaiguri Govt Enggineering College
'''
from os import path
import sys
from heapq import heappush,heappop
from functools import cmp_to_key as ctk
from collections import deque,defaultdict as dd
from bisect import bisect,bisect_left,bisect_right,insort,insort_lef... |
You are given three integers A, B and C.
Determine if there exists an equilateral triangle whose sides have lengths A, B and C.
Constraints
* All values in input are integers.
* 1 \leq A,B,C \leq 100
Input
Input is given from Standard Input in the following format:
A B C
Output
If there exists an equilateral ... | 3 | a=input().split()
if int(a[0])==int(a[1])==int(a[2]):
print("Yes")
else:
print("No") |
Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first n. He writes down the followin... | 1 | n = raw_input().split()
n[0] = int(n[0])
n[1] = int(n[1])
half = n[0] / 2
if(n[0] % 2 != 0):
half += 1
if(n[1] > half):
res = n[1] - half
print res*2
else:
res = n[1] * 2
print res - 1
|
You are given an array a_1, a_2, ... , a_n consisting of integers from 0 to 9. A subarray a_l, a_{l+1}, a_{l+2}, ... , a_{r-1}, a_r is good if the sum of elements of this subarray is equal to the length of this subarray (β_{i=l}^{r} a_i = r - l + 1).
For example, if a = [1, 2, 0], then there are 3 good subarrays: a_{1... | 3 | # ord(i)-ord('0')
# t=int(input())
# listi=[tuple(map(int, input().split())) for x in range(t)]
# a=min(tup[0] for tup in listi)
# b=max(tup[1] for tup in listi)
# if (a,b) in listi:
# print(listi.index((a,b))+1)
# else:print(-1)
for _ in range(int(input())):
n=int(input())
s=input()
cnt=[0]*(n*9+2)
... |
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.
For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two ... | 1 | def composite(n):
for i in range(2,n/2+1):
if n%i==0:
return True
return False
n=int(raw_input())
c=0
for i in range(n/2+1):
#print i
if (composite(i)==True and composite(n-i)==True):
print i,n-i
break |
Today, Mezo is playing a game. Zoma, a character in that game, is initially at position x = 0. Mezo starts sending n commands to Zoma. There are two possible commands:
* 'L' (Left) sets the position x: =x - 1;
* 'R' (Right) sets the position x: =x + 1.
Unfortunately, Mezo's controller malfunctions sometimes. ... | 3 | N=int(input())
A=input()
L=A.count('L')
R=A.count('R')
ans=L+R+1
print(ans)
|
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 | n, m, a = map(int, input().split())
area = n * m
square = a * a
overf_n, overf_m = False, False
n_num = n // a
if n // a < n / a:
n_num += 1
overf_n = True
m_num = m // a
if m // a < m / a:
m_num += 1
overf_m = True
print(m_num * n_num) |
Fox Ciel is playing a card game with her friend Jiro.
Jiro has n cards, each one has two attributes: position (Attack or Defense) and strength. Fox Ciel has m cards, each one has these two attributes too. It's known that position of all Ciel's cards is Attack.
Now is Ciel's battle phase, Ciel can do the following ope... | 3 | n, m = map(int, input().split())
(a, d) = ([], [])
for i in range(n):
t, val = input().split()
(a if t == 'ATK' else d).append(int(val))
my = sorted([int(input()) for i in range(m)])
a.sort()
d.sort()
def solve1():
ret = 0
used = [False] * m
for val in d:
for i in range(m):
if n... |
n! = n Γ (n β 1) Γ (n β 2) Γ ... Γ 3 Γ 2 Γ 1
Is called the factorial of n. For example, the factorial of 12
12! = 12 x 11 x 10 x 9 x 8 x 7 x 6 x 5 x 4 x 3 x 2 x 1 = 479001600
And there are two consecutive 0s at the end.
Write a program that inputs the integer n and outputs the number of consecutive 0s at the end of... | 3 | # coding: utf-8
import math
while True:
n = int(input())
if n == 0:
break
fn = math.factorial(n)
z_c = 0
for i in str(fn)[::-1]:
if i != "0":
break
else:
z_c += 1
print(z_c) |
You are given a non-decreasing array of non-negative integers a_1, a_2, β¦, a_n. Also you are given a positive integer k.
You want to find m non-decreasing arrays of non-negative integers b_1, b_2, β¦, b_m, such that:
* The size of b_i is equal to n for all 1 β€ i β€ m.
* For all 1 β€ j β€ n, a_j = b_{1, j} + b_{2, j}... | 3 | #!/usr/bin/env python3
import sys
input=sys.stdin.readline
t=int(input())
for _ in range(t):
n,k=map(int,input().split())
arr=list(map(int,input().split()))
if k==1:
if len(set(arr))!=1:
print(-1)
else:
print(1)
continue
else:
#answer is always e... |
You are given two arrays of integers a and b. For each element of the second array bj you should find the number of elements in array a that are less than or equal to the value bj.
Input
The first line contains two integers n, m (1 β€ n, m β€ 2Β·105) β the sizes of arrays a and b.
The second line contains n integers β ... | 3 | from sys import stdin, stdout
def b_s(arr, l, r, target):
while l+1 < r:
m = int((l+r)/2)
if arr[m] > target:
r = m
else:
l = m
return r
def main():
outputs = []
n, m = map(int, input().split())
A = sorted([int(num) for num in input().split()])
B ... |
You are given a permutation p=[p_1, p_2, β¦, p_n] of integers from 1 to n. Let's call the number m (1 β€ m β€ n) beautiful, if there exists two indices l, r (1 β€ l β€ r β€ n), such that the numbers [p_l, p_{l+1}, β¦, p_r] is a permutation of numbers 1, 2, β¦, m.
For example, let p = [4, 5, 1, 3, 2, 6]. In this case, the numb... | 3 | if __name__ == '__main__':
for _ in range (int(input())):
n = int(input())
l = list(map(int,input().split()))
p = [0]*n
for i in range(n):
p[l[i]-1] = i
a,r = n,0
ans = ''
for i in range (n):
a = min(a,p[i])
r = max(r,p[i])
if r-a == i:
ans+='1'
else:
ans+='0'
print(ans) |
We have a sequence of length N, a = (a_1, a_2, ..., a_N). Each a_i is a positive integer.
Snuke's objective is to permute the element in a so that the following condition is satisfied:
* For each 1 β€ i β€ N - 1, the product of a_i and a_{i + 1} is a multiple of 4.
Determine whether Snuke can achieve his objective.
... | 3 | n=int(input())
a=list(map(int,input().split()))
ans=[0]*3
for i in a:
if i%4==0:
ans[2]+=1
elif i%2==0:
ans[1]+=1
else:ans[0]+=1
if ans[0]<=ans[2] or (ans[0]<=ans[2]+1 and ans[1]==0):print('Yes')
else:print('No') |
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d... | 3 | n = input()
x = 0
for i in n:
if i == '4' or i == '7':
x += 1
if x == 4 or x == 7:
print('YES')
else:
print('NO') |
Polycarpus has an array, consisting of n integers a1, a2, ..., an. Polycarpus likes it when numbers in an array match. That's why he wants the array to have as many equal numbers as possible. For that Polycarpus performs the following operation multiple times:
* he chooses two elements of the array ai, aj (i β j);
... | 1 | import sys
n = int(raw_input())
l = map(int, raw_input().split())
if not(sum(l)%n): print n
else: print n-1 |
Small, but very brave, mouse Brain was not accepted to summer school of young villains. He was upset and decided to postpone his plans of taking over the world, but to become a photographer instead.
As you may know, the coolest photos are on the film (because you can specify the hashtag #film for such).
Brain took a ... | 3 | n, m = map(int, input().split(" "))
ai = [[j for j in input().split()] for i in range(n)]
check = False
for i in range(n):
if ai[i].count("C") > 0 or ai[i].count("M") > 0 or ai[i].count("Y") > 0:
check = True
if check:
print("#Color")
else:
print("#Black&White")
|
Paul was the most famous character in Tekken-3. Of course he went to college and stuff. In one of the exams he wasn't able to answer a question which asked to check if a tuple of 3 non negative integers constituted a Primitive Pythagorian Triplet or not. Paul was not able to answer it correctly and henceforth, he coul... | 1 | from fractions import gcd
t=int(raw_input())
a=[0]*3
for i in range(t):
n=raw_input().split()
a[0]=(long)(n[0])
a[1]=(long)(n[1])
a[2]=(long)(n[2])
a.sort()
#print a[0] ,a[1] ,a[2]
if a[0]+a[1]<=a[2]:
print "NO"
continue
if gcd(a[0],a[1])==1 and gcd(a[2],a[1])==1 and gcd(a[0],a[2])==1:
if (a[0]*a[0]+a[1]*... |
Write a program which reads an integer and prints sum of its digits.
Input
The input consists of multiple datasets. For each dataset, an integer x is given in a line. The number of digits in x does not exceed 1000.
The input ends with a line including single zero. Your program should not process for this terminal ... | 3 | while True:
a=input()
if a=='0':
break
a=map(int,list(a))
print(sum(a))
|
Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it ... | 3 | n=int(input())
pas=[]
num=0
for i in range(n):
a=[int(j) for j in input().split(" ")]
num+=a[1]-a[0]
pas.append(num)
print(max(pas)) |
Greg is a beginner bodybuilder. Today the gym coach gave him the training plan. All it had was n integers a1, a2, ..., an. These numbers mean that Greg needs to do exactly n exercises today. Besides, Greg should repeat the i-th in order exercise ai times.
Greg now only does three types of exercises: "chest" exercises,... | 3 | import sys
from math import *
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int, minp().split())
n = mint()
a = [0,0,0]
j = 0
for i in mints():
a[j] += i
j = (j+1)%3
i = a.index(max(a))
print(["chest","biceps","back"][i])
|
Another programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place.
You know the rules of comparing the results of two give... | 3 | n, k = map(int, input().split())
matrix = []
for _ in range(n):
matrix.append(list(map(int, input().split())))
#sorted_matrix = sorted(matrix)[::-1]
matrix.sort(key=lambda x: (-x[0], x[1]))
print(matrix.count(matrix[k-1]))
|
The last contest held on Johnny's favorite competitive programming platform has been received rather positively. However, Johnny's rating has dropped again! He thinks that the presented tasks are lovely, but don't show the truth about competitors' skills.
The boy is now looking at the ratings of consecutive participan... | 3 | t = int(input())
for _ in range(t):
n = int(input())
ans = 0
two = 1
for i in range(63):
ans += (n)//two
two *= 2
print(ans) |
Bob watches TV every day. He always sets the volume of his TV to b. However, today he is angry to find out someone has changed the volume to a. Of course, Bob has a remote control that can change the volume.
There are six buttons (-5, -2, -1, +1, +2, +5) on the control, which in one press can either increase or decrea... | 3 | import math
test=int(input())
for t in range(0,test):
a,b=map(int,input().split())
t=abs(a-b)
ans=t//5
t=t%5
ans=ans+t//2
t=t%2
print(ans+t)
#print('\n')
|
You are given an array a consisting of n integers. Indices of the array start from zero (i. e. the first element is a_0, the second one is a_1, and so on).
You can reverse at most one subarray (continuous subsegment) of this array. Recall that the subarray of a with borders l and r is a[l; r] = a_l, a_{l + 1}, ..., a_... | 3 | # def max_subarray(numbers):
# """Find the largest sum of any contiguous subarray."""
# best_sum = 0 # or: float('-inf')
# current_sum = 0
# for x in numbers:
# current_sum = max(0, current_sum + x)
# best_sum = max(best_sum, current_sum)
# return best_sum
# t=int(input())
# for _ i... |
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).
Let p be any permutation of length ... | 3 | for _ in range(int(input())):
n = int(input())
s = list(map(int,input().split()))
s.reverse()
print(*s)
|
You have a robot that can move along a number line. At time moment 0 it stands at point 0.
You give n commands to the robot: at time t_i seconds you command the robot to go to point x_i. Whenever the robot receives a command, it starts moving towards the point x_i with the speed of 1 unit per second, and he stops when... | 3 | import sys
input = sys.stdin.readline
for _ in range(int(input())):
n = int(input())
p, dp, dt, lt, lp, tp = 0, 0, 0, 0, 0, None
m = 1
sucs = 0
for k in range(n):
t, d = map(int, input().split())
p = lp + m * (min(t, dt) - lt)
if tp != None and ((tp <= p and tp >= lp) or (t... |
The Little Elephant enjoys recursive functions.
This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows:
... | 3 | a=int(input())
b=[]
for i in range(1,a):
b.append(str(i))
print(a,*b) |
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.
Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, seco... | 3 | n=int(input())
k=["I hate","I love"]*100
print(" that ".join(k[:n])+" it")
|
You play a computer game. In this game, you lead a party of m heroes, and you have to clear a dungeon with n monsters. Each monster is characterized by its power a_i. Each hero is characterized by his power p_i and endurance s_i.
The heroes clear the dungeon day by day. In the beginning of each day, you choose a hero ... | 3 | from sys import stdin
input=stdin.readline
import bisect
#i = bisect.bisect_left(a, k)
#list=input().split(maxsplit=1)
for xoxo in range(1):
#a=[]
for _ in range (int(input())):
n=int(input())
a=list(map(int, input().split()))
b=[]
sn=int(input())
for i in range(sn):
... |
You took a peek on Thanos wearing Infinity Gauntlet. In the Gauntlet there is a place for six Infinity Gems:
* the Power Gem of purple color,
* the Time Gem of green color,
* the Space Gem of blue color,
* the Soul Gem of orange color,
* the Reality Gem of red color,
* the Mind Gem of yellow color.
... | 3 | g={'purple':'Power','green':'Time','orange':'Soul',"blue":"Space","red":"Reality",'yellow':"Mind"}
n=int(input().strip())
print(6-n)
c=[]
for _ in range(n):
c.append(input().strip())
gems=[]
for i in g:
if i not in c:
gems.append(g[i])
for k in gems:
print(k) |
A word or a sentence in some language is called a pangram if all the characters of the alphabet of this language appear in it at least once. Pangrams are often used to demonstrate fonts in printing or test the output devices.
You are given a string consisting of lowercase and uppercase Latin letters. Check whether thi... | 1 | d = {'q':0,
'w':0,
'e':0,
'r':0,
't':0,
'y':0,
'u':0,
'i':0,
'o':0,
'p':0,
'a':0,
's':0,
'd':0,
'f':0,
'g':0,
'h':0,
'j':0,
'k':0,
'l':0,
'z':0,
'x':0,
'c':0,
'v':0,
'b':0,
'n':0,
'm':0}
a = int(raw_input())
b = str(raw_input())
b = b.lower()
for i in b:
d[i] = d[i]... |
There are N children, numbered 1, 2, \ldots, N.
They have decided to share K candies among themselves. Here, for each i (1 \leq i \leq N), Child i must receive between 0 and a_i candies (inclusive). Also, no candies should be left over.
Find the number of ways for them to share candies, modulo 10^9 + 7. Here, two way... | 3 | N,K = map(int,input().split())
a = [0]*110
a[1:] = list(map(int,input().split()))
MOD = 10**9+7
dp = [[0]*110000 for _ in range(110)]
dp_sum = [[0]*110000 for _ in range(110)]
dp[0][0] = 1
for i in range(K+1):
dp_sum[0][i] = 1
for i in range(1,N+1):
for j in range(K+1):
dp[i][j] = dp_sum[i-1][j]
... |
Polycarp plays "Game 23". Initially he has a number n and his goal is to transform it to m. In one move, he can multiply n by 2 or multiply n by 3. He can perform any number of moves.
Print the number of moves needed to transform n to m. Print -1 if it is impossible to do so.
It is easy to prove that any way to trans... | 3 | from math import log,ceil,modf
a=list(map(int,input().split(" ")))
p=ceil(log(a[1]/(2*a[0]),2)+1)
p=int(p)
c=0
for x in range(0,p+1):
k=log(a[1]/(a[0]*2**x),3)+x
if modf(k)[0]==0:
print (int(k))
c=1
break
if c==0:
print (-1)
|
After a long party Petya decided to return home, but he turned out to be at the opposite end of the town from his home. There are n crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.
The crossroads are represented as a string s of length n, where s_i = A, if there is... | 3 | def solve(s, a, b, p):
index = len(s)
totalSum = 0
while totalSum <= p and index > 0:
index -= 1
if index == len(s) - 1 or s[index - 1] != s[index]:
totalSum += a if s[index - 1] == "A" else b
return index + 1
for case in range(int(input())):
a,b,p = map(int, input().sp... |
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 | from fractions import gcd
n = int(input())
a = list(map(int, input().split()))
m = [0]*n
l, r = [0]*n, [0]*n
for i in range(1, n):
l[i] = gcd(a[i-1], l[i-1])
r[n-1-i] = gcd(r[n-i], a[n-i])
ans = 1
for a, b in zip(l, r):
x = gcd(a, b)
if ans < x:
ans = x
print(ans) |
Vector Willman and Array Bolt are the two most famous athletes of Byteforces. They are going to compete in a race with a distance of L meters today.
<image>
Willman and Bolt have exactly the same speed, so when they compete the result is always a tie. That is a problem for the organizers because they want a winner.
... | 3 | t, a, b = map(int, input().split())
def gcd(a, b):
if (b == 0):
return a
else:
return gcd(b, a%b)
x, d = gcd(a, b), min(a, b)
lcm = (a*b)//x
answer = t//lcm*d + min(d, t%lcm + 1) - 1
gcd_of = gcd(answer, t)
print(answer // gcd_of, "/", t // gcd_of, sep = "")
|
Welcome to PC Koshien, players. This year marks the 10th anniversary of Computer Koshien, but the number of questions and the total score will vary from year to year. Scores are set for each question according to the difficulty level. When the number of questions is 10 and the score of each question is given, create a ... | 3 | s1 = int(input())
s2 = int(input())
s3 = int(input())
s4 = int(input())
s5 = int(input())
s6 = int(input())
s7 = int(input())
s8 = int(input())
s9 = int(input())
s10 = int(input())
s = s1 + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10
print(s)
|
Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?
Given a n Γ n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of th... | 1 | def is_valid(x, y, n):
x_valid = (x >= 0 and x < n)
y_valid = (y >= 0 and y < n)
return x_valid and y_valid
def isTrue(board):
n = len(board)
for i in xrange(n):
for j in xrange(n):
count = 0
x = [i - 1, i, i + 1, i]
y = [j, j + 1, j, j - 1]
... |
In some game by Playrix it takes t minutes for an oven to bake k carrot cakes, all cakes are ready at the same moment t minutes after they started baking. Arkady needs at least n cakes to complete a task, but he currently don't have any. However, he has infinitely many ingredients and one oven. Moreover, Arkady can bui... | 3 | n, t, k, d = list(map(int, input().split(" ")))
a = (n+k-1)//k
t1= 0
t2 = d
for i in range(a):
if t1 <= t2:
t1 += t
else:
t2 += t
if (a*t <= max(t1, t2)):
print("NO")
else:
print("YES")
|
Mislove had an array a_1, a_2, β
β
β
, a_n of n positive integers, but he has lost it. He only remembers the following facts about it:
* The number of different numbers in the array is not less than l and is not greater than r;
* For each array's element a_i either a_i = 1 or a_i is even and there is a number (a_i)/(... | 3 | import sys
def main():
n,l,r = map(int,sys.stdin.readline().split())
sm=[1]
for i in range(1,l):
sm.append(sm[-1]*2)
for i in range(l,n):
sm.insert(0,1)
lg=[1]
for i in range(1,r):
lg.append(lg[-1]*2)
for i in range(r,n):
lg.append(lg[-1])
print(sum(sm),su... |
Every day, N passengers arrive at Takahashi Airport. The i-th passenger arrives at time T_i.
Every passenger arrived at Takahashi airport travels to the city by bus. Each bus can accommodate up to C passengers. Naturally, a passenger cannot take a bus that departs earlier than the airplane arrives at the airport. Also... | 3 | n,c,k=map(int,input().split())
t=[int(input()) for i in range(n)]
t.sort()
check=t[0]+k
kyaku=1
ans=1
for i in range(1,n):
if t[i]<=check and kyaku<c:
kyaku+=1
continue
check=t[i]+k
kyaku=1
ans+=1
print(ans)
|
Polycarp and his friends want to visit a new restaurant. The restaurant has n tables arranged along a straight line. People are already sitting at some tables. The tables are numbered from 1 to n in the order from left to right. The state of the restaurant is described by a string of length n which contains characters ... | 3 | from sys import stdin
input = stdin.readline
from math import ceil
from math import ceil
for _ in range(int(input())):
n,k = map(int,input().split())
s = input().rstrip()
ans = 0
if '1' not in s:
ans+=ceil(n/(k+1))
print(ans)
continue
a = s.find('1')
b = n-s[::-1].find('... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.