problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
You have a string s of length n consisting of only characters > and <. You may do some operations with this string, for each operation you have to choose some character that still remains in the string. If you choose a character >, the character that comes right after it is deleted (if the character you chose was the l... | 3 | import sys
import math
from collections import defaultdict,deque
input = sys.stdin.readline
def inar():
return [int(el) for el in input().split()]
def main():
t=int(input())
for _ in range(t):
n=int(input())
st=input().strip()
ans1=10**18
for i in range(n-1,-1,-1):
... |
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line.
Unfortunately, from time to ti... | 3 | letters = input()
letters = letters.replace("{", "")
letters = letters.replace("}", "")
letters = letters.replace(",", "")
letters_list = letters.split(" ")
letters_set = set(letters_list)
count = 0
for letter in letters_set :
if letter == "" :
count += 0
else :
count = len(letters_set)
print(co... |
Olesya loves numbers consisting of n digits, and Rodion only likes numbers that are divisible by t. Find some number that satisfies both of them.
Your task is: given the n and t print an integer strictly larger than zero consisting of n digits that is divisible by t. If such number doesn't exist, print - 1.
Input
T... | 3 | n,t=map(int,input().split())
a='1'+'0'*(n-1)
b='9'*(n)
a=int(a)
b=int(b)
for i in range(a,b+1):
if int(i)%t==0:
print(i)
exit()
print(-1)
exit() |
Pasha loves to send strictly positive integers to his friends. Pasha cares about security, therefore when he wants to send an integer n, he encrypts it in the following way: he picks three integers a, b and c such that l ≤ a,b,c ≤ r, and then he computes the encrypted value m = n ⋅ a + b - c.
Unfortunately, an adversa... | 1 | from __future__ import print_function
import sys
import math
import time
import random
if sys.subversion[0] == "PyPy":
import io, atexit
sys.stdout = io.BytesIO()
atexit.register(lambda: sys.__stdout__.write(sys.stdout.getvalue()))
sys.stdin = io.BytesIO(sys.stdin.read())
input = lambda: sys.std... |
A number is ternary if it contains only digits 0, 1 and 2. For example, the following numbers are ternary: 1022, 11, 21, 2002.
You are given a long ternary number x. The first (leftmost) digit of x is guaranteed to be 2, the other digits of x can be 0, 1 or 2.
Let's define the ternary XOR operation ⊙ of two ternary n... | 3 | # from sys import stdin
# inf=stdin
for _ in range(int(input())):
n=int(input())
num=input()
num1=[1]
num2=[1]
equal=True
for i in range(1,n):
if(not equal):
num1.append('0')
num2.append(num[i])
continue
if(num[i]=='2'):
num1.append('1')
num2.append('1')
elif(num[i]=='3'):
num1.append('... |
Ann has recently started commuting by subway. We know that a one ride subway ticket costs a rubles. Besides, Ann found out that she can buy a special ticket for m rides (she can buy it several times). It costs b rubles. Ann did the math; she will need to use subway n times. Help Ann, tell her what is the minimum sum of... | 3 | x=[int(q) for q in input().split()]
n=x[0]
m=x[1]
a=x[2]
b=x[3]
ans = min((n//m)*b + (n%m)*a, (n//m + 1)*b,n*a)
print(ans) |
Theatre Square in the capital city of Berland has a rectangular shape with the size n × m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a × a.
What is the least number of flagstones needed to pave the Square? It'... | 1 | inputs = raw_input()
arr = inputs.split(" ")
n = int(arr[0])
m = int(arr[1])
a = int(arr[2])
result = 0
if m%a != 0:
result = (m/a) + 1
else:
result = m/a
if n%a != 0:
result *= (n/a) + 1
else:
result *= n/a
print str(result) |
There are three houses on a number line: House 1, 2 and 3, with coordinates A, B and C, respectively. Print `Yes` if we pass the coordinate of House 3 on the straight way from House 1 to House 2 without making a detour, and print `No` otherwise.
Constraints
* 0\leq A,B,C\leq 100
* A, B and C are distinct integers.
I... | 3 | a, b, c = map(int, input().split())
print('Yes' if (a<=c<=b) or (a>=c>=b) else 'No')
|
Pasha loves his phone and also putting his hair up... But the hair is now irrelevant.
Pasha has installed a new game to his phone. The goal of the game is following. There is a rectangular field consisting of n row with m pixels in each row. Initially, all the pixels are colored white. In one move, Pasha can choose an... | 3 | if __name__ == '__main__':
n, m, k = map(int, input().split())
field = [[False for _ in range(m)] for _ in range(n)]
flag = False
for i in range(k):
x, y = map(int, input().split())
x -= 1
y -= 1
field[x][y] = True
if 0 < x:
if 0 < y:
f... |
There is an empty array. The following N operations will be performed to insert integers into the array. In the i-th operation (1≤i≤N), b_i copies of an integer a_i are inserted into the array. Find the K-th smallest integer in the array after the N operations. For example, the 4-th smallest integer in the array \\{1,2... | 1 | from collections import defaultdict
n,k = map(int, raw_input().split())
d = defaultdict(int)
for _ in range(n):
a,b = map(int, raw_input().split())
d[a] += b
s = 0
for p in sorted(d.keys()):
if k <= s + d[p]:
print p
break
s += d[p]
|
There was an electronic store heist last night.
All keyboards which were in the store yesterday were numbered in ascending order from some integer number x. For example, if x = 4 and there were 3 keyboards in the store, then the devices had indices 4, 5 and 6, and if x = 10 and there were 7 of them then the keyboards ... | 3 | import sys
import math as mt
import bisect
input=sys.stdin.readline
#t=int(input())
t=1
for _ in range(t):
n=int(input())
#n,q=map(int,input().split())
#x,y,k=map(int,input().split())
l=list(map(int,input().split()))
#l2=list(map(int,input().split()))
mini=min(l[:])
maxi=max(l[:]... |
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.
The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe... | 1 | s = raw_input()
l = []
for i in xrange(len(s)):
if i%2==0:
l.append(int(s[i]))
l = sorted(l)
st = ''.join(str(i) for i in l)
print "+".join(st)
|
There are n employees in Alternative Cake Manufacturing (ACM). They are now voting on some very important question and the leading world media are trying to predict the outcome of the vote.
Each of the employees belongs to one of two fractions: depublicans or remocrats, and these two fractions have opposite opinions o... | 3 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
class lq(list):
def __init__(self):
self.value=[]
self.lenght=0
self.startPos=0
self.maxLen = 50000
def append(self, item):
self.value.append(item)
self.lenght+=1
def pop(self):
if self.startPos < self.maxLen:
rv= self.value[self.startPos]
self.len... |
Wabbit is trying to move a box containing food for the rest of the zoo in the coordinate plane from the point (x_1,y_1) to the point (x_2,y_2).
He has a rope, which he can use to pull the box. He can only pull the box if he stands exactly 1 unit away from the box in the direction of one of two coordinate axes. He will... | 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)]... |
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it [here](http://tiny.cc/636xmz).
The picture showing the correct sudoku solution:
<image>
Blocks are bordered with bold black color.
Your task is to change at most 9 elements of this field (i.e. choose s... | 3 | from heapq import *
from collections import *
import os
import sys
from io import BytesIO, IOBase
import math
ins = lambda: [int(x) for x in input()]
inp = lambda: int(input())
inps = lambda: [int(x) for x in input().split()]
def main():
t=inp()
for i in range(t):
sud=[]
for i in range(9):
... |
Mishka wants to buy some food in the nearby shop. Initially, he has s burles on his card.
Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1 ≤ x ≤ s, buy food that costs exactly x burles and obtain ⌊x/10⌋ burles as a cashback (in other words, Mishka ... | 3 | def process(n):
ans = 0
while n >= 10:
tmp = n // 10
cur_spending = tmp * 10
ans += cur_spending
n = n % 10 + tmp
ans += n
return ans
T = int(input())
for t in range(T):
print(process(int(input()))) |
Alice has a cute cat. To keep her cat fit, Alice wants to design an exercising walk for her cat!
Initially, Alice's cat is located in a cell (x,y) of an infinite grid. According to Alice's theory, cat needs to move:
* exactly a steps left: from (u,v) to (u-1,v);
* exactly b steps right: from (u,v) to (u+1,v); ... | 3 | res = []
t = int(input())
for t_curr in range(t):
a, b, c, d = [int(x) for x in input().split()]
x, y, x1, y1, x2, y2 = [int(x) for x in input().split()]
final_x = x - a + b
final_y = y - c + d
check = False
if x1 <= final_x <= x2 and y1 <= final_y <= y2:
check = True
if a * b > 0 ... |
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... | 3 | def newyear(n,k):
r=240-k
count=0
for i in range(n):
if (5*(i+1))<=r:
count=count+1
r=r-(5*(i+1))
return count
n,k=map(int,input().split())
print(newyear(n, k))
|
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory.
George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living... | 3 | n = int(input())
number = 0
for i in range(n):
pq= input().split(" ")
p = int(pq[0])
q = int(pq[1])
if q-p>=2:
number+=1
print(number)
|
Chef Al Gorithm was reading a book about climate and oceans when he encountered the word “glaciological”. He thought it was quite curious, because it has the following interesting property: For every two letters in the word, if the first appears x times and the second appears y times, then |x - y| ≤ 1.
Chef Al was happ... | 1 | #cnexans
test_cases = int(raw_input())
for case in range(0, test_cases):
line = raw_input().strip(' ').split()
word = list(line[0].lower())
k = int(line[1])
unique = list(set(word))
numbers = [len([v for v in word if v == letter]) for letter in unique]
total = []
for minimum in number... |
Theatre Square in the capital city of Berland has a rectangular shape with the size n × m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a × a.
What is the least number of flagstones needed to pave the Square? It'... | 3 | n, m, a = map(int, input().split(' '))
x = n // a
y = m // a
if n%a:
x=x+1
if m%a:
y=y+1
print (x*y)
|
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 | def coverBoard(m, n):
return (m * n) // 2
if __name__ == "__main__":
m, n = input().split(" ")
print(coverBoard(int(m), int(n))) |
Takahashi is participating in a programming contest called AXC002, and he has just submitted his code to Problem A.
The problem has N test cases.
For each test case i (1\leq i \leq N), you are given a string S_i representing the verdict for that test case. Find the numbers of test cases for which the verdict is `AC`,... | 3 | n=int(input())
l=[input()for i in range(n)]
for i in ["AC","WA","TLE","RE"]:
print(i,"x",l.count(i)) |
Eighth-grader Vova is on duty today in the class. After classes, he went into the office to wash the board, and found on it the number n. He asked what is this number and the teacher of mathematics Inna Petrovna answered Vova that n is the answer to the arithmetic task for first-graders. In the textbook, a certain posi... | 3 | def decnums(n):
v=[]
dec=10
while n>=dec:
v.append(n%dec)
n=n//dec
v.append(n)
return v
def iscornum(n,c):
sumnums=sum(decnums(c))
return n==c+sumnums
n=int(input())
v=[]
delta=len(decnums(n))
for c in range(n-1,n-9*delta,-1):
if c<=0:
break
if iscornum(n,c):
v.append(c)
print(len(v))
v.sort()
for c ... |
You are given two positive integers A and B. Compare the magnitudes of these numbers.
Constraints
* 1 ≤ A, B ≤ 10^{100}
* Neither A nor B begins with a `0`.
Input
Input is given from Standard Input in the following format:
A
B
Output
Print `GREATER` if A>B, `LESS` if A<B and `EQUAL` if A=B.
Examples
Input
3... | 1 | a = input()
b = input()
if a > b:
print "GREATER"
elif a == b:
print "EQUAL"
else:
print "LESS"
|
One day, n people (n is an even number) met on a plaza and made two round dances, each round dance consists of exactly n/2 people. Your task is to find the number of ways n people can make two round dances if each round dance consists of exactly n/2 people. Each person should belong to exactly one of these two round da... | 3 | n = 43
# fac = list()
fac = [1]
for i in range(1,n):
fac.append(i*fac[-1])
# print(fac)
n = int(input())
n-=2
x = int(fac[n +1]/(n//2+1))
print(x) |
There are some beautiful girls in Arpa’s land as mentioned before.
Once Arpa came up with an obvious problem:
Given an array and a number x, count the number of pairs of indices i, j (1 ≤ i < j ≤ n) such that <image>, where <image> is bitwise xor operation (see notes for explanation).
<image>
Immediately, Mehrdad d... | 3 | n,x=map(int,input().split())
l=list(map(int,input().split()))
from collections import defaultdict
d=defaultdict(int)
ans=0
for i in l:
d[i]+=1
for j in l:
a=j^x
if d[a]>0 and a>j:
ans+=d[a]
elif d[a]>0 and a==j:
ans+=(d[a]*(d[a]-1))//2
d[a]=0
print(ans)
|
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc.... | 3 | li = input()
le = input()
if le == li[::-1]:
print('YES')
else:
print('NO')
|
Caisa is going to have a party and he needs to buy the ingredients for a big chocolate cake. For that he is going to the biggest supermarket in town.
Unfortunately, he has just s dollars for sugar. But that's not a reason to be sad, because there are n types of sugar in the supermarket, maybe he able to buy one. But t... | 3 | n, s = map(int, input().split())
res = []
for sugar in range(n):
dollars, cents = map(int, input().split())
if dollars < s:
if (100 - cents) < 100:
res.append(100 - cents)
if dollars <= s and cents == 0:
res.append(0)
if len(res) == 0:
print(-1)
else:
print(max(res))... |
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 | #23 elephant
n=int(input())
print(n//5+1 if n%5!=0 else n//5) |
Sereja and Dima play a game. The rules of the game are very simple. The players have n cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The ... | 3 | n = int(input())
cards = input()
cards = cards.split();
p1 = 0
p2 = 0
for i in range((n+1)//2):
if(len(cards) != 0):
temp1 = max(int(cards[0]),int(cards[-1]))
p1 += int(temp1)
cards.remove(str(temp1))
if(len(cards) != 0):
temp2 = max(int(cards[0]),int(cards[-1]))
p2 += i... |
Recently, you bought a brand new smart lamp with programming features. At first, you set up a schedule to the lamp. Every day it will turn power on at moment 0 and turn power off at moment M. Moreover, the lamp allows you to set a program of switching its state (states are "lights on" and "lights off"). Unfortunately, ... | 3 | n, m = map(int, input().split())
l= sorted(list(map(int, input().split())) + [0, m])
sum_list= [l[i+1] - l[i] for i in range(len(l) - 1)]
insert=sum(sum_list[1::2])+sum_list[0]-1
result=max(sum(sum_list[::2]),insert)
for i in range(2,len(sum_list),2):
insert=insert+sum_list[i]-sum_list[i-1]
if insert>result:
... |
After the mysterious disappearance of Ashish, his two favourite disciples Ishika and Hriday, were each left with one half of a secret message. These messages can each be represented by a permutation of size n. Let's call them a and b.
Note that a permutation of n elements is a sequence of numbers a_1, a_2, …, a_n, in ... | 3 | """
____ _ _____
/ ___|___ __| | ___| ___|__ _ __ ___ ___ ___
| | / _ \ / _` |/ _ \ |_ / _ \| '__/ __/ _ \/ __|
| |__| (_) | (_| | __/ _| (_) | | | (_| __/\__ \
\____\___/ \__,_|\___|_| \___/|_| \___\___||___/
"""
"""
░░██▄░░░░░░░░░░░▄██
░▄▀░█▄░░░░░░░░▄█░░█░
░█░▄░█▄░░░░░░▄█░▄░█░
░█░██████... |
Bertown is a city with n buildings in a straight line.
The city's security service discovered that some buildings were mined. A map was compiled, which is a string of length n, where the i-th character is "1" if there is a mine under the building number i and "0" otherwise.
Bertown's best sapper knows how to activate... | 1 | for _ in range(input()):
a,b=map(int,raw_input().split())
s=raw_input()
cost=0
ones=[]
for i in range(len(s)):
if s[i]=='1':
ones.append(i)
if ones==[]:
print 0
continue
cost=a
for i in range(len(ones)-1):
if ones[i+1]-ones[i]==1:
c... |
You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.
Sorting integers in a subsequence is... | 3 | import os,io
input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n=int(input())
a=list(map(int,input().split()))
b=[]
for i in range(n):
b.append([a[i],i])
b.sort()
destinations=[0]*n
inverses=[0]*n
for i in range(n):
y=b[i][1]
destinations[i]=y
inverses[y]=i
visited=[0]*n
k=[]
for i in range(n):
if vis... |
Despite his bad reputation, Captain Flint is a friendly person (at least, friendly to animals). Now Captain Flint is searching worthy sailors to join his new crew (solely for peaceful purposes). A sailor is considered as worthy if he can solve Flint's task.
Recently, out of blue Captain Flint has been interested in ma... | 3 | import sys
input = sys.stdin.readline
for _ in range(int(input())):
n = int(input())
if n<=30:
print("NO")
else:
print("YES")
if n==36: print(6,10,15,5)
elif n==40: print(6,10,15,9)
elif n==44: print(6,10,15,13)
else: print(6,10,14,n-(6+10+14))
|
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 | mod = 10**9 + 7
import math
def ain():
return map(int, input().split())
for _ in range(int(input())):
a,b = ain()
sol = (a - a%b) + min( b//2, a%b )
print(int(sol))
# python3 pan.py
|
You are given two integers n and m. You have to construct the array a of length n consisting of non-negative integers (i.e. integers greater than or equal to zero) such that the sum of elements of this array is exactly m and the value ∑_{i=1}^{n-1} |a_i - a_{i+1}| is the maximum possible. Recall that |x| is the absolut... | 3 | for t in range(int(input())):
n,m = map(int, input().split())
if n==1:
print(0)
continue
if n==2:
print(m)
continue
mod = m%n
answer = m*2
print(answer)
|
You are given a 4-character string S consisting of uppercase English letters. Determine if S consists of exactly two kinds of characters which both appear twice in S.
Constraints
* The length of S is 4.
* S consists of uppercase English letters.
Input
Input is given from Standard Input in the following format:
S
... | 3 | S=list(input())
A=len(set(S))
if A==2:
print("Yes")
else:
print("No") |
Ivan has a robot which is situated on an infinite grid. Initially the robot is standing in the starting cell (0, 0). The robot can process commands. There are four types of commands it can perform:
* U — move from the cell (x, y) to (x, y + 1);
* D — move from (x, y) to (x, y - 1);
* L — move from (x, y) to (x... | 3 | num=int(input())
string=input()
u=string.count("U")
d=string.count("D")
l=string.count("L")
r=string.count("R")
print(2*min(u,d)+2*min(l,r))
|
Write a program which calculates the area and circumference of a circle for given radius r.
Constraints
* 0 < r < 10000
Input
A real number r is given.
Output
Print the area and circumference of the circle in a line. Put a single space between them. The output should not contain an absolute error greater than 10-... | 1 | r = map(float,raw_input().split())
print '%.10f'%(r[0]*r[0]*3.14159265358979323846)
print '%.10f'%(r[0]*2*3.14159265358979323846) |
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.
This new device is equipped with specially designed artificial intelligence (AI). Employees of Pine... | 3 | import sys
import re
a = sys.stdin.readline().strip()
b = sys.stdin.readline().strip()
print(len(re.findall(b, a)))
|
The last contest held on Johnny's favorite competitive programming platform has been received rather positively. However, Johnny's rating has dropped again! He thinks that the presented tasks are lovely, but don't show the truth about competitors' skills.
The boy is now looking at the ratings of consecutive participan... | 3 | t = int(input())
for i in range(t):
n = int(input())
ans2 = 0
num2 = 1
while num2 <= n:
ans2 += n // num2
num2 *= 2
print(ans2)
|
You are given three strings a, b and c of the same length n. The strings consist of lowercase English letters only. The i-th letter of a is a_i, the i-th letter of b is b_i, the i-th letter of c is c_i.
For every i (1 ≤ i ≤ n) you must swap (i.e. exchange) c_i with either a_i or b_i. So in total you'll perform exactly... | 3 | T = int(input())
for _ in range(T):
A = input()
B = input()
C = input()
N = len(A)
for i in range(N):
if not (A[i] == C[i] or B[i] == C[i]):
print("NO")
break
else:
print("YES")
|
The mayor of Amida, the City of Miracle, is not elected like any other city. Once exhausted by long political struggles and catastrophes, the city has decided to leave the fate of all candidates to the lottery in order to choose all candidates fairly and to make those born under the lucky star the mayor. I did. It is a... | 3 | while True:
n, m, a = map(int, input().split())
if n==0 and m==0 and a==0:
break
branch = [[0 for _ in range(1001)] for _ in range(n+1)]
for i in range(m):
h, p, q = map(int, input().split())
branch[p][h] = q
branch[q][h] = p
cur = a
for i in range(1000, 0, -1):... |
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())
sum=0
max=0
for i in range(0,n):
a=input().split()
sum+=int(a[1])-int(a[0])
if(sum>max):
max=sum
print(max) |
A class of students wrote a multiple-choice test.
There are n students in the class. The test had m questions, each of them had 5 possible answers (A, B, C, D or E). There is exactly one correct answer for each question. The correct answer for question i worth a_i points. Incorrect answers are graded with zero points.... | 3 |
n, m = map(int, input().split())
tmp = [''] * m
final = 0
z = 'A', 'B', 'C', 'D', 'E'
for i in range(n):
temp = input()
for j in range(m):
tmp[j] += temp[j]
score = list(map(int, input().split()))
for i in range(m):
final += (max(tmp[i].count(k) for k in z) * score[i])
print(final)
|
We have a secret array. You don't know this array and you have to restore it. However, you know some facts about this array:
* The array consists of n distinct positive (greater than 0) integers.
* The array contains two elements x and y (these elements are known for you) such that x < y.
* If you sort the arr... | 3 | from functools import reduce
def factors(n):
return set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))
for i in range(int(input())):
n,x,y = list(map(int , input().split()))
diff = y-x;
fact = factors(diff)
finallis = []
for i in fact:
lis = []
... |
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Bi... | 3 | n = int(input())
if n <= 2:
print("NO")
elif n & 1 == 1:
print("NO")
else:
print("YES") |
Bob is a competitive programmer. He wants to become red, and for that he needs a strict training regime. He went to the annual meeting of grandmasters and asked n of them how much effort they needed to reach red.
"Oh, I just spent x_i hours solving problems", said the i-th of them.
Bob wants to train his math skills... | 3 | for _ in range(int(input())):
z, e, s = 0, 0, 0
for c in map(int, input()):
s += c
z += c == 0
e += c % 2 == 0
print('red' if z > 0 and e > 1 and s % 3 == 0 else 'cyan') |
Kuroni has n daughters. As gifts for them, he bought n necklaces and n bracelets:
* the i-th necklace has a brightness a_i, where all the a_i are pairwise distinct (i.e. all a_i are different),
* the i-th bracelet has a brightness b_i, where all the b_i are pairwise distinct (i.e. all b_i are different).
Kuro... | 1 | t=int(raw_input())
for i in range(t):
n=int(raw_input())
L=list(map(int,raw_input().split()))
L2=list(map(int,raw_input().split()))
L.sort()
L2.sort()
print(" ".join(map(str,L)))
print(" ".join(map(str,L2))) |
The Little Girl loves problems on games very much. Here's one of them.
Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules:
* The players move in turns; In one move the player can remove an arbitrary letter from string s.
* If the pl... | 1 | s = raw_input()
c = sum(s.count(x) % 2 for x in set(s))
print "First" if c & 1 or c == 0 else "Second"
|
Given are strings s and t of length N each, both consisting of lowercase English letters.
Let us form a new string by alternating the characters of S and the characters of T, as follows: the first character of S, the first character of T, the second character of S, the second character of T, ..., the N-th character of... | 3 | n=int(input())
s1,s2=input().split()
s=""
for i in range(n):
s+=s1[i]+s2[i]
print(s)
|
Print all the integers that satisfies the following in ascending order:
* Among the integers between A and B (inclusive), it is either within the K smallest integers or within the K largest integers.
Constraints
* 1 \leq A \leq B \leq 10^9
* 1 \leq K \leq 100
* All values in input are integers.
Input
Input is give... | 3 | A, B, K = map(int,input().split())
for i in range(A,min(B,A+K-1)+1,1):
print(i)
for j in range(max(B-K+1,A+K),B+1,1):
print(j)
|
The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations:
* d1 is the distance between the 1-st and the 2-nd station;
* d2 is the distance between the 2-nd and the 3-rd station;
...
* dn - 1 is the distance between the n - 1-th and the n-th station;
... | 3 | n=int(input())
a=input().split()
b=input().split()
start=int(b[0])
end=int(b[1])
tot=0
for i in range(len(a)):
tot=tot+int(a[i])
dis=0
if start<end:
for i in range(start,end):
dis=dis+int(a[i-1])
elif start>end:
for i in range(end,start):
dis=dis+int(a[i-1])
ano=tot-dis
if ano>dis:
... |
You are given an array a consisting of n positive integers.
Initially, you have an integer x = 0. During one move, you can do one of the following two operations:
1. Choose exactly one i from 1 to n and increase a_i by x (a_i := a_i + x), then increase x by 1 (x := x + 1).
2. Just increase x by 1 (x := x + 1).
... | 3 | # https://codeforces.com/contest/1374/problem/D
import sys
from collections import Counter
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
# do magic here
t = int(input())
for _ in range(t):
n, K = map(int, input().split())
arr = sorted([int(x) % K for x in input().split()])
if arr[-1]:
... |
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob.
Right now, Limak and Bob weigh a and b respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight.
Limak eats a lot and his weight is tripled after every year, while Bob's weight... | 3 | def we(li,bo):
y=0
while li<=bo:
li=li*3
bo=bo*2
y+=1
return y
i=list(map(int,input().split()))
li=i[0]
bo=i[1]
print(we(li,bo)) |
Three years have passes and nothing changed. It is still raining in London, and Mr. Black has to close all the doors in his home in order to not be flooded. Once, however, Mr. Black became so nervous that he opened one door, then another, then one more and so on until he opened all the doors in his house.
There are ex... | 3 | def doors(iterations, door_number):
pos_zero = 0
pos_one = 0
for i in range(iterations):
if(door_number[i] == "0"):
pos_zero = i
else:
pos_one = i
if(pos_zero < pos_one):
return pos_zero + 1
else:
return pos_one + 1
if __name__ == "__main__":
iterations = int(input())
... |
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()
f = ""
for i in n:
if i not in "aeiouy":
f+="."+i
print (f) |
You are given an array a consisting of n integers a_1, a_2, ..., a_n. You want to split it into exactly k non-empty non-intersecting subsegments such that each subsegment has odd sum (i. e. for each subsegment, the sum of all elements that belong to this subsegment is odd). It is impossible to rearrange (shuffle) the e... | 3 | import sys
input = sys.stdin.readline
print = sys.stdout.write
def main():
q = int(input())
for _ in range(q):
n,k = map(int,input().split())
tab = list(map(int,input().split()))
inc = 0
for x in range(n):
if tab[x]%2!=0:
inc += 1
if k%2!=inc%2 or inc < k:
print("NO\n")
else:
print("YES\n")
... |
Alice has a cute cat. To keep her cat fit, Alice wants to design an exercising walk for her cat!
Initially, Alice's cat is located in a cell (x,y) of an infinite grid. According to Alice's theory, cat needs to move:
* exactly a steps left: from (u,v) to (u-1,v);
* exactly b steps right: from (u,v) to (u+1,v); ... | 3 | tc = int(input())
for cn in range(tc) :
a,b,c,d = map(int,input().split())
x,y,x1,y1,x2,y2 = map(int,input().split())
if a + b > 0 and x1 == x2 :
print("No")
continue
if c + d > 0 and y1 == y2 :
print("No")
continue
m = min(a,b)
a -= m
b -= m
m = min(c,d)
c -= m
d -= m
if x - a >= x1 and x + b <= x2 ... |
You're given an array a of length n. You can perform the following operations on it:
* choose an index i (1 ≤ i ≤ n), an integer x (0 ≤ x ≤ 10^6), and replace a_j with a_j+x for all (1 ≤ j ≤ i), which means add x to all the elements in the prefix ending at i.
* choose an index i (1 ≤ i ≤ n), an integer x (1 ≤ x ≤... | 3 | n=int(input())
print(n+1)
print(1,n,10**5)
l=list(map(int,input().split()))
l=[l[i]+100000 for i in range(n)]
for i in range(n):
print(2,i+1,l[i]-i) |
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 = input()
s = input()
count0, count1 = 0, 0
for c in s:
if c == '0': count0 +=1
else: count1 += 1
print(abs(count0 - count1)) |
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 | gl=['A', 'O', 'Y', 'E', 'U', 'I','a', 'o', 'y', 'e', 'u', 'i']
s = str(input())
out=""
for i in s:
if i not in gl:
out+=('.'+i)
print(out.lower())
|
You are given two integers n and k. Your task is to find if n can be represented as a sum of k distinct positive odd (not divisible by 2) integers or not.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases.
The next t lines... | 3 | t=int(input())
for _ in range(t):
a,b=map(int,input().split())
if (a%2==0 and b%2==0) or (a%2!=0 and b%2!=0):
r=(b/2)*(2+(b-1)*2)
if r<=a:
print('YES')
else:
print('NO')
else:
print('NO') |
This is the easy version of the problem. The difference between the versions is the constraint on n and the required number of operations. You can make hacks only if all versions of the problem are solved.
There are two binary strings a and b of length n (a binary string is a string consisting of symbols 0 and 1). In ... | 3 | ''' ░░█ ▄▀█ █ █▀ █░█ █▀█ █▀▀ █▀▀ █▀█ ▄▀█ █▀▄▀█
█▄█ █▀█ █ ▄█ █▀█ █▀▄ ██▄ ██▄ █▀▄ █▀█ █░▀░█ '''
# [cf-1382-c.py] => [21-07-2020 @ 20:28:34]
# Author & Template by : Udit "luctivud" Gupta
# https://www.linkedin.com/in/udit-gupta-1b7863135/
import math; from collections import *
import sys;... |
Notes
Template in C
Constraints
2 ≤ the number of operands in the expression ≤ 100
1 ≤ the number of operators in the expression ≤ 99
-1 × 109 ≤ values in the stack ≤ 109
Input
An expression is given in a line. Two consequtive symbols (operand or operator) are separated by a space character.
You can assume that +... | 3 | ops = {"+": lambda a, b: b + a,
"-": lambda a, b: b - a,
"*": lambda a, b: b * a}
stack = []
for s in input().split():
if s in ops:
stack.append(ops[s](stack.pop(), stack.pop()))
else:
stack.append(int(s))
print(stack[-1]) |
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... | 1 | n=int(raw_input())
a=map(int,raw_input().split())
if n>1 and a.count(0)==1:
print "YES"
exit()
elif n==1 and a[0]==1:
print "YES"
exit()
print "NO"
|
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 | n,k = map(int,input().split())
A = list(map(int,input().split()))
mod = 10**9 + 7
if n ==1: print(0 if k> A[0] else 1);exit()
dp = [[0]*(k+1) for _ in range(n)]
for i in range(A[0]+1):
dp[0][i] = 1
for i in range(1,n):
B = [0]
for j in range(k+1):
B.append(B[-1] + dp[i-1][j])
B[-1]%=mod
... |
You are given two arrays a and b, each consisting of n positive integers, and an integer x. Please determine if one can rearrange the elements of b so that a_i + b_i ≤ x holds for each i (1 ≤ i ≤ n).
Input
The first line of input contains one integer t (1 ≤ t ≤ 100) — the number of test cases. t blocks follow, each d... | 3 | t = int(input())
for test in range(t):
n,x = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
b.sort(reverse = True)
result = True
for i in range(n):
if a[i]+b[i]>x:
result = False
break
ans = "Yes" if result else "No"
print(ans)
if test < t-1:
input() |
Snuke loves working out. He is now exercising N times.
Before he starts exercising, his power is 1. After he exercises for the i-th time, his power gets multiplied by i.
Find Snuke's power after he exercises N times. Since the answer can be extremely large, print the answer modulo 10^{9}+7.
Constraints
* 1 ≤ N ≤ 10... | 3 | import math;print(math.factorial(int(input()))%int(7+1e9)) |
There are n students standing in a row. Two coaches are forming two teams — the first coach chooses the first team and the second coach chooses the second team.
The i-th student has integer programming skill a_i. All programming skills are distinct and between 1 and n, inclusive.
Firstly, the first coach will choose ... | 3 | class Node:
def __init__(self, v, i):
self.v = v
self.i = i
self.left = None
self.right = None
n, k = map(int, input().split())
nums = list(map(int, input().split()))
nodes = [Node(v, i) for i, v in enumerate(nums)]
sort = [[v, i] for i, v in enumerate(nums)]
sort = sorted(sort, key... |
Vanya is managed to enter his favourite site Codehorses. Vanya uses n distinct passwords for sites at all, however he can't remember which one exactly he specified during Codehorses registration.
Vanya will enter passwords in order of non-decreasing their lengths, and he will enter passwords of same length in arbitrar... | 3 |
n, k = [int(i) for i in input().split()]
ary = []
for i in range(n):
ary.append(input())
key = input()
def allSum(n):
return n * 1 + (n // k) * 5
def worstSum(n):
if n % k != 0:
return n * 1 + (n // k) * 5
return n * 1 + (n // k - 1) * 5
smaller = 0
equal = 0
for i in ary:
if len(i) < len(key):
smaller... |
Petya's friends made him a birthday present — a bracket sequence. Petya was quite disappointed with his gift, because he dreamed of correct bracket sequence, yet he told his friends nothing about his dreams and decided to fix present himself.
To make everything right, Petya is going to move at most one bracket from i... | 3 | def solve(s):
opn=0
for i in s:
if i=='(':
opn+=1
else:
opn-=1
if opn<-1:
return 'NO'
if opn!=0:
return 'NO'
return 'YES'
n=int(input())
s=input()
print(solve(s))
|
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 | for i in range(5):
line = list(input())
for j in line:
if j==" ":
line.remove(j)
for j in line:
j = int(j)
if '1' in line:
location=line.index('1')+1
columndist=abs(location-3)
rowdist=abs(i-2)
j=columndist+rowdist
print(j) |
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 | if __name__ == "__main__":
m,n=input().split()
list=input().split()
cur=1
sumt=0
r=0
for next1 in list:
if int(cur) < int(next1):
sumt=int(next1)-int(cur)
r+=sumt
elif int(cur) > int(next1):
sumt=int(m)-(int(cur)-int(next1))
r+=sum... |
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on n - 2 intermediate planets. Formally: we number all the planets from 1 to n. 1 is Earth, n is Mars. Natasha will make exactly n flights: 1 → 2 → … n → 1.
Flight from x to y consists of two phases: take-off from ... | 3 | n = int(input())
m = int(input())
a = [int(i) for i in input().split()]
b = [int(i) for i in input().split()]
if b[0] == 1 or a[0] == 1:
print(-1)
exit(0)
ans = m / (b[0] - 1)
for i in range(n - 1, 0, -1):
if b[i] == 1 or a[i] == 1:
print(-1)
exit(0)
ans += (m + ans) / (a[i] - 1)
a... |
Very soon Berland will hold a School Team Programming Olympiad. From each of the m Berland regions a team of two people is invited to participate in the olympiad. The qualifying contest to form teams was held and it was attended by n Berland students. There were at least two schoolboys participating from each of the m ... | 3 |
def STR(): return list(input())
def INT(): return int(input())
def MAP(): return map(int, input().split())
def MAP2():return map(float,input().split())
def LIST(): return list(map(int, input().split()))
def STRING(): return input()
import string
import sys
from heapq import heappop , heappush
from bisect import *
from... |
«One dragon. Two dragon. Three dragon», — the princess was counting. She had trouble falling asleep, and she got bored of counting lambs when she was nine.
However, just counting dragons was boring as well, so she entertained herself at best she could. Tonight she imagined that all dragons were here to steal her, and ... | 1 | def retrieve_input():
dragon_list=[]
for index in xrange(5):
dragon_list.append(int(raw_input()))
return dragon_list
def dragon_list(dragon_list):
k, l, m, n, d = dragon_list[0], dragon_list[1], dragon_list[2], dragon_list[3], dragon_list[4]
count = 0
for dragon in xrange(1,d+1):
... |
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
You have to answer t independent test cases.
Input
The first line of the input co... | 3 | for i in range(int(input())):
a,b = map(int,input().split())
if a%b == 0:
print('0')
else:
print(b - a%b) |
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())
listnilai =[]
nilai1 = (a+b)*c
nilai2 = a*(b+c)
nilai3 = a*b*c
nilai4 = a+b+c
listnilai.append(nilai1)
listnilai.append(nilai2)
listnilai.append(nilai3)
listnilai.append(nilai4)
print(max(listnilai))
|
In the city of Ultima Thule job applicants are often offered an IQ test.
The test is as follows: the person gets a piece of squared paper with a 4 × 4 square painted on it. Some of the square's cells are painted black and others are painted white. Your task is to repaint at most one cell the other color so that the p... | 3 | l=[]
for i in range(4):
l.append(list(input()))
f=0
for i in range(3):
for j in range(3):
c=1
x=l[i][j]
if(l[i][j+1]==x):
c+=1
if(l[i+1][j]==x):
c+=1
if(l[i+1][j+1]==x):
c+=1
if(c==3 or c==1 or c==4):
f=1
... |
Write a program which computes the area of a shape represented by the following three lines:
$y = x^2$
$y = 0$
$x = 600$
It is clear that the area is $72000000$, if you use an integral you learn in high school. On the other hand, we can obtain an approximative area of the shape by adding up areas of many rectangles... | 1 | import sys
for n in map(int,sys.stdin):
s=sum([i*i for i in range(n,600,n)])*n
print s |
Alice and Bob like games. And now they are ready to start a new game. They have placed n chocolate bars in a line. Alice starts to eat chocolate bars one by one from left to right, and Bob — from right to left. For each chocololate bar the time, needed for the player to consume it, is known (Alice and Bob eat them with... | 3 | n = int(input())
s = list(map(int,input().split()))
a = x = y = 0
b = n-1
while (a<=b):
if(x<=y):
x+=s[a]
a+=1
else:
y+=s[b]
b-=1
print(a, n-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 | n=int(input());
n=n+1;
while(n):
s=set(map(int,str(n)));
if(len(s)==4):
print(n);
break;
n+=1 |
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.... | 1 | n = int(raw_input())
count = 0
for _ in range(n):
if raw_input().count('1') > 1:
count+=1
print(count)
|
Write a program which reads a sequence A of n elements and an integer M, and outputs "yes" if you can make M by adding elements in A, otherwise "no". You can use an element only once.
You are given the sequence A and q questions where each question contains Mi.
Notes
You can solve this problem by a Burte Force appro... | 3 | n = int(input())
a = list(map(int, input().split()))
q = int(input())
m = list(map(int, input().split()))
b = set()
for i in range(2**n):
t = 0
for j in range(n):
if i>>j&1:
t += a[j]
b.add(t)
for ele in m:
if ele in b:
print("yes")
else:
print("no")
|
You are given two arrays a and b, each consisting of n positive integers, and an integer x. Please determine if one can rearrange the elements of b so that a_i + b_i ≤ x holds for each i (1 ≤ i ≤ n).
Input
The first line of input contains one integer t (1 ≤ t ≤ 100) — the number of test cases. t blocks follow, each d... | 3 | import sys
tests = int(sys.stdin.readline())
for _ in range(tests):
n,x = list(map(int,sys.stdin.readline().split()))
a = list(map(int,sys.stdin.readline().split()))
b = list(map(int,sys.stdin.readline().split()))
s = [i[0] + i[1] for i in zip(sorted(a),reversed(sorted(b)))]
_ = sys.stdin.readline()
for y in s:
... |
After making bad dives into swimming pools, Wilbur wants to build a swimming pool in the shape of a rectangle in his backyard. He has set up coordinate axes, and he wants the sides of the rectangle to be parallel to them. Of course, the area of the rectangle must be positive. Wilbur had all four vertices of the planned... | 1 |
count = int(raw_input())
coords = []
for i in range(count):
vals = map(int,raw_input().split(" "))
coords.append((vals[0],vals[1]))
coords.sort()
if len(coords) == 4:
print (coords[2][0] - coords[0][0]) * (coords[1][1] - coords[0][1])
elif len(coords) == 3:
val = (coords[2][0] - coords[0][0]) * (coo... |
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob.
Right now, Limak and Bob weigh a and b respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight.
Limak eats a lot and his weight is tripled after every year, while Bob's weight... | 3 | x,y = [int(j) for j in input().split()]
count=0
while x <= y:
x*=3
y*=2
count+=1
print(count)
|
You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft k torches. One torch can be crafted using one stick and one coal.
Hopefully, you've met a very handsome wandering trader who has two trade offers:
* exchange 1 stick for x sticks (you lose 1 stick and gain x sticks... | 3 | import math
from decimal import *
t=int(input())
for i in range(t):
s=(input().split(" "))
x=int(s[0])
y=int(s[1])
k=int(s[2])
print(k+math.ceil(Decimal(k*y+k-1)/Decimal(x-1))) |
Polycarpus has a ribbon, its length is n. He wants to cut the ribbon in a way that fulfils the following two conditions:
* After the cutting each ribbon piece should have length a, b or c.
* After the cutting the number of ribbon pieces should be maximum.
Help Polycarpus and find the number of ribbon pieces ... | 3 | # from debug import debug
import sys
# from math import ceil, log2
n,a,b,c = map(int, input().split())
lis = sorted([a,b,c])
dp = [-1]*(n+1)
dp[0] = 0
dp[lis[0]] = 1
for i in range(lis[0], n+1):
for j in lis:
if i-j>=0 and dp[i-j] != -1:
dp[i] = max(dp[i], 1+dp[i-j])
print(dp[-1])
|
A new e-mail service "Berlandesk" is going to be opened in Berland in the near future. The site administration wants to launch their project as soon as possible, that's why they ask you to help. You're suggested to implement the prototype of site registration system. The system should work on the following principle.
... | 3 | nazwy = []
def bins(nowa):
global nazwy
po = 0
ko = len(nazwy)-1
sr = (po+ko)//2
if nowa < nazwy[0][0]:
return -1
elif nowa >= nazwy[ko][0]:
return ko
else:
while po != ko:
if nazwy[sr][0] > nowa:
ko = sr
else:
... |
You are given a permutation p=[p_1, p_2, …, p_n] of integers from 1 to n. Let's call the number m (1 ≤ m ≤ n) beautiful, if there exists two indices l, r (1 ≤ l ≤ r ≤ n), such that the numbers [p_l, p_{l+1}, …, p_r] is a permutation of numbers 1, 2, …, m.
For example, let p = [4, 5, 1, 3, 2, 6]. In this case, the numb... | 3 | def mi():
return map(int, input().split())
'''
3
6
4 5 1 3 2 6
5
5 3 1 2 4
4
1 4 3 2
3
6
4 5 1 3 2 6
5
5 3 1 2 4
4
1 4 3 2
'''
for _ in range(int(input())):
n = int(input())
a = list(mi())
t = a.index(1)
dist = [0]*(n+1)
dic = [0]*n
for i in range(n):
dist[a[i]] = abs(t-i)
d... |
There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of ope... | 3 | # n, s_x, s_y = map(int, input().split())
# east = west = north = south = 0
# for i in range(n):
# x, y = map(int, input().split())
# if x < s_x:
# west += 1
# else:
# east += 1
# if y < s_y:
# # south-west
# south += 1
# else:
# north += 1
# ans = max([east, west, north, south])
# prin... |
During the break the schoolchildren, boys and girls, formed a queue of n people in the canteen. Initially the children stood in the order they entered the canteen. However, after a while the boys started feeling awkward for standing in front of the girls in the queue and they started letting the girls move forward each... | 3 | def main():
info = input().split()
students = int(info[0])
sec = int(info[1])
done = 0
queue = input()
while done < sec:
newq = []
i = 0
while i < students:
if queue[i]=='B':
if i+1 < students:
if queue[i+1]=='G':
... |
Taro's summer vacation starts tomorrow, and he has decided to make plans for it now.
The vacation consists of N days. For each i (1 \leq i \leq N), Taro will choose one of the following activities and do it on the i-th day:
* A: Swim in the sea. Gain a_i points of happiness.
* B: Catch bugs in the mountains. Gain b_i... | 3 | n = int(input())
dpa = 0
dpb = 0
dpc = 0
for i in range(n):
a,b,c = map(int,input().split())
dpat,dpbt,dpct = dpa,dpb,dpc
dpa = max(dpbt,dpct) + a
dpb = max(dpct,dpat) + b
dpc = max(dpat,dpbt) + c
print(max(dpa,dpb,dpc))
|
You are given two integers n and k. Your task is to find if n can be represented as a sum of k distinct positive odd (not divisible by 2) integers or not.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases.
The next t lines... | 3 | # -*- coding: utf-8 -*-
import sys
import math
import os
import itertools
import string
import heapq
import _collections
from collections import Counter
from collections import defaultdict
from functools import lru_cache
import bisect
import re
import queue
from decimal import *
class Scanner():
@staticmethod
... |
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second.
One day in 230 AD Shapur was trying to find out if any one can possibly do... | 3 | s1 = input()
s2 = input()
l = []
for i in range(len(s1)):
l.append(str((int(s1[i]) + int(s2[i])) % 2))
print(''.join(l))
|
Tavak and Seyyed are good friends. Seyyed is very funny and he told Tavak to solve the following problem instead of longest-path.
You are given l and r. For all integers from l to r, inclusive, we wrote down all of their integer divisors except 1. Find the integer that we wrote down the maximum number of times.
Solve... | 3 | import math
l, r = [int(a) for a in input().split()]
if l == r:
print(l)
else:
print(2) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.