problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
We have a square grid with H rows and W columns. Snuke wants to write 0 or 1 in each of the squares. Here, all of the following conditions have to be satisfied:
* For every row, the smaller of the following is A: the number of 0s contained in the row, and the number of 1s contained in the row. (If these two numbers ar... | 3 | H, W, A, B = map(int, input().split())
for _ in range(B):
print('0' * A + '1' * (W - A))
for _ in range(H - B):
print('1' * A + '0' * (W - A))
|
This is an interactive problem.
You are given a sorted in increasing order singly linked list. You should find the minimum integer in the list which is greater than or equal to x.
More formally, there is a singly liked list built on an array of n elements. Element with index i contains two integers: valuei is the int... | 3 | from random import sample
def R():
return map(int, input().split())
def ask(i):
print('?', i, flush=True)
v, nxt = R()
if v < 0:
exit()
return v, nxt
def ans(v):
print('!', v)
exit()
n, s, x = R()
mv = -1
i = s
SIZE = 950
q = range(1, n + 1)
if n > SIZE:
q = sample(q, SIZE)
... |
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.
The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe... | 3 | l=input()
l2=[]
for i in range(0,len(l)):
if l[i] != '+':
l2.append(int(l[i]))
l2.sort()
s=""
s+=str(l2[0])
for i in range(1,len(l2)):
s+='+'
s+=str(l2[i])
print(s) |
One day Jeff got hold of an integer sequence a1, a2, ..., an of length n. The boy immediately decided to analyze the sequence. For that, he needs to find all values of x, for which these conditions hold:
* x occurs in sequence a.
* Consider all positions of numbers x in the sequence a (such i, that ai = x). These... | 3 | n = int(input())
elements = list(map(int, input().split()))
i, d = 0, {}
for j in elements:
if j in d:
d[j].append(i)
else:
d[j] = [i]
i += 1
final = []
for x, v in d.items():
if len(v) == 1:
final.append((x, 0))
else:
s = set([v[i] - v[i - 1] for i in range(1, len(... |
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 weightControl(w:int) -> bool:
if w < 4 or w % 2: #Even ingredients of 2 are 0 and 2. The two of the boys need to eat...
return False
else:
return True
if __name__ == "__main__":
w = int(input()) # Watermelon weight
print("YES" if weightControl(w) else "NO") |
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." β an excerpt from contest rules.
A total of n participants took part in the contest (n β₯ k), and you already know their scores. Calculate how many ... | 1 | # -*- coding: utf-8 -*-
"""
The first line of the input contains two integers n and k (1ββ€βkββ€βnββ€β50) separated by a single space.
The second line contains n space-separated integers a1,βa2,β...,βan (0ββ€βaiββ€β100),
where ai is the score earned by the participant who got the i-th place.
The given sequence is non-incre... |
What joy! Petya's parents went on a business trip for the whole year and the playful kid is left all by himself. Petya got absolutely happy. He jumped on the bed and threw pillows all day long, until...
Today Petya opened the cupboard and found a scary note there. His parents had left him with duties: he should water... | 3 | n=int(input())
a=[int(x) for x in input().split()]
a.sort(reverse=True)
p=0
for i in range (0,len(a)):
p += a[i]
if(p>=n):
break
if(n==0):
print("0")
elif (p<n):
print("-1")
else :
print(i+1) |
Suppose you are performing the following algorithm. There is an array v_1, v_2, ..., v_n filled with zeroes at start. The following operation is applied to the array several times β at i-th step (0-indexed) you can:
* either choose position pos (1 β€ pos β€ n) and increase v_{pos} by k^i;
* or not choose any posit... | 3 | t = int(input())
for _ in range(t):
n, k = map(int, input().split())
a = list(map(int, input().split()))
while any(a):
flg = 0
for i in range(n):
if (flg and a[i] % k == 1) or a[i] % k > 1:
print('NO')
break
elif a[i] % k == 1:
... |
You are given a non-decreasing array of non-negative integers a_1, a_2, β¦, a_n. Also you are given a positive integer k.
You want to find m non-decreasing arrays of non-negative integers b_1, b_2, β¦, b_m, such that:
* The size of b_i is equal to n for all 1 β€ i β€ m.
* For all 1 β€ j β€ n, a_j = b_{1, j} + b_{2, j}... | 3 | import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.wri... |
Takahashi wants to be a member of some web service.
He tried to register himself with the ID S, which turned out to be already used by another user.
Thus, he decides to register using a string obtained by appending one character at the end of S as his ID.
He is now trying to register with the ID T. Determine whether... | 3 | S = input()
T = input()
print('Yes' if S == T[:-1] else 'No') |
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 ... | 3 | for _ in range(int(input())):
n = int(input())
l = [int(s)-1 for s in input().split()]
visited = [0]*n
ans = [0]*n
d = [0]*n
for i in range(n):
j = l[i]
ann = 1
if not visited[i]:
d[i] = i
visited[i] = 1
while j != i:
vi... |
problem
You decide to invite your friends of the school and your friends of a friend to the Christmas party. The number of students in your school is n, and each student is assigned a number from 1 to n. Your number is 1. You have a list of who and who are your friends. Based on this list, create a program that asks f... | 3 | def solve():
while True:
n = int(input())
if not n:
break
m = int(input())
edge = [[0 for i in range(n + 1)] for j in range(n + 1)]
for i in range(m):
a,b = map(int,input().split())
edge[a][b] = 1
edge[b][a] = 1
friends1 = [i for i in range(n + 1) if edge[1][i]]
fri... |
Colonel has n badges. He wants to give one badge to every of his n soldiers. Each badge has a coolness factor, which shows how much it's owner reached. Coolness factor can be increased by one for the cost of one coin.
For every pair of soldiers one of them should get a badge with strictly higher factor than the secon... | 1 | [n] = map(int, raw_input('').split(' '))
nums = map(int, raw_input('').split(' '))
nums.sort()
distinct = []
distinct.append(nums[0])
repeats = []
for i in xrange(1, n):
if nums[i] != nums[i - 1]:
distinct.append(nums[i])
else:
repeats.append(nums[i])
coins = 0
distinct_length = len(distinct)
n... |
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 | m,n=[int(x) for x in input().split()]
if m%2==0 or n%2==0:
print(n*m//2)
else:
print(n*m//2)
|
Pashmak decided to give Parmida a pair of flowers from the garden. There are n flowers in the garden and the i-th of them has a beauty number bi. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty difference i... | 1 | import math
input()
l=map(int,raw_input().split(' '))
l.sort(reverse=True)
s=set(l)
if len(s)==1:
print 0,sum(range(len(l)))
else:
print l[0]-l[-1],l.count(l[0])*l.count(l[-1])
|
Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of length k have the same sum. A subarray of an array is any sequence of consecutive elements.
Phoenix currently has an array a of length n. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautifu... | 3 | t=int(input())
for _ in range(t):
n,k=map(int,input().split())
List=list(map(int,input().split()))
x=list(set(List))
if len(x)>k:
print(-1)
else:
i=0
print(n*k)
for i in range(n):
for j in x:
print(j,end=" ")
for l in range(0,k-... |
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... | 3 | n,k=map(int,input().split())
o,e=(n+1)//2,n//2
if(k<=o):
print(int(k*2)-1)
else:
print(int((k-o)*2)) |
You are given a string s consisting of n lowercase Latin letters. Polycarp wants to remove exactly k characters (k β€ n) from the string s. Polycarp uses the following algorithm k times:
* if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;
* if th... | 3 | # Author: S Mahesh Raju
# Username: maheshraju2020
# Date: 04/07/2020
from sys import stdin,stdout
from math import gcd, ceil, sqrt
from collections import Counter
ii1 = lambda: int(stdin.readline().strip())
is1 = lambda: stdin.readline().strip()
iia = lambda: list(map(int, stdin.readline().strip().split()))
isa = lam... |
Nastya just made a huge mistake and dropped a whole package of rice on the floor. Mom will come soon. If she sees this, then Nastya will be punished.
In total, Nastya dropped n grains. Nastya read that each grain weighs some integer number of grams from a - b to a + b, inclusive (numbers a and b are known), and the wh... | 3 | for _ in range(int(input())):
n,a,b,c,d=map(int,input().split())
minn=c-d
maxx=c+d
if (a+b)*n<minn or n*(a-b)>maxx:
print('NO')
else:
print('YES')
|
This week Arkady wanted to cook some pancakes (to follow ancient traditions) and make a problem about that. But then he remembered that one can't make a problem about stacking pancakes without working at a specific IT company, so he decided to bake the Napoleon cake instead.
To bake a Napoleon cake, one has to bake n ... | 3 | t = int(input())
mas = [0] * (2 * (10**5) + 1)
for i in range(t):
n = int(input())
cnt = 0
buf = input().split()
for j in range(n, 0, -1):
x = int(buf[j - 1])
cnt = max(cnt, x)
if (cnt > 0):
mas[j] = 1
cnt -= 1
else:
mas[... |
On the Planet AtCoder, there are four types of bases: `A`, `C`, `G` and `T`. `A` bonds with `T`, and `C` bonds with `G`.
You are given a letter b as input, which is `A`, `C`, `G` or `T`. Write a program that prints the letter representing the base that bonds with the base b.
Constraints
* b is one of the letters `A`... | 3 | b = input()
a = {'A':'T', 'T':'A', 'C':'G', 'G':'C'}
print(a[b]) |
The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her n students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often oddl... | 1 | n,m=map(int,raw_input().split(" "))
arr=map(int,raw_input().split(" "))
diff=10000
arr.sort()
for k,v in enumerate(arr):
if k+n-1<len(arr) and arr[k+n-1]-arr[k]<diff:
diff=arr[k+n-1]-arr[k]
print diff |
Is it rated?
Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.
Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before ... | 3 | x = int(input())
lst1 = [];lst2=[]
for i in range(x) :
y,z = map(int,input().split())
lst1.append(y);lst2.append(z)
if lst1[i] != lst2[i] :
print("rated");exit(0)
for i in range(1,x):
if lst1[i]>lst1[i-1]:
print("unrated");break
else :
print("maybe")
|
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob β to check his answers, he needs a program that among the given n numbers finds one that is di... | 3 | n = int(input())
ar = list(map(int, input().split()))
odd, odd_i, even, even_i = 0, 0, 0, 0
for i in range(n):
if ar[i] % 2 == 0:
even += 1
even_i = i + 1
else:
odd += 1
odd_i = i + 1
if even != 0 and odd != 0 and (even > 1 or odd > 1):
if even > 1:
print(... |
There are two sisters Alice and Betty. You have n candies. You want to distribute these n candies between two sisters in such a way that:
* Alice will get a (a > 0) candies;
* Betty will get b (b > 0) candies;
* each sister will get some integer number of candies;
* Alice will get a greater amount of candie... | 3 | import math
i = int(input())
while i != 0:
x = int(input())
if x < 3:
print(0)
i -= 1
elif x % 2 != 0:
print(int((x - 1) / 2))
i -= 1
else:
print(int(math.floor((x - 1) / 2)))
i -= 1
|
On the planet Mars a year lasts exactly n days (there are no leap years on Mars). But Martians have the same weeks as earthlings β 5 work days and then 2 days off. Your task is to determine the minimum possible and the maximum possible number of days off per year on Mars.
Input
The first line of the input contains a ... | 3 | n = int(input())
div, mod = divmod(n, 7)
_min = 2 * div + max(0, mod - 5)
_max = 2 * div + min(2, mod)
print(_min, _max) |
Melody Pond was stolen from her parents as a newborn baby by Madame Kovarian, to become a weapon of the Silence in their crusade against the Doctor. Madame Kovarian changed Melody's name to River Song, giving her a new identity that allowed her to kill the Eleventh Doctor.
Heidi figured out that Madame Kovarian uses a... | 3 | r = int(input())
if r >= 5:
if r % 2 == 0:
print('NO')
else:
y = int((r-3)/2)
print(1,'',y)
else:
print('NO')
|
Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths a, b, and c. Now he needs to find out some possible integer length d of the fourth straight fence segment so that he can build the fence using these four... | 1 | #!/usr/bin/env python
from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
def main():
t = int(input())
for _ in range(t):... |
There is a fence in front of Polycarpus's home. The fence consists of n planks of the same width which go one after another from left to right. The height of the i-th plank is hi meters, distinct planks can have distinct heights.
<image> Fence for n = 7 and h = [1, 2, 6, 1, 1, 7, 1]
Polycarpus has bought a posh piano... | 3 | n, k = map(int, input().split())
l = list(map(int, input().split()))
ans = 1
su = sum(l[:k])
min_ = su
for i in range(n - k):
su += l[i + k] - l[i]
if su < min_:
min_ = su
ans = i + 2
print(ans)
|
Polycarp wants to buy exactly n shovels. The shop sells packages with shovels. The store has k types of packages: the package of the i-th type consists of exactly i shovels (1 β€ i β€ k). The store has an infinite number of packages of each type.
Polycarp wants to choose one type of packages and then buy several (one or... | 3 | from math import sqrt, ceil
from sys import stdin, stdout
int_in = lambda: int(stdin.readline())
arr_in = lambda: [int(x) for x in stdin.readline().split()]
mat_in = lambda rows: [arr_in() for y in range(rows)]
str_in = lambda: stdin.readline().strip()
out = lambda o: stdout.write("{}\n".format(o))
arr_out = lambda o:... |
Eugene likes working with arrays. And today he needs your help in solving one challenging task.
An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Let's call a nonempty... | 3 | input()
ns = [int(x) for x in input().split()]
loc = {0: -1}
start = -1
acc = 0
result = 0
for i, v in enumerate(ns):
acc += v
if acc in loc:
start = max(start, loc[acc] + 1)
result += i - start
loc[acc] = i
print(result)
|
You are given an array a[0 β¦ n-1] of length n which consists of non-negative integers. Note that array indices start from zero.
An array is called good if the parity of each index matches the parity of the element at that index. More formally, an array is good if for all i (0 β€ i β€ n - 1) the equality i mod 2 = a[i] m... | 3 | t=int(input())
while t:
n=int(input())
l=list(map(int,(input().split())))
e=0
o=0
swap=0
count=0
for i in range(0,n):
if i%2==0 :
if l[i]%2==0:
continue
else:
o+=1
if i%2==1... |
Duff is in love with lovely numbers! A positive integer x is called lovely if and only if there is no such positive integer a > 1 such that a2 is a divisor of x.
<image>
Malek has a number store! In his store, he has only divisors of positive integer n (and he has all of them). As a birthday present, Malek wants to g... | 1 | from math import sqrt as sq
n=input()
g=n
res=1
i=3
c=0
while n%2==0:
g/=2
n/=2
c+=1
if c>0:
g*=2
while i*i<=g:
c=0
while n%i==0:
g/=i
n/=i
c+=1
if c>0:
g*=i
i+=2
print g
|
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word s. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if... | 3 | s=input()
if 'h' in s:
h=s.index('h')
if 'e' in s[h+1:]:
e=s.index('e',h+1)
if 'l' in s[e+1:]:
l=s.index('l',e+1)
if 'l'in s[l+1:]:
ll=s.index('l',l+1)
if 'o' in s[ll+1:]:
o=s.index('o',ll+1)
if h<e<l... |
This contest is `CODE FESTIVAL`. However, Mr. Takahashi always writes it `CODEFESTIVAL`, omitting the single space between `CODE` and `FESTIVAL`.
So he has decided to make a program that puts the single space he omitted.
You are given a string s with 12 letters. Output the string putting a single space between the fi... | 3 | s = input().strip()
print(s[:4]+" "+s[4:]) |
The School β0 of the capital of Berland has n children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value ti:
* ti = 1, if the i-th child is good at programming,
*... | 3 | n = int(input())
a = [int(i) for i in input().split()]
s = min(a.count(1), a.count(2), a.count(3))
t1 = 0
t2 = 0
t3 = 0
print(s)
for i in range(s):
t1 = a[t1:].index(1) + t1 + 1
t2 = a[t2:].index(2) + t2 + 1
t3 = a[t3:].index(3) + t3 + 1
print(t1, t2, t3)
|
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 | square = raw_input().split()
n = int(square[0])
m = int(square[1])
a = int(square[2])
M=(m+a-1)/a
N=(n+a-1)/a
Answer=M*N
print Answer
|
New Year is coming and you are excited to know how many minutes remain before the New Year. You know that currently the clock shows h hours and m minutes, where 0 β€ hh < 24 and 0 β€ mm < 60. We use 24-hour time format!
Your task is to find the number of minutes before the New Year. You know that New Year comes when the... | 3 | import math
t = int(input())
for i in range(t):
h,m = map(int,input().split())
print((24-h-1)*60 + (60-m)) |
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 | f = int(input())
for i10 in range(f):
n, m = map(int, input().split())
if n == 1:
print(0)
elif n == 2:
print(m)
else:
print(m * 2)
|
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 ... | 3 | n,t=map(int,input().split())
lst=list(map(int,input().split()))
s,j=0,0
for i in range(n):
s=s+lst[i]
if s>t:
s=s-lst[j]
j=j+1
print(n-j) |
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 = input()
a, b = int(x.split()[0]), int(x.split()[1])
years = 0
while a <= b:
years += 1
a *= 3
b *= 2
print(years)
|
Winnie-the-Pooh likes honey very much! That is why he decided to visit his friends. Winnie has got three best friends: Rabbit, Owl and Eeyore, each of them lives in his own house. There are winding paths between each pair of houses. The length of a path between Rabbit's and Owl's houses is a meters, between Rabbit's an... | 3 | n,a,b,c=int(input()),int(input()),int(input()),int(input())
if a<=b and a<=c:
print(a*(n-1))
elif b<=c and b<=a:
print((n-1)*b)
elif a<=b and a>=c:
if n==1:
print("0")
else:
print((n-2)*c+a)
elif b<a and b>=c:
if n==1:
print("0")
else:
print((n-2)*c+b) |
Little boy Valera studies an algorithm of sorting an integer array. After studying the theory, he went on to the practical tasks. As a result, he wrote a program that sorts an array of n integers a1, a2, ..., an in the non-decreasing order. The pseudocode of the program, written by Valera, is given below. The input of ... | 1 | n = int(raw_input())
if n <= 2:
print -1
else:
print ' '.join(map(str,range(1, n + 1, 1)[::-1])) |
Vasya has got n books, numbered from 1 to n, arranged in a stack. The topmost book has number a_1, the next one β a_2, and so on. The book at the bottom of the stack has number a_n. All numbers are distinct.
Vasya wants to move all the books to his backpack in n steps. During i-th step he wants to move the book number... | 3 | from collections import defaultdict
n = int(input())
d = defaultdict(int)
a = list(map(int,input().split()))
for i in range(n):
d[a[i]] = i
b = list(map(int,input().split()))
prev = -1
ans = []
for i in range(n):
if(d[b[i]]>prev):
ans.append(str(d[b[i]]-prev))
prev = d[b[i]]
else:
ans.append('0')
print(' '.joi... |
ZS the Coder and Chris the Baboon are travelling to Udayland! To get there, they have to get on the special IOI bus. The IOI bus has n rows of seats. There are 4 seats in each row, and the seats are separated into pairs by a walkway. When ZS and Chris came, some places in the bus was already occupied.
ZS and Chris are... | 3 | n = int(input())
check = False
b = []
for _ in range (n):
a = list(input())
if(not check):
if(a[0]==a[1]=='O'):
a[0]=a[1]='+'
check = True
elif(a[3]==a[4]=='O'):
a[3]=a[4]='+';
check = True
b.append(a)
if(check):
... |
Atul opens a book store and soon he recives his first bill form his wholeseller. To see the bill is correct or not he try to cross check the bill. since he is weak at mathematics he ask you to sove his problem
P is product Q is quantity of product and T is total cost i.e P *Q=T
INPUT
first line of input contains no ... | 1 | test = int(raw_input())
for i in range(test):
a,b,c = map(int,raw_input().split())
if a*b == c:
print "YES"
else:
print "NO" |
Robot Doc is located in the hall, with n computers stand in a line, numbered from left to right from 1 to n. Each computer contains exactly one piece of information, each of which Doc wants to get eventually. The computers are equipped with a security system, so to crack the i-th of them, the robot needs to collect at ... | 1 | n = input()
a = list(map(int, raw_input().split()))
inf = float('inf')
r = -1
s = 0
while s < n:
for i in range(n):
if a[i] <= s:
a[i] = inf
s += 1
a.reverse()
r += 1
print r
|
Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpr... | 3 | # import math
def main():
a,b = map(int,input().split())
mx = max(a,b)
if mx==6:
print("1/6")
elif mx==5:
print("1/3")
elif mx==4:
print("1/2")
elif mx == 3:
print("2/3")
elif mx==2:
print("5/6")
else:
print("1/1")
main() |
Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings a and b of equal length are called equivalent in one of the two cases:
1. They are equal.
2. If we split string a into two halves of the same size a1 and a2, and string b into two halves of the same size b1 and b2... | 3 | def cut(a,b):
l=len(a)
if a==b:
return True
elif l%2==0:
y=0
middle = l//2
return (cut(a[0:middle],b[middle:l+1]) and cut(a[middle:l+1],b[0:middle])) or (cut(a[0:middle],b[0:middle]) and cut(a[middle:l+1],b[middle:l+1]))
else:
return False
if cut(input(),input()):
print('YES')
else:
p... |
The Fair Nut lives in n story house. a_i people live on the i-th floor of the house. Every person uses elevator twice a day: to get from the floor where he/she lives to the ground (first) floor and to get from the first floor to the floor where he/she lives, when he/she comes back home in the evening.
It was decided ... | 3 | def cost(n,arr,x):
tot = 0
for i in range(n):
tot +=(abs(x-i) + i + x)*arr[i]
return tot*2
def prog():
n = int(input())
arr = [int(x) for x in input().split()]
currcost = 10**18
for i in range(n):
currcost = min(currcost,cost(n,arr,i))
return currcost
print(prog()) |
Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play t matches of a digit game...
In each of t matches of the digit game, a positive integer is generated. It consists of n digits. The digits of this integer are numerated f... | 3 | t=int(input())
nums=[]
c=[]
def solve(num,n):
c1=False
c2=False
b=str(num)
for i in range(n):
if(i%2==0):
c1= c1 or (int(b[i])-0)%2==1
if i%2==1:
c2= c2 or (int(b[i])-0)%2==0
if (n%2==0):
if c2:
return 2
else:
return 1
... |
Polycarp has three sisters: Alice, Barbara, and Cerene. They're collecting coins. Currently, Alice has a coins, Barbara has b coins and Cerene has c coins. Recently Polycarp has returned from the trip around the world and brought n coins.
He wants to distribute all these n coins between his sisters in such a way that ... | 3 | q=int(input())
for j in range(q):
a,b,c,n=list(map(int,input().split(" ")))
if a==b and b==c:
if n%3==0:
print("YES")
else:
print("NO")
else:
d=max(a,b)
e=max(b,c)
g=max(d,e)
abc=g-a+g-b+g-c
n1=n-abc
if abc>n:
print("NO")
# print(n)
# print(n1)
elif n1%3==0:
print("YES")
el... |
Snuke, who loves animals, built a zoo.
There are N animals in this zoo. They are conveniently numbered 1 through N, and arranged in a circle. The animal numbered i (2β€iβ€N-1) is adjacent to the animals numbered i-1 and i+1. Also, the animal numbered 1 is adjacent to the animals numbered 2 and N, and the animal numbered... | 3 | N=int(input())
s=input()
g=0
def ki(a,b):
global g
l=[None]*N
l[-2],l[-1]=a,b
for i in range(-1,N-1):
if l[i-1]==l[i] and s[i]=="o":
l[i+1]=0
elif l[i-1]!=l[i] and s[i]=="x":
l[i+1]=0
else:
l[i+1]=1
if l[-2]==a and l[-1]==b and g==0:
... |
You have final scores of an examination for n students. Calculate standard deviation of the scores s1, s2 ... sn.
The variance Ξ±2 is defined by
Ξ±2 = (βni=1(si - m)2)/n
where m is an average of si. The standard deviation of the scores is the square root of their variance.
Constraints
* n β€ 1000
* 0 β€ si β€ 100
Inpu... | 3 | import math
while True:
n=int(input())
if n == 0:
break
p=list(map(int,input().split()))
m=sum(p)/n
h=0
for i in range(n):
h+=(p[i]-m)**2
print(math.sqrt(h/n))
|
One day, Niwango-kun, an employee of Dwango Co., Ltd., found an integer sequence (a_1, ..., a_N) of length N. He is interested in properties of the sequence a.
For a nonempty contiguous subsequence a_l, ..., a_r (1 \leq l \leq r \leq N) of the sequence a, its beauty is defined as a_l + ... + a_r. Niwango-kun wants to ... | 3 | N, K = [int(_) for _ in input().split()]
A = [int(_) for _ in input().split()]
B = []
for i in range(N):
B += [A[i]]
for j in range(i+1,N):
B += [B[-1] + A[j]]
ans = 0
for i in range(40, -1, -1):
B_new = []
for b in B:
if b & 2 ** i:
B_new += [b]
if len(B_new) >= K:
... |
While walking down the street Vanya saw a label "Hide&Seek". Because he is a programmer, he used & as a bitwise AND for these two words represented as a integers in base 64 and got new word. Now Vanya thinks of some string s and wants to know the number of pairs of words of length |s| (length of s), such that their bit... | 1 | d={}
for i in range(10):
d[str(i)]=i
for i in range(26):
d[chr(ord('A')+i)]=10+i
for i in range(26):
d[chr(ord('a')+i)]=36+i
d['-']=62
d['_']=63
freq=[0]*64
for i in range(64):
for j in range(64):
if i&j<64:
freq[i&j]+=1
freq[i&j]%=(10**9+7)
s=raw_input()
ans=1
for x in s:
ans = (ans*freq[d[x]])%(10**9+7)
... |
Polycarp found under the Christmas tree an array a of n elements and instructions for playing with it:
* At first, choose index i (1 β€ i β€ n) β starting position in the array. Put the chip at the index i (on the value a_i).
* While i β€ n, add a_i to your score and move the chip a_i positions to the right (i.e. r... | 3 | for _ in range(int(input())):
n = int(input())
a = list(map(int,input().split()))
dp = [0 for i in range(n)]
dp[n-1] = a[n-1]
ans = a[n-1]
for i in range(n-2,-1,-1):
if i + a[i] < n:
dp[i] = a[i] + dp[i + a[i]]
else:
dp[i] = a[i]
ans = max(ans,dp[... |
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob β to check his answers, he needs a program that among the given n numbers finds one that is di... | 3 | n=int(input())
l=[]
l=input().split()
l1=[]
for i in range (len(l)):
l[i]=int(l[i])
for i in l:
l1.append(i%2)
if l1.count(1)==1:
print(l1.index(1)+1)
else:
print(l1.index(0)+1)
|
Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.
Rules of the game are very simple: at first number of rounds n is defined. I... | 3 | #!/usr/bin/env python
#-*-coding:utf-8 -*-
s=0
for i in range(int(input())):
m,c=map(int,input().split())
if m<c:s+=1
elif c<m:s-=1
print('Chris'if 0<s else'Mishka'if s else'Friendship is magic!^^')
|
You are given an integer L. Construct a directed graph that satisfies the conditions below. The graph may contain multiple edges between the same pair of vertices. It can be proved that such a graph always exists.
* The number of vertices, N, is at most 20. The vertices are given ID numbers from 1 to N.
* The number o... | 3 | L = int(input())
k = L.bit_length()
ans = []
for i in range(1, k):
ans.append([i,i+1,0])
ans.append([i,i+1,1<<(k-i-1)])
for i in range(k-1):
if L & 1<<i:
mask = (1<<(k+1)) - (1<<(i+1))
w = L & mask
ans.append([1, k-i, w])
print(k, len(ans))
for i in ans:
print(*i) |
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 | n,m,a=map(int,raw_input().split())
print (-n/a)*(m/-a)
|
You are given three positive (i.e. strictly greater than zero) integers x, y and z.
Your task is to find positive integers a, b and c such that x = max(a, b), y = max(a, c) and z = max(b, c), or determine that it is impossible to find such a, b and c.
You have to answer t independent test cases. Print required a, b a... | 3 | import math
for _ in range(int(input())):
x,y,z = map(int, input().split())
if((x==y)and z<=x):
print('YES')
print(x,z,z)
elif((x==z) and y<=x):
print('YES')
print(x,y,y)
elif((y==z) and x<=y):
print('YES')
print(y,x,x)
else:
print('NO')
|
You are given two integers a and b. You may perform any number of operations on them (possibly zero).
During each operation you should choose any positive integer x and set a := a - x, b := b - 2x or a := a - 2x, b := b - x. Note that you may choose different values of x in different operations.
Is it possible to mak... | 3 | n=int(input())
while n:
n-=1
a,b=map(int,input().split())
if min(a,b)*2>=max(a,b):
print(['YES','NO','NO'][(a+b)%3])
else: print('NO')
|
Masha has n types of tiles of size 2 Γ 2. Each cell of the tile contains one integer. Masha has an infinite number of tiles of each type.
Masha decides to construct the square of size m Γ m consisting of the given tiles. This square also has to be a symmetric with respect to the main diagonal matrix, and each cell of ... | 3 | for _ in range(int(input())):
n,m = map(int, input().split())
d1swt = False
d2swt = False
for i in range(n):
new=list()
for j in range(2):
l = list(map(int, input().split()))
new.append(l)
if new[0][0]==new[1][1]:
d1swt = True
if new[0][1]==new[1][0]:
d2swt = True
if m%... |
In Omkar's last class of math, he learned about the least common multiple, or LCM. LCM(a, b) is the smallest positive integer x which is divisible by both a and b.
Omkar, having a laudably curious mind, immediately thought of a problem involving the LCM operation: given an integer n, find positive integers a and b suc... | 3 | t=int(input())
for i in range(t):
n=int(input())
if n%2==0:
print(n//2,n//2)
else:
j=3
p=-1
while j<(n**(0.5))+1:
if n%j==0:
p=n//j
break
j=j+2
if p==-1:
p=1
print(p,n-p) |
Imp likes his plush toy a lot.
<image>
Recently, he found a machine that can clone plush toys. Imp knows that if he applies the machine to an original toy, he additionally gets one more original toy and one copy, and if he applies the machine to a copied toy, he gets two additional copies.
Initially, Imp has only on... | 1 | import sys,math
raw_input = lambda: sys.stdin.readline().rstrip()
r_s = lambda: raw_input().strip() #read str
r_ss = lambda: raw_input().split() #read stringss
r_i = lambda: int(raw_input()) #read int
r_is = lambda: map(int, raw_input().split())#read ints
r_f = lambda: float(raw... |
Fox Ciel is playing a card game with her friend Fox Jiro. There are n piles of cards on the table. And there is a positive integer on each card.
The players take turns and Ciel takes the first turn. In Ciel's turn she takes a card from the top of any non-empty pile, and in Jiro's turn he takes a card from the bottom o... | 3 | from functools import reduce
n = int(input())
cards = [list(map(int, input().split()[1:])) for i in range(n)]
mid = sorted((c[len(c) >> 1] for c in cards if len(c) & 1 == 1), reverse=True)
add = lambda x=0, y=0: x + y
a, b = reduce(add, mid[::2] or [0]), reduce(add, mid[1::2] or [0])
for c in cards:
m = len(c) >> ... |
You are given two segments [l_1; r_1] and [l_2; r_2] on the x-axis. It is guaranteed that l_1 < r_1 and l_2 < r_2. Segments may intersect, overlap or even coincide with each other.
<image> The example of two segments on the x-axis.
Your problem is to find two integers a and b such that l_1 β€ a β€ r_1, l_2 β€ b β€ r_2 an... | 1 | q = int(raw_input())
for i in range(q):
l1,r1,l2,r2 = map(int,raw_input().split())
if l1 <= l2:
print(str(l1)+" "+str(r2))
else:
print(str(r1) + " " + str(l2))
|
You are given a integer n (n > 0). Find any integer s which satisfies these conditions, or report that there are no such numbers:
In the decimal representation of s:
* s > 0,
* s consists of n digits,
* no digit in s equals 0,
* s is not divisible by any of it's digits.
Input
The input consists of mult... | 3 | #!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
from math import log,floor,ceil
def main():
for _ in range(int(input())):
# for i in range(1,101):
n = int(input())
# n = i
if n==1:
print(-1)
continue
elif n==2:
prin... |
[Thanos sort](https://codegolf.stackexchange.com/questions/182221/implement-the-thanos-sorting-algorithm) is a supervillain sorting algorithm, which works as follows: if the array is not sorted, snap your fingers* to remove the first or the second half of the items, and repeat the process.
Given an input array, what i... | 3 |
def solve(l):
length = len(l)
if length <= 1:
return length
elif l == sorted(l):
return length
return max(solve(l[:length // 2]), solve(l[length // 2:]))
if __name__ == '__main__':
num = input()
array = [int(x) for x in input().split()]
print(solve(array))
|
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them.
Input
The first line contains integ... | 3 | n=int(input())
s=input()
i=0
c=0
while i<len(s):
j=i+1
while j<len(s) and s[j]==s[i]:
j+=1
c+=1
i=j
print(c)
|
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word s. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if... | 3 | WORD = "hello"
def is_managed(word):
index = 0
for i in range(0, len(word)):
if index == 5:
return "YES"
if word[i] == WORD[index]:
index += 1
if index < 5:
return "NO"
return "YES"
print(is_managed(input())) |
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 | n, m = map(int,input().split(" "))
a=[]
a = list(map(int,input().split(" ")))
sol = []
dic = {}
for x in range(n-1,-1,-1):
dic.update({a[x]:True})
sol.append(len(dic))
sol = sol[::-1]
res = []
for x in range(1,m+1):
v = int(input())
res.append(sol[v-1])
for x in range(0,len(res)):
print(res[x]) |
You are given a string s. You have to reverse it β that is, the first letter should become equal to the last letter before the reversal, the second letter should become equal to the second-to-last letter before the reversal β and so on. For example, if your goal is to reverse the string "abddea", you should get the str... | 3 | def getNext(num):
return num + (num & (-num))
def getParent(num):
return num - (num & (-num))
def getSum(ftree, index):
s = 0
i = index
while i > 0:
s += ftree[i]
i = getParent(i)
return s
n = int(input())
s = input()
a = [[] for i in range(26)]
b = []
c = [0]*26
for i in ra... |
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 | w=int(input())
sts="NO"
for i in range(2,w,2):
rem=w-i
if rem%2==0:
sts="YES"
break
print(sts)
|
Dreamoon is a big fan of the Codeforces contests.
One day, he claimed that he will collect all the places from 1 to 54 after two more rated contests. It's amazing!
Based on this, you come up with the following problem:
There is a person who participated in n Codeforces rounds. His place in the first round is a_1, hi... | 3 | t = int(input())
for i in range(t):
nx = input().split()
n = int(nx[0])
x = int(nx[1])
a = [int(x) for x in input().split()]
a = set(a)
c = 0
for i in range(1,101+x):
if not(i in a) and x==0:
break
if not(i in a):
x-=1
c = i
print(c)
|
You are given a string S of length 2N consisting of lowercase English letters.
There are 2^{2N} ways to color each character in S red or blue. Among these ways, how many satisfy the following condition?
* The string obtained by reading the characters painted red from left to right is equal to the string obtained by r... | 3 | N=int(input())
S=input()
S,T=S[:N],S[N:][::-1]
A=dict()
B=dict()
X1,Y1,X2,Y2,Z=0,0,0,0,0
for i in range(1<<N):
X1,Y1,X2,Y2,Z='','','','',1
for j in range(N):
if i&Z:
X1+=S[j]
X2+=T[j]
else:
Y1+=S[j]
Y2+=T[j]
Z<<=1
A[(X1,Y1)]=A.get((X1,Y1),0)+1
B[(X2,Y2)]=B.get((X2,Y2),0)+1
P=... |
Johnny has recently found an ancient, broken computer. The machine has only one register, which allows one to put in there one variable. Then in one operation, you can shift its bits left or right by at most three positions. The right shift is forbidden if it cuts off some ones. So, in fact, in one operation, you can m... | 3 | for _ in range(int(input())):
a,b=map(int,input().split())
if(a==b):
print(0)
else:
c=0
if(a>b):
while(a>b):
if(a%8==0 and (a//8)>=b):
a=a//8
c+=1
elif a%4==0 and (a//4)>=b:
a=a//4... |
High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.
Vasya can change no more than k characters of the original string. W... | 3 | ## necessary imports
import sys
input = sys.stdin.readline
from math import log2, log, ceil
# swap_array function
def swaparr(arr, a,b):
temp = arr[a];
arr[a] = arr[b];
arr[b] = temp
## gcd function
def gcd(a,b):
if a == 0:
return b
return gcd(b%a, a)
## nCr function efficient using Binom... |
You are given array consisting of n integers. Your task is to find the maximum length of an increasing subarray of the given array.
A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray strictly greater than previous.
Input
The first line cont... | 1 | n = int(raw_input())
a = map(int, raw_input().split())
maxlen = 0
thislen = 1
for i in range(1, n):
if a[i-1] < a[i]:
thislen += 1
else:
maxlen = max(maxlen, thislen)
thislen = 1
maxlen = max(maxlen, thislen)
print maxlen |
Drazil is playing a math game with Varda.
Let's define <image> for positive integer x as a product of factorials of its digits. For example, <image>.
First, they choose a decimal number a consisting of n digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then th... | 1 | d = {'0':'','1':'','2':'2','3':'3',
'4': '322','5':'5','6':'53',
'7':'7','8':'7222','9':'7332'}
n = input()
print ''.join(sorted(''.join([d[x] for x in raw_input()]))[::-1]) |
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 | n = int(input())
s = list(input())
curr_d = 0
curr_r = 0
ost_d = s.count("D")
ost_r = s.count("R")
while True:
for i in range(len(s)):
if s[i] == "D":
if curr_d > 0:
s[i] = "N"
ost_d -=1
curr_d -= 1
else:
curr_r += 1
... |
Everybody in Russia uses Gregorian calendar. In this calendar there are 31 days in January, 28 or 29 days in February (depending on whether the year is leap or not), 31 days in March, 30 days in April, 31 days in May, 30 in June, 31 in July, 31 in August, 30 in September, 31 in October, 30 in November, 31 in December.
... | 3 | n = int(input())
days = input().split()
normal = '31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, ' * 4
normal2 = ('31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, ' * 4 + '31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, ') * 2
days = str(', '.join(i for i in days))
if str(days) in normal or str(days) in normal2:
p... |
In the school computer room there are n servers which are responsible for processing several computing tasks. You know the number of scheduled tasks for each server: there are mi tasks assigned to the i-th server.
In order to balance the load for each server, you want to reassign some tasks to make the difference betw... | 3 | def solve(arr,n):
# most important : TO SORT
arr.sort()
ans=0
avg=sum(arr)//n
rem=sum(arr)%n
for i in range(n):
if i<n-rem:
diff=arr[i]-avg
else:
diff=arr[i]-(avg+1)
if diff>0:
ans+=diff
return ans
n=int(input())
arr=[int(ele... |
β This is not playing but duty as allies of justice, Nii-chan!
β Not allies but justice itself, Onii-chan!
With hands joined, go everywhere at a speed faster than our thoughts! This time, the Fire Sisters β Karen and Tsukihi β is heading for somewhere they've never reached β water-surrounded islands!
There are three... | 1 | a, b, c = map(int, raw_input().split())
p = 998244353
def C(x, y):
z, t = 0, 1
for i in range(min(x, y) + 1):
z = (z + t) % p
t = t * (x - i) * (y - i) * pow(i + 1, p - 2, p) % p
return z
print C(a, b) * C(a, c) * C(b, c) % p |
You are given a string s of even length n. String s is binary, in other words, consists only of 0's and 1's.
String s has exactly n/2 zeroes and n/2 ones (n is even).
In one operation you can reverse any substring of s. A substring of a string is a contiguous subsequence of that string.
What is the minimum number of... | 3 | for i in range(int(input())):
n=int(input())
s=input()
z=s.count('10')+s.count('01')
print((n-z)//2) |
Monocarp has got two strings s and t having equal length. Both strings consist of lowercase Latin letters "a" and "b".
Monocarp wants to make these two strings s and t equal to each other. He can do the following operation any number of times: choose an index pos_1 in the string s, choose an index pos_2 in the string... | 3 | '''
Auther: ghoshashis545 Ashis Ghosh
College: jalpaiguri Govt Enggineering College
Date:09/06/2020
'''
from os import path
import sys
from functools import cmp_to_key as ctk
from collections import deque,defaultdict as dd
from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
... |
Fox Ciel starts to learn programming. The first task is drawing a fox! However, that turns out to be too hard for a beginner, so she decides to draw a snake instead.
A snake is a pattern on a n by m table. Denote c-th cell of r-th row as (r, c). The tail of the snake is located at (1, 1), then it's body extends to (1,... | 3 | n,m=map(int,input().split())
cnt=1
t=m-1
for i in range(1,n+1):
if(i%2!=0):
print("#"*m)
else:
if(cnt%2!=0):
print("."*t,end="")
print("#")
cnt=cnt+1
else:
print("#",end="")
print("."*t)
cnt=cnt+1 |
Mike has a string s consisting of only lowercase English letters. He wants to change exactly one character from the string so that the resulting one is a palindrome.
A palindrome is a string that reads the same backward as forward, for example strings "z", "aaa", "aba", "abccba" are palindromes, but strings "codeforc... | 3 | a=str(input())
k=0
l=0
if len(a)%2==0:
s1=(a[:len(a)//2])
s2=(a[len(a)//2:])
else:
k=len(a)//2
s1=a[:k]
s2=a[k+1:]
s2=s2[::-1]
for i in range(len(s1)):
if s1[i]!=s2[i]:
l=l+1
if l==1:
print("YES")
else:
if len(a)%2==1 and l==0:
print("YES")
else:
print("NO")
... |
Β«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 | from itertools import cycle, izip
k, l, m, n, d = [int(raw_input()) for _ in range(5)]
dragons = [cycle([False] * (i-1) + [True]) for i in {k, l, m, n}]
print sum(any(next(izip(*dragons))) for _ in xrange(d)) |
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps:
1. Find the number that goes k-th in the current sequence and add the same number to the end of the sequence;
2. Delete the first number of the current s... | 1 | #!/usr/bin/env python
n,k=map(int, raw_input().split())
a = map(int, raw_input().split())
if len(a)==1:
print 0
exit()
i=n-1
flag = True
while i>k-1:
if a[i]==a[i-1]:
i-=1
else:
flag = False
break
ll = len(a[:k-1])
if flag:
c = -1
for i in range(ll):
if a[i]!=a... |
One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:
a1, a2, ..., an β an, a1, a2, ..., an - 1.
Help Twi... | 1 | from sys import stdin
n = int(raw_input())
a = [int(x) for x in stdin.readline().split(' ')]
j = n-1;
while (j > 0 and a[j] >= a[j-1]): j -= 1
asc = 1
for i in range(n-1):
asc &= a[(i+j)%n] <= a[(i+j+1)%n]
if j == 0: j = n
if asc:
print n - j
else:
print -1
|
You are given three positive (i.e. strictly greater than zero) integers x, y and z.
Your task is to find positive integers a, b and c such that x = max(a, b), y = max(a, c) and z = max(b, c), or determine that it is impossible to find such a, b and c.
You have to answer t independent test cases. Print required a, b a... | 3 | t=int(input())
while t:
t-=1
lst=list(map(int,input().split()))
lst.sort()
if lst[1]==lst[2]:
print("YES")
print(lst[0],lst[0],lst[2])
else:
print("NO")
|
You are given an integer sequence A of length N and an integer K. You will perform the following operation on this sequence Q times:
* Choose a contiguous subsequence of length K, then remove the smallest element among the K elements contained in the chosen subsequence (if there are multiple such elements, choose one ... | 3 | from itertools import*
N,K,Q,*A=map(int,open(0).read().split())
s=sorted
print(min((s(sum((v[:max(0,len(v)-K+1)]for v in(k*s(v)for k,v in groupby(A,lambda a:a>=Y))),[]))[Q-1:]or[2e9])[0]-Y for Y in A)) |
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())
cnt=0
while n:
n=n-1
s=input()
s=s.split()
s=list(map(int,s))
if s[1]-s[0]>=2:
cnt=cnt+1
print(cnt)
|
problem
JOI took six subjects: physics, chemistry, biology, earth science, history, and geography. Each test was scored on a 100-point scale.
JOI chooses 3 subjects from 4 subjects of physics, chemistry, biology, and earth science, and 1 subject from 2 subjects of history and geography.
When choosing a subject so th... | 3 | points_1 = []
points_2 = []
for _ in range(4):
points_1.append(int(input()))
for _ in range(2):
points_2.append(int(input()))
print(sum(sorted(points_1)[1:]) + max(points_2))
|
Phoenix has a string s consisting of lowercase Latin letters. He wants to distribute all the letters of his string into k non-empty strings a_1, a_2, ..., a_k such that every letter of s goes to exactly one of the strings a_i. The strings a_i do not need to be substrings of s. Phoenix can distribute letters of s and re... | 3 | from collections import deque
def solve():
n,k=[int(x) for x in input().split()]
string=input()
li=deque()
for ele in string:
li.append(ele)
li=list(li)
li.sort()
s=''
for ele in li:
s+=ele
if n==k:
print(s[n-1])
return
if s[0]!=s[k-1]:
pri... |
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 | count=-1
row=0
col=0
for i in range(5):
a=input().split()
count+=1
if('1' in a):
row=a.index('1')
col=count
print(abs((2-row))+abs((2-col)))
|
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are ... | 3 | """
instagram : essipoortahmasb2018
telegram channel : essi_python
"""
c = 0
n , d = map(int,input().split())
List = [*map(int,input().split())]
for i in range(n-1):
for j in range(i+1,n):
if abs(List[i]-List[j])<=d:
c+=2
print(c)
|
You are given strings s and t. Find one longest string that is a subsequence of both s and t.
Constraints
* s and t are strings consisting of lowercase English letters.
* 1 \leq |s|, |t| \leq 3000
Input
Input is given from Standard Input in the following format:
s
t
Output
Print one longest string that is a su... | 3 | def main():
s = input()
t = input()
dp = [["" for _ in range(3010)] for _ in range(3010)]
for i in range(len(s)):
for j in range(len(t)):
dp[i + 1][j + 1] = dp[i][j + 1] if len(dp[i][j + 1]) >= len(dp[i + 1][j]) else dp[i + 1][j]
if s[i] == t[j] and len(dp[i][j]) + 1 > le... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.