problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay iΒ·k dollars for the i-th banana).
He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas?
Input
The first lin... | 3 | k,n,w=map(int, input().split())
borrow = (k*(w*(w+1)//2)) - n
if(borrow<0):
print(0)
else:
print(borrow) |
On a two-dimensional plane, there are m lines drawn parallel to the x axis, and n lines drawn parallel to the y axis. Among the lines parallel to the x axis, the i-th from the bottom is represented by y = y_i. Similarly, among the lines parallel to the y axis, the i-th from the left is represented by x = x_i.
For ever... | 3 | n, m = map(int, input().split())
x = list(map(int, input().split()))
y = list(map(int, input().split()))
ax = sum([(2*i - n + 1)*x[i] for i in range(n)])
ay = sum([(2*i - m + 1)*y[i] for i in range(m)])
print((ax*ay)%(10**9+7))
|
Given is a tree G with N vertices. The vertices are numbered 1 through N, and the i-th edge connects Vertex a_i and Vertex b_i.
Consider painting the edges in G with some number of colors. We want to paint them so that, for each vertex, the colors of the edges incident to that vertex are all different.
Among the colo... | 3 | N=int(input())
AB=[list(map(int,input().split())) for i in range(N-1)]
l=[[] for i in range(N)]
e=[0]*(N-1)
for i,(a,b) in enumerate(AB):
l[a-1].append((b-1,i))
l[b-1].append((a-1,i))
from collections import deque
q=deque([(AB[0][0]-1,1),(AB[0][1]-1,1)])
e[0]=1
M=1
while q:
vp,c=q.popleft()
x=1
for ... |
Polycarp is a great fan of television.
He wrote down all the TV programs he is interested in for today. His list contains n shows, i-th of them starts at moment li and ends at moment ri.
Polycarp owns two TVs. He can watch two different shows simultaneously with two TVs but he can only watch one show at any given mom... | 3 | n = int(input())
def conflicts(a, b):
return a[1] >= b[0]
shows = []
for i in range(n):
x, y = map(int, input().split())
shows.append((x, y))
shows.sort(key=lambda x: x[0])
ok = True
tv1 = [(-1, -1)]
tv2 = [(-1, -1)]
for s in shows:
if not conflicts(tv1[-1], s):
tv1.append(s)
elif not c... |
You are given three strings A, B and C. Check whether they form a word chain.
More formally, determine whether both of the following are true:
* The last character in A and the initial character in B are the same.
* The last character in B and the initial character in C are the same.
If both are true, print `YES`.... | 3 | a,b,c=input().split();print('YNEOS'[a[-1:]+c[0]!=b[0]+b[-1:]::2]) |
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like [walls](https://www.youtube.com/watch?v=YR5ApYxkU-U), he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.
Roger Waters has a square grid of size nΓ n and he wants to traverse his grid f... | 3 | # by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
def main():
for _ in range(int(input())):
n = int(input())
arr = [list(input().strip()) for _ in range(n)]
a,b,c,d = int(arr[0][1]),int(arr[1][0]),int(arr[n-1][n-2]),int(arr[n-2][n-1])... |
You are given a tree consisting of n vertices. A tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a color assigned to it (a_v = 1 if the vertex v is white and 0 if the vertex v is black).
You have to solve the following problem for each vertex v: what is the maximum difference betwee... | 3 | import sys
input = sys.stdin.readline
getint = lambda: int(input())
getints = lambda: [int(a) for a in input().split()]
if __name__ == "__main__":
n = getint()
colors = [(i*2-1) for i in getints()]
tree = [[] for i in range(n)]
for i in range(n-1):
a, b = getints()
tree[a-1].append(b-1)... |
Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks.
Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off.
You know that there will be n interesting minutes t1, t2, ..., tn. Yo... | 3 | n = int(input())
t = input().split()
current_time = 0
total_time = 0
for idx, i in enumerate(t):
i = int(i)
if i-current_time > 15:
total_time += 15
break
else:
total_time += i-current_time
current_time = i
if idx == n-1:
if i + 15 <= 90:
total_time += 1... |
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 | for _ in range(int(input())):
n, m = map(int, input().split())
mat = []
for i in range(n):
mat.append(list(map(int, input().split())))
flag = 1
for i in range(n):
for j in range(m):
if i == 0 or i == n - 1:
if j == 0 or j == m - 1:
if m... |
Once when Gerald studied in the first year at school, his teacher gave the class the following homework. She offered the students a string consisting of n small Latin letters; the task was to learn the way the letters that the string contains are written. However, as Gerald is too lazy, he has no desire whatsoever to l... | 3 | import sys
import math
st = (sys.stdin.readline())
k = int(sys.stdin.readline())
d = dict()
alla = 0
for i in range(len(st) - 1):
if st[i] in d:
d[st[i]] += 1
else:
d[st[i]] = 1
alla += 1
f = sorted(d.items(), key = lambda x: x[1])
v = []
p = 0
for i in f:
if(k - i[1] >= 0):
... |
Theatre Square in the capital city of Berland has a rectangular shape with the size n Γ m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a Γ a.
What is the least number of flagstones needed to pave the Square? It'... | 3 | n, m, a = tuple(map(int,input().split(' ')))
print(((n-1)//a+1)*((m-1)//a+1))
|
Dima loves representing an odd number as the sum of multiple primes, and Lisa loves it when there are at most three primes. Help them to represent the given number as the sum of at most than three primes.
More formally, you are given an odd numer n. Find a set of numbers pi (1 β€ i β€ k), such that
1. 1 β€ k β€ 3
2. ... | 1 | from __future__ import print_function
from math import sqrt
def isPrime(a):
if a <= 1:
return False
if a == 2:
return True
if a % 2 == 0:
return False
for i in range(3, int(sqrt(a)) + 1, 2):
if a % i == 0:
return False
return True
ret = []
def solve(... |
Arya is new to matrices. With lots of subtopics in the chapter, he finds it difficult in getting good in all of them. As of now, he is practising matrix multiplications. He takes two different matrices and checks in how many different ways could they be multiplied. If they are multiplicable, he multiplies in all the wa... | 1 | for t in range(input()):
x1,x2,x3,x4=map(int,raw_input().split())
print (x1==x4) + (x2==x3) |
A bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.
The teacher gave Dmitry's class a very strange task β she asked every student... | 3 | import math
import os
import sys
from io import BytesIO, IOBase
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.write... |
There are n students in a school class, the rating of the i-th student on Codehorses is a_i. You have to form a team consisting of k students (1 β€ k β€ n) such that the ratings of all team members are distinct.
If it is impossible to form a suitable team, print "NO" (without quotes). Otherwise print "YES", and then pri... | 3 | n,k = map(int,input().split())
a = list(map(int,input().split()))
d = list(set(a))
if len(d) < k:
print("NO")
else:
print("YES")
ans = [a.index(d[i])+1 for i in range(k)]
print(" ".join(map(str,ans)))
|
There are n candies in a row, they are numbered from left to right from 1 to n. The size of the i-th candy is a_i.
Alice and Bob play an interesting and tasty game: they eat candy. Alice will eat candy from left to right, and Bob β from right to left. The game ends if all the candies are eaten.
The process consists o... | 3 | t=input()
for _ in range(int(t)):
n=int(input())
a=input().split()
a=[int(i) for i in a]
ansa=ansb=suma=sumb=mov=0
i=0
j=n-1
flag=0
while flag!=1:
suma=0
while i<=j:
suma+=a[i]
i+=1
if suma>sumb:
mov+=1
a... |
You are given three positive integers n, a and b. You have to construct a string s of length n consisting of lowercase Latin letters such that each substring of length a has exactly b distinct letters. It is guaranteed that the answer exists.
You have to answer t independent test cases.
Recall that the substring s[l ... | 3 | for _ in range(int(input())):
n,a,b = [int(i) for i in input().split()]
s = []
alpha = [chr(i) for i in range(97, 97+b)]
ans = ''.join(alpha)
ans = ans*int((n+b)/b)
ans = ans[:n]
print(ans) |
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.
<image>
There are n cities and n-1 two-way roads connecting pairs of cities in the ki... | 3 | # import time
from collections import defaultdict
from collections import deque
import heapq
N, K = [int(_) for _ in input().split()]
# s = time.time()
G = [[] for i in range(N)]
for i in range(N-1):
U, V = [int(_) for _ in input().split()]
G[U-1].append(V-1)
G[V-1].append(U-1)
nodes = {
0: (0, 0, ... |
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())
m = 0
for k in range(0, n):
if sum([int(i) for i in input().split(' ')]) >= 2:
m += 1
print(m)
|
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc.... | 3 | x=input()
y=input()
n=len(x)
m=len(y)
q=0
if(n!=m):print("NO")
else:
for i in range(n):
if(x[i]!=y[n-1-i]):
q=1
print("NO")
break
if(q==0):print("YES") |
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the oppo... | 3 | n=int(input())
a=0;p=''
for i in range(n):
f=str(input())
if f!=p:
a+=1
p=f
print(a) |
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... | 1 | #!/usr/bin/env python
# Codeforce problem 50A
import sys
m, n = [int(item) for item in sys.stdin.readline().split()]
print(m*n/2)
|
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())
d = input()
s = d.count('A')
e = d.count('D')
if s>e:
print('Anton')
elif s==e:
print('Friendship')
else:
print('Danik')
|
You are given a non-empty string s=s_1s_2... s_n, which consists only of lowercase Latin letters. Polycarp does not like a string if it contains at least one string "one" or at least one string "two" (or both at the same time) as a substring. In other words, Polycarp does not like the string s if there is an integer j ... | 3 | def solve():
S = input()
l = 0
ans = []
while l < len(S)-2:
if S[l] == "o":
if S[l+1] == "n" and S[l+2] == "e":
ans.append(l+1)
l += 3
else:
l += 1
elif S[l] == "t":
if S[l+1] == "w" and S[l+2] == "o":
... |
You have an array a of length n. For every positive integer x you are going to perform the following operation during the x-th second:
* Select some distinct indices i_{1}, i_{2}, β¦, i_{k} which are between 1 and n inclusive, and add 2^{x-1} to each corresponding position of a. Formally, a_{i_{j}} := a_{i_{j}} + 2^{... | 3 | from math import log2
for _ in range(int(input())):
n = int(input())
l = list(map(int,input().split()))
i = 1
s = 0
while(i < len(l)):
if l[i-1] > l[i]:
s = max(s,l[i-1]-l[i])
l[i] = l[i-1]
i = i+1
if s == 0:
print(0)
continue
else:
... |
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 | x = int(input())
for q in range(x):
input1 = input()
if len(input1) <= 10:
print(input1)
else:
length = len(input1)
print(input1[0]+str(length-2)+input1[-1]) |
You are given n strings s_1, s_2, β¦, s_n consisting of lowercase Latin letters.
In one operation you can remove a character from a string s_i and insert it to an arbitrary position in a string s_j (j may be equal to i). You may perform this operation any number of times. Is it possible to make all n strings equal?
In... | 3 | x=int(input())
for i in range(0,x):
n=int(input())
ar=[]
b=[]
for j in range(0,n):
s=input()
d=list(s)
ar=ar+d
r=0
b=ar
set(b)
for k in range(0,len(b)):
g=ar.count(b[k])
if(g%n!=0):
r=r+1
break
if(r):
print("NO")... |
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network.
Bu... | 3 | z=input()
a=set()
for i in z:
if i not in a:
a.add(i)
n=len(a)
if n%2==0:
print("CHAT WITH HER!")
elif n%2==1:
print("IGNORE HIM!")
|
Vasya and Petya are playing a simple game. Vasya thought of number x between 1 and n, and Petya tries to guess the number.
Petya can ask questions like: "Is the unknown number divisible by number y?".
The game is played by the following rules: first Petya asks all the questions that interest him (also, he can ask no ... | 3 | def sieve(a, b):
m = []
if (b != 1):
if (a == 1):
a += 1
primes = [1] * (b + 1)
primes[0] = 0
primes[1] = 0
for i in range(2, b + 1):
if (primes[i] == 1):
for j in range(2 * i, b + 1, i):
primes[j] = 0
fo... |
You are given a permutation p of the set {1, 2, ..., N}. Please construct two sequences of positive integers a_1, a_2, ..., a_N and b_1, b_2, ..., b_N satisfying the following conditions:
* 1 \leq a_i, b_i \leq 10^9 for all i
* a_1 < a_2 < ... < a_N
* b_1 > b_2 > ... > b_N
* a_{p_1}+b_{p_1} < a_{p_2}+b_{p_2} < ... < a... | 3 | n=int(input())
c=list(map(int, input().split()))
a=list(range(n,n**2+1,n))
b=list(range(n**2,0,-n))
for i in range(n):
b[c[i]-1]+=i
for i in a:
print(i,end=' ')
print()
for i in b:
print(i,end=' ')
print() |
A positive (strictly greater than zero) integer is called round if it is of the form d00...0. In other words, a positive integer is round if all its digits except the leftmost (most significant) are equal to zero. In particular, all numbers from 1 to 9 (inclusive) are round.
For example, the following numbers are roun... | 3 | t = int(input())
arr = []
while (t != 0):
sum = 0
s = str(input())
l = len(s)
for i in range(l):
a = int(s[i])*10**(l-i-1)
if (a != 0):
arr.append(a)
sum+=1
print(sum)
for i in range(sum):
print(arr[i], end = ' ')
print()
arr.clear()
t-... |
Fox Ciel is playing a mobile puzzle game called "Two Dots". The basic levels are played on a board of size n Γ m cells, like this:
<image>
Each cell contains a dot that has some color. We will use different uppercase Latin characters to express different colors.
The key of this game is to find a cycle that contain d... | 3 | from sys import setrecursionlimit
setrecursionlimit(10**6)
class Graph:
'''A graph has a set of vertices and a set of edges, with each
edge being an ordered pair of vertices. '''
def __init__ (self):
self._alist = {}
def add_vertex (self, vertex):
''' Adds 'vertex' to the graph
... |
A little bear Limak plays a game. He has five cards. There is one number written on each card. Each number is a positive integer.
Limak can discard (throw out) some cards. His goal is to minimize the sum of numbers written on remaining (not discarded) cards.
He is allowed to at most once discard two or three cards wi... | 1 | from collections import Counter
T = map(int, raw_input().split())
t = Counter(T)
total = sum(T)
mn = total
for v in t.keys():
if t[v] >= 2:
mn = min(mn, total - v * min(3, t[v]))
print mn
|
Many years ago Berland was a small country where only n people lived. Each person had some savings: the i-th one had a_i burles.
The government considered a person as wealthy if he had at least x burles. To increase the number of wealthy people Berland decided to carry out several reforms. Each reform looked like that... | 3 | t = int(input())
for test in range(t):
n, x = map(int, input().split())
a = list(map(int, input().split()))
a = sorted(a, reverse = True)
count = 0
s = a[0]
if (s >= x):
count = 1
i = 1
if (count != 0):
while(i < n and s//count >= x):
s += a[i]
cou... |
During the break the schoolchildren, boys and girls, formed a queue of n people in the canteen. Initially the children stood in the order they entered the canteen. However, after a while the boys started feeling awkward for standing in front of the girls in the queue and they started letting the girls move forward each... | 3 | n,t=map(int,input().split())
s=list(input())
#a=[i for i in input()]
for j in range(t):
i=0
while i<len(s)-1:
if s[i+1]=='G' and s[i]=='B':
s[i],s[i+1]=s[i+1],s[i]
i+=2
else:
i+=1
#print(*a,sep='')
print(''.join(s)) |
Little X and Little Z are good friends. They always chat online. But both of them have schedules.
Little Z has fixed schedule. He always online at any moment of time between a1 and b1, between a2 and b2, ..., between ap and bp (all borders inclusive). But the schedule of Little X is quite strange, it depends on the ti... | 3 | p, q, l, r = map(int, input().split())
x_availabilities = [list(map(int, input().split())) for _ in range(p)]
y_availabilities = [list(map(int, input().split())) for _ in range(q)]
def has_shared_moments(x, y):
for i in x:
for j in y:
if i[0] <= j[1] and j[0] <= i[1]:
return Tr... |
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=[]
for i in range(0,len(s),2):
l.append(int(s[i]))
l.sort()
s1=str(l[0])
for i in range(1,len(l)):
s1+='+'
s1+=str(l[i])
print(s1)
|
You finally woke up after this crazy dream and decided to walk around to clear your head. Outside you saw your house's fence β so plain and boring, that you'd like to repaint it.
<image>
You have a fence consisting of n planks, where the i-th plank has the color a_i. You want to repaint the fence in such a way that t... | 3 | import os
import sys
from collections import defaultdict
from io import BytesIO, IOBase
nmbr = lambda: int(input())
lst = lambda: list(map(int, input().split()))
def main():
# n, k = map(int, input().split())
# s = input()
def check(ans):
for i in range(k):
a[ans[i] - 1] = c[i]
... |
Some number of chocolate pieces were prepared for a training camp. The camp had N participants and lasted for D days. The i-th participant (1 \leq i \leq N) ate one chocolate piece on each of the following days in the camp: the 1-st day, the (A_i + 1)-th day, the (2A_i + 1)-th day, and so on. As a result, there were X ... | 3 | n,d,x,*a=map(int,open(0).read().split())
s=[len(range(1,d+1,c)) for c in a]
print(sum(s)+x) |
You've got a 5 Γ 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix:
1.... | 3 | def find_element():
for i in range(5):
row = input()
j = 0
for e in row.split():
if int(e) == 1:
return (i + 1, j + 1)
j += 1
def main():
i , j = find_element()
x = abs(i-3)
y = abs(j - 3)
moves = str(x + y)
print(moves)
main() |
Leo has developed a new programming language C+=. In C+=, integer variables can only be changed with a "+=" operation that adds the right-hand side value to the left-hand side variable. For example, performing "a += b" when a = 2, b = 3 changes the value of a to 5 (the value of b does not change).
In a prototype progr... | 3 | # @oj: codeforces
# @id: hitwanyang
# @email: 296866643@qq.com
# @date: 2020-06-19 18:26
# @url:https://codeforc.es/contest/1368/problem/A
import sys,os
from io import BytesIO, IOBase
import collections,itertools,bisect,heapq,math,string
from decimal import *
# region fastio
BUFSIZE = 8192
BUFSIZE... |
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())
l = list(map(int, input().split()))
k = 1
m = 1
for i in range(1, n):
if l[i] >= l[i-1]:
k += 1
else:
k = 1
if k > m:
m = k
print(m)
|
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... | 1 | t=input()
cnt=0
while t>0:
p,q=map(int,raw_input().split())
if (q-p)>=2:
cnt+=1
t-=1
print cnt
|
A class of students wrote a multiple-choice test.
There are n students in the class. The test had m questions, each of them had 5 possible answers (A, B, C, D or E). There is exactly one correct answer for each question. The correct answer for question i worth a_i points. Incorrect answers are graded with zero points.... | 3 | import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
# import time,random,resource
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
mod2 = 998244353
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI():... |
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
ntc=1
ntc=int(input())
for tc in range(1,ntc+1):
n=int(input())
ans=0
for i in range(n):
ans+=math.sin(i*math.pi/n)
print("%.12f"%ans)
|
Takahashi has a maze, which is a grid of H \times W squares with H horizontal rows and W vertical columns.
The square at the i-th row from the top and the j-th column is a "wall" square if S_{ij} is `#`, and a "road" square if S_{ij} is `.`.
From a road square, you can move to a horizontally or vertically adjacent ro... | 3 | from collections import deque
H, W = map(int, input().split())
s = ["#"*(W+2)] + ["#" + input() + "#" for _ in range(H)] + ["#"*(W+2)]
DH, DW = [0, 0, 1, -1], [1, -1, 0, 0]
def bfs(start):
que = deque([start])
dist = [[-1 for _ in range(W+2)] for _ in range(H+2)]
dist[start[0]][start[1]] = 0
num = 0
while que:
... |
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... | 3 | n = eval(input())
s = list(map(int,input().split()))
count = [0]*5
i=0
while i < n:
if s[i]==1 :
count[1]+=1
elif s[i]==2 :
count[2]+=1
if s[i]==3 :
count[3]+=1
if s[i]==4 :
count[4]+=1
i+=1
taxi = 0
if count[1] <= count[3] :
taxi+=count[3]
if count[2]%2==0:
... |
You are given a string s consisting of lowercase Latin letters "a", "b" and "c" and question marks "?".
Let the number of question marks in the string s be k. Let's replace each question mark with one of the letters "a", "b" and "c". Here we can obtain all 3^{k} possible strings consisting only of letters "a", "b" and... | 3 | n = int(input())
s = input().lower()
dp_a = 0
dp_ab = 0
dp_abc = 0
hatena = 1
mod = 10**9 + 7
for i in range(n):
if s[i]=="a":
dp_a = (dp_a + hatena) % mod
elif s[i]=="b":
dp_ab = (dp_a + dp_ab) % mod
elif s[i]=="c":
dp_abc = (dp_ab + dp_abc) % mod
else:
dp_abc = (dp_a... |
You are the gym teacher in the school.
There are n students in the row. And there are two rivalling students among them. The first one is in position a, the second in position b. Positions are numbered from 1 to n from left to right.
Since they are rivals, you want to maximize the distance between them. If students a... | 3 | for z in range(int(input())):
n,x,a,b=list(map(int,input().split()))
r=abs(a-b)
if r<n-1:
y=n-1-r
if x<=y:
print(r+x)
else:
print(r+y)
else:
print(r)
|
Find the number of integers between 1 and K (inclusive) satisfying the following condition, modulo 10^9 + 7:
* The sum of the digits in base ten is a multiple of D.
Constraints
* All values in input are integers.
* 1 \leq K < 10^{10000}
* 1 \leq D \leq 100
Input
Input is given from Standard Input in the following ... | 3 | import sys
sys.setrecursionlimit(10070)
printn = lambda x: sys.stdout.write(x)
inn = lambda : int(input())
inl = lambda: list(map(int, input().split()))
inm = lambda: map(int, input().split())
DBG = True and False
MOD = 10**9 + 7
def f(s,r):
sz = len(s)
n = int(s[0])
if sz==1:
sum = 0
... |
Mr. Tanaka died leaving the orchard of HW Earl. The orchard is divided into H x W plots in the north, south, east, and west directions, and apples, oysters, and oranges are planted in each plot. Mr. Tanaka left such a will.
Divide the orchard into as many relatives as possible on a parcel basis. However, if the same k... | 3 | import sys
sys.setrecursionlimit(20000)
while True:
H, W = map(int, input().split())
if H == W == 0:
exit()
orchard = [list(input()) for i in range(H)]
def dfs(i, j, fruit):
orchard[i][j] = '.'
move = [[0, 1], [0, -1], [1, 0], [-1, 0]]
for di, dj in move:
i... |
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 | t=int(input())
for i in range(t):
s="YES"
l=[]
n=int(input())
for i in range(0,n):
l1=[]
a,b=input().split()
a=int(a)
b=int(b)
l1.append(a)
l1.append(b)
l.append(l1)
for i in range(0,len(l)):
if(i==0):
if(l[i][0]<l[i][1]):
... |
Every person likes prime numbers. Alice is a person, thus she also shares the love for them. Bob wanted to give her an affectionate gift but couldn't think of anything inventive. Hence, he will be giving her a graph. How original, Bob! Alice will surely be thrilled!
When building the graph, he needs four conditions to... | 3 | data = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 3... |
We have A cards, each of which has an integer 1 written on it. Similarly, we also have B cards with 0s and C cards with -1s.
We will pick up K among these cards. What is the maximum possible sum of the numbers written on the cards chosen?
Constraints
* All values in input are integers.
* 0 \leq A, B, C
* 1 \leq K \l... | 3 | A, B, C, K = map(int, input().split())
ans = min(A, K)
print(ans - max(K - A - B, 0))
|
You are given an array a of n integers and an integer s. It is guaranteed that n is odd.
In one operation you can either increase or decrease any single element by one. Calculate the minimum number of operations required to make the median of the array being equal to s.
The median of the array with odd length is the ... | 3 |
# -*- coding: utf-8 -*-
# @Date : 2018-09-03 08:46:01
# @Author : raj lath (oorja.halt@gmail.com)
# @Link : http://codeforces.com/contest/1037/problem/B
# @Version : 1.0.0
import os
from sys import stdin
max_val=int(10e12)
min_val=int(-10e12)
def read_int() : return int(stdin.readline())
def read_ints() ... |
You have to go on a trip in your car which can hold a limited amount of fuel. You know how many liters of fuel your car uses per hour for certain speeds and you have to find out how far a certain amount of fuel will take you when travelling at the optimal speed.
You will be given a set of speeds, a corresponding set ... | 1 | n=input()
a=map(float,raw_input().split())
b=map(float,raw_input().split())
z=input()
t,m=0,b[0]/a[0]
for x in xrange(1,n):
if b[x]/a[x]<m:
m=b[x]/a[x]
t=x
k,l=str(z/m).split(".")
if len(l)<3:
l=l+"0"*(3-len(l))
print "{0}.{1}".format(k,l[:3]) |
You took a peek on Thanos wearing Infinity Gauntlet. In the Gauntlet there is a place for six Infinity Gems:
* the Power Gem of purple color,
* the Time Gem of green color,
* the Space Gem of blue color,
* the Soul Gem of orange color,
* the Reality Gem of red color,
* the Mind Gem of yellow color.
... | 3 | my_list = {"purple":"Power", "green":"Time", "blue":"Space", "orange":"Soul", "yellow":"Mind", "red":"Reality"}
n = int(input())
for i in range(n):
my_list.pop(input())
print(len(my_list))
for i in my_list:
print(my_list[i]) |
You might have remembered Theatre square from the [problem 1A](https://codeforces.com/problemset/problem/1/A). Now it's finally getting repaved.
The square still has a rectangular shape of n Γ m meters. However, the picture is about to get more complicated now. Let a_{i,j} be the j-th square in the i-th row of the pav... | 3 | """def updateFenTree(i,val):
while(i<=n):
fen[i]+=val
i+=(i&(-i))
def sumFenTree(i):
sum=0
while(i>0):
sum+=fen[i]
i-=(i&(-i))
return sum"""
"""def power(x, y):
res = 1
x=x
while (y > 0):
if ((y & 1) == 1) :
res = (res * x)
... |
You will be given a string S of length 3 representing the weather forecast for three days in the past.
The i-th character (1 \leq i \leq 3) of S represents the forecast for the i-th day. `S`, `C`, and `R` stand for sunny, cloudy, and rainy, respectively.
You will also be given a string T of length 3 representing the ... | 3 | S = input()
T = input()
print([s==t for (s,t) in zip(S,T)].count(True))
|
Mr. Scrooge, a very busy man, decided to count the time he wastes on all sorts of useless stuff to evaluate the lost profit. He has already counted the time he wastes sleeping and eating. And now Mr. Scrooge wants to count the time he has wasted signing papers.
Mr. Scrooge's signature can be represented as a polyline ... | 1 | n,k=map(int,raw_input().split())
xs,ys=map(int,raw_input().split())
sum=0
for i in range(n-1):
x,y=map(int,raw_input().split())
sum+=((x-xs)**2+(y-ys)**2)**0.5
xs=x
ys=y
print "%.09f"%(float(sum)/50.0*k)
|
This is the easy version of the problem. The difference between versions is the constraints on n and a_i. You can make hacks only if all versions of the problem are solved.
First, Aoi came up with the following idea for the competitive programming problem:
Yuzu is a girl who collecting candies. Originally, she has x ... | 3 | import bisect as b
n,p=map(int,input().split())
a=list(map(int,input().split()))
a.sort()
ct=0
ans=[]
for i in range(1,2001):
fg=0
for j in range(0,n):
h=b.bisect(a,i+j,0,n)-j
if h%p == 0:
fg=1
break
if fg==0:
ans.append(i)
print(len(ans))
for i in range(0,len... |
Selection of Participants of an Experiment
Dr. Tsukuba has devised a new method of programming training. In order to evaluate the effectiveness of this method, he plans to carry out a control experiment. Having two students as the participants of the experiment, one of them will be trained under the conventional metho... | 3 | while True:
n = int(input())
if n == 0:
break
a = list(map(int,input().split()))
a.sort()
ans = 10**10
for i in range(n-1):
ans = min(ans, abs(a[i]-a[i+1]))
print(ans)
|
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.
Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divi... | 3 | n=int(input())
print(n//2)
if(n%2==0):
print(str("2"+" ")*(n//2))
else:
print(str("2"+" ")*(n//2-1)+"3")
|
A dragon symbolizes wisdom, power and wealth. On Lunar New Year's Day, people model a dragon with bamboo strips and clothes, raise them with rods, and hold the rods high and low to resemble a flying dragon.
A performer holding the rod low is represented by a 1, while one holding it high is represented by a 2. Thus, th... | 3 | n = int(input())
A = list(map(int, input().split()))
one = [0]
two = [0]
for i in A:
one.append(one[-1])
two.append(two[-1])
if i == 1:
one[-1] += 1
else:
two[-1] += 1
rdp1 = [[1] * n for _ in range(n)]
for l in range(n):
for r in range(l + 1, n):
if A[r] == 2:
rd... |
Kyoya Ootori is selling photobooks of the Ouran High School Host Club. He has 26 photos, labeled "a" to "z", and he has compiled them into a photo booklet with some photos in some order (possibly with some photos being duplicated). A photo booklet can be described as a string of lowercase letters, consisting of the pho... | 3 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 30 15:37:38 2020
@author: PREET MODH
"""
s=list(input())
print(str(26 + len(s)*25)) |
You are given a garland consisting of n lamps. States of the lamps are represented by the string s of length n. The i-th character of the string s_i equals '0' if the i-th lamp is turned off or '1' if the i-th lamp is turned on. You are also given a positive integer k.
In one move, you can choose one lamp and change i... | 3 | import sys
input = lambda: sys.stdin.readline().rstrip("\r\n")
for _ in range(int(input())):
n, k = map(int, input().split())
a = input()
ans, count, total = 0, 0, 0
for i in range(k):
count = 0
for j in range(i, n, k):
if a[j] == "1":
count += 1
... |
Now it's time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. They've been best friends ever since primary school and hopefully, that can somehow help them in teamwork.
For each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing ... | 1 | nZeros, nOnes = map(int, raw_input().split())
size = min(nZeros, nOnes)
remZeros = nZeros - size
remOnes = nOnes - size
if remZeros == 1:
print '01' * size + '0'
elif remOnes == 1:
print '1' + '01' * size
elif remZeros > 1 or remOnes > nZeros + 2:
print -1
else:
nTriplets = min(size, remOnes)
print ... |
You are given two non-negative integers L and R. We will choose two integers i and j such that L \leq i < j \leq R. Find the minimum possible value of (i \times j) \mbox{ mod } 2019.
Constraints
* All values in input are integers.
* 0 \leq L < R \leq 2 \times 10^9
Input
Input is given from Standard Input in the fol... | 3 | l,r=map(int,input().split())
ans=10000
th=l+min(r-l,2020)
for i in range(l,th):
for j in range(i+1,th+1):
ans=min(ans,(i*j)%2019)
print(ans) |
You have a plate and you want to add some gilding to it. The plate is a rectangle that we split into wΓ h cells. There should be k gilded rings, the first one should go along the edge of the plate, the second one β 2 cells away from the edge and so on. Each ring has a width of 1 cell. Formally, the i-th of these rings ... | 3 | f=[int(y) for y in input().split()]
w=f[0]
h=f[1]
k=f[2]
s=0
for i in range(k):
s+=2*w+2*h-4
w-=4
h-=4
print(s) |
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 | n = int(input())
while n>0:
n=n-1
m, k = map(int,input().split())
a = list(map(int,input().split()))
s = set(a)
if len(s)>k:
print(-1)
continue
print(m*k)
for i in range(m):
for b in s:
print(b, end = " ")
for j in range(k-len(s)):
prin... |
Today Patrick waits for a visit from his friend Spongebob. To prepare for the visit, Patrick needs to buy some goodies in two stores located near his house. There is a d1 meter long road between his house and the first shop and a d2 meter long road between his house and the second shop. Also, there is a road of length ... | 1 | d1,d2,d3=map(int,raw_input().split())
print(min((d1+d2+d3),2*(d1+d2),2*(d1+d3),2*(d2+d3))) |
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits.
Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has on... | 3 | n = input()
def chek(s):
c = 0
for i in range(len(s)):
for j in range(len(s)-1-i):
if s[i] == s[i+j+1]:
c += 1
if c == 0:
return True
else:
return False
b = int(n)+1
b = str(b)
while True:
if chek(b) == True:
print(b)
break
b = str(int(b)+1)
|
In the school computer room there are n servers which are responsible for processing several computing tasks. You know the number of scheduled tasks for each server: there are mi tasks assigned to the i-th server.
In order to balance the load for each server, you want to reassign some tasks to make the difference betw... | 1 | n,ans=input(),0
a=sorted(map(int, raw_input().split()))
s=sum(a)
for i in range(n - (s%n)): ans += abs((s/n) - a[i])
for i in range(n - (s%n), n): ans += abs(a[i] - ((s+n-1)/n))
print ans/2
|
You are given an array a_1, a_2, β¦, a_n.
In one operation you can choose two elements a_i and a_j (i β j) and decrease each of them by one.
You need to check whether it is possible to make all the elements equal to zero or not.
Input
The first line contains a single integer n (2 β€ n β€ 10^5) β the size of the array.... | 3 | from bisect import insort,bisect_right,bisect_left
from sys import stdout, stdin, setrecursionlimit
from heapq import heappush, heappop, heapify
from io import BytesIO, IOBase
from collections import *
from itertools import *
from random import *
from string import *
from queue import *
from math import *
from re imp... |
Hands that shed innocent blood!
There are n guilty people in a line, the i-th of them holds a claw with length Li. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the i-th person kills the j-th person if and only if j < i and j β₯ i - Li.
You are g... | 3 | n=int(input())
v=list(map(int,input().split()))
m,c,i = n-v[n-1] ,0 ,n-2
while i>=0:
if(i+1>=m):
c+=1
m=min(m,i+1-v[i])
i-=1
print(n-c)
|
Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.
Gildong lo... | 3 | n,m=map(int,input().split())
import collections
c=collections.Counter()
ans=[]
for _ in range(n):
s=input()
r=s[::-1]
if c[r]!=0:
ans.append(s)
c[r]-=1
else:
c[s]+=1
mid=''
for x in c:
if c[x]!=0:
if all(x[i]==x[-i-1] for i in range(len(x))) and len(mid)<len(x):
... |
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.
The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe... | 3 | string=input("")
string=string.split('+')
string=sorted(string)
string='+'.join(string)
print(string) |
You have n chains, the i-th chain consists of c_i vertices. Vertices in each chain are numbered independently from 1 to c_i along the chain. In other words, the i-th chain is the undirected graph with c_i vertices and (c_i - 1) edges connecting the j-th and the (j + 1)-th vertices for each 1 β€ j < c_i.
Now you decided... | 1 | from sys import stdin
from collections import defaultdict, Counter
import math
I = lambda : map(int,stdin.readline().split())
def testcase():
n = I()[0]
c = I()
a = I()
b = I()
ans = 0
cur = 0;
for i in range(1, n):
if (not cur or a[i] == b[i]):
cur = abs(b[i] - ... |
The School β0 of the capital of Berland has n children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value ti:
* ti = 1, if the i-th child is good at programming,
*... | 3 | n=int(input())
m=list(map(int,input().split()))
a=[]
b=[]
c=[]
for i in range(n):
if m[i]==1:
a.append(i)
if m[i]==2:
b.append(i)
if m[i]==3:
c.append(i)
mn=min(len(a),len(b))
mn=min(mn,len(c))
print(mn)
for i in range(mn):
t=str(a[i]+1)+' '+str(b[i]+1)+' '+str(c[i]+1)
prin... |
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are ... | 3 | n,d = map(int,input().split())
l = list(map(int,input().split()))
l.sort()
count = 0
for i in range(len(l)):
for j in range(len(l)):
if(abs(l[i]-l[j])<=d and i!=j):
count+=1
print(count) |
One tradition of welcoming the New Year is launching fireworks into the sky. Usually a launched firework flies vertically upward for some period of time, then explodes, splitting into several parts flying in different directions. Sometimes those parts also explode after some period of time, splitting into even more par... | 1 | import decimal,math
from collections import *
from fractions import gcd
from bisect import bisect_right,bisect_left
import sys
def fi():
return int(sys.stdin.readline())
def fi2():
return map(int, sys.stdin.readline().split())
def fi3():
return sys.stdin.readline()
def fo(*args):
for s in args:
sys.stdout.w... |
Unfortunately, Vasya can only sum pairs of integers (a, b), such that for any decimal place at least one number has digit 0 in this place. For example, Vasya can sum numbers 505 and 50, but he cannot sum 1 and 4.
Vasya has a set of k distinct non-negative integers d1, d2, ..., dk.
Vasya wants to choose some integers ... | 1 | import sys
best, best_set = 0, set()
def can_add(a, b):
for i in range(3):
if a[i] != '0' and b[i] != '0':
return False
return True
def find_set(val, cur_set, satisfy):
global best_set, best
cur_set.add(val)
next_vals = [x for x in valids[val] if x in satisfy and x != val... |
Let's denote a k-step ladder as the following structure: exactly k + 2 wooden planks, of which
* two planks of length at least k+1 β the base of the ladder;
* k planks of length at least 1 β the steps of the ladder;
Note that neither the base planks, nor the steps planks are required to be equal.
For example... | 3 | t=int(input())
for i in range(t):
n=int(input())
l=list(map(int,input().split()))
m=max(l)
l.remove(m)
m2=max(l)
l.remove(m2)
lee=len(l)
#
#
if m2>lee:
print(lee)
else:
print(m2-1) |
Allen has a LOT of money. He has n dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are 1, 5, 10, 20, 100. What is the minimum number of bills Allen could receive after withdrawing his entire balance?
Input
The first... | 3 | n=int(input())
l=[100,20,10,5,1]
sum=0
while n>0:
for i in l:
a=n//i
n=n%i
sum=sum+a
print(sum)
|
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... | 1 | import os
import sys
from atexit import register
from io import BytesIO
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
sys.stdout = BytesIO()
register(lambda: os.write(1, sys.stdout.getvalue()))
input = lambda: sys.stdin.readline().rstrip('\r\n')
def inp():
return(int(input()))
def inlt():
return(list(... |
These days, Sid and Jake are learning about number theory. They have just visited the zoo and during the visit they have counted(yes, they are superb at counting :) ) the number of animals at the zoo. Now, after visiting the zoo, Sid is saying that f is a factor of the total number of animals at the zoo and Jake is say... | 1 | t=raw_input()
t=int(t)
while t>0:
f,m=raw_input().split()
f=int(f);
m=int(m);
if m%f==0:
print "CORRECT"
else:
print "WRONG"
t=t-1 |
Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. For example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. When a team plays as ... | 3 | n=input()
list_host=[]
list_guest=[]
for i in range(int(n)):
a,b=map(int,input().split())
list_host.append(a)
list_guest.append(b)
counter=0
for i in list_host:
for j in list_guest:
if i==j:
counter+=1
print(counter)
|
Write a program which reads two integers a and b, and calculates the following values:
* a Γ· b: d (in integer)
* remainder of a Γ· b: r (in integer)
* a Γ· b: f (in real number)
Constraints
* 1 β€ a, b β€ 109
Input
Two integers a and b are given in a line.
Output
Print d, r and f separated by a space in a line. For ... | 1 | a,b=map(int,raw_input().split())
print a/b,a%b,"%.6f"%(1.*a/b) |
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 | n = int(input())
for i in range(0,n):
boring = input()
y = int(boring[0])
s = len(boring)
x = int(boring)
tot = 1
for i in range(0, y):
if (i == y - 1):
for k in range(1, s):
tot = tot + k + 1
break
tot = tot + 10
print(tot)
|
You are given a string S consisting of lowercase English letters. We will write down this string, starting a new line after every w letters. Print the string obtained by concatenating the letters at the beginnings of these lines from top to bottom.
Constraints
* 1 \leq w \leq |S| \leq 1000
* S consists of lowercase E... | 3 | print("".join([s for s in input()[::int(input())]])) |
Two players A and B have a list of n integers each. They both want to maximize the subtraction between their score and their opponent's score.
In one turn, a player can either add to his score any element from his list (assuming his list is not empty), the element is removed from the list afterward. Or remove an elem... | 3 | n = int(input())
a = sorted(map(int, input().split()))
b = sorted(map(int, input().split()))
A, B = 0, 0
for i in range(2 * n):
if i % 2 == 0:
if not b or a and a[-1] >= b[-1]:
A += a[-1]
del a[-1]
else:
del b[-1]
else:
if not a or b and b[-1] >= a[-1... |
You are given a string t consisting of n lowercase Latin letters and an integer number k.
Let's define a substring of some string s with indices from l to r as s[l ... r].
Your task is to construct such string s of minimum possible length that there are exactly k positions i such that s[i ... i + n - 1] = t. In other... | 3 | n,k = map(int,input().split())
s = input()
p=-1
for i in range(1,n):
if s[:n-i]==s[i:]:
p=i
break
t=""
if p!=-1:
t = s[n-i:]*(k-1)
t = s+t
else:
t = s*k
print(t)
|
You are given an array a consisting of n integers. You have to find the length of the smallest (shortest) prefix of elements you need to erase from a to make it a good array. Recall that the prefix of the array a=[a_1, a_2, ..., a_n] is a subarray consisting several first elements: the prefix of the array a of length k... | 3 | def check(a, start):
newArray = []
l, r = start, len(a) - 1
while l <= r:
minVal = min(a[l], a[r])
if len(newArray) > 0 and minVal < newArray[-1]:
return False
newArray.append(minVal)
if minVal == a[l]:
l += 1
else:
r -= 1
retur... |
Let's consider all integers in the range from 1 to n (inclusive).
Among all pairs of distinct integers in this range, find the maximum possible greatest common divisor of integers in pair. Formally, find the maximum value of gcd(a, b), where 1 β€ a < b β€ n.
The greatest common divisor, gcd(a, b), of two positive integ... | 3 | def main():
for __ in [0]*int(input()):
n = int(input())
print(n//2)
if __name__ == '__main__':
main()
|
A number is ternary if it contains only digits 0, 1 and 2. For example, the following numbers are ternary: 1022, 11, 21, 2002.
You are given a long ternary number x. The first (leftmost) digit of x is guaranteed to be 2, the other digits of x can be 0, 1 or 2.
Let's define the ternary XOR operation β of two ternary n... | 3 | t = int(input())
for _ in range(t):
n = int(input())
x = input()
a = "1"
b = "1"
poss = False
for i in range(1,n):
if x[i] == '1':
if poss:
a+='0'
b+='1'
else:
a+='1'
b+='0'
poss = True
elif x[i] == '2':
if poss:
a+='0'
b+= '2'
else:
a+='1'
b+='1'
elif x[i] =... |
You are given k sequences of integers. The length of the i-th sequence equals to n_i.
You have to choose exactly two sequences i and j (i β j) such that you can remove exactly one element in each of them in such a way that the sum of the changed sequence i (its length will be equal to n_i - 1) equals to the sum of the... | 3 | d = {}
sp = {}
ki = int(input())
spk = []
for k in range(ki):
input()
di = list(map(int, input().split()))
sdi = set(di)
sum_di = sum(di)
sp[k] = [sum_di - sek for sek in sdi]
d[k] = di
spk.extend(sp[k])
from collections import Counter
spkc = Counter(spk).most_common(1)[0]
if spkc[1] == 1:
... |
After celebrating the midcourse the students of one of the faculties of the Berland State University decided to conduct a vote for the best photo. They published the photos in the social network and agreed on the rules to choose a winner: the photo which gets most likes wins. If multiple photoes get most likes, the win... | 3 | def main():
n = int(input())
our = [[0, 0] for i in range(1000001)]
ask = list(map(int, input().split()))
for i in range(len(ask)):
e = ask[i]
our[e][0] -= 1
our[e][1] = i
print(our.index(min(our)))
main() |
A progress bar is an element of graphical interface that displays the progress of a process for this very moment before it is completed. Let's take a look at the following form of such a bar.
A bar is represented as n squares, located in line. To add clarity, let's number them with positive integers from 1 to n from t... | 3 | def process(n,k,t):
for i in range(1,n+1):
for l in range(0,k+1):
b1,b2 = ((i-1)*k + l)/(n*k),((i-1)*k + 1 + l)/(n*k)
if(b1<=t/100<b2):
for j in range(1,i):
print(k,end= ' ')
print(l,end = ' ')
for j in range(i+1,n+1... |
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 | import math
x, y = [int(a) for a in input().split()]
ans = math.floor((x*y)/2)
print(ans) |
When preparing a tournament, Codeforces coordinators try treir best to make the first problem as easy as possible. This time the coordinator had chosen some problem and asked n people about their opinions. Each person answered whether this problem is easy or hard.
If at least one of these n people has answered that th... | 3 | n = int(input())
verd = [i for i in input().split()]
lst = [i for i in str(verd)]
if lst.count("1") >= 1:
print("HARD")
else:
print("EASY") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.