problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
Due to the coronavirus pandemic, city authorities obligated citizens to keep a social distance. The mayor of the city Semyon wants to light up Gluharniki park so that people could see each other even at night to keep the social distance.
The park is a rectangular table with n rows and m columns, where the cells of the... | 3 | # https://codeforces.com/contest/1360/problem/F
import sys
import os
import heapq
import math
try:
path = "./file/input.txt"
if os.path.exists(path):
sys.stdin = open(path, 'r')
# sys.stdout = open(r"./file/output.txt", 'w')
except:
pass
t = int(input())
def printd(value):
# print(value)... |
A new e-mail service "Berlandesk" is going to be opened in Berland in the near future. The site administration wants to launch their project as soon as possible, that's why they ask you to help. You're suggested to implement the prototype of site registration system. The system should work on the following principle.
... | 3 | a={}
for i in range(int(input())):b=input();print(b+str(a[b])if a.setdefault(b,0)else'OK');a[b]+=1 |
Jzzhu has invented a kind of sequences, they meet the following property:
<image>
You are given x and y, please calculate fn modulo 1000000007 (109 + 7).
Input
The first line contains two integers x and y (|x|, |y| ≤ 109). The second line contains a single integer n (1 ≤ n ≤ 2·109).
Output
Output a single integer... | 3 | #!/usr/bin/env python3
from itertools import *
MOD = 1000000007
def read_ints():
return map(int, input().strip().split())
x, y = read_ints()
n, = read_ints()
t = [x, y, y-x] + [-x, -y, -(y-x)]
n0 = n-1
print(t[n0%6]%MOD)
|
During a New Year special offer the "Sudislavl Bars" offered n promo codes. Each promo code consists of exactly six digits and gives right to one free cocktail at the bar "Mosquito Shelter". Of course, all the promocodes differ.
As the "Mosquito Shelter" opens only at 9, and partying in Sudislavl usually begins at as ... | 3 | n = int(input())
arr = []
for i in range(n):
line = int(input())
arr.append(line)
m = 6
for i in range(n):
for j in range(i+1, n):
t1 = arr[i]
t2 = arr[j]
tm = 0
for k in range(6):
if t1 % 10 != t2 % 10: tm += 1
t1 //= 10
t2 //= 10
... |
Once Bob got to a sale of old TV sets. There were n TV sets at that sale. TV set with index i costs ai bellars. Some TV sets have a negative price — their owners are ready to pay Bob if he buys their useless apparatus. Bob can «buy» any TV sets he wants. Though he's very strong, Bob can carry at most m TV sets, and he ... | 3 | n, m = map(int, input().split())
nums = sorted(map(int, input().split()))
money = 0
for num in nums:
if (num < 0) and m:
money += num * -1
m -= 1
print(money) |
Polycarp urgently needs a shovel! He comes to the shop and chooses an appropriate one. The shovel that Policarp chooses is sold for k burles. Assume that there is an unlimited number of such shovels in the shop.
In his pocket Polycarp has an unlimited number of "10-burle coins" and exactly one coin of r burles (1 ≤ r ... | 1 | k, r = map(int, raw_input().split())
ct = 1
while (ct * k) % 10 != r and (ct * k) % 10 != 0:
ct += 1
print ct |
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())
s=0
for i in range (n):
a,b,c=map(int,input().split())
if a+b+c>1:
s=s+1
print(s)
|
Dreamoon is standing at the position 0 on a number line. Drazil is sending a list of commands through Wi-Fi to Dreamoon's smartphone and Dreamoon follows them.
Each command is one of the following two types:
1. Go 1 unit towards the positive direction, denoted as '+'
2. Go 1 unit towards the negative direction, ... | 3 | def find(target,doubts):
if target%2!=doubts%2 :
return -1
return int((doubts-target)/2+target)
def prob(p,total):
#print(p,total)
if abs(p)>total:
return 0
x=2**total
k=1
m=1
for i in range(p):
k=k*(total-i)
m=m*(i+1)
r=int(k/m)
return r/x
s1=i... |
Sergey is testing a next-generation processor. Instead of bytes the processor works with memory cells consisting of n bits. These bits are numbered from 1 to n. An integer is stored in the cell in the following way: the least significant bit is stored in the first bit of the cell, the next significant bit is stored in ... | 3 | def to_dec(bina):
res = 0
b = 2**len(bina)
for i in range(len(bina)):
b = b//2
if bina[i] == 1:
res = res + b
return res
def to_bin(d):
res = []
while d > 0:
res.insert(0, d%2)
d = d //2
return "".join(map(str, res))[::-1]
n =... |
You have a fraction <image>. You need to find the first occurrence of digit c into decimal notation of the fraction after decimal point.
Input
The first contains three single positive integers a, b, c (1 ≤ a < b ≤ 105, 0 ≤ c ≤ 9).
Output
Print position of the first occurrence of digit c into the fraction. Positions... | 3 | from fractions import Fraction
(a, b, c) = tuple(map(int, input().split()))
f = Fraction(a, b)
for i in range(900):
for j in range(10):
if f < Fraction(j+1, 10):
if j == c:
print(i+1)
exit(0)
f -= Fraction(j, 10)
f *= 10
break
... |
Holidays have finished. Thanks to the help of the hacker Leha, Noora managed to enter the university of her dreams which is located in a town Pavlopolis. It's well known that universities provide students with dormitory for the period of university studies. Consequently Noora had to leave Vičkopolis and move to Pavlopo... | 3 | # JAI SHREE RAM
import math; from collections import *
import sys; from functools import reduce
# sys.setrecursionlimit(10**6)
def get_ints(): return map(int, input().strip().split())
def get_list(): return list(get_ints())
def get_string(): return list(input().strip().split())
def printxsp(*... |
In this problem you have to simulate the workflow of one-thread server. There are n queries to process, the i-th will be received at moment ti and needs to be processed for di units of time. All ti are guaranteed to be distinct.
When a query appears server may react in three possible ways:
1. If server is free and... | 1 | from collections import deque
n, b = map(int, raw_input().split())
res = [0] * n
server = None
q = deque()
for i in range(n):
t, d = map(int, raw_input().split())
if not server:
server = t+d
res[i] = server
continue
if t < server and len(q) == b:
res[i] = -1
else:
q.append((... |
All cities of Lineland are located on the Ox coordinate axis. Thus, each city is associated with its position xi — a coordinate on the Ox axis. No two cities are located at a single point.
Lineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another city (bec... | 3 | in1 = int(input())
in2 = list(map(int, input().rstrip().split()))
for i in range(len(in2)):
if i == 0:
mini = abs(in2[i+1] - in2[i])
maxi = abs(in2[len(in2) -1] - in2[i])
print(mini, maxi)
elif i == len(in2) - 1:
mini = abs(in2[i - 1] - in2[i])
maxi = abs(in2[0] - in2[i])... |
Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1, p2, ..., pn.
You have a sequence of integers a1, a2, ..., an. In on... | 3 | n = int(input())
arr = list(map(int,input().split()))
arr.sort()
arrSorted = [i for i in range(1,n+1)]
result = 0
for i in range(len(arr)):
result += abs(arrSorted[i]-arr[i])
print(result) |
wHAT DO WE NEED cAPS LOCK FOR?
Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage.
Let's consider that a word has been typed with the Caps lock key accidentall... | 3 | a=input();print(a.swapcase() if a[1:].isupper() or len(a) < 2 else a) |
An array of integers p_1, p_2, ..., p_n is called a permutation if it contains each number from 1 to n exactly once. For example, the following arrays are permutations: [3, 1, 2], [1], [1, 2, 3, 4, 5] and [4, 3, 1, 2]. The following arrays are not permutations: [2], [1, 1], [2, 3, 4].
Polycarp invented a really cool p... | 3 | n = int(input())
arr = list( map(int, input().split()) )
s = n * (n + 1) // 2
for i in range(len(arr)):
s -= arr[i] * (len(arr) - i)
if s < 0:
print (-1)
exit(0)
if s % n:
print (-1)
exit(0)
f = s // n
if not 1 <= f <= n:
print (-1)
exit(0)
freq = [False] * n
freq[f - 1] = True
perm = [f]
e = f
for i in ra... |
Akash has lots of assignments to submit in his college. In one of the assignment he is given a string S of length N consisting of lowercase letters (a - z) only. Akash has to answer Q queries and for every query, he is given L, R and K. For each query he has to find the lexicographically Kth smallest character in subs... | 1 | N, K = [int(i) for i in raw_input().split()]
string = raw_input()
val =[[0]*26 for i in range(N)]
val[0][ord(string[0])-ord('a')] = 1
for i in range(1, N):
for j in range(26):
val[i][j] = val[i-1][j]
val[i][ord(string[i])-ord('a')] += 1
for i in range(K):
L, R, M = [int(i) for i in raw_input().split()]
sum_ = 0... |
You are given a number n and an array b_1, b_2, …, b_{n+2}, obtained according to the following algorithm:
* some array a_1, a_2, …, a_n was guessed;
* array a was written to array b, i.e. b_i = a_i (1 ≤ i ≤ n);
* The (n+1)-th element of the array b is the sum of the numbers in the array a, i.e. b_{n+1} = a_1... | 3 | import sys
from collections import Counter
ints = (int(x) for x in sys.stdin.read().split())
sys.setrecursionlimit(3000)
def main():
ntc = next(ints)
for tc in range(1,ntc+1):
n = next(ints)
b = [next(ints) for i in range(n+2)]
cnt = Counter(b)
total = sum(b)
def cond(i)... |
There are n programmers that you want to split into several non-empty teams. The skill of the i-th programmer is a_i. You want to assemble the maximum number of teams from them. There is a restriction for each team: the number of programmers in the team multiplied by the minimum skill among all programmers in the team ... | 3 | for _ in range(int(input())):
n,x = map(int,input().split())
l = list(map(int,input().split()))
l.sort()
m = 10**9+1
k = 0
cnt = 0
#print(l)
while(len(l) > 0):
s = l.pop()
k = k+1
if s < m:
m = s
if k*m >= x:
cnt = cnt+1
... |
Leo Jr. draws pictures in his notebook with checkered sheets (that is, each sheet has a regular square grid printed on it). We can assume that the sheets are infinitely large in any direction.
To draw a picture, Leo Jr. colors some of the cells on a sheet gray. He considers the resulting picture beautiful if the follo... | 3 | import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.wr... |
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Bi... | 3 | n = int(input())
def is_even(t):
return t % 2 == 0
if is_even(n):
n2 = n // 2
if is_even(n2):
print('YES')
else:
if n2 == 1:
print('NO')
else:
print('YES')
else:
print('No')
|
Kenkoooo is planning a trip in Republic of Snuke. In this country, there are n cities and m trains running. The cities are numbered 1 through n, and the i-th train connects City u_i and v_i bidirectionally. Any city can be reached from any city by changing trains.
Two currencies are used in the country: yen and snuuk.... | 3 | import sys
input=sys.stdin.readline
from collections import defaultdict
from heapq import heappush,heappop
N,m,s,t=map(int,input().split())
en=defaultdict(set)
sneek=defaultdict(set)
for i in range(m):
u,v,a,b=map(int,input().split())
en[u]|={(a,v)}
en[v]|={(a,u)}
sneek[u]|={(b,v)}
sneek[v]|={(b,u)}... |
Find bridges of an undirected graph G(V, E).
A bridge (also known as a cut-edge) is an edge whose deletion increase the number of connected components.
Constraints
* 1 ≤ |V| ≤ 100,000
* 0 ≤ |E| ≤ 100,000
* The graph is connected
* There are no parallel edges
* There are no self-loops
Input
|V| |E|
s0 t0
s1 t1
:
s... | 3 | import sys
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): retu... |
You are planning to buy an apartment in a n-floor building. The floors are numbered from 1 to n from the bottom to the top. At first for each floor you want to know the minimum total time to reach it from the first (the bottom) floor.
Let:
* a_i for all i from 1 to n-1 be the time required to go from the i-th floor... | 3 | import heapq
import sys
input = sys.stdin.readline
def dijkstra(s):
inf = 1145141919810
dist = [inf] * n
dist[s] = 0
visit = [0] * n
p = []
heapq.heappush(p, (dist[s], s))
while p:
d, u = heapq.heappop(p)
if dist[u] < d:
continue
visit[u] = 1
for ... |
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 | def main():
n = int(input())
count = 0
count1 = 0
for i in range(n):
probList = list(map(int, input().split()))
for j in probList:
if j == 1:
count+=1
if count>=2:
count1+=1
count = 0
print(count1)
if __name__ == '__main__'... |
You are given names of two days of the week.
Please, determine whether it is possible that during some non-leap year the first day of some month was equal to the first day of the week you are given, while the first day of the next month was equal to the second day of the week you are given. Both months should belong t... | 3 | a=str(input())
b=str(input())
c=[0,2,3,-4,-5]
cnt=0
x=['monday','tuesday','wednesday','thursday','friday','saturday','sunday']
for i in range (7):
if a==x[i]:
aa=i+1
# print(aa)
for j in range (7):
if b==x[j]:
bb=j+1
# print(bb)
#print(c)
for k in range(5):
if c[k]==bb-aa:
... |
According to a new ISO standard, a flag of every country should have a chequered field n × m, each square should be of one of 10 colours, and the flag should be «striped»: each horizontal row of the flag should contain squares of the same colour, and the colours of adjacent horizontal rows should be different. Berland'... | 1 | #!/usr/bin/env python
from sys import stdin
N, M = map(int, stdin.readline().split())
ok = True
prev_line = ''
for i in xrange(N):
line = stdin.readline().strip()
if line == prev_line:
ok = False
print 'NO'
break
for j in xrange(1, M):
if line[j] != line[0]:
ok = False
... |
You have n distinct points on a plane, none of them lie on OY axis. Check that there is a point after removal of which the remaining points are located on one side of the OY axis.
Input
The first line contains a single positive integer n (2 ≤ n ≤ 105).
The following n lines contain coordinates of the points. The i-t... | 1 | a=int(raw_input())
c1=0
c2=0
c3=0
for i in range(a):
x,y=raw_input().strip().split()
x1=int(x)
y1=int(y)
if x1>0:
c1+=1
elif x1==0:
c2+=1
else:
c3+=1
m1=0
m2=0
m3=0
if c2+c3<=1:
m1=1
elif c3+c1<=1:
m2=1
elif c2+c1<=1:
m3=1
else:
pass
b= m1 or m2 or m3
if b... |
There are N mountains in a circle, called Mountain 1, Mountain 2, ..., Mountain N in clockwise order. N is an odd number.
Between these mountains, there are N dams, called Dam 1, Dam 2, ..., Dam N. Dam i (1 \leq i \leq N) is located between Mountain i and i+1 (Mountain N+1 is Mountain 1).
When Mountain i (1 \leq i \l... | 3 | n = int(input())
A = list(map(int, input().split()))
ans = []
X = []
x1 = sum(A) - 2*sum(A[1::2])
X.append(x1)
for i in range(n-1):
X.append(2*A[i] - X[-1])
print(*X) |
You are given a grid with n rows and m columns, where each cell has a non-negative integer written on it. We say the grid is good if for each cell the following condition holds: if it has a number k > 0 written on it, then exactly k of its neighboring cells have a number greater than 0 written on them. Note that if the... | 3 | from bisect import *
from collections import *
from itertools import *
import functools
import sys
import math
from decimal import *
from copy import *
from heapq import *
from fractions import *
getcontext().prec = 30
MAX = sys.maxsize
MAXN = 1000010
MOD = 10**9+7
spf = [i for i in range(MAXN)]
spf[0]=spf[1] = -1
def ... |
You have two integers l and r. Find an integer x which satisfies the conditions below:
* l ≤ x ≤ r.
* All digits of x are different.
If there are multiple answers, print any of them.
Input
The first line contains two integers l and r (1 ≤ l ≤ r ≤ 10^{5}).
Output
If an answer exists, print any of them. Oth... | 3 | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 6 13:46:21 2020
@author: Олег
"""
l, r = map(int, input().split())
res = -1
for i in range(l, r+1):
cur = str(i)
st = set(cur)
if len(st) == len(cur):
res = i
break
print(res) |
T is a complete binary tree consisting of n vertices. It means that exactly one vertex is a root, and each vertex is either a leaf (and doesn't have children) or an inner node (and has exactly two children). All leaves of a complete binary tree have the same depth (distance from the root). So n is a number such that n ... | 1 | n, q = map(int, raw_input().strip().split())
for t in xrange(q):
u = int(raw_input().strip())
s = raw_input().strip()
b = 1
while u & b == 0:
b <<= 1
for c in s:
if c == 'L':
if b != 1:
u -= b
b >>= 1
u += b
elif c =... |
You are given an array a of length n consisting of zeros. You perform n actions with this array: during the i-th action, the following sequence of operations appears:
1. Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one;
2. Let ... | 3 | import itertools
import heapq
def maxheappush(heap, length, left, right):
heapq.heappush(heap, (-length, left, right))
def maxheappop(heap):
length, left, right = heapq.heappop(heap)
return -length, left, right
def get_length(left, right):
return right - left + 1
def build_array(n):
coun... |
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 | while True:
try:
n = int(raw_input())
a = []
while len(a) != n:
a += map(int,raw_input().split())
r = len(a)-1
l = 0
taxi = 0
aa = sorted(a)
while (l != r):
if aa[l]+aa[r] <= 4:
aa[r]+=... |
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 | t=int(input())
for i in range(0,t):
s=input()
if(len(s)<=10):
print(s)
else:
s1=s[0]+str(len(s)-2)+s[-1]
print(s1)
|
All cities of Lineland are located on the Ox coordinate axis. Thus, each city is associated with its position xi — a coordinate on the Ox axis. No two cities are located at a single point.
Lineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another city (bec... | 3 | def solve(arr , i , j,s):
mi = abs(arr[i]-arr[j])
mx = abs(arr[i]-arr[s])
print(mi , mx)
n =int(input())
arr = list(map(int,input().split()))
for i in range(n):
if i==0:
solve(arr , i , i+1,-1)
elif i ==n-1:
solve(arr , i, i-1,0)
else:
mi = min(abs(arr[i]-arr[i-1]) ,abs(arr[i]-arr[i+1]))
mx = max(abs(arr... |
In Berland the opposition is going to arrange mass walking on the boulevard. The boulevard consists of n tiles that are lain in a row and are numbered from 1 to n from right to left. The opposition should start walking on the tile number 1 and the finish on the tile number n. During the walk it is allowed to move from ... | 1 | #!/usr/bin/python
n = int(raw_input())
a = map(int,raw_input().split())
for i in range(1,1001):
for j in range(n):
if(a[j] >= 1):
a[j] -= 1
else:
a[j] = 0
if(a[0] == 0 or a[n - 1] == 0):
ans = i
break
else:
flag = 0
tag = True
... |
You are given a positive integer m and two integer sequence: a=[a_1, a_2, …, a_n] and b=[b_1, b_2, …, b_n]. Both of these sequence have a length n.
Permutation is a sequence of n different positive integers from 1 to n. For example, these sequences are permutations: [1], [1,2], [2,1], [6,7,3,4,1,2,5]. These are not: [... | 3 | n,m = [int(i) for i in input().split()]
a= [int(i) for i in input().split()]
b= [int(i) for i in input().split()]
a = sorted(a)
b = sorted(b)
x = 10000000000
for i in range(n):
p = (b[0]-a[i])%m
a_new = [(aj+p)%m for aj in a]
a_new = sorted(a_new)
if a_new == b:
x = min(p,x)
print(x) |
Write a program of a Merge Sort algorithm implemented by the following pseudocode. You should also report the number of comparisons in the Merge function.
Merge(A, left, mid, right)
n1 = mid - left;
n2 = right - mid;
create array L[0...n1], R[0...n2]
for i = 0 to n1-1
do L[i] = A[left + i]
for i = 0 to n2-1
do R[i] =... | 3 | cnt = 0
INF = pow(10, 18)
def merge(A, left, mid, right):
L = A[left:mid] + [INF]
R = A[mid:right] + [INF]
i = 0
j = 0
for k in range(left, right):
global cnt
cnt += 1
if L[i] <= R[j]:
A[k] = L[i]
i += 1
else:
A[k] = R[j]
... |
The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her n students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often oddl... | 3 | n, m = map(int, input().split())
f = list(map(int, input().split()))
f = sorted(f)
minfir = []
for i in range(m):
if i+n-1 == m:
break
else:
minfir.append(f[i+n-1] - f[i])
print(min(minfir))
|
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.
The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe... | 3 | s=input()
l=s.split('+');
l.sort()
print('+'.join(l)) |
So the Beautiful Regional Contest (BeRC) has come to an end! n students took part in the contest. The final standings are already known: the participant in the i-th place solved p_i problems. Since the participants are primarily sorted by the number of solved problems, then p_1 ≥ p_2 ≥ ... ≥ p_n.
Help the jury distrib... | 3 | from collections import OrderedDict
n=int(input())
for x in range(n):
a=int(input())
array=list(map(int,input().split()))
limit=int(a//2)
vie=5
unique=len(set(array[0:limit]))
if len(array)==1:
print(0,0,0)
elif unique<3:
print(0,0,0)
else:
if array[limit-1]==arra... |
This year, as in previous years, MemSQL is inviting the top 25 competitors from the Start[c]up qualification round to compete onsite for the final round. Not everyone who is eligible to compete onsite can afford to travel to the office, though. Initially the top 25 contestants are invited to come onsite. Each eligible ... | 3 | a=int(input())
b=list(map(int, input().split()))
print(max(0,max(b)-25)) |
Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1, p2, ..., pn.
Your task is to find such permutation p of length n, that the group of numbers |p1 - p2|, |p2 - p3|, ..., |pn - 1 - pn| has exactly k d... | 1 | import sys
n,k = map(int,(sys.stdin.readline().split()))
l = [n]
t = k
bit = 0
while t >= 1:
if bit == 0:
l.append(l[-1]-t)
bit = 1
else:
l.append(l[-1]+t)
bit = 0
t -= 1
r = n-k-1
while r > 0:
l.append(r)
r -= 1
for i in l:
print i,
|
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Bi... | 3 | while 1:
weight = int(input())
if weight < 1 or weight > 100:
continue
break
if weight % 2 != 0 or weight == 2:
print("NO")
else:
print("YES") |
Given an integer x, find 2 integers a and b such that:
* 1 ≤ a,b ≤ x
* b divides a (a is divisible by b).
* a ⋅ b>x.
* a/b<x.
Input
The only line contains the integer x (1 ≤ x ≤ 100).
Output
You should output two integers a and b, satisfying the given conditions, separated by a space. If no pair of in... | 3 |
def main():
buf = input()
x = int(buf)
for a in range(1, x+1):
for b in range(1, x+1):
if a % b == 0 and a * b > x and a // b < x:
print(a, b)
return
print(-1)
if __name__ == '__main__':
main()
|
Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are n drinks in his fridge, the volume fraction of orange juice in the i-th drink equals pi percent.
One day Vasya decided to make himself an orange cocktail. He took equal proportions of ea... | 1 | n = input()
print sum(map(int, raw_input().split())) * 1.0 / n
|
You are given a set of n segments on the axis Ox, each segment has integer endpoints between 1 and m inclusive. Segments may intersect, overlap or even coincide with each other. Each segment is characterized by two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ m) — coordinates of the left and of the right endpoints.
Consider... | 3 | from __future__ import print_function
import sys
import math
import os.path
from copy import deepcopy
from functools import reduce
from collections import Counter, ChainMap, defaultdict
from itertools import cycle, chain
from queue import Queue, PriorityQueue
from heapq import heappush, heappop, heappushpop, heapify,... |
Tomorrow is a difficult day for Polycarp: he has to attend a lectures and b practical classes at the university! Since Polycarp is a diligent student, he is going to attend all of them.
While preparing for the university, Polycarp wonders whether he can take enough writing implements to write all of the lectures and d... | 3 | q = int(input())
while q > 0:
a, b, c, d, k = map(int, input().split())
p = a // c
if a % c != 0: p += 1
r = b // d
if b % d != 0: r += 1
if p + r > k: print(-1)
else:
print(p, end= ' ')
print(r)
q-=1 |
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties:
* G has exactly n vertices, numbered from 1 to... | 3 | # -*- coding:utf-8 -*-
"""
created by shuangquan.huang at 1/17/20
"""
import collections
import time
import os
import sys
import bisect
import heapq
from typing import List
def solve(N, M, edges):
if M == N*(N-1)//2:
return 'a' * N
g = collections.defaultdict(list)
for u, v in edges:
... |
Vika has n jars with paints of distinct colors. All the jars are numbered from 1 to n and the i-th jar contains ai liters of paint of color i.
Vika also has an infinitely long rectangular piece of paper of width 1, consisting of squares of size 1 × 1. Squares are numbered 1, 2, 3 and so on. Vika decided that she will ... | 1 | n=input()
a=map(int,raw_input().split())
m=min(a)
b=[i for i in range(n) if a[i]==m]
b.append(b[0]+n)
print m*n+max(b[i]-b[i-1] for i in range(len(b)))-1
|
An n × n table a is defined as follows:
* The first row and the first column contain ones, that is: ai, 1 = a1, i = 1 for all i = 1, 2, ..., n.
* Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the remaining elements are defin... | 3 | n=int(input())
arr=[1,2,6,20,70,252,924,3432,12870,48620]
print(arr[n-1])
|
You are given an array a consisting of n integers.
You can remove at most one element from this array. Thus, the final length of the array is n-1 or n.
Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.
Recall that the contiguous subarray a wi... | 3 | z,zz=input,lambda:list(map(int,z().split()))
zzz=lambda:[int(i) for i in stdin.readline().split()]
szz,graph,mod,szzz=lambda:sorted(zz()),{},10**9+7,lambda:sorted(zzz())
from string import *
from re import *
from collections import *
from queue import *
from sys import *
from collections import *
from math import *
fro... |
You are given an undirected graph with N vertices and 0 edges. Process Q queries of the following types.
* `0 u v`: Add an edge (u, v).
* `1 u v`: Print 1 if u and v are in the same connected component, 0 otherwise.
Constraints
* 1 \leq N \leq 200,000
* 1 \leq Q \leq 200,000
* 0 \leq u_i, v_i \lt N
Input
Input is ... | 3 | class UnionFind():
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
if self.parents[x] < 0:
return x
else:
li = []
while self.parents[x] >= 0:
li.append(x)
x = self.parents[x]
... |
Vasya's birthday is approaching and Lena decided to sew a patterned handkerchief to him as a present. Lena chose digits from 0 to n as the pattern. The digits will form a rhombus. The largest digit n should be located in the centre. The digits should decrease as they approach the edges. For example, for n = 5 the handk... | 3 | #in the name of god
#CodeForces,Problemset
n=int(input())
width=n*2+1
lines=[]
for i in range(n+1):
line=""
spaces=" "*(width-(i*2+1))
line+=spaces
for j in range(i+1):
line+=str(j)+" "
for j in reversed(range(i)):
line+=str(j)+" "
line=line[:len(line)-1]
lines.append(line)
... |
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 | inp = lambda: map(int, input().split())
n, l = inp()
a = sorted(list(inp()))
k = mx = 0.0
for i in range(1, n):
k = a[i] - a[i - 1]
mx = max(mx, k / 2)
mx = max(mx, a[0] - 0.0)
mx = max(mx, l - a[n - 1])
print(mx) |
There are three airports A, B and C, and flights between each pair of airports in both directions.
A one-way flight between airports A and B takes P hours, a one-way flight between airports B and C takes Q hours, and a one-way flight between airports C and A takes R hours.
Consider a route where we start at one of th... | 3 | a = input().split()
a.sort()
print(int(a[0]) + int(a[1])) |
Polycarp urgently needs a shovel! He comes to the shop and chooses an appropriate one. The shovel that Policarp chooses is sold for k burles. Assume that there is an unlimited number of such shovels in the shop.
In his pocket Polycarp has an unlimited number of "10-burle coins" and exactly one coin of r burles (1 ≤ r ... | 1 | k, r = map(int,raw_input().split())
flag = 0
val = k
for i in range(1, 10):
k=val*i
#print k
if k%10==r or k%10==0:
flag = i
break
if flag:
print flag
else:
print 10
|
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find ... | 3 | l=[4,7,44,47,74,77,444,447,474,477,744,747,774,777]
ls=l+[1]
n=int(input())
for i in l:
if n%i==0:
n=1001
if n==1001:
print('YES')
else:
print('NO') |
Two foxes Jiro and Saburo are playing a game called 1D Reversi. This game is played on a board, using black and white stones. On the board, stones are placed in a row, and each player places a new stone to either end of the row. Similarly to the original game of Reversi, when a white stone is placed, all black stones b... | 3 | s=input()
ans=0
for i,j in zip(s[:-1],s[1:]):
if i!=j:
ans+=1
print(ans)
|
On the competitive programming platform CodeCook, every person has a rating graph described by an array of integers a of length n. You are now updating the infrastructure, so you've created a program to compress these graphs.
The program works as follows. Given an integer parameter k, the program takes the minimum of ... | 3 | from collections import deque
def cal(nums, k):
q = deque()
ans = []
for i, n in enumerate(nums):
while q and q[-1] > n:
q.pop()
q.append(n)
if i >= k - 1:
ans.append(q[0])
if q[0] == nums[i - k + 1]:
q.popleft()
return ans
for... |
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()
for c in s:
if not (c == 'a' or c == 'e' or c == 'i' or c == 'o' or c == 'u' or c == 'y'):
print("." + c, end = "") |
A string s of length n (1 ≤ n ≤ 26) is called alphabetical if it can be obtained using the following algorithm:
* first, write an empty string to s (i.e. perform the assignment s := "");
* then perform the next step n times;
* at the i-th step take i-th lowercase letter of the Latin alphabet and write it eithe... | 3 |
# Author : raj1307 - Raj Singh
# Date : 10.07.2021
from __future__ import division, print_function
import os,sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
def ii(): return int(input())... |
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm:
* if the last digit of the number is non-zero, she decreases the number by one;
* if the last digit of the number is ze... | 3 | l1 = input().split(" ")
n = int(l1[0])
k = int(l1[1])
for i in range(k):
if n % 10 == 0:
n = n/10
else:
n = n-1
print (int(n))
|
You are given several queries. In the i-th query you are given a single positive integer ni. You are to represent ni as a sum of maximum possible number of composite summands and print this maximum number, or print -1, if there are no such splittings.
An integer greater than 1 is composite, if it is not prime, i.e. if... | 1 | n_queries = int(raw_input())
sol = []
while n_queries:
n = int(raw_input())
_parts = -1
if( not(n <= 3 or n == 5 or n == 7 or n == 11) ):
if n%4 == 0:
_parts = n/4
elif n%4 == 1:
_parts = (n - 9)/4 + 1
elif n%4 == 2:
_parts = (n - 6)/4 + 1
... |
As you may know, MemSQL has American offices in both San Francisco and Seattle. Being a manager in the company, you travel a lot between the two cities, always by plane.
You prefer flying from Seattle to San Francisco than in the other direction, because it's warmer in San Francisco. You are so busy that you don't rem... | 3 | # ===================================
# (c) MidAndFeed aka ASilentVoice
# ===================================
# import math
# import collections
# import string
# ===================================
n = int(input())
s = str(input())
print("YES" if s.count("SF") > s.count("FS") else "NO") |
You are given a grid of squares with H horizontal rows and W vertical columns, where each square is painted white or black. HW characters from A_{11} to A_{HW} represent the colors of the squares. A_{ij} is `#` if the square at the i-th row from the top and the j-th column from the left is black, and A_{ij} is `.` if t... | 3 | h, w = map(int, input().split())
a = [list(input()) for _ in range(h)]
d = (-1, 0), (1, 0), (0, -1), (0, 1)
p = [(i, j) for i in range(h) for j in range(w) if a[i][j] == '#']
n = h * w - len(p)
r = 0
while n:
r += 1
s = []
for i, j in p:
for di, dj in d:
di += i
dj += j
... |
Today Tavas got his test result as an integer score and he wants to share it with his girlfriend, Nafas.
His phone operating system is Tavdroid, and its keyboard doesn't have any digits! He wants to share his score with Nafas via text, so he has no choice but to send this number using words.
<image>
He ate coffee mi... | 1 | n = int(input())
w = ["one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve"]
w1 = [x + "teen" for x in (["thir"] + w[3:9])]; w1[2] = "fifteen"; w1[5] = "eighteen";
w += w1
w10 = ["twenty","thirty","forty","fifty"] + [x + "ty" for x in w[5:9]]; w10[-2] = "eighty"
for x in w10: w += [x] +... |
Alexey is travelling on a train. Unfortunately, due to the bad weather, the train moves slower that it should!
Alexey took the train at the railroad terminal. Let's say that the train starts from the terminal at the moment 0. Also, let's say that the train will visit n stations numbered from 1 to n along its way, and ... | 1 | #!/usr/bin/env python
from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
def main():
t = int(input())
for _ in range(t):... |
The Little Elephant loves sortings.
He has an array a consisting of n integers. Let's number the array elements from 1 to n, then the i-th element will be denoted as ai. The Little Elephant can make one move to choose an arbitrary pair of integers l and r (1 ≤ l ≤ r ≤ n) and increase ai by 1 for all i such that l ≤ i ... | 3 | # cook your dish here
n=int(input())
lst=list(map(int,input().split()))
sum1=0
for i in range(1,n):
sum1+=(max(lst[i-1]-lst[i],0))
print(sum1)
|
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Bi... | 3 | x = input()
if int(x) <= 2:
print('NO')
elif int(x) % 2 == 0:
print('YES')
else:
print('NO') |
One rainy gloomy evening when all modules hid in the nearby cafes to drink hot energetic cocktails, the Hexadecimal virus decided to fly over the Mainframe to look for a Great Idea. And she has found one!
Why not make her own Codeforces, with blackjack and other really cool stuff? Many people will surely be willing to... | 1 | def solve():
num = int(raw_input())
if(num>21) or num<=10:
print 0
return
if(num == 20):
print 15
else:
print 4
solve()
|
Omkar is building a waterslide in his water park, and he needs your help to ensure that he does it as efficiently as possible.
Omkar currently has n supports arranged in a line, the i-th of which has height a_i. Omkar wants to build his waterslide from the right to the left, so his supports must be nondecreasing in he... | 3 | import sys
t=int(input())
for _ in range(t):
n=int(input())
a=list(map(int,input().split()))
mx=-1
mi=sys.maxsize
cost=0
for i in range(1,n):
if(a[i-1]>a[i]):
mx=max(mx,a[i-1])
mi=min(mi,a[i])
else:
if(mx!=-1 and mi!=sys.maxsize):
cost+=abs(mx-mi)
mx=-1
mi=sys.maxsize
if(mx!=-1 and mi!=sy... |
Polycarp wants to cook a soup. To do it, he needs to buy exactly n liters of water.
There are only two types of water bottles in the nearby shop — 1-liter bottles and 2-liter bottles. There are infinitely many bottles of these two types in the shop.
The bottle of the first type costs a burles and the bottle of the se... | 3 | t=int(input())
for i in range(t):
n,a,b=map(int, input().split())
total=0
if(a*2<b):
total=a*n
else:
total=(n//2)*b
total+=(n%2)*a
print(total) |
Amr is a young coder who likes music a lot. He always wanted to learn how to play music but he was busy coding so he got an idea.
Amr has n instruments, it takes ai days to learn i-th instrument. Being busy, Amr dedicated k days to learn how to play the maximum possible number of instruments.
Amr asked for your help ... | 1 | n,k = map(int,raw_input().split())
array = []
array = map(int ,raw_input().split())
lenth = len(array)
total = 0
cnt = 0
temp = []
kk = k
def second_element(t):
return t[1]
indices = zip(range(n),array)
pair = sorted(indices,key = second_element)
a = [(array[i],i) for i in range(n)]
a.sort()
for i in range(0... |
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory.
George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living... | 3 | n=int(input())
total=0
for i in range (0,n):
q,p=(int(x) for x in input().split())
if(p-q)>=2:
total+=1
print(total) |
Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, inf... | 3 | n = int(input())
s = input()
print(s[::-1][1:n:2]+s[1-n%2:n:2]) |
The length of the longest common prefix of two strings s = s_1 s_2 … s_n and t = t_1 t_2 … t_m is defined as the maximum integer k (0 ≤ k ≤ min(n,m)) such that s_1 s_2 … s_k equals t_1 t_2 … t_k.
Koa the Koala initially has n+1 strings s_1, s_2, ..., s_{n+1}.
For each i (1 ≤ i ≤ n) she calculated a_i — the length of ... | 3 | def solve(A, n):
a = max(A)
ans = ['a' * (a+1)] * (n + 1)
for i in range(n):
t = ans[i][A[i]]
change = 'b' if t == 'a' else 'a'
ans[i + 1] = ans[i][:A[i]] + change + ans[i][A[i] + 1:]
return ans
for _ in range(int(input())):
n = int(input())
A = list(map(int, input().spl... |
Little Arjit is the leader of a marvellous fighting army. His team is very good at fighting against all their enemies. But like Hound from Game of Thrones, Little Arjit and his entire team is scared of fire. When they see fire, they feel threatened, and scared like a little child, and don’t even mind giving up from a f... | 1 | for _ in range(int(raw_input())):
s = raw_input().strip().replace("XO", "X").replace("OX", "X")
while "XO" in s or "OX" in s:
s = s.replace("XO", "X").replace("OX", "X")
print s.count("O") |
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th... | 3 | n=list(input())
u,l=0,0
for i in range(len(n)):
if n[i].islower():
l+=1
else:
u+=1
if u>l:
n=[x.capitalize() for x in n]
n=''.join(n)
print(n)
else:
n=[x.lower() for x in n]
n=''.join(n)
print(n)
|
Write a program which judges wheather given length of three side form a right triangle. Print "YES" if the given sides (integers) form a right triangle, "NO" if not so.
Constraints
* 1 ≤ length of the side ≤ 1,000
* N ≤ 1,000
Input
Input consists of several data sets. In the first line, the number of data set, N is... | 3 | N = int(input())
for i in range(N):
a = list(map(int, input().split()))
a.sort()
if a[0]**2 + a[1]**2 == a[2]**2:
print("YES")
else:
print("NO")
|
In Japan, people make offerings called hina arare, colorful crackers, on March 3.
We have a bag that contains N hina arare. (From here, we call them arare.)
It is known that the bag either contains arare in three colors: pink, white and green, or contains arare in four colors: pink, white, green and yellow.
We have ... | 3 | # coding: utf-8
input()
print('Four' if 'Y' in input() else 'Three') |
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th... | 3 | def get_values():
word = input()
lower = 0
upper = 0
result = ''
for i in word:
if i.isupper():
upper += 1
else:
lower += 1
if upper > lower:
return print(word.upper())
return print(word.lower())
get_values() |
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If... | 3 | players = input()
count = 0
count2 = 0
temp = players[0]
for i in range(len(players)):
if players[i] == temp:
count += 1
else:
temp = players[i]
count = 1
if count >= 7:
count2 += 1
if count2 >= 1:
print("YES")
else:
print("NO") |
There is an integer sequence A of length N whose values are unknown.
Given is an integer sequence B of length N-1 which is known to satisfy the following:
B_i \geq \max(A_i, A_{i+1})
Find the maximum possible sum of the elements of A.
Constraints
* All values in input are integers.
* 2 \leq N \leq 100
* 0 \leq B_i... | 3 | n=int(input())
b=list(map(int,input().split()))
ans=0
for i in range(n-2):
ans+=min(b[i],b[i+1])
ans+=b[0]
ans+=b[n-2]
print(ans) |
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had a red socks and b blue socks.
According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot.
Every day Vasya puts on new socks in the morning and ... | 3 | a,b = list(map(int,input().strip().split()))
c1=0
while a>0 and b>0:
c1=c1+1
a = a-1
b = b-1
c2=0
if a>b:
c2 =a//2
else:
c2 = b//2
print(c1,c2,end="")
|
The only difference between easy and hard versions is the maximum value of n.
You are given a positive integer number n. You really love good numbers so you want to find the smallest good number greater than or equal to n.
The positive integer is called good if it can be represented as a sum of distinct powers of 3 (... | 3 | def Solve(n):
Di={}
save=n
j=FindPow(n)
ma=j
b=False
while n>0:
if j in Di.keys():
Di[j]+=1
b=True
else:
Di[j]=1
n-=int(pow(3,j))
#print(n)
j=FindPow(n)
if not b:
return save
data=[0]*(ma+2)
for j in ... |
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≤ i ≤ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is it... | 3 | n = int(input())
arr = input().split()
count = 1
max_len = 1
for i in range(n - 1):
arr[i] = int(arr[i])
arr[i + 1] = int(arr[i + 1])
if arr[i] <= arr[i + 1]:
count += 1
else:
if count > max_len:
max_len = count
count = 1
if count > max_len:
max_len = count
print(max_len) |
It is November 18 now in Japan. By the way, 11 and 18 are adjacent Lucas numbers.
You are given an integer N. Find the N-th Lucas number.
Here, the i-th Lucas number L_i is defined as follows:
* L_0=2
* L_1=1
* L_i=L_{i-1}+L_{i-2} (i≥2)
Constraints
* 1≤N≤86
* It is guaranteed that the answer is less than 10^{18}.
... | 3 | a, b = 2, 1
N = int(input())
for _ in range(N):
a, b = b, a+b
print(a) |
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob.
Right now, Limak and Bob weigh a and b respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight.
Limak eats a lot and his weight is tripled after every year, while Bob's weight... | 3 | a , b = map(int, input().split())
y = 0
while True:
a *= 3
b *= 2
if a <= b:
y += 1
else:
y += 1
break
print(y) |
There are N slimes lining up in a row. Initially, the i-th slime from the left has a size of a_i.
Taro is trying to combine all the slimes into a larger slime. He will perform the following operation repeatedly until there is only one slime:
* Choose two adjacent slimes, and combine them into a new slime. The new sli... | 3 | # dp[l][r]=min(区間[l,r]を合成するための最小コスト)
n=int(input())
a=list(map(int,input().split()))
INF=10**15
dp=[[0]*n for i in range(n)]
for i in range(n):
dp[i][i]=a[i]
# 合成するときの必要経費を構成
for i in range(n-1):
for j in range(i+1,n):
dp[i][j]=dp[i][j-1]+a[j]
dp[0][-1]=0
# dp[i][j]=min(dp[i][k]+dp[k+1][j])+必要経費 で斜め(0,1... |
You are given two sequences a_1, a_2, ..., a_n and b_1, b_2, ..., b_n. Each element of both sequences is either 0, 1 or 2. The number of elements 0, 1, 2 in the sequence a is x_1, y_1, z_1 respectively, and the number of elements 0, 1, 2 in the sequence b is x_2, y_2, z_2 respectively.
You can rearrange the elements i... | 3 | t=int(input())
while t>0:
x1,y1,z1=input().split()
x1,y1,z1=int(x1),int(y1),int(z1)
x2,y2,z2=input().split()
x2,y2,z2=int(x2),int(y2),int(z2)
ans=0
if z1>y2:
ans=2*y2
if y1>x2:
ans=ans-2*(y1-x2)
else:
ans=2*z1
if y1>x2+y2-z1:
ans=ans-2*... |
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya has two strings a and b of the same length n. The strings consist only of lucky digits. Pety... | 3 | from collections import Counter
string1 = input()
string2 = input()
x1 = Counter(string1)
x2 = Counter(string2)
string1 = list(string1)
string2 = list(string2)
q = Counter()
q['4'] = abs(x1['4'] - x2['4'])
q['7'] = abs(x1['7'] - x2['7'])
if q['4'] < q['7']:
w = '4'
else:
w = '7'
ans = 0
dp = 0
for i in range... |
We have a grid with H rows and W columns of squares. Snuke is painting these squares in colors 1, 2, ..., N. Here, the following conditions should be satisfied:
* For each i (1 ≤ i ≤ N), there are exactly a_i squares painted in Color i. Here, a_1 + a_2 + ... + a_N = H W.
* For each i (1 ≤ i ≤ N), the squares painted i... | 3 | h,w=map(int,input().split())
n=int(input())
b=list(map(int,input().split()))
a=[]
for i in range(n):
for j in range(b[i]):
a.append(i+1)
g=[[0 for i in range(w)] for j in range(h)]
for i in range(h):
if i%2==0:
for j in range(w):
g[i][j]=a[0]
a.remove(a[0])
else:
for j in range(w):
... |
You are given two integers n and d. You need to construct a rooted binary tree consisting of n vertices with a root at the vertex 1 and the sum of depths of all vertices equals to d.
A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last diffe... | 3 | import sys
sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(ro... |
High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.
Vasya can change no more than k characters of the original string. W... | 1 | # https://vjudge.net/contest/339400#problem/F
(n, k) = list(map(int, raw_input().split(' ')))
s = raw_input()
def sol(s, c, k):
l = 0
r = 0
used = 0
res = 0
while l < len(s):
while r < len(s) and (used < k or s[r] == c):
if s[r] != c:
used += 1
r += ... |
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 | for i in range(int(input())):
a,b=tuple(map(int,input().split()))
b,a=max(b,a),min(b,a)
if((b-a)%10!=0):
print(abs((b-a)//10 + 1))
else:
print(abs((b-a)//10)) |
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 | s=str(input())
if(ord(s[0])>=97):
print(str(chr(ord(s[0])-32))+s[1:])
else:
print(s)
|
Recently Anton found a box with digits in his room. There are k2 digits 2, k3 digits 3, k5 digits 5 and k6 digits 6.
Anton's favorite integers are 32 and 256. He decided to compose this integers from digits he has. He wants to make the sum of these integers as large as possible. Help him solve this task!
Each digit c... | 1 | def main():
tmp=raw_input()
tmp=tmp.split()
x1=int(tmp[0])
x2=int(tmp[1])
x3=int(tmp[2])
x4=int(tmp[3])
ans=0
ans+=256*min(x1,min(x3,x4))
ans+=32*max(min(x1-min(x3,x4),x2),0)
print ans
main() |
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
__author__ = "runekri3"
n, m, a = [int(digit) for digit in input().split(" ")]
rows = math.ceil(n/a)
cols = math.ceil(m/a)
print(rows*cols) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.