I found an interesting problem on https://codeforces.com/problemset/problem/987/A:
You took a peek on Thanos wearing Infinity Gauntlet. In the Gauntlet there is a place for six Infinity Gems:  the Power Gem of purple color,  the Time Gem of green color,  the Space Gem of blue color,  the Soul Gem of orange color,  the Reality Gem of red color,  the Mind Gem of yellow color.

Using colors of Gems you saw in the Gauntlet determine the names of absent Gems.

-----Input-----

In the first line of input there is one integer $n$ ($0 \le n \le 6$) — the number of Gems in Infinity Gauntlet.

In next $n$ lines there are colors of Gems you saw. Words used for colors are: purple, green, blue, orange, red, yellow. It is guaranteed that all the colors are distinct. All colors are given in lowercase English letters.

-----Output-----

In the first line output one integer $m$ ($0 \le m \le 6$) — the number of absent Gems.

Then in $m$ lines print the names of absent Gems, each on its own line. Words used for names are: Power, Time, Space, Soul, Reality, Mind. Names can be printed in any order. Keep the first letter uppercase, others lowercase.

-----Examples-----
Input
4
red
purple
yellow
orange

Output
2
Space
Time

Input
0

Output
6
Time
Mind
Soul
Power
Reality
Space

-----Note-----

In the first sample Thanos already has Reality, Power, Mind and Soul Gems, so he needs two more: Time and Space.

In the second sample Thanos doesn't have any Gems, so he needs all six.

I tried it in Python, but could not do it. Can you solve it?

d={"purple":"Power","green":"Time","blue":"Space","orange":"Soul","red":"Reality","yellow":"Mind"}
n=int(input())
temp=set()
for i in range(n):
    temp|={d[input()]}
#m,n=list(map(int,input().split()))
#a=list(map(int,input().split()))
#ans=0
ans=set()
for i in d:
    ans|={d[i]}
ans=ans-temp
print(len(ans))
for i in ans:
    print(i)


I found an interesting problem on https://codeforces.com/problemset/problem/987/B:
Year 2118. Androids are in mass production for decades now, and they do all the work for humans. But androids have to go to school to be able to solve creative tasks. Just like humans before.

It turns out that high school struggles are not gone. If someone is not like others, he is bullied. Vasya-8800 is an economy-class android which is produced by a little-known company. His design is not perfect, his characteristics also could be better. So he is bullied by other androids.

One of the popular pranks on Vasya is to force him to compare $x^y$ with $y^x$. Other androids can do it in milliseconds while Vasya's memory is too small to store such big numbers.

Please help Vasya! Write a fast program to compare $x^y$ with $y^x$ for Vasya, maybe then other androids will respect him.

-----Input-----

On the only line of input there are two integers $x$ and $y$ ($1 \le x, y \le 10^{9}$).

-----Output-----

If $x^y < y^x$, then print '<' (without quotes). If $x^y > y^x$, then print '>' (without quotes). If $x^y = y^x$, then print '=' (without quotes).

-----Examples-----
Input
5 8

Output
>

Input
10 3

Output
<

Input
6 6

Output
=

-----Note-----

In the first example $5^8 = 5 \cdot 5 \cdot 5 \cdot 5 \cdot 5 \cdot 5 \cdot 5 \cdot 5 = 390625$, and $8^5 = 8 \cdot 8 \cdot 8 \cdot 8 \cdot 8 = 32768$. So you should print '>'.

In the second example $10^3 = 1000 < 3^{10} = 59049$.

In the third example $6^6 = 46656 = 6^6$.

I tried it in Python, but could not do it. Can you solve it?

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 29 21:10:19 2018

@st0rmbring3r
"""
# l = [int(x) for x in input().split()]
# for _ in range(int(input()))

import math

x,y = [int(x) for x in input().split()]

k1 = math.log(y)*x
k2 = math.log(x)*y

if k1>k2:
    print("<")
elif k1<k2:
    print(">")
else:
    print("=")


I found an interesting problem on https://codeforces.com/problemset/problem/987/C:
It is the middle of 2018 and Maria Stepanovna, who lives outside Krasnokamensk (a town in Zabaikalsky region), wants to rent three displays to highlight an important problem.

There are $n$ displays placed along a road, and the $i$-th of them can display a text with font size $s_i$ only. Maria Stepanovna wants to rent such three displays with indices $i < j < k$ that the font size increases if you move along the road in a particular direction. Namely, the condition $s_i < s_j < s_k$ should be held.

The rent cost is for the $i$-th display is $c_i$. Please determine the smallest cost Maria Stepanovna should pay.

-----Input-----

The first line contains a single integer $n$ ($3 \le n \le 3\,000$) — the number of displays.

The second line contains $n$ integers $s_1, s_2, \ldots, s_n$ ($1 \le s_i \le 10^9$) — the font sizes on the displays in the order they stand along the road.

The third line contains $n$ integers $c_1, c_2, \ldots, c_n$ ($1 \le c_i \le 10^8$) — the rent costs for each display.

-----Output-----

If there are no three displays that satisfy the criteria, print -1. Otherwise print a single integer — the minimum total rent cost of three displays with indices $i < j < k$ such that $s_i < s_j < s_k$.

-----Examples-----
Input
5
2 4 5 4 10
40 30 20 10 40

Output
90

Input
3
100 101 100
2 4 5

Output
-1

Input
10
1 2 3 4 5 6 7 8 9 10
10 13 11 14 15 12 13 13 18 13

Output
33

-----Note-----

In the first example you can, for example, choose displays $1$, $4$ and $5$, because $s_1 < s_4 < s_5$ ($2 < 4 < 10$), and the rent cost is $40 + 10 + 40 = 90$.

In the second example you can't select a valid triple of indices, so the answer is -1.

I tried it in Python, but could not do it. Can you solve it?

import math;
def getIntList():
    return list(map(int, input().split()));
def getTransIntList(n):
    first=getIntList();
    m=len(first);
    result=[[0]*n for _ in range(m)];
    for i in range(m):
        result[i][0]=first[i];
    for j in range(1, n):
        curr=getIntList();
        for i in range(m):
            result[i][j]=curr[i];
    return result;
n=int(input());
s=getIntList();
c=getIntList();
maxValue=10**8+1;
result=maxValue*3;
minLeft=[0]*n;
minRight=[0]*n;
minLeft[0]=c[0];
for i in range(1, n):
    minLeft[i]=min(c[i], minLeft[i-1]);
minRight[n-1]=c[n-1];
for i in range(n-2, -1, -1):
    minRight[i]=min(c[i], minRight[i+1]);
minSLeft=[0]*n;
maxSRight=[0]*n;
minSLeft[0]=s[0];
for i in range(1, n):
    minSLeft[i]=min(s[i], minSLeft[i-1]);
maxSRight[n-1]=s[n-1];
for i in range(n-2, -1, -1):
    maxSRight[i]=max(s[i], maxSRight[i+1]);
prices=[(c[j], j) for j in range(1, n-1)];
prices.sort();
for currC, j in prices:
    if minLeft[j-1]+c[j]+minRight[j+1]>=result:
        continue;
    if minSLeft[j-1]>=s[j] or s[j]>=maxSRight[j+1]:
        continue;
    a=maxValue;
    for i in range(j):
        if s[i]<s[j]:
            a=min(a, c[i]);
    b=maxValue;
    for k in range(j+1, n):
        if (s[j]<s[k]):
            b=min(b, c[k]);
    curr=a+b+c[j];
    result=min(result, curr);
if result==maxValue*3:
    result=-1;
print(result);


I found an interesting problem on https://codeforces.com/problemset/problem/988/A:
There are $n$ students in a school class, the rating of the $i$-th student on Codehorses is $a_i$. You have to form a team consisting of $k$ students ($1 \le k \le n$) such that the ratings of all team members are distinct.

If it is impossible to form a suitable team, print "NO" (without quotes). Otherwise print "YES", and then print $k$ distinct numbers which should be the indices of students in the team you form. If there are multiple answers, print any of them.

-----Input-----

The first line contains two integers $n$ and $k$ ($1 \le k \le n \le 100$) — the number of students and the size of the team you have to form.

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 100$), where $a_i$ is the rating of $i$-th student.

-----Output-----

If it is impossible to form a suitable team, print "NO" (without quotes). Otherwise print "YES", and then print $k$ distinct integers from $1$ to $n$ which should be the indices of students in the team you form. All the ratings of the students in the team should be distinct. You may print the indices in any order. If there are multiple answers, print any of them.

Assume that the students are numbered from $1$ to $n$.

-----Examples-----
Input
5 3
15 13 15 15 12

Output
YES
1 2 5

Input
5 4
15 13 15 15 12

Output
NO

Input
4 4
20 10 40 30

Output
YES
1 2 3 4

-----Note-----

All possible answers for the first example:   {1 2 5}  {2 3 5}  {2 4 5}

Note that the order does not matter.

I tried it in Python, but could not do it. Can you solve it?

n,k=map(int,input().split())
arr=list(map(int,input().split()))
arr1=[]
arr2=[]
for i in range(n):
    if(arr[i] not in arr1):
        arr1.append(arr[i])
        arr2.append(i+1)
if(len(arr1)<k):
    print("NO")
else:
    print("YES")
    print(*arr2[:k])


I found an interesting problem on https://codeforces.com/problemset/problem/988/B:
You are given $n$ strings. Each string consists of lowercase English letters. Rearrange (reorder) the given strings in such a way that for every string, all strings that are placed before it are its substrings.

String $a$ is a substring of string $b$ if it is possible to choose several consecutive letters in $b$ in such a way that they form $a$. For example, string "for" is contained as a substring in strings "codeforces", "for" and "therefore", but is not contained as a substring in strings "four", "fofo" and "rof".

-----Input-----

The first line contains an integer $n$ ($1 \le n \le 100$) — the number of strings.

The next $n$ lines contain the given strings. The number of letters in each string is from $1$ to $100$, inclusive. Each string consists of lowercase English letters.

Some strings might be equal.

-----Output-----

If it is impossible to reorder $n$ given strings in required order, print "NO" (without quotes).

Otherwise print "YES" (without quotes) and $n$ given strings in required order.

-----Examples-----
Input
5
a
aba
abacaba
ba
aba

Output
YES
a
ba
aba
aba
abacaba

Input
5
a
abacaba
ba
aba
abab

Output
NO

Input
3
qwerty
qwerty
qwerty

Output
YES
qwerty
qwerty
qwerty

-----Note-----

In the second example you cannot reorder the strings because the string "abab" is not a substring of the string "abacaba".

I tried it in Python, but could not do it. Can you solve it?

n=int(input())
s=[]
for x in range(n):
    e=input()
    s.append(e)
s=sorted(s,key=lambda x:len(x))
def issubstring(a,b):
    return b.count(a)
b=True
for x in range(n):
    for y in range(x):
        if(not issubstring(s[y],s[x])):
            b=False
if b:
    print("YES")
    for x in s:
        print(x)
else:
    print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/988/C:
You are given $k$ sequences of integers. The length of the $i$-th sequence equals to $n_i$.

You have to choose exactly two sequences $i$ and $j$ ($i \ne j$) such that you can remove exactly one element in each of them in such a way that the sum of the changed sequence $i$ (its length will be equal to $n_i - 1$) equals to the sum of the changed sequence $j$ (its length will be equal to $n_j - 1$).

Note that it's required to remove exactly one element in each of the two chosen sequences.

Assume that the sum of the empty (of the length equals $0$) sequence is $0$.

-----Input-----

The first line contains an integer $k$ ($2 \le k \le 2 \cdot 10^5$) — the number of sequences.

Then $k$ pairs of lines follow, each pair containing a sequence.

The first line in the $i$-th pair contains one integer $n_i$ ($1 \le n_i < 2 \cdot 10^5$) — the length of the $i$-th sequence. The second line of the $i$-th pair contains a sequence of $n_i$ integers $a_{i, 1}, a_{i, 2}, \dots, a_{i, n_i}$.

The elements of sequences are integer numbers from $-10^4$ to $10^4$.

The sum of lengths of all given sequences don't exceed $2 \cdot 10^5$, i.e. $n_1 + n_2 + \dots + n_k \le 2 \cdot 10^5$.

-----Output-----

If it is impossible to choose two sequences such that they satisfy given conditions, print "NO" (without quotes). Otherwise in the first line print "YES" (without quotes), in the second line — two integers $i$, $x$ ($1 \le i \le k, 1 \le x \le n_i$), in the third line — two integers $j$, $y$ ($1 \le j \le k, 1 \le y \le n_j$). It means that the sum of the elements of the $i$-th sequence without the element with index $x$ equals to the sum of the elements of the $j$-th sequence without the element with index $y$.

Two chosen sequences must be distinct, i.e. $i \ne j$. You can print them in any order.

If there are multiple possible answers, print any of them.

-----Examples-----
Input
2
5
2 3 1 3 2
6
1 1 2 2 2 1

Output
YES
2 6
1 2

Input
3
1
5
5
1 1 1 1 1
2
2 3

Output
NO

Input
4
6
2 2 2 2 2 2
5
2 2 2 2 2
3
2 2 2
5
2 2 2 2...

I tried it in Python, but could not do it. Can you solve it?

k = int(input())
a = []
for i in range(k):
    n = int(input())
    b = [int(i) for i in input().split()]
    s = sum(b)
    for j in range(n):
        x = s-b[j]
        a.append([x,i,j])
f = True
a = sorted(a)
for i in range(1,len(a)):
    if a[i][0] == a[i-1][0] and a[i][1]!=a[i-1][1]:
        f = False
        print('YES')
        print(a[i][1]+1,a[i][2]+1)
        print(a[i-1][1]+1, a[i-1][2]+1)
        break
if f:
    print('NO')


I found an interesting problem on https://codeforces.com/problemset/problem/988/D:
There are $n$ distinct points on a coordinate line, the coordinate of $i$-th point equals to $x_i$. Choose a subset of the given set of points such that the distance between each pair of points in a subset is an integral power of two. It is necessary to consider each pair of points, not only adjacent. Note that any subset containing one element satisfies the condition above. Among all these subsets, choose a subset with maximum possible size.

In other words, you have to choose the maximum possible number of points $x_{i_1}, x_{i_2}, \dots, x_{i_m}$ such that for each pair $x_{i_j}$, $x_{i_k}$ it is true that $|x_{i_j} - x_{i_k}| = 2^d$ where $d$ is some non-negative integer number (not necessarily the same for each pair of points).

-----Input-----

The first line contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of points.

The second line contains $n$ pairwise distinct integers $x_1, x_2, \dots, x_n$ ($-10^9 \le x_i \le 10^9$) — the coordinates of points.

-----Output-----

In the first line print $m$ — the maximum possible number of points in a subset that satisfies the conditions described above.

In the second line print $m$ integers — the coordinates of points in the subset you have chosen.

If there are multiple answers, print any of them.

-----Examples-----
Input
6
3 5 4 7 10 12

Output
3
7 3 5
Input
5
-1 2 5 8 11

Output
1
8

-----Note-----

In the first example the answer is $[7, 3, 5]$. Note, that $|7-3|=4=2^2$, $|7-5|=2=2^1$ and $|3-5|=2=2^1$. You can't find a subset having more points satisfying the required property.

I tried it in Python, but could not do it. Can you solve it?

n = int(input())
n1 = input().split()

n2 = []
s1 = set()
for x in n1:
	n2.append(int(x))
	s1.add(int(x))

n2.sort()

maxy = n2[len(n2)-1]-n2[0]

count = 0
num = 1

while(num<maxy):
	num = num*2
	count = count + 1

flag = 0
base0 = 0
base1 = 0
base2 = -1

cflag = 0

for x in n2:
	for z in range(0, count+1):
		# print(z)
		if(x+2**z in s1):
			if(flag==0):
				flag = 1
				base0 = x
				base1 = x+2**z
			if(x+2**(z+1) in s1):
				cflag = 1
				base0 = x
				base1 = x+2**z
				base2 = x+2**(z+1)
				break
	if(cflag==1):
		break

if(cflag==1):
	s = "3\n" + str(base0) + " " + str(base1) + " " + str(base2)
	print(s)
if(cflag==0 and flag==1):
	s = "2\n" + str(base0) + " " + str(base1)
	print(s)
if(cflag==0 and flag==0):
	s = "1\n" + str(n2[0])
	print(s)


I found an interesting problem on https://codeforces.com/problemset/problem/988/E:
You are given an integer $n$ from $1$ to $10^{18}$ without leading zeroes.

In one move you can swap any two adjacent digits in the given number in such a way that the resulting number will not contain leading zeroes. In other words, after each move the number you have cannot contain any leading zeroes.

What is the minimum number of moves you have to make to obtain a number that is divisible by $25$? Print -1 if it is impossible to obtain a number that is divisible by $25$.

-----Input-----

The first line contains an integer $n$ ($1 \le n \le 10^{18}$). It is guaranteed that the first (left) digit of the number $n$ is not a zero.

-----Output-----

If it is impossible to obtain a number that is divisible by $25$, print -1. Otherwise print the minimum number of moves required to obtain such number.

Note that you can swap only adjacent digits in the given number.

-----Examples-----
Input
5071

Output
4

Input
705

Output
1

Input
1241367

Output
-1

-----Note-----

In the first example one of the possible sequences of moves is 5071 $\rightarrow$ 5701 $\rightarrow$ 7501 $\rightarrow$ 7510 $\rightarrow$ 7150.

I tried it in Python, but could not do it. Can you solve it?


I found an interesting problem on https://codeforces.com/problemset/problem/988/F:
Polycarp lives on a coordinate line at the point $x = 0$. He goes to his friend that lives at the point $x = a$. Polycarp can move only from left to right, he can pass one unit of length each second.

Now it's raining, so some segments of his way are in the rain. Formally, it's raining on $n$ non-intersecting segments, the $i$-th segment which is in the rain is represented as $[l_i, r_i]$ ($0 \le l_i < r_i \le a$).

There are $m$ umbrellas lying on the line, the $i$-th umbrella is located at point $x_i$ ($0 \le x_i \le a$) and has weight $p_i$. When Polycarp begins his journey, he doesn't have any umbrellas.

During his journey from $x = 0$ to $x = a$ Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from $x$ to $x + 1$ if a segment $[x, x + 1]$ is in the rain (i.e. if there exists some $i$ such that $l_i \le x$ and $x + 1 \le r_i$).

The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain.

Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving.

Can Polycarp make his way from point $x = 0$ to point $x = a$? If yes, find the minimum total fatigue after reaching $x = a$, if Polycarp picks up and throws away umbrellas optimally.

-----Input-----

The first line contains three integers $a$, $n$ and $m$ ($1 \le a, m \le 2000, 1 \le n \le \lceil\frac{a}{2}\rceil$) — the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas.

Each of the next $n$ lines contains two integers $l_i$ and $r_i$ ($0 \le l_i < r_i \le a$) — the borders of the $i$-th segment under rain. It is guaranteed that there...

I tried it in Python, but could not do it. Can you solve it?

rd = lambda: list(map(int, input().split()))
a, n, m = rd()
s = set()
u = {}
k = set([0, a])
for _ in range(n):
    l, r = rd()
    for x in range(l + 1, r + 1):
        s.add(x)
    k.add(r)
for _ in range(m):
    x, p = rd()
    u[x] = min(p, u.get(x, 1e9))
    k.add(x)
k = sorted(list(k))
dp = {}
dp[0] = {}
dp[0][0] = 0
if 0 in u:
    dp[0][u[0]] = 0
for i in range(1, len(k)):
    x = k[i]
    y = k[i - 1]
    dp[x] = {}
    for z in dp[y]:
        if z:
            dp[x][z] = dp[y][z] + z * (x - y)
        else:
            if x not in s:
                dp[x][0] = dp[y][0]
    if len(dp[x]):
        dp[x][0] = min(dp[x].values())
        if x in u:
            if u[x] not in dp[x] or dp[x][0] < dp[x][u[x]]:
                dp[x][u[x]] = dp[x][0]
    else:
        print(-1)
        return
print(dp[a][0])


I found an interesting problem on https://codeforces.com/problemset/problem/989/A:
When the curtains are opened, a canvas unfolds outside. Kanno marvels at all the blonde colours along the riverside — not tangerines, but blossoms instead.

"What a pity it's already late spring," sighs Mino with regret, "one more drizzling night and they'd be gone."

"But these blends are at their best, aren't they?" Absorbed in the landscape, Kanno remains optimistic.

The landscape can be expressed as a row of consecutive cells, each of which either contains a flower of colour amber or buff or canary yellow, or is empty.

When a flower withers, it disappears from the cell that it originally belonged to, and it spreads petals of its colour in its two neighbouring cells (or outside the field if the cell is on the side of the landscape). In case petals fall outside the given cells, they simply become invisible.

You are to help Kanno determine whether it's possible that after some (possibly none or all) flowers shed their petals, at least one of the cells contains all three colours, considering both petals and flowers. Note that flowers can wither in arbitrary order.

-----Input-----

The first and only line of input contains a non-empty string $s$ consisting of uppercase English letters 'A', 'B', 'C' and characters '.' (dots) only ($\lvert s \rvert \leq 100$) — denoting cells containing an amber flower, a buff one, a canary yellow one, and no flowers, respectively.

-----Output-----

Output "Yes" if it's possible that all three colours appear in some cell, and "No" otherwise.

You can print each letter in any case (upper or lower).

-----Examples-----
Input
.BAC.

Output
Yes

Input
AA..CB

Output
No

-----Note-----

In the first example, the buff and canary yellow flowers can leave their petals in the central cell, blending all three colours in it.

In the second example, it's impossible to satisfy the requirement because there is no way that amber and buff meet in any cell.

I tried it in Python, but could not do it. Can you solve it?

s = input()
if s.count('ABC') + s.count('ACB') + s.count('BAC') + s.count('BCA') + s.count('CAB') + s.count('CBA') != 0:
    print('Yes')
else:
    print('No')


I found an interesting problem on https://codeforces.com/problemset/problem/989/D:
Gathering darkness shrouds the woods and the world. The moon sheds its light on the boat and the river.

"To curtain off the moonlight should be hardly possible; the shades present its mellow beauty and restful nature." Intonates Mino.

"See? The clouds are coming." Kanno gazes into the distance.

"That can't be better," Mino turns to Kanno.

The sky can be seen as a one-dimensional axis. The moon is at the origin whose coordinate is $0$.

There are $n$ clouds floating in the sky. Each cloud has the same length $l$. The $i$-th initially covers the range of $(x_i, x_i + l)$ (endpoints excluded). Initially, it moves at a velocity of $v_i$, which equals either $1$ or $-1$.

Furthermore, no pair of clouds intersect initially, that is, for all $1 \leq i \lt j \leq n$, $\lvert x_i - x_j \rvert \geq l$.

With a wind velocity of $w$, the velocity of the $i$-th cloud becomes $v_i + w$. That is, its coordinate increases by $v_i + w$ during each unit of time. Note that the wind can be strong and clouds can change their direction.

You are to help Mino count the number of pairs $(i, j)$ ($i < j$), such that with a proper choice of wind velocity $w$ not exceeding $w_\mathrm{max}$ in absolute value (possibly negative and/or fractional), the $i$-th and $j$-th clouds both cover the moon at the same future moment. This $w$ doesn't need to be the same across different pairs.

-----Input-----

The first line contains three space-separated integers $n$, $l$, and $w_\mathrm{max}$ ($1 \leq n \leq 10^5$, $1 \leq l, w_\mathrm{max} \leq 10^8$) — the number of clouds, the length of each cloud and the maximum wind speed, respectively.

The $i$-th of the following $n$ lines contains two space-separated integers $x_i$ and $v_i$ ($-10^8 \leq x_i \leq 10^8$, $v_i \in \{-1, 1\}$) — the initial position and the velocity of the $i$-th cloud, respectively.

The input guarantees that for all $1 \leq i \lt j \leq n$, $\lvert x_i - x_j \rvert \geq l$.

-----Output-----

Output one integer — the number of unordered pairs of clouds such that...

I tried it in Python, but could not do it. Can you solve it?

#      Codeforces Round #487 (Div. 2)import collections
from functools import cmp_to_key
#key=cmp_to_key(lambda x,y: 1 if x not in y else -1 )

import sys
def getIntList():
    return list(map(int, input().split()))
import bisect

N,L,WM  = getIntList()

z = {}
z[-1] = {1:[], -1:[]}
z[0] = {1:[], -1:[]}
z[1] = {1:[], -1:[]}
for i in range(N):
    x0,v = getIntList()
    t = (x0,v)
    if x0+L <=0:
        z[-1][v].append(t)
    elif x0>=0:
        z[1][v].append(t)
    else:
        z[0][v].append(t)
res = 0

res += len(z[-1][1] ) * len(z[ 1][-1] )
res += len(z[0][1] ) * len(z[ 1][-1] )
res += len(z[-1][1] ) * len(z[ 0][-1] )

if WM==1:
    print(res)
    return

z[1][-1].sort()
z[-1][1].sort()
#print(z[-1][1])
tn = len(z[1][-1])
for t in z[1][1]:
    g = (-WM-1) * t[0] / (-WM+1) - L
    g = max(g, t[0]+ 0.5)
    p = bisect.bisect_right(z[1][-1], (g,2) )
    res +=  tn-p

tn = len(z[-1][1])
for t in z[-1][-1]:
    g = (WM+1) * (t[0] + L)/ (WM-1)
    g = min(g, t[0] - 0.1)

    p = bisect.bisect_left(z[-1][1], (g,-2) )
    res +=  p

print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/990/A:
Berland Football Cup starts really soon! Commentators from all over the world come to the event.

Organizers have already built $n$ commentary boxes. $m$ regional delegations will come to the Cup. Every delegation should get the same number of the commentary boxes. If any box is left unoccupied then the delegations will be upset. So each box should be occupied by exactly one delegation.

If $n$ is not divisible by $m$, it is impossible to distribute the boxes to the delegations at the moment.

Organizers can build a new commentary box paying $a$ burles and demolish a commentary box paying $b$ burles. They can both build and demolish boxes arbitrary number of times (each time paying a corresponding fee). It is allowed to demolish all the existing boxes.

What is the minimal amount of burles organizers should pay to satisfy all the delegations (i.e. to make the number of the boxes be divisible by $m$)?

-----Input-----

The only line contains four integer numbers $n$, $m$, $a$ and $b$ ($1 \le n, m \le 10^{12}$, $1 \le a, b \le 100$), where $n$ is the initial number of the commentary boxes, $m$ is the number of delegations to come, $a$ is the fee to build a box and $b$ is the fee to demolish a box.

-----Output-----

Output the minimal amount of burles organizers should pay to satisfy all the delegations (i.e. to make the number of the boxes be divisible by $m$). It is allowed that the final number of the boxes is equal to $0$.

-----Examples-----
Input
9 7 3 8

Output
15

Input
2 7 3 7

Output
14

Input
30 6 17 19

Output
0

-----Note-----

In the first example organizers can build $5$ boxes to make the total of $14$ paying $3$ burles for the each of them.

In the second example organizers can demolish $2$ boxes to make the total of $0$ paying $7$ burles for the each of them.

In the third example organizers are already able to distribute all the boxes equally among the delegations, each one get $5$ boxes.

I tried it in Python, but could not do it. Can you solve it?

n, m, a, b = list(map(int, input().split()))
print(min((n%m)*b, (m - n%m)*a))


I found an interesting problem on https://codeforces.com/problemset/problem/990/B:
You have a Petri dish with bacteria and you are preparing to dive into the harsh micro-world. But, unfortunately, you don't have any microscope nearby, so you can't watch them.

You know that you have $n$ bacteria in the Petri dish and size of the $i$-th bacteria is $a_i$. Also you know intergalactic positive integer constant $K$.

The $i$-th bacteria can swallow the $j$-th bacteria if and only if $a_i > a_j$ and $a_i \le a_j + K$. The $j$-th bacteria disappear, but the $i$-th bacteria doesn't change its size. The bacteria can perform multiple swallows. On each swallow operation any bacteria $i$ can swallow any bacteria $j$ if $a_i > a_j$ and $a_i \le a_j + K$. The swallow operations go one after another.

For example, the sequence of bacteria sizes $a=[101, 53, 42, 102, 101, 55, 54]$ and $K=1$. The one of possible sequences of swallows is: $[101, 53, 42, 102, \underline{101}, 55, 54]$ $\to$ $[101, \underline{53}, 42, 102, 55, 54]$ $\to$ $[\underline{101}, 42, 102, 55, 54]$ $\to$ $[42, 102, 55, \underline{54}]$ $\to$ $[42, 102, 55]$. In total there are $3$ bacteria remained in the Petri dish.

Since you don't have a microscope, you can only guess, what the minimal possible number of bacteria can remain in your Petri dish when you finally will find any microscope.

-----Input-----

The first line contains two space separated positive integers $n$ and $K$ ($1 \le n \le 2 \cdot 10^5$, $1 \le K \le 10^6$) — number of bacteria and intergalactic constant $K$.

The second line contains $n$ space separated integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^6$) — sizes of bacteria you have.

-----Output-----

Print the only integer — minimal possible number of bacteria can remain.

-----Examples-----
Input
7 1
101 53 42 102 101 55 54

Output
3

Input
6 5
20 15 10 15 20 25

Output
1

Input
7 1000000
1 1 1 1 1 1 1

Output
7

-----Note-----

The first example is clarified in the problem statement.

In the second example an optimal possible sequence of swallows is: $[20, 15, 10, 15, \underline{20}, 25]$ $\to$ $[20,...

I tried it in Python, but could not do it. Can you solve it?

n, k = list(map(int, input().split()))
a = list(map(int, input().split()))
a.sort(reverse=True)

ans = 1
i = 1
while i < len(a):
	if a[i - 1] > a[i]:
		while i < len(a) and a[i] + k >= a[i - 1]:
			i += 1
	i += 1
	if i - 1 < len(a):
		ans += 1

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/990/C:
A bracket sequence is a string containing only characters "(" and ")".

A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()", "(())" are regular (the resulting expressions are: "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.

You are given $n$ bracket sequences $s_1, s_2, \dots , s_n$. Calculate the number of pairs $i, j \, (1 \le i, j \le n)$ such that the bracket sequence $s_i + s_j$ is a regular bracket sequence. Operation $+$ means concatenation i.e. "()(" + ")()" = "()()()".

If $s_i + s_j$ and $s_j + s_i$ are regular bracket sequences and $i \ne j$, then both pairs $(i, j)$ and $(j, i)$ must be counted in the answer. Also, if $s_i + s_i$ is a regular bracket sequence, the pair $(i, i)$ must be counted in the answer.

-----Input-----

The first line contains one integer $n \, (1 \le n \le 3 \cdot 10^5)$ — the number of bracket sequences. The following $n$ lines contain bracket sequences — non-empty strings consisting only of characters "(" and ")". The sum of lengths of all bracket sequences does not exceed $3 \cdot 10^5$.

-----Output-----

In the single line print a single integer — the number of pairs $i, j \, (1 \le i, j \le n)$ such that the bracket sequence $s_i + s_j$ is a regular bracket sequence.

-----Examples-----
Input
3
)
()
(

Output
2

Input
2
()
()

Output
4

-----Note-----

In the first example, suitable pairs are $(3, 1)$ and $(2, 2)$.

In the second example, any pair is suitable, namely $(1, 1), (1, 2), (2, 1), (2, 2)$.

I tried it in Python, but could not do it. Can you solve it?

#!/usr/bin/env python3

from collections import defaultdict

def hd(s):
	d, h = 0, 0
	dmax = 0
	for c in s:
		if c == '(':
			h += 1
			d -= 1
		else:
			h -= 1
			d += 1
			dmax = max(d, dmax)
	return h, dmax

n = int(input().strip())
h0 = 0
hp = defaultdict(int)
hm = defaultdict(int)
for _ in range(n):
	s = input().strip()
	h, d = hd(s)
	if h == d == 0:
		h0 += 1
	elif h > 0 and d == 0:
		hp[h] += 1
	elif h < 0 and h + d <= 0:
		hm[-h] += 1

res = h0 ** 2
for k, v in list(hp.items()):
	if k in hm:
		res += v * hm[k]

print (res)


I found an interesting problem on https://codeforces.com/problemset/problem/990/D:
Given three numbers $n, a, b$. You need to find an adjacency matrix of such an undirected graph that the number of components in it is equal to $a$, and the number of components in its complement is $b$. The matrix must be symmetric, and all digits on the main diagonal must be zeroes.

In an undirected graph loops (edges from a vertex to itself) are not allowed. It can be at most one edge between a pair of vertices.

The adjacency matrix of an undirected graph is a square matrix of size $n$ consisting only of "0" and "1", where $n$ is the number of vertices of the graph and the $i$-th row and the $i$-th column correspond to the $i$-th vertex of the graph. The cell $(i,j)$ of the adjacency matrix contains $1$ if and only if the $i$-th and $j$-th vertices in the graph are connected by an edge.

A connected component is a set of vertices $X$ such that for every two vertices from this set there exists at least one path in the graph connecting this pair of vertices, but adding any other vertex to $X$ violates this rule.

The complement or inverse of a graph $G$ is a graph $H$ on the same vertices such that two distinct vertices of $H$ are adjacent if and only if they are not adjacent in $G$.

-----Input-----

In a single line, three numbers are given $n, a, b \,(1 \le n \le 1000, 1 \le a, b \le n)$: is the number of vertexes of the graph, the required number of connectivity components in it, and the required amount of the connectivity component in it's complement.

-----Output-----

If there is no graph that satisfies these constraints on a single line, print "NO" (without quotes).

Otherwise, on the first line, print "YES"(without quotes). In each of the next $n$ lines, output $n$ digits such that $j$-th digit of $i$-th line must be $1$ if and only if there is an edge between vertices $i$ and $j$ in $G$ (and $0$ otherwise). Note that the matrix must be symmetric, and all digits on the main diagonal must be zeroes.

If there are several matrices that satisfy the conditions — output any of...

I tried it in Python, but could not do it. Can you solve it?

n,a,b=map(int,input().split())
if a>n:
    print('NO')
    return
if b>n:
    print("NO")
    return
if a==1  and b==1:
    if n==2 or n==3:
        print('NO')
        return
if n==1 and a>1 or n==1 and b>1:
    print('NO')
    return
if min(a,b)>1:
    print('NO')
    return

def check(mat):
    vis=[0]*n
    cnt=0
    for i in range(n):
        if vis[i]==0:
            q=[i]
            cnt+=1
            vis[i]=1
            while q:
                t=q.pop(0)
                for j in range(n):
                    if mat[t][j]==1 and vis[j]==0:
                        vis[j]=1
                        q.append(j)
        return cnt
mat=[[0 for i in range(n)] for j in range(n)]
m=max(a,b)
j=1
for i in range(n):
    if j<n:
        mat[i][j]=1
        mat[j][i]=1
    j+=1
for i in range(m-1):
    curr=n-i-1
    for j in range(n):
        if mat[curr][j]==1:
            mat[curr][j]=0
            mat[j][curr]=0
if b==1:
    print('YES')
    for i in range(n):
        print(*mat[i],sep='')

else:
    print('YES')
    for i in range(n):
        for j in range(n):
            mat[i][j]=1-mat[i][j]
    for i in range(n):
        mat[i][i]=0
    for i in range(n):
        print(*mat[i],sep='')


I found an interesting problem on https://codeforces.com/problemset/problem/990/E:
Adilbek's house is located on a street which can be represented as the OX axis. This street is really dark, so Adilbek wants to install some post lamps to illuminate it. Street has $n$ positions to install lamps, they correspond to the integer numbers from $0$ to $n - 1$ on the OX axis. However, some positions are blocked and no post lamp can be placed there.

There are post lamps of different types which differ only by their power. When placed in position $x$, post lamp of power $l$ illuminates the segment $[x; x + l]$. The power of each post lamp is always a positive integer number.

The post lamp shop provides an infinite amount of lamps of each type from power $1$ to power $k$. Though each customer is only allowed to order post lamps of exactly one type. Post lamps of power $l$ cost $a_l$ each.

What is the minimal total cost of the post lamps of exactly one type Adilbek can buy to illuminate the entire segment $[0; n]$ of the street? If some lamps illuminate any other segment of the street, Adilbek does not care, so, for example, he may place a lamp of power $3$ in position $n - 1$ (even though its illumination zone doesn't completely belong to segment $[0; n]$).

-----Input-----

The first line contains three integer numbers $n$, $m$ and $k$ ($1 \le k \le n \le 10^6$, $0 \le m \le n$) — the length of the segment of the street Adilbek wants to illuminate, the number of the blocked positions and the maximum power of the post lamp available.

The second line contains $m$ integer numbers $s_1, s_2, \dots, s_m$ ($0 \le s_1 < s_2 < \dots s_m < n$) — the blocked positions.

The third line contains $k$ integer numbers $a_1, a_2, \dots, a_k$ ($1 \le a_i \le 10^6$) — the costs of the post lamps.

-----Output-----

Print the minimal total cost of the post lamps of exactly one type Adilbek can buy to illuminate the entire segment $[0; n]$ of the street.

If illumintaing the entire segment $[0; n]$ is impossible, print -1.

-----Examples-----
Input
6 2 3
1 3
1 2 3

Output
6

Input
4 3 4
1 2 3
1 10 100...

I tried it in Python, but could not do it. Can you solve it?

import sys
from math import ceil

n, m, k = list(map(int, sys.stdin.readline().split()))
places = [True for _ in range(n)]
for x in map(int, sys.stdin.readline().split()):
    places[x] = False
costs = list(map(int, sys.stdin.readline().split()))
if not places[0]:
    print(-1)
    return

prev = [i for i in range(n)]
last = 0
for i in range(n):
    if places[i]:
        last = i
    prev[i] = last

best_cost = float('inf')
for lamp in range(k, 0, -1):
    min_cost = ceil(n/lamp) * costs[lamp-1]
    if min_cost >= best_cost:
        continue

    # try this shit
    cost = costs[lamp-1]
    reach = lamp
    fail = False

    while reach < n:
        if prev[reach] + lamp <= reach:
            fail = True
            break
        reach = prev[reach] + lamp
        cost += costs[lamp - 1]

        if cost + (ceil((n - reach)/lamp) * costs[lamp-1]) >= best_cost:
            fail = True
            break

    if not fail:
        best_cost = min(best_cost, cost)

print(best_cost if best_cost != float('inf') else -1)


I found an interesting problem on https://codeforces.com/problemset/problem/991/A:
Each student eagerly awaits the day he would pass the exams successfully. Thus, Vasya was ready to celebrate, but, alas, he didn't pass it. However, many of Vasya's fellow students from the same group were more successful and celebrated after the exam.

Some of them celebrated in the BugDonalds restaurant, some of them — in the BeaverKing restaurant, the most successful ones were fast enough to celebrate in both of restaurants. Students which didn't pass the exam didn't celebrate in any of those restaurants and elected to stay home to prepare for their reexamination. However, this quickly bored Vasya and he started checking celebration photos on the Kilogramm. He found out that, in total, BugDonalds was visited by $A$ students, BeaverKing — by $B$ students and $C$ students visited both restaurants. Vasya also knows that there are $N$ students in his group.

Based on this info, Vasya wants to determine either if his data contradicts itself or, if it doesn't, how many students in his group didn't pass the exam. Can you help him so he won't waste his valuable preparation time?

-----Input-----

The first line contains four integers — $A$, $B$, $C$ and $N$ ($0 \leq A, B, C, N \leq 100$).

-----Output-----

If a distribution of $N$ students exists in which $A$ students visited BugDonalds, $B$ — BeaverKing, $C$ — both of the restaurants and at least one student is left home (it is known that Vasya didn't pass the exam and stayed at home), output one integer — amount of students (including Vasya) who did not pass the exam.

If such a distribution does not exist and Vasya made a mistake while determining the numbers $A$, $B$, $C$ or $N$ (as in samples 2 and 3), output $-1$.

-----Examples-----
Input
10 10 5 20

Output
5
Input
2 2 0 4

Output
-1
Input
2 2 2 1

Output
-1

-----Note-----

The first sample describes following situation: $5$ only visited BugDonalds, $5$ students only visited BeaverKing, $5$ visited both of them and $5$ students (including Vasya) didn't pass the exam.

In the second sample $2$...

I tried it in Python, but could not do it. Can you solve it?

a,b,c,n=list(map(int,input().split()))
if (c > a or c > b or a + b - c > n - 1):
  print(-1)
else:
  print(n-a-b+c)


I found an interesting problem on https://codeforces.com/problemset/problem/991/B:
Translator's note: in Russia's most widespread grading system, there are four grades: 5, 4, 3, 2, the higher the better, roughly corresponding to A, B, C and F respectively in American grading system.

The term is coming to an end and students start thinking about their grades. Today, a professor told his students that the grades for his course would be given out automatically  — he would calculate the simple average (arithmetic mean) of all grades given out for lab works this term and round to the nearest integer. The rounding would be done in favour of the student — $4.5$ would be rounded up to $5$ (as in example 3), but $4.4$ would be rounded down to $4$.

This does not bode well for Vasya who didn't think those lab works would influence anything, so he may receive a grade worse than $5$ (maybe even the dreaded $2$). However, the professor allowed him to redo some of his works of Vasya's choosing to increase his average grade. Vasya wants to redo as as few lab works as possible in order to get $5$ for the course. Of course, Vasya will get $5$ for the lab works he chooses to redo.

Help Vasya — calculate the minimum amount of lab works Vasya has to redo.

-----Input-----

The first line contains a single integer $n$ — the number of Vasya's grades ($1 \leq n \leq 100$).

The second line contains $n$ integers from $2$ to $5$ — Vasya's grades for his lab works.

-----Output-----

Output a single integer — the minimum amount of lab works that Vasya has to redo. It can be shown that Vasya can always redo enough lab works to get a $5$.

-----Examples-----
Input
3
4 4 4

Output
2

Input
4
5 4 5 5

Output
0

Input
4
5 3 3 5

Output
1

-----Note-----

In the first sample, it is enough to redo two lab works to make two $4$s into $5$s.

In the second sample, Vasya's average is already $4.75$ so he doesn't have to redo anything to get a $5$.

In the second sample Vasya has to redo one lab work to get rid of one of the $3$s, that will make the average exactly $4.5$ so the final grade would be $5$.

I tried it in Python, but could not do it. Can you solve it?

n = int(input())
a = sorted(list(map(int, input().split())))

for i in range(n + 1):
    cur_sum = 5 * i + sum(a[i:])

    if cur_sum * 10 >= n * 45:
        print(i)
        break


I found an interesting problem on https://codeforces.com/problemset/problem/991/C:
After passing a test, Vasya got himself a box of $n$ candies. He decided to eat an equal amount of candies each morning until there are no more candies. However, Petya also noticed the box and decided to get some candies for himself.

This means the process of eating candies is the following: in the beginning Vasya chooses a single integer $k$, same for all days. After that, in the morning he eats $k$ candies from the box (if there are less than $k$ candies in the box, he eats them all), then in the evening Petya eats $10\%$ of the candies remaining in the box. If there are still candies left in the box, the process repeats — next day Vasya eats $k$ candies again, and Petya — $10\%$ of the candies left in a box, and so on.

If the amount of candies in the box is not divisible by $10$, Petya rounds the amount he takes from the box down. For example, if there were $97$ candies in the box, Petya would eat only $9$ of them. In particular, if there are less than $10$ candies in a box, Petya won't eat any at all.

Your task is to find out the minimal amount of $k$ that can be chosen by Vasya so that he would eat at least half of the $n$ candies he initially got. Note that the number $k$ must be integer.

-----Input-----

The first line contains a single integer $n$ ($1 \leq n \leq 10^{18}$) — the initial amount of candies in the box.

-----Output-----

Output a single integer — the minimal amount of $k$ that would allow Vasya to eat at least half of candies he got.

-----Example-----
Input
68

Output
3

-----Note-----

In the sample, the amount of candies, with $k=3$, would change in the following way (Vasya eats first):

$68 \to 65 \to 59 \to 56 \to 51 \to 48 \to 44 \to 41 \\ \to 37 \to 34 \to 31 \to 28 \to 26 \to 23 \to 21 \to 18 \to 17 \to 14 \\ \to 13 \to 10 \to 9 \to 6 \to 6 \to 3 \to 3 \to 0$.

In total, Vasya would eat $39$ candies, while Petya — $29$.

I tried it in Python, but could not do it. Can you solve it?

n = int(input())

l = 0
r = n

def eats(n, k):
	res = 0
	while n > 0:
		if n < k:
			res += n
			n = 0
		else:
			res += k
			n -= k
			n -= n//10
	return res

while r-l > 1:
	mid = (r + l) // 2
	if eats(n, mid) >= (n+1) // 2:
		r = mid
	else:
		l = mid

print(r)


I found an interesting problem on https://codeforces.com/problemset/problem/991/D:
Bishwock is a chess figure that consists of three squares resembling an "L-bar". This figure can be rotated by 90, 180 and 270 degrees so it can have four possible states:

XX   XX   .X   X.

X.   .X   XX   XX

Bishwocks don't attack any squares and can even occupy on the adjacent squares as long as they don't occupy the same square.

Vasya has a board with $2\times n$ squares onto which he wants to put some bishwocks. To his dismay, several squares on this board are already occupied by pawns and Vasya can't put bishwocks there. However, pawns also don't attack bishwocks and they can occupy adjacent squares peacefully.

Knowing the positions of pawns on the board, help Vasya to determine the maximum amount of bishwocks he can put onto the board so that they wouldn't occupy the same squares and wouldn't occupy squares with pawns.

-----Input-----

The input contains two nonempty strings that describe Vasya's board. Those strings contain only symbols "0" (zero) that denote the empty squares and symbols "X" (uppercase English letter) that denote the squares occupied by pawns. Strings are nonempty and are of the same length that does not exceed $100$.

-----Output-----

Output a single integer — the maximum amount of bishwocks that can be placed onto the given board.

-----Examples-----
Input
00
00

Output
1
Input
00X00X0XXX0
0XXX0X00X00

Output
4
Input
0X0X0
0X0X0

Output
0
Input
0XXX0
00000

Output
2

I tried it in Python, but could not do it. Can you solve it?

topboard = list(input())
botboard = list(input())

bish = 0
left = 0
while left + 1 < len(topboard):
    if topboard[left] == '0' and botboard[left] == '0':
        if topboard[left+1] == '0':
            bish += 1
            topboard[left] = 'X'
            topboard[left+1] = 'X'
            botboard[left] = 'X'
        elif botboard[left+1] == '0':
            bish += 1
            topboard[left] = 'X'
            botboard[left] = 'X'
            botboard[left+1] = 'X'
    elif topboard[left+1] == '0' and botboard[left+1] == '0':
        if topboard[left] == '0':
            bish += 1
            topboard[left] = 'X'
            topboard[left+1] = 'X'
            botboard[left+1] = 'X'
        elif botboard[left] == '0':
            bish += 1
            topboard[left+1] = 'X'
            botboard[left] = 'X'
            botboard[left+1] = 'X'

    left += 1

print(bish)


I found an interesting problem on https://codeforces.com/problemset/problem/991/E:
This night wasn't easy on Vasya. His favorite team lost, and he didn't find himself victorious either — although he played perfectly, his teammates let him down every time. He had to win at least one more time, but the losestreak only grew longer and longer... It's no wonder he didn't get any sleep this night at all.

In the morning, Vasya was waiting the bus to the university on the bus stop. Vasya's thoughts were hazy and so he couldn't remember the right bus' number quite right and got onto the bus with the number $n$.

In the bus, Vasya thought that he could get the order of the digits in the number of the bus wrong. Futhermore, he could "see" some digits several times, but the digits he saw were definitely in the real number of the bus. For example, if Vasya saw the number 2028, it could mean that the real bus number could be 2028, 8022, 2820 or just 820. However, numbers 80, 22208, 52 definitely couldn't be the number of the bus. Also, real bus number couldn't start with the digit 0, this meaning that, for example, number 082 couldn't be the real bus number too.

Given $n$, determine the total number of possible bus number variants.

-----Input-----

The first line contains one integer $n$ ($1 \leq n \leq 10^{18}$) — the number of the bus that was seen by Vasya. It is guaranteed that this number does not start with $0$.

-----Output-----

Output a single integer — the amount of possible variants of the real bus number.

-----Examples-----
Input
97

Output
2

Input
2028

Output
13

-----Note-----

In the first sample, only variants $97$ and $79$ are possible.

In the second sample, the variants (in the increasing order) are the following: $208$, $280$, $802$, $820$, $2028$, $2082$, $2208$, $2280$, $2802$, $2820$, $8022$, $8202$, $8220$.

I tried it in Python, but could not do it. Can you solve it?

import itertools as it

def factorial(n):
    i = 1
    for j in range(1, n + 1):
        i *= j
    return i

def C(n, k):
    k = max([k, n - k])
    result = 1
    for i in range(k + 1, n + 1):
        result *= i
    result //= factorial(n - k)
    return result

n = input()

digits = [0 for _ in range(10)]

for i in n:
    digits[int(i)] += 1

result = 0

for amounts in it.product(*[[0] if x == 0 else list(range(1, x + 1)) for x in digits]):
    sum_no_zero = sum(amounts[1:])
    if sum_no_zero == 0:
        continue
    #print(amounts)
    tmp = factorial(sum_no_zero)
    for j in amounts[1:]:
        tmp //= factorial(j)
    tmp *= C(sum_no_zero + amounts[0] - 1, amounts[0])
    result += tmp

print(result)


I found an interesting problem on https://codeforces.com/problemset/problem/992/A:
Nastya owns too many arrays now, so she wants to delete the least important of them. However, she discovered that this array is magic! Nastya now knows that the array has the following properties:

  In one second we can add an arbitrary (possibly negative) integer to all elements of the array that are not equal to zero.  When all elements of the array become equal to zero, the array explodes.

Nastya is always busy, so she wants to explode the array as fast as possible. Compute the minimum time in which the array can be exploded.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 10^5) — the size of the array.

The second line contains n integers a_1, a_2, ..., a_{n} ( - 10^5 ≤ a_{i} ≤ 10^5) — the elements of the array.

-----Output-----

Print a single integer — the minimum number of seconds needed to make all elements of the array equal to zero.

-----Examples-----
Input
5
1 1 1 1 1

Output
1

Input
3
2 0 -1

Output
2

Input
4
5 -6 -5 1

Output
4

-----Note-----

In the first example you can add  - 1 to all non-zero elements in one second and make them equal to zero.

In the second example you can add  - 2 on the first second, then the array becomes equal to [0, 0,  - 3]. On the second second you can add 3 to the third (the only non-zero) element.

I tried it in Python, but could not do it. Can you solve it?

n = int(input())
a = set(list(map(int, input().split())))
ans = len(a)
if 0 in a:
    ans -= 1
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/992/B:
Today on Informatics class Nastya learned about GCD and LCM (see links below). Nastya is very intelligent, so she solved all the tasks momentarily and now suggests you to solve one of them as well.

We define a pair of integers (a, b) good, if GCD(a, b) = x and LCM(a, b) = y, where GCD(a, b) denotes the greatest common divisor of a and b, and LCM(a, b) denotes the least common multiple of a and b.

You are given two integers x and y. You are to find the number of good pairs of integers (a, b) such that l ≤ a, b ≤ r. Note that pairs (a, b) and (b, a) are considered different if a ≠ b.

-----Input-----

The only line contains four integers l, r, x, y (1 ≤ l ≤ r ≤ 10^9, 1 ≤ x ≤ y ≤ 10^9).

-----Output-----

In the only line print the only integer — the answer for the problem.

-----Examples-----
Input
1 2 1 2

Output
2

Input
1 12 1 12

Output
4

Input
50 100 3 30

Output
0

-----Note-----

In the first example there are two suitable good pairs of integers (a, b): (1, 2) and (2, 1).

In the second example there are four suitable good pairs of integers (a, b): (1, 12), (12, 1), (3, 4) and (4, 3).

In the third example there are good pairs of integers, for example, (3, 30), but none of them fits the condition l ≤ a, b ≤ r.

I tried it in Python, but could not do it. Can you solve it?

import math

def get_div(n):
    a = []
    for i in range(1,int(n**.5)+1):
        if n % i == 0:
            a.append([i,n//i])
    return a

tmp = [int(i) for i in input().split()]
l,r,x,y = tmp[0],tmp[1],tmp[2],tmp[3]
if y % x != 0:
    print(0)
else:
    c = 0
    a = get_div(y//x)
    for p in a:
        pl = min(p)
        pr = max(p)
        if math.gcd(pl,pr) == 1:#(1 in p) or (pr % pl != 0):
            if l <= x * pl and x * pr <= r:
                c += 1
                if p[0] != p[1]:
                    c += 1
    print(c)


I found an interesting problem on https://codeforces.com/problemset/problem/992/C:
Nastya received a gift on New Year — a magic wardrobe. It is magic because in the end of each month the number of dresses in it doubles (i.e. the number of dresses becomes twice as large as it is in the beginning of the month).

Unfortunately, right after the doubling the wardrobe eats one of the dresses (if any) with the 50% probability. It happens every month except the last one in the year.

Nastya owns x dresses now, so she became interested in the expected number of dresses she will have in one year. Nastya lives in Byteland, so the year lasts for k + 1 months.

Nastya is really busy, so she wants you to solve this problem. You are the programmer, after all. Also, you should find the answer modulo 10^9 + 7, because it is easy to see that it is always integer.

-----Input-----

The only line contains two integers x and k (0 ≤ x, k ≤ 10^18), where x is the initial number of dresses and k + 1 is the number of months in a year in Byteland.

-----Output-----

In the only line print a single integer — the expected number of dresses Nastya will own one year later modulo 10^9 + 7.

-----Examples-----
Input
2 0

Output
4

Input
2 1

Output
7

Input
3 2

Output
21

-----Note-----

In the first example a year consists on only one month, so the wardrobe does not eat dresses at all.

In the second example after the first month there are 3 dresses with 50% probability and 4 dresses with 50% probability. Thus, in the end of the year there are 6 dresses with 50% probability and 8 dresses with 50% probability. This way the answer for this test is (6 + 8) / 2 = 7.

I tried it in Python, but could not do it. Can you solve it?

x, k = [int(x) for x in input().split()]

if x == 0:
    print(0)
    return

mod = 10 ** 9 + 7

res = x * pow(2, k + 1, mod) % mod
res = ((res - (pow(2, k, mod) - 1)) % mod + mod) % mod

print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/992/D:
Nastya received one more array on her birthday, this array can be used to play a traditional Byteland game on it. However, to play the game the players should first select such a subsegment of the array that $\frac{p}{s} = k$, where p is the product of all integers on the given array, s is their sum, and k is a given constant for all subsegments.

Nastya wonders how many subsegments of the array fit the described conditions. A subsegment of an array is several consecutive integers of the array.

-----Input-----

The first line contains two integers n and k (1 ≤ n ≤ 2·10^5, 1 ≤ k ≤ 10^5), where n is the length of the array and k is the constant described above.

The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^8) — the elements of the array.

-----Output-----

In the only line print the number of subsegments such that the ratio between the product and the sum on them is equal to k.

-----Examples-----
Input
1 1
1

Output
1

Input
4 2
6 3 8 1

Output
2

-----Note-----

In the first example the only subsegment is [1]. The sum equals 1, the product equals 1, so it suits us because $\frac{1}{1} = 1$.

There are two suitable subsegments in the second example — [6, 3] and [3, 8, 1]. Subsegment [6, 3] has sum 9 and product 18, so it suits us because $\frac{18}{9} = 2$. Subsegment [3, 8, 1] has sum 12 and product 24, so it suits us because $\frac{24}{12} = 2$.

I tried it in Python, but could not do it. Can you solve it?

# https://codeforces.com/problemset/problem/992/D
n, k =  map(int, input().split())
a    =  list(map(int, input().split()))
max_ =  10 ** 13 + 1

def get(l, r, x):
    min_ =  min(l,r)
    max_ =  max(l,r)

    if x <= min_:
        return x + 1

    if x <= max_:
        return min_ + 1

    return l+r+1-x

def solve(a, k):
    cnt  = 0
    arr  = [i  for i, x in enumerate(a) if x>1]
    n_   = len(arr)

    for i in range(n_-1):
        curS = 0
        curP = 1
        l    = arr[i] if i == 0 else arr[i] - arr[i-1] - 1

        for j in range(i, n_):
            ind   = arr[j]
            curS += a[ind]
            curP *= a[ind]

            if curP > max_:
                break

            if curP % curS == 0:
                if curP // curS == k:
                    #print(arr[i], arr[j], curP, curS)
                    cnt+=1

            r = arr[j+1] - arr[j] - 1
            x = curP // k - curS

            if curP % k == 0 and x > 0  and x <= l + r:
                #print(arr[i], arr[j], curP, curS)
                cnt+=get(l, r, x)
            curS += r

    if k==1:
        cnt+=len(a)-n_
    return cnt

ans=0
a.append(max_)
ans += solve(a, k)

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/993/A:
You are given two squares, one with sides parallel to the coordinate axes, and another one with sides at 45 degrees to the coordinate axes. Find whether the two squares intersect.

The interior of the square is considered to be part of the square, i.e. if one square is completely inside another, they intersect. If the two squares only share one common point, they are also considered to intersect.

-----Input-----

The input data consists of two lines, one for each square, both containing 4 pairs of integers. Each pair represents coordinates of one vertex of the square. Coordinates within each line are either in clockwise or counterclockwise order.

The first line contains the coordinates of the square with sides parallel to the coordinate axes, the second line contains the coordinates of the square at 45 degrees.

All the values are integer and between $-100$ and $100$.

-----Output-----

Print "Yes" if squares intersect, otherwise print "No".

You can print each letter in any case (upper or lower).

-----Examples-----
Input
0 0 6 0 6 6 0 6
1 3 3 5 5 3 3 1

Output
YES

Input
0 0 6 0 6 6 0 6
7 3 9 5 11 3 9 1

Output
NO

Input
6 0 6 6 0 6 0 0
7 4 4 7 7 10 10 7

Output
YES

-----Note-----

In the first example the second square lies entirely within the first square, so they do intersect.

In the second sample squares do not have any points in common.

Here are images corresponding to the samples: [Image]  [Image]  [Image]

I tried it in Python, but could not do it. Can you solve it?


I found an interesting problem on https://codeforces.com/problemset/problem/993/B:
Two participants are each given a pair of distinct numbers from 1 to 9 such that there's exactly one number that is present in both pairs. They want to figure out the number that matches by using a communication channel you have access to without revealing it to you.

Both participants communicated to each other a set of pairs of numbers, that includes the pair given to them. Each pair in the communicated sets comprises two different numbers.

Determine if you can with certainty deduce the common number, or if you can determine with certainty that both participants know the number but you do not.

-----Input-----

The first line contains two integers $n$ and $m$ ($1 \le n, m \le 12$) — the number of pairs the first participant communicated to the second and vice versa.

The second line contains $n$ pairs of integers, each between $1$ and $9$, — pairs of numbers communicated from first participant to the second.

The third line contains $m$ pairs of integers, each between $1$ and $9$, — pairs of numbers communicated from the second participant to the first.

All pairs within each set are distinct (in particular, if there is a pair $(1,2)$, there will be no pair $(2,1)$ within the same set), and no pair contains the same number twice.

It is guaranteed that the two sets do not contradict the statements, in other words, there is pair from the first set and a pair from the second set that share exactly one number.

-----Output-----

If you can deduce the shared number with certainty, print that number.

If you can with certainty deduce that both participants know the shared number, but you do not know it, print $0$.

Otherwise print $-1$.

-----Examples-----
Input
2 2
1 2 3 4
1 5 3 4

Output
1

Input
2 2
1 2 3 4
1 5 6 4

Output
0

Input
2 3
1 2 4 5
1 2 1 3 2 3

Output
-1

-----Note-----

In the first example the first participant communicated pairs $(1,2)$ and $(3,4)$, and the second communicated $(1,5)$, $(3,4)$. Since we know that the actual pairs they received share exactly one number, it can't be that...

I tried it in Python, but could not do it. Can you solve it?

def readpts():
	ip = list(map(int, input().split()))
	return [(min(ip[i], ip[i+1]), max(ip[i], ip[i+1])) for i in range(0,len(ip),2)]

N, M = list(map(int, input().split()))
pts1 = readpts()
pts2 = readpts()
#print(pts1)
#print(pts2)

def psb(a, b):
	if a == b: return False
	return any(i in b for i in a)

def sb(a, b):
	for i in a:
		if i in b:
			return i
	return -1 # should not happen

def ipsv(pts1, pts2):
	ans = False
	for p1 in pts1:
		gsb = set()
		for p2 in pts2:
			if psb(p1, p2):
				gsb.add(sb(p1, p2))
		if len(gsb) > 1: return False
		if len(gsb) == 1: ans = True
	return ans

def sv():
	gsb = set()
	for p1 in pts1:
		for p2 in pts2:
			if psb(p1, p2):
				gsb.add(sb(p1, p2))
	if len(gsb) == 0: return -1
	if len(gsb) == 1: return list(gsb)[0]
	if ipsv(pts1, pts2) and ipsv(pts2, pts1): return 0
	return -1

print(sv())


I found an interesting problem on https://codeforces.com/problemset/problem/993/C:
There are two small spaceship, surrounded by two groups of enemy larger spaceships. The space is a two-dimensional plane, and one group of the enemy spaceships is positioned in such a way that they all have integer $y$-coordinates, and their $x$-coordinate is equal to $-100$, while the second group is positioned in such a way that they all have integer $y$-coordinates, and their $x$-coordinate is equal to $100$.

Each spaceship in both groups will simultaneously shoot two laser shots (infinite ray that destroys any spaceship it touches), one towards each of the small spaceships, all at the same time. The small spaceships will be able to avoid all the laser shots, and now want to position themselves at some locations with $x=0$ (with not necessarily integer $y$-coordinates), such that the rays shot at them would destroy as many of the enemy spaceships as possible. Find the largest numbers of spaceships that can be destroyed this way, assuming that the enemy spaceships can't avoid laser shots.

-----Input-----

The first line contains two integers $n$ and $m$ ($1 \le n, m \le 60$), the number of enemy spaceships with $x = -100$ and the number of enemy spaceships with $x = 100$, respectively.

The second line contains $n$ integers $y_{1,1}, y_{1,2}, \ldots, y_{1,n}$ ($|y_{1,i}| \le 10\,000$) — the $y$-coordinates of the spaceships in the first group.

The third line contains $m$ integers $y_{2,1}, y_{2,2}, \ldots, y_{2,m}$ ($|y_{2,i}| \le 10\,000$) — the $y$-coordinates of the spaceships in the second group.

The $y$ coordinates are not guaranteed to be unique, even within a group.

-----Output-----

Print a single integer – the largest number of enemy spaceships that can be destroyed.

-----Examples-----
Input
3 9
1 2 3
1 2 3 7 8 9 11 12 13

Output
9

Input
5 5
1 2 3 4 5
1 2 3 4 5

Output
10

-----Note-----

In the first example the first spaceship can be positioned at $(0, 2)$, and the second – at $(0, 7)$. This way all the enemy spaceships in the first group and $6$ out of $9$ spaceships in the second...

I tried it in Python, but could not do it. Can you solve it?

from collections import Counter
MV = 400020
a = [0] * MV
for i in range(MV):
    a[i] = set()

n ,m = list(map(int , input().split()))

first = list(map(int , input().split()))
second = list(map(int , input().split()))

for fid, f in enumerate(first):
    for sid, s in enumerate(second):
        a[f+s].add(fid + MV)
        a[f+s].add(sid)

a.sort(key = lambda x: -len(x))

b = [len(k) for k in a]

# for k in range(MV):
#     if b[k]>0:
#         print(k, b[k], a[k])

best_res = b[0]
for pos in range(MV):
    for pos2 in range(MV):
        if b[pos] + b [pos2] <= best_res:
            break
        cur = len(a[pos].union(a[pos2]))
        if cur > best_res :
            best_res = cur
print(best_res)


I found an interesting problem on https://codeforces.com/problemset/problem/993/D:
You need to execute several tasks, each associated with number of processors it needs, and the compute power it will consume.

You have sufficient number of analog computers, each with enough processors for any task. Each computer can execute up to one task at a time, and no more than two tasks total. The first task can be any, the second task on each computer must use strictly less power than the first. You will assign between 1 and 2 tasks to each computer. You will then first execute the first task on each computer, wait for all of them to complete, and then execute the second task on each computer that has two tasks assigned.

If the average compute power per utilized processor (the sum of all consumed powers for all tasks presently running divided by the number of utilized processors) across all computers exceeds some unknown threshold during the execution of the first tasks, the entire system will blow up. There is no restriction on the second tasks execution. Find the lowest threshold for which it is possible.

Due to the specifics of the task, you need to print the answer multiplied by 1000 and rounded up.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 50) — the number of tasks.

The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^8), where a_{i} represents the amount of power required for the i-th task.

The third line contains n integers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 100), where b_{i} is the number of processors that i-th task will utilize.

-----Output-----

Print a single integer value — the lowest threshold for which it is possible to assign all tasks in such a way that the system will not blow up after the first round of computation, multiplied by 1000 and rounded up.

-----Examples-----
Input
6
8 10 9 9 8 10
1 1 1 1 1 1

Output
9000

Input
6
8 10 9 9 8 10
1 10 5 5 1 10

Output
1160

-----Note-----

In the first example the best strategy is to run each task on a separate computer, getting average compute per processor during the first round...

I tried it in Python, but could not do it. Can you solve it?

#     Codeforces Round #488 by NEAR (Div. 2)
import collections
from functools import cmp_to_key
#key=cmp_to_key(lambda x,y: 1 if x not in y else -1 )
import math
import sys
def getIntList():
    return list(map(int, input().split()))

import bisect

def makePair(z):
    return  [(z[i], z[i+1]) for i in range(0,len(z),2) ]

N, =  getIntList()
za = getIntList()
zb = getIntList()

sa = set(za)

xa = list(sa)
xa.sort(reverse = True)

zz = [(t, sorted([zb[i]  for i in range(N) if za[i] == t]) )  for t in xa ]
#print(zz)

lastdp = [[] for i in range(52)]
lastdp[0] = [(0,0)]

def addres(z, t):
    if len(z) ==0:
        z.append(t)
        return
    i = bisect.bisect_right(z,t)
    if i>0 and z[i-1][1] >= t[1]: return
    if i<len(z) and t[1] >= z[i][1]:
        z[i] = t
        return
    z.insert(i,t)

for x in zz:
    nowdp  = [[] for i in range(52)]
    for i in range(len(lastdp)):
        tz = lastdp[i]
        if len( tz ) ==0 : continue
        num = len(x[1])
        hide = min(i, num )

        tb = sum(x[1])
        acc =0;

        for j in range(hide + 1):
            la = x[0] * (num-j)
            lb = tb - acc
            if j<num: acc += x[1][j]
            for t in tz:
                # t = (0,0)
                tr = (t[0] + la, t[1] + lb)
                addres(nowdp[ i -j + num -j] ,tr)
    lastdp = nowdp
    #print(lastdp)

res = 10 ** 20
for x in lastdp:
    for y in x:
        t = math.ceil(y[0] *1000   /  y[1] )
        res = min( res,t)

print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/994/A:
You are locked in a room with a door that has a keypad with 10 keys corresponding to digits from 0 to 9. To escape from the room, you need to enter a correct code. You also have a sequence of digits.

Some keys on the keypad have fingerprints. You believe the correct code is the longest not necessarily contiguous subsequence of the sequence you have that only contains digits with fingerprints on the corresponding keys. Find such code.

-----Input-----

The first line contains two integers $n$ and $m$ ($1 \le n, m \le 10$) representing the number of digits in the sequence you have and the number of keys on the keypad that have fingerprints.

The next line contains $n$ distinct space-separated integers $x_1, x_2, \ldots, x_n$ ($0 \le x_i \le 9$) representing the sequence.

The next line contains $m$ distinct space-separated integers $y_1, y_2, \ldots, y_m$ ($0 \le y_i \le 9$) — the keys with fingerprints.

-----Output-----

In a single line print a space-separated sequence of integers representing the code. If the resulting sequence is empty, both printing nothing and printing a single line break is acceptable.

-----Examples-----
Input
7 3
3 5 7 1 6 2 8
1 2 7

Output
7 1 2

Input
4 4
3 4 1 0
0 1 7 9

Output
1 0

-----Note-----

In the first example, the only digits with fingerprints are $1$, $2$ and $7$. All three of them appear in the sequence you know, $7$ first, then $1$ and then $2$. Therefore the output is 7 1 2. Note that the order is important, and shall be the same as the order in the original sequence.

In the second example digits $0$, $1$, $7$ and $9$ have fingerprints, however only $0$ and $1$ appear in the original sequence. $1$ appears earlier, so the output is 1 0. Again, the order is important.

I tried it in Python, but could not do it. Can you solve it?

from math import ceil, log
t = 1
for test in range(t):
    n,m = list(map(int, input().split()))
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))
    ans = []
    for key in a:
        if key in b:
            ans.append(key)
    print(*ans)


I found an interesting problem on https://codeforces.com/problemset/problem/994/B:
Unlike Knights of a Round Table, Knights of a Polygonal Table deprived of nobility and happy to kill each other. But each knight has some power and a knight can kill another knight if and only if his power is greater than the power of victim. However, even such a knight will torment his conscience, so he can kill no more than $k$ other knights. Also, each knight has some number of coins. After a kill, a knight can pick up all victim's coins.

Now each knight ponders: how many coins he can have if only he kills other knights?

You should answer this question for each knight.

-----Input-----

The first line contains two integers $n$ and $k$ $(1 \le n \le 10^5, 0 \le k \le \min(n-1,10))$ — the number of knights and the number $k$ from the statement.

The second line contains $n$ integers $p_1, p_2 ,\ldots,p_n$ $(1 \le p_i \le 10^9)$ — powers of the knights. All $p_i$ are distinct.

The third line contains $n$ integers $c_1, c_2 ,\ldots,c_n$ $(0 \le c_i \le 10^9)$ — the number of coins each knight has.

-----Output-----

Print $n$ integers — the maximum number of coins each knight can have it only he kills other knights.

-----Examples-----
Input
4 2
4 5 9 7
1 2 11 33

Output
1 3 46 36
Input
5 1
1 2 3 4 5
1 2 3 4 5

Output
1 3 5 7 9
Input
1 0
2
3

Output
3

-----Note-----

Consider the first example.   The first knight is the weakest, so he can't kill anyone. That leaves him with the only coin he initially has.  The second knight can kill the first knight and add his coin to his own two.  The third knight is the strongest, but he can't kill more than $k = 2$ other knights. It is optimal to kill the second and the fourth knights: $2+11+33 = 46$.  The fourth knight should kill the first and the second knights: $33+1+2 = 36$.

In the second example the first knight can't kill anyone, while all the others should kill the one with the index less by one than their own.

In the third example there is only one knight, so he can't kill anyone.

I tried it in Python, but could not do it. Can you solve it?

import heapq
n, k = list(map(int, input().split()))
p = list(map(int, input().split()))
c = list(map(int, input().split()))
indexes = sorted(list(range(n)), key=p.__getitem__)
most_vyg_odn_yye = []
res = [1]*n
cur_res = 0
for ind in indexes:
	this_cost = c[ind]
	heapq.heappush(most_vyg_odn_yye, this_cost)
	cur_res += this_cost
	res[ind] = cur_res
	if len(most_vyg_odn_yye) > k:
		cur_res -= heapq.heappop(most_vyg_odn_yye)
print(*res)


I found an interesting problem on https://codeforces.com/problemset/problem/996/A:
Allen has a LOT of money. He has $n$ dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are $1$, $5$, $10$, $20$, $100$. What is the minimum number of bills Allen could receive after withdrawing his entire balance?

-----Input-----

The first and only line of input contains a single integer $n$ ($1 \le n \le 10^9$).

-----Output-----

Output the minimum number of bills that Allen could receive.

-----Examples-----
Input
125

Output
3

Input
43

Output
5

Input
1000000000

Output
10000000

-----Note-----

In the first sample case, Allen can withdraw this with a $100$ dollar bill, a $20$ dollar bill, and a $5$ dollar bill. There is no way for Allen to receive $125$ dollars in one or two bills.

In the second sample case, Allen can withdraw two $20$ dollar bills and three $1$ dollar bills.

In the third sample case, Allen can withdraw $100000000$ (ten million!) $100$ dollar bills.

I tried it in Python, but could not do it. Can you solve it?


I found an interesting problem on https://codeforces.com/problemset/problem/996/B:
Allen wants to enter a fan zone that occupies a round square and has $n$ entrances.

There already is a queue of $a_i$ people in front of the $i$-th entrance. Each entrance allows one person from its queue to enter the fan zone in one minute.

Allen uses the following strategy to enter the fan zone:   Initially he stands in the end of the queue in front of the first entrance.  Each minute, if he is not allowed into the fan zone during the minute (meaning he is not the first in the queue), he leaves the current queue and stands in the end of the queue of the next entrance (or the first entrance if he leaves the last entrance).

Determine the entrance through which Allen will finally enter the fan zone.

-----Input-----

The first line contains a single integer $n$ ($2 \le n \le 10^5$) — the number of entrances.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 10^9$) — the number of people in queues. These numbers do not include Allen.

-----Output-----

Print a single integer — the number of entrance that Allen will use.

-----Examples-----
Input
4
2 3 2 0

Output
3

Input
2
10 10

Output
1

Input
6
5 2 6 5 7 4

Output
6

-----Note-----

In the first example the number of people (not including Allen) changes as follows: $[\textbf{2}, 3, 2, 0] \to [1, \textbf{2}, 1, 0] \to [0, 1, \textbf{0}, 0]$. The number in bold is the queue Alles stands in. We see that he will enter the fan zone through the third entrance.

In the second example the number of people (not including Allen) changes as follows: $[\textbf{10}, 10] \to [9, \textbf{9}] \to [\textbf{8}, 8] \to [7, \textbf{7}] \to [\textbf{6}, 6] \to \\ [5, \textbf{5}] \to [\textbf{4}, 4] \to [3, \textbf{3}] \to [\textbf{2}, 2] \to [1, \textbf{1}] \to [\textbf{0}, 0]$.

In the third example the number of people (not including Allen) changes as follows: $[\textbf{5}, 2, 6, 5, 7, 4] \to [4, \textbf{1}, 5, 4, 6, 3] \to [3, 0, \textbf{4}, 3, 5, 2] \to \\ [2, 0, 3, \textbf{2}, 4, 1] \to [1, 0, 2, 1, \textbf{3}, 0] \to [0, 0, 1, 0, 2,...

I tried it in Python, but could not do it. Can you solve it?

n = int(input())
a = list(map(int, input().split()))
mn = 10000000000
ans = -1
from math import ceil
for i in range(n):
    b = a[i] - i
    c = int(ceil(b / n))
    cc = n*c
    if n*c < mn:
        mn = n*c
        ans = i+1
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/997/A:
You've got a string $a_1, a_2, \dots, a_n$, consisting of zeros and ones.

Let's call a sequence of consecutive elements $a_i, a_{i + 1}, \ldots, a_j$ ($1\leq i\leq j\leq n$) a substring of string $a$.

You can apply the following operations any number of times:  Choose some substring of string $a$ (for example, you can choose entire string) and reverse it, paying $x$ coins for it (for example, «0101101» $\to$ «0111001»);  Choose some substring of string $a$ (for example, you can choose entire string or just one symbol) and replace each symbol to the opposite one (zeros are replaced by ones, and ones — by zeros), paying $y$ coins for it (for example, «0101101» $\to$ «0110001»).

You can apply these operations in any order. It is allowed to apply the operations multiple times to the same substring.

What is the minimum number of coins you need to spend to get a string consisting only of ones?

-----Input-----

The first line of input contains integers $n$, $x$ and $y$ ($1 \leq n \leq 300\,000, 0 \leq x, y \leq 10^9$) — length of the string, cost of the first operation (substring reverse) and cost of the second operation (inverting all elements of substring).

The second line contains the string $a$ of length $n$, consisting of zeros and ones.

-----Output-----

Print a single integer — the minimum total cost of operations you need to spend to get a string consisting only of ones. Print $0$, if you do not need to perform any operations.

-----Examples-----
Input
5 1 10
01000

Output
11

Input
5 10 1
01000

Output
2

Input
7 2 3
1111111

Output
0

-----Note-----

In the first sample, at first you need to reverse substring $[1 \dots 2]$, and then you need to invert substring $[2 \dots 5]$.

Then the string was changed as follows:

«01000» $\to$ «10000» $\to$ «11111».

The total cost of operations is $1 + 10 = 11$.

In the second sample, at first you need to invert substring $[1 \dots 1]$, and then you need to invert substring $[3 \dots 5]$.

Then the string was changed as follows:

«01000» $\to$ «11000»...

I tried it in Python, but could not do it. Can you solve it?


I found an interesting problem on https://codeforces.com/problemset/problem/997/B:
Let's introduce a number system which is based on a roman digits. There are digits I, V, X, L which correspond to the numbers $1$, $5$, $10$ and $50$ respectively. The use of other roman digits is not allowed.

Numbers in this system are written as a sequence of one or more digits. We define the value of the sequence simply as the sum of digits in it.

For example, the number XXXV evaluates to $35$ and the number IXI — to $12$.

Pay attention to the difference to the traditional roman system — in our system any sequence of digits is valid, moreover the order of digits doesn't matter, for example IX means $11$, not $9$.

One can notice that this system is ambiguous, and some numbers can be written in many different ways. Your goal is to determine how many distinct integers can be represented by exactly $n$ roman digits I, V, X, L.

-----Input-----

The only line of the input file contains a single integer $n$ ($1 \le n \le 10^9$) — the number of roman digits to use.

-----Output-----

Output a single integer — the number of distinct integers which can be represented using $n$ roman digits exactly.

-----Examples-----
Input
1

Output
4

Input
2

Output
10

Input
10

Output
244

-----Note-----

In the first sample there are exactly $4$ integers which can be represented — I, V, X and L.

In the second sample it is possible to represent integers $2$ (II), $6$ (VI), $10$ (VV), $11$ (XI), $15$ (XV), $20$ (XX), $51$ (IL), $55$ (VL), $60$ (XL) and $100$ (LL).

I tried it in Python, but could not do it. Can you solve it?


I found an interesting problem on https://codeforces.com/problemset/problem/998/A:
There are quite a lot of ways to have fun with inflatable balloons. For example, you can fill them with water and see what happens.

Grigory and Andrew have the same opinion. So, once upon a time, they went to the shop and bought $n$ packets with inflatable balloons, where $i$-th of them has exactly $a_i$ balloons inside.

They want to divide the balloons among themselves. In addition, there are several conditions to hold:

  Do not rip the packets (both Grigory and Andrew should get unbroken packets);  Distribute all packets (every packet should be given to someone);  Give both Grigory and Andrew at least one packet;  To provide more fun, the total number of balloons in Grigory's packets should not be equal to the total number of balloons in Andrew's packets.

Help them to divide the balloons or determine that it's impossible under these conditions.

-----Input-----

The first line of input contains a single integer $n$ ($1 \le n \le 10$) — the number of packets with balloons.

The second line contains $n$ integers: $a_1$, $a_2$, $\ldots$, $a_n$ ($1 \le a_i \le 1000$) — the number of balloons inside the corresponding packet.

-----Output-----

If it's impossible to divide the balloons satisfying the conditions above, print $-1$.

Otherwise, print an integer $k$ — the number of packets to give to Grigory followed by $k$ distinct integers from $1$ to $n$ — the indices of those. The order of packets doesn't matter.

If there are multiple ways to divide balloons, output any of them.

-----Examples-----
Input
3
1 2 1

Output
2
1 2

Input
2
5 5

Output
-1

Input
1
10

Output
-1

-----Note-----

In the first test Grigory gets $3$ balloons in total while Andrey gets $1$.

In the second test there's only one way to divide the packets which leads to equal numbers of balloons.

In the third test one of the boys won't get a packet at all.

I tried it in Python, but could not do it. Can you solve it?

def solve():
    n = int(input())
    a = [int(c) for c in input().split(" ")]
    total = sum(a)

    if n < 2: return None
    elif n == 2:
        if a[0] == a[1]: return None
        else: return (0,)
    else:
        for i in range(n):
            if a[i] != total - a[i]:
                return (i,)

result = solve()
if not result:
    print(-1)
else:
    print(len(result))
    for num in result:
        print(num+1, end = " ")


I found an interesting problem on https://codeforces.com/problemset/problem/998/B:
There are a lot of things which could be cut — trees, paper, "the rope". In this problem you are going to cut a sequence of integers.

There is a sequence of integers, which contains the equal number of even and odd numbers. Given a limited budget, you need to make maximum possible number of cuts such that each resulting segment will have the same number of odd and even integers.

Cuts separate a sequence to continuous (contiguous) segments. You may think about each cut as a break between two adjacent elements in a sequence. So after cutting each element belongs to exactly one segment. Say, $[4, 1, 2, 3, 4, 5, 4, 4, 5, 5]$ $\to$ two cuts $\to$ $[4, 1 | 2, 3, 4, 5 | 4, 4, 5, 5]$. On each segment the number of even elements should be equal to the number of odd elements.

The cost of the cut between $x$ and $y$ numbers is $|x - y|$ bitcoins. Find the maximum possible number of cuts that can be made while spending no more than $B$ bitcoins.

-----Input-----

First line of the input contains an integer $n$ ($2 \le n \le 100$) and an integer $B$ ($1 \le B \le 100$) — the number of elements in the sequence and the number of bitcoins you have.

Second line contains $n$ integers: $a_1$, $a_2$, ..., $a_n$ ($1 \le a_i \le 100$) — elements of the sequence, which contains the equal number of even and odd numbers

-----Output-----

Print the maximum possible number of cuts which can be made while spending no more than $B$ bitcoins.

-----Examples-----
Input
6 4
1 2 5 10 15 20

Output
1

Input
4 10
1 3 2 4

Output
0

Input
6 100
1 2 3 4 5 6

Output
2

-----Note-----

In the first sample the optimal answer is to split sequence between $2$ and $5$. Price of this cut is equal to $3$ bitcoins.

In the second sample it is not possible to make even one cut even with unlimited number of bitcoins.

In the third sample the sequence should be cut between $2$ and $3$, and between $4$ and $5$. The total price of the cuts is $1 + 1 = 2$ bitcoins.

I tried it in Python, but could not do it. Can you solve it?

n, m = list(map(int, input().split()))

ls = [int(i) for i in input().split()]

odd_num, even_num = 0, 0

cur_odd = 0
cur_even = 0

ans = []

for i in range(n - 2):
    if ls[i] & 1:
        cur_odd += 1
    else:
        cur_even += 1

    if i >= 1 and cur_odd == cur_even:
        ans.append(abs(ls[i+1] - ls[i]))

ans.sort()

res = 0
for i in ans:
    if m - i >= 0:
        m -= i
        res += 1
    else:
        break

print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/999/A:
Mishka started participating in a programming contest. There are $n$ problems in the contest. Mishka's problem-solving skill is equal to $k$.

Mishka arranges all problems from the contest into a list. Because of his weird principles, Mishka only solves problems from one of the ends of the list. Every time, he chooses which end (left or right) he will solve the next problem from. Thus, each problem Mishka solves is either the leftmost or the rightmost problem in the list.

Mishka cannot solve a problem with difficulty greater than $k$. When Mishka solves the problem, it disappears from the list, so the length of the list decreases by $1$. Mishka stops when he is unable to solve any problem from any end of the list.

How many problems can Mishka solve?

-----Input-----

The first line of input contains two integers $n$ and $k$ ($1 \le n, k \le 100$) — the number of problems in the contest and Mishka's problem-solving skill.

The second line of input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 100$), where $a_i$ is the difficulty of the $i$-th problem. The problems are given in order from the leftmost to the rightmost in the list.

-----Output-----

Print one integer — the maximum number of problems Mishka can solve.

-----Examples-----
Input
8 4
4 2 3 1 5 1 6 4

Output
5

Input
5 2
3 1 2 1 3

Output
0

Input
5 100
12 34 55 43 21

Output
5

-----Note-----

In the first example, Mishka can solve problems in the following order: $[4, 2, 3, 1, 5, 1, 6, 4] \rightarrow [2, 3, 1, 5, 1, 6, 4] \rightarrow [2, 3, 1, 5, 1, 6] \rightarrow [3, 1, 5, 1, 6] \rightarrow [1, 5, 1, 6] \rightarrow [5, 1, 6]$, so the number of solved problems will be equal to $5$.

In the second example, Mishka can't solve any problem because the difficulties of problems from both ends are greater than $k$.

In the third example, Mishka's solving skill is so amazing that he can solve all the problems.

I tried it in Python, but could not do it. Can you solve it?


I found an interesting problem on https://codeforces.com/problemset/problem/999/B:
A string $s$ of length $n$ can be encrypted by the following algorithm:  iterate over all divisors of $n$ in decreasing order (i.e. from $n$ to $1$),  for each divisor $d$, reverse the substring $s[1 \dots d]$ (i.e. the substring which starts at position $1$ and ends at position $d$).

For example, the above algorithm applied to the string $s$="codeforces" leads to the following changes: "codeforces" $\to$ "secrofedoc" $\to$ "orcesfedoc" $\to$ "rocesfedoc" $\to$ "rocesfedoc" (obviously, the last reverse operation doesn't change the string because $d=1$).

You are given the encrypted string $t$. Your task is to decrypt this string, i.e., to find a string $s$ such that the above algorithm results in string $t$. It can be proven that this string $s$ always exists and is unique.

-----Input-----

The first line of input consists of a single integer $n$ ($1 \le n \le 100$) — the length of the string $t$. The second line of input consists of the string $t$. The length of $t$ is $n$, and it consists only of lowercase Latin letters.

-----Output-----

Print a string $s$ such that the above algorithm results in $t$.

-----Examples-----
Input
10
rocesfedoc

Output
codeforces

Input
16
plmaetwoxesisiht

Output
thisisexampletwo

Input
1
z

Output
z

-----Note-----

The first example is described in the problem statement.

I tried it in Python, but could not do it. Can you solve it?

n = int(input())
s = input()
arr = []
for i in range(n):
    arr.append(s[i])
for i in range(1, n + 1):
    if n % i == 0:
        arr = list(reversed(arr[:i])) + arr[i:]
print(*arr, sep='')


I found an interesting problem on https://codeforces.com/problemset/problem/999/C:
You are given a string $s$ consisting of $n$ lowercase Latin letters. Polycarp wants to remove exactly $k$ characters ($k \le 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 there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;  ...  remove the leftmost occurrence of the letter 'z' and stop the algorithm.

This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly $k$ times, thus removing exactly $k$ characters.

Help Polycarp find the resulting string.

-----Input-----

The first line of input contains two integers $n$ and $k$ ($1 \le k \le n \le 4 \cdot 10^5$) — the length of the string and the number of letters Polycarp will remove.

The second line contains the string $s$ consisting of $n$ lowercase Latin letters.

-----Output-----

Print the string that will be obtained from $s$ after Polycarp removes exactly $k$ letters using the above algorithm $k$ times.

If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).

-----Examples-----
Input
15 3
cccaabababaccbc

Output
cccbbabaccbc

Input
15 9
cccaabababaccbc

Output
cccccc

Input
1 1
u

Output

I tried it in Python, but could not do it. Can you solve it?

tn,tk=input().split()
n=int(tn)
k=int(tk)
a=input()
vis=[]
t=[]
for i in range(n):
    t.append((a[i],i))
t.sort()
for i in range(n):
    vis.append(0)
for i in range(k):
    vis[t[i][1]]=1
for i in range(n):
    if vis[i]:continue
    print(a[i],end="")


I found an interesting problem on https://codeforces.com/problemset/problem/999/D:
You are given an array consisting of $n$ integers $a_1, a_2, \dots, a_n$, and a positive integer $m$. It is guaranteed that $m$ is a divisor of $n$.

In a single move, you can choose any position $i$ between $1$ and $n$ and increase $a_i$ by $1$.

Let's calculate $c_r$ ($0 \le r \le m-1)$ — the number of elements having remainder $r$ when divided by $m$. In other words, for each remainder, let's find the number of corresponding elements in $a$ with that remainder.

Your task is to change the array in such a way that $c_0 = c_1 = \dots = c_{m-1} = \frac{n}{m}$.

Find the minimum number of moves to satisfy the above requirement.

-----Input-----

The first line of input contains two integers $n$ and $m$ ($1 \le n \le 2 \cdot 10^5, 1 \le m \le n$). It is guaranteed that $m$ is a divisor of $n$.

The second line of input contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 10^9$), the elements of the array.

-----Output-----

In the first line, print a single integer — the minimum number of moves required to satisfy the following condition: for each remainder from $0$ to $m - 1$, the number of elements of the array having this remainder equals $\frac{n}{m}$.

In the second line, print any array satisfying the condition and can be obtained from the given array with the minimum number of moves. The values of the elements of the resulting array must not exceed $10^{18}$.

-----Examples-----
Input
6 3
3 2 0 6 10 12

Output
3
3 2 0 7 10 14

Input
4 2
0 1 2 3

Output
0
0 1 2 3

I tried it in Python, but could not do it. Can you solve it?

n, m = map(int,input().split())
a = list(map(int,input().split()))
f = [[] for i in range(m)]
l = [0 for i in range(m)]
for i in range(n):
    f[a[i] % m].append(i)
    l[a[i] % m] += 1
k = n // m
j = 0
tot = 0
for i in range(m):
    while l[i] > k:
        while l[j] >= k:
            j = (j + 1) % m
        tot += (j + m - i) % m
        l[j] += 1
        a[f[i][-1]] += (j + m - i) % m
        f[i].pop()
        l[i] -= 1
    if i == j:
        j += 1
print(tot)
for i in a:
    print(i,end=' ')


I found an interesting problem on https://codeforces.com/problemset/problem/999/E:
There are $n$ cities and $m$ roads in Berland. Each road connects a pair of cities. The roads in Berland are one-way.

What is the minimum number of new roads that need to be built to make all the cities reachable from the capital?

New roads will also be one-way.

-----Input-----

The first line of input consists of three integers $n$, $m$ and $s$ ($1 \le n \le 5000, 0 \le m \le 5000, 1 \le s \le n$) — the number of cities, the number of roads and the index of the capital. Cities are indexed from $1$ to $n$.

The following $m$ lines contain roads: road $i$ is given as a pair of cities $u_i$, $v_i$ ($1 \le u_i, v_i \le n$, $u_i \ne v_i$). For each pair of cities $(u, v)$, there can be at most one road from $u$ to $v$. Roads in opposite directions between a pair of cities are allowed (i.e. from $u$ to $v$ and from $v$ to $u$).

-----Output-----

Print one integer — the minimum number of extra roads needed to make all the cities reachable from city $s$. If all the cities are already reachable from $s$, print 0.

-----Examples-----
Input
9 9 1
1 2
1 3
2 3
1 5
5 6
6 1
1 8
9 8
7 1

Output
3

Input
5 4 5
1 2
2 3
3 4
4 1

Output
1

-----Note-----

The first example is illustrated by the following: [Image]

For example, you can add roads ($6, 4$), ($7, 9$), ($1, 7$) to make all the cities reachable from $s = 1$.

The second example is illustrated by the following: [Image]

In this example, you can add any one of the roads ($5, 1$), ($5, 2$), ($5, 3$), ($5, 4$) to make all the cities reachable from $s = 5$.

I tried it in Python, but could not do it. Can you solve it?

import sys

N = 5000 + 5
adj = [[] for i in range(N)]
mark = [0 for i in range(N)]
topo = []
sys.setrecursionlimit(6000)
#fin = open("999E.inp", "r")
#fou = open("999E.out", "w")
#n, m, s = map(int, fin.readline().split())
n, m, s = list(map(int, input().split()))
for i in range(m):
	#u, v = map(int, fin.readline().split())
	u, v = list(map(int, input().split()))
	adj[u].append(v)

def topoSort(u):
	mark[u] = 1
	for j in range(len(adj[u])):
		v = adj[u][j]
		if (mark[v] == 0): topoSort(v)
	topo.append(u)

def dfs(u):
	mark[u] = 1
	for j in range(len(adj[u])):
		v = adj[u][j]
		if (mark[v] == 0): dfs(v)

for i in range(1, n+1):
	if (mark[i] == 0):
		topoSort(i)
topo.reverse()
for i in range(1, n+1):
	mark[i] = 0
dfs(s)
res = 0
for i in range(n):
	v = topo[i]
	if (mark[v] == 0):
		res += 1
		dfs(v)
#fou.write(str(res))
print(res)