problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
You got a job as a marketer in a pet shop, and your current task is to boost sales of cat food. One of the strategies is to sell cans of food in packs with discounts.
Suppose you decided to sell packs with a cans in a pack with a discount and some customer wants to buy x cans of cat food. Then he follows a greedy str... | 3 | for _ in range(int(input())):
l,r = list(map(int,input().split()))
x = 2*l-1
if x >= r :
print("YES")
else :
print("NO") |
Takahashi has N days of summer vacation.
His teacher gave him M summer assignments. It will take A_i days for him to do the i-th assignment.
He cannot do multiple assignments on the same day, or hang out on a day he does an assignment.
What is the maximum number of days Takahashi can hang out during the vacation if ... | 3 | N, M = map(int, input().split())
A = [int(i) for i in input().split()]
print(max(-1, N - sum(A))) |
There are n students who have taken part in an olympiad. Now it's time to award the students.
Some of them will receive diplomas, some wiil get certificates, and others won't receive anything. Students with diplomas and certificates are called winners. But there are some rules of counting the number of diplomas and ce... | 3 | n,k=map(int,input().split())
nd=n//(2*(k+1))
nc=k*nd
print(nd,nc,n-(nc+nd)) |
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy... | 3 | forces = []
for _ in range(int(input())):
forces.append([int(num) for num in input().split()])
for dim in range(3):
if sum(map(lambda x: x[dim], forces)):
print("NO")
break
else:
print("YES") |
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 | import sys
import math
import heapq
import collections
def inputnum():
return(int(input()))
def inputnums():
return(map(int,input().split()))
def inputlist():
return(list(map(int,input().split())))
def inputstring():
return([x for x in input()])
def inputmatrixchar(rows):
arr2d = [[j for j in input(... |
You are given an integer n.
You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times:
1. Replace n with n/2 if n is divisible by 2;
2. Replace n with 2n/3 if n is divisible by 3;
3. Replace n with 4n/5 if n is divisible by 5.
For example, you can repl... | 3 | """
Code Forces Template
"""
import os
import sys
import string
import math
def solution(num):
m2 = 0
m3 = 0
m5 = 0
while num != 1:
if num % 5 == 0:
num = num // 5
m5 += 1
elif num % 3 == 0:
num = num // 3
m3 += 1
elif num % 2 == ... |
Kitahara Haruki has bought n apples for Touma Kazusa and Ogiso Setsuna. Now he wants to divide all the apples between the friends.
Each apple weights 100 grams or 200 grams. Of course Kitahara Haruki doesn't want to offend any of his friend. Therefore the total weight of the apples given to Touma Kazusa must be equal ... | 3 | n = input()
arr = input()
apples = [int(x) for x in arr.split(" ")]
tk = []
os = []
apples.sort(reverse=True)
for apple in apples:
if sum(tk) > sum(os):
os.append(apple)
else:
tk.append(apple)
if sum(tk) == sum(os):
print("YES")
else:
print("NO")
|
Caracal is fighting with a monster.
The health of the monster is H.
Caracal can attack by choosing one monster. When a monster is attacked, depending on that monster's health, the following happens:
* If the monster's health is 1, it drops to 0.
* If the monster's health, X, is greater than 1, that monster disappear... | 3 | print(2**int(input()).bit_length()-1) |
Write a program which reads a $ n \times m$ matrix $A$ and a $m \times 1$ vector $b$, and prints their product $Ab$.
A column vector with m elements is represented by the following equation.
\\[ b = \left( \begin{array}{c} b_1 \\\ b_2 \\\ : \\\ b_m \\\ \end{array} \right) \\]
A $n \times m$ matrix with $m$ column ve... | 3 | n, m = map(int, input().split())
M = [map(int, input().split()) for _ in range(n)]
V = [int(input()) for _ in range(m)]
for r in M:
print(sum(x*y for x, y in zip(r, V))) |
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
x = input()
x = x.split()
for i in range(3):
x[i] = int(x[i])
a = x[0]
b = x[1]
c = x[2]
print(int(math.ceil(a/c))*int(math.ceil(b/c))) |
You are given three positive (i.e. strictly greater than zero) integers x, y and z.
Your task is to find positive integers a, b and c such that x = max(a, b), y = max(a, c) and z = max(b, c), or determine that it is impossible to find such a, b and c.
You have to answer t independent test cases. Print required a, b a... | 3 | t = int(input())
for _ in range(t):
x, y, z = map(int, input().split())
a1 = 1
a2 = x
b1 = x
b2 = 1
c1 = y
c2 = z
if x == max(a1, b1) and y == max(a1, c1) and z == max(b1, c1):
print("YES")
print(a1, b1, c1)
elif x == max(a2, b2) and y == max(a2, c2) and z == max(b2, ... |
For any positive integer, we define a digit rotation as either moving the first digit
to the end of the number (left digit rotation), or the last digit to the front of the number (right digit rotation).
For example, the number 12345 could be left digit rotated to 23451, or right digit rotated to 51234.
If there are any... | 1 | def l(s):
s = s[-1]+s[:-1]
s = s.lstrip('0')
return s
def r(s):
s = s[1:]+s[0]
s = s.lstrip('0')
return s
t = int(raw_input())
while t :
t=t-1
n = raw_input()
ans = max(int(l(r(n))),int(r(l(n))))
temp = n[:]
for i in range(len(n)) :
temp = l(temp)
ans = ma... |
Since Sonya is interested in robotics too, she decided to construct robots that will read and recognize numbers.
Sonya has drawn n numbers in a row, a_i is located in the i-th position. She also has put a robot at each end of the row (to the left of the first number and to the right of the last number). Sonya will giv... | 3 | import sys
import math
from collections import defaultdict,deque
input = sys.stdin.readline
def inar():
return [int(el) for el in input().split()]
def main():
n=int(input())
arr=inar()
dic={}
dp=[0]*n
count=0
for i in range(n-1,-1,-1):
if arr[i] not in dic:
dic[arr[i]]=1... |
You got a job as a marketer in a pet shop, and your current task is to boost sales of cat food. One of the strategies is to sell cans of food in packs with discounts.
Suppose you decided to sell packs with a cans in a pack with a discount and some customer wants to buy x cans of cat food. Then he follows a greedy str... | 3 | from math import floor
for _ in range(int(input())):
l,r=map(int,input().split())
if r<(2*l):
print("YES")
else:
print("NO")
|
Twilight Sparkle was playing Ludo with her friends Rainbow Dash, Apple Jack and Flutter Shy. But she kept losing. Having returned to the castle, Twilight Sparkle became interested in the dice that were used in the game.
The dice has m faces: the first face of the dice contains a dot, the second one contains two dots, ... | 3 | import math
import collections
import sys
input = sys.stdin.readline
m, n = map(int, input().split())
ans = 0
for i in range(1, m+1):
ans+=i*((i/m)**n - ((i-1)/m)**n)
print(ans) |
Recently Vova found n candy wrappers. He remembers that he bought x candies during the first day, 2x candies during the second day, 4x candies during the third day, ..., 2^{k-1} x candies during the k-th day. But there is an issue: Vova remembers neither x nor k but he is sure that x and k are positive integers and k >... | 3 | t = int(input())
while t > 0:
t -= 1
n = int(input())
k = 2
while True:
x = n/(2**k-1)
xi = n//(2**k-1)
if x == xi:
print(xi)
break
k += 1
|
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")
for i in range(len(s)):
if len(s[i])!=0:
print(s[i],end=' ') |
You are given three positive (i.e. strictly greater than zero) integers x, y and z.
Your task is to find positive integers a, b and c such that x = max(a, b), y = max(a, c) and z = max(b, c), or determine that it is impossible to find such a, b and c.
You have to answer t independent test cases. Print required a, b a... | 3 | for _ in range(int(input())):
a,b,c=map(int,input().split())
if a==b and b==c and c==a:
print("YES")
print(a,b,c)
elif a!=b and b!=c and c!=a:print("NO")
else:
l=[]
l.append(a)
l.append(b)
l.append(c)
l.sort(reverse=True)
if l[0]!=l[1]:prin... |
Dolphin is planning to generate a small amount of a certain chemical substance C.
In order to generate the substance C, he must prepare a solution which is a mixture of two substances A and B in the ratio of M_a:M_b.
He does not have any stock of chemicals, however, so he will purchase some chemicals at a local pharmac... | 3 | N, Ma, Mb = map(int, input().split())
a, b, c = [0] * N, [0] * N, [0] * N
for i in range(N):
a[i], b[i], c[i] = map(int, input().split())
S = 411
MAX_N = 10
MAX_SIZE = 400
INF = int(1e9)
dp = [[INF] * S for i in range(S)]
dp[0][0] = 0
for i in range(N):
for j in range(MAX_SIZE, -1, -1):
for k in range(... |
You are given an integer x of n digits a_1, a_2, …, a_n, which make up its decimal notation in order from left to right.
Also, you are given a positive integer k < n.
Let's call integer b_1, b_2, …, b_m beautiful if b_i = b_{i+k} for each i, such that 1 ≤ i ≤ m - k.
You need to find the smallest beautiful integer y,... | 3 | # 20200118 19:10 ~ 19:22
n, k = map(int, input().split())
a = input()
aSub = a[:k]
ans = ""
for i in range(n):
ans += aSub[i%k]
if int(ans) < int(a):
aSub = str(int(aSub)+1)
ans = ""
for i in range(n):
ans += aSub[i%k]
print(n)
print(ans) |
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 | n=input().split()
k=0
for i in range(int(n[2])):
k+=int(n[0])*(i+1)
if k>=int(n[1]):
print(k-int(n[1]))
else:
print('0')
|
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word.
Note, that during capitalization all the letters except the first one remains unchanged.
Input
A single line contains a non-empty word. This word consists of lowercase and uppercase English letters.... | 3 | a = input()
b = a[0]
y = 0;
if a[0].isupper() == "true":
print (a)
else:
c = a.replace(a[0],a[0].upper(),1)
print (c)
|
Professor Vasechkin is studying evolution of worms. Recently he put forward hypotheses that all worms evolve by division. There are n forms of worms. Worms of these forms have lengths a1, a2, ..., an. To prove his theory, professor needs to find 3 different forms that the length of the first form is equal to sum of len... | 3 | # -*- coding: utf-8 -*-
n = int(input())
a = list(map(int,input().split()))
for i in range(n):
for j in range(i+1,n):
if a[i]+a[j] in a:
print(a.index(a[i]+a[j])+1,i+1,j+1); quit()
print(-1)
|
Devu has an array A consisting of N positive integers. He would like to perform following operation on array.
Pick some two elements a, b in the array (a could be same as b, but their corresponding indices in the array should not be same).
Remove both the elements a and b and instead add a number x such that x lies be... | 1 | '''input
2 4
1 3
1
2
3
4
'''
#~~~~~~~~~~~~~~~~~~~~dwij28 == Abhinav Jha~~~~~~~~~~~~~~~~~~~~#
from sys import stdin, stdout
from math import sqrt, floor, ceil, log
from collections import defaultdict, Counter
def read(): return stdin.readline().rstrip()
def write(x): stdout.write(str(x))
def endl(): write("\n")
n, q... |
Alex, Bob and Carl will soon participate in a team chess tournament. Since they are all in the same team, they have decided to practise really hard before the tournament. But it's a bit difficult for them because chess is a game for two players, not three.
So they play with each other according to following rules:
... | 3 | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 11 14:04:22 2017
@author: ms
"""
def check(playing, win):
ingame = []
out = -1
for i in range(3):
if playing[i] == True:
ingame.append(i)
else:
out = i
if win == out: return False
else: return True
def chan... |
One day a highly important task was commissioned to Vasya — writing a program in a night. The program consists of n lines of code. Vasya is already exhausted, so he works like that: first he writes v lines of code, drinks a cup of tea, then he writes as much as <image> lines, drinks another cup of tea, then he writes <... | 3 | progLines, reduceFactor = map(int, input().split())
hi = 10**9
lo = 0
while lo < hi - 1:
mid = (hi - lo) // 2 + lo
# test mid
numLines = mid
div = reduceFactor
while mid // div != 0:
numLines += mid // div
div *= reduceFactor
if numLines < progLines:
lo = mid
else:... |
Mancala is a game famous in the Middle East. It is played on a board that consists of 14 holes.
<image>
Initially, each hole has a_i stones. When a player makes a move, he chooses a hole which contains a positive number of stones. He takes all the stones inside it and then redistributes these stones one by one in th... | 3 | list1 = list(map(int,input().split()))
sum1 = 0
for i in range(len(list1)):
s = int(list1[i]/14)
mod = list1[i]%14
tempS = 0
if(s%2 == 0):
tempS += s
for j in range(1,len(list1)):
if((list1[(i+j)%14]+(mod > 0)+ s)%2 == 0):
tempS += list1[(i+j)%14]+(mod > 0)+ s
mod -= 1
sum1 = max(sum1,tempS)
print(sum1) |
Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpr... | 3 | from math import gcd
a, b = map(int, input().split())
n = 6 - max(a, b)+1
g = gcd(n, 6)
s = str(n//g)+"/"+str(6//g)
print(s) |
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of n students doing yet another trick.
Let's assume that all these students are numbered from 1 to n. The teacher came to student a and put a hole in his badge. The student, ... | 3 | n = int(input())
lista = list(map(int, input().split()))
# print(lista)
lista.insert(0,0)
saida = []
for i in range(1, n+1):
s = set()
p = i
while True:
# print(s)
# print(lista[p])
if p in s:
saida.append(str(p))
# print(p)
break
else:
s.add(p)
p = lista[p]
print(' '.join(saida)) |
Little Dormi received a histogram with n bars of height a_1, a_2, …, a_n for Christmas. However, the more he played with his new histogram, the more he realized its imperfections, so today he wanted to modify it to his liking.
To modify the histogram, Little Dormi is able to perform the following operation an arbitrar... | 3 | def ii():
return map(int,input().split())
def ti():
return int(input())
def lis():
return [int(i) for i in input().split()]
def maxSub(a,size):
best=a[0]
su=0
start,stop=0,0
for i in range(size):
if su>0:
su+=a[i]
else:
su=a[i]
temp=i
... |
Chef loves games! But he likes to invent his own. Now he plays game "Digit Jump". Chef has sequence of digits S1, S2,..., SN,. He is staying in the first digit (S1) and want to reach the last digit (SN) in the minimal number of jumps.
While staying in some digit x with index i (digit Si) Chef can jump into digits with... | 1 | arr=raw_input().strip()
l=arr.__len__()
num=[]
h={}
for i in range(0,l):
num.append(int(arr[i]))
for i in range(10):
h[i]=[]
for i in xrange(l):
h[num[i]].append(i)
#print h
visited=[]
a={0:0}
q=[0]
def bfs():
i=q.pop(0)
if i==l-1:
return a[i]
x=num[i]
m=[]
if x not in visited:
visited.append(x)
m=h[x... |
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 | def ck(k,n):
if k**2<=n:
return True
return False
for _ in range(int(input())):
n,k = map(int,input().split())
if n%2==k%2 and ck(k,n):
print('YES')
else:
print('NO') |
<image>
While trading on his favorite exchange trader William realized that he found a vulnerability. Using this vulnerability he could change the values of certain internal variables to his advantage. To play around he decided to change the values of all internal variables from a_1, a_2, …, a_n to -a_1, -a_2, …, -a_n... | 3 | import math, sys
from collections import defaultdict, Counter, deque
from heapq import heapify, heappush, heappop
MOD = int(1e9) + 7
INF = float('inf')
def solve():
n = int(input())
arr = list(map(int, input().split()))
l, r = 1, n
print(3 * n)
while l < r:
print(2, l, r)
print(1, l, r)
print(1, l, r)
... |
You are given a special jigsaw puzzle consisting of n⋅ m identical pieces. Every piece has three tabs and one blank, as pictured below.
<image>
The jigsaw puzzle is considered solved if the following conditions hold:
1. The pieces are arranged into a grid with n rows and m columns.
2. For any two pieces that sh... | 1 | for _ in range(input()):
a,b=[int(i) for i in raw_input().split()]
if a==2 and b==2:
print "YES"
elif min(a,b)==1:
print "YES"
else:
print "NO"
|
There is an N-car train.
You are given an integer i. Find the value of j such that the following statement is true: "the i-th car from the front of the train is the j-th car from the back."
Constraints
* 1 \leq N \leq 100
* 1 \leq i \leq N
Input
Input is given from Standard Input in the following format:
N i
O... | 1 | n,i=map(int,raw_input().split())
print n-i+1 |
Write a program to simulate rolling a dice, which can be constructed by the following net.
<image>
<image>
As shown in the figures, each face is identified by a different label from 1 to 6.
Write a program which reads integers assigned to each face identified by the label and a sequence of commands to roll the d... | 1 | class Dice:
def __init__(self):
self.numbers = map(int, raw_input().split())
def roll(self, direction):
if direction == "N":
before_inds = [0, 1, 5, 4]
after_inds = [1, 5, 4, 0]
elif direction == "S":
before_inds = [0, 1, 5, 4]
af... |
Imp is watching a documentary about cave painting.
<image>
Some numbers, carved in chaotic order, immediately attracted his attention. Imp rapidly proposed a guess that they are the remainders of division of a number n by all integers i from 1 to k. Unfortunately, there are too many integers to analyze for Imp.
Imp ... | 1 | def solve():
n, k = map(int, raw_input().split())
if n % 2 == 0 and k > 1: return "NO"
if n % 2 == 0 and k == 1: return "YES"
seen = set()
i = 1
while i <= k:
if n % i in seen: return "NO"
seen.add(n % i)
i += 1
return "YES"
print solve() |
Vanya walks late at night along a straight street of length l, lit by n lanterns. Consider the coordinate system with the beginning of the street corresponding to the point 0, and its end corresponding to the point l. Then the i-th lantern is at the point ai. The lantern lights all points of the street that are at the ... | 3 | n,l = map(int,input().split())
r = sorted(map(int,input().split()))
d = max(r[0],l-r[n-1])
for i in range(1,n):
d = max((r[i]-r[i-1])/2,d)
print(d) |
Screen resolution of Polycarp's monitor is a × b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x, y) (0 ≤ x < a, 0 ≤ y < b). You can consider columns of pixels to be numbered from 0 to a-1, and rows — from 0 to b-1.
Polycarp wants to open a rectangular window of maximal size, which ... | 3 | def max_area(a, b, x, y):
return max([(a - x - 1) *b, a * (b - y - 1), x * b, y * a])
for _ in range(int(input())):
a, b, x, y = map(int, input().split())
print(max_area(a, b, x, y)) |
Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number n. How many times can Gerald put a spell on it until the number becomes one-di... | 3 | st1 = input()
cnt = 0
l = len(st1)
while(l>1):
s = 0
for i in range(l):
s+=int(st1[i])
st1 = str(s)
l = len(st1)
cnt+=1
print(cnt)
|
Ann has recently started commuting by subway. We know that a one ride subway ticket costs a rubles. Besides, Ann found out that she can buy a special ticket for m rides (she can buy it several times). It costs b rubles. Ann did the math; she will need to use subway n times. Help Ann, tell her what is the minimum sum of... | 3 | n, m, a, b = map(int, input().split())
k = b//m
if k>=a:
print(n*a)
else:
z = min(a*(n%m),b)
print(b*(n//m)+z) |
A railroad running from west to east in Atcoder Kingdom is now complete.
There are N stations on the railroad, numbered 1 through N from west to east.
Tomorrow, the opening ceremony of the railroad will take place.
On this railroad, for each integer i such that 1≤i≤N-1, there will be trains that run from Station i t... | 3 | N = int(input())
CSF = [list(map(int,input().split())) for _ in [0]*(N-1)]
for i in range(N-1):
ans = CSF[i][0] + CSF[i][1]
for j in range(i+1,N-1):
c,s,f = CSF[j]
ans = ((max(s,ans)-1)//f +1 )*f + c
print(ans)
print(0) |
Given an integer N, find the base -2 representation of N.
Here, S is the base -2 representation of N when the following are all satisfied:
* S is a string consisting of `0` and `1`.
* Unless S = `0`, the initial character of S is `1`.
* Let S = S_k S_{k-1} ... S_0, then S_0 \times (-2)^0 + S_1 \times (-2)^1 + ... + S... | 3 | N=int(input())
s=""
while N != 0:
r = 0 if N % 2 == 0 else 1
N = (N - r) // -2
s = str(r) + s
print(s if s != "" else "0")
|
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())
l = []
capacity = []
for i in range(n):
x = input().split(" ")
l.append(x)
c = 0
for i in l:
c = c - int(i[0]) + int(i[1])
capacity.append(c)
print(max(capacity)) |
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 |
n = int(input())
C = [list(map(int,input().split())) for i in range(n)]
for i in range(n):
n = C[i][0]
d = C[i][1]
x = int(d**0.5)-1
if x + -(-d // (x+1)) <= n:
print("YES")
else:
print("NO") |
You are given an array s consisting of n integers.
You have to find any array t of length k such that you can cut out maximum number of copies of array t from array s.
Cutting out the copy of t means that for each element t_i of array t you have to find t_i in s and remove it from s. If for some t_i you cannot find s... | 3 | import math
def how(listo,div):
sumi=0
for guy in listo:
if guy[0]<div:
break
sumi+=guy[0]//div
return sumi
n,k=map(int,input().split())
counts=[0]*200000
a=list(map(int,input().split()))
for guy in a:
counts[guy-1]+=1
stuff=[(counts[i],i+1) for i in range(200000)]
stuff.sort... |
Alice and Bob are playing a game with n piles of stones. It is guaranteed that n is an even number. The i-th pile has a_i stones.
Alice and Bob will play a game alternating turns with Alice going first.
On a player's turn, they must choose exactly n/2 nonempty piles and independently remove a positive number of stone... | 3 | n = int(input())
a = [int(i) for i in input().split()]
print("Alice" if sum([1 if i==min(a) else 0 for i in a ]) <= n/2 else "Bob") |
Takahashi has two positive integers A and B.
It is known that A plus B equals N. Find the minimum possible value of "the sum of the digits of A" plus "the sum of the digits of B" (in base 10).
Constraints
* 2 ≤ N ≤ 10^5
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Outp... | 3 | a = [int(i) for i in list(input())]
if a[0] == 1 and max(a[1:])==0:
print(10)
else:
print(sum(a))
|
There are N apple trees in a row. People say that one of them will bear golden apples.
We want to deploy some number of inspectors so that each of these trees will be inspected.
Each inspector will be deployed under one of the trees. For convenience, we will assign numbers from 1 through N to the trees. An inspector ... | 3 | N,D=map(int,input().split())
import math
print(math.ceil(N/(2*D+1))) |
Ivan has number b. He is sorting through the numbers a from 1 to 10^{18}, and for every a writes ([a, b])/(a) on blackboard. Here [a, b] stands for least common multiple of a and b. Ivan is very lazy, that's why this task bored him soon. But he is interested in how many different numbers he would write on the boa... | 3 | def f(n, A):
global M
M.append(n)
if len(A) == 0:
return 1
ans = 0
for i in range(len(A)):
if n // A[i] not in M:
f(n // A[i], A[:i] + A[(i + 1):])
b = int(input())
k = b
A = []
d = 2
while d * d <= b:
if b % d == 0:
A.append(d)
b //= d
else:... |
Constraints
* 1 ≤ |V| ≤ 100
* 0 ≤ |E| ≤ 9900
* -2 × 107 ≤ di ≤ 2 × 107
* There are no parallel edges
* There are no self-loops
Input
An edge-weighted graph G (V, E).
|V| |E|
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
|V| is the number of vertices and |E| is the number of edges in G. The graph vertices are named wi... | 3 | import sys
def floyd(v_count, matrix):
for i in range(v_count):
for j, c2 in enumerate(matrix[j][i] for j in range(v_count)):
for k, (c1, c3) in enumerate(zip(matrix[j], matrix[i])):
if c1 > c2+c3:
matrix[j][k] = c2+c3
return matrix
def has_negative_cycle(a):
return any(row[i] < 0 fo... |
You are given two lists of segments [al_1, ar_1], [al_2, ar_2], ..., [al_n, ar_n] and [bl_1, br_1], [bl_2, br_2], ..., [bl_n, br_n].
Initially, all segments [al_i, ar_i] are equal to [l_1, r_1] and all segments [bl_i, br_i] are equal to [l_2, r_2].
In one step, you can choose one segment (either from the first or fro... | 3 | """T=int(input())
for _ in range(0,T):
n=int(input())
a,b=map(int,input().split())
s=input()
s=[int(x) for x in input().split()]
for i in range(0,len(s)):
a,b=map(int,input().split())"""
T=int(input())
for _ in range(0,T):
n,k=map(int,input().split())
l1,r1=map(int,input().split())... |
When new students come to the Specialized Educational and Scientific Centre (SESC) they need to start many things from the beginning. Sometimes the teachers say (not always unfairly) that we cannot even count. So our teachers decided to teach us arithmetics from the start. And what is the best way to teach students add... | 3 | def verify(a,b,c):
if a == 0 or b == 0 or c == 0:
return False
return a+b == c
def get_expression(a, b, c):
return "|"*a+"+"+"|"*b+"="+"|"*c
expression = input()
a = expression.split("+")[0].count("|")
b = expression.split("+")[1].split("=")[0].count("|")
c = expression.split("=")[1].count("|")
... |
One day Greg and his friends were walking in the forest. Overall there were n people walking, including Greg. Soon he found himself in front of a river. The guys immediately decided to get across the river. Luckily, there was a boat by the river bank, just where the guys were standing. We know that the boat can hold pe... | 3 | from collections import deque
n, k = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
c50 = sum([1 for i in a if i == 50])
c100 = sum([1 for i in a if i == 100])
c = [[0] * 51 for i in range(51)]
c[0][0] = 1
c[1][0] = 1
c[1][1] = 1
for x in range(2, 51):
for y in range(x + 1):
c[x][y... |
Pooja would like to withdraw X $US from an ATM. The cash machine will only accept the transaction if X is a multiple of 5, and Pooja's account balance has enough cash to perform the withdrawal transaction (including bank charges). For each successful withdrawal the bank charges 0.50 $US.
Calculate Pooja's account bal... | 1 | d, a = map(float, raw_input().split())
c = d % 5
if (d < a and a > (d+0.50)):
if c == 0 :
rem = a - (d+0.50)
print "%.2f" %(rem)
else:
print "%.2f" %(a)
else:
print "%.2f" %(a) |
Taro and Hanako are playing card games. They have n cards each, and they compete n turns. At each turn Taro and Hanako respectively puts out a card. The name of the animal consisting of alphabetical letters is written on each card, and the bigger one in lexicographical order becomes the winner of that turn. The winner ... | 1 | #encoding=utf-8
import sys
printf = sys.stdout.write
taro = 0
hanako = 0
x = input()
for i in range(x):
word = map(str, raw_input().split())
if word[0] > word[1]:
taro += 3
elif word[0] < word[1]:
hanako += 3
else:
taro += 1
hanako += 1
print str(taro) + " " + str(ha... |
You are given a bracket sequence s consisting of n opening '(' and closing ')' brackets.
A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the original characters of the sequence. For example, bracket sequences "()(... | 3 | n=int(input())
s=input()
ans = 0
s1,s2=[],[]
f1=[1]*n
f2=[1]*n
for i in range(n):
s1.append([0,0])
s2.append([0,0])
#s1[0][0]=8
#print(s1,s2)
if s[0]=='(':
s1[0][0]+=1
else:
s1[0][1]+=1
#print(s1)
for i in range(1,n):
s1[i][0]=s1[i-1][0]
s1[i][1]=s1[i-1][1]
if s[i]=='(':
s1[i][0]+=1
else:
s1[i][1]+=1
#prin... |
Over time, Alexey's mail box got littered with too many letters. Some of them are read, while others are unread.
Alexey's mail program can either show a list of all letters or show the content of a single letter. As soon as the program shows the content of an unread letter, it becomes read letter (if the program shows... | 3 | import sys, re
print(len(re.sub('0+', '0', sys.stdin.readlines()[1][:-1].replace(' ', '')).strip('0'))) |
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 | a=int(input())
ca=0
cap=[]
for i in range (a):
b=input().split()
ca-=int(b[0])
ca+=int(b[1])
cap.append(ca)
print(max(cap))
|
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 | num = int(input())
string = list(input())
#print(num)
#print(string)
i=0
count1=0
count2=0
j=0
while j<len(string):
for alpha in string[i]:
if alpha=='A':
count1+=1
else:
count2+=1
i+=1
j+=1
if (count1==count2):
print('Friendship'... |
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())
cnt=0
while n>0:
inp = list(map(int,input().split()))
count=0
for i in inp:
if i == 1:
count+=1
if count >= 2:
cnt+=1
n-=1
print(cnt) |
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 | t = int(input())
for _ in range(t):
n, k = map(int, input().split())
a = list(map(int, input().split()))
sa = set(a)
if len(set(a)) > k:
print(-1)
else:
used = set()
ret = []
if len(sa) < k:
num = 1
while len(sa) < k:
sa.add(num)
num += 1
for i in range(n):
... |
Polycarp has recently created a new level in this cool new game Berlio Maker 85 and uploaded it online. Now players from all over the world can try his level.
All levels in this game have two stats to them: the number of plays and the number of clears. So when a player attempts the level, the number of plays increases... | 3 | for _ in range(int(input())):
n = int(input())
valid = True
x = y = 0
for i in range(n):
a, b = map(int, input().split())
valid &= a >= b
valid &= a >= x
valid &= b >= y
total_played = a - x
total_won = b - y
valid &= total_played >= total_won
... |
Hilbert's Hotel is a very unusual hotel since the number of rooms is infinite! In fact, there is exactly one room for every integer, including zero and negative integers. Even stranger, the hotel is currently at full capacity, meaning there is exactly one guest in every room. The hotel's manager, David Hilbert himself,... | 3 | for T in range(1, int(input()) + 1):
N = int(input())
arr = list(map(int, input().split()))
s = set()
for i, a in enumerate(arr):
s.add((i + a) % N)
if len(s) == N:
print("YES")
else:
print("NO")
|
You are given two integers a and b.
In one move, you can choose some integer k from 1 to 10 and add it to a or subtract it from a. In other words, you choose an integer k ∈ [1; 10] and perform a := a + k or a := a - k. You may use different values of k in different moves.
Your task is to find the minimum number of mo... | 3 | loops = int(input())
for i in range(loops):
times = 0
a, b = map(int, input().split())
if a == b:
print(0)
continue
if a > b and abs(a - b) % 2 == 0:
print(1)
elif a < b and abs(a - b) % 2 != 0:
print(1)
else:
print(2) |
There are n dormitories in Berland State University, they are numbered with integers from 1 to n. Each dormitory consists of rooms, there are a_i rooms in i-th dormitory. The rooms in i-th dormitory are numbered from 1 to a_i.
A postman delivers letters. Sometimes there is no specific dormitory and room number in it o... | 3 | import bisect as b
n,m=map(int,input().split())
room=[int(x) for x in input().split()]
req=[int(x) for x in input().split()]
prev=-1
for i in range(1,len(room)):
room[i]=room[i]+room[i-1]
for r in req:
index=b.bisect_left(room,r)
upper=room[index]
if index!=0:
lower=room[index-1]
else:
... |
You are given a string s consisting only of characters + and -. You perform some process with this string. This process can be described by the following pseudocode:
res = 0
for init = 0 to inf
cur = init
ok = true
for i = 1 to |s|
res = res + 1
... | 3 | test = int(input())
for _ in range(test):
s = list(input())
res = 0
cur = 0
for i in range(len(s)):
if s[i]=='-':
cur-=1
else:
cur+=1
if cur<0:
res+=(i+1)
cur = 0
if cur>=0:
res+=len(s)
print(res) |
A bus moves along the coordinate line Ox from the point x = 0 to the point x = a. After starting from the point x = 0, it reaches the point x = a, immediately turns back and then moves to the point x = 0. After returning to the point x = 0 it immediately goes back to the point x = a and so on. Thus, the bus moves from ... | 3 | a, b, f, k = map(int, input().split())
s, t = 0, b - f
g = f = a - f
for i in range(k):
if t < 0:
break
if k - 1 - i:
g += f
if t < g:
s, t = s + 1, b
t -= g
g = f = a - f
if t < 0:
print(-1)
else:
print(s) |
Gennady owns a small hotel in the countryside where he lives a peaceful life. He loves to take long walks, watch sunsets and play cards with tourists staying in his hotel. His favorite game is called "Mau-Mau".
To play Mau-Mau, you need a pack of 52 cards. Each card has a suit (Diamonds — D, Clubs — C, Spades — S, or ... | 3 | from sys import stdin
inp = stdin.readline
table = inp().strip()
hand = inp().strip().split()
canPlay = False
for card in hand:
if card[0] == table[0] or card[1] == table[1]:
canPlay = True
break
print("YES" if canPlay else "NO")
|
You can not just take the file and send it. When Polycarp trying to send a file in the social network "Codehorses", he encountered an unexpected problem. If the name of the file contains three or more "x" (lowercase Latin letters "x") in a row, the system considers that the file content does not correspond to the socia... | 3 | import math
from collections import defaultdict,deque
import bisect
x=int(input())
a=list(input())
c=0
for i in range(x-2):
if a[i]+a[i+1]+a[i+2]=="xxx":
c+=1
print(c) |
Serval is fighting with a monster.
The health of the monster is H.
In one attack, Serval can decrease the monster's health by A. There is no other way to decrease the monster's health.
Serval wins when the monster's health becomes 0 or below.
Find the number of attacks Serval needs to make before winning.
Constrai... | 3 | H, A = map(int, input().split())
print (int((H+A-1)/A)) |
An extension of a complex number is called a quaternion. It is a convenient number that can be used to control the arm of a robot because it is convenient for expressing the rotation of an object. Quaternions are $ using four real numbers $ x $, $ y $, $ z $, $ w $ and special numbers (extended imaginary numbers) $ i $... | 3 | b = [[1,2,3,4],[2,-1,4,-3],[3,-4,-1,2],[4,3,-2,-1]]
while 1:
n = int(input())
if n == 0:break
for _ in range(n):
x = tuple(map(int, input().split()))
x1, x2 = x[:4], x[4:]
a = [0,0,0,0]
for i in range(4):
for j in range(4):
if b[i][j] > 0:a[b[i][j]... |
We call two numbers x and y similar if they have the same parity (the same remainder when divided by 2), or if |x-y|=1. For example, in each of the pairs (2, 6), (4, 3), (11, 7), the numbers are similar to each other, and in the pairs (1, 4), (3, 12), they are not.
You are given an array a of n (n is even) positive in... | 3 | t = int(input())
for _ in range(t):
n = int(input())
a = list(map(int, input().split()))
t = [0]*102
m = 0
k = 0
for i in a:
t[i] += 1
if i % 2 == 0:
k += 1
else:
m += 1
check = 0
if m % 2 == 0 or k % 2 == 0:
print('YES')
c... |
Ashish has two strings a and b, each of length n, and an integer k. The strings only contain lowercase English letters.
He wants to convert string a into string b by performing some (possibly zero) operations on a.
In one move, he can either
* choose an index i (1 ≤ i≤ n-1) and swap a_i and a_{i+1}, or
* choos... | 1 | from collections import Counter, defaultdict, deque
import bisect
from sys import stdin, stdout
from itertools import repeat
import math
# sys.stdin = open('input')
def inp(force_list=False):
re = map(int, raw_input().split())
if len(re) == 1 and not force_list:
return re[0]
return re
def inst():... |
Every great chef knows that lucky numbers are 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.
Our chef has recently returned from the Lucky country. He observed that every restaurant in the Lucky country had a luc... | 1 | t=input()
while(t>0):
n=input()
four=n/7
flag=0
while(four>=0):
temp=n - 7*four
if(temp%4 ==0):
flag=1
break
four=four-1;
if(flag==0):
print "-1\n"
else:
print four*7
t=t-1 |
Alice and Brown are brothers in a family and each receives pocket money in celebration of the coming year. They are very close and share the total amount of the money fifty-fifty. The pocket money each receives is a multiple of 1,000 yen.
Write a program to calculate each one’s share given the amount of money Alice an... | 3 |
a,b=(int(x) for x in input().split())
print((a+b)//2)
|
Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they ... | 3 | y = int(input())
lz= []
j = 0
flag = True
for i in range(y):
z = str(input())
lz.append(z)
for j in range(i+1):
if lz[j] == lz[i]:
flag = False
break
if j == i:
print("NO")
elif not flag:
print("YES")
else:
print("NO") |
Polycarp has an array a consisting of n integers.
He wants to play a game with this array. The game consists of several moves. On the first move he chooses any element and deletes it (after the first move the array contains n-1 elements). For each of the next moves he chooses any element with the only restriction: its... | 3 | t=int(input(""))
l=[int(x) for x in input().split()]
odd_list = list(filter(lambda x: (x%2 != 0) , l))
if len(odd_list)>0:
odd_list.sort()
even_list=list(filter(lambda x: (x%2 == 0) , l))
if len(even_list)>0:
even_list.sort()
if len(odd_list)>len(even_list):
for i in range(len(even_list)):
odd_list.... |
This is a hard version of the problem. The actual problems are different, but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.
You are given a string s consisting of n lowercase Latin letters.
You have to color all its characters the minimum numb... | 3 | n = int(input())
s = input()
c, res = ['0']*26, ['']*n
for i in range(n):
for j in range(26):
if s[i] >= c[j]:
res[i] = str(j+1)
c[j] = s[i]
break
print(26-c.count('0'))
print(' '.join(res))
|
Let n be a positive integer. Let a, b, c be nonnegative integers such that a + b + c = n.
Alice and Bob are gonna play rock-paper-scissors n times. Alice knows the sequences of hands that Bob will play. However, Alice has to play rock a times, paper b times, and scissors c times.
Alice wins if she beats Bob in at lea... | 3 | tT = int(input())
while(tT):
tT-=1
n = int(input())
a, b, c = map(int, input().split())
s = input()
t = ["X"] * n
wins = 0
for i,en in enumerate(s):
if en=='P' and c:
c-=1
t[i]='S'
wins+=1
elif en=='R' and b:
b-=1
t[... |
For a positive integer n let's define a function f:
f(n) = - 1 + 2 - 3 + .. + ( - 1)nn
Your task is to calculate f(n) for a given integer n.
Input
The single line contains the positive integer n (1 ≤ n ≤ 1015).
Output
Print f(n) in a single line.
Examples
Input
4
Output
2
Input
5
Output
-3
Note
f(4)... | 3 | n=int(input())
print(n//2*(n//2+1)-(n-n//2)**2) |
The game of Berland poker is played with a deck of n cards, m of which are jokers. k players play this game (n is divisible by k).
At the beginning of the game, each player takes n/k cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he... | 3 | n = int(input())
for i in range(n):
n,m,k = map(int,input().split())
x = min(m,int(n/k))
y = int((m-x)/(k-1)) + (((m-x)%(k-1))!=0)
print(x-y)
|
Find the minimum area of a square land on which you can place two identical rectangular a × b houses. The sides of the houses should be parallel to the sides of the desired square land.
Formally,
* You are given two identical rectangles with side lengths a and b (1 ≤ a, b ≤ 100) — positive integers (you are given ... | 3 | t=int(input())
while t:
t-=1
a,b = [int(i) for i in input().split(" ")]
if a>b:
b=2*b
else:
a=2*a
sqaure=a if a>b else b
print(sqaure**2) |
There is a building consisting of 10~000 apartments numbered from 1 to 10~000, inclusive.
Call an apartment boring, if its number consists of the same digit. Examples of boring apartments are 11, 2, 777, 9999 and so on.
Our character is a troublemaker, and he calls the intercoms of all boring apartments, till someone... | 3 | def func():
n = input()
l = len(n)
setN = set(n)
for i in setN:
a = int(i)
#print(a, l)
ans = (10 * (a - 1)) + l * (l + 1) // 2
print(ans)
def main():
for i in range(int(input())):
func()
# print()
main()
|
You have three tasks, all of which need to be completed.
First, you can complete any one task at cost 0.
Then, just after completing the i-th task, you can complete the j-th task at cost |A_j - A_i|.
Here, |x| denotes the absolute value of x.
Find the minimum total cost required to complete all the task.
Constrain... | 3 | a = sorted(map(int, input().split()))[::-1]
print(a[0]-a[2]) |
Sasha likes investigating different math objects, for example, magic squares. But Sasha understands that magic squares have already been studied by hundreds of people, so he sees no sense of studying them further. Instead, he invented his own type of square — a prime square.
A square of size n × n is called prime if ... | 3 | import sys
import math
from collections import defaultdict,Counter
# input=sys.stdin.readline
# def print(x):
# sys.stdout.write(str(x)+"\n")
# sys.stdout=open("CP2/output.txt",'w')
# sys.stdin=open("CP2/input.txt",'r')
# mod=pow(10,9)+7
l=set([2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, ... |
Misha and Vasya participated in a Codeforces contest. Unfortunately, each of them solved only one problem, though successfully submitted it at the first attempt. Misha solved the problem that costs a points and Vasya solved the problem that costs b points. Besides, Misha submitted the problem c minutes after the contes... | 3 | l = list(map(int,input().split()))
a,b,c,d = l[0],l[1],l[2],l[3]
m = max(3*a/10, a - a/250*c)
v = max(3*b/10, b - b/250*d)
if m >v:
print('Misha')
elif m == v:
print('Tie')
else:
print('Vasya')
|
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: s of length n and t of length m.
A sequence p_1, p_2, …, p_m, where 1 ≤ p_1 < p_2 < … < p_m ≤ n, is called beautiful, if s_{p_i} = t_i for all i from 1 to m. The width of a sequence is defined as max_{1 ... | 3 | from collections import deque
def do():
a2i = lambda x: ord(x) - ord("a")
n, m = map(int, input().split())
s = input()
target = input()
posAlphas = [deque([]) for _ in range(26)]
# まず、最短を求める
loc = [None] * m
cur = 0
for i in range(n):
val = a2i(s[i])
posAlphas[val].ap... |
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())
k = 0
for i in range(n):
a = list(map(int, input().split()))
if sum(a) >= 2:
k += 1
print(k)
|
You are given a rectangular board of M × N squares. Also you are given an unlimited number of standard domino pieces of 2 × 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squa... | 3 | n=list(map(int,input().split()))
if(n[0]==1 and n[1]==1):
print('0')
else:
s=n[0]*n[1]
m=0
for i in range(s):
k=s-2
s=k
m=m+1
if(s<=1):
print(m)
break |
There are N boxes arranged in a row from left to right. The i-th box from the left contains A_i candies.
You will take out the candies from some consecutive boxes and distribute them evenly to M children.
Such being the case, find the number of the pairs (l, r) that satisfy the following:
* l and r are both integers... | 3 | n,m=map(int,input().split())
l=[0]+list(map(int,input().split()))
from itertools import accumulate
l=list(accumulate(l))
l=[i%m for i in l]
import collections
c=collections.Counter(l)
ans=0
for i in c.values():
ans+=i*(i-1)//2
print(ans) |
The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, n is always even, and in C2, n is always odd.
You are given a regular polygon with 2 ⋅ n vertices (it's convex and has equal sides and equal angles) and all its sides have length 1. Let's name it as 2n... | 3 | import math
import sys
input = sys.stdin.readline
Q = int(input())
Query = [int(input()) for _ in range(Q)]
for N in Query:
if N%2 == 0:
print(1/math.tan(math.pi/(N*2))) |
You are given a rectangular board of M × N squares. Also you are given an unlimited number of standard domino pieces of 2 × 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squa... | 3 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 25 13:27:36 2020
@author: pc612
"""
m, n = map(int,input().split())
a = m*n
result = int(a/2)
print(result) |
After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum nu... | 1 | k = 4
n = int(raw_input())
l = map(int, raw_input().split())
d = dict()
for i in xrange(1, k+1):
d[i] = l.count(i)
d[1] = (d[1] - d[3]) if (d[1] - d[3]) >= 0 else 0
h = 1 if ((d[2] % 2)*2 + d[1]) % 4 > 0 else 0
x = d[4] + d[3] + d[2]/2 + ((d[2] % 2)*2 + d[1]) / 4 + h
print x
|
You are given a string S of length N consisting of `A`, `B` and `C`, and an integer K which is between 1 and N (inclusive). Print the string S after lowercasing the K-th character in it.
Constraints
* 1 ≤ N ≤ 50
* 1 ≤ K ≤ N
* S is a string of length N consisting of `A`, `B` and `C`.
Input
Input is given from Standa... | 3 | N, K = map(int, input().split())
S = input()
print(S[:K-1] + S[K-1].lower() + S[K:])
|
You are given two strings s and t. Both strings have length n and consist of lowercase Latin letters. The characters in the strings are numbered from 1 to n.
You can successively perform the following move any number of times (possibly, zero):
* swap any two adjacent (neighboring) characters of s (i.e. for any i = ... | 3 | n = int(input())
st1 = list(input())
st2 = list(input())
ans = 0
anslist = []
for i in range(n):
if st1[i] != st2[i]:
f = True
for j in range(i + 1, n):
if st1[j] == st2[i]:
ans += j - i
anslist += [k + 1 for k in reversed(range(i, j))]
f =... |
For some binary string s (i.e. each character s_i is either '0' or '1'), all pairs of consecutive (adjacent) characters were written. In other words, all substrings of length 2 were written. For each pair (substring of length 2), the number of '1' (ones) in it was calculated.
You are given three numbers:
* n_0 — th... | 3 | def main():
caseNum = int(input())
for _ in range(caseNum):
n0, n1, n2 = list(map(int, input().split(' ')))
if n1 + n2 > 0:
finalStr = '1'
for _ in range(n2):
finalStr += '1'
if n1 > 0:
n1 -= 1
finalStr += '0'
... |
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point x(x > 0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order ... | 3 | n = int(input())
cost = 0
cost += int(n / 5)
n %= 5
cost += int(n / 4)
n %= 4
cost += int(n / 3)
n %= 3
cost += int(n / 2)
n %= 2
cost += int(n / 1)
n %= 1
print(int(cost)) |
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())
k = str(input()).upper()
x = sum([1 if k[i] == 'D' else 0 for i in range(len(k))])
if x/len(k)<0.5:
print('Anton')
elif x/len(k)>0.5:
print('Danik')
else:
print('Friendship') |
There are n dormitories in Berland State University, they are numbered with integers from 1 to n. Each dormitory consists of rooms, there are a_i rooms in i-th dormitory. The rooms in i-th dormitory are numbered from 1 to a_i.
A postman delivers letters. Sometimes there is no specific dormitory and room number in it o... | 3 | dorms, letters = input().split()
a = list(map(int, input().split()))
b = list(map(int, input().split()))
i = 0
room = a[0]
j = 0
while j < len(b):
if b[j] <= room:
print(i+1, a[i] - (room - b[j]))
j += 1
else:
i += 1
room += a[i] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.