problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
RedDreamer has an array a consisting of n non-negative integers, and an unlucky integer T.
Let's denote the misfortune of array b having length m as f(b) — the number of pairs of integers (i, j) such that 1 ≤ i < j ≤ m and b_i + b_j = T. RedDreamer has to paint each element of a into one of two colors, white and black... | 3 | test_cases=int(input())
for test_case in range(test_cases):
n,t = list(map(int, input().split()))
a = list(map(int, input().split()))
zero=[]
one=[]
x=t//2
p=[]
count=0
for i in a:
if i>x:
p.append(1)
elif i<x:
p.append(0)
else:
... |
You are given an integer n.
You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times:
1. Replace n with n/2 if n is divisible by 2;
2. Replace n with 2n/3 if n is divisible by 3;
3. Replace n with 4n/5 if n is divisible by 5.
For example, you can repl... | 3 | t=int(input())
for _ in range(t):
n=int(input())
c=0
flag=0
while(1):
if(n%2==0):
n=n//2
c+=1
if(n%3==0):
n=(2*n)//3
c+=1
if(n%5==0):
n=(4*n)//5
c+=1
if(n==1):
break
if(n%5!=0 and ... |
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like.
Now let's imagine a typical morning in your family. You haven't w... | 1 | n = int(raw_input())
myList = map(int, raw_input().split())
totalSum = sum(myList)
myList.sort(reverse=True)
calcSum = 0
count = 0
for i in myList:
calcSum += i
count += 1
if calcSum > totalSum/2:
break
print count |
There are N people. The name of the i-th person is S_i.
We would like to choose three people so that the following conditions are met:
* The name of every chosen person begins with `M`, `A`, `R`, `C` or `H`.
* There are no multiple people whose names begin with the same letter.
How many such ways are there to choo... | 3 | import itertools
n=int(input())
s=[]
for _ in range(n):
s.append(input())
m=[0]*5
p=['M','A','R','C','H']
for x in s:
for i in range(5):
if x[0]==p[i]:
m[i] += 1
ans=0
for v in itertools.combinations(m,3):
ans += v[0]*v[1]*v[2]
print(ans) |
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits.
Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has on... | 3 | #CodeForces
#Beautiful Year
#Python 3.6.5
def isBeautiful(year):
numberSet = set()
for i in year:
if i in numberSet:
return isBeautiful( str(int(year) + 1))
else:
numberSet.add(i)
print(year)
import sys
year = int(input())
isBeautiful(str(year + 1))
|
You are given a positive integer m and two integer sequence: a=[a_1, a_2, …, a_n] and b=[b_1, b_2, …, b_n]. Both of these sequence have a length n.
Permutation is a sequence of n different positive integers from 1 to n. For example, these sequences are permutations: [1], [1,2], [2,1], [6,7,3,4,1,2,5]. These are not: [... | 3 | n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a.sort()
b.sort()
count = 0
while a != b:
d = b[-1] - a[-1]
if d == 0:
d = 1
elif d < 0:
d = m - a[-1]
count += d
a = list(map(lambda k: (k+d) % m, a))
a.sort()
print(count) |
Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers a, b, c on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting e... | 3 | a = int(input())
b = int(input())
c = int(input())
d = []
e = a+b*c
d.append(e)
e = a*b+c
d.append(e)
e = a+b+c
d.append(e)
e = a*b*c
d.append(e)
e = (a+b)*c
d.append(e)
e = a*(b+c)
d.append(e)
print(max(d)) |
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm:
* if the last digit of the number is non-zero, she decreases the number by one;
* if the last digit of the number is ze... | 3 | n, k = input().split()
n = int(n)
k =int(k)
while(k > 0):
if n % 10 == 0:
n = n // 10
else:
n = n - 1
k = k -1
print(n) |
Anton likes to play chess, and so does his friend Danik.
Once they have played n games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie.
Now Anton wonders, who won more games, he or Danik? Help him determine this.
Input
The first line of the input contains a... | 3 | a = int(input())
b = input()
x = y = 0
for i in b :
if i == 'A' :
x += 1
elif i == 'D' :
y += 1
if x > y :
out = 'Anton'
elif x < y :
out = 'Danik'
else :
out = 'Friendship'
print(out) |
Let n be an integer. Consider all permutations on integers 1 to n in lexicographic order, and concatenate them into one big sequence P. For example, if n = 3, then P = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]. The length of this sequence is n ⋅ n!.
Let 1 ≤ i ≤ j ≤ n ⋅ n! be a pair of indices. We call the... | 3 | t = int(input())
res = t
i = 2
while(i<=t):
res = (res-1)*i%998244353
i+=1
print(res) |
You are given one integer number n. Find three distinct integers a, b, c such that 2 ≤ a, b, c and a ⋅ b ⋅ c = n or say that it is impossible to do it.
If there are several answers, you can print any.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 100)... | 3 | #!/usr/bin/env python3
import math
primes = [2]
for n in range(3,math.ceil(math.sqrt(1e9)),2):
is_prime = True
sqrt_n = math.sqrt(n)
for p in primes:
if p > sqrt_n:
break
if n%p == 0:
is_prime = False
break
if is_prime:
primes.append(n)
t =... |
All cities of Lineland are located on the Ox coordinate axis. Thus, each city is associated with its position xi — a coordinate on the Ox axis. No two cities are located at a single point.
Lineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another city (bec... | 3 | def diferenta(x,y):
if x>=0 and y>=0:
return y-x
elif x<=0 and y<=0:
return abs(x)-abs(y)
else:
return abs(x)+y
n = int(input())
l = list(map(int,input().split()))
print(diferenta(l[0],l[1]), diferenta(l[0],l[len(l)-1]))
for i in range (1,len(l)-1):
print(min(diferenta(l[i-1],l... |
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d... | 3 | digits = input()
happy_four = '4'
happy_seven = '7'
happy_digits = [4, 7, 44, 47, 74, 77, 444, 447, 474, 477, 744, 747, 774, 777]
result_happy_digits_list = []
result = 0
for el in digits:
if el == happy_four or el == happy_seven:
result_happy_digits_list.append(el)
for el in happy_digits:
if len(resu... |
Snuke found N strange creatures. Each creature has a fixed color and size. The color and size of the i-th creature are represented by i and A_i, respectively.
Every creature can absorb another creature whose size is at most twice the size of itself. When a creature of size A and color B absorbs another creature of siz... | 3 | import copy
n=int(input())
a=list(map(int,input().split()))
a.sort()
c=i=st=0
while i <n-1:
if 2*(a[st]+c) >= a[i+1]:
c+=a[i+1]
i+=1
else:
c=a[st]+c
st=i+1
i+=1
print(n-st) |
Find the number of integers between 1 and N (inclusive) that contains exactly K non-zero digits when written in base ten.
Constraints
* 1 \leq N < 10^{100}
* 1 \leq K \leq 3
Input
Input is given from Standard Input in the following format:
N
K
Output
Print the count.
Examples
Input
100
1
Output
19
Inpu... | 3 | from functools import lru_cache
N=int(input())
K=int(input())
@lru_cache(None)
def F(N, K):
"""N以下で0でないものがちょうどK個。0を含める"""
# assert N >= 0
if N < 10:
if K == 0:
return 1
if K == 1:
return N
return 0
q,r = divmod(N,10)
ret = 0
if K >= 1:
#... |
You got a box with a combination lock. The lock has a display showing n digits. There are two buttons on the box, each button changes digits on the display. You have quickly discovered that the first button adds 1 to all the digits (all digits 9 become digits 0), and the second button shifts all the digits on the displ... | 1 | import sys
def right(now):
now = now[-1] + now[:-1]
return now
def add1(now):
ret = ""
for x in now:
if x == '9':
x = '0'
else:
x = str(int(x) + 1)
ret += x
return ret
n = int(sys.stdin.readline())
numstr = sys.stdin.readline()
numstr = numstr[... |
Iahub helps his grandfather at the farm. Today he must milk the cows. There are n cows sitting in a row, numbered from 1 to n from left to right. Each cow is either facing to the left or facing to the right. When Iahub milks a cow, all the cows that see the current cow get scared and lose one unit of the quantity of mi... | 3 | from collections import *
from itertools import accumulate
def arr_sum(arr):
arr.appendleft(0)
return list(accumulate(arr, lambda x, y: x + y))
def solve():
ans1, ans0 = 0, 0
for i in range(n):
if a[i]:
ans1 += (n - (i + 1)) - (mem[-1] - mem[i + 1])
else:
ans... |
VK news recommendation system daily selects interesting publications of one of n disjoint categories for each user. Each publication belongs to exactly one category. For each category i batch algorithm selects a_i publications.
The latest A/B test suggests that users are reading recommended publications more actively ... | 3 | """
Author - Satwik Tiwari .
27th Oct , 2020 - Tuesday
"""
#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import Byt... |
Mike has n strings s1, s2, ..., sn each consisting of lowercase English letters. In one move he can choose a string si, erase the first character and append it to the end of the string. For example, if he has the string "coolmike", in one move he can transform it into the string "oolmikec".
Now Mike asks himself: what... | 3 | string_count = int(input())
strings = [input() for _ in range(string_count)]
min_count = float('inf')
for curr_str in strings:
round_count = 0
for str_to_change in strings:
if curr_str == str_to_change:
continue
curr_count = 0
max_count = len(str_to_change)
while st... |
Pasha has two hamsters: Arthur and Alexander. Pasha put n apples in front of them. Pasha knows which apples Arthur likes. Similarly, Pasha knows which apples Alexander likes. Pasha doesn't want any conflict between the hamsters (as they may like the same apple), so he decided to distribute the apples between the hamste... | 3 | naual=list(input().strip().split())
n=int(naual[0])
au=naual[1]
al=naual[2]
#print(n,au,al)
auther=list(map(int,input().strip().split()))
alex=list(map(int,input().strip().split()))
for i in range(1,n+1):
if(au>=al):
if(i in auther):
print("1",end=" ")
elif(i in alex):
print("2",end=" ")
elif(a... |
The School №0 of the capital of Berland has n children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value ti:
* ti = 1, if the i-th child is good at programming,
*... | 3 | n = int(input())
arr = list(map(str,input().split()))
if "1" in arr and "2" in arr and "3" in arr:
mydict = {}
for i in range(len(arr)):
if arr[i] not in mydict:
mydict[arr[i]] = [i+1]
else:
mydict[arr[i]].append(i+1)
arr3 = []
teams = n // 2
for i in range(te... |
The new operating system BerOS has a nice feature. It is possible to use any number of characters '/' as a delimiter in path instead of one traditional '/'. For example, strings //usr///local//nginx/sbin// and /usr/local/nginx///sbin are equivalent. The character '/' (or some sequence of such characters) at the end of ... | 3 | '''for i in range(0, len(s) - 1):
if s[i - 1] != s[i]:
ans += s[i]'''
s = input()
meet = False
#ans = ''
for i in range(len(s) - 1):
if s[i] == '/' and s[i + 1] != '/':
# ans += '/'
print('/', end='')
elif s[i] != '/':
#ans += s[i]
print(s[i], end='')
meet = ... |
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th... | 3 | s = input()
lower = sum(1 for char in s if char.islower())
upper = sum(1 for char in s if char.isupper())
if lower < upper:
print(s.upper())
else:
print(s.lower()) |
When the curtains are opened, a canvas unfolds outside. Kanno marvels at all the blonde colours along the riverside — not tangerines, but blossoms instead.
"What a pity it's already late spring," sighs Mino with regret, "one more drizzling night and they'd be gone."
"But these blends are at their best, aren't they?" ... | 3 | # take risk at the edge of Accepted
Str = input()
for par in ['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA']:
if par in Str:
print('YES')
exit(0)
print('NO')
|
You are playing another computer game, and now you have to slay n monsters. These monsters are standing in a circle, numbered clockwise from 1 to n. Initially, the i-th monster has a_i health.
You may shoot the monsters to kill them. Each shot requires exactly one bullet and decreases the health of the targeted monste... | 3 | #!/usr/bin/env python
from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
def main():
t = int(input())
for _ in range(t):
... |
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 | n=input("")
data=[i for i in n]
dataf=list(set(data))
if(len(dataf)%2==0):
print("CHAT WITH HER!")
else:
print("IGNORE HIM!")
|
The game of Berland poker is played with a deck of n cards, m of which are jokers. k players play this game (n is divisible by k).
At the beginning of the game, each player takes n/k cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he... | 1 | FAST_IO = 0
if FAST_IO:
import io, sys, atexit
rr = iter(sys.stdin.read().splitlines()).next
sys.stdout = _OUTPUT_BUFFER = io.BytesIO()
@atexit.register
def write():
sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
else:
rr = raw_input
rri = lambda: int(rr())
rrm = lambda: map(int, rr().s... |
A card pyramid of height 1 is constructed by resting two cards against each other. For h>1, a card pyramid of height h is constructed by placing a card pyramid of height h-1 onto a base. A base consists of h pyramids of height 1, and h-1 cards on top. For example, card pyramids of heights 1, 2, and 3 look as follows:
... | 3 | import math
t=int(input())
for i in range(t):
n=int(input())
count=0
while(n>0):
x=int((math.sqrt(1+24*n)-1)/6)
if(x>0):
h=int((3*x*x+x)/2)
n=n-h
count+=1
else:
break
print(count)
|
N people are standing in a queue, numbered 1, 2, 3, ..., N from front to back. Each person wears a hat, which is red, blue, or green.
The person numbered i says:
* "In front of me, exactly A_i people are wearing hats with the same color as mine."
Assuming that all these statements are correct, find the number of p... | 3 | N = int(input())
*A, = map(int, input().split())
mod = 10**9 + 7
ans = 1
cnt = [0, 0, 0]
for a in A:
if a not in cnt:
ans = 0
break
ans = ans * cnt.count(a) % mod
cnt[cnt.index(a)] += 1
print(ans)
|
Monocarp had a tree which consisted of n vertices and was rooted at vertex 1. He decided to study BFS ([Breadth-first search](https://en.wikipedia.org/wiki/Breadth-first_search)), so he ran BFS on his tree, starting from the root. BFS can be described by the following pseudocode:
a = [] # the order in whi... | 3 | import sys
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c for j in range(b)] for i in range(a)]
def list3d(a, b, c, d): return [[[d for k in range(c)] for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e for l in range(d)] for k in range(c)] for j in range(b)]... |
Consider the infinite sequence of integers: 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5.... The sequence is built in the following way: at first the number 1 is written out, then the numbers from 1 to 2, then the numbers from 1 to 3, then the numbers from 1 to 4 and so on. Note that the sequence contains numbers, not d... | 3 | import math
n = int(input())
k = math.floor(math.sqrt(2 * n))
z = int(n - k* k / 2 + k / 2) % (k)
if z:
print(z)
else:
print(k)
|
You are given string s consists of opening and closing brackets of four kinds <>, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >.
The following definition of a... | 3 | #!/usr/bin/env python3
import sys
s = input()
OPENING = ('<', '{', '[', '(')
CLOSING = ('>', '}', ']', ')')
result = 0
stack = []
for c in s:
if c in OPENING:
stack.append(c)
else:
if stack:
last_br = stack.pop()
if c != CLOSING[OPENING.index(last_br)]:
... |
One day, Snuke was given a permutation of length N, a_1, a_2, ..., a_N, from his friend.
Find the following:
<image>
Constraints
* 1 ≦ N ≦ 200,000
* (a_1, a_2, ..., a_N) is a permutation of (1, 2, ..., N).
Input
The input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print th... | 3 | n = int(input())
A = list(map(int, input().split()))
A = [a-1 for a in A]
P = [-1]*n
for i, a in enumerate(A):
P[a] = i
R = [n]*n
q = []
import heapq
heapq.heapify(q)
for i in range(n):
while q:
if -q[0] > A[i]:
v = -heapq.heappop(q)
R[v] = i
else:
break
... |
Nikolay has a lemons, b apples and c pears. He decided to cook a compote. According to the recipe the fruits should be in the ratio 1: 2: 4. It means that for each lemon in the compote should be exactly 2 apples and exactly 4 pears. You can't crumble up, break up or cut these fruits into pieces. These fruits — lemons, ... | 3 | import math
from fractions import Fraction as frac
MOD = 1e9 + 7
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
def lcm(a, b):
return a * b // gcd(a, b)
def solve(case_no):
a = int(input())
b = int(input())
c = int(input())
print(min(a, b // 2, c // 4) * 7)
t = 1
# t = ... |
The Monk is trying to explain to its users that even a single unit of time can be extremely important and to demonstrate this particular fact he gives them a challenging task.
There are N processes to be completed by you, the chosen one, since you're Monk's favorite student. All the processes have a unique number as... | 1 | import sys
n = int(sys.stdin.readline().strip())
pca = map(int,sys.stdin.readline().strip().split(' '))
pco = map(int,sys.stdin.readline().strip().split(' '))
t=0 ; i=0 ; j=0 ; k=0;
while i<n:
if pca[j]==-1:
j=(j+1)%n
continue
if pco[i] !=pca[j]:
t+=1
else:
pca[j]=-1;
... |
Alice guesses the strings that Bob made for her.
At first, Bob came up with the secret string a consisting of lowercase English letters. The string a has a length of 2 or more characters. Then, from string a he builds a new string b and offers Alice the string b so that she can guess the string a.
Bob builds b from a... | 3 | def shrt_substr(b):
if len(b)==2:
return b
l = []
l.append(b[0])
for i in range(1,len(b),2):
l.append(b[i])
a = "".join(l)
return a
t = int(input())
for _ in range(t):
b = input()
print(shrt_substr(b)) |
Recently, a chaotic virus Hexadecimal advanced a new theorem which will shake the Universe. She thinks that each Fibonacci number can be represented as sum of three not necessary different Fibonacci numbers.
Let's remember how Fibonacci numbers can be calculated. F0 = 0, F1 = 1, and all the next numbers are Fi = Fi - ... | 3 | n=int(input())
def fun(n):
i=0
j=1
k=1
t=2
while(t!=n):
i,j,k,t=j,k,t,t+k
print(j,i,j)
if(n==0):
print(0,0,0)
elif(n==1):
print(1,0,0)
else:
fun(n) |
Some natural number was written on the board. Its sum of digits was not less than k. But you were distracted a bit, and someone changed this number to n, replacing some digits with others. It's known that the length of the number didn't change.
You have to find the minimum number of digits in which these two numbers c... | 1 |
def binary_search(arr, n):
# find the first idx such that sum(n[:idx]) >= n
lo = -1
hi = len(arr) - 1
while lo + 1 < hi:
mid = (lo + hi) / 2
if arr[mid] >= n:
hi = mid
else:
lo = mid
return hi + 1
def solve(k, n):
# min number of digits two number can differ
n = map(int, n)
temp = k - sum(n)
if ... |
E869120 has A 1-yen coins and infinitely many 500-yen coins.
Determine if he can pay exactly N yen using only these coins.
Constraints
* N is an integer between 1 and 10000 (inclusive).
* A is an integer between 0 and 1000 (inclusive).
Input
Input is given from Standard Input in the following format:
N
A
Output... | 3 | n=int(input())
a=int(input())
print('YNeos'[n%500>a::2]) |
[Sakuzyo - Imprinting](https://www.youtube.com/watch?v=55Ca6av1kAY)
A.R.C. Markland-N is a tall building with n floors numbered from 1 to n. Between each two adjacent floors in the building, there is a staircase connecting them.
It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location... | 3 | from sys import stdin
inp = lambda : stdin.readline().strip()
t = int(inp())
for _ in range(t):
n, s, k = [int(x) for x in inp().split()]
a = set([int(x) for x in inp().split()])
minimum = 10**9
for i in range(1001):
if s+i >n:
break
if s + i not in a :
minimum ... |
You are given a rectangular board of M × N squares. Also you are given an unlimited number of standard domino pieces of 2 × 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squa... | 3 | ar=list(map(int,input().split()))
print((ar[0]*ar[1])//2) |
Masha has n types of tiles of size 2 × 2. Each cell of the tile contains one integer. Masha has an infinite number of tiles of each type.
Masha decides to construct the square of size m × m consisting of the given tiles. This square also has to be a symmetric with respect to the main diagonal matrix, and each cell of ... | 3 | t=int(input())
for i in range(t):
n,m=map(int,input().split(" "))
flag=0
for j in range(n):
q,r = map(int,input().split(" "))
a,b = map(int,input().split(" "))
if r==a:
flag=1
if flag==1 and m%2==0:
print("YES")
else:
... |
Andrey needs one more problem to conduct a programming contest. He has n friends who are always willing to help. He can ask some of them to come up with a contest problem. Andrey knows one value for each of his fiends — the probability that this friend will come up with a problem if Andrey asks him.
Help Andrey choose... | 3 | n = int(input())
l = [float(x) for x in input().split()]
assert len(l) == n
l.sort()
if l[-1] == 1: print("%11.10f"%1)
else:
sig = 0
prod = 1
while sig < 1 and len(l) > 0:
x = l.pop()
sig += x/(1-x)
prod *= (1-x)
print("%11.10f"%(sig*prod))
|
Bob programmed a robot to navigate through a 2d maze.
The maze has some obstacles. Empty cells are denoted by the character '.', where obstacles are denoted by '#'.
There is a single robot in the maze. Its start position is denoted with the character 'S'. This position has no obstacle in it. There is also a single ex... | 3 | n,m=(map(int,input().split()))
lab=[]
for i in range(n):
lab.append(list(input()))
if 'S' in lab[-1]:
rpp=[i,lab[-1].index('S')]
st=input()
cl='urdl'
co=0
for c1 in cl:
for c2 in cl:
if c2==c1:
continue
for c3 in cl:
if c3==c2 or c3==c1:
contin... |
Pashmak decided to give Parmida a pair of flowers from the garden. There are n flowers in the garden and the i-th of them has a beauty number bi. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty difference i... | 3 | n=int(input())
a=list(map(int, input().split()))
x=0
y=0
mini=min(a)
maxi=max(a)
for i in range (n):
if (a[i]==maxi):
x+=1
if (a[i]==mini):
y+=1
if (maxi!=mini):
print(maxi-mini, x*y)
else:
print(0, n*(n-1)//2) |
Petya is preparing for his birthday. He decided that there would be n different dishes on the dinner table, numbered from 1 to n. Since Petya doesn't like to cook, he wants to order these dishes in restaurants.
Unfortunately, all dishes are prepared in different restaurants and therefore Petya needs to pick up his ord... | 3 |
for _ in range (int(input())):
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
c=[[a[i],b[i]] for i in range (n)]
c.sort(key=lambda x:x[0])
min=0
for i in range (n):
min+=c[i][1]
kek=min
k=0
for i in range (n):
k+=c[i][1]
... |
Let s be some string consisting of symbols "0" or "1". Let's call a string t a substring of string s, if there exists such number 1 ≤ l ≤ |s| - |t| + 1 that t = s_l s_{l+1} … s_{l + |t| - 1}. Let's call a substring t of string s unique, if there exist only one such l.
For example, let s = "1010111". A string t = "010... | 3 | import math
import sys
n, k = map(int, input().split())
a = [0] * n
side = (n - k) // 2
for i in range(side, n, side + 1):
a[i] = 1
print(''.join(map(str, a)))
|
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits.
Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has on... | 3 | s=input()
n=int(s)
s=str(n+1)
a=set(map(int,s))
while len(a)<4:
n+=1
s=str(n)
a=set(map(int,s))
print(s)
|
Find the least common multiple (LCM) of given n integers.
Constraints
* 2 ≤ n ≤ 10
* 1 ≤ ai ≤ 1000
* Product of given integers ai(i = 1, 2, ... n) does not exceed 231-1
Input
n
a1 a2 ... an
n is given in the first line. Then, n integers are given in the second line.
Output
Print the least common multiple of th... | 1 | def get_primes(n):
lst = []
for x in xrange(2, n+1):
is_prime = True
for i in xrange(len(lst)):
if x % lst[i] == 0:
is_prime = False
break
if is_prime:
lst.append(x)
return lst
primes = get_primes(1000)
n = int(raw_input())
a = map(int, raw_input().split())
mul_list = {}
f... |
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... | 1 | w = int(raw_input())
assert(1 <= w and w <= 100)
if w > 2 and w % 2 == 0:
print "YES"
else:
print "NO"
|
This problem is different from the hard version. In this version Ujan makes exactly one exchange. You can hack this problem only if you solve both problems.
After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.
Ujan has two distinct str... | 3 | import bisect
import os
from collections import Counter
import bisect
from collections import defaultdict
import math
import random
import heapq as hq
from math import sqrt
import sys
from functools import reduce, cmp_to_key
from collections import deque
import threading
from itertools import combinations
from io impor... |
You are given a string S as input. This represents a valid date in the year 2019 in the `yyyy/mm/dd` format. (For example, April 30, 2019 is represented as `2019/04/30`.)
Write a program that prints `Heisei` if the date represented by S is not later than April 30, 2019, and prints `TBD` otherwise.
Constraints
* S is... | 3 | s = input()
if int(s[5:7]) > 4:
print("TBD")
else:
print("Heisei") |
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 | import math
def main():
n = int(input())
if n%2!=0:
print('No')
else:
if n>2:
print('Yes')
else:
print('No')
if __name__ == '__main__':
main()
|
The city park of IT City contains n east to west paths and n north to south paths. Each east to west path crosses each north to south path, so there are n2 intersections.
The city funded purchase of five benches. To make it seems that there are many benches it was decided to place them on as many paths as possible. Ob... | 1 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import sys, math, random, operator
from string import ascii_lowercase
from string import ascii_uppercase
from fractions import Fraction, gcd
from decimal import Decimal, getcontext
from itertools import product, permutations, combinations
from Queue import Queue, PriorityQue... |
AtCoDeer the deer found two positive integers, a and b. Determine whether the product of a and b is even or odd.
Constraints
* 1 ≤ a,b ≤ 10000
* a and b are integers.
Input
Input is given from Standard Input in the following format:
a b
Output
If the product is odd, print `Odd`; if it is even, print `Even`.
E... | 3 | a, b = [int(i) for i in input().split()]
print(["Even", "Odd"][a * b % 2]) |
So, the Berland is at war with its eternal enemy Flatland again, and Vasya, an accountant, was assigned to fulfil his duty to the nation.
Right now the situation in Berland is dismal — their both cities are surrounded! The armies of flatlanders stand on the borders of circles, the circles' centers are in the surround... | 3 | from math import sqrt
def circle(x1, y1, x2, y2, r1, r2):
dist, r, minimum = sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)), r1 + r2, 0
if dist > r:
minimum = dist - r
elif dist < abs(r1 - r2):
minimum = abs(r1 - r2) - dist
return '{0:.15f}'.format(minimum / 2)
X1, Y1, R1 = [int... |
Mikhail walks on a 2D plane. He can go either up or right. You are given a sequence of Mikhail's moves. He thinks that this sequence is too long and he wants to make it as short as possible.
In the given sequence moving up is described by character U and moving right is described by character R. Mikhail can replace an... | 3 | n =int(input())
s = input()
i = 1
cnt = 0
while i <n:
if s[i]=='U' and s[i-1] =='R':
cnt = cnt+1
i = i+2
continue
if s[i]=='R' and s[i-1]=='U':
cnt = cnt+1
i = i + 2
continue
i = i+1
print(n - cnt)
|
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory.
George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living... | 3 | num=int(input())
c=0
for i in range(num):
p,q=map(int,input().split())
if q >p+1:
c=c+1
print(c) |
Bob has a permutation of integers from 1 to n. Denote this permutation as p. The i-th element of p will be denoted as pi. For all pairs of distinct integers i, j between 1 and n, he wrote the number ai, j = min(pi, pj). He writes ai, i = 0 for all integer i from 1 to n.
Bob gave you all the values of ai, j that he wro... | 3 | a = int(input())
m = []
for i in range(a):
m.append([int(x) for x in input().split()])
minn = set()
minn.add(0)
ans = [0 for i in range(a)]
for k in range(1, a + 1):
for i in range(a):
cont = True
for j in range(a):
if m[i][j] > k or ans[i] != 0:
cont = False
... |
You might have remembered Theatre square from the [problem 1A](https://codeforces.com/problemset/problem/1/A). Now it's finally getting repaved.
The square still has a rectangular shape of n × m meters. However, the picture is about to get more complicated now. Let a_{i,j} be the j-th square in the i-th row of the pav... | 3 | t = int(input())
for _ in range(t):
n,m,x,y = map(int,input().split())
grid = [input() for _ in range(n)]
res = 0
if x*2<=y:
for r in grid:
total = r.count(".")
res += total*x
else:
for r in grid:
total = r.count(".")
double = r.count("... |
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... | 3 | x=input('')
y=input('')
if x.upper()==y.upper():
print(0)
elif x.upper()<y.upper():
print(-1)
elif x.upper()>y.upper():
print(1) |
You are given an array a[0 … n-1] of length n which consists of non-negative integers. Note that array indices start from zero.
An array is called good if the parity of each index matches the parity of the element at that index. More formally, an array is good if for all i (0 ≤ i ≤ n - 1) the equality i mod 2 = a[i] m... | 3 | t=int(input())
for i in range(t):
n=int(input())
l=list(map(int,input().split()))
odd=0
even=0
notequal=0
for i in range(n):
if l[i]%2==i%2:
if l[i]%2==0:
even+=1
else:
odd+=1
else:
notequal+=1
if n%2==0 and ... |
Each evening after the dinner the SIS's students gather together to play the game of Sport Mafia.
For the tournament, Alya puts candies into the box, which will serve as a prize for a winner. To do that, she performs n actions. The first action performed is to put a single candy into the box. For each of the remainin... | 3 | n,k=map(int,input().split())
i=1
s=0
while(i<=n):
s=s+i
if(s-k>=0 and s-k==n-i):
print(n-i)
break
i+=1
|
Ivan is going to sleep now and wants to set his alarm clock. There will be many necessary events tomorrow, the i-th of them will start during the x_i-th minute. Ivan doesn't want to skip any of the events, so he has to set his alarm clock in such a way that it rings during minutes x_1, x_2, ..., x_n, so he will be awak... | 3 | import math
n,m=map(int,input().split())
a=list(map(int,input().split()))
p=list(map(int,input().split()))
diff=[]
for i in range(n-1,0,-1):
diff.append(a[i]-a[i-1])
g=diff[0]
for i in range(n-1):
g=math.gcd(g,diff[i])
ans=0
pj=0
for i in range(m):
if(g%p[i]==0):
pj=i+1
ans=1
break;
if(ans==0):
print("NO")
e... |
In this problem we consider a very simplified model of Barcelona city.
Barcelona can be represented as a plane with streets of kind x = c and y = c for every integer c (that is, the rectangular grid). However, there is a detail which makes Barcelona different from Manhattan. There is an avenue called Avinguda Diagonal... | 3 | import math
l1 = 0
l2 = 0
l3 = 0
l4 = 0
l5 = 0
a,b,c=map(int,input().split())
x1,y1,x2,y2=map(int,input().split())
l = 0
if (a!=0 and b!=0):
if (x1 == x2):
r = max(y1,y2) - min(y1,y2)
elif (y1 == y2):
r = max(x1,x2) - min(x1,x2)
else:
x0 = -1*(b*y1+c)/a
y0 = y... |
During the break the schoolchildren, boys and girls, formed a queue of n people in the canteen. Initially the children stood in the order they entered the canteen. However, after a while the boys started feeling awkward for standing in front of the girls in the queue and they started letting the girls move forward each... | 1 | n,t=map(int,raw_input().split())
x=raw_input()
try:
for i in range(t):
x=x.replace('BG','GB')
print x
except:
print x
|
A new agent called Killjoy invented a virus COVID-2069 that infects accounts on Codeforces. Each account has a rating, described by an integer (it can possibly be negative or very large).
Killjoy's account is already infected and has a rating equal to x. Its rating is constant. There are n accounts except hers, number... | 3 | import sys
import math
import collections
import bisect
import itertools
import decimal
import copy
import heapq
# import numpy as np
# sys.setrecursionlimit(10 ** 6)
INF = 10 ** 20
MOD = 10 ** 9 + 7
# MOD = 998244353
ni = lambda: int(sys.stdin.readline().rstrip())
ns = lambda: map(int, sys.stdin.readline().rstrip()... |
You have two integers l and r. Find an integer x which satisfies the conditions below:
* l ≤ x ≤ r.
* All digits of x are different.
If there are multiple answers, print any of them.
Input
The first line contains two integers l and r (1 ≤ l ≤ r ≤ 10^{5}).
Output
If an answer exists, print any of them. Oth... | 3 | from math import *
def f():
l,r=map(int,input().split())
if len(set(list(str(r))))>=len(list(str(r))):
print(r)
else:
f=0
for i in range(l,r+1):
if len(set(list(str(i))))>=len(list(str(i))):
x=i;f=1;break
if f==1:
print(x)
else:... |
We have a sequence p = {p_1,\ p_2,\ ...,\ p_N} which is a permutation of {1,\ 2,\ ...,\ N}.
You can perform the following operation at most once: choose integers i and j (1 \leq i < j \leq N), and swap p_i and p_j. Note that you can also choose not to perform it.
Print `YES` if you can sort p in ascending order in th... | 3 | input()
*p,=map(int,input().split())
print('YNEOS'[2<sum(1 for i,j in zip(p,sorted(p)) if i!=j)::2]) |
Gardener Alexey teaches competitive programming to high school students. To congratulate Alexey on the Teacher's Day, the students have gifted him a collection of wooden sticks, where every stick has an integer length. Now Alexey wants to grow a tree from them.
The tree looks like a polyline on the plane, consisting o... | 3 | input()
data = sorted(map(int, input().split()))
b = len(data) // 2
print(sum(data[:b])**2 + sum(data[b:])**2)
|
Guy-Manuel and Thomas have an array a of n integers [a_1, a_2, ..., a_n]. In one step they can add 1 to any element of the array. Formally, in one step they can choose any integer index i (1 ≤ i ≤ n) and do a_i := a_i + 1.
If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and T... | 3 | t = int(input())
for i in range(t):
n = int(input())
a = list(map(int, input().split()))
if 0 in a:
x = a.count(0)
if sum(a) + x == 0:
x += 1
print(x)
elif sum(a) == 0:
print(1)
else:
print(0) |
Takahashi loves gold coins. He gains 1000 happiness points for each 500-yen coin he has and gains 5 happiness points for each 5-yen coin he has. (Yen is the currency of Japan.)
Takahashi has X yen. If he exchanges his money so that he will gain the most happiness points, how many happiness points will he earn?
(We as... | 3 | X = int(input())
print((X//500)*1000+(X%500)//5*5) |
Anton is playing a very interesting computer game, but now he is stuck at one of the levels. To pass to the next level he has to prepare n potions.
Anton has a special kettle, that can prepare one potions in x seconds. Also, he knows spells of two types that can faster the process of preparing potions.
1. Spells of... | 3 | import bisect
n, m, k = [int(i) for i in input().split()]
#n:potionNumber, m:firstSpellNumber, k:secondSpellNumber
x, s = [int(i) for i in input().split()]
#x:potion/seconds, s:manapointsNumber
timeOne = [int(i) for i in input().split()]
manaOne = [int(i) for i in input().split()]
numTwo = [int(i) for i in input().spl... |
On a chessboard with a width of n and a height of n, rows are numbered from bottom to top from 1 to n, columns are numbered from left to right from 1 to n. Therefore, for each cell of the chessboard, you can assign the coordinates (r,c), where r is the number of the row, and c is the number of the column.
The white ki... | 3 | n=int(input());x,y=map(int,input().split())
w=[x-1,y-1];w=sum(w)-min(w)
b=[n-x,n-y];b=sum(b)-min(b)
print('White' if w<=b else 'Black')
|
Polycarp decided to relax on his weekend and visited to the performance of famous ropewalkers: Agafon, Boniface and Konrad.
The rope is straight and infinite in both directions. At the beginning of the performance, Agafon, Boniface and Konrad are located in positions a, b and c respectively. At the end of the performa... | 3 | a, b, c, d = map(int, input().split())
a1 = min(a, b, c)
c1 = max(a, b, c)
numbers = [a, b, c]
numbers.remove(a1)
numbers.remove(c1)
b1 = numbers[0]
answer = 0
if c1 - a1 < d:
answer += d - (c1 - a1)
c1 += d - (c1 - a1)
if c1 - b1 < d:
answer += d - (c1 - b1)
c1 += d - (c1 - b1)
if b1 - a1 < d:
answ... |
T is playing a game with his friend, HL.
There are n piles of stones, the i-th pile initially has a_i stones.
T and HL will take alternating turns, with T going first. In each turn, a player chooses a non-empty pile and then removes a single stone from it. However, one cannot choose a pile that has been chosen in th... | 3 | import sys
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): retu... |
Someone gave Alyona an array containing n positive integers a1, a2, ..., an. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not ... | 3 | le = int(input())
n = sorted(map(int, input().split()))
# 1: faccio il sorting
n.sort()
# 2: abbasso tutti fino ad occupare lo spazio più vicino possibile al precedente (senza diventarne uguale)
# il primo ovviamente è 1 in ogni caso
n[0] = 1
for x in range(1,le):
if n[x] > (n[x-1]+1):
n[x] = n[x-1]+1
print (n[-1]... |
There is a binary string a of length n. In one operation, you can select any prefix of a with an equal number of 0 and 1 symbols. Then all symbols in the prefix are inverted: each 0 becomes 1 and each 1 becomes 0.
For example, suppose a=0111010000.
* In the first operation, we can select the prefix of length 8 sin... | 3 | # template begins
#####################################
from io import BytesIO, IOBase
import sys
import math
import os
from collections import defaultdict
from math import ceil
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
... |
Santa has n candies and he wants to gift them to k kids. He wants to divide as many candies as possible between all k kids. Santa can't divide one candy into parts but he is allowed to not use some candies at all.
Suppose the kid who recieves the minimum number of candies has a candies and the kid who recieves the max... | 3 | t = int(input())
for i in range(t):
n, k = map(int, input().split())
print((n // k) * k + min(n - (n // k) * k, k // 2))
|
Two famous competing companies ChemForces and TopChemist decided to show their sets of recently discovered chemical elements on an exhibition. However they know that no element should be present in the sets of both companies.
In order to avoid this representatives of both companies decided to make an agreement on the ... | 3 | from collections import defaultdict
d = defaultdict(int)
for _ in range(int(input())):
a,x = map(int, input().split())
d[a] = x
for _ in range(int(input())):
b,y = map(int, input().split())
d[b] = max(d[b], y)
print(sum(d.values())) |
Polycarp has guessed three positive integers a, b and c. He keeps these numbers in secret, but he writes down four numbers on a board in arbitrary order — their pairwise sums (three numbers) and sum of all three numbers (one number). So, there are four numbers on a board in random order: a+b, a+c, b+c and a+b+c.
You h... | 3 | inp = [int(x) for x in input().split()]
maximal = max(inp)
inp.remove(maximal)
string = ""
for x in inp:
string += str(maximal-x) + " "
print(string[:-1]) |
Today on Informatics class Nastya learned about GCD and LCM (see links below). Nastya is very intelligent, so she solved all the tasks momentarily and now suggests you to solve one of them as well.
We define a pair of integers (a, b) good, if GCD(a, b) = x and LCM(a, b) = y, where GCD(a, b) denotes the [greatest commo... | 3 | from math import sqrt
def p_divs(n):
_a = []
for _i in range(2,int(sqrt(n)) + 10):
while n % _i == 0:
_a.append(_i)
n //= _i
if n > 1:
_a.append(n)
return _a
l, r, x, y = map(int, input().split())
if y % x != 0:
print(0)
else:
m = y // x
divs = p_divs(m)
d = dict()
for p in ... |
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d... | 3 | a = input()
num = a.count('4') + a.count('7')
if num == 4 or num == 7:
print('YES')
else:
print('NO') |
Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him.
One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For e... | 3 | input()
n = list(map(int, input().split(" ")))
mn, mx, count = n[0], n[0], 0
for i in range(1, len(n)):
if n[i] > mx:
mx = n[i]
count += 1
elif n[i] < mn:
mn = n[i]
count += 1
print(count) |
There are N children, numbered 1, 2, \ldots, N.
They have decided to share K candies among themselves. Here, for each i (1 \leq i \leq N), Child i must receive between 0 and a_i candies (inclusive). Also, no candies should be left over.
Find the number of ways for them to share candies, modulo 10^9 + 7. Here, two way... | 3 | mod = 10**9+7
N, K = map(int, input().split())
a = list(map(int, input().split()))
dp = [[0]*(K+1) for i in range(N+1)]
S = [0] * (K+2)
dp[0][0] = 1
for i in range(1,N+1):
for j in range(1,K+2):
S[j] = (S[j-1] + dp[i-1][j-1])%mod
for j in range(K+1):
dp[i][j] = (S[j+1] - S[max(0, j-a[i-1])])%mod... |
Lord Omkar has permitted you to enter the Holy Church of Omkar! To test your worthiness, Omkar gives you a password which you must interpret!
A password is an array a of n positive integers. You apply the following operation to the array: pick any two adjacent numbers that are not equal to each other and replace them ... | 3 | t = int(input())
n = 0
arr = []
for k in range(t):
n = int(input())
arr = input().split()
arr = [int(arr[i]) for i in range(n)]
#print(arr)
if max(arr) == min(arr):
print(n)
else:
print(1)
|
You have a string s consisting of n characters. Each character is either 0 or 1.
You can perform operations on the string. Each operation consists of two steps:
1. select an integer i from 1 to the length of the string s, then delete the character s_i (the string length gets reduced by 1, the indices of characters ... | 3 | from collections import deque
def read_int() -> int:
return int(input())
def read_ints():
return map(int, input().split(' '))
def test_case():
_ = read_int()
input_string = input()
cnt = 0
sizes_queue = deque()
prev = None
for cur in input_string:
if prev == cur:
... |
[3R2 as DJ Mashiro - Happiness Breeze](https://open.spotify.com/track/2qGqK8GRS65Wlf20qUBEak)
[Ice - DJ Mashiro is dead or alive](https://soundcloud.com/iceloki/dj-mashiro-is-dead-or-alive)
NEKO#ΦωΦ has just got a new maze game on her PC!
The game's main puzzle is a maze, in the forms of a 2 × n rectangle grid. NEKO... | 3 | # -*- coding: utf-8 -*-
import sys
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a... |
Chilly Willy loves playing with numbers. He only knows prime numbers that are digits yet. These numbers are 2, 3, 5 and 7. But Willy grew rather bored of such numbers, so he came up with a few games that were connected with them.
Chilly Willy wants to find the minimum number of length n, such that it is simultaneously... | 1 | L = [50, 80, 170, 20, 200, 110]
n = int(raw_input())
if (n < 3):
print -1
elif (n == 3):
print 210
else:
print('1' + '0' * (n - 1 - len(str(L[(n + 2) % 6]))) + str(L[(n + 2) % 6])) |
You are given a string s consisting of n lowercase Latin letters. Polycarp wants to remove exactly k characters (k ≤ n) from the string s. Polycarp uses the following algorithm k times:
* if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;
* if th... | 3 | def calc(n,k,a):
dic={}
lis=[]
val=k
for i in a:
if i in dic:
dic[i]+=1
else:
dic[i]=1
lis.append(i)
dic2={}
lis.sort()
# print(lis)
for i in lis:
if val==0:
break
else:
dic2[i]=0
whil... |
Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.
There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th ho... | 1 | n, m, k = map(int, raw_input().split())
a = [[] for i in xrange(n)]
for i in xrange(n):
s = raw_input()
for j in xrange(m):
if s[j] == '1': a[i].append(j)
w = [([0] * (k + 1)) for i in xrange(n)]
for i in xrange(n):
if len(a[i]) == 0: continue
for j in xrange(k + 1):
if len(a[i]) > j:
... |
Ilya is a very clever lion, he lives in an unusual city ZooVille. In this city all the animals have their rights and obligations. Moreover, they even have their own bank accounts. The state of a bank account is an integer. The state of a bank account can be a negative number. This means that the owner of the account ow... | 3 | n = input()
n1 = int(n[:len(n)-1])
n2 = int(n[:len(n)-2]+n[len(n)-1])
n = int(n)
print(max(n,n1,n2)) |
You are given an array of integers. Vasya can permute (change order) its integers. He wants to do it so that as many as possible integers will become on a place where a smaller integer used to stand. Help Vasya find the maximal number of such integers.
For instance, if we are given an array [10, 20, 30, 40], we can pe... | 3 | n = int(input())
a = list(map(int, input().split()))
Mp = dict()
for e in a:
if(e in Mp):
Mp[e]+=1
else:
Mp[e]=1
mx=-1
for k in Mp:
mx = max(mx, Mp[k])
print(n-mx)
|
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm:
* if the last digit of the number is non-zero, she decreases the number by one;
* if the last digit of the number is ze... | 3 | a, b = map(int, input().split())
for i in range(b):
if(a%10 == 0):
a /= 10
else:
a -= 1
print(int(a))
|
Formula One championship consists of series of races called Grand Prix. After every race drivers receive points according to their final position. Only the top 10 drivers receive points in the following order 25, 18, 15, 12, 10, 8, 6, 4, 2, 1. At the conclusion of the championship the driver with most points is the cha... | 1 | from itertools import *
from collections import defaultdict
t = input ()
bonus = [25, 18, 15, 12, 10, 8, 6, 4, 2, 1] + [0] * 40
score = defaultdict (int)
bestplace = defaultdict (list)
for races in xrange (t):
for place in xrange (input ()):
name = raw_input ()
score[name] += bonus[place]
... |
Polycarp and his friends want to visit a new restaurant. The restaurant has n tables arranged along a straight line. People are already sitting at some tables. The tables are numbered from 1 to n in the order from left to right. The state of the restaurant is described by a string of length n which contains characters ... | 3 | t = int(input())
while t > 0:
n, k = map(int, input().split())
string = input()
prevOff = k
forwOff = k
seats = 0
prevLi = []
forwLi = []
for i in range(len(string)):
if string[i] == '1':
prevOff = 0
prevLi.append(0)
if string[i] == '0':
... |
You will be given a contest schedule for D days. For each d=1,2,\ldots,D, calculate the satisfaction at the end of day d.
Input
Input is given from Standard Input in the form of the input of Problem A followed by the output of Problem A.
D
c_1 c_2 \cdots c_{26}
s_{1,1} s_{1,2} \cdots s_{1,26}
\vdots
s_{D,1} s_{D,... | 3 | D=int(input())
c=list(map(int,input().split()))
s=[list(map(int,input().split())) for _ in range(D)]
last=[0]*26
ans=0
for d in range(1,D+1):
choice=int(input())
ans+=s[d-1][choice-1]
last[choice-1]=d
for i in range(26):
ans-=c[i]*(d-last[i])
print(ans) |
Allen is hosting a formal dinner party. 2n people come to the event in n pairs (couples). After a night of fun, Allen wants to line everyone up for a final picture. The 2n people line up, but Allen doesn't like the ordering. Allen prefers if each pair occupies adjacent positions in the line, as this makes the picture m... | 3 | #!/usr/bin/env python3
n = int(input().strip())
ais = list(map(int, input().strip().split()))
cnt = 0
while len(ais) > 0:
a = ais[0]
del ais[0]
i = ais.index(a)
cnt += i
del ais[i]
print (cnt)
|
It's one more school day now. Sasha doesn't like classes and is always bored at them. So, each day he invents some game and plays in it alone or with friends.
Today he invented one simple game to play with Lena, with whom he shares a desk. The rules are simple. Sasha draws n sticks in a row. After that the players tak... | 3 | n,m=map(int,input().split())
d=n//m
if d%2==1:
print("YES")
else:
print("NO") |
You are given two integers a and b. You may perform any number of operations on them (possibly zero).
During each operation you should choose any positive integer x and set a := a - x, b := b - 2x or a := a - 2x, b := b - x. Note that you may choose different values of x in different operations.
Is it possible to mak... | 3 | t=int(input())
for i in range(t):
a,b=input().split()
a,b=int(a),int(b)
if a>=b:
a,b=b,a
if (a+b)%3==0 and 2*a>=b:
print("YES")
continue
else:
print("NO")
continue |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.