problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
Write a program which reverses a given string str.
Input
str (the size of str ≤ 20) is given in a line.
Output
Print the reversed str in a line.
Example
Input
w32nimda
Output
admin23w | 1 | import sys
for i in sys.stdin.readlines():
print "".join(reversed(i.strip())) |
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.
We know that several boy&girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair m... | 3 | g = int(input())
girls = [int(x) for x in input().split()]
b = int(input())
boys = [int(x) for x in input().split()]
girls.sort()
boys.sort()
count = 0
j = 0
i = 0
while i < g and j < b:
if abs(girls[i]-boys[j]) <= 1:
count += 1
j += 1
i += 1
elif girls[i]<boys[j]:
i += 1
... |
You are given a string s[1 ... n] consisting of lowercase Latin letters. It is guaranteed that n = 2^k for some integer k ≥ 0.
The string s[1 ... n] is called c-good if at least one of the following three conditions is satisfied:
* The length of s is 1, and it consists of the character c (i.e. s_1=c);
* The lengt... | 3 | import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
import math
def gift():
for _ in range(t):
n=int(input())
arry= input()
if n==1:
if arry[0]=='a':
yield 0
else:
yield 1
else:
def... |
You have been blessed as a child of Omkar. To express your gratitude, please solve this problem for Omkar!
An array a of length n is called complete if all elements are positive and don't exceed 1000, and for all indices x,y,z (1 ≤ x,y,z ≤ n), a_{x}+a_{y} ≠ a_{z} (not necessarily distinct).
You are given one integer ... | 3 | t = int(input())
for i in range(t):
n = int(input())
for i in range(n):
print(1,end=" ")
print("") |
In the city of Saint Petersburg, a day lasts for 2^{100} minutes. From the main station of Saint Petersburg, a train departs after 1 minute, 4 minutes, 16 minutes, and so on; in other words, the train departs at time 4^k for each integer k ≥ 0. Team BowWow has arrived at the station at the time s and it is trying to co... | 3 | a = input()
n = len(a)
if n % 2 == 0:
print(n//2)
else:
if a.count('1') > 1:
print(n//2 +1)
else:
print(n//2) |
Let's call a number k-good if it contains all digits not exceeding k (0, ..., k). You've got a number k and an array a containing n numbers. Find out how many k-good numbers are in a (count each number every time it occurs in array a).
Input
The first line contains integers n and k (1 ≤ n ≤ 100, 0 ≤ k ≤ 9). The i-th ... | 1 | n,k = map(int, raw_input().split())
a = []
javab = 0
for i in range (0,n) :
[adad] = map(int,raw_input().split())
a.append(adad)
for i in range (0,n) :
p = 0
for j in range (0,k+1) :
flag_j = 0
adad = a[i]
while True :
if adad % 10 == j :
flag_j = 1
... |
Shichi-Go-San (literally "Seven-Five-Three") is a traditional event in a certain country to celebrate the growth of seven-, five- and three-year-old children.
Takahashi is now X years old. Will his growth be celebrated in Shichi-Go-San this time?
Constraints
* 1 ≤ X ≤ 9
* X is an integer.
Input
Input is given from... | 3 | n=str(input())
print("YES" if n in "753" else "NO") |
Ehab loves number theory, but for some reason he hates the number x. Given an array a, find the length of its longest subarray such that the sum of its elements isn't divisible by x, or determine that such subarray doesn't exist.
An array a is a subarray of an array b if a can be obtained from b by deletion of several... | 3 | from sys import stdin, stdout
from sys import maxsize
#input = stdin.readline().strip
def solve():
pass
test = 1
test = int(input())
for t in range(0, test):
# brr = [list(map(int,input().split())) for i in range(rows)] # 2D array row-wise input
# n = int(input())
# s = list(input()) ... |
It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not en... | 3 | n = int(input())
r = 1
l = 0
for a in input().split():
u = 0
for e in a:
u += int(e)
if u > 1:
r = a
elif u == 0:
l = -1
break
else:
l += len(a) - 1
if l < 0:
print(0)
else:
print(r,'0' * l,sep = '')
|
Sean is trying to save a large file to a USB flash drive. He has n USB flash drives with capacities equal to a1, a2, ..., an megabytes. The file size is equal to m megabytes.
Find the minimum number of USB flash drives needed to write Sean's file, if he can split the file between drives.
Input
The first line contai... | 3 | n = int(input())
m = int(input())
l = []
for i in range(n):
s = int(input())
l.append(s)
a =0
while(m>0):
a+=1
k = max(l)
c = l.index(k)
m -=k
l.pop(c)
if(m<=0):
break
print(a) |
Little Shino loves to play with coins. In the city she lives, there are 26 different types of coins. Each coin is represented with a lowercase letter a, b, c, ... , y, z. Shino has some number of coins and she placed them in some random sequence, S, on the table. She is wondering how many pairs (i, j) are there, where... | 1 | K = int(raw_input())
data = raw_input()
length = len(data)
ans = 0
for i in range(length-(K-1)):
distinct = []
count = 0
for j in range(i, length):
if data[j] not in distinct:
distinct.append(data[j])
count += 1
if count == K:
ans += 1
elif count > K:
break
print ans |
The only difference between easy and hard versions is constraints.
There are n kids, each of them is reading a unique book. At the end of any day, the i-th kid will give his book to the p_i-th kid (in case of i = p_i the kid will give his book to himself). It is guaranteed that all values of p_i are distinct integers ... | 1 | from __future__ import print_function
q = input()
output = []
for i in range(q):
num = input()
order = list(map(int, raw_input().split()))
ans = []
for j in range(len(order)):
count = 1
index = order[j]
while (order[index - 1] != order[j]):
index = order[index - 1]
... |
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the... | 3 | n, h = map(int, input().split())
a = list(map(int, input().split()))
ans = n
for el in a:
if el > h:
ans += 1
print(ans)
|
There are n pillars aligned in a row and numbered from 1 to n.
Initially each pillar contains exactly one disk. The i-th pillar contains a disk having radius a_i.
You can move these disks from one pillar to another. You can take a disk from pillar i and place it on top of pillar j if all these conditions are met:
... | 3 | import sys
strInp = lambda : input().strip().split()
intInp = lambda : list(map(int,strInp()))
n = int(input())
arr = intInp()
inc = True
dec = True
failed = False
for i in range(n - 1):
if arr[i] > arr[i+1]:
inc = False
if inc == False:
if arr[i] < arr[i + 1]:
failed... |
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them.
Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain nu... | 3 |
def main():
phrase = input()
phrases = phrase.split("WUB")
phrase = ""
for item in phrases:
if len(item):
phrase += (" " + item)
phrase = phrase.strip()
print(phrase)
main() |
Pasha has a wooden stick of some positive integer length n. He wants to perform exactly three cuts to get four parts of the stick. Each part must have some positive integer length and the sum of these lengths will obviously be n.
Pasha likes rectangles but hates squares, so he wonders, how many ways are there to spli... | 1 | from math import *
from Queue import *
from sys import *
from random import *
n = int(raw_input())
if n%2 == 1:
print(0)
exit(0)
k = n/2
print((k-1)/2)
|
Dolphin is planning to generate a small amount of a certain chemical substance C.
In order to generate the substance C, he must prepare a solution which is a mixture of two substances A and B in the ratio of M_a:M_b.
He does not have any stock of chemicals, however, so he will purchase some chemicals at a local pharmac... | 3 | INF = float('inf')
n, ma, mb = map(int, input().split())
ccmax = n * 10
t = [[INF] * (ccmax + 1) for _ in range(ccmax + 1)]
for _ in range(n):
a, b, c = map(int, input().split())
for aa in range(ccmax, 0, -1):
taa = t[aa]
for bb in range(ccmax, 0, -1):
if taa[bb] == INF:
continue
if t[a ... |
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 | l = []
for i in range(int(input())):
l.append(input())
for x in ["AC", "WA", "TLE", "RE"]:
print(x + " x " + str(l.count(x))) |
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 = [i for i in input() if i.isalpha()]
print(len(set(letters))) |
Sorting algorithms for sorting data are basic algorithms indispensable in computer science. For example, as shown in the figure below, the operation of "sorting the elements of an array of integer values in ascending order" is alignment.
<image>
Many alignment algorithms have been devised, but one of the basic alg... | 3 | def bubbleSort(list):
j = len(list) - 1
bcnt = 0
while j:
for i in range(j):
if list[i] > list[i + 1]:
list[i], list[i + 1] = list[i + 1], list[i]
bcnt += 1
j -= 1
return bcnt
while True:
n = int(input())
if n == 0:
break
A = []
for _ in range(n):
A.append(int(inp... |
Alice likes word "nineteen" very much. She has a string s and wants the string to contain as many such words as possible. For that reason she can rearrange the letters of the string.
For example, if she has string "xiineteenppnnnewtnee", she can get string "xnineteenppnineteenw", containing (the occurrences marked) tw... | 1 | s = raw_input()
n = 0
e = 0
i = 0
t = 0
for _ in s:
if _ == 'n':
n += 1
elif _ == 'e':
e += 1
elif _ == 'i':
i += 1
elif _ == 't':
t += 1
else:
continue
if n and e and i and t:
print min((n-1)/2,... |
<image>
My grandmother uses a balance. The balance will balance if you place the same size on both of the two dishes, otherwise it will tilt to the heavier side. The weights of the 10 weights are 1g, 2g, 4g, 8g, 16g, 32g, 64g, 128g, 256g, 512g in order of lightness.
My grandmother says, "Weigh up to about 1 kg in gr... | 3 | g = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
while True :
try :
c = -1
left, right = int(input()), []
while True :
if left <= 0 : break
else :
if left - g[c] < 0 : c += -1
else :
left -= g[c]
righ... |
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 | l=list((input()))
if (l.count('4')+l.count('7'))==7 or (l.count('4')+l.count('7'))==4:
print('YES')
else:
print('NO') |
Petya has an array a consisting of n integers. He wants to remove duplicate (equal) elements.
Petya wants to leave only the rightmost entry (occurrence) for each element of the array. The relative order of the remaining unique elements should not be changed.
Input
The first line contains a single integer n (1 ≤ n ≤ ... | 3 | n=int(input())
alist=list(map(int,input().split()))
alist.reverse()
dup=[]
for x in alist:
if x not in dup:
dup.append(x)
dup.reverse()
print(len(dup))
print(*dup) |
Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity.
There are n columns of toy cubes in the box arranged in a line. The i-th column contains ai cubes. At first, the gravity in the box is pulling... | 3 | n=int(input())
b=[int(i) for i in input().split()]
b.sort()
st=str(b[0])
for i in range(1,n):
st=st+' '+str(b[i])
print(st)
|
Polycarp was dismantling his attic and found an old floppy drive on it. A round disc was inserted into the drive with n integers written on it.
Polycarp wrote the numbers from the disk into the a array. It turned out that the drive works according to the following algorithm:
* the drive takes one positive number x... | 3 | #TESTING FAST IO AGAIN
import io,os,sys
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
in_length = int(input())
final_ouput = []
def find_minimum_stop(array, element, start, end):
mid = (start+end)//2
if start == end:
return 0
if element == array[mid]:
return mid
if element <= ... |
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 | import sys
import math
import heapq
import collections
def inputnum():
return(int(input()))
def inputnums():
return(map(int,input().split()))
def inputlist():
return(list(map(int,input().split())))
def inputstring():
return([x for x in input()])
def inputstringnum():
return([ord(x)-ord('a') for x in... |
Sereja has an array a, consisting of n integers a1, a2, ..., an. The boy cannot sit and do nothing, he decided to study an array. Sereja took a piece of paper and wrote out m integers l1, l2, ..., lm (1 ≤ li ≤ n). For each number li he wants to know how many distinct numbers are staying on the positions li, li + 1, ...... | 3 | import math
import sys
#n = int(input())
#n, m = map(int, input().split())
#d = list(map(int, input().split()))
n, m = map(int, input().split())
d = list(map(int, input().split()))
used = set()
suf = [0]*n
suf[n-1] = 1
used.add(d[-1])
for i in range(n - 2, -1, -1):
if d[i] not in used:
suf[i] = suf[i+1]... |
Given are a sequence of N positive integers A_1, A_2, \ldots, A_N and another positive integer S.
For a non-empty subset T of the set \\{1, 2, \ldots , N \\}, let us define f(T) as follows:
* f(T) is the number of different non-empty subsets \\{x_1, x_2, \ldots , x_k \\} of T such that A_{x_1}+A_{x_2}+\cdots +A_{x_k}... | 3 | n, s = map(int, input().split())
A = list(map(int, input().split()))
MOD = 998244353
U = 3010
dp = [0] * (U + 1)
dp[0] = 1
for a in A:
dp2 = [0] * (s + 1)
for j in range(s + 1):
dp2[j] = dp[j] * 2
if j >= a:
dp2[j] += dp[j - a]
dp2[j] %= MOD
dp = dp2
print(dp[s]) |
Happy new year! The year 2020 is also known as Year Gyeongja (경자년, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.
There are two sequences of n strings s_1, s_2, s_3, …, s_{n} and m strings t_1, t_2, t_3, …, t_{m}. ... | 3 | n,m = map(int,input().split())
s = input().split()
t = input().split()
for _ in range(int(input())):
x = int(input())-1
print(s[x%n]+t[x%m])
|
Today Vasya visited a widely known site and learned that the continuation of his favourite game Codecraft II will appear after exactly k months. He looked at the calendar and learned that at the moment is the month number s. Vasya immediately got interested in what month Codecraft III will appear. Help him understand t... | 1 | m=["January","February","March","April","May","June","July","August","September","October","November","December"]
c=m.index(raw_input())
print m[(c+int(raw_input()))%12]
|
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.
The language is that peculiar as it has exactly one variable, called x. Also, there are two operations:
* Operation ++ increases the value of variable x by 1.
* Operation -- decreases the value of variable x by 1.... | 3 | x = 0
for a in range(int(input())):
x += 1 if "++" in input() else -1
print(x) |
Tomorrow is a difficult day for Polycarp: he has to attend a lectures and b practical classes at the university! Since Polycarp is a diligent student, he is going to attend all of them.
While preparing for the university, Polycarp wonders whether he can take enough writing implements to write all of the lectures and d... | 3 | from math import ceil
n = int(input())
for i in range(n):
a,b,c,d,e = map(int,input().split())
k1 =ceil(a/c)
if k1 ==0:
k1=1
k2 = ceil(b/d)
if k2 ==0:
k2=1
if k1+k2<=e:
print(*[k1,k2])
else:
print(-1)
|
You are both a shop keeper and a shop assistant at a small nearby shop. You have n goods, the i-th good costs a_i coins.
You got tired of remembering the price of each product when customers ask for it, thus you decided to simplify your life. More precisely you decided to set the same price for all n goods you have.
... | 3 | from bisect import *
from collections import *
from itertools import *
import functools
import sys
import math
from decimal import *
from copy import *
from heapq import *
getcontext().prec = 30
MAX = sys.maxsize
MAXN = 1000010
MOD = 10**9+7
spf = [i for i in range(MAXN)]
def sieve():
for i in range(2,MAXN,2):
... |
Nowadays all circuses in Berland have a round arena with diameter 13 meters, but in the past things were different.
In Ancient Berland arenas in circuses were shaped as a regular (equiangular) polygon, the size and the number of angles could vary from one circus to another. In each corner of the arena there was a spec... | 1 | # In the name of Allah, Most Gracious, Most Merciful
# /
#
#
#
#
# ??
import math
EPS = 1e-4
def gcd(a, b):
while abs(a) > EPS and abs(b) > EPS:
if a > b:
a -= math.floor(a/b)*b
else:
b -= math.floor(b/a)*a
return a+b
def dist(x0, y0, x1, y1):
return math.sqrt((x0-x1)**2+(y0-y1)**2)
x0, y0 = map(... |
There is a white sheet of paper lying on a rectangle table. The sheet is a rectangle with its sides parallel to the sides of the table. If you will take a look from above and assume that the bottom left corner of the table has coordinates (0, 0), and coordinate axes are left and bottom sides of the table, then the bott... | 1 | import sys,os
def find_ins_coord(loc1, loc2):
x1 = max(loc1[0], loc2[0])
y1 = max(loc1[1], loc2[1])
x2 = min(loc1[2], loc2[2])
y2 = min(loc1[3], loc2[3])
if x1>x2 or y1>y2:
return [0, 0, 0, 0]
return [x1, y1, x2, y2]
def cal_area(loc):
return (loc[2] - loc[0])*(loc[3]-loc[1])
fr... |
There are three airports A, B and C, and flights between each pair of airports in both directions.
A one-way flight between airports A and B takes P hours, a one-way flight between airports B and C takes Q hours, and a one-way flight between airports C and A takes R hours.
Consider a route where we start at one of th... | 3 | p,q,r=map(int, input().split())
i=p+q+r
print(i-max(p,q,r))
|
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 | def main():
w = int(input())
if (w > 2) and (w % 2 == 0):
print('YES')
else:
print('NO')
if __name__ == '__main__':
main()
|
You are given two integers a and b.
In one move, you can choose some integer k from 1 to 10 and add it to a or subtract it from a. In other words, you choose an integer k ∈ [1; 10] and perform a := a + k or a := a - k. You may use different values of k in different moves.
Your task is to find the minimum number of mo... | 3 | n=int(input())
for i in range(n):
a,b=(map(int,input().split()))
ans=0
if b>a:
if (b-a)%2==0:
ans=min(2,b-a)
else:
ans=1
if b==a:
ans=0
if b<a:
ans=(a-b)%2+1
print(ans)
|
You are given an array a consisting of n integers. You have to find the length of the smallest (shortest) prefix of elements you need to erase from a to make it a good array. Recall that the prefix of the array a=[a_1, a_2, ..., a_n] is a subarray consisting several first elements: the prefix of the array a of length k... | 3 | t = int(input())
for _ in range(t):
n = int(input())
A = list(map(int,input().split()))
i = n-1
while i>0 and A[i-1]>=A[i]:
i-=1
while i>0 and A[i-1]<=A[i]:
i-=1
print(i) |
We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer t Т-prime, if t has exactly three distinct positive divisors.
You are given an array of n positive integers. For each of them determine whether it is Т-prime or not.
Input
The f... | 3 | import math
n=int(input())
l=list(map(int,input().split()))
def checkprime(n):
if n%2==0:
return False
for i in range(3,int(math.sqrt(n))+1,2):
if n%i==0:
return False
return True
for i in range(n):
a=l[i]
b=math.sqrt(a)
if a<4:
print ("NO")
elif a==4:
... |
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... | 1 | # -*- coding:UTF-8 -*-
__author__ = 'Licc_xd'
get_input = raw_input().split()
n = int(get_input[0])
t = int(get_input[1])
if (n == 1 and t == 10 ):
print -1
else:
if (t != 10):
print str(t)*n
else:
print "1"+"0"*(n-1)
|
You have a playlist consisting of n songs. The i-th song is characterized by two numbers t_i and b_i — its length and beauty respectively. The pleasure of listening to set of songs is equal to the total length of the songs in the set multiplied by the minimum beauty among them. For example, the pleasure of listening to... | 3 | # @oj: codeforces
# @id: hitwanyang
# @email: 296866643@qq.com
# @date: 2020-11-16 14:49
# @url:https://codeforc.es/contest/1140/problem/C
import sys,os
from io import BytesIO, IOBase
import collections,itertools,bisect,heapq,math,string
from decimal import *
# region fastio
BUFSIZE = 8192
BUFSIZE = 8192
class FastI... |
Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is n.
There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains 2 apartments, every other floor contains x apartments each. Apartments are numbered starting from one, from... | 3 | from functools import reduce
import os
import sys
from collections import *
#from fractions import *
from math import *
from bisect import *
from heapq import *
from io import BytesIO, IOBase
input = lambda: sys.stdin.readline().rstrip("\r\n")
def value(): return tuple(map(int, input().split())) # multiple values
def a... |
When Serezha was three years old, he was given a set of cards with letters for his birthday. They were arranged into words in the way which formed the boy's mother favorite number in binary notation. Serezha started playing with them immediately and shuffled them because he wasn't yet able to read. His father decided t... | 3 | n = int(input())
s = input()
ans = '1' * s.count('n')
ans += '0' * s.count('z')
print(*list(ans)) |
Snuke has come to a store that sells boxes containing balls. The store sells the following three kinds of boxes:
* Red boxes, each containing R red balls
* Green boxes, each containing G green balls
* Blue boxes, each containing B blue balls
Snuke wants to get a total of exactly N balls by buying r red boxes, g gre... | 3 | r,g,b,n=map(int,input().split())
a=0
for i in range(0,n+1,r):
for j in range(0,n+1,g):
k=n-i-j
if k>=0 and not k%b:
a+=1
print(a) |
You are given a sequence a consisting of n integers. Find the maximum possible value of <image> (integer remainder of ai divided by aj), where 1 ≤ i, j ≤ n and ai ≥ aj.
Input
The first line contains integer n — the length of the sequence (1 ≤ n ≤ 2·105).
The second line contains n space-separated integers ai (1 ≤ a... | 3 | def main():
input()
aa = sorted(map(int, input().split()))
maxa = max(aa)
m = [False] * (maxa + 1)
x = []
b = 0
for a in aa:
if b != a:
m[a] = True
for i in range(b, a):
x.append(b)
b = a
x.append(b)
ans = 0
for i in ran... |
How many strings can be obtained by applying the following operation on a string S exactly K times: "choose one lowercase English letter and insert it somewhere"?
The answer can be enormous, so print it modulo (10^9+7).
Constraints
* K is an integer between 1 and 10^6 (inclusive).
* S is a string of length between 1... | 3 | MOD = 10**9+7
k = int(input())
s = input()
n = len(s)
U = n+k
fact = [0]*(U+1)
fact[0] = 1
for i in range(1, U+1):
fact[i] = fact[i-1]*i % MOD
invfact = [0]*(U+1)
invfact[U] = pow(fact[U], MOD-2, MOD)
for i in reversed(range(U)):
invfact[i] = invfact[i+1]*(i+1) % MOD
def nCr(n, r):
if r < 0 or n... |
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution.... | 3 | n = (int(input()))
count = 0
for x in range(n):
a, b, c = map(int, input().split())
if a+b+c > 1:
count += 1
print(count) |
On a random day, Neko found n treasure chests and m keys. The i-th chest has an integer a_i written on it and the j-th key has an integer b_j on it. Neko knows those chests contain the powerful mysterious green Grapes, thus Neko wants to open as many treasure chests as possible.
The j-th key can be used to unlock the ... | 3 | def main():
n, m = (int(x) for x in input().strip().split(" "))
a = [int(x) for x in input().strip().split(" ")]
b = [int(x) for x in input().strip().split(" ")]
answer = solve(a, b)
print(answer)
def is_odd(num):
return num % 2 == 1
def is_even(num):
return num % 2 == 0
def solve(a, b):
term1 = m... |
For given two sequences $X$ and $Y$, a sequence $Z$ is a common subsequence of $X$ and $Y$ if $Z$ is a subsequence of both $X$ and $Y$. For example, if $X = \\{a,b,c,b,d,a,b\\}$ and $Y = \\{b,d,c,a,b,a\\}$, the sequence $\\{b,c,a\\}$ is a common subsequence of both $X$ and $Y$. On the other hand, the sequence $\\{b,c,a... | 3 | def Ics(X, Y):
m = len(X)
n = len(Y)
c1 = [0] * (n + 1)
for i in range(m):
d = X[i]
c2 = c1[:]
for j in range(n):
if (d == Y[j]):
c1[j + 1] = c2[j] + 1
elif (c1[j + 1] < c1[j]):
c1[j + 1] = c1[j]
return (c1[-1])
q = int... |
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made lik... | 1 | t =input()
while t:
a = raw_input()
b = len(a)
if b<=10:
print a
else:
print a[0]+str(b-2)+a[b-1]
t-=1 |
When Valera has got some free time, he goes to the library to read some books. Today he's got t free minutes to read. That's why Valera took n books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to n. Valera needs ai minutes to read the ... | 1 |
n, t = map(int, raw_input().split(" "))
a = map(int, raw_input().split(" "))
x = 0
s = 0
limiteDeEsquerda = 0
limiteDeDireita = 0
while limiteDeDireita < n:
if t < s + a[limiteDeDireita]:
s -= a[limiteDeEsquerda]
limiteDeEsquerda += 1
else:
s += a[limiteDeDireita]
limiteDeDir... |
There are n programmers that you want to split into several non-empty teams. The skill of the i-th programmer is a_i. You want to assemble the maximum number of teams from them. There is a restriction for each team: the number of programmers in the team multiplied by the minimum skill among all programmers in the team ... | 3 | from collections import deque
from collections import OrderedDict
import math
import sys
import os
import threading
import bisect
import operator
import heapq
from atexit import register
from io import BytesIO
#sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
#sys.stdout = BytesIO()
#register(lambda: os.wri... |
You are given array a_1, a_2, ..., a_n. Find the subsegment a_l, a_{l+1}, ..., a_r (1 ≤ l ≤ r ≤ n) with maximum arithmetic mean (1)/(r - l + 1)∑_{i=l}^{r}{a_i} (in floating-point numbers, i.e. without any rounding).
If there are many such subsegments find the longest one.
Input
The first line contains single integer... | 3 | import sys
inn = lambda:input().strip()
N = int(inn())
A = tuple(int(a) for a in inn().split(" "))
mx = max(A)
mxIndex = tuple(i for i in range(N) if A[i]==mx)
maxCount = 1
count = 1
before = mxIndex[0]
for i in range(1, len(mxIndex)):
if mxIndex[i] - before == 1:
count += 1
maxCount = max(maxCou... |
You are given a positive integer n, it is guaranteed that n is even (i.e. divisible by 2).
You want to construct the array a of length n such that:
* The first n/2 elements of a are even (divisible by 2);
* the second n/2 elements of a are odd (not divisible by 2);
* all elements of a are distinct and positi... | 3 | t = int(input())
for i in range(t):
n = int(input())
if(n%4 != 0):
print("NO")
continue
a1 = []
a2 = []
curx = 3
for i in range(n//4):
a1.append(curx-2)
a1.append(curx+2)
a2.append(curx+1)
a2.append(curx-1)
curx+=6
print("YES")
print(*(a2+a1))
|
Gildong recently learned how to find the [longest increasing subsequence](https://en.wikipedia.org/wiki/Longest_increasing_subsequence) (LIS) in O(nlog{n}) time for a sequence of length n. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though the... | 1 | from sys import stdin
out = []
for _ in range(int(input())):
n, s = map(str, stdin.readline().split())
n = int(n)
s += '.'
ma, mi = list(range(1, n + 1)), list(range(n, 0, -1))
i, j = 0, 0
while i < n - 1:
while j < n and s[i] == s[j]:
j += 1
if s[i] == '<':
... |
Kana was just an ordinary high school girl before a talent scout discovered her. Then, she became an idol. But different from the stereotype, she is also a gameholic.
One day Kana gets interested in a new adventure game called Dragon Quest. In this game, her quest is to beat a dragon.
<image>
The dragon has a hit p... | 3 |
T = int(input())
for _ in range(T):
# a, b, c, d = map(int, input().split())
x, n, m = map(int, input().split())
lul = x
haha = n
while x > 0 and n > 0:
x //= 2
x += 10
n -= 1
x -= (m*10)
lul -= (m*10)
while lul > 0 and haha > 0:
lul //= 2
lul += ... |
Doubly linked list is one of the fundamental data structures. A doubly linked list is a sequence of elements, each containing information about the previous and the next elements of the list. In this problem all lists have linear structure. I.e. each element except the first has exactly one previous element, each eleme... | 3 | l=[]
l2=[]
r2=[]
r=[]
a=[]
u=0
q=0
p=0
n = int(input())
for i in range(n):
x1,x2 = map(int, input().split())
l.append(x1)
r.append(x2)
if x1==0:
u=u+1
for i2 in range(u):
y=0
for i in range(p,n):
if l[i]==0 and y==0:
a.append(i+1)
y=1
q=i
p=i+1
while r[q]!=0:
a.append(r[q])
... |
The professor is conducting a course on Discrete Mathematics to a class of N students. He is angry at the lack of their discipline, and he decides to cancel the class if there are fewer than K students present after the class starts.
Given the arrival time of each student, your task is to find out if the class gets ca... | 1 | for i in range(input()):
n,k=map(int,raw_input().split(" "))
stud=map(int,raw_input().split(" "))
c=0
for i in stud:
if i<=0:
c=c+1
else:
c=c
if c<k:
print "YES"
else:
print "NO" |
You are given a string S consisting of lowercase English letters. Another string T is initially empty. Determine whether it is possible to obtain S = T by performing the following operation an arbitrary number of times:
* Append one of the following at the end of T: `dream`, `dreamer`, `erase` and `eraser`.
Constrain... | 3 | import re
s = input()
print('YES' if re.match('^(dream|dreamer|erase|eraser)+$', s) else 'NO') |
Each day in Berland consists of n hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a_1, a_2, ..., a_n (each a_i is either 0 or 1), where a_i=0 if Polycarp works during the i-th hour of the day and a_i=1 if Polycarp rests during the i-th hour of the day.
Days go ... | 3 | n = int(input())
a = input().split()
a += a;
m = 0; num = 0;
for i in a:
if i == '1': num += 1;
else: num = 0;
if num > m: m = num;
print(m)
|
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 | def fun():
a=int(input())
if a%5==0:
print(a//5)
else:
print((a//5)+1)
fun(); |
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the... | 3 | n,h=map(int,input().split())
cnt=0
he=[int(x) for x in input().split()]
for i in range(0,n):
if(he[i]>h):
cnt+=1
print((n-cnt)+(cnt*2))
|
Little girl Alyona is in a shop to buy some copybooks for school. She study four subjects so she wants to have equal number of copybooks for each of the subjects. There are three types of copybook's packs in the shop: it is possible to buy one copybook for a rubles, a pack of two copybooks for b rubles, and a pack of t... | 1 | n, a, b, c = map(int, raw_input().split())
mins = dict()
mins[0] = 0
mins[1] = min(a, b + c, 3 * c)
mins[2] = min(2 * mins[1], b, 2 * c)
mins[3] = min(3 * mins[1], mins[1] + mins[2], c)
rem = n % 4
rest = 4 - rem if rem else 0
print mins[rest] |
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 | from sys import stdin, stdout
str1 = stdin.readline().lower()
str2 = stdin.readline().lower()
if str1 < str2:
stdout.write("-1")
elif str1 > str2:
stdout.write("1")
else:
stdout.write("0")
|
Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first n. He writes down the followin... | 1 | t = map( int, raw_input().split())
n = t[0]
k = t[1]
if n%2 == 0 :
if k == n/2 :
print n-1
if( k> n/2):
print 2*(k-n/2)
if k< n/2 :
print 2*k - 1
if n%2 == 1 :
if( k == (n/2 + 1)):
print n
if( k < (n/2 + 1)):
print 2*k - 1
if( k> (n/2+1)):
pr... |
A permutation is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as pi. We'll call number n the size of permutation p1, p2, ..., pn.
Nickolas adores permutations. He likes some permutations more than the o... | 3 | import sys
n = int(input())
if(n % 2 == 1):
print(-1)
sys.exit()
for i in range(1, n + 1, 2):
print(i + 1)
print(i)
sys.exit() |
Ted has a pineapple. This pineapple is able to bark like a bulldog! At time t (in seconds) it barks for the first time. Then every s seconds after it, it barks twice with 1 second interval. Thus it barks at times t, t + s, t + s + 1, t + 2s, t + 2s + 1, etc.
<image>
Barney woke up in the morning and wants to eat the ... | 1 | # -*- coding: utf-8 -*-
if __name__ == '__main__':
t, s, x = map(int, raw_input().split())
if x == t:
result = 'YES'
elif x < t:
result = 'NO'
else:
d, m = divmod(x-t, s)
if d > 0 and m in (0, 1):
result = 'YES'
else:
result = 'NO'
pr... |
So you decided to hold a contest on Codeforces. You prepared the problems: statements, solutions, checkers, validators, tests... Suddenly, your coordinator asks you to change all your tests to multiple testcases in the easiest problem!
Initially, each test in that problem is just an array. The maximum size of an array... | 3 | #The Greedy algorithm takes as many arrays as possible for the
#earlier test cases.
import sys
input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
n,k=[int(x) for x in input().s... |
You are given a sequence a_1, a_2, ..., a_n consisting of n integers.
You can choose any non-negative integer D (i.e. D ≥ 0), and for each a_i you can:
* add D (only once), i. e. perform a_i := a_i + D, or
* subtract D (only once), i. e. perform a_i := a_i - D, or
* leave the value of a_i unchanged.
It is... | 3 | from collections import Counter
n=int(input())
l=list(map(int,input().split()))
d=Counter(l)
k=list(d.keys())
# print(k)
a=min(k)
b=max(k)
if(len(k)==2 and (a+b)&1):
print(b-a)
elif(len(k)==2):
print((b-a)//2)
elif(len(k)<=3):
if((a+b)&1):
print(-1)
elif((a+b)//2 in k):
print((b-a)/... |
Professor GukiZ makes a new robot. The robot are in the point with coordinates (x1, y1) and should go to the point (x2, y2). In a single step the robot can change any of its coordinates (maybe both of them) by one (decrease or increase). So the robot can move in one of the 8 directions. Find the minimal number of steps... | 1 | #in the name of God
st=raw_input()
i=0
while(st[i]!=" "):
i+=1
x1=int(st[0:i])
y1=int(st[i+1:])
st=raw_input()
i=0
while(st[i]!=" "):
i+=1
x2=int(st[0:i])
y2=int(st[i+1:])
ex=x2-x1
ey=y2-y1
if(ex!=0 or ey!=0):
if abs(ex)>abs(ey):
ay,ax=ey,abs(ey)*(abs(ex)/ex)
else:
ay,ax=abs(ex)*(... |
Kicker (table football) is a board game based on football, in which players control the footballers' figures mounted on rods by using bars to get the ball into the opponent's goal. When playing two on two, one player of each team controls the goalkeeper and the full-backs (plays defence), the other player controls the ... | 3 | a1,d1 = [int(a) for a in input().split()]
a2,d2 = [int(a) for a in input().split()]
a3,d3 = [int(a) for a in input().split()]
a4,d4 = [int(a) for a in input().split()]
# Team 1 wins if E a team 1 st A team 2, team 1 must win
# Team 2 wins if A team 1 E team 2 st team 2 must win
team1win = False
for (A1,D1) in [(a1,d2... |
There is a bookshelf which can fit n books. The i-th position of bookshelf is a_i = 1 if there is a book on this position and a_i = 0 otherwise. It is guaranteed that there is at least one book on the bookshelf.
In one move, you can choose some contiguous segment [l; r] consisting of books (i.e. for each i from l to r... | 3 | for i in range(int(input())):
n = int(input())
res = ''.join(input().split()).strip('0').count('0')
print(res)
|
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy... | 3 | n = int(input())
x = y = z = 0
for i in range(n):
xf, yf, zf = tuple(map(int, input().split()))
x += xf
y += yf
z += zf
if x == 0 and y == 0 and z == 0:
print('YES')
else:
print('NO')
|
Prof. Hachioji has devised a new numeral system of integral numbers with four lowercase letters "m", "c", "x", "i" and with eight digits "2", "3", "4", "5", "6", "7", "8", "9". He doesn't use digit "0" nor digit "1" in this system.
The letters "m", "c", "x" and "i" correspond to 1000, 100, 10 and 1, respectively, and ... | 1 | n = int(raw_input())
num = [1000, 100, 10, 1]
cha = ['m', 'c', 'x', 'i']
for i in xrange(n):
po = raw_input().split()
poyo = [0, 0]
for j in xrange(2):
c = 1
for k in xrange(len(po[j])):
if po[j][k] == cha[0]:
poyo[j] += c*num[0]
c = 1
... |
Vasya has a multiset s consisting of n integer numbers. Vasya calls some number x nice if it appears in the multiset exactly once. For example, multiset \{1, 1, 2, 3, 3, 3, 4\} contains nice numbers 2 and 4.
Vasya wants to split multiset s into two multisets a and b (one of which may be empty) in such a way that the q... | 3 | n = int(input())
a = list(map(int, input().split()))
b = dict()
for x in a:
b[x] = b.get(x, 0) + 1
A = dict()
B = dict()
cnta = 0
cntb = 0
for k, v in b.items():
if v == 1:
if cnta > cntb:
cntb += 1
B[k] = 1
else:
cnta += 1
A[k] = 1
for k, v in b.... |
You are given an integer N. Among the divisors of N! (= 1 \times 2 \times ... \times N), how many Shichi-Go numbers (literally "Seven-Five numbers") are there?
Here, a Shichi-Go number is a positive integer that has exactly 75 divisors.
Constraints
* 1 \leq N \leq 100
* N is an integer.
Input
Input is given from S... | 3 | N = [int(_) for _ in input().split()][0]
e = [0] * (N + 1)
for i in range(2, N + 1):
tmp = i
for j in range(2, i + 1):
if tmp <= 1: break
while tmp % j == 0:
e[j] += 1
tmp //= j
dp = [[0] * 76 for _ in range(N + 1)]
dp[0][1] = 1
for i in range(1, N + 1):
for j in ... |
You are given a board of size n × n, where n is odd (not divisible by 2). Initially, each cell of the board contains one figure.
In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell (i, j) you can move... | 3 | t =int(input())
for i in range(t):
n = int(input())
ans =0
for x in range(1, (n-1)//2+1):
m = 2*x-1
ans += x*((m+2)*2+m*2)
print(ans)
|
Today's morning was exceptionally snowy. Meshanya decided to go outside and noticed a huge snowball rolling down the mountain! Luckily, there are two stones on that mountain.
Initially, snowball is at height h and it has weight w. Each second the following sequence of events happens: snowball's weights increases by i,... | 3 | w, h = map(int, input().split())
u1, d1 = map(int, input().split())
u2, d2 = map(int, input().split())
while h >= 0:
w += h
if h == d1:
w = max(0, w - u1)
elif h == d2:
w = max(0, w - u2)
h -= 1
print(w)
|
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.
Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, seco... | 3 | a = int(input())
out = ""
for i in range(0,a):
if i%2 == 0:
out = out + 'I hate '
else:
out = out + 'I love '
if i != a-1:
out = out + 'that '
else:
out = out+'it'
print(out) |
You manage 4 buildings, each of which has 3 floors, each of which consists of 10 rooms. Write a program which reads a sequence of tenant/leaver notices, and reports the number of tenants for each room.
For each notice, you are given four integers b, f, r and v which represent that v persons entered to room r of fth fl... | 3 | wall = "#" * 20
n = int(input())
dat = []
for _ in range(12):
dat.append([0] * 10)
for _ in range(n):
b,f,r,v = map(int, input().split())
dat[3 * (b - 1) + ( f-1)][r - 1] += v
for i in range(12):
print(" ",end="")
print(" ".join(map(str, dat[i])))
if i % 3 == 2 and i!=11:
print(wall)
|
Arkady's morning seemed to be straight of his nightmare. He overslept through the whole morning and, still half-asleep, got into the tram that arrived the first. Some time after, leaving the tram, he realized that he was not sure about the line number of the tram he was in.
During his ride, Arkady woke up several time... | 3 | from collections import Counter as c
x=int(input())
l=[]
for i in range(x):
l=l+list(map(int,input().split()))[1:]
l=dict(c(l))
for a,b in l.items():
if b==x:
print(a,end=' ')
|
In this problem, your task is to use ASCII graphics to paint a cardiogram.
A cardiogram is a polyline with the following corners:
<image>
That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an.
Your task is to paint a cardiogram by given sequence ai.
Input
The first line contai... | 3 | import operator
n = int(input())
points = list(map(int, input().split()))
def praf(g):
for i in g[1:]:
print(''.join(i))
def calc(n):
global points
a = b = 0
step = 1
for i in range(n):
a += points[i]
b += points[i] * step
step = -step
return (a, b)
seq = [(0,... |
There are n programmers that you want to split into several non-empty teams. The skill of the i-th programmer is a_i. You want to assemble the maximum number of teams from them. There is a restriction for each team: the number of programmers in the team multiplied by the minimum skill among all programmers in the team ... | 3 | t = int(input())
MAX = 9999999999
for _ in range(t):
n,x = map(int,input().split())
a = list(map(int,input().split()))
a.sort(reverse=True)
ans = 0
current = 0
cur_min = MAX
for i in range(n):
cur_min = min(cur_min,a[i])
current+=1
if cur_min * current >= x:
... |
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] = list(map(int, input().split(" ")))
for i in range(k):
if n % 10 != 0:
n -= 1
else:
n /= 10
print(int(n)) |
Sonya decided to organize an exhibition of flowers. Since the girl likes only roses and lilies, she decided that only these two kinds of flowers should be in this exhibition.
There are n flowers in a row in the exhibition. Sonya can put either a rose or a lily in the i-th position. Thus each of n positions should cont... | 3 | # -*- coding: utf-8 -*-
def problem(in1):
inp1 = list(map(int, in1.split()))
n = inp1[0]
guests = inp1[1]
s = ''.join(['10' for x in range(n // 2)])
if n % 2 == 1:
s += '1'
return s;
if __name__ == '__main__':
in1 = input()
result = problem(in1)
print(result)
|
You've got another problem dealing with arrays. Let's consider an arbitrary sequence containing n (not necessarily different) integers a1, a2, ..., an. We are interested in all possible pairs of numbers (ai, aj), (1 ≤ i, j ≤ n). In other words, let's consider all n2 pairs of numbers, picked from the given array.
For e... | 1 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
n,k = map(int, raw_input().split())
l = map(int, raw_input().split())
#n,k = 8, 56
#l = [10 ,1,1,4,10,10, 4 ,4]
l.sort()
if k%n == 0:
c = k/n -1
else:
c = k//n
#print l[c]
s = l.count(l[c])
if s > 1:
x = 0
while l[x] < l[c]:
x += 1
k -= x*n
#pri... |
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of n students doing yet another trick.
Let's assume that all these students are numbered from 1 to n. The teacher came to student a and put a hole in his badge. The student, ... | 3 | n = int(input())
s =list(map(int,input().split()))
for i in range(n):
a=[1]*n
while a[i]:
a[i]=0
i=s[i]-1
print(i+1,end=' ')
|
You have n gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The i-th gift consists of a_i candies and b_i oranges.
During one move, you can choose some gift 1 ≤ i ≤ n and do one of the following operations:
* eat exactly... | 3 | t=int(input())
a=[[]]*t
b=[[]]*t
for i in range(t):
n=int(input())
a[i]=list(map(int,input().strip().split()))[:n]
b[i]=list(map(int,input().strip().split()))[:n]
for i in range(t):
ans=0
am=min(a[i])
bm=min(b[i])
for j in range(len(a[i])):
ans+=max(a[i][j]-am,b[i][j]-bm)
print(... |
<image>
Input
The input contains two integers row, col (0 ≤ row, col ≤ 63), separated by a single space.
Output
Output "IN" or "OUT".
Examples
Input
0 0
Output
OUT
Input
27 0
Output
IN
Input
0 27
Output
OUT
Input
27 27
Output
IN | 3 | s=[
" # # ###### # ",
" # ### # # # # ##### ",
" ### # # ## # # # ",
" #### # # ##### #### # ### # ",
" ## # # #### # #... |
You have n problems. You have estimated the difficulty of the i-th one as integer ci. Now you want to prepare a problemset for a contest, using some of the problems you've made.
A problemset for the contest must consist of at least two problems. You think that the total difficulty of the problems of the contest must b... | 3 | import math,sys
from collections import defaultdict,deque
import bisect as bi
def yes():print('YES')
def no():print('NO')
def I():return (int(sys.stdin.readline()))
def In():return(map(int,sys.stdin.readline().split()))
def Sn():return sys.stdin.readline().strip()
def Pr(x): sys.stdout.write(str(x)+'\n')
#sys.setrecurs... |
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to r... | 3 | import sys
n=int(input())
arr=list(map(int,input().split()))
pref=[0]*n
suff=[0]*n
pref[0],suff[n-1]=sys.maxsize,sys.maxsize
for i in range(1,n):pref[i]=pref[i-1]&(~arr[i-1])
for i in range(n-2,-1,-1):suff[i]=suff[i+1]&(~arr[i+1])
ans=-sys.maxsize-1
temp=0
for i in range(n):
temp=pref[i]&arr[i]&suff[i]
if temp>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'... | 3 | a,b,c=map(int,input().split())
if a%c==0 :
k1=a//c
else:
k1=(a//c)+1
if b%c==0 :
k2=b//c
else:
k2=(b//c)+1
print(k1*k2) |
Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited n his friends there.
If t... | 3 | n = int(input())
gifts = list(map(int,input().split()))
getGifts = ['0']*n
for i in range(n):
getGifts[int(gifts[i])-1] = str(i+1)
print (" ".join(getGifts)) |
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 | print(eval('*'.join(input().split()))//2) |
You are given a string s consisting of |s| small english letters.
In one move you can replace any character of this string to the next character in alphabetical order (a will be replaced with b, s will be replaced with t, etc.). You cannot replace letter z with any other letter.
Your target is to make some number of ... | 3 | def main():
s = list(input())
curr = ord('a')
for i in range(len(s)):
if ord(s[i]) <= curr and curr <= ord('z'):
s[i] = chr(curr)
curr += 1
if curr <= ord('z'):
print(-1)
return
new = ''
for i in s:
new += i
print(new)
main()
|
Given an array a of length n, find another array, b, of length n such that:
* for each i (1 ≤ i ≤ n) MEX(\\{b_1, b_2, …, b_i\})=a_i.
The MEX of a set of integers is the smallest non-negative integer that doesn't belong to this set.
If such array doesn't exist, determine this.
Input
The first line contains an ... | 3 | def get_not_elements(a:list):
elements = set(a)
max_element = a[-1] +2
not_elements = []
for i in range(0,max_element):
if not i in elements:
not_elements.append(i)
not_elements.reverse()
return not_elements
#Ahora pensar esta funcion...
def is_valid(a : list):
for i i... |
You've got a rectangular table with length a and width b and the infinite number of plates of radius r. Two players play the following game: they take turns to put the plates on the table so that the plates don't lie on each other (but they can touch each other), and so that any point on any plate is located within the... | 3 | a,b,r=map(int,input().split())
print('Second' if min(a,b)<2*r else 'First') |
Screen resolution of Polycarp's monitor is a × b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x, y) (0 ≤ x < a, 0 ≤ y < b). You can consider columns of pixels to be numbered from 0 to a-1, and rows — from 0 to b-1.
Polycarp wants to open a rectangular window of maximal size, which ... | 3 | # https://codeforces.com/contest/1315/problem/A
for _ in range(int(input())):
a,b,x,y = map(int,input().split())
area = [ (a) * (y) , (x) * (b) , (a-x-1) * (b) , (b-y-1) * (a) ]
print(max(area))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.