I found an interesting problem on https://codeforces.com/problemset/problem/1207/C:
You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment $[0, n]$ on $OX$ axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval $(x, x + 1)$ with integer $x$. So we can represent the road as a binary string consisting of $n$ characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.

Usually, we can install the pipeline along the road on height of $1$ unit with supporting pillars in each integer point (so, if we are responsible for $[0, n]$ road, we must install $n + 1$ pillars). But on crossroads we should lift the pipeline up to the height $2$, so the pipeline won't obstruct the way for cars.

We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment $[x, x + 1]$ with integer $x$ consisting of three parts: $0.5$ units of horizontal pipe + $1$ unit of vertical pipe + $0.5$ of horizontal. Note that if pipeline is currently on height $2$, the pillars that support it should also have length equal to $2$ units.

 [Image]

Each unit of gas pipeline costs us $a$ bourles, and each unit of pillar — $b$ bourles. So, it's not always optimal to make the whole pipeline on the height $2$. Find the shape of the pipeline with minimum possible cost and calculate that cost.

Note that you must start and finish the pipeline on height $1$ and, also, it's guaranteed that the first and last characters of the input string are equal to 0.

-----Input-----

The fist line contains one integer $T$ ($1 \le T \le 100$) — the number of queries. Next $2 \cdot T$ lines contain independent queries — one query per two lines.

The first line contains three integers $n$, $a$, $b$ ($2 \le n \le 2 \cdot 10^5$, $1 \le a \le 10^8$, $1 \le b \le 10^8$) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively.

The second line contains binary string $s$ ($|s| = n$, $s_i \in...

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

import sys

def solve(A, n, a, b):
    cost = n*a + (n+1)*b
    num_ones = 0
    groups_ones = 0
    groups_zeros = [0]
    on_zeros = True
    for i in A:
        if i == 0:
            if on_zeros:
                groups_zeros[-1] += 1
            else:
                on_zeros = True
                groups_zeros.append(1)
        else:
            if on_zeros:
                on_zeros = False
                groups_ones += 1
            num_ones += 1
    cost += (groups_ones+num_ones)*b
    for i in range(1, len(groups_zeros)-1):
        z = groups_zeros[i]
        cost += min(2*a, (z-1)*b)
    if num_ones >0 :
        cost += 2*a
    return cost

in_file = sys.stdin#open("C.txt", "r")

t = int(in_file.readline().strip())
for _ in range(t):
    n, a, b = map(int, in_file.readline().strip().split())
    A = list(map(int, in_file.readline().strip()))
    sys.stdout.write(str(solve(A, n, a, b)) + "\n")
sys.stdout.flush()


I found an interesting problem on https://codeforces.com/problemset/problem/1207/D:
You are given a sequence of $n$ pairs of integers: $(a_1, b_1), (a_2, b_2), \dots , (a_n, b_n)$. This sequence is called bad if it is sorted in non-descending order by first elements or if it is sorted in non-descending order by second elements. Otherwise the sequence is good. There are examples of good and bad sequences:  $s = [(1, 2), (3, 2), (3, 1)]$ is bad because the sequence of first elements is sorted: $[1, 3, 3]$;  $s = [(1, 2), (3, 2), (1, 2)]$ is bad because the sequence of second elements is sorted: $[2, 2, 2]$;  $s = [(1, 1), (2, 2), (3, 3)]$ is bad because both sequences (the sequence of first elements and the sequence of second elements) are sorted;  $s = [(1, 3), (3, 3), (2, 2)]$ is good because neither the sequence of first elements $([1, 3, 2])$ nor the sequence of second elements $([3, 3, 2])$ is sorted.

Calculate the number of permutations of size $n$ such that after applying this permutation to the sequence $s$ it turns into a good sequence.

A permutation $p$ of size $n$ is a sequence $p_1, p_2, \dots , p_n$ consisting of $n$ distinct integers from $1$ to $n$ ($1 \le p_i \le n$). If you apply permutation $p_1, p_2, \dots , p_n$ to the sequence $s_1, s_2, \dots , s_n$ you get the sequence $s_{p_1}, s_{p_2}, \dots , s_{p_n}$. For example, if $s = [(1, 2), (1, 3), (2, 3)]$ and $p = [2, 3, 1]$ then $s$ turns into $[(1, 3), (2, 3), (1, 2)]$.

-----Input-----

The first line contains one integer $n$ ($1 \le n \le 3 \cdot 10^5$).

The next $n$ lines contains description of sequence $s$. The $i$-th line contains two integers $a_i$ and $b_i$ ($1 \le a_i, b_i \le n$) — the first and second elements of $i$-th pair in the sequence.

The sequence $s$ may contain equal elements.

-----Output-----

Print the number of permutations of size $n$ such that after applying this permutation to the sequence $s$ it turns into a good sequence. Print the answer modulo $998244353$ (a prime number).

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

Output
3

Input
4
2 3
2 2
2 1
2 4

Output
0

Input
3
1 1
1 1
2...

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

import sys
import itertools
input = sys.stdin.readline

def main():
    n = int(input())
    s = []
    A = []
    B = []
    for _ in range(n):
        a, b = list(map(int, input().split()))
        s.append([a, b])
        A.append(a)
        B.append(b)

    A.sort()
    B.sort()
    s.sort()
    ansA = 1
    ansB = 1
    anss = 1
    for key, val in itertools.groupby(A):
        f = len(list(val))
        for i in range(1, f+1):
            ansA *= i
            ansA %= 998244353

    for key, val in itertools.groupby(B):
        f = len(list(val))
        for i in range(1, f+1):
            ansB *= i
            ansB %= 998244353

    for key, val in itertools.groupby(s):
        f = len(list(val))
        for i in range(1, f+1):
            anss *= i
            anss %= 998244353

    flag = 1
    for i in range(n-1):
        if s[i+1][1] < s[i][1] or s[i+1][0] < s[i][0]:
            flag = 0
            break
    if flag == 0:
        anss = 0

    ansn = 1
    for i in range(1, n+1):
        ansn *= i
        ansn %= 998244353

    print((ansn-ansA-ansB+anss)%998244353)

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1207/F:
You are given an array $a$ consisting of $500000$ integers (numbered from $1$ to $500000$). Initially all elements of $a$ are zero.

You have to process two types of queries to this array:  $1$ $x$ $y$ — increase $a_x$ by $y$;  $2$ $x$ $y$ — compute $\sum\limits_{i \in R(x, y)} a_i$, where $R(x, y)$ is the set of all integers from $1$ to $500000$ which have remainder $y$ modulo $x$.

Can you process all the queries?

-----Input-----

The first line contains one integer $q$ ($1 \le q \le 500000$) — the number of queries.

Then $q$ lines follow, each describing a query. The $i$-th line contains three integers $t_i$, $x_i$ and $y_i$ ($1 \le t_i \le 2$). If $t_i = 1$, then it is a query of the first type, $1 \le x_i \le 500000$, and $-1000 \le y_i \le 1000$. If $t_i = 2$, then it it a query of the second type, $1 \le x_i \le 500000$, and $0 \le y_i < x_i$.

It is guaranteed that there will be at least one query of type $2$.

-----Output-----

For each query of type $2$ print one integer — the answer to it.

-----Example-----
Input
5
1 3 4
2 3 0
2 4 3
1 4 -4
2 1 0

Output
4
4
0

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

import sys
n = 500001
sqrt = int(0.75 * n**0.5)

data = [0]*(n)
ans = [[]]
# out = []
for i in range(1, sqrt):
    ans.append([0]*i)
j = int(sys.stdin.readline())
qus = sys.stdin.readlines()
for qu in qus:
    q = [int(i) for i in qu.split()]
    if q[0] == 1:
        x = q[1]
        y = q[2]
        data[x] += y
        for i in range(1, sqrt):
            ans[i][x%i] += y
    else:
        if q[1] < sqrt:
            sys.stdout.write(str(ans[q[1]][q[2]]))

        else:
            sm = 0
            for i in range(q[2], n, q[1]):
                sm += data[i]
            sys.stdout.write(str(sm))
            # out.append(str(sm))

            #out.append(str(sum([data[i] for i in range(q[2], n, q[1])])))
        sys.stdout.write("\n")

# sys.stdout.write('\n'.join(out) + '\n')


I found an interesting problem on https://codeforces.com/problemset/problem/1208/B:
You are given an array $a_{1}, a_{2}, \ldots, a_{n}$. You can remove at most one subsegment from it. The remaining elements should be pairwise distinct.

In other words, at most one time you can choose two integers $l$ and $r$ ($1 \leq l \leq r \leq n$) and delete integers $a_l, a_{l+1}, \ldots, a_r$ from the array. Remaining elements should be pairwise distinct.

Find the minimum size of the subsegment you need to remove to make all remaining elements distinct.

-----Input-----

The first line of the input contains a single integer $n$ ($1 \le n \le 2000$) — the number of elements in the given array.

The next line contains $n$ spaced integers $a_{1}, a_{2}, \ldots, a_{n}$ ($1 \le a_{i} \le 10^{9}$) — the elements of the array.

-----Output-----

Print a single integer — the minimum size of the subsegment you need to remove to make all elements of the array pairwise distinct. If no subsegment needs to be removed, print $0$.

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

Output
0

Input
4
1 1 2 2

Output
2

Input
5
1 4 1 4 9

Output
2

-----Note-----

In the first example all the elements are already distinct, therefore no subsegment needs to be removed.

In the second example you can remove the subsegment from index $2$ to $3$.

In the third example you can remove the subsegments from index $1$ to $2$, or from index $2$ to $3$, or from index $3$ to $4$.

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

import sys
input = lambda: sys.stdin.readline().strip()

n = int(input())
ls = list(map(int, input().split()))
d = [{}]
works = {}
for i in range(n):
    works[i] = True
for i in range(n):
    d.append(dict(d[-1]))
    try: d[-1][ls[i]]+=1; works[i] = False
    except: d[-1][ls[i]] = 1
m = n
for l in range(n):
    for r in range(n-1, l-1, -1):
        try:
            d[l][ls[r]]+=0
            break
        except:
            d[l][ls[r]] = 1
            pass
    if works[l]:
        m = min(m, r-l+1)
    else:
        m = min(m, r-l+1)
        break
if len(set(ls))==n: print(0)
else: print(m)


I found an interesting problem on https://codeforces.com/problemset/problem/1209/A:
You are given a sequence of integers $a_1, a_2, \dots, a_n$. You need to paint elements in colors, so that:   If we consider any color, all elements of this color must be divisible by the minimal element of this color.  The number of used colors must be minimized.

For example, it's fine to paint elements $[40, 10, 60]$ in a single color, because they are all divisible by $10$. You can use any color an arbitrary amount of times (in particular, it is allowed to use a color only once). The elements painted in one color do not need to be consecutive.

For example, if $a=[6, 2, 3, 4, 12]$ then two colors are required: let's paint $6$, $3$ and $12$ in the first color ($6$, $3$ and $12$ are divisible by $3$) and paint $2$ and $4$ in the second color ($2$ and $4$ are divisible by $2$). For example, if $a=[10, 7, 15]$ then $3$ colors are required (we can simply paint each element in an unique color).

-----Input-----

The first line contains an integer $n$ ($1 \le n \le 100$), where $n$ is the length of the given sequence.

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 100$). These numbers can contain duplicates.

-----Output-----

Print the minimal number of colors to paint all the given numbers in a valid way.

-----Examples-----
Input
6
10 2 3 5 4 2

Output
3

Input
4
100 100 100 100

Output
1

Input
8
7 6 5 4 3 2 2 3

Output
4

-----Note-----

In the first example, one possible way to paint the elements in $3$ colors is:

  paint in the first color the elements: $a_1=10$ and $a_4=5$,  paint in the second color the element $a_3=3$,  paint in the third color the elements: $a_2=2$, $a_5=4$ and $a_6=2$.

In the second example, you can use one color to paint all the elements.

In the third example, one possible way to paint the elements in $4$ colors is:

  paint in the first color the elements: $a_4=4$, $a_6=2$ and $a_7=2$,  paint in the second color the elements: $a_2=6$, $a_5=3$ and $a_8=3$,  paint in the third color the element $a_3=5$,  paint in the fourth color the element $a_1=7$.

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

n = int(input())
a = sorted(list(map(int, input().split())))
s = []
for q in a:
    for q1 in s:
        if q % q1 == 0:
            break
    else:
        s.append(q)
print(len(s))


I found an interesting problem on https://codeforces.com/problemset/problem/1209/B:
It is a holiday season, and Koala is decorating his house with cool lights! He owns $n$ lights, all of which flash periodically.

After taking a quick glance at them, Koala realizes that each of his lights can be described with two parameters $a_i$ and $b_i$. Light with parameters $a_i$ and $b_i$ will toggle (on to off, or off to on) every $a_i$ seconds starting from the $b_i$-th second. In other words, it will toggle at the moments $b_i$, $b_i + a_i$, $b_i + 2 \cdot a_i$ and so on.

You know for each light whether it's initially on or off and its corresponding parameters $a_i$ and $b_i$. Koala is wondering what is the maximum number of lights that will ever be on at the same time. So you need to find that out.

 [Image] Here is a graphic for the first example.

-----Input-----

The first line contains a single integer $n$ ($1 \le n \le 100$), the number of lights.

The next line contains a string $s$ of $n$ characters. The $i$-th character is "1", if the $i$-th lamp is initially on. Otherwise, $i$-th character is "0".

The $i$-th of the following $n$ lines contains two integers $a_i$ and $b_i$ ($1 \le a_i, b_i \le 5$)  — the parameters of the $i$-th light.

-----Output-----

Print a single integer — the maximum number of lights that will ever be on at the same time.

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

Output
2

Input
4
1111
3 4
5 2
3 1
3 2

Output
4

Input
6
011100
5 3
5 5
2 4
3 5
4 2
1 5

Output
6

-----Note-----

For first example, the lamps' states are shown in the picture above. The largest number of simultaneously on lamps is $2$ (e.g. at the moment $2$).

In the second example, all lights are initially on. So the answer is $4$.

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

n = int(input())
state = [int(e == '1') for e in input()]
l = [[*map(int, input().split())] for _ in range(n)]
res = sum(state)
for t in range(1, 1000):
    for i in range(n):
        if t >= l[i][1] and (t - l[i][1]) % l[i][0] == 0:
            state[i] ^= 1
    res = max(res, sum(state))
print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/1210/A:
Anadi has a set of dominoes. Every domino has two parts, and each part contains some dots. For every $a$ and $b$ such that $1 \leq a \leq b \leq 6$, there is exactly one domino with $a$ dots on one half and $b$ dots on the other half. The set contains exactly $21$ dominoes. Here is an exact illustration of his set:

 [Image]

Also, Anadi has an undirected graph without self-loops and multiple edges. He wants to choose some dominoes and place them on the edges of this graph. He can use at most one domino of each type. Each edge can fit at most one domino. It's not necessary to place a domino on each edge of the graph.

When placing a domino on an edge, he also chooses its direction. In other words, one half of any placed domino must be directed toward one of the endpoints of the edge and the other half must be directed toward the other endpoint. There's a catch: if there are multiple halves of dominoes directed toward the same vertex, each of these halves must contain the same number of dots.

How many dominoes at most can Anadi place on the edges of his graph?

-----Input-----

The first line contains two integers $n$ and $m$ ($1 \leq n \leq 7$, $0 \leq m \leq \frac{n\cdot(n-1)}{2}$) — the number of vertices and the number of edges in the graph.

The next $m$ lines contain two integers each. Integers in the $i$-th line are $a_i$ and $b_i$ ($1 \leq a, b \leq n$, $a \neq b$) and denote that there is an edge which connects vertices $a_i$ and $b_i$.

The graph might be disconnected. It's however guaranteed that the graph doesn't contain any self-loops, and that there is at most one edge between any pair of vertices.

-----Output-----

Output one integer which denotes the maximum number of dominoes which Anadi can place on the edges of the graph.

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

Output
4

Input
7 0

Output
0

Input
3 1
1 3

Output
1

Input
7 21
1 2
1 3
1 4
1 5
1 6
1 7
2 3
2 4
2 5
2 6
2 7
3 4
3 5
3 6
3 7
4 5
4 6
4 7
5 6
5 7
6 7

Output
16

-----Note-----

Here is an illustration of Anadi's graph...

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

n,m = [int(j) for j in input().split()]
adj = [set() for i in range(n)]
for i in range(m):
	l, r = [int(j)-1 for j in input().split()]
	adj[l].add(r)
	adj[r].add(l)
if n<7:
	print(m)
else:
	maxi = 10**12
	for i in range(n):
		for j in range(i+1, n):
			l = adj[i].intersection(adj[j])
			tmp = len(l)
			if tmp<maxi:
				maxi = tmp
	print(m-maxi)


I found an interesting problem on https://codeforces.com/problemset/problem/1210/B:
Marcin is a coach in his university. There are $n$ students who want to attend a training camp. Marcin is a smart coach, so he wants to send only the students that can work calmly with each other.

Let's focus on the students. They are indexed with integers from $1$ to $n$. Each of them can be described with two integers $a_i$ and $b_i$; $b_i$ is equal to the skill level of the $i$-th student (the higher, the better). Also, there are $60$ known algorithms, which are numbered with integers from $0$ to $59$. If the $i$-th student knows the $j$-th algorithm, then the $j$-th bit ($2^j$) is set in the binary representation of $a_i$. Otherwise, this bit is not set.

Student $x$ thinks that he is better than student $y$ if and only if $x$ knows some algorithm which $y$ doesn't know. Note that two students can think that they are better than each other. A group of students can work together calmly if no student in this group thinks that he is better than everyone else in this group.

Marcin wants to send a group of at least two students which will work together calmly and will have the maximum possible sum of the skill levels. What is this sum?

-----Input-----

The first line contains one integer $n$ ($1 \leq n \leq 7000$) — the number of students interested in the camp.

The second line contains $n$ integers. The $i$-th of them is $a_i$ ($0 \leq a_i < 2^{60}$).

The third line contains $n$ integers. The $i$-th of them is $b_i$ ($1 \leq b_i \leq 10^9$).

-----Output-----

Output one integer which denotes the maximum sum of $b_i$ over the students in a group of students which can work together calmly. If no group of at least two students can work together calmly, print 0.

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

Output
15

Input
3
1 2 3
1 2 3

Output
0

Input
1
0
1

Output
0

-----Note-----

In the first sample test, it's optimal to send the first, the second and the third student to the camp. It's also possible to send only the first and the third student, but they'd have a lower sum of $b_i$.

In the...

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

from collections import defaultdict
N = int(input())
if(N == 1):
    print(0)
    return
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
Dict = defaultdict(int)
Sum = defaultdict(int)
for i in range(N):
    Dict[a[i]] += 1
    Sum[a[i]] += b[i]
ans = 0
val = 0
Group = []
for i in Dict.keys():
    if(Dict[i]>1):
        Group.append(i)
        ans += Sum[i]
        val |= i
for i in range(N):
    if(Dict[a[i]] == 1):
        for k in Group:
            if(a[i] | k <= k):
                ans += Sum[a[i]]
                break
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1210/C:
Kamil likes streaming the competitive programming videos. His MeTube channel has recently reached $100$ million subscribers. In order to celebrate this, he posted a video with an interesting problem he couldn't solve yet. Can you help him?

You're given a tree — a connected undirected graph consisting of $n$ vertices connected by $n - 1$ edges. The tree is rooted at vertex $1$. A vertex $u$ is called an ancestor of $v$ if it lies on the shortest path between the root and $v$. In particular, a vertex is an ancestor of itself.

Each vertex $v$ is assigned its beauty $x_v$ — a non-negative integer not larger than $10^{12}$. This allows us to define the beauty of a path. Let $u$ be an ancestor of $v$. Then we define the beauty $f(u, v)$ as the greatest common divisor of the beauties of all vertices on the shortest path between $u$ and $v$. Formally, if $u=t_1, t_2, t_3, \dots, t_k=v$ are the vertices on the shortest path between $u$ and $v$, then $f(u, v) = \gcd(x_{t_1}, x_{t_2}, \dots, x_{t_k})$. Here, $\gcd$ denotes the greatest common divisor of a set of numbers. In particular, $f(u, u) = \gcd(x_u) = x_u$.

Your task is to find the sum

$$ \sum_{u\text{ is an ancestor of }v} f(u, v). $$

As the result might be too large, please output it modulo $10^9 + 7$.

Note that for each $y$, $\gcd(0, y) = \gcd(y, 0) = y$. In particular, $\gcd(0, 0) = 0$.

-----Input-----

The first line contains a single integer $n$ ($2 \le n \le 100\,000$) — the number of vertices in the tree.

The following line contains $n$ integers $x_1, x_2, \dots, x_n$ ($0 \le x_i \le 10^{12}$). The value $x_v$ denotes the beauty of vertex $v$.

The following $n - 1$ lines describe the edges of the tree. Each of them contains two integers $a, b$ ($1 \le a, b \le n$, $a \neq b$) — the vertices connected by a single edge.

-----Output-----

Output the sum of the beauties on all paths $(u, v)$ such that $u$ is ancestor of $v$. This sum should be printed modulo $10^9 + 7$.

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

Output
42

Input
7
0 2...

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

n = int(input())
beauty = list(map(int, input().strip().split()))
tree = [[] for i in range(n)]
mod = 1000000007
used = [False for i in range(n)]
def gcd(a,b):
    mn = min(a,b)
    mx = max(a,b)
    if mn == 0:
        return mx
    md = mx%mn
    if md == 0:
        return mn
    else:
        return gcd(mn, md)
for i in range(n-1):
    a,b = map(int, input().strip().split())
    tree[a-1].append(b-1)
    tree[b-1].append(a-1)
segment_vals = [{} for i in range(n)]
ans = beauty[0]
segment_vals[0][beauty[0]] = 1
cur_nodes = [0]
used[0] = True
while 1:
    new_nodes = []
    for node in cur_nodes:
        for potential_new in tree[node]:
            if used[potential_new] == False:
                used[potential_new] = True
                new_nodes.append(potential_new)
                new_beauty = beauty[potential_new]
                segment_vals[potential_new][new_beauty] = 1
                for g in segment_vals[node].keys():
                    segment_gcd = gcd(new_beauty,g)
                    segment_vals[potential_new][segment_gcd] = segment_vals[potential_new].get(segment_gcd,0) + segment_vals[node][g]
                for k in segment_vals[potential_new].keys():
                    ans += k*segment_vals[potential_new][k]
                    ans = ans % mod
    if len(new_nodes) == 0:
        break
    else:
        cur_nodes = new_nodes
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1213/A:
You are given $n$ chips on a number line. The $i$-th chip is placed at the integer coordinate $x_i$. Some chips can have equal coordinates.

You can perform each of the two following types of moves any (possibly, zero) number of times on any chip:

  Move the chip $i$ by $2$ to the left or $2$ to the right for free (i.e. replace the current coordinate $x_i$ with $x_i - 2$ or with $x_i + 2$);  move the chip $i$ by $1$ to the left or $1$ to the right and pay one coin for this move (i.e. replace the current coordinate $x_i$ with $x_i - 1$ or with $x_i + 1$).

Note that it's allowed to move chips to any integer coordinate, including negative and zero.

Your task is to find the minimum total number of coins required to move all $n$ chips to the same coordinate (i.e. all $x_i$ should be equal after some sequence of moves).

-----Input-----

The first line of the input contains one integer $n$ ($1 \le n \le 100$) — the number of chips.

The second line of the input contains $n$ integers $x_1, x_2, \dots, x_n$ ($1 \le x_i \le 10^9$), where $x_i$ is the coordinate of the $i$-th chip.

-----Output-----

Print one integer — the minimum total number of coins required to move all $n$ chips to the same coordinate.

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

Output
1

Input
5
2 2 2 3 3

Output
2

-----Note-----

In the first example you need to move the first chip by $2$ to the right and the second chip by $1$ to the right or move the third chip by $2$ to the left and the second chip by $1$ to the left so the answer is $1$.

In the second example you need to move two chips with coordinate $3$ by $1$ to the left so the answer is $2$.

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

# cook your dish here
n=int(input())
it=list(map(int,input().split()))
a=len([i for i in it if i%2==0])
b=n-a
if a>=b:
    print(b)
else:
    print(a)


I found an interesting problem on https://codeforces.com/problemset/problem/1213/D1:
The only difference between easy and hard versions is the number of elements in the array.

You are given an array $a$ consisting of $n$ integers. In one move you can choose any $a_i$ and divide it by $2$ rounding down (in other words, in one move you can set $a_i := \lfloor\frac{a_i}{2}\rfloor$).

You can perform such an operation any (possibly, zero) number of times with any $a_i$.

Your task is to calculate the minimum possible number of operations required to obtain at least $k$ equal numbers in the array.

Don't forget that it is possible to have $a_i = 0$ after some operations, thus the answer always exists.

-----Input-----

The first line of the input contains two integers $n$ and $k$ ($1 \le k \le n \le 50$) — the number of elements in the array and the number of equal numbers required.

The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 2 \cdot 10^5$), where $a_i$ is the $i$-th element of $a$.

-----Output-----

Print one integer — the minimum possible number of operations required to obtain at least $k$ equal numbers in the array.

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

Output
1

Input
5 3
1 2 3 4 5

Output
2

Input
5 3
1 2 3 3 3

Output
0

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

import collections
n,k=list(map(int,input().split()))
A=[int(i) for i in input().split()]
ans=float("inf")
D1,D2=collections.defaultdict(list),collections.defaultdict(int)
for i in range(n):
  a=A[i]
  c=0
  D1[a].append(c)
  D2[a]+=1
  while a>0:
    a//=2
    c+=1
    D1[a].append(c)
    D2[a]+=1
for i in range(max(A)+1):
  if D2[i]>=k:
    D1[i].sort()
    ans=min(ans,sum(D1[i][:k]))
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1213/D2:
The only difference between easy and hard versions is the number of elements in the array.

You are given an array $a$ consisting of $n$ integers. In one move you can choose any $a_i$ and divide it by $2$ rounding down (in other words, in one move you can set $a_i := \lfloor\frac{a_i}{2}\rfloor$).

You can perform such an operation any (possibly, zero) number of times with any $a_i$.

Your task is to calculate the minimum possible number of operations required to obtain at least $k$ equal numbers in the array.

Don't forget that it is possible to have $a_i = 0$ after some operations, thus the answer always exists.

-----Input-----

The first line of the input contains two integers $n$ and $k$ ($1 \le k \le n \le 2 \cdot 10^5$) — the number of elements in the array and the number of equal numbers required.

The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 2 \cdot 10^5$), where $a_i$ is the $i$-th element of $a$.

-----Output-----

Print one integer — the minimum possible number of operations required to obtain at least $k$ equal numbers in the array.

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

Output
1

Input
5 3
1 2 3 4 5

Output
2

Input
5 3
1 2 3 3 3

Output
0

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

n, k = [int(x) for x in input().split()]
nums = sorted([int(x) for x in input().split()])
count = [0 for _ in range(2 * 100000 + 10)]
ops = [0 for _ in range(2 * 100000 + 10)]
for num in nums:
    op = 0
    while (num > 0):
        ops[num] += op if count[num] < k else 0
        count[num] += 1
        num = num // 2
        op += 1
    ops[num] += op if count[num] < k else 0
    count[num] += 1

minn = 0
minop = ops[0]
for i in range(2 * 100000 + 1):
    if (count[i] >= k and ops[i] < minop):
        minn = i
        minop = ops[i]

print(minop)


I found an interesting problem on https://codeforces.com/problemset/problem/1213/E:
You are given two strings $s$ and $t$ both of length $2$ and both consisting only of characters 'a', 'b' and 'c'.

Possible examples of strings $s$ and $t$: "ab", "ca", "bb".

You have to find a string $res$ consisting of $3n$ characters, $n$ characters should be 'a', $n$ characters should be 'b' and $n$ characters should be 'c' and $s$ and $t$ should not occur in $res$ as substrings.

A substring of a string is a contiguous subsequence of that string. So, the strings "ab", "ac" and "cc" are substrings of the string "abacc", but the strings "bc", "aa" and "cb" are not substrings of the string "abacc".

If there are multiple answers, you can print any of them.

-----Input-----

The first line of the input contains one integer $n$ ($1 \le n \le 10^5$) — the number of characters 'a', 'b' and 'c' in the resulting string.

The second line of the input contains one string $s$ of length $2$ consisting of characters 'a', 'b' and 'c'.

The third line of the input contains one string $t$ of length $2$ consisting of characters 'a', 'b' and 'c'.

-----Output-----

If it is impossible to find the suitable string, print "NO" on the first line.

Otherwise print "YES" on the first line and string $res$ on the second line. $res$ should consist of $3n$ characters, $n$ characters should be 'a', $n$ characters should be 'b' and $n$ characters should be 'c' and $s$ and $t$ should not occur in $res$ as substrings.

If there are multiple answers, you can print any of them.

-----Examples-----
Input
2
ab
bc

Output
YES
acbbac

Input
3
aa
bc

Output
YES
cacbacbab

Input
1
cb
ac

Output
YES
abc

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

n = int(input())
s = input()
t = input()
#n = 1
#s2 = ["aa", "ab", "ac", "ba", "bb", "bc", "ca", "cb", "cc"]
us = ["abc", "acb", "bac", "bca", "cab", "cba"]
flag = 0
for u in us:
    if (s in u or t in u):
        continue
    if (n > 1 and (s in (u[2] + u[0]) or t in (u[2] + u[0]))):
        continue
    flag = 1
    print("YES")
    print(u * n)
    return

if (not flag):
    for u in us:
        if (s in u or t in u):
            continue
        print("YES")
        print(u[0] * n + u[1] * n + u[2] * n)
        return


I found an interesting problem on https://codeforces.com/problemset/problem/1213/F:
Authors have come up with the string $s$ consisting of $n$ lowercase Latin letters.

You are given two permutations of its indices (not necessary equal) $p$ and $q$ (both of length $n$). Recall that the permutation is the array of length $n$ which contains each integer from $1$ to $n$ exactly once.

For all $i$ from $1$ to $n-1$ the following properties hold: $s[p_i] \le s[p_{i + 1}]$ and $s[q_i] \le s[q_{i + 1}]$. It means that if you will write down all characters of $s$ in order of permutation indices, the resulting string will be sorted in the non-decreasing order.

Your task is to restore any such string $s$ of length $n$ consisting of at least $k$ distinct lowercase Latin letters which suits the given permutations.

If there are multiple answers, you can print any of them.

-----Input-----

The first line of the input contains two integers $n$ and $k$ ($1 \le n \le 2 \cdot 10^5, 1 \le k \le 26$) — the length of the string and the number of distinct characters required.

The second line of the input contains $n$ integers $p_1, p_2, \dots, p_n$ ($1 \le p_i \le n$, all $p_i$ are distinct integers from $1$ to $n$) — the permutation $p$.

The third line of the input contains $n$ integers $q_1, q_2, \dots, q_n$ ($1 \le q_i \le n$, all $q_i$ are distinct integers from $1$ to $n$) — the permutation $q$.

-----Output-----

If it is impossible to find the suitable string, print "NO" on the first line.

Otherwise print "YES" on the first line and string $s$ on the second line. It should consist of $n$ lowercase Latin letters, contain at least $k$ distinct characters and suit the given permutations.

If there are multiple answers, you can print any of them.

-----Example-----
Input
3 2
1 2 3
1 3 2

Output
YES
abb

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

from heapq import *

def solve(a, b):

    b_map = {i: idx for idx, i in enumerate(a)}

    intervals = []

    for idx, i in enumerate(b):
        f = b_map[i]
        intervals.append(sorted([f, idx]))

    intervals.sort(reverse=True)
    res = []
    endings = []
    for i in range(len(a)):
        while endings and endings[0] < i:
            heappop(endings)

        if not res:
            res.append(97)
        elif not endings:
            res.append(res[-1] + 1)
        else:
            res.append(res[-1])

        while intervals and intervals[-1][0] <= i:
            s, e = intervals.pop()
            heappush(endings, e)

    def build(k, r):
        res = [0] * len(k)

        for idx, i in enumerate(k):

            res[i - 1] = r[idx]

        return res
    # print(res)
    return build(a, res)

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

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

b = solve(a, b)
string = ''.join(chr(min(i, 97 + 25)) for i in b)
if len(set(string)) < k: print("NO")
else:
    print("YES")
    print(string)


I found an interesting problem on https://codeforces.com/problemset/problem/1213/G:
You are given a weighted tree consisting of $n$ vertices. Recall that a tree is a connected graph without cycles. Vertices $u_i$ and $v_i$ are connected by an edge with weight $w_i$.

You are given $m$ queries. The $i$-th query is given as an integer $q_i$. In this query you need to calculate the number of pairs of vertices $(u, v)$ ($u < v$) such that the maximum weight of an edge on a simple path between $u$ and $v$ doesn't exceed $q_i$.

-----Input-----

The first line of the input contains two integers $n$ and $m$ ($1 \le n, m \le 2 \cdot 10^5$) — the number of vertices in the tree and the number of queries.

Each of the next $n - 1$ lines describes an edge of the tree. Edge $i$ is denoted by three integers $u_i$, $v_i$ and $w_i$ — the labels of vertices it connects ($1 \le u_i, v_i \le n$, $u_i \ne v_i$) and the weight of the edge ($1 \le w_i \le 2 \cdot 10^5$). It is guaranteed that the given edges form a tree.

The last line of the input contains $m$ integers $q_1, q_2, \dots, q_m$ ($1 \le q_i \le 2 \cdot 10^5$), where $q_i$ is the maximum weight of an edge in the $i$-th query.

-----Output-----

Print $m$ integers — the answers to the queries. The $i$-th value should be equal to the number of pairs of vertices $(u, v)$ ($u < v$) such that the maximum weight of an edge on a simple path between $u$ and $v$ doesn't exceed $q_i$.

Queries are numbered from $1$ to $m$ in the order of the input.

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

Output
21 7 15 21 3

Input
1 2
1 2

Output
0 0

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

Output
1 3 3

-----Note-----

The picture shows the tree from the first example: [Image]

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

from collections import defaultdict
import sys
sys.setrecursionlimit(10**6)

readline = sys.stdin.readline
N, M = map(int, readline().split())
E = []
for i in range(N-1):
    u, v, w = map(int, readline().split())
    E.append((w, u-1, v-1))
E.sort()
Q = set()
MP = defaultdict(list)
for i, q in enumerate(map(int, readline().split())):
    MP[q].append(i)
    Q.add(q)
Q = list(Q)
Q.sort()

def fact(N):
    return N*fact(N-1) % 100 if N > 1 else 1
fact(2800)

def root(x):
    if x == p[x]:
        return x
    y = x
    while y != p[y]:
        y = p[y]
    while x != y:
        p[x], x = y, p[x]
    return y
*p, = range(N)
sz = [1]*N
c = 0
def unite(x, y):
    nonlocal c
    px = root(x); py = root(y)
    if px == py:
        return 0
    c += sz[px] * sz[py]
    if sz[px] < sz[py]:
        p[py] = px
        sz[px] += sz[py]
    else:
        p[px] = py
        sz[py] += sz[px]
    return 1

k = 0
ans = [N*(N-1)//2]*M
L = len(Q)
for w, u, v in E:
    while k < L and Q[k] < w:
        e = Q[k]
        for i in MP[e]:
            ans[i] = c
        k += 1
    unite(u, v)
sys.stdout.write(" ".join(map(str, ans)))
sys.stdout.write("\n")


I found an interesting problem on https://codeforces.com/problemset/problem/1214/A:
Andrew was very excited to participate in Olympiad of Metropolises. Days flew by quickly, and Andrew is already at the airport, ready to go home. He has $n$ rubles left, and would like to exchange them to euro and dollar bills. Andrew can mix dollar bills and euro bills in whatever way he wants. The price of one dollar is $d$ rubles, and one euro costs $e$ rubles.

Recall that there exist the following dollar bills: $1$, $2$, $5$, $10$, $20$, $50$, $100$, and the following euro bills — $5$, $10$, $20$, $50$, $100$, $200$ (note that, in this problem we do not consider the $500$ euro bill, it is hard to find such bills in the currency exchange points). Andrew can buy any combination of bills, and his goal is to minimize the total number of rubles he will have after the exchange.

Help him — write a program that given integers $n$, $e$ and $d$, finds the minimum number of rubles Andrew can get after buying dollar and euro bills.

-----Input-----

The first line of the input contains one integer $n$ ($1 \leq n \leq 10^8$) — the initial sum in rubles Andrew has.

The second line of the input contains one integer $d$ ($30 \leq d \leq 100$) — the price of one dollar in rubles.

The third line of the input contains integer $e$ ($30 \leq e \leq 100$) — the price of one euro in rubles.

-----Output-----

Output one integer — the minimum number of rubles Andrew can have after buying dollar and euro bills optimally.

-----Examples-----
Input
100
60
70

Output
40

Input
410
55
70

Output
5

Input
600
60
70

Output
0

-----Note-----

In the first example, we can buy just $1$ dollar because there is no $1$ euro bill.

In the second example, optimal exchange is to buy $5$ euro and $1$ dollar.

In the third example, optimal exchange is to buy $10$ dollars in one bill.

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

import sys
from collections import defaultdict
input = lambda : sys.stdin.readline().rstrip()

n = int(input())
d = int(input())
e = int(input())

dollar = d
euro = 5 * e

ans = n

if n % dollar == 0 or n % euro == 0:
  print(0)
  return

for i in range(n // dollar + 1):
  k = n - i * dollar
  k -= (k // euro) * euro

  ans = min(ans, k)

for i in range(n // euro + 1):
  k = n - i * euro
  k -= (k // dollar) * dollar

  ans = min(ans, k)

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1214/B:
There are $b$ boys and $g$ girls participating in Olympiad of Metropolises. There will be a board games tournament in the evening and $n$ participants have accepted the invitation. The organizers do not know how many boys and girls are among them.

Organizers are preparing red badges for girls and blue ones for boys.

Vasya prepared $n+1$ decks of badges. The $i$-th (where $i$ is from $0$ to $n$, inclusive) deck contains $i$ blue badges and $n-i$ red ones. The total number of badges in any deck is exactly $n$.

Determine the minimum number of decks among these $n+1$ that Vasya should take, so that there will be a suitable deck no matter how many girls and boys there will be among the participants of the tournament.

-----Input-----

The first line contains an integer $b$ ($1 \le b \le 300$), the number of boys.

The second line contains an integer $g$ ($1 \le g \le 300$), the number of girls.

The third line contains an integer $n$ ($1 \le n \le b + g$), the number of the board games tournament participants.

-----Output-----

Output the only integer, the minimum number of badge decks that Vasya could take.

-----Examples-----
Input
5
6
3

Output
4

Input
5
3
5

Output
4

-----Note-----

In the first example, each of 4 decks should be taken: (0 blue, 3 red), (1 blue, 2 red), (2 blue, 1 red), (3 blue, 0 red).

In the second example, 4 decks should be taken: (2 blue, 3 red), (3 blue, 2 red), (4 blue, 1 red), (5 blue, 0 red). Piles (0 blue, 5 red) and (1 blue, 4 red) can not be used.

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

b = int(input())
g = int(input())
n = int(input())
wyn = 0
for bb in range(b + 1):
    if n - bb in range(g + 1):
        wyn += 1
print(wyn)


I found an interesting problem on https://codeforces.com/problemset/problem/1214/C:
Petya's friends made him a birthday present — a bracket sequence. Petya was quite disappointed with his gift, because he dreamed of correct bracket sequence, yet he told his friends nothing about his dreams and decided to fix present himself.

To make everything right, Petya is going to move at most one bracket from its original place in the sequence to any other position. Reversing the bracket (e.g. turning "(" into ")" or vice versa) isn't allowed.

We remind that bracket sequence $s$ is called correct if:   $s$ is empty;  $s$ is equal to "($t$)", where $t$ is correct bracket sequence;  $s$ is equal to $t_1 t_2$, i.e. concatenation of $t_1$ and $t_2$, where $t_1$ and $t_2$ are correct bracket sequences.

For example, "(()())", "()" are correct, while ")(" and "())" are not. Help Petya to fix his birthday present and understand whether he can move one bracket so that the sequence becomes correct.

-----Input-----

First of line of input contains a single number $n$ ($1 \leq n \leq 200\,000$) — length of the sequence which Petya received for his birthday.

Second line of the input contains bracket sequence of length $n$, containing symbols "(" and ")".

-----Output-----

Print "Yes" if Petya can make his sequence correct moving at most one bracket. Otherwise print "No".

-----Examples-----
Input
2
)(

Output
Yes

Input
3
(()

Output
No

Input
2
()

Output
Yes

Input
10
)))))(((((

Output
No

-----Note-----

In the first example, Petya can move first bracket to the end, thus turning the sequence into "()", which is correct bracket sequence.

In the second example, there is no way to move at most one bracket so that the sequence becomes correct.

In the third example, the sequence is already correct and there's no need to move brackets.

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

n = int(input())
s= input()

depth = 0
ig = False
for i in range(n):
    if(not ig and s[i] == ')' ):
        ig = True
        continue
    if(s[i] == '('):
        depth +=1
    else:
        depth -= 1
    if(depth < 0):
        print('No')
        return
if(ig): depth -= 1

if(depth):
    print('No')
else:
    print('Yes')


I found an interesting problem on https://codeforces.com/problemset/problem/1214/D:
All of us love treasures, right? That's why young Vasya is heading for a Treasure Island.

Treasure Island may be represented as a rectangular table $n \times m$ which is surrounded by the ocean. Let us number rows of the field with consecutive integers from $1$ to $n$ from top to bottom and columns with consecutive integers from $1$ to $m$ from left to right. Denote the cell in $r$-th row and $c$-th column as $(r, c)$. Some of the island cells contain impassable forests, and some cells are free and passable. Treasure is hidden in cell $(n, m)$.

Vasya got off the ship in cell $(1, 1)$. Now he wants to reach the treasure. He is hurrying up, so he can move only from cell to the cell in next row (downwards) or next column (rightwards), i.e. from cell $(x, y)$ he can move only to cells $(x+1, y)$ and $(x, y+1)$. Of course Vasya can't move through cells with impassable forests.

Evil Witch is aware of Vasya's journey and she is going to prevent him from reaching the treasure. Before Vasya's first move she is able to grow using her evil magic impassable forests in previously free cells. Witch is able to grow a forest in any number of any free cells except cells $(1, 1)$ where Vasya got off his ship and $(n, m)$ where the treasure is hidden.

Help Evil Witch by finding out the minimum number of cells she has to turn into impassable forests so that Vasya is no longer able to reach the treasure.

-----Input-----

First line of input contains two positive integers $n$, $m$ ($3 \le n \cdot m \le 1\,000\,000$), sizes of the island.

Following $n$ lines contains strings $s_i$ of length $m$ describing the island, $j$-th character of string $s_i$ equals "#" if cell $(i, j)$ contains an impassable forest and "." if the cell is free and passable. Let us remind you that Vasya gets of his ship at the cell $(1, 1)$, i.e. the first cell of the first row, and he wants to reach cell $(n, m)$, i.e. the last cell of the last row.

It's guaranteed, that cells $(1, 1)$ and $(n, m)$ are empty.

-----Output-----

Print the only...

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

from sys import stdin
from collections import defaultdict
n, m = list(map(int, input().split()))

if n == 1 or m == 1:
    if '#' in stdin.read():
        print(0)
    else:
        print(1)
    return

graph = []
for i in range(n):
    graph.append(input())

def dfs(visited):
    reachable = []
    stack = []
    stack.append((0, 0))

    while stack:
        node_r, node_c = stack.pop()
        if not visited[node_r][node_c]:
            visited[node_r][node_c] = True
            reachable.append((node_r, node_c))
            if node_r + 1 < n and not visited[node_r + 1][node_c] and graph[node_r + 1][node_c] != '#':
                stack.append((node_r + 1, node_c))
            if node_c + 1 < m and not visited[node_r][node_c + 1] and graph[node_r][node_c + 1] != '#':
                stack.append((node_r, node_c + 1))
            if node_r == n - 1 and node_c == m - 1:
                break

    return reachable

'''
def dfs_reverse():
    visited = [[False for j in range(m)] for i in range(n)]
    reachable = []
    stack = []
    stack.append((n - 1, m - 1))

    while stack:
        node_r, node_c = stack.pop()
        if not visited[node_r][node_c]:
            visited[node_r][node_c] = True
            reachable.append((node_r, node_c))
            if node_r - 1 >= 0 and not visited[node_r - 1][node_c] and graph[node_r - 1][node_c] != '#':
                stack.append((node_r - 1, node_c))
            if node_c - 1 >= 0 and not visited[node_r][node_c - 1] and graph[node_r][node_c - 1] != '#':
                stack.append((node_r, node_c - 1))

    return reachable
'''

visited = [[False for j in range(m)] for i in range(n)]
dfs(visited)

if not visited[n - 1][m - 1]:
    print(0)
else:
    visited[0][0] = False
    visited[n - 1][m - 1] = False
    dfs(visited)
    if visited[n - 1][m - 1]:
        print(2)
    else:
        print(1)


I found an interesting problem on https://codeforces.com/problemset/problem/1215/A:
The final match of the Berland Football Cup has been held recently. The referee has shown $n$ yellow cards throughout the match. At the beginning of the match there were $a_1$ players in the first team and $a_2$ players in the second team.

The rules of sending players off the game are a bit different in Berland football. If a player from the first team receives $k_1$ yellow cards throughout the match, he can no longer participate in the match — he's sent off. And if a player from the second team receives $k_2$ yellow cards, he's sent off. After a player leaves the match, he can no longer receive any yellow cards. Each of $n$ yellow cards was shown to exactly one player. Even if all players from one team (or even from both teams) leave the match, the game still continues.

The referee has lost his records on who has received each yellow card. Help him to determine the minimum and the maximum number of players that could have been thrown out of the game.

-----Input-----

The first line contains one integer $a_1$ $(1 \le a_1 \le 1\,000)$ — the number of players in the first team.

The second line contains one integer $a_2$ $(1 \le a_2 \le 1\,000)$ — the number of players in the second team.

The third line contains one integer $k_1$ $(1 \le k_1 \le 1\,000)$ — the maximum number of yellow cards a player from the first team can receive (after receiving that many yellow cards, he leaves the game).

The fourth line contains one integer $k_2$ $(1 \le k_2 \le 1\,000)$ — the maximum number of yellow cards a player from the second team can receive (after receiving that many yellow cards, he leaves the game).

The fifth line contains one integer $n$ $(1 \le n \le a_1 \cdot k_1 + a_2 \cdot k_2)$ — the number of yellow cards that have been shown during the match.

-----Output-----

Print two integers — the minimum and the maximum number of players that could have been thrown out of the game.

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

Output
0 4

Input
3
1
6
7
25

Output
4 4

Input
6
4
9
10
89

Output
5...

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

a1=int(input())
a2=int(input())
k1=int(input())
k2=int(input())
n=int(input())
ans1=0
ans2=0

if k1<k2:
    ans1+=min(n//k1,a1)
    ans1+=(n-ans1*k1)//k2
else :
    ans1+=min(n//k2,a2)
    ans1+=(n-ans1*k2)//k1
ans2=max(0,n-(k1-1)*a1-(k2-1)*a2)
print(ans2,ans1)


I found an interesting problem on https://codeforces.com/problemset/problem/1215/B:
You are given a sequence $a_1, a_2, \dots, a_n$ consisting of $n$ non-zero integers (i.e. $a_i \ne 0$).

You have to calculate two following values:  the number of pairs of indices $(l, r)$ $(l \le r)$ such that $a_l \cdot a_{l + 1} \dots a_{r - 1} \cdot a_r$ is negative;  the number of pairs of indices $(l, r)$ $(l \le r)$ such that $a_l \cdot a_{l + 1} \dots a_{r - 1} \cdot a_r$ is positive;

-----Input-----

The first line contains one integer $n$ $(1 \le n \le 2 \cdot 10^{5})$ — the number of elements in the sequence.

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ $(-10^{9} \le a_i \le 10^{9}; a_i \neq 0)$ — the elements of the sequence.

-----Output-----

Print two integers — the number of subsegments with negative product and the number of subsegments with positive product, respectively.

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

Output
8 7

Input
10
4 2 -4 3 1 2 -4 3 2 3

Output
28 27

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

Output
9 6

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

from itertools import accumulate
from operator import xor
n = int(input())
l = accumulate([1 if x < 0 else 0 for x in map(int, input().split())], xor)
a = b = 0
cnt = [1, 0]
for e in l:
    a += cnt[e ^ 1]
    b += cnt[e]
    cnt[e] += 1
print(a, b)


I found an interesting problem on https://codeforces.com/problemset/problem/1215/C:
Monocarp has got two strings $s$ and $t$ having equal length. Both strings consist of lowercase Latin letters "a" and "b".

Monocarp wants to make these two strings $s$ and $t$ equal to each other. He can do the following operation any number of times: choose an index $pos_1$ in the string $s$, choose an index $pos_2$ in the string $t$, and swap $s_{pos_1}$ with $t_{pos_2}$.

You have to determine the minimum number of operations Monocarp has to perform to make $s$ and $t$ equal, and print any optimal sequence of operations — or say that it is impossible to make these strings equal.

-----Input-----

The first line contains one integer $n$ $(1 \le n \le 2 \cdot 10^{5})$ — the length of $s$ and $t$.

The second line contains one string $s$ consisting of $n$ characters "a" and "b".

The third line contains one string $t$ consisting of $n$ characters "a" and "b".

-----Output-----

If it is impossible to make these strings equal, print $-1$.

Otherwise, in the first line print $k$ — the minimum number of operations required to make the strings equal. In each of the next $k$ lines print two integers — the index in the string $s$ and the index in the string $t$ that should be used in the corresponding swap operation.

-----Examples-----
Input
4
abab
aabb

Output
2
3 3
3 2

Input
1
a
b

Output
-1

Input
8
babbaabb
abababaa

Output
3
2 6
1 3
7 8

-----Note-----

In the first example two operations are enough. For example, you can swap the third letter in $s$ with the third letter in $t$. Then $s = $ "abbb", $t = $ "aaab". Then swap the third letter in $s$ and the second letter in $t$. Then both $s$ and $t$ are equal to "abab".

In the second example it's impossible to make two strings equal.

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

import math
import sys
import collections

# imgur.com/Pkt7iIf.png

def getdict(n):
    d = {}
    if type(n) is list:
        for i in n:
            if i in d:
                d[i] += 1
            else:
                d[i] = 1
    else:
        for i in range(n):
            t = ii()
            if t in d:
                d[t] += 1
            else:
                d[t] = 1
    return d
def sieve(n):
    prime = [True for i in range(n + 1)]
    p = 2
    while (p * p <= n):
        if (prime[p] == True):
            for i in range(p * 2, n + 1, p):
                prime[i] = False
        p += 1
    prime[0] = prime[1] = False
    r = [p for p in range(n + 1) if prime[p]]
    return r
def cdiv(n, k): return n // k + (n % k != 0)
def ii(): return int(input())
def mi(): return map(int, input().split())
def li(): return list(map(int, input().split()))
def lcm(a, b): return abs(a * b) // math.gcd(a, b)
def prr(a, sep = ' '): print(sep.join(map(str, a)))

n = ii()
s = input()
t = input()
if (s.count('a') + t.count('a'))%2:
    print(-1);return()

ab = []
ba = []
for i in range(n):
    if s[i] == 'a' and t[i] == 'b':
        ab.append(i + 1)
    elif s[i] == 'b' and t[i] == 'a':
        ba.append(i + 1)

r = []
while len(ab) >= 2:
    v = ab.pop()
    u = ab.pop()
    r.append(f'{u} {v}')
while len(ba) >= 2:
    v = ba.pop()
    u = ba.pop()
    r.append(f'{u} {v}')

if len(ab) != len(ba):
    print(-1);return()
elif len(ab) > 0:
    u = ab[0]
    v = ba[0]
    r.append(f'{u} {u}')
    r.append(f'{u} {v}')

print(len(r))
for i in r:
    print(i)


I found an interesting problem on https://codeforces.com/problemset/problem/1215/D:
Monocarp and Bicarp live in Berland, where every bus ticket consists of $n$ digits ($n$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.

Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $\frac{n}{2}$ digits of this ticket is equal to the sum of the last $\frac{n}{2}$ digits.

Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $0$ to $9$. The game ends when there are no erased digits in the ticket.

If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally.

-----Input-----

The first line contains one even integer $n$ $(2 \le n \le 2 \cdot 10^{5})$ — the number of digits in the ticket.

The second line contains a string of $n$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $i$-th character is "?", then the $i$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even.

-----Output-----

If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes).

-----Examples-----
Input
4
0523

Output
Bicarp

Input
2
??

Output
Bicarp

Input
8
?054??0?

Output
Bicarp

Input
6
???00?

Output
Monocarp

-----Note-----

Since there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.

In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy.

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

n=int(input())

s=input()

sum1=0
kol1=0
sum2=0
kol2=0

for i in range(n//2):
    if s[i]=='?':
        kol1+=1
    else:
        sum1+=int(s[i])

for i in range(n//2,n):
    if s[i]=='?':
        kol2+=1
    else:
        sum2+=int(s[i])

if sum1>sum2:
    sum1,sum2,kol1,kol2=sum2,sum1,kol2,kol1

if sum1==sum2 and kol1==kol2:
    print('Bicarp')
elif sum1==sum2 and kol1!=kol2:
    print('Monocarp')
elif (sum2-sum1)%9!=0:
    print('Monocarp')
elif kol1==kol2==0:
    print('Monocarp')
elif (sum2-sum1)//9==(kol1-kol2)//2:
    print('Bicarp')
else:
    print('Monocarp')


I found an interesting problem on https://codeforces.com/problemset/problem/1215/E:
Monocarp has arranged $n$ colored marbles in a row. The color of the $i$-th marble is $a_i$. Monocarp likes ordered things, so he wants to rearrange marbles in such a way that all marbles of the same color form a contiguos segment (and there is only one such segment for each color).

In other words, Monocarp wants to rearrange marbles so that, for every color $j$, if the leftmost marble of color $j$ is $l$-th in the row, and the rightmost marble of this color has position $r$ in the row, then every marble from $l$ to $r$ has color $j$.

To achieve his goal, Monocarp can do the following operation any number of times: choose two neighbouring marbles, and swap them.

You have to calculate the minimum number of operations Monocarp has to perform to rearrange the marbles. Note that the order of segments of marbles having equal color does not matter, it is only required that, for every color, all the marbles of this color form exactly one contiguous segment.

-----Input-----

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

The second line contains an integer sequence $a_1, a_2, \dots, a_n$ $(1 \le a_i \le 20)$, where $a_i$ is the color of the $i$-th marble.

-----Output-----

Print the minimum number of operations Monocarp has to perform to achieve his goal.

-----Examples-----
Input
7
3 4 2 3 4 2 2

Output
3

Input
5
20 1 14 10 2

Output
0

Input
13
5 5 4 4 3 5 7 6 5 4 4 6 5

Output
21

-----Note-----

In the first example three operations are enough. Firstly, Monocarp should swap the third and the fourth marbles, so the sequence of colors is $[3, 4, 3, 2, 4, 2, 2]$. Then Monocarp should swap the second and the third marbles, so the sequence is $[3, 3, 4, 2, 4, 2, 2]$. And finally, Monocarp should swap the fourth and the fifth marbles, so the sequence is $[3, 3, 4, 4, 2, 2, 2]$.

In the second example there's no need to perform any operations.

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

import sys

n = int(sys.stdin.readline().strip())
a = list(map(int, sys.stdin.readline().strip().split()))
M = [[0 for i in range (0, 21)] for j in range (0, 21)]
F = [0 for i in range (0, 21)]
for i in range (0, n):
    x = int(a[i])
    for j in range (0, 21):
        if j != x:
            M[j][x] = M[j][x] + F[j]
    F[x] = F[x] + 1
ans = 0
for i in range (0, 21):
    for j in range (0, i):
        ans = ans + min(M[i][j], M[j][i])
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1216/A:
Nikolay got a string $s$ of even length $n$, which consists only of lowercase Latin letters 'a' and 'b'. Its positions are numbered from $1$ to $n$.

He wants to modify his string so that every its prefix of even length has an equal amount of letters 'a' and 'b'. To achieve that, Nikolay can perform the following operation arbitrary number of times (possibly, zero): choose some position in his string and replace the letter on this position with the other letter (i.e. replace 'a' with 'b' or replace 'b' with 'a'). Nikolay can use no letters except 'a' and 'b'.

The prefix of string $s$ of length $l$ ($1 \le l \le n$) is a string $s[1..l]$.

For example, for the string $s=$"abba" there are two prefixes of the even length. The first is $s[1\dots2]=$"ab" and the second $s[1\dots4]=$"abba". Both of them have the same number of 'a' and 'b'.

Your task is to calculate the minimum number of operations Nikolay has to perform with the string $s$ to modify it so that every its prefix of even length has an equal amount of letters 'a' and 'b'.

-----Input-----

The first line of the input contains one even integer $n$ $(2 \le n \le 2\cdot10^{5})$ — the length of string $s$.

The second line of the input contains the string $s$ of length $n$, which consists only of lowercase Latin letters 'a' and 'b'.

-----Output-----

In the first line print the minimum number of operations Nikolay has to perform with the string $s$ to modify it so that every its prefix of even length has an equal amount of letters 'a' and 'b'.

In the second line print the string Nikolay obtains after applying all the operations. If there are multiple answers, you can print any of them.

-----Examples-----
Input
4
bbbb

Output
2
abba

Input
6
ababab

Output
0
ababab

Input
2
aa

Output
1
ba

-----Note-----

In the first example Nikolay has to perform two operations. For example, he can replace the first 'b' with 'a' and the last 'b' with 'a'.

In the second example Nikolay doesn't need to do anything because each prefix of an even length of the...

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

l = int(input())
s = [char for char in input()]
cc = 0

other_char = {'a': 'b', 'b': 'a'}

for i in range(0, l, 2):
    if s[i] == s[i+1]:
        cc += 1
        s[i] = other_char[s[i]]

print(cc)
print(''.join(s))


I found an interesting problem on https://codeforces.com/problemset/problem/1216/B:
Recently Vasya decided to improve his pistol shooting skills. Today his coach offered him the following exercise. He placed $n$ cans in a row on a table. Cans are numbered from left to right from $1$ to $n$. Vasya has to knock down each can exactly once to finish the exercise. He is allowed to choose the order in which he will knock the cans down.

Vasya knows that the durability of the $i$-th can is $a_i$. It means that if Vasya has already knocked $x$ cans down and is now about to start shooting the $i$-th one, he will need $(a_i \cdot x + 1)$ shots to knock it down. You can assume that if Vasya starts shooting the $i$-th can, he will be shooting it until he knocks it down.

Your task is to choose such an order of shooting so that the number of shots required to knock each of the $n$ given cans down exactly once is minimum possible.

-----Input-----

The first line of the input contains one integer $n$ $(2 \le n \le 1\,000)$ — the number of cans.

The second line of the input contains the sequence $a_1, a_2, \dots, a_n$ $(1 \le a_i \le 1\,000)$, where $a_i$ is the durability of the $i$-th can.

-----Output-----

In the first line print the minimum number of shots required to knock each of the $n$ given cans down exactly once.

In the second line print the sequence consisting of $n$ distinct integers from $1$ to $n$ — the order of indices of cans that minimizes the number of shots required. If there are several answers, you can print any of them.

-----Examples-----
Input
3
20 10 20

Output
43
1 3 2

Input
4
10 10 10 10

Output
64
2 1 4 3

Input
6
5 4 5 4 4 5

Output
69
6 1 3 5 2 4

Input
2
1 4

Output
3
2 1

-----Note-----

In the first example Vasya can start shooting from the first can. He knocks it down with the first shot because he haven't knocked any other cans down before. After that he has to shoot the third can. To knock it down he shoots $20 \cdot 1 + 1 = 21$ times. After that only second can remains. To knock it down Vasya shoots $10 \cdot 2 + 1 = 21$ times. So the total number of shots...

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

'''input
6
5 4 5 4 4 5
'''
from sys import stdin

def check_valid(string):
	stack = []
	for i in string:
		if i in ['(',  '[']:
			stack.append(i)
		elif i == ')':
			if len(stack) > 0:
				if stack[-1] == '(':
					stack.pop()
					continue
			return False
		elif i == ']':
			if len(stack) > 0:
				if stack[-1] == '[':
					stack.pop()
					continue
			return False

	return len(stack) == 0

def merge(index):
	aux = []
	if len(index) > 0:
		aux = [index[0]]
		for i in range(1, len(index)):
			if index[i][0] == aux[-1][1] + 1:
				aux[-1][1] = index[i][1]
			else:
				if check_valid(string[aux[-1][1] + 1: index[i][0]]):
					aux[-1][1] = index[i][1]
				else:
					aux.append(index[i])
	return aux

# main starts
n = int(stdin.readline().strip())
arr = []
arr = list(map(int, stdin.readline().split()))
for i in range(n):
	arr[i] = [i, arr[i]]

arr.sort(key = lambda x: x[1], reverse  = True)
count = 0
ans = []
total = 0
for i in range(n):
	index, a = arr[i]
	ans.append(index + 1)
	total += count * a + 1

	count += 1

print(total)
print(*ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1216/C:
There is a white sheet of paper lying on a rectangle table. The sheet is a rectangle with its sides parallel to the sides of the table. If you will take a look from above and assume that the bottom left corner of the table has coordinates $(0, 0)$, and coordinate axes are left and bottom sides of the table, then the bottom left corner of the white sheet has coordinates $(x_1, y_1)$, and the top right — $(x_2, y_2)$.

After that two black sheets of paper are placed on the table. Sides of both black sheets are also parallel to the sides of the table. Coordinates of the bottom left corner of the first black sheet are $(x_3, y_3)$, and the top right — $(x_4, y_4)$. Coordinates of the bottom left corner of the second black sheet are $(x_5, y_5)$, and the top right — $(x_6, y_6)$.  [Image] Example of three rectangles.

Determine if some part of the white sheet can be seen from the above after the two black sheets are placed. The part of the white sheet can be seen if there is at least one point lying not strictly inside the white sheet and strictly outside of both black sheets.

-----Input-----

The first line of the input contains four integers $x_1, y_1, x_2, y_2$ $(0 \le x_1 < x_2 \le 10^{6}, 0 \le y_1 < y_2 \le 10^{6})$ — coordinates of the bottom left and the top right corners of the white sheet.

The second line of the input contains four integers $x_3, y_3, x_4, y_4$ $(0 \le x_3 < x_4 \le 10^{6}, 0 \le y_3 < y_4 \le 10^{6})$ — coordinates of the bottom left and the top right corners of the first black sheet.

The third line of the input contains four integers $x_5, y_5, x_6, y_6$ $(0 \le x_5 < x_6 \le 10^{6}, 0 \le y_5 < y_6 \le 10^{6})$ — coordinates of the bottom left and the top right corners of the second black sheet.

The sides of each sheet of paper are parallel (perpendicular) to the coordinate axes.

-----Output-----

If some part of the white sheet can be seen from the above after the two black sheets are placed, print "YES" (without quotes). Otherwise print "NO".

-----Examples-----
Input
2 2 4...

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

x1,y1,x2,y2=list(map(int,input().split()))
x3,y3,x4,y4=list(map(int,input().split()))
x5,y5,x6,y6=list(map(int,input().split()))
z=0
if x3<=x1 and x4>=x2 and y3<=y1 and y4>=y2:
    z=1
if x5<=x1 and x6>=x2 and y5<=y1 and y6>=y2:
    z=1
if y3>y5:
    if y3<=y6 and y4>=y2 and y5<=y1:
        if x3<=x1 and x4>=x2 and x5<=x1 and x6>=x2:
            z=1
else:
    y3,y5=y5,y3
    y6,y4=y4,y6
    if y3<=y6 and y4>=y2 and y5<=y1:
        if x3<=x1 and x4>=x2 and x5<=x1 and x6>=x2:
            z=1
y3,y5=y5,y3
y6,y4=y4,y6
if x3<x5:
    if x3<=x1 and x4>=x5 and x6>=x2:
        if y3<=y1 and y4>=y2 and y5<=y1 and y6>=y2:
            z=1
else:
    x3,x5=x5,x3
    x6,x4=x4,x6
    if x3<=x1 and x4>=x5 and x6>=x2:
        if y3<=y1 and y4>=y2 and y5<=y1 and y6>=y2:
            z=1
if z==1:
    print("NO")
else:
    print("YES")


I found an interesting problem on https://codeforces.com/problemset/problem/1216/D:
There were $n$ types of swords in the theater basement which had been used during the plays. Moreover there were exactly $x$ swords of each type. $y$ people have broken into the theater basement and each of them has taken exactly $z$ swords of some single type. Note that different people might have taken different types of swords. Note that the values $x, y$ and $z$ are unknown for you.

The next morning the director of the theater discovers the loss. He counts all swords — exactly $a_i$ swords of the $i$-th type are left untouched.

The director has no clue about the initial number of swords of each type in the basement, the number of people who have broken into the basement and how many swords each of them have taken.

For example, if $n=3$, $a = [3, 12, 6]$ then one of the possible situations is $x=12$, $y=5$ and $z=3$. Then the first three people took swords of the first type and the other two people took swords of the third type. Note that you don't know values $x, y$ and $z$ beforehand but know values of $n$ and $a$.

Thus he seeks for your help. Determine the minimum number of people $y$, which could have broken into the theater basement, and the number of swords $z$ each of them has taken.

-----Input-----

The first line of the input contains one integer $n$ $(2 \le n \le 2 \cdot 10^{5})$ — the number of types of swords.

The second line of the input contains the sequence $a_1, a_2, \dots, a_n$ $(0 \le a_i \le 10^{9})$, where $a_i$ equals to the number of swords of the $i$-th type, which have remained in the basement after the theft. It is guaranteed that there exists at least one such pair of indices $(j, k)$ that $a_j \neq a_k$.

-----Output-----

Print two integers $y$ and $z$ — the minimum number of people which could have broken into the basement and the number of swords each of them has taken.

-----Examples-----
Input
3
3 12 6

Output
5 3

Input
2
2 9

Output
1 7

Input
7
2 1000000000 4 6 8 4 2

Output
2999999987 2

Input
6
13 52 0 13 26 52

Output
12 13

-----Note-----

In the first...

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

import math
from functools import reduce

l = int(input())

arr = list([int(x) for x in input().split(' ')])

cel = max(arr)
nwd = reduce(lambda x, y: math.gcd(x, y), [cel-x for x in arr])

people = sum((cel - elem) // nwd for elem in arr)

print('{} {}'.format(people, nwd))


I found an interesting problem on https://codeforces.com/problemset/problem/1216/E1:
The only difference between the easy and the hard versions is the maximum value of $k$.

You are given an infinite sequence of form "112123123412345$\dots$" which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from $1$ to $1$, the second one — from $1$ to $2$, the third one — from $1$ to $3$, $\dots$, the $i$-th block consists of all numbers from $1$ to $i$.

So the first $56$ elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the $1$-st element of the sequence is $1$, the $3$-rd element of the sequence is $2$, the $20$-th element of the sequence is $5$, the $38$-th element is $2$, the $56$-th element of the sequence is $0$.

Your task is to answer $q$ independent queries. In the $i$-th query you are given one integer $k_i$. Calculate the digit at the position $k_i$ of the sequence.

-----Input-----

The first line of the input contains one integer $q$ ($1 \le q \le 500$) — the number of queries.

The $i$-th of the following $q$ lines contains one integer $k_i$ $(1 \le k_i \le 10^9)$ — the description of the corresponding query.

-----Output-----

Print $q$ lines. In the $i$-th line print one digit $x_i$ $(0 \le x_i \le 9)$ — the answer to the query $i$, i.e. $x_i$ should be equal to the element at the position $k_i$ of the sequence.

-----Examples-----
Input
5
1
3
20
38
56

Output
1
2
5
2
0

Input
4
2132
506
999999999
1000000000

Output
8
2
9
8

-----Note-----

Answers on queries from the first example are described in the problem statement.

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

q=int(input())

num_cnt=[[0,0]]
for i in range(1,22000):
    if i<10: num_cnt.append([num_cnt[-1][1]+1,num_cnt[-1][1]+i])
    elif i<100: num_cnt.append([num_cnt[-1][1]+1,num_cnt[-1][1]+9+(i-9)*2])
    elif i<1000: num_cnt.append([num_cnt[-1][1]+1,num_cnt[-1][1]+9+90*2+(i-99)*3])
    elif i<10000: num_cnt.append([num_cnt[-1][1]+1,num_cnt[-1][1]+9+90*2+900*3+(i-999)*4])
    elif i<100000: num_cnt.append([num_cnt[-1][1]+1,num_cnt[-1][1]+9+90*2+900*3+9000*4+(i-9999)*5])

for i in range(q):
    k=int(input())
    left,right=1,len(num_cnt)
    mid=0
    while left<=right:
        mid=(left+right)//2
        if k >= num_cnt[mid][0] and k <= num_cnt[mid][1]:
            break
        if k < num_cnt[mid][0]:
            right=mid-1
        else:
            left=mid+1

    now_cnt=num_cnt[mid][0]-1
    now_val=1
    succ=False
    while not succ:
        temp_val=list(str(now_val))
        for j in temp_val:
            now_cnt+=1
            if now_cnt==k:
                print(j)
                succ=True
                break
        now_val+=1


I found an interesting problem on https://codeforces.com/problemset/problem/1216/E2:
The only difference between the easy and the hard versions is the maximum value of $k$.

You are given an infinite sequence of form "112123123412345$\dots$" which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from $1$ to $1$, the second one — from $1$ to $2$, the third one — from $1$ to $3$, $\dots$, the $i$-th block consists of all numbers from $1$ to $i$.

So the first $56$ elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the $1$-st element of the sequence is $1$, the $3$-rd element of the sequence is $2$, the $20$-th element of the sequence is $5$, the $38$-th element is $2$, the $56$-th element of the sequence is $0$.

Your task is to answer $q$ independent queries. In the $i$-th query you are given one integer $k_i$. Calculate the digit at the position $k_i$ of the sequence.

-----Input-----

The first line of the input contains one integer $q$ ($1 \le q \le 500$) — the number of queries.

The $i$-th of the following $q$ lines contains one integer $k_i$ $(1 \le k_i \le 10^{18})$ — the description of the corresponding query.

-----Output-----

Print $q$ lines. In the $i$-th line print one digit $x_i$ $(0 \le x_i \le 9)$ — the answer to the query $i$, i.e. $x_i$ should be equal to the element at the position $k_i$ of the sequence.

-----Examples-----
Input
5
1
3
20
38
56

Output
1
2
5
2
0

Input
4
2132
506
999999999999999999
1000000000000000000

Output
8
2
4
1

-----Note-----

Answers on queries from the first example are described in the problem statement.

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/1216/F:
You work as a system administrator in a dormitory, which has $n$ rooms one after another along a straight hallway. Rooms are numbered from $1$ to $n$.

You have to connect all $n$ rooms to the Internet.

You can connect each room to the Internet directly, the cost of such connection for the $i$-th room is $i$ coins.

Some rooms also have a spot for a router. The cost of placing a router in the $i$-th room is also $i$ coins. You cannot place a router in a room which does not have a spot for it. When you place a router in the room $i$, you connect all rooms with the numbers from $max(1,~i - k)$ to $min(n,~i + k)$ inclusive to the Internet, where $k$ is the range of router. The value of $k$ is the same for all routers.

Calculate the minimum total cost of connecting all $n$ rooms to the Internet. You can assume that the number of rooms which have a spot for a router is not greater than the number of routers you have.

-----Input-----

The first line of the input contains two integers $n$ and $k$ ($1 \le n, k \le 2 \cdot 10^5$) — the number of rooms and the range of each router.

The second line of the input contains one string $s$ of length $n$, consisting only of zeros and ones. If the $i$-th character of the string equals to '1' then there is a spot for a router in the $i$-th room. If the $i$-th character of the string equals to '0' then you cannot place a router in the $i$-th room.

-----Output-----

Print one integer — the minimum total cost of connecting all $n$ rooms to the Internet.

-----Examples-----
Input
5 2
00100

Output
3

Input
6 1
000000

Output
21

Input
4 1
0011

Output
4

Input
12 6
000010000100

Output
15

-----Note-----

In the first example it is enough to place the router in the room $3$, then all rooms will be connected to the Internet. The total cost of connection is $3$.

In the second example you can place routers nowhere, so you need to connect all rooms directly. Thus, the total cost of connection of all rooms is $1 + 2 + 3 + 4 + 5 + 6 = 21$.

In the third example you need to...

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

from heapq import heappush, heappop
from collections import deque
N, K = map(int, input().split())
*B, = map(int, input())

INF = 10**18
que = deque()
hq = []
dp = [INF]*(N+1)
dp[0] = 0
for i in range(N):
    a = dp[i]
    while hq and hq[0][1] < i:
        heappop(hq)
    if hq:
        a = min(hq[0][0], a)
    #print(i, a)

    while que and a <= que[-1][1]:
        que.pop()
    que.append((i, a))

    if B[i]:
        heappush(hq, (que[0][1] + (i+1), i+K+1))

    if que and que[0][0] <= i-K:
        que.popleft()
    dp[i+1] = a + (i+1)
while hq and hq[0][1] < N:
    heappop(hq)
a = dp[N]
if hq:
    a = min(hq[0][0], a)
print(a)


I found an interesting problem on https://codeforces.com/problemset/problem/1217/A:
You play your favourite game yet another time. You chose the character you didn't play before. It has $str$ points of strength and $int$ points of intelligence. Also, at start, the character has $exp$ free experience points you can invest either in strength or in intelligence (by investing one point you can either raise strength by $1$ or raise intelligence by $1$).

Since you'd like to make some fun you want to create a jock character, so it has more strength than intelligence points (resulting strength is strictly greater than the resulting intelligence).

Calculate the number of different character builds you can create (for the purpose of replayability) if you must invest all free points. Two character builds are different if their strength and/or intellect are different.

-----Input-----

The first line contains the single integer $T$ ($1 \le T \le 100$) — the number of queries. Next $T$ lines contain descriptions of queries — one per line.

This line contains three integers $str$, $int$ and $exp$ ($1 \le str, int \le 10^8$, $0 \le exp \le 10^8$) — the initial strength and intelligence of the character and the number of free points, respectively.

-----Output-----

Print $T$ integers — one per query. For each query print the number of different character builds you can create.

-----Example-----
Input
4
5 3 4
2 1 0
3 5 5
4 10 6

Output
3
1
2
0

-----Note-----

In the first query there are only three appropriate character builds: $(str = 7, int = 5)$, $(8, 4)$ and $(9, 3)$. All other builds are either too smart or don't use all free points.

In the second query there is only one possible build: $(2, 1)$.

In the third query there are two appropriate builds: $(7, 6)$, $(8, 5)$.

In the fourth query all builds have too much brains.

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

for i in range(int(input())):
    a,b,c = list(map(int,input().split()))
    if a+c <= b:
        print(0)
    else:
        print(min((a+c-b+1)//2,c+1))


I found an interesting problem on https://codeforces.com/problemset/problem/1217/B:
You are fighting with Zmei Gorynich — a ferocious monster from Slavic myths, a huge dragon-like reptile with multiple heads!

 $m$

Initially Zmei Gorynich has $x$ heads. You can deal $n$ types of blows. If you deal a blow of the $i$-th type, you decrease the number of Gorynich's heads by $min(d_i, curX)$, there $curX$ is the current number of heads. But if after this blow Zmei Gorynich has at least one head, he grows $h_i$ new heads. If $curX = 0$ then Gorynich is defeated.

You can deal each blow any number of times, in any order.

For example, if $curX = 10$, $d = 7$, $h = 10$ then the number of heads changes to $13$ (you cut $7$ heads off, but then Zmei grows $10$ new ones), but if $curX = 10$, $d = 11$, $h = 100$ then number of heads changes to $0$ and Zmei Gorynich is considered defeated.

Calculate the minimum number of blows to defeat Zmei Gorynich!

You have to answer $t$ independent queries.

-----Input-----

The first line contains one integer $t$ ($1 \le t \le 100$) – the number of queries.

The first line of each query contains two integers $n$ and $x$ ($1 \le n \le 100$, $1 \le x \le 10^9$) — the number of possible types of blows and the number of heads Zmei initially has, respectively.

The following $n$ lines of each query contain the descriptions of types of blows you can deal. The $i$-th line contains two integers $d_i$ and $h_i$ ($1 \le d_i, h_i \le 10^9$) — the description of the $i$-th blow.

-----Output-----

For each query print the minimum number of blows you have to deal to defeat Zmei Gorynich.

If Zmei Gorynuch cannot be defeated print $-1$.

-----Example-----
Input
3
3 10
6 3
8 2
1 4
4 10
4 1
3 2
2 6
1 100
2 15
10 11
14 100

Output
2
3
-1

-----Note-----

In the first query you can deal the first blow (after that the number of heads changes to $10 - 6 + 3 = 7$), and then deal the second blow.

In the second query you just deal the first blow three times, and Zmei is defeated.

In third query you can not defeat Zmei Gorynich. Maybe it's better to convince it to stop fighting?

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

import math

T = int(input())
for t in range(T):
    n, x = map(int, input().split())
    gs = [tuple(map(int, input().split())) for _ in range(n)]
    max_d = max(g[0] for g in gs)
    max_delta = max(g[0] - g[1] for g in gs)
    if x <= max_d:
        c = 1
    elif max_delta <= 0:
        c = -1
    else:
        c = math.ceil((x - max_d)/max_delta) + 1
    print(c)


I found an interesting problem on https://codeforces.com/problemset/problem/1217/D:
You are given a directed graph with $n$ vertices and $m$ directed edges without self-loops or multiple edges.

Let's denote the $k$-coloring of a digraph as following: you color each edge in one of $k$ colors. The $k$-coloring is good if and only if there no cycle formed by edges of same color.

Find a good $k$-coloring of given digraph with minimum possible $k$.

-----Input-----

The first line contains two integers $n$ and $m$ ($2 \le n \le 5000$, $1 \le m \le 5000$) — the number of vertices and edges in the digraph, respectively.

Next $m$ lines contain description of edges — one per line. Each edge is a pair of integers $u$ and $v$ ($1 \le u, v \le n$, $u \ne v$) — there is directed edge from $u$ to $v$ in the graph.

It is guaranteed that each ordered pair $(u, v)$ appears in the list of edges at most once.

-----Output-----

In the first line print single integer $k$ — the number of used colors in a good $k$-coloring of given graph.

In the second line print $m$ integers $c_1, c_2, \dots, c_m$ ($1 \le c_i \le k$), where $c_i$ is a color of the $i$-th edge (in order as they are given in the input).

If there are multiple answers print any of them (you still have to minimize $k$).

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

Output
1
1 1 1 1 1

Input
3 3
1 2
2 3
3 1

Output
2
1 1 2

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

import math
# import sys
# input = sys.stdin.readline
n,m=[int(i) for i in input().split(' ')]
d=[[] for i in range(n)]
done = [False for i in range(n)]
def dfs(visited,i,d):
    visited[i]=True
    done[i] = True
    for j in d[i]:
        if visited[j]:
            return True
        if not done[j]:
            temp = dfs(visited,j,d)
            if temp:return True
    visited[i]=False
    return False
edgelist=[]
for i in range(m):
    a,b=[int(i) for i in input().split(' ')]
    edgelist.append([a,b])
    d[a-1].append(b-1)

ans = 0
visited=[False for i in range(n)]
for i in range(n):
    if dfs(visited,i,d):
        ans = 1
        break
if ans:
    print(2)
    for i in edgelist:
        if i[0]>i[1]:
            print(2,end=' ')
        else:print(1,end=' ')
else:
    print(1)
    print(' '.join('1' for i in range(m)))


I found an interesting problem on https://codeforces.com/problemset/problem/1219/C:
Alice became interested in periods of integer numbers. We say positive $X$ integer number is periodic with length $L$ if there exists positive integer number $P$ with $L$ digits such that $X$ can be written as $PPPP…P$. For example:

$X = 123123123$ is periodic number with length $L = 3$ and $L = 9$

$X = 42424242$ is periodic number with length $L = 2,L = 4$ and $L = 8$

$X = 12345$ is periodic number with length $L = 5$

For given positive period length $L$ and positive integer number $A$, Alice wants to find smallest integer number $X$ strictly greater than $A$ that is periodic with length L.

-----Input-----

First line contains one positive integer number $L \ (1 \leq L \leq 10^5)$ representing length of the period. Second line contains one positive integer number $A \ (1 \leq A \leq 10^{100 000})$.

-----Output-----

One positive integer number representing smallest positive number that is periodic with length $L$ and is greater than $A$.

-----Examples-----
Input
3
123456

Output
124124

Input
3
12345

Output
100100

-----Note-----

In first example 124124 is the smallest number greater than 123456 that can be written with period L = 3 (P = 124).

In the second example 100100 is the smallest number greater than 12345 with period L = 3 (P=100)

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

L = int(input())
A = input()
N = len(A)

if N%L != 0 or A == '9'*N:
    K = N//L + 1
    for _ in range(K):
        print(1, end='')
        for _ in range(L-1):
            print(0, end='')
    print()
else:
    for k in range(N//L):
        lg = 0
        for l in range(L):
            a0 = int(A[l])
            a = int(A[k*L+l])
            if a > a0:
                lg = 1
                break
            if a < a0:
                lg = -1
                break
        if lg == -1 or lg == 1:
            break
    if lg == -1:
        for _ in range(N//L):
            print(A[:L], end='')
        print()
    elif lg == 1 or lg == 0:
        B = list(A[:L])
        for l in range(L):
            b = int(B[L-1-l])+1
            if b == 10:
                B[L-1-l] = '0'
            else:
                B[L-1-l] = str(b)
                break
        for _ in range(N//L):
            print(''.join(B), end='')
        print()


I found an interesting problem on https://codeforces.com/problemset/problem/1220/B:
Sasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table $M$ with $n$ rows and $n$ columns such that $M_{ij}=a_i \cdot a_j$ where $a_1, \dots, a_n$ is some sequence of positive integers.

Of course, the girl decided to take it to school with her. But while she was having lunch, hooligan Grisha erased numbers on the main diagonal and threw away the array $a_1, \dots, a_n$. Help Sasha restore the array!

-----Input-----

The first line contains a single integer $n$ ($3 \leqslant n \leqslant 10^3$), the size of the table.

The next $n$ lines contain $n$ integers each. The $j$-th number of the $i$-th line contains the number $M_{ij}$ ($1 \leq M_{ij} \leq 10^9$). The table has zeroes on the main diagonal, that is, $M_{ii}=0$.

-----Output-----

In a single line print $n$ integers, the original array $a_1, \dots, a_n$ ($1 \leq a_i \leq 10^9$). It is guaranteed that an answer exists. If there are multiple answers, print any.

-----Examples-----
Input
5
0 4 6 2 4
4 0 6 2 4
6 6 0 3 6
2 2 3 0 2
4 4 6 2 0

Output
2 2 3 1 2
Input
3
0 99990000 99970002
99990000 0 99980000
99970002 99980000 0

Output
9999 10000 9998

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

from math import sqrt
n = int(input())
matrix = []
for i in range(n):
    matrix.append(list(map(int, input().split())))

a0 = int(sqrt(matrix[0][1] * matrix[0][2] / matrix[1][2]))
print(a0, end=' ')
for i in range(1, n):
    print(int(matrix[0][i]/a0), end=' ')

print('')


I found an interesting problem on https://codeforces.com/problemset/problem/1220/C:
Mike and Ann are sitting in the classroom. The lesson is boring, so they decided to play an interesting game. Fortunately, all they need to play this game is a string $s$ and a number $k$ ($0 \le k < |s|$).

At the beginning of the game, players are given a substring of $s$ with left border $l$ and right border $r$, both equal to $k$ (i.e. initially $l=r=k$). Then players start to make moves one by one, according to the following rules: A player chooses $l^{\prime}$ and $r^{\prime}$ so that $l^{\prime} \le l$, $r^{\prime} \ge r$ and $s[l^{\prime}, r^{\prime}]$ is lexicographically less than $s[l, r]$. Then the player changes $l$ and $r$ in this way: $l := l^{\prime}$, $r := r^{\prime}$. Ann moves first. The player, that can't make a move loses.

Recall that a substring $s[l, r]$ ($l \le r$) of a string $s$ is a continuous segment of letters from s that starts at position $l$ and ends at position $r$. For example, "ehn" is a substring ($s[3, 5]$) of "aaaehnsvz" and "ahz" is not.

Mike and Ann were playing so enthusiastically that they did not notice the teacher approached them. Surprisingly, the teacher didn't scold them, instead of that he said, that he can figure out the winner of the game before it starts, even if he knows only $s$ and $k$.

Unfortunately, Mike and Ann are not so keen in the game theory, so they ask you to write a program, that takes $s$ and determines the winner for all possible $k$.

-----Input-----

The first line of the input contains a single string $s$ ($1 \leq |s| \leq 5 \cdot 10^5$) consisting of lowercase English letters.

-----Output-----

Print $|s|$ lines.

In the line $i$ write the name of the winner (print Mike or Ann) in the game with string $s$ and $k = i$, if both play optimally

-----Examples-----
Input
abba

Output
Mike
Ann
Ann
Mike

Input
cba

Output
Mike
Mike
Mike

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

a = input()
l = []
mi = 999999999999999
for i in a:
    k = ord(i) - 97
    if k > mi:
        l.append("1")
    else:
        l.append("0")
        mi = k
for i in l:
    print(i.replace("1", "Ann").replace("0", "Mike"))


I found an interesting problem on https://codeforces.com/problemset/problem/1220/D:
Boy Dima gave Julian a birthday present — set $B$ consisting of positive integers. However, he didn't know, that Julian hates sets, but enjoys bipartite graphs more than anything else!

Julian was almost upset, but her friend Alex said, that he can build an undirected graph using this set in such a way: let all integer numbers be vertices, then connect any two $i$ and $j$ with an edge if $|i - j|$ belongs to $B$.

Unfortunately, Julian doesn't like the graph, that was built using $B$. Alex decided to rectify the situation, so he wants to erase some numbers from $B$, so that graph built using the new set is bipartite. The difficulty of this task is that the graph, Alex has to work with, has an infinite number of vertices and edges! It is impossible to solve this task alone, so Alex asks you for help. Write a program that erases a subset of minimum size from $B$ so that graph constructed on the new set is bipartite.

Recall, that graph is bipartite if all its vertices can be divided into two disjoint sets such that every edge connects a vertex from different sets.

-----Input-----

First line contains an integer $n ~ (1 \leqslant n \leqslant 200\,000)$ — size of $B$

Second line contains $n$ integers $b_1, b_2, \ldots, b_n ~ (1 \leqslant b_i \leqslant 10^{18})$ — numbers of $B$, all $b_i$ are unique

-----Output-----

In the first line print single integer $k$ – the number of erased elements. In the second line print $k$ integers — values of erased elements.

If there are multiple answers, print any of them.

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

Output
1
2
Input
2
2 6

Output
0

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

#!usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

#A
def A():
    n = I()
    s = S()
    d = defaultdict(lambda : 0)
    for i in s:
        d[i] += 1
    ans = [1]*d["n"]
    d["o"] -= d["n"]
    ans += [0]*d["o"]
    print(*ans)
    return

#B
def B():

    n = I()
    m = LIR(n)
    f = [0]*n
    for i in range(n):
        for j in range(n):
            if i == j:
                continue
            f[i] += math.log(m[i][j],10)
    F = sum(f)
    p = F/(2*(n-1))
    a = [round(10**((f[i]-p)/(n-2))) for i in range(n)]
    print(*a)
    return

#C
def C():
    s = S()
    n = len(s)
    g = [0]*n
    m = 26
    f = [set() for i in range(n)]
    f[ord(s[0])-ord("a")].add(0)
    for i in range(1,n):
        lis = set()
        k = ord(s[i])-ord("a")
        for j in range(k):
            lis |= f[j]
        for j in range(100):
            if j not in lis:
                g[i] = j
                break
        f[k].add(j)
    for i in g:
        if i == 0:
            print("Mike")
        else:
            print("Ann")
    return

#D
def D():
    n = I()
    b = LI()
    l = [i&-i for i in b]
    d = defaultdict(lambda : 0)
    for i in l:
        d[i] += 1
    m = [0,0]
    for i,j in list(d.items()):
        if m[1] < j:
            m = [i,j]
    ans = []
    for i in range(n):
        if m[0] != l[i]:
            ans.append(b[i])
    print(len(ans))
    print(*ans)
    return

#E
def E():

    return

#F
def...


I found an interesting problem on https://codeforces.com/problemset/problem/1221/B:
You are given a chess board with $n$ rows and $n$ columns. Initially all cells of the board are empty, and you have to put a white or a black knight into each cell of the board.

A knight is a chess piece that can attack a piece in cell ($x_2$, $y_2$) from the cell ($x_1$, $y_1$) if one of the following conditions is met:

  $|x_1 - x_2| = 2$ and $|y_1 - y_2| = 1$, or  $|x_1 - x_2| = 1$ and $|y_1 - y_2| = 2$.

Here are some examples of which cells knight can attack. In each of the following pictures, if the knight is currently in the blue cell, it can attack all red cells (and only them).

 [Image]

A duel of knights is a pair of knights of different colors such that these knights attack each other. You have to put a knight (a white one or a black one) into each cell in such a way that the number of duels is maximum possible.

-----Input-----

The first line contains one integer $n$ ($3 \le n \le 100$) — the number of rows (and columns) in the board.

-----Output-----

Print $n$ lines with $n$ characters in each line. The $j$-th character in the $i$-th line should be W, if the cell ($i$, $j$) contains a white knight, or B, if it contains a black knight. The number of duels should be maximum possible. If there are multiple optimal answers, print any of them.

-----Example-----
Input
3

Output
WBW
BBB
WBW

-----Note-----

In the first example, there are $8$ duels:

  the white knight in ($1$, $1$) attacks the black knight in ($3$, $2$);  the white knight in ($1$, $1$) attacks the black knight in ($2$, $3$);  the white knight in ($1$, $3$) attacks the black knight in ($3$, $2$);  the white knight in ($1$, $3$) attacks the black knight in ($2$, $1$);  the white knight in ($3$, $1$) attacks the black knight in ($1$, $2$);  the white knight in ($3$, $1$) attacks the black knight in ($2$, $3$);  the white knight in ($3$, $3$) attacks the black knight in ($1$, $2$);  the white knight in ($3$, $3$) attacks the black knight in ($2$, $1$).

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

n = int(input())
a = 'WB' * (n // 2)
b = 'BW' * (n // 2)
if n & 1:
    a += 'W'
    b += 'B'
for i in range(n):
    print(a if i & 1 else b)