I found an interesting problem on https://codeforces.com/problemset/problem/1120/E:
A positive integer $a$ is given. Baron Munchausen claims that he knows such a positive integer $n$ that if one multiplies $n$ by $a$, the sum of its digits decreases $a$ times. In other words, $S(an) = S(n)/a$, where $S(x)$ denotes the sum of digits of the number $x$.

Find out if what Baron told can be true.

-----Input-----

The only line contains a single integer $a$ ($2 \le a \le 10^3$).

-----Output-----

If there is no such number $n$, print $-1$.

Otherwise print any appropriate positive integer $n$. Your number must not consist of more than $5\cdot10^5$ digits. We can show that under given constraints either there is no answer, or there is an answer no longer than $5\cdot10^5$ digits.

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

Output
6

Input
3

Output
6669

Input
10

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/1121/B:
Mike decided to teach programming to children in an elementary school. He knows that it is not an easy task to interest children in that age to code. That is why he decided to give each child two sweets.

Mike has $n$ sweets with sizes $a_1, a_2, \ldots, a_n$. All his sweets have different sizes. That is, there is no such pair $(i, j)$ ($1 \leq i, j \leq n$) such that $i \ne j$ and $a_i = a_j$.

Since Mike has taught for many years, he knows that if he gives two sweets with sizes $a_i$ and $a_j$ to one child and $a_k$ and $a_p$ to another, where $(a_i + a_j) \neq (a_k + a_p)$, then a child who has a smaller sum of sizes will be upset. That is, if there are two children who have different sums of sweets, then one of them will be upset. Apparently, Mike does not want somebody to be upset.

Mike wants to invite children giving each of them two sweets. Obviously, he can't give one sweet to two or more children. His goal is to invite as many children as he can.

Since Mike is busy preparing to his first lecture in the elementary school, he is asking you to find the maximum number of children he can invite giving each of them two sweets in such way that nobody will be upset.

-----Input-----

The first line contains one integer $n$ ($2 \leq n \leq 1\,000$) — the number of sweets Mike has.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^5$) — the sizes of the sweets. It is guaranteed that all integers are distinct.

-----Output-----

Print one integer — the maximum number of children Mike can invite giving each of them two sweets in such way that nobody will be upset.

-----Examples-----
Input
8
1 8 3 11 4 9 2 7

Output
3

Input
7
3 1 7 11 9 2 12

Output
2

-----Note-----

In the first example, Mike can give $9+2=11$ to one child, $8+3=11$ to another one, and $7+4=11$ to the third child. Therefore, Mike can invite three children. Note that it is not the only solution.

In the second example, Mike can give $3+9=12$ to one child and $1+11$ to another one. Therefore, Mike can...

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

n = int(input())
a = list(map(int,input().split()))
cnt = [0 for i in range(2*10**5+1)]
for i in range(n):
	for j in range(i+1,n):
		cnt[a[i]+a[j]]+=1
print(max(cnt))


I found an interesting problem on https://codeforces.com/problemset/problem/1129/A1:
This is a simplified version of the task Toy Train. These two versions differ only in the constraints. Hacks for this version are disabled.

Alice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of $n$ stations, enumerated from $1$ through $n$. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit after station $i$ is station $i+1$ if $1 \leq i < n$ or station $1$ if $i = n$. It takes the train $1$ second to travel to its next station as described.

Bob gave Alice a fun task before he left: to deliver $m$ candies that are initially at some stations to their independent destinations using the train. The candies are enumerated from $1$ through $m$. Candy $i$ ($1 \leq i \leq m$), now at station $a_i$, should be delivered to station $b_i$ ($a_i \neq b_i$). [Image] The blue numbers on the candies correspond to $b_i$ values. The image corresponds to the $1$-st example.

The train has infinite capacity, and it is possible to load off any number of candies at a station. However, only at most one candy can be loaded from a station onto the train before it leaves the station. You can choose any candy at this station. The time it takes to move the candies is negligible.

Now, Alice wonders how much time is needed for the train to deliver all candies. Your task is to find, for each station, the minimum time the train would need to deliver all the candies were it to start from there.

-----Input-----

The first line contains two space-separated integers $n$ and $m$ ($2 \leq n \leq 100$; $1 \leq m \leq 200$) — the number of stations and the number of candies, respectively.

The $i$-th of the following $m$ lines contains two space-separated integers $a_i$ and $b_i$ ($1 \leq a_i, b_i \leq n$; $a_i \neq b_i$) — the station that initially contains candy $i$ and the destination station of the candy, respectively.

-----Output-----

In the first and only line,...

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

def dista(start, n):
    return lambda end: n - (start - end) if(start > end) else end - start

n, m = list(map(int,input().split(' ')))
dicta = [[] for i in range(n+1)]
for i in range(m):
    s, d = list(map(int,input().split(' ')))
    dicta[s].append(d)
for i in range(n+1):
    dicta[i].sort(key = dista(i, n))
maxlen = max((list(map(len, dicta))))

result = (maxlen-1)*n
minadd = 0

ansans = []
for k in range(1, n+1):
    disk = dista(k, n)
    minadd = 0
    for i in range(1, n+1):
        lndicta = len(dicta[i])
        tmp = 0
        if(lndicta == maxlen-1):
            if lndicta != 0:
                tmp = min([(disk(i) + dista(i, n)(j)) for j in dicta[i]]) - n
        elif(lndicta == maxlen):
            tmp = min([(disk(i) + dista(i, n)(j)) for j in dicta[i]])
        if(tmp > minadd):
            minadd = tmp
    ansans.append(str(minadd + result))

print(' '.join(ansans))


I found an interesting problem on https://codeforces.com/problemset/problem/1129/C:
In Morse code, an letter of English alphabet is represented as a string of some length from $1$ to $4$. Moreover, each Morse code representation of an English letter contains only dots and dashes. In this task, we will represent a dot with a "0" and a dash with a "1".

Because there are $2^1+2^2+2^3+2^4 = 30$ strings with length $1$ to $4$ containing only "0" and/or "1", not all of them correspond to one of the $26$ English letters. In particular, each string of "0" and/or "1" of length at most $4$ translates into a distinct English letter, except the following four strings that do not correspond to any English alphabet: "0011", "0101", "1110", and "1111".

You will work with a string $S$, which is initially empty. For $m$ times, either a dot or a dash will be appended to $S$, one at a time. Your task is to find and report, after each of these modifications to string $S$, the number of non-empty sequences of English letters that are represented with some substring of $S$ in Morse code.

Since the answers can be incredibly tremendous, print them modulo $10^9 + 7$.

-----Input-----

The first line contains an integer $m$ ($1 \leq m \leq 3\,000$) — the number of modifications to $S$.

Each of the next $m$ lines contains either a "0" (representing a dot) or a "1" (representing a dash), specifying which character should be appended to $S$.

-----Output-----

Print $m$ lines, the $i$-th of which being the answer after the $i$-th modification to $S$.

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

Output
1
3
7

Input
5
1
0
1
0
1

Output
1
4
10
22
43

Input
9
1
1
0
0
0
1
1
0
1

Output
1
3
10
24
51
109
213
421
833

-----Note-----

Let us consider the first sample after all characters have been appended to $S$, so S is "111".

As you can see, "1", "11", and "111" all correspond to some distinct English letter. In fact, they are translated into a 'T', an 'M', and an 'O', respectively. All non-empty sequences of English letters that are represented with some substring of $S$ in Morse code, therefore, are as follows.  "T"...

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/1130/A:
You are given an array of $n$ integers: $a_1, a_2, \ldots, a_n$. Your task is to find some non-zero integer $d$ ($-10^3 \leq d \leq 10^3$) such that, after each number in the array is divided by $d$, the number of positive numbers that are presented in the array is greater than or equal to half of the array size (i.e., at least $\lceil\frac{n}{2}\rceil$). Note that those positive numbers do not need to be an integer (e.g., a $2.5$ counts as a positive number). If there are multiple values of $d$ that satisfy the condition, you may print any of them. In case that there is no such $d$, print a single integer $0$.

Recall that $\lceil x \rceil$ represents the smallest integer that is not less than $x$ and that zero ($0$) is neither positive nor negative.

-----Input-----

The first line contains one integer $n$ ($1 \le n \le 100$) — the number of elements in the array.

The second line contains $n$ space-separated integers $a_1, a_2, \ldots, a_n$ ($-10^3 \le a_i \le 10^3$).

-----Output-----

Print one integer $d$ ($-10^3 \leq d \leq 10^3$ and $d \neq 0$) that satisfies the given condition. If there are multiple values of $d$ that satisfy the condition, you may print any of them. In case that there is no such $d$, print a single integer $0$.

-----Examples-----
Input
5
10 0 -7 2 6
Output
4
Input
7
0 0 1 -1 0 0 2

Output
0

-----Note-----

In the first sample, $n = 5$, so we need at least $\lceil\frac{5}{2}\rceil = 3$ positive numbers after division. If $d = 4$, the array after division is $[2.5, 0, -1.75, 0.5, 1.5]$, in which there are $3$ positive numbers (namely: $2.5$, $0.5$, and $1.5$).

In the second sample, there is no valid $d$, so $0$ should be printed.

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

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

pos = sum(x > 0 for x in a)
neg = sum(x < 0 for x in a)

needed = (n + 1) // 2
if pos >= needed:
    print("1")
elif neg >= needed:
    print("-1")
else:
    print(0)


I found an interesting problem on https://codeforces.com/problemset/problem/1130/B:
Sasha and Dima want to buy two $n$-tier cakes. Each cake should consist of $n$ different tiers: from the size of $1$ to the size of $n$. Tiers should go in order from the smallest to the biggest (from top to bottom).

They live on the same street, there are $2 \cdot n$ houses in a row from left to right. Each house has a pastry shop where you can buy a cake tier. Unfortunately, in each pastry shop you can buy only one tier of only one specific size: in the $i$-th house you can buy a tier of the size $a_i$ ($1 \le a_i \le n$).

Since the guys carry already purchased tiers, and it is impossible to insert a new tier in the middle of the cake, they agreed to buy tiers from the smallest to the biggest. That is, each of them buys tiers in order: $1$, then $2$, then $3$ and so on up to $n$.

Initially, Sasha and Dima are located near the first (leftmost) house. Output the minimum distance that they will have to walk in total to buy both cakes. The distance between any two neighboring houses is exactly $1$.

-----Input-----

The first line of the input contains an integer number $n$ — the number of tiers in each cake ($1 \le n \le 10^5$).

The second line contains $2 \cdot n$ integers $a_1, a_2, \dots, a_{2n}$ ($1 \le a_i \le n$), where $a_i$ is equal to the size of the tier, which can be bought in the $i$-th house. Remember that in each house you can buy only one tier. It is guaranteed that every number from $1$ to $n$ occurs in $a$ exactly two times.

-----Output-----

Print one number  — the minimum distance that the guys have to walk in total to buy both cakes. Guys can be near same house at the same time. They begin near the first (leftmost) house. Each of the guys should buy $n$ tiers in ascending order of their sizes.

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

Output
9

Input
2
2 1 1 2

Output
5

Input
4
4 1 3 2 2 3 1 4

Output
17

-----Note-----

In the first example, the possible optimal sequence of actions is:  Sasha buys a tier of size $1$ near the $1$-st house ($a_1=1$);  Dima goes to the house $2$; ...

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

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

p1 = 0
p2 = 0
total = 0

pos = {}
for i in range(n):
    pos[i] = []

for i, val in enumerate(a):
    pos[val - 1].append(i)

for i in range(n):
    d1, d2 = pos[i]

    if p1 > p2:
        p1, p2 = p2, p1

    total += abs(p1 - d1)
    total += abs(p2 - d2)
    p1, p2 = d1, d2

print(total)


I found an interesting problem on https://codeforces.com/problemset/problem/1130/C:
Alice lives on a flat planet that can be modeled as a square grid of size $n \times n$, with rows and columns enumerated from $1$ to $n$. We represent the cell at the intersection of row $r$ and column $c$ with ordered pair $(r, c)$. Each cell in the grid is either land or water.

 [Image] An example planet with $n = 5$. It also appears in the first sample test.

Alice resides in land cell $(r_1, c_1)$. She wishes to travel to land cell $(r_2, c_2)$. At any moment, she may move to one of the cells adjacent to where she is—in one of the four directions (i.e., up, down, left, or right).

Unfortunately, Alice cannot swim, and there is no viable transportation means other than by foot (i.e., she can walk only on land). As a result, Alice's trip may be impossible.

To help Alice, you plan to create at most one tunnel between some two land cells. The tunnel will allow Alice to freely travel between the two endpoints. Indeed, creating a tunnel is a lot of effort: the cost of creating a tunnel between cells $(r_s, c_s)$ and $(r_t, c_t)$ is $(r_s-r_t)^2 + (c_s-c_t)^2$.

For now, your task is to find the minimum possible cost of creating at most one tunnel so that Alice could travel from $(r_1, c_1)$ to $(r_2, c_2)$. If no tunnel needs to be created, the cost is $0$.

-----Input-----

The first line contains one integer $n$ ($1 \leq n \leq 50$) — the width of the square grid.

The second line contains two space-separated integers $r_1$ and $c_1$ ($1 \leq r_1, c_1 \leq n$) — denoting the cell where Alice resides.

The third line contains two space-separated integers $r_2$ and $c_2$ ($1 \leq r_2, c_2 \leq n$) — denoting the cell to which Alice wishes to travel.

Each of the following $n$ lines contains a string of $n$ characters. The $j$-th character of the $i$-th such line ($1 \leq i, j \leq n$) is 0 if $(i, j)$ is land or 1 if $(i, j)$ is water.

It is guaranteed that $(r_1, c_1)$ and $(r_2, c_2)$ are land.

-----Output-----

Print an integer that is the minimum possible cost of creating at most one tunnel so that...

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

def dis(u,v):
    x1,y1=u
    x2,y2=v
    return(( (x1-x2)**2 + (y1-y2)**2 ))

def adj(u):
    x,y=u
    t=[]
    #print(x,y)
    if x+1<n and a[x+1][y]=='0':
        t.append([x+1,y])
    if y+1<n and a[x][y+1]=='0':
        t.append([x,y+1])
    if x-1>=0 and a[x-1][y]=='0':
        t.append([x-1,y])
    if y-1>=0 and a[x][y-1]=='0':
        t.append([x,y-1])
    return(t)

def bfs(s):
    ans=[s]
    x,y=s
    v2[x][y]=1
    frontier=[s]
    while frontier:
        nex=[]
        for u in frontier:
            for v in adj(u):
                if v2[v[0]][v[1]]==0:
                    nex.append(v)
                    v2[v[0]][v[1]]=1
                    ans.append(v)
        frontier=nex
    return(ans)

n=int(input())
r1,c1=[int(i) for i in input().split(' ')]
r2,c2=[int(i) for i in input().split(' ')]
a=[]
for i in range(n):
    a.append(list(input()))

v2=[[0 for i in range(n)] for j in range(n)]

ans1=bfs([r1-1,c1-1])
ans2=bfs([r2-1,c2-1])
r=9999999999
for i in ans1:
    for j in ans2:
        #print(i,j)
        r=min(r,dis(i,j))
print(r)


I found an interesting problem on https://codeforces.com/problemset/problem/1131/A:
In order to make the "Sea Battle" game more interesting, Boris decided to add a new ship type to it. The ship consists of two rectangles. The first rectangle has a width of $w_1$ and a height of $h_1$, while the second rectangle has a width of $w_2$ and a height of $h_2$, where $w_1 \ge w_2$. In this game, exactly one ship is used, made up of two rectangles. There are no other ships on the field.

The rectangles are placed on field in the following way:  the second rectangle is on top the first rectangle;  they are aligned to the left, i.e. their left sides are on the same line;  the rectangles are adjacent to each other without a gap.

See the pictures in the notes: the first rectangle is colored red, the second rectangle is colored blue.

Formally, let's introduce a coordinate system. Then, the leftmost bottom cell of the first rectangle has coordinates $(1, 1)$, the rightmost top cell of the first rectangle has coordinates $(w_1, h_1)$, the leftmost bottom cell of the second rectangle has coordinates $(1, h_1 + 1)$ and the rightmost top cell of the second rectangle has coordinates $(w_2, h_1 + h_2)$.

After the ship is completely destroyed, all cells neighboring by side or a corner with the ship are marked. Of course, only cells, which don't belong to the ship are marked. On the pictures in the notes such cells are colored green.

Find out how many cells should be marked after the ship is destroyed. The field of the game is infinite in any direction.

-----Input-----

Four lines contain integers $w_1, h_1, w_2$ and $h_2$ ($1 \leq w_1, h_1, w_2, h_2 \leq 10^8$, $w_1 \ge w_2$) — the width of the first rectangle, the height of the first rectangle, the width of the second rectangle and the height of the second rectangle. You can't rotate the rectangles.

-----Output-----

Print exactly one integer — the number of cells, which should be marked after the ship is destroyed.

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

Output
12

Input
2 2 1 2

Output
16

-----Note-----

In the first example the field looks as follows...

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

ii = lambda: int(input())
mi = lambda: map(int, input().split())
li = lambda: list(mi())

w1, h1, w2, h2 = mi()
ans = h1 + h2 + 2 + w1 + w2 + 2 + h1 + h2 + w1 - w2
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1131/B:
You still have partial information about the score during the historic football match. You are given a set of pairs $(a_i, b_i)$, indicating that at some point during the match the score was "$a_i$: $b_i$". It is known that if the current score is «$x$:$y$», then after the goal it will change to "$x+1$:$y$" or "$x$:$y+1$". What is the largest number of times a draw could appear on the scoreboard?

The pairs "$a_i$:$b_i$" are given in chronological order (time increases), but you are given score only for some moments of time. The last pair corresponds to the end of the match.

-----Input-----

The first line contains a single integer $n$ ($1 \le n \le 10000$) — the number of known moments in the match.

Each of the next $n$ lines contains integers $a_i$ and $b_i$ ($0 \le a_i, b_i \le 10^9$), denoting the score of the match at that moment (that is, the number of goals by the first team and the number of goals by the second team).

All moments are given in chronological order, that is, sequences $x_i$ and $y_j$ are non-decreasing. The last score denotes the final result of the match.

-----Output-----

Print the maximum number of moments of time, during which the score was a draw. The starting moment of the match (with a score 0:0) is also counted.

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

Output
2

Input
3
0 0
0 0
0 0

Output
1

Input
1
5 4

Output
5

-----Note-----

In the example one of the possible score sequences leading to the maximum number of draws is as follows: 0:0, 1:0, 2:0, 2:1, 3:1, 3:2, 3:3, 3:4.

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

n = int(input())

a, b = map(int, input().split())
ans = min(a, b) + 1
for i in range(n - 1):
    c, d = map(int, input().split())
    if c > a or d > b:
        e = max(a, b)
        f = min(c, d)
        ans += max(0, f - e + 1)
        if a == b:
            ans -= 1
        #print(ans)
    a, b = c, d

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1131/C:
Cowboy Vlad has a birthday today! There are $n$ children who came to the celebration. In order to greet Vlad, the children decided to form a circle around him. Among the children who came, there are both tall and low, so if they stand in a circle arbitrarily, it may turn out, that there is a tall and low child standing next to each other, and it will be difficult for them to hold hands. Therefore, children want to stand in a circle so that the maximum difference between the growth of two neighboring children would be minimal possible.

Formally, let's number children from $1$ to $n$ in a circle order, that is, for every $i$ child with number $i$ will stand next to the child with number $i+1$, also the child with number $1$ stands next to the child with number $n$. Then we will call the discomfort of the circle the maximum absolute difference of heights of the children, who stand next to each other.

Please help children to find out how they should reorder themselves, so that the resulting discomfort is smallest possible.

-----Input-----

The first line contains a single integer $n$ ($2 \leq n \leq 100$) — the number of the children who came to the cowboy Vlad's birthday.

The second line contains integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^9$) denoting heights of every child.

-----Output-----

Print exactly $n$ integers — heights of the children in the order in which they should stand in a circle. You can start printing a circle with any child.

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

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

Output
1 2 3 2 1

Input
3
30 10 20

Output
10 20 30

-----Note-----

In the first example, the discomfort of the circle is equal to $1$, since the corresponding absolute differences are $1$, $1$, $1$ and $0$. Note, that sequences $[2, 3, 2, 1, 1]$ and $[3, 2, 1, 1, 2]$ form the same circles and differ only by the selection of the starting point.

In the second example, the discomfort of the circle is equal to $20$, since the absolute difference of $10$...

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

n = int(input())
L = sorted(list(map(int, input().split())))
M = L[::2]
N = L[1::2][::-1]
print(*(M + N))


I found an interesting problem on https://codeforces.com/problemset/problem/1131/D:
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review  — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer.

Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes.

The gourmet tasted a set of $n$ dishes on the first day and a set of $m$ dishes on the second day. He made a table $a$ of size $n \times m$, in which he described his impressions. If, according to the expert, dish $i$ from the first set was better than dish $j$ from the second set, then $a_{ij}$ is equal to ">", in the opposite case $a_{ij}$ is equal to "<". Dishes also may be equally good, in this case $a_{ij}$ is "=".

Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if $a_{ij}$ is "<", then the number assigned to dish $i$ from the first set should be less than the number of dish $j$ from the second set, if $a_{ij}$ is ">", then it should be greater, and finally if $a_{ij}$ is "=", then the numbers should be the same.

Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible.

-----Input-----

The...

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

def prov(mass, now):
    check = True
    for i in range(n):
        for k in range(m):
            if now[i][k] == '>' and mass[i] <= mass[n + k]:
                check = False
                break
            elif now[i][k] == '<' and mass[i] >= mass[n + k]:
                check = False
                break
            elif now[i][k] == '=' and mass[i] != mass[n + k]:
                check = False
                break
        if not check:
            break
    return check

def prog(mass, n, m):
    prov = True
    for i in range(1, m):
        for k in range(n):
            if mass[i][k] < mass[i - 1][k]:
                prov = False
                break
        if not prov:
            break
    if not prov:
        return False
    else:
        mass_new = []
        for i in range(1, m):
            mass_n = []
            for k in range(n):
                mass_n.append(mass[i][k] - mass[i - 1][k])
            mass_new.append(max(mass_n))
        arr = [1 for i in range(m)]
        now = 1
        if 1 in mass[0][:-1]:
            now += 1
            arr = [2 for i in range(m)]
        for i in range(1, m):
            now += mass_new[i - 1]
            arr[mass[i][-1]] = now
        return arr

n, m = map(int, input().split())
if n + m <= 6:
    now = []
    for i in range(n):
        now.append(input())
    ppp = True
    for i1 in range(n + m):
        for i2 in range(n + m):
            for i3 in range(n + m):
                for i4 in range(n + m):
                    for i5 in range(n + m):
                        for i6 in range(n + m):
                            mass = [i1 + 1, i2 + 1, i3 + 1, i4 + 1, i5 + 1, i6 + 1][:n + m]
                            if prov(mass, now) and ppp:
                                print('Yes')
                                print(*mass[:n])
                                print(*mass[n:])
                                ppp = False
    if ppp:
        print('No')
else:
    mass = [[] for i in range(m)]
    mass1 = [[] for i in range(n)]
    for i in...


I found an interesting problem on https://codeforces.com/problemset/problem/1131/E:
Roman and Denis are on the trip to the programming competition. Since the trip was long, they soon got bored, and hence decided to came up with something. Roman invented a pizza's recipe, while Denis invented a string multiplication. According to Denis, the result of multiplication (product) of strings $s$ of length $m$ and $t$ is a string $t + s_1 + t + s_2 + \ldots + t + s_m + t$, where $s_i$ denotes the $i$-th symbol of the string $s$, and "+" denotes string concatenation. For example, the product of strings "abc" and "de" is a string "deadebdecde", while the product of the strings "ab" and "z" is a string "zazbz". Note, that unlike the numbers multiplication, the product of strings $s$ and $t$ is not necessarily equal to product of $t$ and $s$.

Roman was jealous of Denis, since he invented such a cool operation, and hence decided to invent something string-related too. Since Roman is beauty-lover, he decided to define the beauty of the string as the length of the longest substring, consisting of only one letter. For example, the beauty of the string "xayyaaabca" is equal to $3$, since there is a substring "aaa", while the beauty of the string "qwerqwer" is equal to $1$, since all neighboring symbols in it are different.

In order to entertain Roman, Denis wrote down $n$ strings $p_1, p_2, p_3, \ldots, p_n$ on the paper and asked him to calculate the beauty of the string $( \ldots (((p_1 \cdot p_2) \cdot p_3) \cdot \ldots ) \cdot p_n$, where $s \cdot t$ denotes a multiplication of strings $s$ and $t$. Roman hasn't fully realized how Denis's multiplication works, so he asked you for a help. Denis knows, that Roman is very impressionable, he guarantees, that the beauty of the resulting string is at most $10^9$.

-----Input-----

The first line contains a single integer $n$ ($2 \leq n \leq 100\,000$) — the number of strings, wroted by Denis.

Next $n$ lines contain non-empty strings $p_1, p_2, \ldots, p_n$, consisting of lowercase english letters.

It's guaranteed, that the total length of the strings $p_i$...

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

def mult(s, t):
    f1, l1, cntf1, cntl1, beaut1, n1 = s
    f2, l2, cntf2, cntl2, beaut2, n2, p = t
    f3, l3, cntf3, cntl3, beaut3, n3 = 0, 0, 0, 0, beaut1, 0
    f3 = f1
    l3 = l1
    n3 = n1 * (n2 + 1) + n2
    if cntf1 >= n1 and f1 == f2:
        cntf3 = n1 * (cntf2 + 1) + cntf2
    else:
        cntf3 = cntf1
    if cntl1 == n1 and l1 == l2:
        cntl3 = n1 * (cntl2 + 1) + cntl2
    else:
        cntl3 = cntl1
    if f1 != l1:
        if f1 in p:
            beaut3 = max(beaut3, cntf1 + 1)
        if l1 in p:
            beaut3 = max(beaut3, cntl1 + 1)
    elif cntf1 >= n1:
        beaut3 = max(n1, beaut3)
        ans = 0
        h = 0
        for d in p:
            if d == f1:
                h += 1
                ans = max(ans, h)
            else:
                h = 0
        ans = max(ans, h)
        beaut3 = max(beaut3, n1 * (ans + 1) + ans)
    else:
        if f1 in p:
            beaut3 = max(beaut3, 1 + cntf1 + cntl1)
        else:
            beaut3 = max(beaut3, cntf1, cntl1)
    return [f3, l3, cntf3, cntl3, beaut3, n3]

n = int(input())
p = []
for i in range(n):
    p.append(input())
pp = []
for s in p:
    f = s[0]
    l = s[-1]
    cntf = 0
    cntl = 0
    beaut = 1
    hep = 1
    for i in s:
        if i == f:
            cntf += 1
        else:
            break
    for i in s[::-1]:
        if i == l:
            cntl += 1
        else:
            break
    for i in range(1, len(s)):
        if s[i] == s[i - 1]:
            hep += 1
        else:
            beaut = max(beaut, hep)
            hep = 1
    beaut = max(beaut, hep)
    pp.append([f, l, cntf, cntl, beaut, len(s), s])
p = pp[::-1]
lasts = p[0][:-1]
for i in range(1, len(p)):
    lasts = mult(lasts, p[i])
print(lasts[-2])


I found an interesting problem on https://codeforces.com/problemset/problem/1131/F:
Asya loves animals very much. Recently, she purchased $n$ kittens, enumerated them from $1$ and $n$ and then put them into the cage. The cage consists of one row of $n$ cells, enumerated with integers from $1$ to $n$ from left to right. Adjacent cells had a partially transparent partition wall between them, hence there were $n - 1$ partitions originally. Initially, each cell contained exactly one kitten with some number.

Observing the kittens, Asya noticed, that they are very friendly and often a pair of kittens in neighboring cells wants to play together. So Asya started to remove partitions between neighboring cells. In particular, on the day $i$, Asya:  Noticed, that the kittens $x_i$ and $y_i$, located in neighboring cells want to play together.  Removed the partition between these two cells, efficiently creating a single cell, having all kittens from two original cells.

Since Asya has never putted partitions back, after $n - 1$ days the cage contained a single cell, having all kittens.

For every day, Asya remembers numbers of kittens $x_i$ and $y_i$, who wanted to play together, however she doesn't remember how she placed kittens in the cage in the beginning. Please help her and find any possible initial arrangement of the kittens into $n$ cells.

-----Input-----

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

Each of the following $n - 1$ lines contains integers $x_i$ and $y_i$ ($1 \le x_i, y_i \le n$, $x_i \ne y_i$) — indices of kittens, which got together due to the border removal on the corresponding day.

It's guaranteed, that the kittens $x_i$ and $y_i$ were in the different cells before this day.

-----Output-----

For every cell from $1$ to $n$ print a single integer — the index of the kitten from $1$ to $n$, who was originally in it.

All printed integers must be distinct.

It's guaranteed, that there is at least one answer possible. In case there are multiple possible answers, print any of them.

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

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

n = int(input())

# 要素iの親（マージ先）を指す
parent = [i for i in range(n+1)]

# 各要素をここにマージしていく
group = [[i] for i in range(n+1)]

for i in range(n-1):
    x, y = map(int, input().split())
    # xのマージ先の配列の要素数 >= yのマージ先の配列の要素数となるようにxとyを入れ替える（マージテクの前処理）
    if len(group[parent[x]]) < len(group[parent[y]]):
        x, y = y, x

    # 要素数が大きい方へマージする（マージテク）
    group[parent[x]] += group[parent[y]]

    # マージされた各要素の親（マージ先）の情報を更新する
    for j in group[parent[y]]:
        parent[j] = parent[x]

print(*group[parent[1]])


I found an interesting problem on https://codeforces.com/problemset/problem/1132/A:
A string is called bracket sequence if it does not contain any characters other than "(" and ")". A bracket sequence is called regular if it it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, "", "(())" and "()()" are regular bracket sequences; "))" and ")((" are bracket sequences (but not regular ones), and "(a)" and "(1)+(1)" are not bracket sequences at all.

You have a number of strings; each string is a bracket sequence of length $2$. So, overall you have $cnt_1$ strings "((", $cnt_2$ strings "()", $cnt_3$ strings ")(" and $cnt_4$ strings "))". You want to write all these strings in some order, one after another; after that, you will get a long bracket sequence of length $2(cnt_1 + cnt_2 + cnt_3 + cnt_4)$. You wonder: is it possible to choose some order of the strings you have such that you will get a regular bracket sequence? Note that you may not remove any characters or strings, and you may not add anything either.

-----Input-----

The input consists of four lines, $i$-th of them contains one integer $cnt_i$ ($0 \le cnt_i \le 10^9$).

-----Output-----

Print one integer: $1$ if it is possible to form a regular bracket sequence by choosing the correct order of the given strings, $0$ otherwise.

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

Output
1

Input
0
0
0
0

Output
1

Input
1
2
3
4

Output
0

-----Note-----

In the first example it is possible to construct a string "(())()(()((()()()())))", which is a regular bracket sequence.

In the second example it is possible to construct a string "", which is a regular bracket sequence.

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

cnt1=int(input())
cnt2=int(input())
cnt3=int(input())
cnt4=int(input())

if cnt1 == cnt4 and cnt1 > 0:
    print(1)
    return
if cnt1 == cnt4 and cnt3 == 0:
    print(1)
    return
print(0)


I found an interesting problem on https://codeforces.com/problemset/problem/1132/B:
You came to a local shop and want to buy some chocolate bars. There are $n$ bars in the shop, $i$-th of them costs $a_i$ coins (and you want to buy all of them).

You have $m$ different coupons that allow you to buy chocolate bars. $i$-th coupon allows you to buy $q_i$ chocolate bars while you have to pay only for the $q_i - 1$ most expensive ones (so, the cheapest bar of those $q_i$ bars is for free).

You can use only one coupon; if you use coupon $i$, you have to choose $q_i$ bars and buy them using the coupon, and buy all the remaining $n - q_i$ bars without any discounts.

To decide which coupon to choose, you want to know what will be the minimum total amount of money you have to pay if you use one of the coupons optimally.

-----Input-----

The first line contains one integer $n$ ($2 \le n \le 3 \cdot 10^5$) — the number of chocolate bars in the shop.

The second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($1 \le a_i \le 10^9$), where $a_i$ is the cost of $i$-th chocolate bar.

The third line contains one integer $m$ ($1 \le m \le n - 1$) — the number of coupons you have.

The fourth line contains $m$ integers $q_1$, $q_2$, ..., $q_m$ ($2 \le q_i \le n$), where $q_i$ is the number of chocolate bars you have to buy using $i$-th coupon so that the least expensive of them will be for free. All values of $q_i$ are pairwise distinct.

-----Output-----

Print $m$ integers, $i$-th of them should be the minimum amount of money you have to pay if you buy $q_i$ bars with $i$-th coupon, and all the remaining bars one by one for their full price.

-----Example-----
Input
7
7 1 3 1 4 10 8
2
3 4

Output
27
30

-----Note-----

Consider the first example.

If we use the first coupon, we may choose chocolate bars having indices $1$, $6$ and $7$, and we pay $18$ coins for them and $9$ coins for all other bars.

If we use the second coupon, we may choose chocolate bars having indices $1$, $5$, $6$ and $7$, and we pay $25$ coins for them and $5$ coins for all other bars.

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

n = int(input())
a = list(map(int, input().split()))
s = sum(a)
a.sort(reverse=True)
m = int(input())
q = list(map(int, input().split()))
for i in q:
    print(s - a[i - 1])


I found an interesting problem on https://codeforces.com/problemset/problem/1132/C:
You have a long fence which consists of $n$ sections. Unfortunately, it is not painted, so you decided to hire $q$ painters to paint it. $i$-th painter will paint all sections $x$ such that $l_i \le x \le r_i$.

Unfortunately, you are on a tight budget, so you may hire only $q - 2$ painters. Obviously, only painters you hire will do their work.

You want to maximize the number of painted sections if you choose $q - 2$ painters optimally. A section is considered painted if at least one painter paints it.

-----Input-----

The first line contains two integers $n$ and $q$ ($3 \le n, q \le 5000$) — the number of sections and the number of painters availible for hire, respectively.

Then $q$ lines follow, each describing one of the painters: $i$-th line contains two integers $l_i$ and $r_i$ ($1 \le l_i \le r_i \le n$).

-----Output-----

Print one integer — maximum number of painted sections if you hire $q - 2$ painters.

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

Output
7

Input
4 3
1 1
2 2
3 4

Output
2

Input
4 4
1 1
2 2
2 3
3 4

Output
3

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

# -*- coding: utf-8 -*-
# @Time    : 2019/3/7 13:43
# @Author  : LunaFire
# @Email   : gilgemesh2012@gmail.com
# @File    : C. Painting the Fence.py

def main():
    n, q = list(map(int, input().split()))
    painters = []
    for _ in range(q):
        painters.append(list(map(int, input().split())))
    # print(painters)

    ret = 0
    for index in range(q):
        mask = [0] * (n + 1)
        for i in range(q):
            if i == index:
                continue
            left, right = painters[i]
            mask[left - 1] += 1
            mask[right] -= 1

        curr_sum, paint_count = 0, 0
        section_count = [0] * n
        for i in range(n):
            curr_sum += mask[i]
            section_count[i] = curr_sum
            if section_count[i] > 0:
                paint_count += 1

        one_count = [0] * (n + 1)
        for i in range(n):
            one_count[i + 1] = one_count[i] + (1 if section_count[i] == 1 else 0)

        desc_ones = n
        for i in range(q):
            if i == index:
                continue
            left, right = painters[i]
            desc_ones = min(desc_ones, one_count[right] - one_count[left - 1])

        ret = max(ret, paint_count - desc_ones)
    print(ret)

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1132/E:
You have a set of items, each having some integer weight not greater than $8$. You denote that a subset of items is good if total weight of items in the subset does not exceed $W$.

You want to calculate the maximum possible weight of a good subset of items. Note that you have to consider the empty set and the original set when calculating the answer.

-----Input-----

The first line contains one integer $W$ ($0 \le W \le 10^{18}$) — the maximum total weight of a good subset.

The second line denotes the set of items you have. It contains $8$ integers $cnt_1$, $cnt_2$, ..., $cnt_8$ ($0 \le cnt_i \le 10^{16}$), where $cnt_i$ is the number of items having weight $i$ in the set.

-----Output-----

Print one integer — the maximum possible weight of a good subset of items.

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

Output
10

Input
0
0 0 0 0 0 0 0 0

Output
0

Input
3
0 4 1 0 0 9 8 3

Output
3

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

import time
import random
W = int(input())
M = [int(a) for a in input().split()]
A = [0] * 8
sTime = time.time()

s = 0
mi = 10**20
for i in range(8):
    if s + M[i]*(i+1) <= W:
        s += M[i]*(i+1)
        A[i] = M[i]
    else:
        t = (W-s)//(i+1)
        s += t*(i+1)
        A[i] += t

    if s <= W:
        mi = min(mi, W-s)

while time.time() - sTime < 1.7:
    i = random.randrange(8)
    a = random.randrange(2)
    if W-s >= 20 or (s-W < 10 and a == 0):
        if A[i] < M[i]:
            A[i] += 1
            s += (i+1)
    else:
        if A[i] > 0:
            A[i] -= 1
            s -= (i+1)

    if s <= W:
        mi = min(mi, W-s)

print(W-mi)


I found an interesting problem on https://codeforces.com/problemset/problem/1132/F:
You are given a string $s$ of length $n$ consisting of lowercase Latin letters. You may apply some operations to this string: in one operation you can delete some contiguous substring of this string, if all letters in the substring you delete are equal. For example, after deleting substring bbbb from string abbbbaccdd we get the string aaccdd.

Calculate the minimum number of operations to delete the whole string $s$.

-----Input-----

The first line contains one integer $n$ ($1 \le n \le 500$) — the length of string $s$.

The second line contains the string $s$ ($|s| = n$) consisting of lowercase Latin letters.

-----Output-----

Output a single integer — the minimal number of operation to delete string $s$.

-----Examples-----
Input
5
abaca

Output
3
Input
8
abcddcba

Output
4

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

#credits https://www.geeksforgeeks.org/minimum-steps-to-delete-a-ssing-after-repeated-deletion-of-palindrome-subssings/

n=int(input())
s=input()
N = len(s)
dp = [[0 for x in range(N + 1)]
         for y in range(N + 1)]
D = [[[] for x in range(N + 1)]
         for y in range(N + 1)]
ss=""
re=""
for i in range(0,N):
    if re!=s[i]:
        ss+=re
        re=s[i]
ss+=re
a=ss
N=len(a)
for l in range(1, N + 1):
    i = 0
    j = l - 1
    while j < N:
        if (l == 1):
            dp[i][j] = 1
        else:

            dp[i][j] =1+dp[i + 1][j]

            for K in range(i + 1, j + 1):
                if (a[i] == a[K]):
                        if dp[i][j]>=dp[i ][K - 1] + dp[K + 1][j]:
                            dp[i][j] = dp[i][K - 1] + dp[K + 1][j]

        i += 1
        j += 1

print(dp[0][N-1])


I found an interesting problem on https://codeforces.com/problemset/problem/1133/A:
Polycarp is going to participate in the contest. It starts at $h_1:m_1$ and ends at $h_2:m_2$. It is guaranteed that the contest lasts an even number of minutes (i.e. $m_1 \% 2 = m_2 \% 2$, where $x \% y$ is $x$ modulo $y$). It is also guaranteed that the entire contest is held during a single day. And finally it is guaranteed that the contest lasts at least two minutes.

Polycarp wants to know the time of the midpoint of the contest. For example, if the contest lasts from $10:00$ to $11:00$ then the answer is $10:30$, if the contest lasts from $11:10$ to $11:12$ then the answer is $11:11$.

-----Input-----

The first line of the input contains two integers $h_1$ and $m_1$ in the format hh:mm.

The second line of the input contains two integers $h_2$ and $m_2$ in the same format (hh:mm).

It is guaranteed that $0 \le h_1, h_2 \le 23$ and $0 \le m_1, m_2 \le 59$.

It is guaranteed that the contest lasts an even number of minutes (i.e. $m_1 \% 2 = m_2 \% 2$, where $x \% y$ is $x$ modulo $y$). It is also guaranteed that the entire contest is held during a single day. And finally it is guaranteed that the contest lasts at least two minutes.

-----Output-----

Print two integers $h_3$ and $m_3$ ($0 \le h_3 \le 23, 0 \le m_3 \le 59$) corresponding to the midpoint of the contest in the format hh:mm. Print each number as exactly two digits (prepend a number with leading zero if needed), separate them with ':'.

-----Examples-----
Input
10:00
11:00

Output
10:30

Input
11:10
11:12

Output
11:11

Input
01:02
03:02

Output
02:02

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

h1, m1 = map(int, input().split(':'))
h2, m2 = map(int, input().split(':'))
diff = h1*60 + m1 + ((h2*60 + m2) - (h1*60 + m1))//2
hres = diff // 60
mres = diff % 60
print(str(hres).zfill(2), str(mres).zfill(2), sep=':')


I found an interesting problem on https://codeforces.com/problemset/problem/1133/B:
International Women's Day is coming soon! Polycarp is preparing for the holiday.

There are $n$ candy boxes in the shop for sale. The $i$-th box contains $d_i$ candies.

Polycarp wants to prepare the maximum number of gifts for $k$ girls. Each gift will consist of exactly two boxes. The girls should be able to share each gift equally, so the total amount of candies in a gift (in a pair of boxes) should be divisible by $k$. In other words, two boxes $i$ and $j$ ($i \ne j$) can be combined as a gift if $d_i + d_j$ is divisible by $k$.

How many boxes will Polycarp be able to give? Of course, each box can be a part of no more than one gift. Polycarp cannot use boxes "partially" or redistribute candies between them.

-----Input-----

The first line of the input contains two integers $n$ and $k$ ($1 \le n \le 2 \cdot 10^5, 1 \le k \le 100$) — the number the boxes and the number the girls.

The second line of the input contains $n$ integers $d_1, d_2, \dots, d_n$ ($1 \le d_i \le 10^9$), where $d_i$ is the number of candies in the $i$-th box.

-----Output-----

Print one integer — the maximum number of the boxes Polycarp can give as gifts.

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

Output
6

Input
8 2
1 2 2 3 2 4 6 10

Output
8

Input
7 3
1 2 2 3 2 4 5

Output
4

-----Note-----

In the first example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes):   $(2, 3)$;  $(5, 6)$;  $(1, 4)$.

So the answer is $6$.

In the second example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes):   $(6, 8)$;  $(2, 3)$;  $(1, 4)$;  $(5, 7)$.

So the answer is $8$.

In the third example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes):   $(1, 2)$;  $(6, 7)$.

So the answer is $4$.

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

n,k=map(int,input().split())
d=[*map(int,input().split())]
cnt=[0]*k
for i in d:
    cnt[i%k]+=1
ans=cnt[0]//2
for i in range(1,k):
    req=k-i
    if i<req:
        ans+=min(cnt[i],cnt[req])
    elif i==req:
        ans+=cnt[i]//2
print(ans*2)


I found an interesting problem on https://codeforces.com/problemset/problem/1133/C:
You are a coach at your local university. There are $n$ students under your supervision, the programming skill of the $i$-th student is $a_i$.

You have to create a team for a new programming competition. As you know, the more students some team has the more probable its victory is! So you have to create a team with the maximum number of students. But you also know that a team should be balanced. It means that the programming skill of each pair of students in a created team should differ by no more than $5$.

Your task is to report the maximum possible number of students in a balanced team.

-----Input-----

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

The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$), where $a_i$ is a programming skill of the $i$-th student.

-----Output-----

Print one integer — the maximum possible number of students in a balanced team.

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

Output
3

Input
10
1337 1337 1337 1337 1337 1337 1337 1337 1337 1337

Output
10

Input
6
1 1000 10000 10 100 1000000000

Output
1

-----Note-----

In the first example you can create a team with skills $[12, 17, 15]$.

In the second example you can take all students in a team because their programming skills are equal.

In the third example you can create a team consisting of a single student (and you cannot create a team consisting of at least two students).

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

def main():
    n = int(input())
    arr = sorted(list(map(int, input().split())))
    ans = 0
    a = 0
    b = 0
    while b < n:
        if (arr[b] - arr[a] <= 5):
            ans = max(ans, b - a + 1)
            b += 1
        else:
            a += 1
    print(ans)

main()


I found an interesting problem on https://codeforces.com/problemset/problem/1133/D:
You are given two arrays $a$ and $b$, each contains $n$ integers.

You want to create a new array $c$ as follows: choose some real (i.e. not necessarily integer) number $d$, and then for every $i \in [1, n]$ let $c_i := d \cdot a_i + b_i$.

Your goal is to maximize the number of zeroes in array $c$. What is the largest possible answer, if you choose $d$ optimally?

-----Input-----

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

The second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($-10^9 \le a_i \le 10^9$).

The third line contains $n$ integers $b_1$, $b_2$, ..., $b_n$ ($-10^9 \le b_i \le 10^9$).

-----Output-----

Print one integer — the maximum number of zeroes in array $c$, if you choose $d$ optimally.

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

Output
2

Input
3
13 37 39
1 2 3

Output
2

Input
4
0 0 0 0
1 2 3 4

Output
0

Input
3
1 2 -1
-6 -12 6

Output
3

-----Note-----

In the first example, we may choose $d = -2$.

In the second example, we may choose $d = -\frac{1}{13}$.

In the third example, we cannot obtain any zero in array $c$, no matter which $d$ we choose.

In the fourth example, we may choose $d = 6$.

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

def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

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

pre = 0
for ai, bi in zip(a, b):
    if (ai, bi) == (0, 0):
        pre += 1

fracs = [(-bi // gcd(ai, bi), ai // gcd(ai, bi)) if ai
         != 0 else float('inf') for ai, bi in zip(a, b)]

cnt = {item: 0 for item in fracs}

for x in fracs:
    if x != float('inf'):
        cnt[x] += 1

print(max(cnt.values()) + pre)


I found an interesting problem on https://codeforces.com/problemset/problem/1133/E:
You are a coach at your local university. There are $n$ students under your supervision, the programming skill of the $i$-th student is $a_i$.

You have to form $k$ teams for yet another new programming competition. As you know, the more students are involved in competition the more probable the victory of your university is! So you have to form no more than $k$ (and at least one) non-empty teams so that the total number of students in them is maximized. But you also know that each team should be balanced. It means that the programming skill of each pair of students in each team should differ by no more than $5$. Teams are independent from one another (it means that the difference between programming skills of two students from two different teams does not matter).

It is possible that some students not be included in any team at all.

Your task is to report the maximum possible total number of students in no more than $k$ (and at least one) non-empty balanced teams.

If you are Python programmer, consider using PyPy instead of Python when you submit your code.

-----Input-----

The first line of the input contains two integers $n$ and $k$ ($1 \le k \le n \le 5000$) — the number of students and the maximum number of teams, correspondingly.

The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$), where $a_i$ is a programming skill of the $i$-th student.

-----Output-----

Print one integer — the maximum possible total number of students in no more than $k$ (and at least one) non-empty balanced teams.

-----Examples-----
Input
5 2
1 2 15 15 15

Output
5

Input
6 1
36 4 1 25 9 16

Output
2

Input
4 4
1 10 100 1000

Output
4

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

dp=[]
for i in range(5005):
    dp.append([0]*5005)

n,k=map(int,input().split())
a=list(map(int,input().split()))
a.sort()
p=[0]*(n+1)
for i in range(n):
    z=a[i]-5
    for j in range(i+1):
        if a[j]>=z:
            p[i]=j
            break
ans=-1
for i in range(1,n+1):
    for j in range(k+1):
        dp[i][j]=max(dp[i-1][j],dp[p[i-1]][j-1]+(i-p[i-1]))
        if j!=k:
            ans=max(ans,dp[i][j])
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1133/F1:
You are given an undirected unweighted connected graph consisting of $n$ vertices and $m$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.

Your task is to find any spanning tree of this graph such that the maximum degree over all vertices is maximum possible. Recall that the degree of a vertex is the number of edges incident to it.

-----Input-----

The first line contains two integers $n$ and $m$ ($2 \le n \le 2 \cdot 10^5$, $n - 1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2})$) — the number of vertices and edges, respectively.

The following $m$ lines denote edges: edge $i$ is represented by a pair of integers $v_i$, $u_i$ ($1 \le v_i, u_i \le n$, $u_i \ne v_i$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair ($v_i, u_i$) there are no other pairs ($v_i, u_i$) or ($u_i, v_i$) in the list of edges, and for each pair $(v_i, u_i)$ the condition $v_i \ne u_i$ is satisfied.

-----Output-----

Print $n-1$ lines describing the edges of a spanning tree such that the maximum degree over all vertices is maximum possible. Make sure that the edges of the printed spanning tree form some subset of the input edges (order doesn't matter and edge $(v, u)$ is considered the same as the edge $(u, v)$).

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

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

Output
3 5
2 1
3 2
3 4

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

Output
4 1
1 2
1 3

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

Output
3 2
2 5
8 5
6 1
2 7
1 2
3 4

-----Note-----

Picture corresponding to the first example: [Image]

In this example the number of edges of spanning tree incident to the vertex $3$ is $3$. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer.

Picture corresponding to the second example: [Image]

In this example the number of edges of spanning tree incident to the vertex $1$ is $3$. It is the...

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

from collections import deque
n, m = list(map(int, input().split()))
a = []
rinsetu = [[] for i in range(n+1)]
count = [0 for i in range(n+1)]
for i in range(m):
    u, v = list(map(int, input().split()))
    count[u] += 1
    count[v] += 1
    a.append([u,v])
    rinsetu[u].append(v)
    rinsetu[v].append(u)
root = count.index(max(count))

visitflag = [0 for i in range(n+1)]
queue = deque([root])
while len(queue) > 0:
    now = queue.popleft()
    for i in rinsetu[now]:
        if visitflag[i] == 0:
            visitflag[i] = now
            queue.append(i)

for i in range(1, n+1):
    if i == root:
        continue
    else:
        print(i, visitflag[i])


I found an interesting problem on https://codeforces.com/problemset/problem/1133/F2:
You are given an undirected unweighted connected graph consisting of $n$ vertices and $m$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.

Your task is to find any spanning tree of this graph such that the degree of the first vertex (vertex with label $1$ on it) is equal to $D$ (or say that there are no such spanning trees). Recall that the degree of a vertex is the number of edges incident to it.

-----Input-----

The first line contains three integers $n$, $m$ and $D$ ($2 \le n \le 2 \cdot 10^5$, $n - 1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2}), 1 \le D < n$) — the number of vertices, the number of edges and required degree of the first vertex, respectively.

The following $m$ lines denote edges: edge $i$ is represented by a pair of integers $v_i$, $u_i$ ($1 \le v_i, u_i \le n$, $u_i \ne v_i$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair ($v_i, u_i$) there are no other pairs ($v_i, u_i$) or ($u_i, v_i$) in the list of edges, and for each pair $(v_i, u_i)$ the condition $v_i \ne u_i$ is satisfied.

-----Output-----

If there is no spanning tree satisfying the condition from the problem statement, print "NO" in the first line.

Otherwise print "YES" in the first line and then print $n-1$ lines describing the edges of a spanning tree such that the degree of the first vertex (vertex with label $1$ on it) is equal to $D$. Make sure that the edges of the printed spanning tree form some subset of the input edges (order doesn't matter and edge $(v, u)$ is considered the same as the edge $(u, v)$).

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

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

Output
YES
2 1
2 3
3 4

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

Output
YES
1 2
1 3
4 1

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

Output
NO

-----Note-----

The picture corresponding to the first and second examples: [Image]

The picture corresponding to the third example: [Image]

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

import sys
input = sys.stdin.readline

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

EDGELIST=[[] for i in range(n+1)]

for x,y in E:
    EDGELIST[x].append(y)
    EDGELIST[y].append(x)

Group=[i for i in range(n+1)]

def find(x):
    while Group[x] != x:
        x=Group[x]
    return x

def Union(x,y):
    if find(x) != find(y):
        Group[find(y)]=Group[find(x)]=min(find(y),find(x))

ONE=EDGELIST[1]

for x,y in E:
    if x==1 or y==1:
        continue
    Union(x,y)

ONEU=[find(e) for e in ONE]

if len(set(ONEU))>D or D>len(ONE):
    print("NO")
    return
else:
    print("YES")

USED=set()
ANS=[]
from collections import deque
QUE=deque()
check=[0]*(n+1)
check[1]=1

for j in range(len(ONE)):
    if find(ONE[j]) in USED:
        continue
    else:
        ANS.append([1,ONE[j]])
        QUE.append(ONE[j])
        USED.add(find(ONE[j]))
        check[ONE[j]]=1
        D-=1

j=0
for i in range(D):
    while check[ONE[j]]==1:
        j+=1
    ANS.append([1,ONE[j]])
    QUE.append(ONE[j])
    check[ONE[j]]=1

while QUE:
    x=QUE.popleft()
    check[x]=1

    for to in EDGELIST[x]:
        if check[to]==0:
            ANS.append([x,to])
            QUE.append(to)
            check[to]=1

#print(ANS)
for x,y in ANS:
    print(x,y)


I found an interesting problem on https://codeforces.com/problemset/problem/1136/A:
After lessons Nastya decided to read a book. The book contains $n$ chapters, going one after another, so that one page of the book belongs to exactly one chapter and each chapter contains at least one page.

Yesterday evening Nastya did not manage to finish reading the book, so she marked the page with number $k$ as the first page which was not read (i.e. she read all pages from the $1$-st to the $(k-1)$-th).

The next day Nastya's friend Igor came and asked her, how many chapters remain to be read by Nastya? Nastya is too busy now, so she asks you to compute the number of chapters she has not completely read yet (i.e. the number of chapters she has not started to read or has finished reading somewhere in the middle).

-----Input-----

The first line contains a single integer $n$ ($1 \leq n \leq 100$) — the number of chapters in the book.

There are $n$ lines then. The $i$-th of these lines contains two integers $l_i$, $r_i$ separated by space ($l_1 = 1$, $l_i \leq r_i$) — numbers of the first and the last pages of the $i$-th chapter. It's guaranteed that $l_{i+1} = r_i + 1$ for all $1 \leq i \leq n-1$, and also that every chapter contains at most $100$ pages.

The $(n+2)$-th line contains a single integer $k$ ($1 \leq k \leq r_n$) — the index of the marked page.

-----Output-----

Print a single integer — the number of chapters which has not been completely read so far.

-----Examples-----
Input
3
1 3
4 7
8 11
2

Output
3

Input
3
1 4
5 9
10 12
9

Output
2

Input
1
1 7
4

Output
1

-----Note-----

In the first example the book contains $11$ pages and $3$ chapters — $[1;3]$, $[4;7]$ and $[8;11]$. Nastya marked the $2$-nd page, so she finished in the middle of the $1$-st chapter. So, all chapters has not been read so far, so the answer is $3$.

The book in the second example contains $12$ pages and $3$ chapters too, but Nastya finished reading in the middle of the $2$-nd chapter, so that the answer is $2$.

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

n = int(input())
arr = [list(map(int, input().split())) for i in range(n)]
k = int(input()) - 1
cnt = 0
for el in arr:
	if el[1] <= k:
		cnt += 1
print(n - cnt)


I found an interesting problem on https://codeforces.com/problemset/problem/1136/B:
Finished her homework, Nastya decided to play computer games. Passing levels one by one, Nastya eventually faced a problem. Her mission is to leave a room, where a lot of monsters live, as quickly as possible.

There are $n$ manholes in the room which are situated on one line, but, unfortunately, all the manholes are closed, and there is one stone on every manhole. There is exactly one coin under every manhole, and to win the game Nastya should pick all the coins. Initially Nastya stands near the $k$-th manhole from the left. She is thinking what to do.

In one turn, Nastya can do one of the following:   if there is at least one stone on the manhole Nastya stands near, throw exactly one stone from it onto any other manhole (yes, Nastya is strong).  go to a neighboring manhole;  if there are no stones on the manhole Nastya stays near, she can open it and pick the coin from it. After it she must close the manhole immediately (it doesn't require additional moves).

 [Image] The figure shows the intermediate state of the game. At the current position Nastya can throw the stone to any other manhole or move left or right to the neighboring manholes. If she were near the leftmost manhole, she could open it (since there are no stones on it).

Nastya can leave the room when she picks all the coins. Monsters are everywhere, so you need to compute the minimum number of moves Nastya has to make to pick all the coins.

Note one time more that Nastya can open a manhole only when there are no stones onto it.

-----Input-----

The first and only line contains two integers $n$ and $k$, separated by space ($2 \leq n \leq 5000$, $1 \leq k \leq n$) — the number of manholes and the index of manhole from the left, near which Nastya stays initially. Initially there is exactly one stone near each of the $n$ manholes.

-----Output-----

Print a single integer — minimum number of moves which lead Nastya to pick all the coins.

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

Output
6

Input
4 2

Output
13

Input
5...

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

n, k = (int(t) for t in input().split(' '))
print(n*3 + min(k-1, (n-k)))


I found an interesting problem on https://codeforces.com/problemset/problem/1136/C:
Nastya came to her informatics lesson, and her teacher who is, by the way, a little bit famous here gave her the following task.

Two matrices $A$ and $B$ are given, each of them has size $n \times m$. Nastya can perform the following operation to matrix $A$ unlimited number of times:   take any square square submatrix of $A$ and transpose it (i.e. the element of the submatrix which was in the $i$-th row and $j$-th column of the submatrix will be in the $j$-th row and $i$-th column after transposing, and the transposed submatrix itself will keep its place in the matrix $A$).

Nastya's task is to check whether it is possible to transform the matrix $A$ to the matrix $B$.

 $\left. \begin{array}{|c|c|c|c|c|c|c|c|} \hline 6 & {3} & {2} & {11} \\ \hline 5 & {9} & {4} & {2} \\ \hline 3 & {3} & {3} & {3} \\ \hline 4 & {8} & {2} & {2} \\ \hline 7 & {8} & {6} & {4} \\ \hline \end{array} \right.$ Example of the operation

As it may require a lot of operations, you are asked to answer this question for Nastya.

A square submatrix of matrix $M$ is a matrix which consist of all elements which comes from one of the rows with indeces $x, x+1, \dots, x+k-1$ of matrix $M$ and comes from one of the columns with indeces $y, y+1, \dots, y+k-1$ of matrix $M$. $k$ is the size of square submatrix. In other words, square submatrix is the set of elements of source matrix which form a solid square (i.e. without holes).

-----Input-----

The first line contains two integers $n$ and $m$ separated by space ($1 \leq n, m \leq 500$) — the numbers of rows and columns in $A$ and $B$ respectively.

Each of the next $n$ lines contains $m$ integers, the $j$-th number in the $i$-th of these lines denotes the $j$-th element of the $i$-th row of the matrix $A$ ($1 \leq A_{ij} \leq 10^{9}$).

Each of the next $n$ lines contains $m$ integers, the $j$-th number in the $i$-th of these lines denotes the $j$-th element of the $i$-th row of the matrix $B$ ($1 \leq B_{ij} \leq 10^{9}$).

-----Output-----

Print "YES" (without quotes) if it is...

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

'''input
3 3
1 2 3
4 5 6
7 8 9
1 4 7
2 5 6
3 8 9
'''
import sys
from collections import defaultdict as dd
from itertools import  permutations as pp
from itertools import combinations as cc
from collections import Counter as ccd
from random import randint as rd
from bisect import bisect_left as bl
import heapq
mod=10**9+7

def ri(flag=0):
	if flag==0:
		return [int(i) for i in sys.stdin.readline().split()]
	else:
		return int(sys.stdin.readline())

n,m=ri()

mat=[]
mat1=[]
for i in range(n):
	mat.append(ri())
for i in range(n):
	mat1.append(ri())
one=dd(list)
for i in range(n):
	for j in range(m):
		one[i+j].append(mat[i][j])

two=dd(list)
for i in range(n):
	for j in range(m):
		two[i+j].append(mat1[i][j])

for i in one:
	one[i].sort()
for i in two:
	two[i].sort()

f=1
for i in one:
	if one[i]!=two[i]:
		f=0
if f:
	print("YES")
else:
	print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/1136/D:
At the big break Nastya came to the school dining room. There are $n$ pupils in the school, numbered from $1$ to $n$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.

Formally, there are some pairs $u$, $v$ such that if the pupil with number $u$ stands directly in front of the pupil with number $v$, Nastya can ask them and they will change places.

Nastya asks you to find the maximal number of places in queue she can move forward.

-----Input-----

The first line contains two integers $n$ and $m$ ($1 \leq n \leq 3 \cdot 10^{5}$, $0 \leq m \leq 5 \cdot 10^{5}$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second.

The second line contains $n$ integers $p_1$, $p_2$, ..., $p_n$ — the initial arrangement of pupils in the queue, from the queue start to its end ($1 \leq p_i \leq n$, $p$ is a permutation of integers from $1$ to $n$). In other words, $p_i$ is the number of the pupil who stands on the $i$-th position in the queue.

The $i$-th of the following $m$ lines contains two integers $u_i$, $v_i$ ($1 \leq u_i, v_i \leq n, u_i \neq v_i$), denoting that the pupil with number $u_i$ agrees to change places with the pupil with number $v_i$ if $u_i$ is directly in front of $v_i$. It is guaranteed that if $i \neq j$, than $v_i \neq v_j$ or $u_i \neq u_j$. Note that it is possible that in some pairs both pupils agree to change places with each other.

Nastya is the last person in the queue, i.e. the pupil with number $p_n$.

-----Output-----

Print a single integer — the number of places in queue she can move forward.

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

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

Output
2
Input
5 2
3 1 5 4 2
5 2
5...

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

def __starting_point():
    n, m = (int(x) for x in input().split())
    queue = [int(x) - 1 for x in input().split()]
    id___passables = [set() for _ in range(n)]
    for _ in range(m):
        id1, id2 = (int(x) - 1 for x in input().split())
        id___passables[id2].add(id1)
    train_passables = id___passables[queue[-1]].copy()
    ans = 0
    for person in reversed(queue[:-1]):
        if person in train_passables:
            ans += 1
        else:
            train_passables &= id___passables[person]
    print(ans)
    # swapable = [[int(x) for x in input().split()] for _ in range(m)]

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1137/A:
Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $n$ streets along the Eastern direction and $m$ streets across the Southern direction. Naturally, this city has $nm$ intersections. At any intersection of $i$-th Eastern street and $j$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.

When Dora passes through the intersection of the $i$-th Eastern and $j$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.

Formally, on every of $nm$ intersections Dora solves an independent problem. She sees $n + m - 1$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $x$ and assign every skyscraper a height from $1$ to $x$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $x$.

For example, if the intersection and the two streets corresponding to it look as follows: [Image]

Then it is optimal to replace the heights of the skyscrapers as...

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

n, m = list(map(int, input().split()))
gor = []
ver = []
o = []
for i in range(n):
    gor.append(list(map(int, input().split())))
    o.append([])
for i in range(m):
    ver.append([])
for i in range(m):
    for g in gor:
        ver[i].append(g[i])
ver = list([sorted(list(set(x))) for x in ver])

def f(vg, vr, o):
    vr1 = vr.index(o)
    vg1 = vg.index(o)
    if vr1 > vg1:
        return max([len(vr), len(vg) + vr1 - vg1])
    return max([len(vg), len(vr) + vg1 - vr1])

for i, vg in enumerate(gor):
    vg1 = sorted(list(set(vg)))
    for j, vr in enumerate(vg):
        o[i].append(f(vg1, ver[j], vr))
for i in o:
    print(' '.join(list(map(str, i))))


I found an interesting problem on https://codeforces.com/problemset/problem/1137/B:
The new camp by widely-known over the country Spring Programming Camp is going to start soon. Hence, all the team of friendly curators and teachers started composing the camp's schedule. After some continuous discussion, they came up with a schedule $s$, which can be represented as a binary string, in which the $i$-th symbol is '1' if students will write the contest in the $i$-th day and '0' if they will have a day off.

At the last moment Gleb said that the camp will be the most productive if it runs with the schedule $t$ (which can be described in the same format as schedule $s$). Since the number of days in the current may be different from number of days in schedule $t$, Gleb required that the camp's schedule must be altered so that the number of occurrences of $t$ in it as a substring is maximum possible. At the same time, the number of contest days and days off shouldn't change, only their order may change.

Could you rearrange the schedule in the best possible way?

-----Input-----

The first line contains string $s$ ($1 \leqslant |s| \leqslant 500\,000$), denoting the current project of the camp's schedule.

The second line contains string $t$ ($1 \leqslant |t| \leqslant 500\,000$), denoting the optimal schedule according to Gleb.

Strings $s$ and $t$ contain characters '0' and '1' only.

-----Output-----

In the only line print the schedule having the largest number of substrings equal to $t$. Printed schedule should consist of characters '0' and '1' only and the number of zeros should be equal to the number of zeros in $s$ and the number of ones should be equal to the number of ones in $s$.

In case there multiple optimal schedules, print any of them.

-----Examples-----
Input
101101
110

Output
110110
Input
10010110
100011

Output
01100011

Input
10
11100

Output
01

-----Note-----

In the first example there are two occurrences, one starting from first position and one starting from fourth position.

In the second example there is only one occurrence, which starts from third position. Note,...

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

s = input()
t = input()
overlap = t
tt = ''
for i in range(len(t) - 1):
    tt = tt + t[i]
    if (t.endswith(tt)):
        overlap = t[i + 1:]
zro = s.count('0')
mek = s.count('1')
zro_tum = t.count('0')
mek_tum = t.count('1')
zro_toxum = overlap.count('0')
mek_toxum = overlap.count('1')

if (zro >= zro_tum and mek >= mek_tum):
    print(t, end='')
    zro -= zro_tum
    mek -= mek_tum
if zro_toxum:
    k = zro//zro_toxum
else:
    k = 10000000000
if mek_toxum:
    n = mek//mek_toxum
else:
    n = 10000000000
ans = min(n, k)
print(overlap * ans, end='')
zro -= zro_toxum * ans
mek -= mek_toxum * ans
print('0' * zro + '1' * mek)


I found an interesting problem on https://codeforces.com/problemset/problem/1138/A:
Arkady invited Anna for a dinner to a sushi restaurant. The restaurant is a bit unusual: it offers $n$ pieces of sushi aligned in a row, and a customer has to choose a continuous subsegment of these sushi to buy.

The pieces of sushi are of two types: either with tuna or with eel. Let's denote the type of the $i$-th from the left sushi as $t_i$, where $t_i = 1$ means it is with tuna, and $t_i = 2$ means it is with eel.

Arkady does not like tuna, Anna does not like eel. Arkady wants to choose such a continuous subsegment of sushi that it has equal number of sushi of each type and each half of the subsegment has only sushi of one type. For example, subsegment $[2, 2, 2, 1, 1, 1]$ is valid, but subsegment $[1, 2, 1, 2, 1, 2]$ is not, because both halves contain both types of sushi.

Find the length of the longest continuous subsegment of sushi Arkady can buy.

-----Input-----

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

The second line contains $n$ integers $t_1$, $t_2$, ..., $t_n$ ($t_i = 1$, denoting a sushi with tuna or $t_i = 2$, denoting a sushi with eel), representing the types of sushi from left to right.

It is guaranteed that there is at least one piece of sushi of each type. Note that it means that there is at least one valid continuous segment.

-----Output-----

Print a single integer — the maximum length of a valid continuous segment.

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

Output
4

Input
6
1 2 1 2 1 2

Output
2

Input
9
2 2 1 1 1 2 2 2 2

Output
6

-----Note-----

In the first example Arkady can choose the subsegment $[2, 2, 1, 1]$ or the subsegment $[1, 1, 2, 2]$ with length $4$.

In the second example there is no way but to choose one of the subsegments $[2, 1]$ or $[1, 2]$ with length $2$.

In the third example Arkady's best choice is the subsegment $[1, 1, 1, 2, 2, 2]$.

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

import sys

def main():
	n = int(input())
	sushi = list(map(int,sys.stdin.readline().split()))
	debut, milieu, fin = 0,0,1
	maxLong = 0
	for i in range(1,n):
		if sushi[i] == sushi[i-1]:
			fin+=1
		else:
			maxLong = max(maxLong, 2*min((fin-milieu, milieu-debut)))
			debut = milieu
			milieu = fin
			fin += 1
	maxLong = max(maxLong, 2*min((n-milieu, milieu-debut)))
	print(maxLong)

main()


I found an interesting problem on https://codeforces.com/problemset/problem/1139/A:
You are given a string $s=s_1s_2\dots s_n$ of length $n$, which only contains digits $1$, $2$, ..., $9$.

A substring $s[l \dots r]$ of $s$ is a string $s_l s_{l + 1} s_{l + 2} \ldots s_r$. A substring $s[l \dots r]$ of $s$ is called even if the number represented by it is even.

Find the number of even substrings of $s$. Note, that even if some substrings are equal as strings, but have different $l$ and $r$, they are counted as different substrings.

-----Input-----

The first line contains an integer $n$ ($1 \le n \le 65000$) — the length of the string $s$.

The second line contains a string $s$ of length $n$. The string $s$ consists only of digits $1$, $2$, ..., $9$.

-----Output-----

Print the number of even substrings of $s$.

-----Examples-----
Input
4
1234

Output
6
Input
4
2244

Output
10

-----Note-----

In the first example, the $[l, r]$ pairs corresponding to even substrings are:   $s[1 \dots 2]$

 $s[2 \dots 2]$

 $s[1 \dots 4]$

 $s[2 \dots 4]$

 $s[3 \dots 4]$

 $s[4 \dots 4]$

In the second example, all $10$ substrings of $s$ are even substrings. Note, that while substrings $s[1 \dots 1]$ and $s[2 \dots 2]$ both define the substring "2", they are still counted as different substrings.

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

import math
import bisect

def argsort(ls):
    return sorted(range(len(ls)), key=ls.__getitem__)

def f(p=0):
    if p==0:
        return int(input())
    if p==1:
        return map(int, input().split())
    elif p==2:
        return list(map(int, input().split()))
    else:
        return sorted(list(map(int, input().split())))

n = f()
s = input()
sm = 0
for i in range(n):
    if int(s[i])%2==0:
        sm+=i+1

print(sm)


I found an interesting problem on https://codeforces.com/problemset/problem/1139/B:
You went to the store, selling $n$ types of chocolates. There are $a_i$ chocolates of type $i$ in stock.

You have unlimited amount of cash (so you are not restricted by any prices) and want to buy as many chocolates as possible. However if you buy $x_i$ chocolates of type $i$ (clearly, $0 \le x_i \le a_i$), then for all $1 \le j < i$ at least one of the following must hold:  $x_j = 0$ (you bought zero chocolates of type $j$) $x_j < x_i$ (you bought less chocolates of type $j$ than of type $i$)

For example, the array $x = [0, 0, 1, 2, 10]$ satisfies the requirement above (assuming that all $a_i \ge x_i$), while arrays $x = [0, 1, 0]$, $x = [5, 5]$ and $x = [3, 2]$ don't.

Calculate the maximum number of chocolates you can buy.

-----Input-----

The first line contains an integer $n$ ($1 \le n \le 2 \cdot 10^5$), denoting the number of types of chocolate.

The next line contains $n$ integers $a_i$ ($1 \le a_i \le 10^9$), denoting the number of chocolates of each type.

-----Output-----

Print the maximum number of chocolates you can buy.

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

Output
10
Input
5
3 2 5 4 10

Output
20
Input
4
1 1 1 1

Output
1

-----Note-----

In the first example, it is optimal to buy: $0 + 0 + 1 + 3 + 6$ chocolates.

In the second example, it is optimal to buy: $1 + 2 + 3 + 4 + 10$ chocolates.

In the third example, it is optimal to buy: $0 + 0 + 0 + 1$ chocolates.

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

n = int(input())
a = list(map(int, input().split()))
c = a[-1]
res = c
for i in a[::-1][1:]:
    if i < c:
        res += i
        c = i
    else:
        if c == 0:
            break
        res += c - 1
        c -= 1
print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/1139/C:
You are given a tree (a connected undirected graph without cycles) of $n$ vertices. Each of the $n - 1$ edges of the tree is colored in either black or red.

You are also given an integer $k$. Consider sequences of $k$ vertices. Let's call a sequence $[a_1, a_2, \ldots, a_k]$ good if it satisfies the following criterion:  We will walk a path (possibly visiting same edge/vertex multiple times) on the tree, starting from $a_1$ and ending at $a_k$.  Start at $a_1$, then go to $a_2$ using the shortest path between $a_1$ and $a_2$, then go to $a_3$ in a similar way, and so on, until you travel the shortest path between $a_{k-1}$ and $a_k$. If you walked over at least one black edge during this process, then the sequence is good.  [Image]

Consider the tree on the picture. If $k=3$ then the following sequences are good: $[1, 4, 7]$, $[5, 5, 3]$ and $[2, 3, 7]$. The following sequences are not good: $[1, 4, 6]$, $[5, 5, 5]$, $[3, 7, 3]$.

There are $n^k$ sequences of vertices, count how many of them are good. Since this number can be quite large, print it modulo $10^9+7$.

-----Input-----

The first line contains two integers $n$ and $k$ ($2 \le n \le 10^5$, $2 \le k \le 100$), the size of the tree and the length of the vertex sequence.

Each of the next $n - 1$ lines contains three integers $u_i$, $v_i$ and $x_i$ ($1 \le u_i, v_i \le n$, $x_i \in \{0, 1\}$), where $u_i$ and $v_i$ denote the endpoints of the corresponding edge and $x_i$ is the color of this edge ($0$ denotes red edge and $1$ denotes black edge).

-----Output-----

Print the number of good sequences modulo $10^9 + 7$.

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

Output
252
Input
4 6
1 2 0
1 3 0
1 4 0

Output
0
Input
3 5
1 2 1
2 3 0

Output
210

-----Note-----

In the first example, all sequences ($4^4$) of length $4$ except the following are good:   $[1, 1, 1, 1]$ $[2, 2, 2, 2]$ $[3, 3, 3, 3]$ $[4, 4, 4, 4]$

In the second example, all edges are red, hence there aren't any good sequences.

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

from collections import defaultdict,deque
MOD = (10**9)+7
def bfs(v):
    q.append(v)
    visited[v]=True
    while q:
        s=q.popleft()
        b.append(v)
        for i in g[s]:
            if not visited[i[0]] and i[1]==0:
                q.append(i[0])
                visited[i[0]]=True

n,k=list(map(int,input().split()))
g=defaultdict(list)
for _ in range(n-1):
    x,y,c=list(map(int,input().split()))
    g[x].append((y,c))
    g[y].append((x,c))
visited=[False]*(n+1)
count=0;ans=pow(n,k,MOD)
q=deque()
for i in range(1,n+1):
    b=[]
    if visited[i]==False:
        bfs(i)
    #print(b)
    f =len(b)
    count=(count+pow(f,k,MOD))%MOD

ans=(ans-count)%MOD
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1139/D:
Vivek initially has an empty array $a$ and some integer constant $m$.

He performs the following algorithm:  Select a random integer $x$ uniformly in range from $1$ to $m$ and append it to the end of $a$.  Compute the greatest common divisor of integers in $a$.  In case it equals to $1$, break  Otherwise, return to step $1$.

Find the expected length of $a$. It can be shown that it can be represented as $\frac{P}{Q}$ where $P$ and $Q$ are coprime integers and $Q\neq 0 \pmod{10^9+7}$. Print the value of $P \cdot Q^{-1} \pmod{10^9+7}$.

-----Input-----

The first and only line contains a single integer $m$ ($1 \leq m \leq 100000$).

-----Output-----

Print a single integer — the expected length of the array $a$ written as $P \cdot Q^{-1} \pmod{10^9+7}$.

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

Output
1

Input
2

Output
2

Input
4

Output
333333338

-----Note-----

In the first example, since Vivek can choose only integers from $1$ to $1$, he will have $a=[1]$ after the first append operation, and after that quit the algorithm. Hence the length of $a$ is always $1$, so its expected value is $1$ as well.

In the second example, Vivek each time will append either $1$ or $2$, so after finishing the algorithm he will end up having some number of $2$'s (possibly zero), and a single $1$ in the end. The expected length of the list is $1\cdot \frac{1}{2} + 2\cdot \frac{1}{2^2} + 3\cdot \frac{1}{2^3} + \ldots = 2$.

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

# https://codeforces.com/blog/entry/66101?#comment-501153
MOD = 10 ** 9 + 7
m = int(input())
f = [0] * (m + 1)
ans = 1
for i in range(m, 1, -1):
    p = m // i * pow(m, MOD - 2, MOD)
    f[i] = p * pow(1 - p, MOD - 2, MOD) % MOD
    for j in range(2 * i, m + 1, i):
        f[i] = (f[i] - f[j]) % MOD
    ans += f[i]
print(ans % MOD)


I found an interesting problem on https://codeforces.com/problemset/problem/1139/E:
There are $n$ students and $m$ clubs in a college. The clubs are numbered from $1$ to $m$. Each student has a potential $p_i$ and is a member of the club with index $c_i$. Initially, each student is a member of exactly one club. A technical fest starts in the college, and it will run for the next $d$ days. There is a coding competition every day in the technical fest.

Every day, in the morning, exactly one student of the college leaves their club. Once a student leaves their club, they will never join any club again. Every day, in the afternoon, the director of the college will select one student from each club (in case some club has no members, nobody is selected from that club) to form a team for this day's coding competition. The strength of a team is the mex of potentials of the students in the team. The director wants to know the maximum possible strength of the team for each of the coming $d$ days. Thus, every day the director chooses such team, that the team strength is maximized.

The mex of the multiset $S$ is the smallest non-negative integer that is not present in $S$. For example, the mex of the $\{0, 1, 1, 2, 4, 5, 9\}$ is $3$, the mex of $\{1, 2, 3\}$ is $0$ and the mex of $\varnothing$ (empty set) is $0$.

-----Input-----

The first line contains two integers $n$ and $m$ ($1 \leq m \leq n \leq 5000$), the number of students and the number of clubs in college.

The second line contains $n$ integers $p_1, p_2, \ldots, p_n$ ($0 \leq p_i < 5000$), where $p_i$ is the potential of the $i$-th student.

The third line contains $n$ integers $c_1, c_2, \ldots, c_n$ ($1 \leq c_i \leq m$), which means that $i$-th student is initially a member of the club with index $c_i$.

The fourth line contains an integer $d$ ($1 \leq d \leq n$), number of days for which the director wants to know the maximum possible strength of the team.

Each of the next $d$ lines contains an integer $k_i$ ($1 \leq k_i \leq n$), which means that $k_i$-th student lefts their club on the $i$-th day. It is guaranteed, that the...

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

import sys
input = sys.stdin.readline

n, m = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
d = int(input())
disable = [False] * n
base = 5001
ds = [int(input())-1 for _ in range(d)]
for ele in ds:
    disable[ele] = True

# Create Graph

childs = [[] for i in range(base+m+1)]

for idx, (i, j) in enumerate(zip(p, c)):
    if not disable[idx]:
        childs[i].append(base+j)

# dfs
# alternative path for finding maximum cardinality

vis = [False]*(base+m+1)
matching = [-1]*(base+m+1)

def dfs(num):
    for child in childs[num]:
        if not vis[child]:
            vis[child] = True
            if matching[child] == -1 or dfs(matching[child]):
                matching[child] = num
                return True
    return False

ans = []
mex = 0
for idx in range(d-1, -1, -1):
    while True:
        vis = [False]*(base+m+1)
        if not dfs(mex):
            break
        mex += 1
    # Add edge
    ans.append(mex)
    childs[p[ds[idx]]].append(base+c[ds[idx]])

print("\n".join([str(a) for a in reversed(ans)]))


I found an interesting problem on https://codeforces.com/problemset/problem/1140/A:
Ivan recently bought a detective book. The book is so interesting that each page of this book introduces some sort of a mystery, which will be explained later. The $i$-th page contains some mystery that will be explained on page $a_i$ ($a_i \ge i$).

Ivan wants to read the whole book. Each day, he reads the first page he didn't read earlier, and continues to read the following pages one by one, until all the mysteries he read about are explained and clear to him (Ivan stops if there does not exist any page $i$ such that Ivan already has read it, but hasn't read page $a_i$). After that, he closes the book and continues to read it on the following day from the next page.

How many days will it take to read the whole book?

-----Input-----

The first line contains single integer $n$ ($1 \le n \le 10^4$) — the number of pages in the book.

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($i \le a_i \le n$), where $a_i$ is the number of page which contains the explanation of the mystery on page $i$.

-----Output-----

Print one integer — the number of days it will take to read the whole book.

-----Example-----
Input
9
1 3 3 6 7 6 8 8 9

Output
4

-----Note-----

Explanation of the example test:

During the first day Ivan will read only the first page. During the second day Ivan will read pages number $2$ and $3$. During the third day — pages $4$-$8$. During the fourth (and the last) day Ivan will read remaining page number $9$.

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

n = int(input().strip())
arr = list(map(lambda x: int(x) - 1, input().strip().split()))

maximum = 0
answer = 0
for start, end in enumerate(arr):
    maximum = max(maximum, end)
    if maximum == start:
        answer += 1

print(answer)


I found an interesting problem on https://codeforces.com/problemset/problem/1140/B:
You have a string $s$ of length $n$ consisting of only characters > and <. You may do some operations with this string, for each operation you have to choose some character that still remains in the string. If you choose a character >, the character that comes right after it is deleted (if the character you chose was the last one, nothing happens). If you choose a character <, the character that comes right before it is deleted (if the character you chose was the first one, nothing happens).

For example, if we choose character > in string > > < >, the string will become to > > >. And if we choose character < in string > <, the string will become to <.

The string is good if there is a sequence of operations such that after performing it only one character will remain in the string. For example, the strings >, > > are good.

Before applying the operations, you may remove any number of characters from the given string (possibly none, possibly up to $n - 1$, but not the whole string). You need to calculate the minimum number of characters to be deleted from string $s$ so that it becomes good.

-----Input-----

The first line contains one integer $t$ ($1 \le t \le 100$) – the number of test cases. Each test case is represented by two lines.

The first line of $i$-th test case contains one integer $n$ ($1 \le n \le 100$) – the length of string $s$.

The second line of $i$-th test case contains string $s$, consisting of only characters > and <.

-----Output-----

For each test case print one line.

For $i$-th test case print the minimum number of characters to be deleted from string $s$ so that it becomes good.

-----Example-----
Input
3
2
<>
3
><<
1
>

Output
1
0
0

-----Note-----

In the first test case we can delete any character in string <>.

In the second test case we don't need to delete any characters. The string > < < is good, because we can perform the following sequence of operations: > < < $\rightarrow$ < < $\rightarrow$ <.

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

for _ in range(int(input())):
    n = int(input())
    s = input()
    k = 0
    for i in range(n-1,-1,-1):
        if s[i] is '<':
            k = n-1-i
            break

    for i in range(n):
        if s[i] is '>':
            k = min(k,i)
            break
    print(k)


I found an interesting problem on https://codeforces.com/problemset/problem/1140/C:
You have a playlist consisting of $n$ songs. The $i$-th song is characterized by two numbers $t_i$ and $b_i$ — its length and beauty respectively. The pleasure of listening to set of songs is equal to the total length of the songs in the set multiplied by the minimum beauty among them. For example, the pleasure of listening to a set of $3$ songs having lengths $[5, 7, 4]$ and beauty values $[11, 14, 6]$ is equal to $(5 + 7 + 4) \cdot 6 = 96$.

You need to choose at most $k$ songs from your playlist, so the pleasure of listening to the set of these songs them is maximum possible.

-----Input-----

The first line contains two integers $n$ and $k$ ($1 \le k \le n \le 3 \cdot 10^5$) – the number of songs in the playlist and the maximum number of songs you can choose, respectively.

Each of the next $n$ lines contains two integers $t_i$ and $b_i$ ($1 \le t_i, b_i \le 10^6$) — the length and beauty of $i$-th song.

-----Output-----

Print one integer — the maximum pleasure you can get.

-----Examples-----
Input
4 3
4 7
15 1
3 6
6 8

Output
78

Input
5 3
12 31
112 4
100 100
13 55
55 50

Output
10000

-----Note-----

In the first test case we can choose songs ${1, 3, 4}$, so the total pleasure is $(4 + 3 + 6) \cdot 6 = 78$.

In the second test case we can choose song $3$. The total pleasure will be equal to $100 \cdot 100 = 10000$.

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

import sys
input = sys.stdin.readline
import heapq
N, K = map(int, input().split())
X = [[0, 0] for _ in range(N)]
for i in range(N):
    t, b = map(int, input().split())
    X[i][0] = t
    X[i][1] = b
X = sorted(X, key = lambda x: -x[1])

a = []
s = 0
ma = 0
for i in range(N):
    heapq.heappush(a, X[i][0])
    s += X[i][0]
    if i >= K:
        s -= heapq.heappop(a)
    ma = max(ma, s * X[i][1])

print(ma)


I found an interesting problem on https://codeforces.com/problemset/problem/1140/D:
You are given a regular polygon with $n$ vertices labeled from $1$ to $n$ in counter-clockwise order. The triangulation of a given polygon is a set of triangles such that each vertex of each triangle is a vertex of the initial polygon, there is no pair of triangles such that their intersection has non-zero area, and the total area of all triangles is equal to the area of the given polygon. The weight of a triangulation is the sum of weigths of triangles it consists of, where the weight of a triagle is denoted as the product of labels of its vertices.

Calculate the minimum weight among all triangulations of the polygon.

-----Input-----

The first line contains single integer $n$ ($3 \le n \le 500$) — the number of vertices in the regular polygon.

-----Output-----

Print one integer — the minimum weight among all triangulations of the given polygon.

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

Output
6

Input
4

Output
18

-----Note-----

According to Wiki: polygon triangulation is the decomposition of a polygonal area (simple polygon) $P$ into a set of triangles, i. e., finding a set of triangles with pairwise non-intersecting interiors whose union is $P$.

In the first example the polygon is a triangle, so we don't need to cut it further, so the answer is $1 \cdot 2 \cdot 3 = 6$.

In the second example the polygon is a rectangle, so it should be divided into two triangles. It's optimal to cut it using diagonal $1-3$ so answer is $1 \cdot 2 \cdot 3 + 1 \cdot 3 \cdot 4 = 6 + 12 = 18$.

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

n = int(input())
t = 0

for i in range(n-2):
    t += (i+2)*(i+3)

print(t)