problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
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 | from math import ceil
for _ in range(int(input())):
a,b = map(int,input().split())
print(ceil((max(a,b)-min(a,b))/10)) |
Alexandra has an even-length array a, consisting of 0s and 1s. The elements of the array are enumerated from 1 to n. She wants to remove at most n/2 elements (where n β length of array) in the way that alternating sum of the array will be equal 0 (i.e. a_1 - a_2 + a_3 - a_4 + ... = 0). In other words, Alexandra wants s... | 3 | from sys import stdin, stdout
import math,sys,heapq
from itertools import permutations, combinations
from collections import defaultdict,deque,OrderedDict
from os import path
import random
import bisect as bi
def yes():print('YES')
def no():print('NO')
if (path.exists('input.txt')):
#------------------Sublime-----... |
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." β an excerpt from contest rules.
A total of n participants took part in the contest (n β₯ k), and you already know their scores. Calculate how many ... | 3 | n,k = map(int,input().split())
a=list(map(int,input().split()))
o=0
count=0
for i in range(k):
o=a[i]
for i in a:
if i>=o and i>0:
count+=1
print(count)
|
There were n groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team.
The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams... | 3 | n=int(input())
arr=[int(x) for x in input().split()]
count_1=arr.count(1)
count_2=arr.count(2)
if count_1>count_2:
ans=count_2+(count_1-count_2)//3
print(ans)
else:
print(count_1) |
Takahashi has N balls. Initially, an integer A_i is written on the i-th ball.
He would like to rewrite the integer on some balls so that there are at most K different integers written on the N balls.
Find the minimum number of balls that Takahashi needs to rewrite the integers on them.
Constraints
* 1 \leq K \leq N... | 3 | from collections import Counter
n, k = list(map(int, input().rstrip().split()))
lst = list(map(int, input().rstrip().split()))
cnt = sorted(Counter(lst).values(), reverse=True)
print(sum(cnt[k:])) |
You have n coins, each of the same value of 1.
Distribute them into packets such that any amount x (1 β€ x β€ n) can be formed using some (possibly one or all) number of these packets.
Each packet may only be used entirely or not used at all. No packet may be used more than once in the formation of the single x, howeve... | 3 | n = int(input())
binary = str(bin(n))
print(len(binary) - 2)
|
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 | # Whatever the mind of man can conceive and believe, it can achieve. Napoleon Hill
# by : Blue Edge - Create some chaos
for _ in range(int(input())):
s=input()
n=len(s)
i=0;a=[]
while i<n:
# print(s[i],end="")
if s[i:i+5]=="twone":
a+=i+3,
i+=5
elif s[i:i... |
In this problem, we use the 24-hour clock.
Takahashi gets up exactly at the time H_1 : M_1 and goes to bed exactly at the time H_2 : M_2. (See Sample Inputs below for clarity.) He has decided to study for K consecutive minutes while he is up. What is the length of the period in which he can start studying?
Constraint... | 3 | a,b,c,d,e=map(int,input().split())
print(60*(c-a)+(d-b)-e) |
Twilight Sparkle once got a crystal from the Crystal Mine. A crystal of size n (n is odd; n > 1) is an n Γ n matrix with a diamond inscribed into it.
You are given an odd integer n. You need to draw a crystal of size n. The diamond cells of the matrix should be represented by character "D". All other cells of the matr... | 3 | a = int(input())
for j in range(1, a+1, 2):
b = 'D' * j
print(b.center(a, '*'))
for k in range(a-2, 0, -2):
b = 'D' * k
print(b.center(a, '*')) |
Let's arrange a deck of cards. Your task is to sort totally n cards. A card consists of a part of a suit (S, H, C or D) and an number. Write a program which sorts such cards based on the following pseudocode:
Partition(A, p, r)
1 x = A[r]
2 i = p-1
3 for j = p to r-1
4 do if A[j] <= x
5 then i = i+1
6 ... | 3 | def partition(A, p, r):
x = A[r][1]
i = p-1
for j in range(p, r):
if A[j][1] <= x:
i = i + 1
(A[i], A[j]) = (A[j], A[i])
(A[i+1], A[r]) = (A[r], A[i+1])
return i+1
def quicksort(A, p, r):
if p < r:
q = partition(A, p, r)
quicksort(A, p, q-1)... |
Sereja and Dima play a game. The rules of the game are very simple. The players have n cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The ... | 3 | n=int(input())
l=list(map(int,input().split()))
i=0
j=n-1
s,d,f=0,0,0
while(i<=j):
if(i==j):
if(f==0):
s+=l[i]
else:
d+=l[i]
i+=1
elif(l[i]>l[j]):
if(f==0):
s+=l[i]
f=1
else:
d+=l[i]
f=0
i+=1
... |
Kawashiro Nitori is a girl who loves competitive programming.
One day she found a string and an integer. As an advanced problem setter, she quickly thought of a problem.
Given a string s and a parameter k, you need to check if there exist k+1 non-empty strings a_1,a_2...,a_{k+1}, such that $$$s=a_1+a_2+β¦ +a_k+a_{k+1}... | 3 | for _ in range(int(input())):
n, k = map(int, input().split())
s=input()
if s[:k]==s[::-1][:k] and n>2*k:
print("YES")
else:
print("No")
|
Karl likes Codeforces and subsequences. He wants to find a string of lowercase English letters that contains at least k subsequences codeforces. Out of all possible strings, Karl wants to find a shortest one.
Formally, a codeforces subsequence of a string s is a subset of ten characters of s that read codeforces from ... | 3 | k=int(input())
x=[1]*10
p=1
s='codeforces'
while(p<k):
for i in range(len(x)):
x[i]+=1
p=p//(x[i]-1)
p=p*x[i]
if p>=k:
break
t=''
for i in range(len(x)):
t+=s[i]*x[i]
print(t) |
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr... | 1 | a=raw_input()
b=raw_input()
a=a.lower()
b=b.lower()
l=len(a)
f=0
for i in range(l):
if a[i]<b[i]:
print '-1'
f=1
break
elif a[i]>b[i]:
print '1'
f=1
break
if f==0:
print '0' |
Kirito is stuck on a level of the MMORPG he is playing now. To move on in the game, he's got to defeat all n dragons that live on this level. Kirito and the dragons have strength, which is represented by an integer. In the duel between two opponents the duel's outcome is determined by their strength. Initially, Kirito'... | 3 | import sys
def input(): return sys.stdin.readline().strip()
def iinput(): return int(input())
def rinput(): return map(int, sys.stdin.readline().strip().split())
def get_list(): return list(map(int, sys.stdin.readline().strip().split()))
s,n=rinput()
a=[]
count=0
for i in range(n):
a.append(list(map(int... |
You're given an array a of length n. You can perform the following operation on it as many times as you want:
* Pick two integers i and j (1 β€ i,j β€ n) such that a_i+a_j is odd, then swap a_i and a_j.
What is lexicographically the smallest array you can obtain?
An array x is [lexicographically smaller](https://... | 3 | n = int(input())
y = list(map(int,input().split()))
b = 0
c = 0
for x in y:
if x%2 == 0:
b += 1
else:
c += 1
if b == len(y):
for x in y:
print(x,end=" ")
elif c == len(y):
for x in y:
print(x,end=" ")
else:
y.sort()
for x in y:
print(x,end=" ") |
You have a digit sequence S of length 4. You are wondering which of the following formats S is in:
* YYMM format: the last two digits of the year and the two-digit representation of the month (example: `01` for January), concatenated in this order
* MMYY format: the two-digit representation of the month and the last t... | 3 | s = input()
l = 1 <= int(s[:2]) <= 12
r = 1 <= int(s[2:]) <= 12
if l and r:
print("AMBIGUOUS")
elif l:
print('MMYY')
elif r:
print('YYMM')
else:
print('NA')
|
The restaurant AtCoder serves the following five dishes:
* ABC Don (rice bowl): takes A minutes to serve.
* ARC Curry: takes B minutes to serve.
* AGC Pasta: takes C minutes to serve.
* APC Ramen: takes D minutes to serve.
* ATC Hanbagu (hamburger patty): takes E minutes to serve.
Here, the time to serve a dish is ... | 3 | x = [int(input()) for i in range(5)]
n,a = 10,0
for i in x:
if i%10: n,a = min(i%10,n),a+i-i%10+10
else: a+=i
print(a+n-10) |
You are given two squares, one with sides parallel to the coordinate axes, and another one with sides at 45 degrees to the coordinate axes. Find whether the two squares intersect.
The interior of the square is considered to be part of the square, i.e. if one square is completely inside another, they intersect. If the ... | 3 | # -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
... |
Little girl Alyona is in a shop to buy some copybooks for school. She study four subjects so she wants to have equal number of copybooks for each of the subjects. There are three types of copybook's packs in the shop: it is possible to buy one copybook for a rubles, a pack of two copybooks for b rubles, and a pack of t... | 1 | n,a,b,c=map(int,raw_input().split())
k=4-n%4
k%=4
ans=10**20
for i in range(4):
for j in range(4):
for l in range(4):
if(i+2*j+3*l)%4==k:
ans=min(ans,i*a+j*b+l*c)
print ans |
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them.
Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain nu... | 3 | inp = input()
song = inp.split("WUB")
song = [s for s in song if s not in ('')]
print(' '.join(song))
|
Takahashi lives in another world. There are slimes (creatures) of 10000 colors in this world. Let us call these colors Color 1, 2, ..., 10000.
Takahashi has N slimes, and they are standing in a row from left to right. The color of the i-th slime from the left is a_i. If two slimes of the same color are adjacent, they ... | 3 | from itertools import groupby
N = int(input())
a = list(map(int, input().split()))
n = sum(len(list(s))//2 for _,s in groupby(a))
print(n)
|
Find out if it is possible to partition the first n positive integers into two non-empty disjoint sets S_1 and S_2 such that:
gcd(sum(S_1), sum(S_2)) > 1
Here sum(S) denotes the sum of all elements present in set S and gcd means the[greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor).
Ev... | 3 | """#N=int(input())
n,k=map(int,input().split())
s=input()
L=[0]*26
#s=[int(x) for x in input().split()]
for j in range(0,len(s)):
L[ord(s[j])-65]=L[ord(s[j])-65]+1
ans=1000000007
for j in range(0,k):
ans=min(ans,L[j])
ans=k*ans
print(ans)"""
import math
pre=[]
for i in range(0,45010):
pre.append(((i*(i+1))/... |
You are given an integer N.
Find a triple of positive integers h, n and w such that 4/N = 1/h + 1/n + 1/w.
If there are multiple solutions, any of them will be accepted.
Constraints
* It is guaranteed that, for the given integer N, there exists a solution such that h,n,w \leq 3500.
Inputs
Input is given from Stan... | 3 | N = int(input())
if N % 2 == 0:
print(N//2,N,N)
else:
for h in range(2,3501,2):
for n in range(2,3501,2):
if 4*h*n-n*N-h*N != 0:
w = h*n*N/(4*h*n-n*N-h*N)
if w > 0 and w.is_integer():
print(h,n,int(w))
exit()
|
While sailing on a boat, Inessa noticed a beautiful water lily flower above the lake's surface. She came closer and it turned out that the lily was exactly H centimeters above the water surface. Inessa grabbed the flower and sailed the distance of L centimeters. Exactly at this point the flower touched the water surfac... | 3 | # Don't brood. Get on with living and loving. You don't have forever. Leo Buscaglia
# by : Blue Edge - Create some chaos
h,l=map(int,input().split())
d=l*l - h*h
d=d/h
d=d/2
print(d)
|
There are N boxes arranged in a row from left to right. The i-th box from the left contains A_i candies.
You will take out the candies from some consecutive boxes and distribute them evenly to M children.
Such being the case, find the number of the pairs (l, r) that satisfy the following:
* l and r are both integers... | 3 | n,m=map(int,input().split())
a=[0]+list(map(int,input().split()))
a[0]%=m
for i in range(1,n+1):
a[i]+=a[i-1]
a[i]%=m
a.sort()
p=0
s=0
for i in range(1,n+1):
if a[i]-a[p]:
l=a[i]
p=i-p
s+=p*(p-1)
p=i
p=n-p
s+=p*(p+1)
print(int(s/2)) |
You are given an array a consisting of n integers numbered from 1 to n.
Let's define the k-amazing number of the array as the minimum number that occurs in all of the subsegments of the array having length k (recall that a subsegment of a of length k is a contiguous part of a containing exactly k elements). If there i... | 3 | t = int(input())
for z in range(t):
n = int(input())
a = list(map(int, input().split()))
a.insert(0, -1)
rast = dict()
last = dict()
for i in range(1, n + 1):
x = a[i]
ll = last.get(x, -1)
if ll == -1:
last[x] = i
rast[x] = i
else:
... |
One day Vasya heard a story: "In the city of High Bertown a bus number 62 left from the bus station. It had n grown-ups and m kids..."
The latter events happen to be of no importance to us. Vasya is an accountant and he loves counting money. So he wondered what maximum and minimum sum of money these passengers could h... | 1 | #http://codeforces.com pypy 2.7.10 (2.6.1)
a,b=[int(a) for a in raw_input().split()]
if a<1 and b>0:print'Impossible';exit()
c=a+b-1
if b==0:c=a
print max(a,b),c |
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 | n = list(input().split("+"))
n.sort()
print("+".join(n))
|
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
You have to answer t independent test cases.
Input
The first line of the input co... | 3 | t= int(input())
for i in range(t):
a,b = map(int, input().split(" "))
c = a%b
if c==0:
print(c)
else:
print(b-c) |
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 | import fpformat
a,b= map(int,raw_input().split())
d = a/b
r = a%b
f = a/float(b)
print d,r,fpformat.fix(f, 8) |
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them.
Input
The first line contains integ... | 3 | n = int(input())
str =[]
str =[char for char in input()]
count = 0
for i in range(len(str)-1):
if str[i] == str[i+1]:
count += 1
print(count) |
Petya is having a party soon, and he has decided to invite his n friends.
He wants to make invitations in the form of origami. For each invitation, he needs two red sheets, five green sheets, and eight blue sheets. The store sells an infinite number of notebooks of each color, but each notebook consists of only one co... | 3 | import sys
list1 = [2, 5, 8]
for line in sys.stdin:
n, k = map(int, line.split())
books = 0
for x in range(len(list1)):
list1[x] *= n
books += ((list1[x] + k - 1) // k)
print(books) |
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word s. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if... | 3 | # --------------------------------
def index(s, c):
i = 0
s = list(s)
while i < len(s):
if s[i] == c:
return (i)
i += 1
return (999)
# --------------------------------
def ko(index_h, index_e, index_l, index_o, s):
s = list(s)
i = 0
while i < len(s):
if s[... |
The police department of your city has just started its journey. Initially, they donβt have any manpower. So, they started hiring new recruits in groups.
Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime.
If there is no police offi... | 3 | n= int(input())
mang = [int(nhap) for nhap in input().split()]
nums = 0
untreated = 0
for i in mang:
if i >0:
nums += i
else:
if(nums ==0):
untreated +=1
elif(nums>0):
nums = nums -1
print(untreated) |
A complete binary tree is a binary tree in which every internal node has two children and all leaves have the same depth. A binary tree in which if last level is not completely filled but all nodes (leaves) are pushed across to the left, is also (nearly) a complete binary tree.
A binary heap data structure is an array... | 3 | def printHeap(H,Q,n):
if H+1 == n:
return
print("node",n,end=": ")
print("key =",Q[n],end=", ")
print("parent key =",Q[int(n/2)],end=", ") if 1<n else None
print("left key =",Q[2*n],end=", ") if 2*n<=H else None
print("right key =",Q[2*n+1],end=", ") if 2*n+1<=H else None
print()
... |
Vus the Cossack has a simple graph with n vertices and m edges. Let d_i be a degree of the i-th vertex. Recall that a degree of the i-th vertex is the number of conected edges to the i-th vertex.
He needs to remain not more than β (n+m)/(2) β edges. Let f_i be the degree of the i-th vertex after removing. He needs to ... | 1 | def main():
inp = readnumbers()
ii = 0
n = inp[ii]
ii += 1
m = inp[ii]
ii += 1
coupl = [[] for _ in range(n)]
nei_id = [[] for _ in range(n)]
for _ in range(m):
u = inp[ii] - 1
ii += 1
v = inp[ii] - 1
ii += 1
nei_id[v].append(len(coupl[u]))
... |
In the city of Saint Petersburg, a day lasts for 2^{100} minutes. From the main station of Saint Petersburg, a train departs after 1 minute, 4 minutes, 16 minutes, and so on; in other words, the train departs at time 4^k for each integer k β₯ 0. Team BowWow has arrived at the station at the time s and it is trying to co... | 3 | n=int(input(),2)
x=1
z=0
while(x<n):
x=x*4
z=z+1
print(z)
|
You are given a string s=s_1s_2... s_n of length n, which only contains digits 1, 2, ..., 9.
A substring s[l ... r] of s is a string s_l s_{l + 1} s_{l + 2} β¦ s_r. A substring s[l ... r] of s is called even if the number represented by it is even.
Find the number of even substrings of s. Note, that even if some subs... | 3 | N = int(input())
s = input()
cnt = 0
for i in range(N):
if int(s[i])%2==0:
cnt+=(i+1)
print(cnt)
|
Igor the analyst has adopted n little bunnies. As we all know, bunnies love carrots. Thus, Igor has bought a carrot to be shared between his bunnies. Igor wants to treat all the bunnies equally, and thus he wants to cut the carrot into n pieces of equal area.
Formally, the carrot can be viewed as an isosceles triangl... | 3 | from math import sqrt
n,h=[int(element) for element in input().split(' ')]
answer=[]
for i in range(1,n):
answer.append(str(h*sqrt(i/n)))
print(('\n').join(answer)) |
Mister B once received a gift: it was a book about aliens, which he started read immediately. This book had c pages.
At first day Mister B read v0 pages, but after that he started to speed up. Every day, starting from the second, he read a pages more than on the previous day (at first day he read v0 pages, at second β... | 3 | def list_input():
return list(map(int,input().split()))
def map_input():
return map(int,input().split())
def map_string():
return input().split()
c,v0,v1,a,l = map_input()
cur = 0
cnt = 0
while cur < c:
if cnt != 0:
cur += min(v1,v0+cnt*a)-l
else:
cur += min(v1,v0+cnt*a)
cnt... |
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.
Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, seco... | 3 | def main():
n = int(input())
ans = 'I '
for i in range(n):
if i %2 == 0:
ans += 'hate '
else:
ans += 'love '
if i < n-1:
ans += 'that I '
print(ans + 'it')
main() |
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... | 1 | blah=raw_input()
new=""
upper="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
lower="abcdefghijklmnopqrstuvwxyz"
vowels="aeiouyAEIOUY"
for char in blah:
if char not in vowels:
if char in lower:
new+="."
new+=char
elif char in upper:
new+="."
bla=upper.index(char)
... |
A new airplane SuperPuperJet has an infinite number of rows, numbered with positive integers starting with 1 from cockpit to tail. There are six seats in each row, denoted with letters from 'a' to 'f'. Seats 'a', 'b' and 'c' are located to the left of an aisle (if one looks in the direction of the cockpit), while seats... | 3 | ns = input()
n = int(ns[:len(ns) - 1])
s = ns[-1]
t = 0
n -= 1
t = (n // 4) * 16 + n % 2 * 7
for i in "fedabc":
t += 1
if i == s:
break
print(t) |
A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters + and 1 into this sequence. For example, sequences (())(), () and (()(())) are regular, while )(, (() and (()))( are not. Let's call a regular bracket sequence "RBS".
You are given a sequence s of n c... | 1 | t=int(raw_input())
for _ in range(t):
s=list(raw_input())
n=len(s)
if n%2!=0 or s[0]==')' or s[-1]=='(':
print("NO")
else:
print('YES')
|
There was an electronic store heist last night.
All keyboards which were in the store yesterday were numbered in ascending order from some integer number x. For example, if x = 4 and there were 3 keyboards in the store, then the devices had indices 4, 5 and 6, and if x = 10 and there were 7 of them then the keyboards ... | 3 | n = int(input()); Min = float('inf'); Max = 0
for i in input().split():
Max = max(Max, int(i))
Min = min(Min, int(i))
print(Max - Min + 1 - n) |
You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes.
You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consi... | 3 | I = lambda: input().split()
_, m = map(int, I())
d = {}
for _ in range(m):
a, b = I()
if len(a) > len(b):
d[a] = b
for c in I():
print(d[c] if c in d else c, end=' ') |
There is a fence in front of Polycarpus's home. The fence consists of n planks of the same width which go one after another from left to right. The height of the i-th plank is hi meters, distinct planks can have distinct heights.
<image> Fence for n = 7 and h = [1, 2, 6, 1, 1, 7, 1]
Polycarpus has bought a posh piano... | 3 | n, k = input().split()
n = int(n)
k = int(k)
a = [int(i) for i in input().split()]
sm = 10000000000
b = 0
s = 0
for j in range(k) :
s += a[j]
if s < sm :
sm = s
b = 0
for i in range(1,n-k + 1) :
s += a[i+k-1]
s -= a[i-1]
if s < sm :
sm = s
b = i
if s == k :
break
prin... |
There are n piranhas with sizes a_1, a_2, β¦, a_n in the aquarium. Piranhas are numbered from left to right in order they live in the aquarium.
Scientists of the Berland State University want to find if there is dominant piranha in the aquarium. The piranha is called dominant if it can eat all the other piranhas in the... | 3 | for _ in range(int(input())):
l = int(input())
ar = list(map(int, input().split()))
mx = max(ar)
id = ar.index(mx)
if (ar.count(mx) == len(ar)):
print(-1)
else:
if (id == 0):
while (ar[id] == ar[id + 1]):
id += 1
print(id + 1)
|
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them.
Input
The first line contains integ... | 3 | n = int(input())
s = input()
l = []
for a in s:
l.append(a)
poppable = []
for i in range(len(l)):
if i == 0 and i + 1 < len(l):
if l[i] == l[i + 1]:
poppable.append(l[i + 1])
else:
if i - 1 >= 0 and i + 1 < len(l):
if l[i - 1] == l[i] and l[i] == l[i + 1]:
... |
Petya has recently learned data structure named "Binary heap".
The heap he is now operating with allows the following operations:
* put the given number into the heap;
* get the value of the minimum element in the heap;
* extract the minimum element from the heap;
Thus, at any moment of time the heap con... | 3 |
import sys,bisect
from sys import stdin,stdout
from bisect import bisect_left,bisect_right,bisect,insort,insort_left,insort_right
from math import gcd,ceil,floor,sqrt
from collections import Counter,defaultdict,deque,OrderedDict
from queue import Queue,PriorityQueue
from string import ascii_lowercase
from heap... |
Bishwock is a chess figure that consists of three squares resembling an "L-bar". This figure can be rotated by 90, 180 and 270 degrees so it can have four possible states:
XX XX .X X.
X. .X XX XX
Bishwocks don't attack any squares and can even occupy on the adjacent square... | 1 | import sys, math
from sys import stdin, stdout
rem = 10 ** 9 + 7
sys.setrecursionlimit(10 ** 6)
take = lambda: map(int, stdin.readline().split())
a=list(raw_input())
b=list(raw_input())
n=len(a)
#print a,b
arr=[0 for i in range(n)]
for i in range(n):
arr[i]=[a[i],b[i]].count('0')
ans=0
#print arr
for i in rang... |
Takahashi has a strong stomach. He never gets a stomachache from eating something whose "best-by" date is at most X days earlier. He gets a stomachache if the "best-by" date of the food is X+1 or more days earlier, though.
Other than that, he finds the food delicious if he eats it not later than the "best-by" date. Ot... | 3 | x,a,b=map(int,input().split())
if x+a<b:print("dangerous")
elif a<b:print("safe")
else:print("delicious") |
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 | A = input()
n = int(A)
x = 0
for i in A:
if i != '4' and i !='7':
x =0
break
x = 1
if n%4 == 0:
x = 1
if n%7 == 0:
x =1
if n == 799 or n == 94 or n == 141:
x = 1
if x == 1:
print('YES')
else:
print('NO')
|
Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited n his friends there.
If t... | 3 | n = int(input())
a = [ int(s) for s in input().split()]
b = [1] * (n)
for i in range(n):
b[a[i]-1] = i + 1
b = list(map(str, b))
print(' '.join(b)) |
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 | a=int(input())
for i in range(a):
b,c=map(int,input().split())
dist=abs(b-c)
if b==c:
print('0')
else:
print((dist+9)//10)
|
You are given an array of integers a_1,a_2,β¦,a_n. Find the maximum possible value of a_ia_ja_ka_la_t among all five indices (i, j, k, l, t) (i<j<k<l<t).
Input
The input consists of multiple test cases. The first line contains an integer t (1β€ tβ€ 2 β
10^4) β the number of test cases. The description of the test cases ... | 3 | import sys
import itertools
import math
input = sys.stdin.readline
I = lambda : list(map(int,input().split()))
m,=I()
while(m):
m-=1
n,=I()
arr=sorted(I())
ans=-math.inf
if n>10:
arr=arr[:5]+arr[-5:]
n=len(arr)
for i in range(n):
for j in range(i+1,n):
for k in... |
Nothing is eternal in the world, Kostya understood it on the 7-th of January when he saw partially dead four-color garland.
Now he has a goal to replace dead light bulbs, however he doesn't know how many light bulbs for each color are required. It is guaranteed that for each of four colors at least one light is workin... | 3 | g = list(input())
r = [0, 0, 0, 0]
c = {'R':0, 'G':0, 'B':0, 'Y':0}
l = len(g)
for i in range(0, l, 4):
for j in range(4):
if j+i < l:
if g[i+j] == '!':
r[j] += 1
else:
c[g[i+j]] = j
print(r[c['R']], r[c['B']],r[c['Y']],r[c['G']])
|
New Year is coming and you are excited to know how many minutes remain before the New Year. You know that currently the clock shows h hours and m minutes, where 0 β€ hh < 24 and 0 β€ mm < 60. We use 24-hour time format!
Your task is to find the number of minutes before the New Year. You know that New Year comes when the... | 3 | t = int(input())
a = []
full_day = 24 * 60
for _ in range(t):
h, m = map(int, input().split())
hour_to_min = h * 60
sum_of_min_went = hour_to_min + m
res = full_day - sum_of_min_went
a.append(res)
print("\n".join(map(str, a))) |
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them.
Input
The first line contains integ... | 3 | i = int(input())
A=input()
count=0
for i in range(1,len(A)):
if(A[i]==A[i-1]):
count+=1
print(count) |
There are four points: $A(x_1, y_1)$, $B(x_2, y_2)$, $C(x_3, y_3)$, and $D(x_4, y_4)$. Write a program which determines whether the line $AB$ and the line $CD$ are parallel. If those two lines are parallel, your program should prints "YES" and if not prints "NO".
Input
Input consists of several datasets. In the fir... | 1 | #! -*- coding: utf-8-unix -*-
import math
if __name__=='__main__':
# lines = [x.strip() for x in sys.stdin.readlines() if x != '' and x != '\n']
# n = int(lines[0])
n = int(raw_input())
for i in xrange(n):
# x1, y1, x2, y2, x3, y3, x4, y4 = map(float, lines[i+1].split(' '))
x1, y1, x2, y2, x3, y3, x4, ... |
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 | for _tc in range(int(input())):
i = int(input())
print(i // 2) |
Tattah is asleep if and only if Tattah is attending a lecture. This is a well-known formula among Tattah's colleagues.
On a Wednesday afternoon, Tattah was attending Professor HH's lecture. At 12:21, right before falling asleep, he was staring at the digital watch around Saher's wrist. He noticed that the digits on th... | 3 | def to_string(n):
if n<10:
return "0"+str(n)
return str(n)
def next(h,m):
m+=1
if m==60:
m=0
h+=1
if h==24:
h=0
return h,m
h,m=map(int,input().split(':'))
h,m=next(h,m)
while to_string(h)!=to_string(m)[::-1]:
h,m=next(h,m)
print("%s:%s"%(to_string(h),to_string(m)))
|
Given is a number sequence A of length N.
Find the number of integers i \left(1 \leq i \leq N\right) with the following property:
* For every integer j \left(1 \leq j \leq N\right) such that i \neq j , A_j does not divide A_i.
Constraints
* All values in input are integers.
* 1 \leq N \leq 2 \times 10^5
* 1 \leq A_... | 3 | n = int(input())
a = [int(i) for i in input().split()]
max_a = max(a)
cnt_d = [0] * (max_a + 1)
for ai in a:
for multi in range(ai, max_a + 1, ai):
cnt_d[multi] += 1
print(sum(cnt_d[ai] == 1 for ai in a)) |
You are given a matrix with n rows (numbered from 1 to n) and m columns (numbered from 1 to m). A number a_{i, j} is written in the cell belonging to the i-th row and the j-th column, each number is either 0 or 1.
A chip is initially in the cell (1, 1), and it will be moved to the cell (n, m). During each move, it eit... | 3 | I=lambda:map(int,input().split())
t,=I()
for _ in[0]*t:
n,m=I()
a=0
g={}
for i in range(n):
s=[*I()]
for j in range(m):
if not g.get(i+j):g[i+j]=[0,0]
g[i+j][s[j]]+=1
k=n+m-1
for i in range(k):
if i!=k-i-1:a+=min(g[i][0]+g[k-i-1][0],g[i][1]+g[k-i-1... |
Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to th... | 3 | a=list(map(int,input().split(" ")))
if(len(set(a))==4):
print(0)
elif(len(set(a))==3):
print(1)
elif(len(set(a))==2):
print(2)
else:
print(3)
|
A permutation is a sequence of n integers from 1 to n, in which all the numbers occur exactly once. For example, [1], [3, 5, 2, 1, 4], [1, 3, 2] are permutations, and [2, 3, 2], [4, 3, 1], [0] are not.
Polycarp was given four integers n, l, r (1 β€ l β€ r β€ n) and s (1 β€ s β€ (n (n+1))/(2)) and asked to find a permutatio... | 3 | import sys
import math
import bisect
import functools
from functools import lru_cache
from sys import stdin, stdout
from math import gcd, floor, sqrt, log, ceil
from heapq import heappush, heappop, heapify
from collections import defaultdict as dd
from collections import Counter as cc
from bisect import bisect_left as ... |
We've got no test cases. A big olympiad is coming up. But the problemsetters' number one priority should be adding another problem to the round.
The diameter of a multiset of points on the line is the largest distance between two points from this set. For example, the diameter of the multiset {1, 3, 2, 1} is 2.
Diame... | 3 | n, d = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
minCost = len(a)
for i in range(len(a)-1):
for j in range(i+1, len(a)):
if a[j]-a[i] <= d:
cost = i+(len(a)-j-1)
minCost = min(cost, minCost)
print (min(minCost, len(a)-1) if len(a) > 1 else 0)
|
There are N bags of biscuits. The i-th bag contains A_i biscuits.
Takaki will select some of these bags and eat all of the biscuits inside. Here, it is also possible to select all or none of the bags.
He would like to select bags so that the total number of biscuits inside is congruent to P modulo 2. How many such wa... | 3 | n,p = map(int,input().split())
al = list(map(int,input().split()))
for a in al:
if a % 2 == 1:
print(2**(n-1))
exit()
if p == 0:
print(2**n)
else:
print(0)
|
Hierarchical Democracy
The presidential election in Republic of Democratia is carried out through multiple stages as follows.
1. There are exactly two presidential candidates.
2. At the first stage, eligible voters go to the polls of his/her electoral district. The winner of the district is the candidate who takes a ... | 3 | import re
n = int(input())
for _ in range(n):
dataset = input()
stage = 1
while (re.match('\[[0-9]+\]', dataset) is None):
iterator = re.finditer('\[([0-9]+\]\[)+[0-9]+\]', dataset)
minimum_votes = []
for i, match in enumerate(iterator):
areas = list(map(int, match.group... |
Kolya is going to make fresh orange juice. He has n oranges of sizes a1, a2, ..., an. Kolya will put them in the juicer in the fixed order, starting with orange of size a1, then orange of size a2 and so on. To be put in the juicer the orange must have size not exceeding b, so if Kolya sees an orange that is strictly gr... | 3 | n, b, d = map(int, input().split())
sm = 0
counter = 0
li = list(map(int, input().split()))
for i in li:
if i <= b:
sm += i
if (sm > d):
counter += 1
sm = 0
print(counter)
|
The bloodiest battle of World War II has started. Germany and its allies have attacked the Soviet union army to gain control of the city of Stalingrad (now Volgograd) in the south-western Soviet Union.The war has become intensive and the soviet union's 64th army is fighting against the germans. General "Vasily Chuikov"... | 1 | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
def sign(x1,y1,x2,y2,x3,y3):
i=((x1 - x3) * (y2 - y3)) - ((x2 - x3) * (y1 - y3))
return i
T=raw_input()
T=int(T)
for T in range(0, T):
x1,y1,x2,y2,x3,y3,x4,y4 = raw_input().split()... |
Try guessing the statement from this picture:
<image>
You are given a non-negative integer d. You have to find two non-negative real numbers a and b such that a + b = d and a β
b = d.
Input
The first line contains t (1 β€ t β€ 10^3) β the number of test cases.
Each test case contains one integer d (0 β€ d β€ 10^3).
... | 3 | t = int(input())
for q in range(t):
d = int(input())
D = d * d - 4 * d
if D < 0:
print("N")
else:
b = (d + D ** 0.5) / 2
a = d - b
print('Y ', end = '')
print(a, b) |
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... | 1 | import sys
input = sys.stdin.readline
############ ---- Input Functions ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(list(s[:len(s) - 1]))
def invr():
return(map(int,input().split()))
import math
t=inp()
for i i... |
It is only six months until Christmas, and AtCoDeer the reindeer is now planning his travel to deliver gifts.
There are N houses along TopCoDeer street. The i-th house is located at coordinate a_i. He has decided to deliver gifts to all these houses.
Find the minimum distance to be traveled when AtCoDeer can start and ... | 3 | import math
input()
a=sorted(map(int,input().split()))
print(a[-1]-a[0])
|
Orac is studying number theory, and he is interested in the properties of divisors.
For two positive integers a and b, a is a divisor of b if and only if there exists an integer c, such that aβ
c=b.
For n β₯ 2, we will denote as f(n) the smallest positive divisor of n, except 1.
For example, f(7)=7,f(10)=2,f(35)=5.
... | 3 | # Fall 7, Stand 8...
def smallestDivisor(n):
if (n % 2 == 0):
return 2;
i = 3;
while (i * i <= n):
if (n % i == 0):
return i;
i += 2;
return n;
for tin in range(int(input())):
n,k=map(int,input().split())
i=0
for _ in range(k):
n=n+smallestDivisor(... |
Two players play a simple game. Each player is provided with a box with balls. First player's box contains exactly n1 balls and second player's box contains exactly n2 balls. In one move first player can take from 1 to k1 balls from his box and throw them away. Similarly, the second player can take from 1 to k2 balls f... | 3 | a,b,*c=map(int,input().split())
print('SFeicrosntd'[a>b::2]) |
You have a set of n distinct positive numbers. You also have m colors. Your colors are labeled from 1 to m. You're also given a list c with m distinct integers.
You paint the numbers according to the following rules:
For each i in order from 1 to m, paint numbers divisible by c[i] with color i.
If multiple rules apply... | 1 | # get number of integers and noumber of colours
n, m = map(int, raw_input().split())
# paint integer
c = map(int, raw_input().split())
c.insert(0, c[0])
my_ints = map(int, raw_input().split())
result = []
result.append(c[my_ints[0]])
# for every integer in my_ints
for integer in range(1, len(my_ints)):
# start... |
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 | n = int(input())
s = input()
num = 0
F, S = 0, 0
pre = s[0]
for i in range(n):
if s[i] != pre:
if s[i] == "S":
F += 1
pre = "S"
else:
S += 1
pre = "F"
if F < S:
print("YES")
else:
print("NO") |
We have N boxes, numbered 1 through N. At first, box 1 contains one red ball, and each of the other boxes contains one white ball.
Snuke will perform the following M operations, one by one. In the i-th operation, he randomly picks one ball from box x_i, then he puts it into box y_i.
Find the number of boxes that may ... | 3 | n,m=map(int,input().split())
xy=[list(map(lambda x:int(x)-1,input().split())) for _ in [0]*m]
cnt=[1 for _ in [0]*n]
red=[False for _ in [0]*n]
red[0]=1
for x,y in xy:
cnt[x]-=1
cnt[y]+=1
if red[x]==True:
red[y]=True
if cnt[x]==0:
red[x]=False
print(red.count(True)) |
Find the minimum area of a square land on which you can place two identical rectangular a Γ b houses. The sides of the houses should be parallel to the sides of the desired square land.
Formally,
* You are given two identical rectangles with side lengths a and b (1 β€ a, b β€ 100) β positive integers (you are given ... | 3 | t = int(input())
def minimal_square():
a,b = input().split(' ')
a = int(a)
b= int(b)
if b>a :
a,b = b,a
dtbn = 1000000000
if 2*b>=a:
dtbn = min(dtbn,(2*b)**2)
dtbn = min(dtbn,(2*a)**2)
if 2*b<=a:
dtbn = min(dtbn,(a)**2)
dtbn = min(dtbn,(a+b)**2)
print(dtb... |
You are given two positive integers β A and B. You have to check whether A is divisible by all the prime divisors of B.
Input
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
For each test case, you are given two space separated integers β A ... | 1 | t = int(raw_input())
for i in range(0, t):
a, b = raw_input().split()
a = int(a)
b = int(b)
if (a ** 65) % b == 0:
print "Yes"
else:
print "No" |
A competitive eater, Alice is scheduling some practices for an eating contest on a magical calendar. The calendar is unusual because a week contains not necessarily 7 days!
In detail, she can choose any integer k which satisfies 1 β€ k β€ r, and set k days as the number of days in a week.
Alice is going to paint some n... | 3 | def solve():
n, k = map(int, input().split())
if k < n:
print(k * (k+1) // 2)
else:
ans = n * (n-1) // 2
ans += 1
print(ans)
for i in range(int(input())):
solve() |
There always is something to choose from! And now, instead of "Noughts and Crosses", Inna choose a very unusual upgrade of this game. The rules of the game are given below:
There is one person playing the game. Before the beginning of the game he puts 12 cards in a row on the table. Each card contains a character: "X"... | 1 | n = int(raw_input())
P = [[1,12],[2,6],[3,4],[4,3],[6,2],[12,1]]
for i in range(n):
t = raw_input()
res = []
for a,b in P:
data = [t[b*i:b*(i+1)] for i in range(a)]
#print data
data_check = [1 if 'X' in [data[i][j] for i in range(a)]==['X']*a else 0 for j in range(b)]
#print ... |
Takahashi is now competing in a programming contest, but he received TLE in a problem where the answer is `YES` or `NO`.
When he checked the detailed status of the submission, there were N test cases in the problem, and the code received TLE in M of those cases.
Then, he rewrote the code to correctly solve each of th... | 3 | N, M = map(int, input().split())
print((100*(N-M) + 1900*M)*pow(2, M)) |
There are two popular keyboard layouts in Berland, they differ only in letters positions. All the other keys are the same. In Berland they use alphabet with 26 letters which coincides with English alphabet.
You are given two strings consisting of 26 distinct letters each: all keys of the first and the second layouts i... | 3 | # -*- coding: utf-8 -*-
r1 = list(input())
r2 = list(input())
s = list(input())
dic = {}
for i in range(26):
dic[r1[i]] = r2[i]
ans = ''
for i in s:
x = i.lower()
try:
y = dic[x]
if x.upper()==i: ans += y.upper()
else: ans += y
except:
ans += x
print(ans)
|
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth.
Now Diamond has given Bort a string consisting of only uppercase English letters of length n. There is a great number of "QAQ" in the string (Diamond is so cute!).
<image> illustration by η«ε± https://twitter.com/nekoy... | 3 | s=str(input())
dp='QAQ'
c=0
for i in range(len(s)):
if s[i]=='Q':
for j in range(i,len(s)):
if s[j]=='A':
for k in range(j, len(s)):
if s[k]=='Q':
c+=1
print(c)
|
After a long party Petya decided to return home, but he turned out to be at the opposite end of the town from his home. There are n crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.
The crossroads are represented as a string s of length n, where s_i = A, if there is... | 3 | t=int(input())
for _ in range(t):
a,b,c=map(int,input().split())
d=str(input())
n=len(d)
i=n-2
sol=n
e=0
while(i>=0):
t=d[i]
while(i>=0 and d[i]==t):
i=i-1
if(t=='A'):
e=e+a
else:
e=e+b
if(e<=c):
sol=i+2
... |
One day, the Grasshopper was jumping on the lawn and found a piece of paper with a string. Grasshopper became interested what is the minimum jump ability he should have in order to be able to reach the far end of the string, jumping only on vowels of the English alphabet. Jump ability is the maximum possible length of ... | 3 | s=input()
l=[0]
for i in range(len(s)):
if(s[i]=='A' or s[i]=='E' or s[i]=='I' or s[i]=='O' or s[i]=='U' or s[i]=='Y'):
l.append(i+1)
l.append(len(s)+1)
l2=[]
for i in range(len(l)-1):
l2.append(l[i+1]-l[i])
print(max(l2)) |
You are given a graph with n nodes and m directed edges. One lowercase letter is assigned to each node. We define a path's value as the number of the most frequently occurring letter. For example, if letters on a path are "abaca", then the value of that path is 3. Your task is find a path whose value is the largest.
I... | 3 |
from collections import defaultdict, deque, Counter
import sys
import bisect
import math
#
# mod = 1000000007
input = sys.stdin.readline
def beauty(n, m, z, x, y):
l = z
degree = [0 for i in range(n)]
graph = defaultdict(list)
for i in range(m):
a, b = x[i], y[i]
a -= 1
b -= 1... |
Polycarp likes numbers that are divisible by 3.
He has a huge number s. Polycarp wants to cut from it the maximum number of numbers that are divisible by 3. To do this, he makes an arbitrary number of vertical cuts between pairs of adjacent digits. As a result, after m such cuts, there will be m+1 parts in total. Poly... | 3 | t=1
r=s=0
for c in input():
s=(s+int(c))%3
if t>>s&1:
r+=1;s,t=0,1
else:t|=1<<s
print(r) |
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 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 22 17:48:26 2020
@author: ΠΠ»Π΅Π³
"""
n, k=map(int, input().split())
a=list(map(int, input(). split()))
c=set(a)
s=0
if len(c)>=k:
print("YES")
for i in c:
s+=1
print(a.index(i)+1, end=" ")
if s==k:
break
else:
print("NO") |
Iahub got bored, so he invented a game to be played on paper.
He writes n integers a1, a2, ..., an. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices i and j (1 β€ i β€ j β€ n) and flips all values ak for which their positions are in range [i, j] (that is i β€ k β€ j)... | 3 | n = int(input())
bs = list(map(int, input().split()))
ans = 0
for i in range(n):
for j in range(i, n):
ans = max(ans, sum(bs) + j - i + 1 - 2 * sum(bs[i: j + 1]))
print(ans)
|
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 | t = int(input())
for _ in range(t):
n, m = map(int,input().split())
ans = (n*m + 1) // 2
print(ans) |
Innokentiy decides to change the password in the social net "Contact!", but he is too lazy to invent a new password by himself. That is why he needs your help.
Innokentiy decides that new password should satisfy the following conditions:
* the length of the password must be equal to n,
* the password should con... | 1 | n, k = map(int, raw_input().split())
alp = ''
for i in range(26):
alp += chr(ord('a') + i)
print alp[:k] * (n / k) + alp[:n % k] |
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy... | 3 | n=int(input())
a,b,c=0,0,0
for i in range(n):
l=list(map(int,input().split()))
a+=l[0]
b+=l[1]
c+=l[2]
if a==0 and b==0 and c==0:
print("YES")
else:
print("NO")
|
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 | s=input()
t=input()
x=0
if len(s)>len(t) or len(s)<len(t):
print('NO')
else:
for i in range(len(s)):
if s[i]==t[-i-1]:
x=x+1
if x==len(s):
print('YES')
else:
print('NO')
|
Tanya has n candies numbered from 1 to n. The i-th candy has the weight a_i.
She plans to eat exactly n-1 candies and give the remaining candy to her dad. Tanya eats candies in order of increasing their numbers, exactly one candy per day.
Your task is to find the number of such candies i (let's call these candies goo... | 3 | n = int(input())
a = list(map(int, input().split()))
s_l = [0] * n
s = 0
i = n - 1
while (i >= 0):
if i % 2 == 0:
s += a[i]
else:
s -= a[i]
s_l[i] = s
i -= 1
s = 0
ans = 0
for i in range(n - 1):
if s + s_l[i + 1] == 0:
ans += 1
if i % 2 == 0:
s -= a[i]
else:
... |
You are given an integer n and an integer k.
In one step you can do one of the following moves:
* decrease n by 1;
* divide n by k if n is divisible by k.
For example, if n = 27 and k = 3 you can do the following steps: 27 β 26 β 25 β 24 β 8 β 7 β 6 β 2 β 1 β 0.
You are asked to calculate the minimum numbe... | 3 | def go_to_zero(n, k):
res = 0
if n < k:
return n
while (n > 0):
if n % k == 0:
n = n // k
res += 1
else:
res += n % k
n -= n % k
return res
t = int(input())
for _ in range(t):
n, k = map(int, input().split())
print(go_to_zero(n, k)) |
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 | #####################################################
""""""""""""" Mino """""""""""""
#####################################################
"""############ Β© Mino's corporation #############"""
import re
s = str(input()).lower()
s = re.sub("[aeuioy]", "", s)
print("".join(["."+elt for elt in s]... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.