I found an interesting problem on https://codeforces.com/problemset/problem/976/B:
You might have heard about the next game in Lara Croft series coming out this year. You also might have watched its trailer. Though you definitely missed the main idea about its plot, so let me lift the veil of secrecy.

Lara is going to explore yet another dangerous dungeon. Game designers decided to use good old 2D environment. The dungeon can be represented as a rectangle matrix of n rows and m columns. Cell (x, y) is the cell in the x-th row in the y-th column. Lara can move between the neighbouring by side cells in all four directions.

Moreover, she has even chosen the path for herself to avoid all the traps. She enters the dungeon in cell (1, 1), that is top left corner of the matrix. Then she goes down all the way to cell (n, 1) — the bottom left corner. Then she starts moving in the snake fashion — all the way to the right, one cell up, then to the left to the cell in 2-nd column, one cell up. She moves until she runs out of non-visited cells. n and m given are such that she always end up in cell (1, 2).

Lara has already moved to a neighbouring cell k times. Can you determine her current position?

-----Input-----

The only line contains three integers n, m and k (2 ≤ n, m ≤ 10^9, n is always even, 0 ≤ k < n·m). Note that k doesn't fit into 32-bit integer type!

-----Output-----

Print the cell (the row and the column where the cell is situated) where Lara ends up after she moves k times.

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

Output
1 1

Input
4 3 11

Output
1 2

Input
4 3 7

Output
3 2

-----Note-----

Here is her path on matrix 4 by 3: [Image]

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

# python3

def readline(): return tuple(map(int, input().split()))

def main():
    n, m, k = readline()
    if k < n:
        print(k + 1, 1)
    else:
        k -= n
        q, r = divmod(k, m - 1)
        print(n - q, m - r if q & 1 else 2 + r)

main()


I found an interesting problem on https://codeforces.com/problemset/problem/976/C:
You are given a sequence a_1, a_2, ..., a_{n} of one-dimensional segments numbered 1 through n. Your task is to find two distinct indices i and j such that segment a_{i} lies within segment a_{j}.

Segment [l_1, r_1] lies within segment [l_2, r_2] iff l_1 ≥ l_2 and r_1 ≤ r_2.

Print indices i and j. If there are multiple answers, print any of them. If no answer exists, print -1 -1.

-----Input-----

The first line contains one integer n (1 ≤ n ≤ 3·10^5) — the number of segments.

Each of the next n lines contains two integers l_{i} and r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ 10^9) — the i-th segment.

-----Output-----

Print two distinct indices i and j such that segment a_{i} lies within segment a_{j}. If there are multiple answers, print any of them. If no answer exists, print -1 -1.

-----Examples-----
Input
5
1 10
2 9
3 9
2 3
2 9

Output
2 1

Input
3
1 5
2 6
6 20

Output
-1 -1

-----Note-----

In the first example the following pairs are considered correct:  (2, 1), (3, 1), (4, 1), (5, 1) — not even touching borders;  (3, 2), (4, 2), (3, 5), (4, 5) — touch one border;  (5, 2), (2, 5) — match exactly.

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

#!/usr/bin/env python3
from sys import stdin, stdout

def rint():
    return list(map(int, stdin.readline().split()))

n = int(input())

a = [list(rint()) + [i+1] for i in range(n)]

a.sort(key=lambda aa: [aa[0], -aa[1], aa[2]])

start = [-1, -1, -1]

for aa in a:
    if start[1] >= aa[1]:
        ans = [aa[2], start[2]]
        print(*ans)
        return
    else:
        start = aa

print(-1, -1)


I found an interesting problem on https://codeforces.com/problemset/problem/976/D:
You are given a sequence of n positive integers d_1, d_2, ..., d_{n} (d_1 < d_2 < ... < d_{n}). Your task is to construct an undirected graph such that:

  there are exactly d_{n} + 1 vertices;  there are no self-loops;  there are no multiple edges;  there are no more than 10^6 edges;  its degree set is equal to d.

Vertices should be numbered 1 through (d_{n} + 1).

Degree sequence is an array a with length equal to the number of vertices in a graph such that a_{i} is the number of vertices adjacent to i-th vertex.

Degree set is a sorted in increasing order sequence of all distinct values from the degree sequence.

It is guaranteed that there exists such a graph that all the conditions hold, and it contains no more than 10^6 edges.

Print the resulting graph.

-----Input-----

The first line contains one integer n (1 ≤ n ≤ 300) — the size of the degree set.

The second line contains n integers d_1, d_2, ..., d_{n} (1 ≤ d_{i} ≤ 1000, d_1 < d_2 < ... < d_{n}) — the degree set.

-----Output-----

In the first line print one integer m (1 ≤ m ≤ 10^6) — the number of edges in the resulting graph. It is guaranteed that there exists such a graph that all the conditions hold and it contains no more than 10^6 edges.

Each of the next m lines should contain two integers v_{i} and u_{i} (1 ≤ v_{i}, u_{i} ≤ d_{n} + 1) — the description of the i-th edge.

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

Output
8
3 1
4 2
4 5
2 5
5 1
3 2
2 1
5 3

Input
3
1 2 3

Output
4
1 2
1 3
1 4
2 3

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

# python3

def readline(): return list(map(int, input().split()))

def solve(d):
    while d:
        dn = d.pop()
        if not d:
            for i in range(1, dn + 1):
                for j in range(i, dn + 1):
                    yield i, j + 1
            return
        else:
            d1 = d.pop(0)
            for i in range(1, dn + 1):
                for j in range(max(dn - d1 + 1, i), dn + 1):
                    yield i, j + 1

            d = [di - d1 for di in d]

def main():
    n, = readline()
    d = readline()

    assert len(d) == n

    edges = list(solve(d))
    print(len(edges))
    print("\n".join(map("{0[0]} {0[1]}".format, edges)))

main()


I found an interesting problem on https://codeforces.com/problemset/problem/976/E:
Recently Max has got himself into popular CCG "BrainStone". As "BrainStone" is a pretty intellectual game, Max has to solve numerous hard problems during the gameplay. Here is one of them:

Max owns n creatures, i-th of them can be described with two numbers — its health hp_{i} and its damage dmg_{i}. Max also has two types of spells in stock:  Doubles health of the creature (hp_{i} := hp_{i}·2);  Assigns value of health of the creature to its damage (dmg_{i} := hp_{i}).

Spell of first type can be used no more than a times in total, of the second type — no more than b times in total. Spell can be used on a certain creature multiple times. Spells can be used in arbitrary order. It isn't necessary to use all the spells.

Max is really busy preparing for his final exams, so he asks you to determine what is the maximal total damage of all creatures he can achieve if he uses spells in most optimal way.

-----Input-----

The first line contains three integers n, a, b (1 ≤ n ≤ 2·10^5, 0 ≤ a ≤ 20, 0 ≤ b ≤ 2·10^5) — the number of creatures, spells of the first type and spells of the second type, respectively.

The i-th of the next n lines contain two number hp_{i} and dmg_{i} (1 ≤ hp_{i}, dmg_{i} ≤ 10^9) — description of the i-th creature.

-----Output-----

Print single integer — maximum total damage creatures can deal.

-----Examples-----
Input
2 1 1
10 15
6 1

Output
27

Input
3 0 3
10 8
7 11
5 2

Output
26

-----Note-----

In the first example Max should use the spell of the first type on the second creature, then the spell of the second type on the same creature. Then total damage will be equal to 15 + 6·2 = 27.

In the second example Max should use the spell of the second type on the first creature, then the spell of the second type on the third creature. Total damage will be equal to 10 + 11 + 5 = 26.

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

# python3
from sys import stdin

def main():
    def parseints(line): return tuple(map(int, line.split()))
    def bdiff(creature): return max(0, creature[0] - creature[1])

    n, a, b = parseints(input())
    hand = list(map(parseints, stdin.readlines()))

    ans = sum(creature[1] for creature in hand)  # default damage
    if b:
        hand.sort(key=bdiff)

        best = 0
        if n > b:
            lost = bdiff(hand[n - b])
            for creature in hand[:n-b]:
                best = max(best, (creature[0] << a) - creature[1] - lost)

        for creature in hand[max(0,n-b):]:
            best = max(best, (creature[0] << a) - max(creature))
            ans += bdiff(creature)
        ans += best

    print(ans)

main()


I found an interesting problem on https://codeforces.com/problemset/problem/977/A:
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm:  if the last digit of the number is non-zero, she decreases the number by one;  if the last digit of the number is zero, she divides the number by 10 (i.e. removes the last digit).

You are given an integer number $n$. Tanya will subtract one from it $k$ times. Your task is to print the result after all $k$ subtractions.

It is guaranteed that the result will be positive integer number.

-----Input-----

The first line of the input contains two integer numbers $n$ and $k$ ($2 \le n \le 10^9$, $1 \le k \le 50$) — the number from which Tanya will subtract and the number of subtractions correspondingly.

-----Output-----

Print one integer number — the result of the decreasing $n$ by one $k$ times.

It is guaranteed that the result will be positive integer number.

-----Examples-----
Input
512 4

Output
50

Input
1000000000 9

Output
1

-----Note-----

The first example corresponds to the following sequence: $512 \rightarrow 511 \rightarrow 510 \rightarrow 51 \rightarrow 50$.

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/977/B:
Two-gram is an ordered pair (i.e. string of length two) of capital Latin letters. For example, "AZ", "AA", "ZA" — three distinct two-grams.

You are given a string $s$ consisting of $n$ capital Latin letters. Your task is to find any two-gram contained in the given string as a substring (i.e. two consecutive characters of the string) maximal number of times. For example, for string $s$ = "BBAABBBA" the answer is two-gram "BB", which contained in $s$ three times. In other words, find any most frequent two-gram.

Note that occurrences of the two-gram can overlap with each other.

-----Input-----

The first line of the input contains integer number $n$ ($2 \le n \le 100$) — the length of string $s$. The second line of the input contains the string $s$ consisting of $n$ capital Latin letters.

-----Output-----

Print the only line containing exactly two capital Latin letters — any two-gram contained in the given string $s$ as a substring (i.e. two consecutive characters of the string) maximal number of times.

-----Examples-----
Input
7
ABACABA

Output
AB

Input
5
ZZZAA

Output
ZZ

-----Note-----

In the first example "BA" is also valid answer.

In the second example the only two-gram "ZZ" can be printed because it contained in the string "ZZZAA" two times.

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

n = int(input())
s = input()
a = [[0] * 26 for _ in range(26)]
for i in range(n -1):
    a[ord(s[i]) - ord('A')][ord(s[i + 1]) - ord('A')] += 1

mx = -1

for i in range(26):
    for j in range(26):
        if a[i][j] > mx:
            mx = a[i][j]
            ans = chr(i + ord('A')) + chr(j + ord('A'))

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/977/C:
You are given a sequence of integers of length $n$ and integer number $k$. You should print any integer number $x$ in the range of $[1; 10^9]$ (i.e. $1 \le x \le 10^9$) such that exactly $k$ elements of given sequence are less than or equal to $x$.

Note that the sequence can contain equal elements.

If there is no such $x$, print "-1" (without quotes).

-----Input-----

The first line of the input contains integer numbers $n$ and $k$ ($1 \le n \le 2 \cdot 10^5$, $0 \le k \le n$). The second line of the input contains $n$ integer numbers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$) — the sequence itself.

-----Output-----

Print any integer number $x$ from range $[1; 10^9]$ such that exactly $k$ elements of given sequence is less or equal to $x$.

If there is no such $x$, print "-1" (without quotes).

-----Examples-----
Input
7 4
3 7 5 1 10 3 20

Output
6
Input
7 2
3 7 5 1 10 3 20

Output
-1

-----Note-----

In the first example $5$ is also a valid answer because the elements with indices $[1, 3, 4, 6]$ is less than or equal to $5$ and obviously less than or equal to $6$.

In the second example you cannot choose any number that only $2$ elements of the given sequence will be less than or equal to this number because $3$ elements of the given sequence will be also less than or equal to this number.

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

n,k=map(int,input().split())
arr=list(map(int,input().split()))
arr.sort()
if k==0:
    if arr[0]==1:
        print(-1)
    else:
        print(arr[0]-1)
elif k<n and arr[k-1]==arr[k]:
    print(-1)
else:
    print(arr[k-1])


I found an interesting problem on https://codeforces.com/problemset/problem/977/D:
Polycarp likes to play with numbers. He takes some integer number $x$, writes it down on the board, and then performs with it $n - 1$ operations of the two kinds:   divide the number $x$ by $3$ ($x$ must be divisible by $3$);  multiply the number $x$ by $2$.

After each operation, Polycarp writes down the result on the board and replaces $x$ by the result. So there will be $n$ numbers on the board after all.

You are given a sequence of length $n$ — the numbers that Polycarp wrote down. This sequence is given in arbitrary order, i.e. the order of the sequence can mismatch the order of the numbers written on the board.

Your problem is to rearrange (reorder) elements of this sequence in such a way that it can match possible Polycarp's game in the order of the numbers written on the board. I.e. each next number will be exactly two times of the previous number or exactly one third of previous number.

It is guaranteed that the answer exists.

-----Input-----

The first line of the input contatins an integer number $n$ ($2 \le n \le 100$) — the number of the elements in the sequence. The second line of the input contains $n$ integer numbers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 3 \cdot 10^{18}$) — rearranged (reordered) sequence that Polycarp can wrote down on the board.

-----Output-----

Print $n$ integer numbers — rearranged (reordered) input sequence that can be the sequence that Polycarp could write down on the board.

It is guaranteed that the answer exists.

-----Examples-----
Input
6
4 8 6 3 12 9

Output
9 3 6 12 4 8

Input
4
42 28 84 126

Output
126 42 84 28

Input
2
1000000000000000000 3000000000000000000

Output
3000000000000000000 1000000000000000000

-----Note-----

In the first example the given sequence can be rearranged in the following way: $[9, 3, 6, 12, 4, 8]$. It can match possible Polycarp's game which started with $x = 9$.

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

def f(x):
    nonlocal a
    if len(ans) == n:
        print(' '.join(map(str, ans)))
        return
    if x % 3 == 0 and x // 3 in a:
        ans.append(x // 3)
        f(x // 3)
        ans.pop()
    if x * 2 in a:
        ans.append(x * 2)
        f(x * 2)
        ans.pop()

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

ans = []
for i in range(n):
    ans.append(a[i])
    f(a[i])
    ans.pop()


I found an interesting problem on https://codeforces.com/problemset/problem/977/E:
You are given an undirected graph consisting of $n$ vertices and $m$ edges. Your task is to find the number of connected components which are cycles.

Here are some definitions of graph theory.

An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex $a$ is connected with a vertex $b$, a vertex $b$ is also connected with a vertex $a$). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.

Two vertices $u$ and $v$ belong to the same connected component if and only if there is at least one path along edges connecting $u$ and $v$.

A connected component is a cycle if and only if its vertices can be reordered in such a way that:  the first vertex is connected with the second vertex by an edge,  the second vertex is connected with the third vertex by an edge,  ...  the last vertex is connected with the first vertex by an edge,  all the described edges of a cycle are distinct.

A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices. [Image] There are $6$ connected components, $2$ of them are cycles: $[7, 10, 16]$ and $[5, 11, 9, 15]$.

-----Input-----

The first line contains two integer numbers $n$ and $m$ ($1 \le n \le 2 \cdot 10^5$, $0 \le m \le 2 \cdot 10^5$) — number of vertices and edges.

The following $m$ lines contains edges: edge $i$ is given as a pair of vertices $v_i$, $u_i$ ($1 \le v_i, u_i \le n$, $u_i \ne v_i$). There is no multiple edges in the given graph, i.e. for each pair ($v_i, u_i$) there no other pairs ($v_i, u_i$) and ($u_i, v_i$) in the list of edges.

-----Output-----

Print one integer — the number of connected components which are also cycles.

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

Output
1

Input
17 15
1 8
1 12
5 11
11 9
9 15
15 5
4 13
3 13
4 3
10 16
7 10
16 7
14 3
14 4
17 6

Output
2

-----Note-----

In the first example only component $[3, 4, 5]$...

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

def dfs(v, g, vis):
    count = 1
    first = v
    st = [v]
    vis[v] = True
    while st:
        v = st[-1]
        st.pop()
        if len(g[v]) != 2 or vis[g[v][0]] and vis[g[v][1]] and g[v][0] != first and g[v][1] != first:
            count = 0
        for i in range(len(g[v])):
            if not vis[g[v][i]]:
                vis[g[v][i]] = True
                st.append(g[v][i])
                if v == first and count:
                    break
    if len(g[first]) == 2 and not vis[g[first][1]]:
        st.append(g[first][1])
        while st:
            v = st[-1]
            st.pop()
            for i in range(len(g[v])):
                if not vis[g[v][i]]:
                    vis[g[v][i]] = True
                    st.append(g[v][i])
    return count

v, e = list(map(int, input().split()))
g = [[] for i in range(v)]
for i in range(e):
    f, to = list(map(int, input().split()))
    g[f-1].append(to-1)
    g[to-1].append(f-1)
vis = [False] * v
ans = 0
for i in range(v):
    if not vis[i]:
        ans += dfs(i, g, vis)
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/977/F:
You are given an integer array of length $n$.

You have to choose some subsequence of this array of maximum length such that this subsequence forms a increasing sequence of consecutive integers. In other words the required sequence should be equal to $[x, x + 1, \dots, x + k - 1]$ for some value $x$ and length $k$.

Subsequence of an array can be obtained by erasing some (possibly zero) elements from the array. You can erase any elements, not necessarily going successively. The remaining elements preserve their order. For example, for the array $[5, 3, 1, 2, 4]$ the following arrays are subsequences: $[3]$, $[5, 3, 1, 2, 4]$, $[5, 1, 4]$, but the array $[1, 3]$ is not.

-----Input-----

The first line of the input containing integer number $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of the array. The second line of the input containing $n$ integer numbers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$) — the array itself.

-----Output-----

On the first line print $k$ — the maximum length of the subsequence of the given array that forms an increasing sequence of consecutive integers.

On the second line print the sequence of the indices of the any maximum length subsequence of the given array that forms an increasing sequence of consecutive integers.

-----Examples-----
Input
7
3 3 4 7 5 6 8

Output
4
2 3 5 6

Input
6
1 3 5 2 4 6

Output
2
1 4

Input
4
10 9 8 7

Output
1
1

Input
9
6 7 8 3 4 5 9 10 11

Output
6
1 2 3 7 8 9

-----Note-----

All valid answers for the first example (as sequences of indices):   $[1, 3, 5, 6]$  $[2, 3, 5, 6]$

All valid answers for the second example:   $[1, 4]$  $[2, 5]$  $[3, 6]$

All valid answers for the third example:   $[1]$  $[2]$  $[3]$  $[4]$

All valid answers for the fourth example:   $[1, 2, 3, 7, 8, 9]$

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

n = int(input())
G = list(map(int,input().split()))
D = {}
M = 0
for i in G:
    if i-1 in D:
        D[i] = D[i-1] + 1
    else:
        D[i] = 1
    if D[i]>M:
        M = D[i]
        Mi = i
#print(M,Mi)
R = []
A = Mi
for i in range(len(G)-1,-1,-1):
    if G[i] == A:
        R.append(i+1)
        A-=1
print(M)
print(*R[::-1])


I found an interesting problem on https://codeforces.com/problemset/problem/978/A:
Petya has an array $a$ consisting of $n$ integers. He wants to remove duplicate (equal) elements.

Petya wants to leave only the rightmost entry (occurrence) for each element of the array. The relative order of the remaining unique elements should not be changed.

-----Input-----

The first line contains a single integer $n$ ($1 \le n \le 50$) — the number of elements in Petya's array.

The following line contains a sequence $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1\,000$) — the Petya's array.

-----Output-----

In the first line print integer $x$ — the number of elements which will be left in Petya's array after he removed the duplicates.

In the second line print $x$ integers separated with a space — Petya's array after he removed the duplicates. For each unique element only the rightmost entry should be left.

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

Output
3
5 6 1

Input
5
2 4 2 4 4

Output
2
2 4

Input
5
6 6 6 6 6

Output
1
6

-----Note-----

In the first example you should remove two integers $1$, which are in the positions $1$ and $4$. Also you should remove the integer $5$, which is in the position $2$.

In the second example you should remove integer $2$, which is in the position $1$, and two integers $4$, which are in the positions $2$ and $4$.

In the third example you should remove four integers $6$, which are in the positions $1$, $2$, $3$ and $4$.

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

n=int(input())
l=list(map(int,input().split()))
v=[]
l.reverse()
for i in l:
      if i not in v:
            v.append(i)
v.reverse()
print(len(v))
for i in v:
      print(i,end=" ")


I found an interesting problem on https://codeforces.com/problemset/problem/978/B:
You can not just take the file and send it. When Polycarp trying to send a file in the social network "Codehorses", he encountered an unexpected problem. If the name of the file contains three or more "x" (lowercase Latin letters "x") in a row, the system considers that the file content does not correspond to the social network topic. In this case, the file is not sent and an error message is displayed.

Determine the minimum number of characters to remove from the file name so after that the name does not contain "xxx" as a substring. Print 0 if the file name does not initially contain a forbidden substring "xxx".

You can delete characters in arbitrary positions (not necessarily consecutive). If you delete a character, then the length of a string is reduced by $1$. For example, if you delete the character in the position $2$ from the string "exxxii", then the resulting string is "exxii".

-----Input-----

The first line contains integer $n$ $(3 \le n \le 100)$ — the length of the file name.

The second line contains a string of length $n$ consisting of lowercase Latin letters only — the file name.

-----Output-----

Print the minimum number of characters to remove from the file name so after that the name does not contain "xxx" as a substring. If initially the file name dost not contain a forbidden substring "xxx", print 0.

-----Examples-----
Input
6
xxxiii

Output
1

Input
5
xxoxx

Output
0

Input
10
xxxxxxxxxx

Output
8

-----Note-----

In the first example Polycarp tried to send a file with name contains number $33$, written in Roman numerals. But he can not just send the file, because it name contains three letters "x" in a row. To send the file he needs to remove any one of this letters.

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

n=int(input())
c,o=0,0
for i in input():
    if i=='x':
        c+=1
    else:
        c=0
    if c>=3:
        o+=1
print(o)


I found an interesting problem on https://codeforces.com/problemset/problem/978/C:
There are $n$ dormitories in Berland State University, they are numbered with integers from $1$ to $n$. Each dormitory consists of rooms, there are $a_i$ rooms in $i$-th dormitory. The rooms in $i$-th dormitory are numbered from $1$ to $a_i$.

A postman delivers letters. Sometimes there is no specific dormitory and room number in it on an envelope. Instead of it only a room number among all rooms of all $n$ dormitories is written on an envelope. In this case, assume that all the rooms are numbered from $1$ to $a_1 + a_2 + \dots + a_n$ and the rooms of the first dormitory go first, the rooms of the second dormitory go after them and so on.

For example, in case $n=2$, $a_1=3$ and $a_2=5$ an envelope can have any integer from $1$ to $8$ written on it. If the number $7$ is written on an envelope, it means that the letter should be delivered to the room number $4$ of the second dormitory.

For each of $m$ letters by the room number among all $n$ dormitories, determine the particular dormitory and the room number in a dormitory where this letter should be delivered.

-----Input-----

The first line contains two integers $n$ and $m$ $(1 \le n, m \le 2 \cdot 10^{5})$ — the number of dormitories and the number of letters.

The second line contains a sequence $a_1, a_2, \dots, a_n$ $(1 \le a_i \le 10^{10})$, where $a_i$ equals to the number of rooms in the $i$-th dormitory. The third line contains a sequence $b_1, b_2, \dots, b_m$ $(1 \le b_j \le a_1 + a_2 + \dots + a_n)$, where $b_j$ equals to the room number (among all rooms of all dormitories) for the $j$-th letter. All $b_j$ are given in increasing order.

-----Output-----

Print $m$ lines. For each letter print two integers $f$ and $k$ — the dormitory number $f$ $(1 \le f \le n)$ and the room number $k$ in this dormitory $(1 \le k \le a_f)$ to deliver the letter.

-----Examples-----
Input
3 6
10 15 12
1 9 12 23 26 37

Output
1 1
1 9
2 2
2 13
3 1
3 12

Input
2 3
5 10000000000
5 6 9999999999

Output
1 5
2 1
2 9999999994

-----Note-----

In the first example...

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

def main():
    n, m = list(map(int, input().split()))
    room = [int(x) for x in input().split()]
    letter = [int(x) for x in input().split()]

    room_num = 0
    j = 0
    for d in range(n):
        while j < m and letter[j] <= room_num + room[d]:
            r = letter[j] - room_num
            print(d+1, r)
            j += 1
        room_num += room[d]

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/978/D:
Polycarp likes arithmetic progressions. A sequence $[a_1, a_2, \dots, a_n]$ is called an arithmetic progression if for each $i$ ($1 \le i < n$) the value $a_{i+1} - a_i$ is the same. For example, the sequences $[42]$, $[5, 5, 5]$, $[2, 11, 20, 29]$ and $[3, 2, 1, 0]$ are arithmetic progressions, but $[1, 0, 1]$, $[1, 3, 9]$ and $[2, 3, 1]$ are not.

It follows from the definition that any sequence of length one or two is an arithmetic progression.

Polycarp found some sequence of positive integers $[b_1, b_2, \dots, b_n]$. He agrees to change each element by at most one. In the other words, for each element there are exactly three options: an element can be decreased by $1$, an element can be increased by $1$, an element can be left unchanged.

Determine a minimum possible number of elements in $b$ which can be changed (by exactly one), so that the sequence $b$ becomes an arithmetic progression, or report that it is impossible.

It is possible that the resulting sequence contains element equals $0$.

-----Input-----

The first line contains a single integer $n$ $(1 \le n \le 100\,000)$ — the number of elements in $b$.

The second line contains a sequence $b_1, b_2, \dots, b_n$ $(1 \le b_i \le 10^{9})$.

-----Output-----

If it is impossible to make an arithmetic progression with described operations, print -1. In the other case, print non-negative integer — the minimum number of elements to change to make the given sequence becomes an arithmetic progression. The only allowed operation is to add/to subtract one from an element (can't use operation twice to the same position).

-----Examples-----
Input
4
24 21 14 10

Output
3

Input
2
500 500

Output
0

Input
3
14 5 1

Output
-1

Input
5
1 3 6 9 12

Output
1

-----Note-----

In the first example Polycarp should increase the first number on $1$, decrease the second number on $1$, increase the third number on $1$, and the fourth number should left unchanged. So, after Polycarp changed three elements by one, his sequence became equals to $[25, 20, 15, 10]$,...

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

import itertools

def read_ints():
    return list(map(int, input().strip().split()))

def read_int():
    return read_ints()[0]

def check(nums, step, pre):
    suma = 0
    # print("Start: ", step)
    for x in nums:
        s = pre-x
        # print(pre, x, s)
        if abs(step-s) > 1:
            # print("BAD")
            raise Exception()
        if step == s:
            pre = x
            continue
        suma += 1
        if pre-(x+1) == step:
            pre = x+1
        else:
            pre = x-1
    # print("OK ", suma)
    return suma

def main():
    n = read_int()
    nums = read_ints()
    if n <= 2:
        print(0)
        return

    suma  = 100000000
    for x, y in itertools.product([-1,0,1], [-1,0,1]):
        a = nums[0]+x
        b = nums[1]+y
        diff = a-b
        try:
            # print(x,y)
            suma = min(suma, check(nums[2:], diff, b)+abs(x)+abs(y))
        except Exception as e:
            # print(repr(e))
            pass

    if suma == 100000000:
        print(-1)
    else:
        print(suma)

main()


I found an interesting problem on https://codeforces.com/problemset/problem/978/E:
The busses in Berland are equipped with a video surveillance system. The system records information about changes in the number of passengers in a bus after stops.

If $x$ is the number of passengers in a bus just before the current bus stop and $y$ is the number of passengers in the bus just after current bus stop, the system records the number $y-x$. So the system records show how number of passengers changed.

The test run was made for single bus and $n$ bus stops. Thus, the system recorded the sequence of integers $a_1, a_2, \dots, a_n$ (exactly one number for each bus stop), where $a_i$ is the record for the bus stop $i$. The bus stops are numbered from $1$ to $n$ in chronological order.

Determine the number of possible ways how many people could be in the bus before the first bus stop, if the bus has a capacity equals to $w$ (that is, at any time in the bus there should be from $0$ to $w$ passengers inclusive).

-----Input-----

The first line contains two integers $n$ and $w$ $(1 \le n \le 1\,000, 1 \le w \le 10^{9})$ — the number of bus stops and the capacity of the bus.

The second line contains a sequence $a_1, a_2, \dots, a_n$ $(-10^{6} \le a_i \le 10^{6})$, where $a_i$ equals to the number, which has been recorded by the video system after the $i$-th bus stop.

-----Output-----

Print the number of possible ways how many people could be in the bus before the first bus stop, if the bus has a capacity equals to $w$. If the situation is contradictory (i.e. for any initial number of passengers there will be a contradiction), print 0.

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

Output
3

Input
2 4
-1 1

Output
4

Input
4 10
2 4 1 2

Output
2

-----Note-----

In the first example initially in the bus could be $0$, $1$ or $2$ passengers.

In the second example initially in the bus could be $1$, $2$, $3$ or $4$ passengers.

In the third example initially in the bus could be $0$ or $1$ passenger.

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

stops,m = list(map(int,input().split()))
people = [int(i) for i in input().split()]

cM = 0
cm = 0
c = 0
for i in range(stops):
    c += people[i]
    if c > cM:
        cM = c
    if c <cm:
        cm = c

print(m-cM+cm+1 if m-cM+cm+1>=1 else 0)


I found an interesting problem on https://codeforces.com/problemset/problem/978/F:
In BerSoft $n$ programmers work, the programmer $i$ is characterized by a skill $r_i$.

A programmer $a$ can be a mentor of a programmer $b$ if and only if the skill of the programmer $a$ is strictly greater than the skill of the programmer $b$ $(r_a > r_b)$ and programmers $a$ and $b$ are not in a quarrel.

You are given the skills of each programmers and a list of $k$ pairs of the programmers, which are in a quarrel (pairs are unordered). For each programmer $i$, find the number of programmers, for which the programmer $i$ can be a mentor.

-----Input-----

The first line contains two integers $n$ and $k$ $(2 \le n \le 2 \cdot 10^5$, $0 \le k \le \min(2 \cdot 10^5, \frac{n \cdot (n - 1)}{2}))$ — total number of programmers and number of pairs of programmers which are in a quarrel.

The second line contains a sequence of integers $r_1, r_2, \dots, r_n$ $(1 \le r_i \le 10^{9})$, where $r_i$ equals to the skill of the $i$-th programmer.

Each of the following $k$ lines contains two distinct integers $x$, $y$ $(1 \le x, y \le n$, $x \ne y)$ — pair of programmers in a quarrel. The pairs are unordered, it means that if $x$ is in a quarrel with $y$ then $y$ is in a quarrel with $x$. Guaranteed, that for each pair $(x, y)$ there are no other pairs $(x, y)$ and $(y, x)$ in the input.

-----Output-----

Print $n$ integers, the $i$-th number should be equal to the number of programmers, for which the $i$-th programmer can be a mentor. Programmers are numbered in the same order that their skills are given in the input.

-----Examples-----
Input
4 2
10 4 10 15
1 2
4 3

Output
0 0 1 2

Input
10 4
5 4 1 5 4 3 7 1 2 5
4 6
2 1
10 8
3 5

Output
5 4 0 5 3 3 9 0 2 5

-----Note-----

In the first example, the first programmer can not be mentor of any other (because only the second programmer has a skill, lower than first programmer skill, but they are in a quarrel). The second programmer can not be mentor of any other programmer, because his skill is minimal among others. The third programmer can be a mentor of the...

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

from collections import defaultdict
n , k = input().split()
n , k = [ int(n) , int(k) ]
prog_power = defaultdict(set)
prog = []
for ind,x in enumerate(input().split()) :
    prog_power[int(x)].add(ind+1)
    prog.append(int(x))

m = defaultdict(set)
for i in range(k) :
    a1 , a2 = input().split()
    a1 , a2 = [int(a1) , int(a2) ]
    if prog[a1-1] > prog[a2-1] :
        m[a1].add(a2)
    elif prog[a1-1] < prog[a2-1] :
        m[a2].add(a1)

power = {}
sum = n
for i in sorted(prog_power.keys() , reverse = True) :
    sum -= len(prog_power[i])
    power[i] = sum

for ind,i in enumerate(prog) :
    mentor = power[i] - len(m[ind+1])
    print(mentor,end = ' ')


I found an interesting problem on https://codeforces.com/problemset/problem/978/G:
Petya studies at university. The current academic year finishes with $n$ special days. Petya needs to pass $m$ exams in those special days. The special days in this problem are numbered from $1$ to $n$.

There are three values about each exam:  $s_i$ — the day, when questions for the $i$-th exam will be published,  $d_i$ — the day of the $i$-th exam ($s_i < d_i$),  $c_i$ — number of days Petya needs to prepare for the $i$-th exam. For the $i$-th exam Petya should prepare in days between $s_i$ and $d_i-1$, inclusive.

There are three types of activities for Petya in each day: to spend a day doing nothing (taking a rest), to spend a day passing exactly one exam or to spend a day preparing for exactly one exam. So he can't pass/prepare for multiple exams in a day. He can't mix his activities in a day. If he is preparing for the $i$-th exam in day $j$, then $s_i \le j < d_i$.

It is allowed to have breaks in a preparation to an exam and to alternate preparations for different exams in consecutive days. So preparation for an exam is not required to be done in consecutive days.

Find the schedule for Petya to prepare for all exams and pass them, or report that it is impossible.

-----Input-----

The first line contains two integers $n$ and $m$ $(2 \le n \le 100, 1 \le m \le n)$ — the number of days and the number of exams.

Each of the following $m$ lines contains three integers $s_i$, $d_i$, $c_i$ $(1 \le s_i < d_i \le n, 1 \le c_i \le n)$ — the day, when questions for the $i$-th exam will be given, the day of the $i$-th exam, number of days Petya needs to prepare for the $i$-th exam.

Guaranteed, that all the exams will be in different days. Questions for different exams can be given in the same day. It is possible that, in the day of some exam, the questions for other exams are given.

-----Output-----

If Petya can not prepare and pass all the exams, print -1. In case of positive answer, print $n$ integers, where the $j$-th number is:  $(m + 1)$, if the $j$-th day is a day of some exam (recall that in each...

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

n,m =map(int,input().split())
l = list()
out = [0] * n
for i in range(m):
    s1,d1,c1 = map(int,input().split())
    l.append((s1,d1,c1,i))
l.sort(key=lambda x:x[1])
can = True
for j in l:
    out[j[1] - 1] = m + 1
for i in l:
    c = i[2]
    for t in range(i[0],i[1]):
        if out[t - 1] == 0 and c > 0:
            out[t - 1] = i[3] + 1
            c -= 1
        if c == 0:
            break
    if c != 0:
        print(-1)
        can = False
        break

if can is True:
    print(" ".join(map(str,out)))


I found an interesting problem on https://codeforces.com/problemset/problem/979/A:
Katie, Kuro and Shiro are best friends. They have known each other since kindergarten. That's why they often share everything with each other and work together on some very hard problems.

Today is Shiro's birthday. She really loves pizza so she wants to invite her friends to the pizza restaurant near her house to celebrate her birthday, including her best friends Katie and Kuro.

She has ordered a very big round pizza, in order to serve her many friends. Exactly $n$ of Shiro's friends are here. That's why she has to divide the pizza into $n + 1$ slices (Shiro also needs to eat). She wants the slices to be exactly the same size and shape. If not, some of her friends will get mad and go home early, and the party will be over.

Shiro is now hungry. She wants to cut the pizza with minimum of straight cuts. A cut is a straight segment, it might have ends inside or outside the pizza. But she is too lazy to pick up the calculator.

As usual, she will ask Katie and Kuro for help. But they haven't come yet. Could you help Shiro with this problem?

-----Input-----

A single line contains one non-negative integer $n$ ($0 \le n \leq 10^{18}$) — the number of Shiro's friends. The circular pizza has to be sliced into $n + 1$ pieces.

-----Output-----

A single integer — the number of straight cuts Shiro needs.

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

Output
2
Input
4

Output
5

-----Note-----

To cut the round pizza into quarters one has to make two cuts through the center with angle $90^{\circ}$ between them.

To cut the round pizza into five equal parts one has to make five cuts.

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

#!/usr/bin/env python3

n = int(input().strip())

if n == 0:
	print(0)
elif n % 2 == 1:
	print(n // 2 + 1)
else:
	print(n + 1)


I found an interesting problem on https://codeforces.com/problemset/problem/979/B:
After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.

The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.

A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $7$ because its subribbon a appears $7$ times, and the ribbon abcdabc has the beauty of $2$ because its subribbon abc appears twice.

The rules are simple. The game will have $n$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $n$ turns wins the treasure.

Could you find out who is going to be the winner if they all play optimally?

-----Input-----

The first line contains an integer $n$ ($0 \leq n \leq 10^{9}$) — the number of turns.

Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than $10^{5}$ uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors.

-----Output-----

Print the name of the winner...

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

n = int(input())
s1 = input().strip()
s2 = input().strip()
s3 = input().strip()
d1 = [0 for _ in range(52)]
d2 = [0 for _ in range(52)]
d3 = [0 for _ in range(52)]

maxi1 = 0
maxi2 = 0
maxi3 = 0

for i in s1:
    if ord(i) <= 90:
        j = ord(i) - 65
    else:
        j = ord(i) - 97 + 26
    d1[j] += 1
maxi1 = max(d1)
for i in s2:
    if ord(i) <= 90:
        j = ord(i) - 65
    else:
        j = ord(i) - 97 + 26
    d2[j] += 1
maxi2 = max(d2)
for i in s3:
    if ord(i) <= 90:
        j = ord(i) - 65
    else:
        j = ord(i) - 97 + 26
    d3[j] += 1
maxi3 = max(d3)

if maxi1 + n <= len(s1):
    maxi1 += n
else:
    if n == 1:
        maxi1 = len(s1) - 1
    else:
        maxi1 = len(s1)

if maxi2 + n <= len(s1):
    maxi2 += n
else:
    if n == 1:
        maxi2 = len(s1) - 1
    else:
        maxi2 = len(s1)

if maxi3 + n <= len(s1):
    maxi3 += n
else:
    if n == 1:
        maxi3 = len(s1) - 1
    else:
        maxi3 = len(s1)

if maxi1 > maxi2 and maxi1 > maxi3:
    print('Kuro')
elif maxi2 > maxi1 and maxi2 > maxi3:
    print('Shiro')
elif maxi3 > maxi1 and maxi3 > maxi2:
    print('Katie')
else:
    print('Draw')


I found an interesting problem on https://codeforces.com/problemset/problem/979/C:
Kuro is living in a country called Uberland, consisting of $n$ towns, numbered from $1$ to $n$, and $n - 1$ bidirectional roads connecting these towns. It is possible to reach each town from any other. Each road connects two towns $a$ and $b$. Kuro loves walking and he is planning to take a walking marathon, in which he will choose a pair of towns $(u, v)$ ($u \neq v$) and walk from $u$ using the shortest path to $v$ (note that $(u, v)$ is considered to be different from $(v, u)$).

Oddly, there are 2 special towns in Uberland named Flowrisa (denoted with the index $x$) and Beetopia (denoted with the index $y$). Flowrisa is a town where there are many strong-scent flowers, and Beetopia is another town where many bees live. In particular, Kuro will avoid any pair of towns $(u, v)$ if on the path from $u$ to $v$, he reaches Beetopia after he reached Flowrisa, since the bees will be attracted with the flower smell on Kuro’s body and sting him.

Kuro wants to know how many pair of city $(u, v)$ he can take as his route. Since he’s not really bright, he asked you to help him with this problem.

-----Input-----

The first line contains three integers $n$, $x$ and $y$ ($1 \leq n \leq 3 \cdot 10^5$, $1 \leq x, y \leq n$, $x \ne y$) - the number of towns, index of the town Flowrisa and index of the town Beetopia, respectively.

$n - 1$ lines follow, each line contains two integers $a$ and $b$ ($1 \leq a, b \leq n$, $a \ne b$), describes a road connecting two towns $a$ and $b$.

It is guaranteed that from each town, we can reach every other town in the city using the given roads. That is, the given map of towns and roads is a tree.

-----Output-----

A single integer resembles the number of pair of towns $(u, v)$ that Kuro can use as his walking route.

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

Output
5
Input
3 1 3
1 2
1 3

Output
4

-----Note-----

On the first example, Kuro can choose these pairs:   $(1, 2)$: his route would be $1 \rightarrow 2$,  $(2, 3)$: his route would be $2 \rightarrow 3$,  $(3, 2)$: his route...

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

from collections import defaultdict

n,x,y = list(map(int,input().split()))
graph = defaultdict(list)
vis = [False for i in range(n+1)]
mat = [False for i in range(n+1)]
subtree = [0 for i in range(n+1)]

for i in range(n-1):
	u,v = list(map(int,input().split()))
	graph[u].append(v)
	graph[v].append(u)
q = []
cur = 0
for v in graph[x]:
	if v!=y:
		q.append([v,v])
	else:
		cur = v
vis[x] = 1
while q!=[]:
	temp = q.pop()
	u,v = temp
	vis[u] = True
	subtree[v]+=1
	for node in graph[u]:
		if vis[node]==False:
			if node!=y:
				q.append([node,v])
			else:
				cur = v
val = sum(subtree)
val1 = (val+1-subtree[cur])
val2 = n-(sum(subtree)+1)
val = val1*val2
print(n*(n-1)-val)


I found an interesting problem on https://codeforces.com/problemset/problem/979/E:
Kuro has recently won the "Most intelligent cat ever" contest. The three friends then decided to go to Katie's home to celebrate Kuro's winning. After a big meal, they took a small break then started playing games.

Kuro challenged Katie to create a game with only a white paper, a pencil, a pair of scissors and a lot of arrows (you can assume that the number of arrows is infinite). Immediately, Katie came up with the game called Topological Parity.

The paper is divided into $n$ pieces enumerated from $1$ to $n$. Shiro has painted some pieces with some color. Specifically, the $i$-th piece has color $c_{i}$ where $c_{i} = 0$ defines black color, $c_{i} = 1$ defines white color and $c_{i} = -1$ means that the piece hasn't been colored yet.

The rules of the game is simple. Players must put some arrows between some pairs of different pieces in such a way that for each arrow, the number in the piece it starts from is less than the number of the piece it ends at. Also, two different pieces can only be connected by at most one arrow. After that the players must choose the color ($0$ or $1$) for each of the unpainted pieces. The score of a valid way of putting the arrows and coloring pieces is defined as the number of paths of pieces of alternating colors. For example, $[1 \to 0 \to 1 \to 0]$, $[0 \to 1 \to 0 \to 1]$, $[1]$, $[0]$ are valid paths and will be counted. You can only travel from piece $x$ to piece $y$ if and only if there is an arrow from $x$ to $y$.

But Kuro is not fun yet. He loves parity. Let's call his favorite parity $p$ where $p = 0$ stands for "even" and $p = 1$ stands for "odd". He wants to put the arrows and choose colors in such a way that the score has the parity of $p$.

It seems like there will be so many ways which satisfy Kuro. He wants to count the number of them but this could be a very large number. Let's help him with his problem, but print it modulo $10^{9} + 7$.

-----Input-----

The first line contains two integers $n$ and $p$ ($1 \leq n \leq 50$, $0 \leq p \leq 1$) — the number...

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/980/A:
A necklace can be described as a string of links ('-') and pearls ('o'), with the last link or pearl connected to the first one. $0$

You can remove a link or a pearl and insert it between two other existing links or pearls (or between a link and a pearl) on the necklace. This process can be repeated as many times as you like, but you can't throw away any parts.

Can you make the number of links between every two adjacent pearls equal? Two pearls are considered to be adjacent if there is no other pearl between them.

Note that the final necklace should remain as one circular part of the same length as the initial necklace.

-----Input-----

The only line of input contains a string $s$ ($3 \leq |s| \leq 100$), representing the necklace, where a dash '-' represents a link and the lowercase English letter 'o' represents a pearl.

-----Output-----

Print "YES" if the links and pearls can be rejoined such that the number of links between adjacent pearls is equal. Otherwise print "NO".

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

-----Examples-----
Input
-o-o--
Output
YES
Input
-o---

Output
YES
Input
-o---o-

Output
NO
Input
ooo

Output
YES

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

s = input()
t = s.count('o')
c = s.count('-')
if (t == 0 or c % t == 0):
    print("YES")
else:
    print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/980/C:
Professor Ibrahim has prepared the final homework for his algorithm’s class. He asked his students to implement the Posterization Image Filter.

Their algorithm will be tested on an array of integers, where the $i$-th integer represents the color of the $i$-th pixel in the image. The image is in black and white, therefore the color of each pixel will be an integer between 0 and 255 (inclusive).

To implement the filter, students are required to divide the black and white color range [0, 255] into groups of consecutive colors, and select one color in each group to be the group’s key. In order to preserve image details, the size of a group must not be greater than $k$, and each color should belong to exactly one group.

Finally, the students will replace the color of each pixel in the array with that color’s assigned group key.

To better understand the effect, here is an image of a basking turtle where the Posterization Filter was applied with increasing $k$ to the right.

 [Image]

To make the process of checking the final answer easier, Professor Ibrahim wants students to divide the groups and assign the keys in a way that produces the lexicographically smallest possible array.

-----Input-----

The first line of input contains two integers $n$ and $k$ ($1 \leq n \leq 10^5$, $1 \leq k \leq 256$), the number of pixels in the image, and the maximum size of a group, respectively.

The second line contains $n$ integers $p_1, p_2, \dots, p_n$ ($0 \leq p_i \leq 255$), where $p_i$ is the color of the $i$-th pixel.

-----Output-----

Print $n$ space-separated integers; the lexicographically smallest possible array that represents the image after applying the Posterization filter.

-----Examples-----
Input
4 3
2 14 3 4

Output
0 12 3 3

Input
5 2
0 2 1 255 254

Output
0 1 1 254 254

-----Note-----

One possible way to group colors and assign keys for the first sample:

Color $2$ belongs to the group $[0,2]$, with group key $0$.

Color $14$ belongs to the group $[12,14]$, with group key $12$.

Colors $3$ and...

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

#!/usr/bin/env python3

[n, k] = map(int, input().strip().split())
pis = list(map(int, input().strip().split()))

import sys
if k == 1:
	print (' '.join(map(str, pis)))
	return

N = 256
gamma = [-1 for _ in range(N)]
done = [False for _ in range(N)]
revdone = [False for _ in range(N)]
notset = 256
pends = {}

def get_bounds(i):
	try:
		l = N - 1 - revdone.index(True, N - 1 - i) + 1
	except ValueError:
		l = 0
	try:
		r = done.index(True, i) - 1
	except ValueError:
		r = N - 1
	return l, r

def set_gamma(l, r, v):
	for i in range(l, r + 1):
		gamma[i] = v
		done[i] = True
		revdone[N - 1 - i] = True

for p in pis:
	if not done[p]:
		lb, rb = get_bounds(p)
		if (lb > 0) and ((lb - 1) in pends) and (lb - 1 + pends[lb - 1] >= p):
			l = lb
			r = p
			set_gamma(l, r, gamma[lb - 1])
			if r - l + 1 < pends[lb - 1]:
				pends[r] = pends[lb - 1] - (r - l + 1)
			del pends[lb - 1]
		else:
			l = max(p - k + 1, lb)
			r = p
			set_gamma(l, r, l)
			if r - l + 1 < k:
				pends[p] = k - (r - l + 1)
		notset -= r - l + 1
		if notset == 0:
			break

if notset > 0:
	for i in range(N):
		if gamma[i] < 0:
			l, r = get_bounds(i)
			set_gamma(l, min(l + k - 1, r), l)

print (' '.join(str(gamma[p]) for p in pis))


I found an interesting problem on https://codeforces.com/problemset/problem/980/D:
SaMer has written the greatest test case of all time for one of his problems. For a given array of integers, the problem asks to find the minimum number of groups the array can be divided into, such that the product of any pair of integers in the same group is a perfect square.

Each integer must be in exactly one group. However, integers in a group do not necessarily have to be contiguous in the array.

SaMer wishes to create more cases from the test case he already has. His test case has an array $A$ of $n$ integers, and he needs to find the number of contiguous subarrays of $A$ that have an answer to the problem equal to $k$ for each integer $k$ between $1$ and $n$ (inclusive).

-----Input-----

The first line of input contains a single integer $n$ ($1 \leq n \leq 5000$), the size of the array.

The second line contains $n$ integers $a_1$,$a_2$,$\dots$,$a_n$ ($-10^8 \leq a_i \leq 10^8$), the values of the array.

-----Output-----

Output $n$ space-separated integers, the $k$-th integer should be the number of contiguous subarrays of $A$ that have an answer to the problem equal to $k$.

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

Output
3 0

Input
5
5 -4 2 1 8

Output
5 5 3 2 0

Input
1
0

Output
1

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/981/A:
A string is a palindrome if it reads the same from the left to the right and from the right to the left. For example, the strings "kek", "abacaba", "r" and "papicipap" are palindromes, while the strings "abb" and "iq" are not.

A substring $s[l \ldots r]$ ($1 \leq l \leq r \leq |s|$) of a string $s = s_{1}s_{2} \ldots s_{|s|}$ is the string $s_{l}s_{l + 1} \ldots s_{r}$.

Anna does not like palindromes, so she makes her friends call her Ann. She also changes all the words she reads in a similar way. Namely, each word $s$ is changed into its longest substring that is not a palindrome. If all the substrings of $s$ are palindromes, she skips the word at all.

Some time ago Ann read the word $s$. What is the word she changed it into?

-----Input-----

The first line contains a non-empty string $s$ with length at most $50$ characters, containing lowercase English letters only.

-----Output-----

If there is such a substring in $s$ that is not a palindrome, print the maximum length of such a substring. Otherwise print $0$.

Note that there can be multiple longest substrings that are not palindromes, but their length is unique.

-----Examples-----
Input
mew

Output
3

Input
wuffuw

Output
5

Input
qqqqqqqq

Output
0

-----Note-----

"mew" is not a palindrome, so the longest substring of it that is not a palindrome, is the string "mew" itself. Thus, the answer for the first example is $3$.

The string "uffuw" is one of the longest non-palindrome substrings (of length $5$) of the string "wuffuw", so the answer for the second example is $5$.

All substrings of the string "qqqqqqqq" consist of equal characters so they are palindromes. This way, there are no non-palindrome substrings. Thus, the answer for the third example is $0$.

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

def is_palindrome(ss):
    return ss == ss[::-1]

s = input().strip()
best = 0
for i in range(len(s)):
    for j in range(i + 1, len(s) + 1):
        if not is_palindrome(s[i:j]):
            best = max(best, j - i)
print(best)


I found an interesting problem on https://codeforces.com/problemset/problem/981/B:
Two famous competing companies ChemForces and TopChemist decided to show their sets of recently discovered chemical elements on an exhibition. However they know that no element should be present in the sets of both companies.

In order to avoid this representatives of both companies decided to make an agreement on the sets the companies should present. The sets should be chosen in the way that maximizes the total income of the companies.

All elements are enumerated with integers. The ChemForces company has discovered $n$ distinct chemical elements with indices $a_1, a_2, \ldots, a_n$, and will get an income of $x_i$ Berland rubles if the $i$-th element from this list is in the set of this company.

The TopChemist company discovered $m$ distinct chemical elements with indices $b_1, b_2, \ldots, b_m$, and it will get an income of $y_j$ Berland rubles for including the $j$-th element from this list to its set.

In other words, the first company can present any subset of elements from $\{a_1, a_2, \ldots, a_n\}$ (possibly empty subset), the second company can present any subset of elements from $\{b_1, b_2, \ldots, b_m\}$ (possibly empty subset). There shouldn't be equal elements in the subsets.

Help the representatives select the sets in such a way that no element is presented in both sets and the total income is the maximum possible.

-----Input-----

The first line contains a single integer $n$ ($1 \leq n \leq 10^5$)  — the number of elements discovered by ChemForces.

The $i$-th of the next $n$ lines contains two integers $a_i$ and $x_i$ ($1 \leq a_i \leq 10^9$, $1 \leq x_i \leq 10^9$)  — the index of the $i$-th element and the income of its usage on the exhibition. It is guaranteed that all $a_i$ are distinct.

The next line contains a single integer $m$ ($1 \leq m \leq 10^5$)  — the number of chemicals invented by TopChemist.

The $j$-th of the next $m$ lines contains two integers $b_j$ and $y_j$, ($1 \leq b_j \leq 10^9$, $1 \leq y_j \leq 10^9$)  — the index of the $j$-th element and the income of its...

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

n=int(input())
sum1=0
fo=dict()
for i in range(n):
    x,y=map(int,input().split())
    fo[x]=y
    sum1+=y
to=dict()
m=int(input())
for i in range(m):
    x,y=map(int,input().split())
    if(x in fo):
        if(fo[x]<y):
            sum1-=fo[x]
            sum1+=y
    else:
        sum1+=y
print(sum1)


I found an interesting problem on https://codeforces.com/problemset/problem/981/C:
Ramesses knows a lot about problems involving trees (undirected connected graphs without cycles)!

He created a new useful tree decomposition, but he does not know how to construct it, so he asked you for help!

The decomposition is the splitting the edges of the tree in some simple paths in such a way that each two paths have at least one common vertex. Each edge of the tree should be in exactly one path.

Help Remesses, find such a decomposition of the tree or derermine that there is no such decomposition.

-----Input-----

The first line contains a single integer $n$ ($2 \leq n \leq 10^{5}$) the number of nodes in the tree.

Each of the next $n - 1$ lines contains two integers $a_i$ and $b_i$ ($1 \leq a_i, b_i \leq n$, $a_i \neq b_i$) — the edges of the tree. It is guaranteed that the given edges form a tree.

-----Output-----

If there are no decompositions, print the only line containing "No".

Otherwise in the first line print "Yes", and in the second line print the number of paths in the decomposition $m$.

Each of the next $m$ lines should contain two integers $u_i$, $v_i$ ($1 \leq u_i, v_i \leq n$, $u_i \neq v_i$) denoting that one of the paths in the decomposition is the simple path between nodes $u_i$ and $v_i$.

Each pair of paths in the decomposition should have at least one common vertex, and each edge of the tree should be presented in exactly one path. You can print the paths and the ends of each path in arbitrary order.

If there are multiple decompositions, print any.

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

Output
Yes
1
1 4

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

Output
No

Input
5
1 2
1 3
1 4
1 5

Output
Yes
4
1 2
1 3
1 4
1 5

-----Note-----

The tree from the first example is shown on the picture below: [Image] The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.

The tree from the second example is shown on the picture below: [Image] We can show that there are no valid decompositions of...

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

n=int(input())
g=[0 for i in range(n)]
for i in range(n-1):
    a,b=map(int,input().split())
    g[a-1]+=1
    g[b-1]+=1
q=0
k=0
kind=0
m=0
for i in range(n):
    if g[i]==1:
        m+=1
    if g[i]>2:
        if g[i]>k:
            kind=i
            k=g[i]
        q+=1
if q>1:
    print('No')
else:
    print('Yes')
    if k>2:
        print(m)
        for i in range(n):
            if g[i]==1:
                print(kind+1,i+1)
    else:
        print(1)
        for i in range(n):
            if g[i]==1:
                print(i+1,end=' ')


I found an interesting problem on https://codeforces.com/problemset/problem/981/D:
Mr Keks is a typical white-collar in Byteland.

He has a bookshelf in his office with some books on it, each book has an integer positive price.

Mr Keks defines the value of a shelf as the sum of books prices on it.

Miraculously, Mr Keks was promoted and now he is moving into a new office.

He learned that in the new office he will have not a single bookshelf, but exactly $k$ bookshelves. He decided that the beauty of the $k$ shelves is the bitwise AND of the values of all the shelves.

He also decided that he won't spend time on reordering the books, so he will place several first books on the first shelf, several next books on the next shelf and so on. Of course, he will place at least one book on each shelf. This way he will put all his books on $k$ shelves in such a way that the beauty of the shelves is as large as possible. Compute this maximum possible beauty.

-----Input-----

The first line contains two integers $n$ and $k$ ($1 \leq k \leq n \leq 50$) — the number of books and the number of shelves in the new office.

The second line contains $n$ integers $a_1, a_2, \ldots a_n$, ($0 < a_i < 2^{50}$) — the prices of the books in the order they stand on the old shelf.

-----Output-----

Print the maximum possible beauty of $k$ shelves in the new office.

-----Examples-----
Input
10 4
9 14 28 1 7 13 15 29 2 31

Output
24

Input
7 3
3 14 15 92 65 35 89

Output
64

-----Note-----

In the first example you can split the books as follows:

$$(9 + 14 + 28 + 1 + 7) \& (13 + 15) \& (29 + 2) \& (31) = 24.$$

In the second example you can split the books as follows:

$$(3 + 14 + 15 + 92) \& (65) \& (35 + 89) = 64.$$

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

[n, k] = [int(x) for x in input().split()]
sum = [int(x) for x in input().split()]
for i in range(1, n):
    sum[i] += sum[i - 1]

def check(mask, all):
    dp = [[False for j in range(n)] for i in range(k)]
    for i in range(n):
        dp[0][i] = ((sum[i] & all & mask) == mask)
    for i in range(1, k):
        for j in range(n):
            dp[i][j] = any(dp[i - 1][p] and ((sum[j] - sum[p]) & all & mask) == mask for p in range(0, j))
    return dp[k - 1][n - 1]

ans = 0
for i in range(60, -1, -1):
    if(check(ans | (1 << i), ~((1 << i) - 1))):
       ans |= 1 << i
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/982/A:
You're given a row with $n$ chairs. We call a seating of people "maximal" if the two following conditions hold:  There are no neighbors adjacent to anyone seated.  It's impossible to seat one more person without violating the first rule.

The seating is given as a string consisting of zeros and ones ($0$ means that the corresponding seat is empty, $1$ — occupied). The goal is to determine whether this seating is "maximal".

Note that the first and last seats are not adjacent (if $n \ne 2$).

-----Input-----

The first line contains a single integer $n$ ($1 \leq n \leq 1000$) — the number of chairs.

The next line contains a string of $n$ characters, each of them is either zero or one, describing the seating.

-----Output-----

Output "Yes" (without quotation marks) if the seating is "maximal". Otherwise print "No".

You are allowed to print letters in whatever case you'd like (uppercase or lowercase).

-----Examples-----
Input
3
101

Output
Yes

Input
4
1011

Output
No

Input
5
10001

Output
No

-----Note-----

In sample case one the given seating is maximal.

In sample case two the person at chair three has a neighbour to the right.

In sample case three it is possible to seat yet another person into chair three.

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

n = int(input())
s = input()
ok = 1
for i in range(n):
	if s[i] == '1':
		if i > 0:
			ok &= s[i - 1] == '0'
		if i < n - 1:
			ok &= s[i + 1] == '0'
	else:
		res = 0
		if i > 0:
			res |= s[i - 1] == '1'
		if i < n - 1:
			res |= s[i + 1] == '1'
		ok &= res
print("Yes" if ok else "No")


I found an interesting problem on https://codeforces.com/problemset/problem/982/B:
In the Bus of Characters there are $n$ rows of seat, each having $2$ seats. The width of both seats in the $i$-th row is $w_i$ centimeters. All integers $w_i$ are distinct.

Initially the bus is empty. On each of $2n$ stops one passenger enters the bus. There are two types of passengers:   an introvert always chooses a row where both seats are empty. Among these rows he chooses the one with the smallest seats width and takes one of the seats in it;  an extrovert always chooses a row where exactly one seat is occupied (by an introvert). Among these rows he chooses the one with the largest seats width and takes the vacant place in it.

You are given the seats width in each row and the order the passengers enter the bus. Determine which row each passenger will take.

-----Input-----

The first line contains a single integer $n$ ($1 \le n \le 200\,000$) — the number of rows in the bus.

The second line contains the sequence of integers $w_1, w_2, \dots, w_n$ ($1 \le w_i \le 10^{9}$), where $w_i$ is the width of each of the seats in the $i$-th row. It is guaranteed that all $w_i$ are distinct.

The third line contains a string of length $2n$, consisting of digits '0' and '1' — the description of the order the passengers enter the bus. If the $j$-th character is '0', then the passenger that enters the bus on the $j$-th stop is an introvert. If the $j$-th character is '1', the the passenger that enters the bus on the $j$-th stop is an extrovert. It is guaranteed that the number of extroverts equals the number of introverts (i. e. both numbers equal $n$), and for each extrovert there always is a suitable row.

-----Output-----

Print $2n$ integers — the rows the passengers will take. The order of passengers should be the same as in input.

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

Output
2 1 1 2

Input
6
10 8 9 11 13 5
010010011101

Output
6 6 2 3 3 1 4 4 1 2 5 5

-----Note-----

In the first example the first passenger (introvert) chooses the row $2$, because it has the seats with smallest width. The second...

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

from collections import deque
def main():
    n = int(input())
    a = list(map(int, input().split()))
    s = input()
    b = []
    for i in range(n):
        b.append([a[i], i + 1])
    b.sort()
    ans = []
    count1, count2 = 0, 0
    c = deque([])
    for i in range(2 * n):
        if (s[i] == '0'):
            ans.append(b[count1][1])
            c.append(b[count1][1])
            count1 += 1
        else:
            ans.append(c[-1])
            c.pop()
            count2 += 1
    for i in range(2 * n):
        print(ans[i], end=' ')
main()


I found an interesting problem on https://codeforces.com/problemset/problem/982/C:
You're given a tree with $n$ vertices.

Your task is to determine the maximum possible number of edges that can be removed in such a way that all the remaining connected components will have even size.

-----Input-----

The first line contains an integer $n$ ($1 \le n \le 10^5$) denoting the size of the tree.

The next $n - 1$ lines contain two integers $u$, $v$ ($1 \le u, v \le n$) each, describing the vertices connected by the $i$-th edge.

It's guaranteed that the given edges form a tree.

-----Output-----

Output a single integer $k$ — the maximum number of edges that can be removed to leave all connected components with even size, or $-1$ if it is impossible to remove edges in order to satisfy this property.

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

Output
1
Input
3
1 2
1 3

Output
-1
Input
10
7 1
8 4
8 10
4 7
6 5
9 3
3 5
2 10
2 5

Output
4
Input
2
1 2

Output
0

-----Note-----

In the first example you can remove the edge between vertices $1$ and $4$. The graph after that will have two connected components with two vertices in each.

In the second example you can't remove edges in such a way that all components have even number of vertices, so the answer is $-1$.

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

n = int(input())
if n % 2 == 1:
    print(-1)
else:
    edges = [[] for i in range(n)]
    for i in range(n-1):
        [a,b] = [int(j) for j in input().split()]
        edges[a-1].append(b-1)
        edges[b-1].append(a-1)
    dfs_stack = [0]
    c = [1 for i in range(n)]
    visited = [-1 for i in range(n)]
    visited[0] = 0

    while dfs_stack != []:
        current_node = dfs_stack[-1]
        can_go_further = False
        for i in edges[current_node]:
            if visited[i] == -1:
                dfs_stack.append(i)
                visited[i] = current_node
                can_go_further = True
        if can_go_further == False:
            dfs_stack.pop(-1)
            c[visited[current_node]] += c[current_node]

    ans = 0
    for i in c[1:]:
        if i % 2 == 0:
            ans += 1
    print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/982/D:
For long time scientists study the behavior of sharks. Sharks, as many other species, alternate short movements in a certain location and long movements between locations.

Max is a young biologist. For $n$ days he watched a specific shark, and now he knows the distance the shark traveled in each of the days. All the distances are distinct. Max wants to know now how many locations the shark visited. He assumed there is such an integer $k$ that if the shark in some day traveled the distance strictly less than $k$, then it didn't change the location; otherwise, if in one day the shark traveled the distance greater than or equal to $k$; then it was changing a location in that day. Note that it is possible that the shark changed a location for several consecutive days, in each of them the shark traveled the distance at least $k$.

The shark never returned to the same location after it has moved from it. Thus, in the sequence of $n$ days we can find consecutive nonempty segments when the shark traveled the distance less than $k$ in each of the days: each such segment corresponds to one location. Max wants to choose such $k$ that the lengths of all such segments are equal.

Find such integer $k$, that the number of locations is as large as possible. If there are several such $k$, print the smallest one.

-----Input-----

The first line contains a single integer $n$ ($1 \leq n \leq 10^5$) — the number of days.

The second line contains $n$ distinct positive integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^9$) — the distance traveled in each of the day.

-----Output-----

Print a single integer $k$, such that   the shark was in each location the same number of days,  the number of locations is maximum possible satisfying the first condition,  $k$ is smallest possible satisfying the first and second conditions.

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

Output
7
Input
6
25 1 2 3 14 36

Output
2

-----Note-----

In the first example the shark travels inside a location on days $1$ and $2$ (first location),...

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

# https://codeforces.com/problemset/problem/982/D

class Union:
    def __init__(self, n):
        self.p    = {i:i for i in range(n)}
        self.rank = {i:1 for i in range(n)}

    def find(self, x):
        if x < 0: return x

        if self.p[x] != x:
            self.p[x] = self.find(self.p[x])

        return self.p[x]

    def union(self, x, y):
        if x < 0 or y < 0:return

        x = self.find(x)
        y = self.find(y)

        if x != y:
            if self.rank[x] < self.rank[y]:
                self.p[x]     = y
                self.rank[y] += self.rank[x]
            else:
                self.p[y]     = x
                self.rank[x] += self.rank[y]

def add(d, key, val):
    if key not in d:
        d[key] = 0
    d[key] += val

    if d[key] == 0:
        del d[key]

def update(i, used, d, u):
    used[i]  = True
    add(d, 1, 1)

    if  i - 1 >=  0 and used[i-1] == True:
        par_1   =  u.find(i)
        par_2   =  u.find(i-1)

        size_1  =  u.rank[par_1]
        size_2  =  u.rank[par_2]

        add(d, size_1, -1)
        add(d, size_2, -1)
        add(d, size_1+size_2, 1)

        u.union(par_1, par_2)

    if i + 1 < n and used[i+1] == True:
        par_1   =  u.find(i)
        par_2   =  u.find(i+1)

        size_1  =  u.rank[par_1]
        size_2  =  u.rank[par_2]

        add(d, size_1, -1)
        add(d, size_2, -1)
        add(d, size_1+size_2, 1)

        u.union(par_1, par_2)

n   = int(input())
a_  = list(map(int, input().split()))
a   = [(i, x) for i, x in enumerate(a_)]
a   = sorted(a, key=lambda x:x[1])

u    = Union(n)
d    = {}
used = [False] * n
ans        = -1
max_length = -1

for (index, val) in a:
    update(index, used, d, u)
    #print(d, val)

    if len(d) == 1:
        len_ = list(d.values())[0]

        if max_length < len_:
            max_length = len_
            ans        = val+1

print(ans)

#8
#1 12 2 11 10 3 9 4 8 5 14 6


I found an interesting problem on https://codeforces.com/problemset/problem/982/E:
Consider a billiard table of rectangular size $n \times m$ with four pockets. Let's introduce a coordinate system with the origin at the lower left corner (see the picture).  [Image]

There is one ball at the point $(x, y)$ currently. Max comes to the table and strikes the ball. The ball starts moving along a line that is parallel to one of the axes or that makes a $45^{\circ}$ angle with them. We will assume that:   the angles between the directions of the ball before and after a collision with a side are equal,  the ball moves indefinitely long, it only stops when it falls into a pocket,  the ball can be considered as a point, it falls into a pocket if and only if its coordinates coincide with one of the pockets,  initially the ball is not in a pocket.

Note that the ball can move along some side, in this case the ball will just fall into the pocket at the end of the side.

Your task is to determine whether the ball will fall into a pocket eventually, and if yes, which of the four pockets it will be.

-----Input-----

The only line contains $6$ integers $n$, $m$, $x$, $y$, $v_x$, $v_y$ ($1 \leq n, m \leq 10^9$, $0 \leq x \leq n$; $0 \leq y \leq m$; $-1 \leq v_x, v_y \leq 1$; $(v_x, v_y) \neq (0, 0)$) — the width of the table, the length of the table, the $x$-coordinate of the initial position of the ball, the $y$-coordinate of the initial position of the ball, the $x$-component of its initial speed and the $y$-component of its initial speed, respectively. It is guaranteed that the ball is not initially in a pocket.

-----Output-----

Print the coordinates of the pocket the ball will fall into, or $-1$ if the ball will move indefinitely.

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

Output
0 0
Input
4 4 2 0 1 1

Output
-1
Input
10 10 10 1 -1 0

Output
-1

-----Note-----

The first sample:  [Image]

The second sample:  [Image]

In the third sample the ball will never change its $y$ coordinate, so the ball will never fall into a pocket.

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

import fractions

def extendedEuclid(A, B):
	X = 0; Y = 0
	if B == 0:
		X = 1; Y = 0
	else:
		X, Y = extendedEuclid(B, A % B)
		temp = X
		X = Y; Y = temp - (A // B) * Y
	return X, Y

def DiophantusSolver(a, b, c):
	g = abs(fractions.gcd(a, b))
	if c % g != 0: return (10 ** 40, 10 ** 40)
	p, q = extendedEuclid(abs(a // g), abs(b // g))
	r11 = (p * c // g); r12 = (q * c // g)
	t1 = xi + r11 * n
	q, p = extendedEuclid(abs(b // g), abs(a // g))
	r21 = (p * c // g); r22 = (q * c // g)
	t2 = xi + r21 * n
	if (r11, r12) < (r21, r22): return r11, r12
	return r21, r22

n, m, x, y, vx, vy = map(int, input().split())

if vx * vy == 0:
	if vx == 0:
		if x > 0 and x < n: print('-1')
		elif vy < 0: print('{} 0'.format(x))
		elif vy > 0: print('{} {}'.format(x, m))
	elif vy == 0:
		if y > 0 and y < m: print('-1')
		elif vx < 0: print('0 {}'.format(y))
		elif vx > 0: print('{} {}'.format(n, y))
else:
	xi = x % n; yi = y % m
	LCM = (n * m // fractions.gcd(n, m))
	if vx > 0: xi = (n - x) % n
	if vy > 0: yi = (m - y) % m
	tx, ty = DiophantusSolver(n, -m, yi - xi)
	if (tx == 10 ** 40):
		print('-1')
	else:
		t = (xi + tx * n) % LCM
		while t < 0: t += LCM
		x1 = (x + t * vx) % (n * 2)
		while x1 < 0: x1 += (n * 2)
		y1 = (y + t * vy) % (m * 2)
		while y1 < 0: y1 += (m * 2)
		print(x1, y1)


I found an interesting problem on https://codeforces.com/problemset/problem/984/A:
Two players play a game.

Initially there are $n$ integers $a_1, a_2, \ldots, a_n$ written on the board. Each turn a player selects one number and erases it from the board. This continues until there is only one number left on the board, i. e. $n - 1$ turns are made. The first player makes the first move, then players alternate turns.

The first player wants to minimize the last number that would be left on the board, while the second player wants to maximize it.

You want to know what number will be left on the board after $n - 1$ turns if both players make optimal moves.

-----Input-----

The first line contains one integer $n$ ($1 \le n \le 1000$) — the number of numbers on the board.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 10^6$).

-----Output-----

Print one number that will be left on the board.

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

Output
2
Input
3
2 2 2

Output
2

-----Note-----

In the first sample, the first player erases $3$ and the second erases $1$. $2$ is left on the board.

In the second sample, $2$ is left on the board regardless of the actions of the players.

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

import sys
import io

stream_enable = 0

inpstream = """
3
2 1 3

"""

if stream_enable:
    sys.stdin = io.StringIO(inpstream)
    input()

def inpmap():
    return list(map(int, input().split()))

n = int(input())
arr = inpmap()
arr.sort()
print(arr[len(arr) // 2 - (1 - n % 2)])


I found an interesting problem on https://codeforces.com/problemset/problem/984/B:
One day Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won.

Alex has grown up since then, so he easily wins the most difficult levels. This quickly bored him, and he thought: what if the computer gave him invalid fields in the childhood and Alex could not win because of it?

He needs your help to check it.

A Minesweeper field is a rectangle $n \times m$, where each cell is either empty, or contains a digit from $1$ to $8$, or a bomb. The field is valid if for each cell:   if there is a digit $k$ in the cell, then exactly $k$ neighboring cells have bombs.  if the cell is empty, then all neighboring cells have no bombs.

Two cells are neighbors if they have a common side or a corner (i. e. a cell has at most $8$ neighboring cells).

-----Input-----

The first line contains two integers $n$ and $m$ ($1 \le n, m \le 100$) — the sizes of the field.

The next $n$ lines contain the description of the field. Each line contains $m$ characters, each of them is "." (if this cell is empty), "*" (if there is bomb in this cell), or a digit from $1$ to $8$, inclusive.

-----Output-----

Print "YES", if the field is valid and "NO" otherwise.

You can choose the case (lower or upper) for each letter arbitrarily.

-----Examples-----
Input
3 3
111
1*1
111

Output
YES
Input
2 4
*.*.
1211

Output
NO

-----Note-----

In the second example the answer is "NO" because, if the positions of the bombs are preserved, the first line of the field should be *2*1.

You can read more about Minesweeper in Wikipedia's article.

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

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

board = [list(input()) for _ in range(n)]

ns = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]

valid = True

for x, row in enumerate(board):
    for y, c in enumerate(row):
        b = 0
        for (dx, dy) in ns:
            nx, ny = x + dx, y + dy
            if 0 <= nx < len(board) and 0 <= ny < len(row):
                if board[nx][ny] == '*':
                    b += 1
        xx = '.' if b == 0 else str(b)
        if c != '*' and xx != c:
            valid = False

print('YES' if valid else 'NO')


I found an interesting problem on https://codeforces.com/problemset/problem/985/A:
You are given a chessboard of size 1 × n. It is guaranteed that n is even. The chessboard is painted like this: "BWBW...BW".

Some cells of the board are occupied by the chess pieces. Each cell contains no more than one chess piece. It is known that the total number of pieces equals to $\frac{n}{2}$.

In one step you can move one of the pieces one cell to the left or to the right. You cannot move pieces beyond the borders of the board. You also cannot move pieces to the cells that are already occupied.

Your task is to place all the pieces in the cells of the same color using the minimum number of moves (all the pieces must occupy only the black cells or only the white cells after all the moves are made).

-----Input-----

The first line of the input contains one integer n (2 ≤ n ≤ 100, n is even) — the size of the chessboard.

The second line of the input contains $\frac{n}{2}$ integer numbers $p_{1}, p_{2}, \ldots, p_{\frac{n}{2}}$ (1 ≤ p_{i} ≤ n) — initial positions of the pieces. It is guaranteed that all the positions are distinct.

-----Output-----

Print one integer — the minimum number of moves you have to make to place all the pieces in the cells of the same color.

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

Output
2

Input
10
1 2 3 4 5

Output
10

-----Note-----

In the first example the only possible strategy is to move the piece at the position 6 to the position 5 and move the piece at the position 2 to the position 3. Notice that if you decide to place the pieces in the white cells the minimum number of moves will be 3.

In the second example the possible strategy is to move $5 \rightarrow 9$ in 4 moves, then $4 \rightarrow 7$ in 3 moves, $3 \rightarrow 5$ in 2 moves and $2 \rightarrow 3$ in 1 move.

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

n=int(input())
arr=list(map(int,input().strip().split(' ')))
arr.sort()
ind = n
cnt = 0
for i in range(n//2-1,-1,-1):
  cnt = cnt + abs(arr[i]-ind)
  ind-=2
cnt1=0
ind=n-1
for i in range(n//2-1,-1,-1):
  cnt1 = cnt1 + abs(arr[i]-ind)
  ind-=2
print(min(cnt,cnt1))


I found an interesting problem on https://codeforces.com/problemset/problem/985/B:
You are given n switches and m lamps. The i-th switch turns on some subset of the lamps. This information is given as the matrix a consisting of n rows and m columns where a_{i}, j = 1 if the i-th switch turns on the j-th lamp and a_{i}, j = 0 if the i-th switch is not connected to the j-th lamp.

Initially all m lamps are turned off.

Switches change state only from "off" to "on". It means that if you press two or more switches connected to the same lamp then the lamp will be turned on after any of this switches is pressed and will remain its state even if any switch connected to this lamp is pressed afterwards.

It is guaranteed that if you push all n switches then all m lamps will be turned on.

Your think that you have too many switches and you would like to ignore one of them.

Your task is to say if there exists such a switch that if you will ignore (not use) it but press all the other n - 1 switches then all the m lamps will be turned on.

-----Input-----

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 2000) — the number of the switches and the number of the lamps.

The following n lines contain m characters each. The character a_{i}, j is equal to '1' if the i-th switch turns on the j-th lamp and '0' otherwise.

It is guaranteed that if you press all n switches all m lamps will be turned on.

-----Output-----

Print "YES" if there is a switch that if you will ignore it and press all the other n - 1 switches then all m lamps will be turned on. Print "NO" if there is no such switch.

-----Examples-----
Input
4 5
10101
01000
00111
10000

Output
YES

Input
4 5
10100
01000
00110
00101

Output
NO

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

n, m = list(map(int, input().split()))
a = [list(map(int, input())) for i in range(n)]

ignorable = [True] * n

for i in range(m):
    cnt = 0
    for j in range(n):
        cnt += a[j][i]
    if cnt == 1:
        for j in range(n):
            if a[j][i]:
                ignorable[j] = False

if any(ignorable):
    print('YES')
else:
    print('NO')


I found an interesting problem on https://codeforces.com/problemset/problem/985/C:
You have m = n·k wooden staves. The i-th stave has length a_{i}. You have to assemble n barrels consisting of k staves each, you can use any k staves to construct a barrel. Each stave must belong to exactly one barrel.

Let volume v_{j} of barrel j be equal to the length of the minimal stave in it. [Image]

You want to assemble exactly n barrels with the maximal total sum of volumes. But you have to make them equal enough, so a difference between volumes of any pair of the resulting barrels must not exceed l, i.e. |v_{x} - v_{y}| ≤ l for any 1 ≤ x ≤ n and 1 ≤ y ≤ n.

Print maximal total sum of volumes of equal enough barrels or 0 if it's impossible to satisfy the condition above.

-----Input-----

The first line contains three space-separated integers n, k and l (1 ≤ n, k ≤ 10^5, 1 ≤ n·k ≤ 10^5, 0 ≤ l ≤ 10^9).

The second line contains m = n·k space-separated integers a_1, a_2, ..., a_{m} (1 ≤ a_{i} ≤ 10^9) — lengths of staves.

-----Output-----

Print single integer — maximal total sum of the volumes of barrels or 0 if it's impossible to construct exactly n barrels satisfying the condition |v_{x} - v_{y}| ≤ l for any 1 ≤ x ≤ n and 1 ≤ y ≤ n.

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

Output
7

Input
2 1 0
10 10

Output
20

Input
1 2 1
5 2

Output
2

Input
3 2 1
1 2 3 4 5 6

Output
0

-----Note-----

In the first example you can form the following barrels: [1, 2], [2, 2], [2, 3], [2, 3].

In the second example you can form the following barrels: [10], [10].

In the third example you can form the following barrels: [2, 5].

In the fourth example difference between volumes of barrels in any partition is at least 2 so it is impossible to make barrels equal enough.

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

def main():
    n, k, l = map(int, input().split())
    m = n * k
    a = list(map(int, input().split()))
    a.sort()
    f = a[0]
    i = 0
    while (i < m and a[i] <= f + l):
        i += 1
    if (i != m):
        i -= 1
    else:
        ans = 0
        ind = 0
        for i in range(n):
            ans += a[ind]
            ind += k
        print(ans)
        return
    last = i
    if (last + 1 < n):
        print(0)
        return
    count = m - last - 1
    ost = last + 1
    ans = 0
    i = last
    while (i >= 0):
        c = min(k - 1, count)
        count -= c
        i -= (k - c)
        ans += a[i + 1]
    print(ans)
main()


I found an interesting problem on https://codeforces.com/problemset/problem/985/D:
You are going to the beach with the idea to build the greatest sand castle ever in your head! The beach is not as three-dimensional as you could have imagined, it can be decribed as a line of spots to pile up sand pillars. Spots are numbered 1 through infinity from left to right.

Obviously, there is not enough sand on the beach, so you brought n packs of sand with you. Let height h_{i} of the sand pillar on some spot i be the number of sand packs you spent on it. You can't split a sand pack to multiple pillars, all the sand from it should go to a single one. There is a fence of height equal to the height of pillar with H sand packs to the left of the first spot and you should prevent sand from going over it.

Finally you ended up with the following conditions to building the castle:  h_1 ≤ H: no sand from the leftmost spot should go over the fence;  For any $i \in [ 1 ; \infty)$ |h_{i} - h_{i} + 1| ≤ 1: large difference in heights of two neighboring pillars can lead sand to fall down from the higher one to the lower, you really don't want this to happen;  $\sum_{i = 1}^{\infty} h_{i} = n$: you want to spend all the sand you brought with you.

As you have infinite spots to build, it is always possible to come up with some valid castle structure. Though you want the castle to be as compact as possible.

Your task is to calculate the minimum number of spots you can occupy so that all the aforementioned conditions hold.

-----Input-----

The only line contains two integer numbers n and H (1 ≤ n, H ≤ 10^18) — the number of sand packs you have and the height of the fence, respectively.

-----Output-----

Print the minimum number of spots you can occupy so the all the castle building conditions hold.

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

Output
3

Input
6 8

Output
3

-----Note-----

Here are the heights of some valid castles:   n = 5, H = 2, [2, 2, 1, 0, ...], [2, 1, 1, 1, 0, ...], [1, 0, 1, 2, 1, 0, ...]  n = 6, H = 8, [3, 2, 1, 0, ...], [2, 2, 1, 1, 0, ...], [0, 1, 0, 1, 2, 1, 1, 0...] (this one has 5 spots...

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/985/E:
Mishka received a gift of multicolored pencils for his birthday! Unfortunately he lives in a monochrome world, where everything is of the same color and only saturation differs. This pack can be represented as a sequence a_1, a_2, ..., a_{n} of n integer numbers — saturation of the color of each pencil. Now Mishka wants to put all the mess in the pack in order. He has an infinite number of empty boxes to do this. He would like to fill some boxes in such a way that:

  Each pencil belongs to exactly one box;  Each non-empty box has at least k pencils in it;  If pencils i and j belong to the same box, then |a_{i} - a_{j}| ≤ d, where |x| means absolute value of x. Note that the opposite is optional, there can be pencils i and j such that |a_{i} - a_{j}| ≤ d and they belong to different boxes.

Help Mishka to determine if it's possible to distribute all the pencils into boxes. Print "YES" if there exists such a distribution. Otherwise print "NO".

-----Input-----

The first line contains three integer numbers n, k and d (1 ≤ k ≤ n ≤ 5·10^5, 0 ≤ d ≤ 10^9) — the number of pencils, minimal size of any non-empty box and maximal difference in saturation between any pair of pencils in the same box, respectively.

The second line contains n integer numbers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — saturation of color of each pencil.

-----Output-----

Print "YES" if it's possible to distribute all the pencils into boxes and satisfy all the conditions. Otherwise print "NO".

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

Output
YES

Input
6 2 3
4 5 3 13 4 10

Output
YES

Input
3 2 5
10 16 22

Output
NO

-----Note-----

In the first example it is possible to distribute pencils into 2 boxes with 3 pencils in each with any distribution. And you also can put all the pencils into the same box, difference of any pair in it won't exceed 10.

In the second example you can split pencils of saturations [4, 5, 3, 4] into 2 boxes of size 2 and put the remaining ones into another box.

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

def main():
    import sys
    from bisect import bisect_left
    input = sys.stdin.readline

    N, K, D = list(map(int, input().split()))
    A = list(map(int, input().split()))
    A.sort()

    part = [0] * (N+2)
    part[0] = 1
    part[1] = -1
    for i, a in enumerate(A):
        part[i] += part[i-1]
        if part[i]:
            j = bisect_left(A, a+D+1)
            if j >= i+K:
                part[i+K] += 1
                part[j+1] -= 1
    part[N] += part[N-1]
    if part[N]:
        print('YES')
    else:
        print('NO')
    #print(A)
    #print(part)

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/985/F:
You are given a string s of length n consisting of lowercase English letters.

For two given strings s and t, say S is the set of distinct characters of s and T is the set of distinct characters of t. The strings s and t are isomorphic if their lengths are equal and there is a one-to-one mapping (bijection) f between S and T for which f(s_{i}) = t_{i}. Formally:  f(s_{i}) = t_{i} for any index i,  for any character $x \in S$ there is exactly one character $y \in T$ that f(x) = y,  for any character $y \in T$ there is exactly one character $x \in S$ that f(x) = y.

For example, the strings "aababc" and "bbcbcz" are isomorphic. Also the strings "aaaww" and "wwwaa" are isomorphic. The following pairs of strings are not isomorphic: "aab" and "bbb", "test" and "best".

You have to handle m queries characterized by three integers x, y, len (1 ≤ x, y ≤ n - len + 1). For each query check if two substrings s[x... x + len - 1] and s[y... y + len - 1] are isomorphic.

-----Input-----

The first line contains two space-separated integers n and m (1 ≤ n ≤ 2·10^5, 1 ≤ m ≤ 2·10^5) — the length of the string s and the number of queries.

The second line contains string s consisting of n lowercase English letters.

The following m lines contain a single query on each line: x_{i}, y_{i} and len_{i} (1 ≤ x_{i}, y_{i} ≤ n, 1 ≤ len_{i} ≤ n - max(x_{i}, y_{i}) + 1) — the description of the pair of the substrings to check.

-----Output-----

For each query in a separate line print "YES" if substrings s[x_{i}... x_{i} + len_{i} - 1] and s[y_{i}... y_{i} + len_{i} - 1] are isomorphic and "NO" otherwise.

-----Example-----
Input
7 4
abacaba
1 1 1
1 4 2
2 1 3
2 4 3

Output
YES
YES
NO
YES

-----Note-----

The queries in the example are following:   substrings "a" and "a" are isomorphic: f(a) = a;  substrings "ab" and "ca" are isomorphic: f(a) = c, f(b) = a;  substrings "bac" and "aba" are not isomorphic since f(b) and f(c) must be equal to a at same time;  substrings "bac" and "cab" are isomorphic: f(b) = c, f(a) = a, f(c) = b.

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

def getIntList():
    return list(map(int, input().split()));
def getTransIntList(n):
    first=getIntList();
    m=len(first);
    result=[[0]*n for _ in range(m)];
    for i in range(m):
        result[i][0]=first[i];
    for j in range(1, n):
        curr=getIntList();
        for i in range(m):
            result[i][j]=curr[i];
    return result;
n, m = getIntList()
s=input();
orda=ord('a');
a=[ord(s[i])-orda for i in range(n)];
countSame=[1]*n;
upLim=0;
for lowLim in range(n):
    if lowLim<upLim:
        continue;
    for upLim in range(lowLim+1, n):
        if a[upLim]!=a[lowLim]:
            break;
    else:
        upLim+=1;
    for i in range(lowLim, upLim):
        countSame[i]=upLim-i;
def test(x, y, l):
    map1=[0]*27;
    map2=[0]*27;
    count=0;
    lowLim=min(countSame[x], countSame[y])-1;
    for i in range(lowLim, l):
        x1=map1[a[x+i]];
        x2=map2[a[y+i]];
        if x1!=x2:
            return 'NO';
        if x1==0:
            count+=1;
            map1[a[x+i]]=count;
            map2[a[y+i]]=count;
    return 'YES';
results=[];
for _ in range(m):
    x, y, l=getIntList();
    results.append(test(x-1, y-1, l));
print('\n'.join(results));