problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
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 | # ------------------- fast io --------------------
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... |
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 | matrix = []
for i in range(5):
permanent_not = input().split()
if "1" in permanent_not:
result = abs(2 - i) + abs(2 - permanent_not.index("1"))
print(result) |
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 | import sys
from os import path
if(path.exists('C:/Users/prana/Desktop/sublime/input.txt')):
sys.stdin = open("C:/Users/prana/Desktop/sublime/input.txt","r")
sys.stdout = open("C:/Users/prana/Desktop/sublime/output.txt","w")
# ----------------------------------------------------------------------
from collectio... |
Sereja loves integer sequences very much. He especially likes stairs.
Sequence a1, a2, ..., a|a| (|a| is the length of the sequence) is stairs if there is such index i (1 ≤ i ≤ |a|), that the following condition is met:
a1 < a2 < ... < ai - 1 < ai > ai + 1 > ... > a|a| - 1 > a|a|.
For example, sequences [1, 2, 3, 2... | 3 | from collections import Counter
n = int(input())
arr = list(map(int, input().split()))
straight = list(sorted(set(arr)))
counter = Counter(arr)
for v in straight:
counter[v] -= 1
counter += Counter()
temp = [x for x in sorted(set(counter), reverse=True) if x < straight[-1]]
print(len(straight) + len(temp))
... |
We call two numbers x and y similar if they have the same parity (the same remainder when divided by 2), or if |x-y|=1. For example, in each of the pairs (2, 6), (4, 3), (11, 7), the numbers are similar to each other, and in the pairs (1, 4), (3, 12), they are not.
You are given an array a of n (n is even) positive in... | 3 | t=int(input())
for i in range(0,t):
n=int(input())
lst=list(int(num) for num in input().split())[:n]
lst=sorted(lst)
count0=0
count1=0
flag=False
for i in range(1,n):
if lst[i]-lst[i-1]==1:
flag=True
for i in range(0,n):
if lst[i]%2==0:
count0+=1
... |
For given integers m and n, compute mn (mod 1,000,000,007). Here, A (mod M) is the remainder when A is divided by M.
Constraints
* 1 ≤ m ≤ 100
* 1 ≤ n ≤ 109
Input
m n
Two integers m and n are given in a line.
Output
Print mn (mod 1,000,000,007) in a line.
Examples
Input
2 3
Output
8
Input
5 8
Output... | 3 | import sys
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 7)
def p(M, N, mod):
if N == 0:
return 1
if N % 2 == 0:
half = p(M, N // 2, mod)
return half * half % mod
else:
return M * p(M, N - 1, mod) % mod
if __name__ == "__main__":
M, N = map(int, input(... |
Polycarp is reading a book consisting of n pages numbered from 1 to n. Every time he finishes the page with the number divisible by m, he writes down the last digit of this page number. For example, if n=15 and m=5, pages divisible by m are 5, 10, 15. Their last digits are 5, 0, 5 correspondingly, their sum is 10.
You... | 3 | q = int(input())
while q > 0:
n, m = [int(x) for x in input().split()]
lm = m%10
D = [lm]
while True:
ld = D[len(D)-1]
nd = (ld + lm)%10
if nd == lm:
break
D.append(nd)
rs = sum(D)
rl = len(D)
pc = n//m
fc = pc//rl
rc = pc%rl
... |
Bholu the Pandit on this New Year wanted to divide his Cuboidal Packaging block into cubes.
But he loves uniformity so he asks you to divide it such a way that all the cubes are of same size and volume of individual cube is as large as possible.
Note: He will utilize whole volume i.e volume of cuboid before dividing i... | 1 | import fractions
t=raw_input()
t=int(t)
while t>0:
t=t-1
a,b,c=map(int,raw_input().split())
a=int(a)
b=int(b)
c=int(c)
minn=fractions.gcd(a,fractions.gcd(b,c))
if minn!=1:
ans=(a*b*c)/(minn*minn*minn)
else:
ans=a*b*c
ans=ans%1000000007
print minn,ans |
«Polygon» is a system which allows to create programming tasks in a simple and professional way. When you add a test to the problem, the corresponding form asks you for the test index. As in most cases it is clear which index the next test will have, the system suggests the default value of the index. It is calculated ... | 3 | n = int(input())
l = sorted(list(map(int,input().split(" "))))
for i in range(n):
if l[i] != i+1:
print(i+1)
break
else:
print(n+1) |
Vasya has got an undirected graph consisting of n vertices and m edges. This graph doesn't contain any self-loops or multiple edges. Self-loop is an edge connecting a vertex to itself. Multiple edges are a pair of edges such that they connect the same pair of vertices. Since the graph is undirected, the pair of edges (... | 3 | import sys
import bisect as bi
import collections as cc
N = 2*(10**5)+5
i=1
ar = []
while i*i<=N:
ar.append([i,i*i])
i+=1
import sys
import collections as cc
input = sys.stdin.readline
I = lambda :list(map(int,input().split()))
ar = [(i*(i-1))//2 for i in range(1,1000)]
n , m = I()
mi = max(0,n-2*m)
tot = m
ini... |
Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).
For example, as a result of typing the word "hello", the follo... | 1 | from __future__ import print_function, division
def ok(s1, s2, i1=0, i2=0):
c1 = s1[i1]
add1=0
add2=0
while i1+add1 < len(s1) and s1[i1+add1] == c1:
add1 += 1
c2 = s2[i2]
if c2 != c1:
return False, None
while i2+add2 < len(s2) and s2[i2+add2] == c2:
add2 += 1
if add1 > add2:
return False, None
return ... |
n participants of the competition were split into m teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends.
Your task is to write a program that will find the minimum and the maximum number of pairs of friends that could ha... | 1 | n,m=map(int,raw_input().split())
a=n/m
print m*a*(a-1)/2+a*(n%m),(n-m)*(n-m+1)/2 |
According to rules of the Berland fashion, a jacket should be fastened by all the buttons except only one, but not necessarily it should be the last one. Also if the jacket has only one button, it should be fastened, so the jacket will not swinging open.
You are given a jacket with n buttons. Determine if it is fasten... | 3 | jacketNumber = ''
jacketList = ''
jacketNumber = int(input())
jacketList = input()
jacketList = jacketList.split()
if len(jacketList) == 1:
if int(jacketList[0]) == 1:
print('YES')
else:
print('NO')
else:
unFastened = []
for i in range(len(jacketList)):
if int(jacketList[i]) == 0:
unFasten... |
Polycarp has 26 tasks. Each task is designated by a capital letter of the Latin alphabet.
The teacher asked Polycarp to solve tasks in the following way: if Polycarp began to solve some task, then he must solve it to the end, without being distracted by another task. After switching to another task, Polycarp cannot re... | 3 | def main():
t = int(input())
for _ in range(1, t+1):
n = int(input())
s = input()
unique = set()
temp = ''
not_suspicious = True
for c in s:
if c == temp:
pass
else:
if ord(c) in unique:
n... |
Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it ... | 3 | n = int(input())
c = []
d = 0
x = 0
for i in range(n):
a, b = map(int,input().split())
if d < 1:
c.append(b)
del a
del b
d = d + 1
else:
c.append((c[-1]) - a + b)
x = max(c)
print(x)
|
wHAT DO WE NEED cAPS LOCK FOR?
Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage.
Let's consider that a word has been typed with the Caps lock key accidentall... | 3 | a = input()
if a[1:].isupper() or len(a) == 1:
if a[0].isupper():
print(a.lower())
else:
print(a[0].upper() + a[1:].lower())
else:
print(a)
|
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area.
Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no e... | 3 | inp = input().split()
a = [int(inp[0]),int(inp[1])]
b = [int(inp[2]),int(inp[3])]
c = [int(inp[4]),int(inp[5])]
a.sort()
a.reverse()
a.append("A")
b.sort()
b.reverse()
b.append("B")
c.sort()
c.reverse()
c.append("C")
first = [a, b ,c]
first.sort()
first.reverse()
second = [a, b, c]
second.sort()
second.reverse()
third ... |
HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.
One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read s... | 1 | n = input()
a = map(int,raw_input().split())
s = 0
indices = sorted(range(n), key = a.__getitem__)
for x in xrange(1,n):
s+=abs(indices[x]-indices[x-1])
print s
|
Luba is surfing the Internet. She currently has n opened tabs in her browser, indexed from 1 to n from left to right. The mouse cursor is currently located at the pos-th tab. Luba needs to use the tabs with indices from l to r (inclusive) for her studies, and she wants to close all the tabs that don't belong to this se... | 3 | import sys
n,pos,l,r=map(int,input().split())
# n = int(n)
# pos = int(pos)
# l = int(l)
# r = int(r)
time = 0
if(pos<l):
if(n>r):
time = r-pos+2
else:
time = l-pos+1
elif(pos>r):
if(l>1):
time = pos-l+2
else:
time = pos-r+1
else:
if(l>1 and r<n):
time = min(pos-l, r-pos)+r-l+2
elif(r<n):
time = r-p... |
Summer holidays! Someone is going on trips, someone is visiting grandparents, but someone is trying to get a part-time job. This summer Noora decided that she wants to earn some money, and took a job in a shop as an assistant.
Shop, where Noora is working, has a plan on the following n days. For each day sales manager... | 1 | from collections import defaultdict
def go():
n, f = [int(i) for i in raw_input().split(" ")]
could = [ ]
sold = [ ]
for i in range(n):
ki,li = [int(i) for i in raw_input().split(" ")]
sold.append(min(ki,li))
could.append(min(2*ki,li)-min(ki,li))
could = sorted(could)
return sum(sold)+sum(could[n-f:])
pri... |
You've got a list of program warning logs. Each record of a log stream is a string in this format:
"2012-MM-DD HH:MM:SS:MESSAGE" (without the quotes).
String "MESSAGE" consists of spaces, uppercase and lowercase English letters and characters "!", ".", ",", "?". String "2012-MM-DD" determines a correct date in the ... | 1 | sec, times = map(int, raw_input().split())
from sys import exit
from datetime import datetime
from datetime import timedelta
def parse(st):
days = (0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335)
month = int(st[5:7])
day = int(st[8:10]) + days[month - 1]
hour = int(st[11:13])
minute = int(... |
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N), the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to Stone i + 1 or Stone i + 2. Here, a cost of |... | 3 | N=int(input())
h=list(map(int,input().split()))
h1=abs(h[0]-h[1])
h0=0
for i in range(1,N-1):
h0,h1=h1,min(
abs(h[i+1]-h[i-1])+h0,
abs(h[i+1]-h[i])+h1
)
print(h1) |
Sergey is testing a next-generation processor. Instead of bytes the processor works with memory cells consisting of n bits. These bits are numbered from 1 to n. An integer is stored in the cell in the following way: the least significant bit is stored in the first bit of the cell, the next significant bit is stored in ... | 3 | input();print((input()[:-1] + "0").index("0") + 1) |
You have been given an array A of size N and an integer K. This array consists of N integers ranging from 1 to 10^7. Each element in this array is said to have a Special Weight. The special weight of an element a[i] is a[i]\%K.
You now need to sort this array in Non-Increasing order of the weight of each element, i.e ... | 1 | import sys
s=raw_input().split(" ")
s1=raw_input().split(" ")
s1=[int(x) for x in s1]
s1=sorted(s1)
dict={}
for i in range(0,len(s1)):
dict.update({s1[i]:s1[i]%int(s[1])})
list=sorted(dict,key=dict.__getitem__,reverse=True)
list=[str(x) for x in list]
print ' '.join(list) |
Nikolay got a string s of even length n, which consists only of lowercase Latin letters 'a' and 'b'. Its positions are numbered from 1 to n.
He wants to modify his string so that every its prefix of even length has an equal amount of letters 'a' and 'b'. To achieve that, Nikolay can perform the following operation arb... | 3 | x = int(input())
s = input()
output = ''
i = 0
count = 0
while (i < len(s)):
if (s[i] == s[i + 1]):
count += 1
if s[i] == 'a':
output += 'b'
output += 'a'
else:
output += 'a'
output += 'b'
else:
output += s[i]
output += s[i... |
Today the kindergarten has a new group of n kids who need to be seated at the dinner table. The chairs at the table are numbered from 1 to 4n. Two kids can't sit on the same chair. It is known that two kids who sit on chairs with numbers a and b (a ≠ b) will indulge if:
1. gcd(a, b) = 1 or,
2. a divides b or b d... | 3 | for i in range(int(input())):
n = int(input())
x = (4*n)-2
for i in range(n):
print(x,end=' ')
x-=2
print() |
Given a lowercase English letter c, determine whether it is a vowel. Here, there are five vowels in the English alphabet: `a`, `e`, `i`, `o` and `u`.
Constraints
* c is a lowercase English letter.
Input
The input is given from Standard Input in the following format:
c
Output
If c is a vowel, print `vowel`. Oth... | 3 | print(['consonant','vowel'][input() in 'aeiou']) |
A schoolboy named Vasya loves reading books on programming and mathematics. He has recently read an encyclopedia article that described the method of median smoothing (or median filter) and its many applications in science and engineering. Vasya liked the idea of the method very much, and he decided to try it in practi... | 3 | n=int(input())
b=[int(t) for t in input().strip().split()]
a=b+[b[-1]]
current=1
is_alternating=False
break_points=[]
for current in range(1,len(a)):
if(a[current]!=a[current-1] and is_alternating==False):
break_points.append(current-1)
is_alternating=True
elif(a[current]==a[current-1] and is_... |
Find the smallest possible sum of the digits in the decimal notation of a positive multiple of K.
Constraints
* 2 \leq K \leq 10^5
* K is an integer.
Input
Input is given from Standard Input in the following format:
K
Output
Print the smallest possible sum of the digits in the decimal notation of a positive mu... | 3 | import sys
from collections import deque
sys.setrecursionlimit(10000)
INF = float('inf')
K = int(input())
# ある数に 1 を足すと各桁の和は 1 増える
# ある数に 10 を掛けると各桁の和は 0 増える
# mod K の世界で同じことやっても同じなので
# このグラフ上で 1 から 0 への最短距離が答え。
distances = [INF for _ in range(K)]
# 01BFS
distances[1] = 1
remains = deque()
remains.append((1, 1))
w... |
Hideo Kojima has just quit his job at Konami. Now he is going to find a new place to work. Despite being such a well-known person, he still needs a CV to apply for a job.
During all his career Hideo has produced n games. Some of them were successful, some were not. Hideo wants to remove several of them (possibly zero)... | 3 | n = int(input())
s = list(map(int, input().split()))
res = max([len(s[:i])-sum(s[:i])+sum(s[i:]) for i in range(n+1)])
print(res) |
There are n athletes in front of you. Athletes are numbered from 1 to n from left to right. You know the strength of each athlete — the athlete number i has the strength s_i.
You want to split all athletes into two teams. Each team must have at least one athlete, and each athlete must be exactly in one team.
You want... | 3 | n=int(input())
arr=[]
for i in range(n):
x=int(input())
c=list(map(int,input().split(" ")))
arr.append(c.copy())
# print(arr)
def merge(arr,start,mid,end):
arr1=[]
if(end-start==1):
if(arr[start]>arr[end]):
arr1.append(arr[end])
arr1.append(arr[start])
else... |
String can be called correct if it consists of characters "0" and "1" and there are no redundant leading zeroes. Here are some examples: "0", "10", "1001".
You are given a correct string s.
You can perform two different operations on this string:
1. swap any pair of adjacent characters (for example, "101" <image>... | 3 | q = int(input())
s = input()
c = 0
if s.find("1") == -1:
print(0)
exit()
for i in range(q):
if s[i] == "0":
c += 1
w = "1"
for i in range(c):
w += "0"
print(w) |
City X consists of n vertical and n horizontal infinite roads, forming n × n intersections. Roads (both vertical and horizontal) are numbered from 1 to n, and the intersections are indicated by the numbers of the roads that form them.
Sand roads have long been recognized out of date, so the decision was made to asphal... | 3 | a=int(input())
b=[]
c=[]
d=[]
for i in range(a**2):
*e,=map(int,input().split())
if e[0]in b or e[1]in c:
continue
else:
d+=[i+1]
b+=[e[0]]
c+=[e[1]]
print(' '.join(map(str,d)))
|
Luba has to do n chores today. i-th chore takes ai units of time to complete. It is guaranteed that for every <image> the condition ai ≥ ai - 1 is met, so the sequence is sorted.
Also Luba can work really hard on some chores. She can choose not more than k any chores and do each of them in x units of time instead of a... | 3 | n,k,x = map(int, input().split())
a = list(map(int, input().split()))
print(sum(a[:-k]) + k*x)
|
Another Codeforces Round has just finished! It has gathered n participants, and according to the results, the expected rating change of participant i is a_i. These rating changes are perfectly balanced — their sum is equal to 0.
Unfortunately, due to minor technical glitches, the round is declared semi-rated. It means... | 3 | q=int(input())
w=[0]*q
e=0
r=0
t=[0]*q
for i in range(q):
w[i]=int(input())
if w[i]<0:
r-=(w[i]+1)//2
t[i]=(w[i]+1)//2
else:
e+=w[i]//2
t[i]=w[i]//2
i=0
while e<r:
if w[i]%2==1 and w[i]>0:
t[i]+=1
e+=1
i+=1
while r<e:
if w[i]%2==1 and w[i]<0:
... |
You are given an array consisting of n integers a_1, a_2, ..., a_n. Initially a_x = 1, all other elements are equal to 0.
You have to perform m operations. During the i-th operation, you choose two indices c and d such that l_i ≤ c, d ≤ r_i, and swap a_c and a_d.
Calculate the number of indices k such that it is poss... | 3 | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 12 08:53:45 2020
@author: SuperDY
"""
t=int(input())
for o in range(t):
s=input().split()
n,k,m=int(s[0]),int(s[1]),int(s[2])
l,r=k,k
for i in range(m):
x,y=map(int,input().split())
if x>r or y<l:
continue
r=max(r,y)
... |
Given are N points (x_i, y_i) in a two-dimensional plane.
Find the minimum radius of a circle such that all the points are inside or on it.
Constraints
* 2 \leq N \leq 50
* 0 \leq x_i \leq 1000
* 0 \leq y_i \leq 1000
* The given N points are all different.
* The values in input are all integers.
Input
Input is giv... | 3 | def gaishin(p,q,r):
a = ((q[0]-r[0])**2+(q[1]-r[1])**2)**(0.5) #qとrの間
b = ((r[0]-p[0])**2+(r[1]-p[1])**2)**(0.5) #rとpの間
c = ((p[0]-q[0])**2+(p[1]-q[1])**2)**(0.5) #pとqの間
cosp = (b**2+c**2-a**2)/(2*b*c)
cosq = (c**2+a**2-b**2)/(2*c*a)
cosr = (a**2+b**2-c**2)/(2*a*b)
if cosp >= 1: cosp = 1
if cosp <= -1: ... |
Takahashi has a tower which is divided into N layers. Initially, all the layers are uncolored. Takahashi is going to paint some of the layers in red, green or blue to make a beautiful tower. He defines the beauty of the tower as follows:
* The beauty of the tower is the sum of the scores of the N layers, where the sco... | 3 | class BinomialCoefficient:
def __init__(self, N, mod):
'''
Preprocess for calculating binomial coefficients nCr (0 <= r <= n, 0 <= n <= N)
over the finite field Z/(mod)Z.
Input:
N (int): maximum n
mod (int): a prime number. The order of the field Z/(mod)Z over... |
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:
* Tetrahedron. Tetrahedron has 4 triangular faces.
* Cube. Cube has 6 square faces.
* Octahedron. Octahedron has 8 triangular faces.
* Dodecahedron. Dodecahedron has 12 pentagonal faces.
*... | 1 | from __future__ import division, print_function
import os,sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
def ii(): return int(input())
def si(): return input()
def mi(): return map(in... |
Takahashi and Aoki are training for long-distance races in an infinitely long straight course running from west to east.
They start simultaneously at the same point and moves as follows towards the east:
* Takahashi runs A_1 meters per minute for the first T_1 minutes, then runs at A_2 meters per minute for the subse... | 3 | t1, t2 = map(int, input().split())
a1, a2 = map(int, input().split())
b1, b2 = map(int, input().split())
atot1 = (a1 - b1) * t1
atot2 = (a2 - b2) * t2
if atot1 > 0:
atot1 *= -1
atot2 *= -1
if atot1 + atot2 < 0:
print(0)
exit()
if atot1 == - atot2:
print('infinity')
exit()
S = (-atot1) // (atot... |
Consider creating the following number pattern.
4 8 2 3 1 0 8 3 7 6
2 0 5 4 1 8 1 0 3
2 5 9 5 9 9 1 3
7 4 4 4 8 0 4
1 8 8 2 8 4
9 6 0 0 2
5 6 0 2
1 6 2
7 8
Five
This pattern follows the rules below.
A B
C
In the sequence of numbers, C is the ones digit of A + B. For example
9 5
Four
Now, the ones digit of 9... | 1 | while True:
try:
n = list(raw_input())
for i in range(9,0,-1):
for j in range(i):
n[j] = (int(n[j])+int(n[j+1]))%10
print n[0]
except:
break |
We have a chocolate bar partitioned into H horizontal rows and W vertical columns of squares.
The square (i, j) at the i-th row from the top and the j-th column from the left is dark if S_{i,j} is `0`, and white if S_{i,j} is `1`.
We will cut the bar some number of times to divide it into some number of blocks. In ea... | 3 | H,W,K = map(int,input().split())
S = [list(map(int,input())) for _ in [0]*H]
ans = H*W
S2 = [[0]*(W+1) for _ in [0]*(H+1)]
for i in range(H):
for j in range(W):
S2[i+1][j+1] = S2[i][j+1] + S[i][j]
for i in range(1,H+1):
for j in range(W):
S2[i][j+1] += S2[i][j]
for i in range(1<<(H-1)):
ch... |
HQ9+ is a joke programming language which has only four one-character instructions:
* "H" prints "Hello, World!",
* "Q" prints the source code of the program itself,
* "9" prints the lyrics of "99 Bottles of Beer" song,
* "+" increments the value stored in the internal accumulator.
Instructions "H" and "Q"... | 3 | s = input()
a = "H"
b = "Q"
c = "9"
if a in s or b in s or c in s:
print("YES")
else:
print("NO") |
HQ9+ is a joke programming language which has only four one-character instructions:
* "H" prints "Hello, World!",
* "Q" prints the source code of the program itself,
* "9" prints the lyrics of "99 Bottles of Beer" song,
* "+" increments the value stored in the internal accumulator.
Instructions "H" and "Q"... | 1 | x=list(raw_input())
t=['H','Q','9']
flag=1
for i in range(len(x)):
if x[i] in t:
print 'YES'
flag=0
break
if flag:
print 'NO' |
Stepan has the newest electronic device with a display. Different digits can be shown on it. Each digit is shown on a seven-section indicator like it is shown on the picture below.
<image>
So, for example, to show the digit 3 on the display, 5 sections must be highlighted; and for the digit 6, 6 sections must be high... | 1 | n=int(raw_input())
s=""
if n%2==1 and n>2:
s=s+'7'
n=n-3
while n>0:
s=s+'1'
n=n-2
print s |
It is the hard version of the problem. The only difference is that in this version 3 ≤ k ≤ n.
You are given a positive integer n. Find k positive integers a_1, a_2, …, a_k, such that:
* a_1 + a_2 + … + a_k = n
* LCM(a_1, a_2, …, a_k) ≤ n/2
Here LCM is the [least common multiple](https://en.wikipedia.org/wiki... | 3 | # cook your dish here
for _ in range(int(input())):
n,k = map(int,input().split())
l = [1]*(k-3)
n -= (k-3)
if n%4==0:
l.extend([n//2,n//4,n//4])
elif n%2==0:
l.extend([2,n//2-1,n//2-1])
else:
l.extend([1,n//2,n//2])
print(*l) |
You are given a positive integer X. Find the largest perfect power that is at most X. Here, a perfect power is an integer that can be represented as b^p, where b is an integer not less than 1 and p is an integer not less than 2.
Constraints
* 1 ≤ X ≤ 1000
* X is an integer.
Input
Input is given from Standard Input ... | 3 | n=int(input())
ans=1
for i in range(1,32):
for j in range(2,10):
if n>=i**j:
ans=max(ans,i**j)
print(ans) |
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point x(x > 0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order ... | 3 | x = int(input())+4
s = x//5
print(s)
|
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya has two strings a and b of the same length n. The strings consist only of lucky digits. Pety... | 1 | import sys
import math
file = sys.stdin
p1 = map(int, list(file.readline().rstrip()))
p2 = map(int, list(file.readline().rstrip()))
d = map(lambda t: t[0] - t[1], [(p1[i], p2[i]) for i in range(len(p1))])
neg = d.count(-3)
pos = d.count(3)
k = min(neg, pos)
cnt = k
neg -= k
pos -= k
cnt += neg + pos
print cnt
|
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other.
Input
The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence o... | 3 | n=int(input())
count=0
one=0
two=0
three=0
x=list(map(int,input().split()))
for i in x:
if i==1:
one=one+1
elif i==2:
two=two+1
elif i==3:
three=three+1
max_=max(one,two ,three)
answer=n-max_
print(answer) |
There is a grid of squares with H horizontal rows and W vertical columns. The square at the i-th row from the top and the j-th column from the left is represented as (i, j). Each square is black or white. The color of the square is given as an H-by-W matrix (a_{i, j}). If a_{i, j} is `.`, the square (i, j) is white; if... | 3 | h, w = map(int, input().split())
a = []
ans = []
for _ in range(h):
aw = input()
if set(aw) != {'.'}:
a.append(aw)
for i in zip(*a):
if set(i) != {'.'}:
ans.append("".join(list(i)))
for j in zip(*ans):
print("".join(list(j))) |
Given any integer x, Aoki can do the operation below.
Operation: Replace x with the absolute difference of x and K.
You are given the initial value of an integer N. Find the minimum possible value taken by N after Aoki does the operation zero or more times.
Constraints
* 0 ≤ N ≤ 10^{18}
* 1 ≤ K ≤ 10^{18}
* All valu... | 3 | n, k = map(int, input().split())
print(min((n % k), (-n % k))) |
Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones.
Once he thought about a string of length n consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and ... | 3 | n=int(input());
s=input();
l=list(s);
a=l.count('1');
b=l.count('0');
print(abs(a-b));
|
You are given a string s, consisting of n lowercase Latin letters.
A substring of string s is a continuous segment of letters from s. For example, "defor" is a substring of "codeforces" and "fors" is not.
The length of the substring is the number of letters in it.
Let's call some string of length n diverse if and o... | 3 | class Substring:
n = int(input())
news= list(input())
isSub=False
substring = ""
for i in range(len(news)-1):
if news[i] != news[i+1]:
substring = news[i]+news[i+1]
isSub=True
break
if isSub == False:
print("NO")
else:
print("YES")
... |
You are given a sequence a consisting of n integers. You may partition this sequence into two sequences b and c in such a way that every element belongs exactly to one of these sequences.
Let B be the sum of elements belonging to b, and C be the sum of elements belonging to c (if some of these sequences is empty, the... | 3 | n = int(input())
a = list(map(int,input().split()))
c = []
a.sort()
if a[0]>=0:
print(sum(a))
exit()
for i in range(n):
if a[i] < 0:
c.append(a[i])
a[i] = 0
else:
break
print(sum(a)-sum(c)) |
Vasily the Programmer loves romance, so this year he decided to illuminate his room with candles.
Vasily has a candles.When Vasily lights up a new candle, it first burns for an hour and then it goes out. Vasily is smart, so he can make b went out candles into a new candle. As a result, this new candle can be used like... | 1 |
a, b = map(int, raw_input().split())
burn_out = 0
hours = 0
while a > 0 or burn_out >= b:
a += burn_out / b
burn_out %= b
hours += a
burn_out += a
a = 0
print hours |
"You must lift the dam. With a lever. I will give it to you.
You must block the canal. With a rock. I will not give the rock to you."
Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.
Hermit Lizard agreed to give Danik the lever. But to get a stone... | 3 | import math
def li(): return list(map(int, input().split()))
t = int(input())
for _ in range(t):
n = int(input())
arr = li()
ans = [0]*30
for i in arr:
x = int(math.log(i, 2))
ans[x] += 1
fans = 0
for i in ans:
if i == 1:
continue
elif i == 2:
... |
You are given two positive integers n and k. Print the k-th positive integer that is not divisible by n.
For example, if n=3, and k=7, then all numbers that are not divisible by 3 are: 1, 2, 4, 5, 7, 8, 10, 11, 13 .... The 7-th number among them is 10.
Input
The first line contains an integer t (1 ≤ t ≤ 1000) — the ... | 3 |
for _ in range(int(input())):
n,k = map(int,input().split())
d = k//(n-1)
r = k%(n-1)
start = n*d-1
if(r > 0):
start += r+1
print(start)
|
You are given three integers A, B and C. Determine whether C is not less than A and not greater than B.
Constraints
* -100≤A,B,C≤100
* A, B and C are all integers.
Input
Input is given from Standard Input in the following format:
A B C
Output
If the condition is satisfied, print `Yes`; otherwise, print `No`.
... | 3 | a, b, c = map(int, (input().split()))
s="No"
if a <= c and c <= b:
s="Yes"
print(s) |
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.
Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, seco... | 3 | n = int(input())
hate = 'that I hate'
love = 'that I love'
out = 'I hate '
add = ''
if n >= 4:
add = (love + ' ' + hate + ' ') * (n//2 - 1)
if n%2 == 0:
add += love + ' '
else:
add += love + ' ' + hate + ' '
print(out + add + 'it')
elif n == 1:
print(out + 'it')
elif n == 2:
... |
Devu is a renowned classical singer. He is invited to many big functions/festivals. Recently he was invited to "All World Classical Singing Festival". Other than Devu, comedian Churu was also invited.
Devu has provided organizers a list of the songs and required time for singing them. He will sing n songs, ith song wi... | 1 | __author__ = 'user'
n, d = map(int, raw_input().split())
l = map(int, raw_input().split())
s = sum(l)
p = (len(l)-1)*10
if p + s <= d:
res = (len(l)-1)*2 +((d-p-s)/5)
else:
res = -1
print res |
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())
gifts = [0 for i in range(n)]
giftsParam = [int(i) for i in input().split(' ')]
for i in range(n):
gifts[giftsParam[i] - 1] = i + 1
print(' '.join(map(str,gifts))) |
Vlad enjoys listening to music. He lives in Sam's Town. A few days ago he had a birthday, so his parents gave him a gift: MP3-player! Vlad was the happiest man in the world! Now he can listen his favorite songs whenever he wants!
Vlad built up his own playlist. The playlist consists of N songs, each has a unique positi... | 1 | t=input()
for i in range(t):
n=input()
count=0
string = raw_input()
list1 = string.split()
list1 = [int(a) for a in list1]
k = input()
f1 = list1[k - 1]
for i in range(0,len(list1)):
if list1[i]<f1:
count+=1
print count+1 |
We have a string S of length N consisting of uppercase English letters.
How many times does `ABC` occur in S as contiguous subsequences (see Sample Inputs and Outputs)?
Constraints
* 3 \leq N \leq 50
* S consists of uppercase English letters.
Input
Input is given from Standard Input in the following format:
N
S
... | 3 | n = int(input())
m = input()
print(m.count("ABC")) |
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 | n,m = map(int,input().split())
lis = list(map(int,input().split()))
li = [0 for i in range(n)]
for i in range(n):li[lis[i]-1] += 1
li.sort(reverse = True)
ans = 0
for k in range(m):
ans += li[k]
print(n-ans) |
Let's call a string good if and only if it consists of only two types of letters — 'a' and 'b' and every two consecutive letters are distinct. For example "baba" and "aba" are good strings and "abb" is a bad string.
You have a strings "a", b strings "b" and c strings "ab". You want to choose some subset of these strin... | 3 | a,b,c=map(int,input().split())
if a==b:
print(a+b+2*c)
else:
if a>b:
print(2*(b+c)+1)
else:
print(2*(a+c)+1) |
Vasya has his favourite number n. He wants to split it to some non-zero digits. It means, that he wants to choose some digits d_1, d_2, …, d_k, such that 1 ≤ d_i ≤ 9 for all i and d_1 + d_2 + … + d_k = n.
Vasya likes beauty in everything, so he wants to find any solution with the minimal possible number of different d... | 3 | n= int(input ())
if n != 1:
for c in range (9,0, -1) :
ans = n/c
if ans == int(ans) :
print (int(ans))
for z in range (1,int(ans+1)):
print (c, "", end = "")
break
if n ==1 :
print (1)
print (1)
|
wHAT DO WE NEED cAPS LOCK FOR?
Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage.
Let's consider that a word has been typed with the Caps lock key accidentall... | 3 | s = input()
alph = 'abcdefghijklmnopqrstuvwxyz'
first_lower = s[0] in alph
rest_upper = all(c in alph.upper() for c in s[1:])
all_upper = all(c in alph.upper() for c in s)
if all_upper:
print(s.lower())
elif first_lower and rest_upper:
print(s[0].upper() + s[1:].lower())
else:
print(s) |
Your favorite shop sells n Kinder Surprise chocolate eggs. You know that exactly s stickers and exactly t toys are placed in n eggs in total.
Each Kinder Surprise can be one of three types:
* it can contain a single sticker and no toy;
* it can contain a single toy and no sticker;
* it can contain both a sing... | 3 | #E67_A
cases = int(input())
for i in range(0, cases):
ln = [int(j) for j in input().split(" ")]
n = ln[0]
s = ln[1]
t = ln[2]
s = n - s
t = n - t
print(max(s, t) + 1)
|
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 | # 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 fir... |
Today at the lesson of mathematics, Petya learns about the digital root.
The digital root of a non-negative integer is the single digit value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-d... | 3 | for i in range(int(input())):
k,l=map(int,input().split());print((k-1)*9+l)
|
Alice likes word "nineteen" very much. She has a string s and wants the string to contain as many such words as possible. For that reason she can rearrange the letters of the string.
For example, if she has string "xiineteenppnnnewtnee", she can get string "xnineteenppnineteenw", containing (the occurrences marked) tw... | 3 | s = input()
v1=0
v2=0
v3=0
v4=0
val=0
for x in range(0,len(s)):
if s[x]=="n":
v1=v1+1
elif s[x]=="i":
v2=v2+1
elif s[x]=="e":
v3=v3+1
elif s[x]=="t":
v4=v4+1
v1=(v1-1)//2 #1
v3=v3//3 #1
while (v1!=0 and v3!=0 and v2!=0 and v4!=0):
val=val+1
v1=v1-1
v2=v2-1
v3=v3-1
v4=... |
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 | counter = 0
symbols = []
s = input()
for k in s:
if k not in symbols:
counter += 1
symbols.append(k)
if counter % 2 == 0:
print('CHAT WITH HER!')
else:
print('IGNORE HIM!')
|
You are given two strings s and t consisting of lowercase Latin letters. Also you have a string z which is initially empty. You want string z to be equal to string t. You can perform the following operation to achieve this: append any subsequence of s at the end of string z. A subsequence is a sequence that can be deri... | 3 | from collections import Counter
from collections import deque
from sys import stdin
from bisect import *
from heapq import *
import math
g = lambda : stdin.readline().strip()
gl = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gfl = lambda : [float(var) for var in gl()]
gcl = lambda : list(g())
gbs ... |
Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are n drinks in his fridge, the volume fraction of orange juice in the i-th drink equals pi percent.
One day Vasya decided to make himself an orange cocktail. He took equal proportions of ea... | 1 | from __future__ import division
n = int(raw_input())
# input the array
arr = [int(x) for x in raw_input().split()]
summation = 0
# calculate sum
for x in arr:
summation += x
print(summation*100/(n*100)) |
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 | n=input().lower()
notvowl = ".".join([c for c in n if not c in "aiueoy"])
print("." + notvowl) |
Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be n problems, sorted by difficulty, i.e. problem 1 is the easiest and problem n is the hardest. Limak knows it will take him 5·i minutes to solve the i-th... | 1 | d = raw_input().split()
s = 0
n = 0
for i in range(int(d[0])):
s = s +(i+1) * 5
if 240 - int(d[1]) < s:
break
else:
n = n + 1
print n |
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.
Namely, it takes several iterations to calculate value v. At the first iteration, Xeni... | 3 | import sys, os, io
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
... |
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Bi... | 3 | a = int(input())
if a % 2 == 1 or a <= 2:
print('NO')
else:
print('YES')
|
There is a rectangle in the xy-plane, with its lower left corner at (0, 0) and its upper right corner at (W, H). Each of its sides is parallel to the x-axis or y-axis. Initially, the whole region within the rectangle is painted white.
Snuke plotted N points into the rectangle. The coordinate of the i-th (1 ≦ i ≦ N) po... | 3 | # coding: utf-8
w,h,N=list(map(int,input().split()))
rect=[0,w,0,h]
for i in range(N):
x,y,a=list(map(int, input().split()))
rect[a-1]=(lambda c,r,p:[r,c][p*(c-r)<0])([x,y][a>2],rect[a-1],[1,-1][a%2])
length=lambda x:[x,0][x<0]
print(length(rect[1]-rect[0])*length(rect[3]-rect[2])) |
Xenia lives in a city that has n houses built along the main ringroad. The ringroad houses are numbered 1 through n in the clockwise order. The ringroad traffic is one way and also is clockwise.
Xenia has recently moved into the ringroad house number 1. As a result, she's got m things to do. In order to complete the i... | 3 | n,m = map(int,input().split())
a = list(map(int,input().split()))
s = a[0]
steps = s - 1
for i in range(m):
if(s > a[i]):
steps = steps + (n - s) + a[i]
s = a[i]
else:
steps = steps + abs(a[i] - s)
s = a[i]
print(steps) |
You have 2n integers 1, 2, ..., 2n. You have to redistribute these 2n elements into n pairs. After that, you choose x pairs and take minimum elements from them, and from the other n - x pairs, you take maximum elements.
Your goal is to obtain the set of numbers \\{b_1, b_2, ..., b_n\} as the result of taking elements ... | 3 | '''
Auther: ghoshashis545 Ashis Ghosh
College: jalpaiguri Govt Enggineering College
'''
from os import path
from io import BytesIO, IOBase
import sys
from heapq import heappush,heappop
from functools import cmp_to_key as ctk
from collections import deque,Counter,defaultdict as dd
from bisect import bisect,bis... |
An altar enshrines N stones arranged in a row from left to right. The color of the i-th stone from the left (1 \leq i \leq N) is given to you as a character c_i; `R` stands for red and `W` stands for white.
You can do the following two kinds of operations any number of times in any order:
* Choose two stones (not nec... | 3 | # abc174_d.py
N = int(input())
S = input()
scnt = S.count("R")
print(S[:scnt].count("W")) |
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 | ch=input()
l=[]
for i in ch:
if i not in l:
l.append(i)
if len(l)%2==0:
print("CHAT WITH HER!")
else:
print("IGNORE HIM!")
|
Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.
Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindro... | 1 | k = raw_input()
print k + ''.join(reversed(k)) |
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())
counter = 0
entry = 0
while (counter<n):
x,y,z=input().split()
counter+=1
sum=int(x)+int(y)+int(z)
if(sum>1):
entry+=1
else:
entry = entry
print(entry)
|
Your friend has n cards.
You know that each card has a lowercase English letter on one side and a digit on the other.
Currently, your friend has laid out the cards on a table so only one side of each card is visible.
You would like to know if the following statement is true for cards that your friend owns: "If a car... | 3 | import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return [int(x) for x in sys.stdin.... |
You are given the array a consisting of n positive (greater than zero) integers.
In one move, you can choose two indices i and j (i ≠ j) such that the absolute difference between a_i and a_j is no more than one (|a_i - a_j| ≤ 1) and remove the smallest of these two elements. If two elements are equal, you can remove a... | 3 | for _ in range(int(input())):
n=int(input())
ls=list(map(int,input().split()))
ls.sort()
flag=0
for i in range(n-1):
if(ls[i+1]-ls[i]>1):
flag=1
break
if(flag==0):
print('YES')
else:
print('NO') |
You are given two integers x and y. You can perform two types of operations:
1. Pay a dollars and increase or decrease any of these integers by 1. For example, if x = 0 and y = 7 there are four possible outcomes after this operation:
* x = 0, y = 6;
* x = 0, y = 8;
* x = -1, y = 7;
* x = 1, y = ... | 3 | for _ in range(int(input())):
x,y=map(int,input().split())
a,b=map(int,input().split())
oi=(x+y)*a
ou=abs(x-y)*a
op=min(x,y)*b
ans=min(oi,ou+op)
print(ans)
|
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 | word = input()
user_word = word.lower()
vowels = 'aoyeui'
new_word = ''
for char in user_word:
if char not in vowels:
new_word += '.' + char
print(new_word) |
You are given the array of integer numbers a0, a1, ..., an - 1. For each element find the distance to the nearest zero (to the element which equals to zero). There is at least one zero element in the given array.
Input
The first line contains integer n (1 ≤ n ≤ 2·105) — length of the array a. The second line contains... | 1 | n = int(raw_input())
arr = map(int, raw_input().split())
def cal_right(arr, n):
right = list()
stack = list()
for item in arr:
if item == 0:
right.extend(range(len(stack), -1, -1))
stack = list()
else:
stack.append(item)
right.extend([2 * n] * len(st... |
In some game by Playrix it takes t minutes for an oven to bake k carrot cakes, all cakes are ready at the same moment t minutes after they started baking. Arkady needs at least n cakes to complete a task, but he currently don't have any. However, he has infinitely many ingredients and one oven. Moreover, Arkady can bui... | 3 | n,t,k,d=[int(x) for x in input().split() ]
x=(int(d/t)+1)*k
rest=n-x
if rest >= 1:
print('YES')
else:
print('NO') |
Mahmoud wants to send a message to his friend Ehab. Their language consists of n words numbered from 1 to n. Some words have the same meaning so there are k groups of words such that all the words in some group have the same meaning.
Mahmoud knows that the i-th word can be sent with cost ai. For each word in his messa... | 3 | n, k, m = list(map(int, input().split()))
words = list(input().split())
costs = list(map(int, input().split()))
table = {}
for i in range(k):
group = list(map(int, input().split()))[1:]
gcosts = [costs[j-1] for j in group]
mcost = min(gcosts)
for j in group:
table[words[j-1]] = mcost
msg = li... |
Mr. Kitayuta has just bought an undirected graph consisting of n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.
Mr. Kitayuta wants you to process the following q queries.
In the i-th query, he gives you two integers — ui... | 3 | def DFS(start, color):
global isUsed
isUsed[start] = True
for i in graph[start]:
if not isUsed[i[0]] and i[1] == color:
DFS(i[0], color)
n, m = tuple(map(int, input().split()))
graph = [[] for i in range(n)]
for i in range(m):
a, b, c = tuple(map(int, input().split()))
graph[a... |
There are n boys and m girls attending a theatre club. To set a play "The Big Bang Theory", they need to choose a group containing exactly t actors containing no less than 4 boys and no less than one girl. How many ways are there to choose a group? Of course, the variants that only differ in the composition of the trou... | 1 | n, m, t = map(int, raw_input().split())
min_guys = 4
min_girls = 1
import operator as op
def ncr(n, r):
r = min(r, n-r)
if r == 0: return 1
numer = reduce(op.mul, xrange(n, n-r, -1))
denom = reduce(op.mul, xrange(1, r+1))
return numer//denom
if t < 5:
print('0')
else:
total = 0
#Fo... |
There are n bags with candies, initially the i-th bag contains i candies. You want all the bags to contain an equal amount of candies in the end.
To achieve this, you will:
* Choose m such that 1 ≤ m ≤ 1000
* Perform m operations. In the j-th operation, you will pick one bag and add j candies to all bags apart ... | 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-----... |
We have a string S of length N consisting of `R`, `G`, and `B`.
Find the number of triples (i,~j,~k)~(1 \leq i < j < k \leq N) that satisfy both of the following conditions:
* S_i \neq S_j, S_i \neq S_k, and S_j \neq S_k.
* j - i \neq k - j.
Constraints
* 1 \leq N \leq 4000
* S is a string of length N consisting of... | 3 | n = int(input())
s = input()
ans = s.count("R")*s.count("G")*s.count("B")
for i in range(n):
for j in range(i+1, n):
k = 2*j-i
if k<n:
if s[i] != s[j] and s[i] != s[k] and s[j] != s[k]:
ans -= 1
print(ans) |
Vasya has written some permutation p_1, p_2, …, p_n of integers from 1 to n, so for all 1 ≤ i ≤ n it is true that 1 ≤ p_i ≤ n and all p_1, p_2, …, p_n are different. After that he wrote n numbers next_1, next_2, …, next_n. The number next_i is equal to the minimal index i < j ≤ n, such that p_j > p_i. If there is no su... | 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')
t=int(input())
for u in xrange(t):
n=int(input())
a=list... |
Amugae has a hotel consisting of 10 rooms. The rooms are numbered from 0 to 9 from left to right.
The hotel has two entrances — one from the left end, and another from the right end. When a customer arrives to the hotel through the left entrance, they are assigned to an empty room closest to the left entrance. Similar... | 3 | k=int(input())
list1=input()
list2=[0]*10
for i in list1:
if i=="L":
list2[list2.index(0)]=1
elif i=='R':
list2[len(list2) - 1 - list2[::-1].index(0) ]=1
else:
list2[int(i)]=0
print(''.join(str(i) for i in list2))
|
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 = list(map(int, input().split()))
oranges = list(map(int, input().split()))
empty = []
count = 0
for i in range(0, n[0]):
if oranges[i] <= n[1]:
empty.append(oranges[i])
if sum(empty) > n[2]:
count += 1
empty.clear()
print(count)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.