I found an interesting problem on https://codeforces.com/problemset/problem/958/A1:
The stardate is 1977 and the science and art of detecting Death Stars is in its infancy. Princess Heidi has received information about the stars in the nearby solar system from the Rebel spies and now, to help her identify the exact location of the Death Star, she needs to know whether this information is correct.

Two rebel spies have provided her with the maps of the solar system. Each map is an N × N grid, where each cell is either occupied by a star or empty. To see whether the information is correct, Heidi needs to know whether the two maps are of the same solar system, or if possibly one of the spies is actually an Empire double agent, feeding her false information.

Unfortunately, spies may have accidentally rotated a map by 90, 180, or 270 degrees, or flipped it along the vertical or the horizontal axis, before delivering it to Heidi. If Heidi can rotate or flip the maps so that two of them become identical, then those maps are of the same solar system. Otherwise, there are traitors in the Rebel ranks! Help Heidi find out.

-----Input-----

The first line of the input contains one number N (1 ≤ N ≤ 10) – the dimension of each map. Next N lines each contain N characters, depicting the first map: 'X' indicates a star, while 'O' indicates an empty quadrant of space. Next N lines each contain N characters, depicting the second map in the same format.

-----Output-----

The only line of output should contain the word Yes if the maps are identical, or No if it is impossible to match them by performing rotations and translations.

-----Examples-----
Input
4
XOOO
XXOO
OOOO
XXXX
XOOO
XOOO
XOXO
XOXX

Output
Yes

Input
2
XX
OO
XO
OX

Output
No

-----Note-----

In the first test, you can match the first map to the second map by first flipping the first map along the vertical axis, and then by rotating it 90 degrees clockwise.

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

n = int(input())
f = lambda: ''.join(input() for i in range(n))
a, b = f(), f()
g = lambda k: k // n + n * (n - 1 - k % n)
e = lambda k: k
h = lambda k: n * (n - 1 - k // n) + k % n
v = lambda k: n * (k // n) + n - 1 - k % n
for i in (e, v, h):
    for j in [e, g, lambda k: g(g(k)), lambda k: g(g(g(k)))]:
        if all(a[k] == b[i(j(k))] for k in range(n * n)): (print('Yes'));return
print('No')


I found an interesting problem on https://codeforces.com/problemset/problem/958/A2:
The stardate is 1983, and Princess Heidi is getting better at detecting the Death Stars. This time, two Rebel spies have yet again given Heidi two maps with the possible locations of the Death Star. Since she got rid of all double agents last time, she knows that both maps are correct, and indeed show the map of the solar system that contains the Death Star. However, this time the Empire has hidden the Death Star very well, and Heidi needs to find a place that appears on both maps in order to detect the Death Star.

The first map is an N × M grid, each cell of which shows some type of cosmic object that is present in the corresponding quadrant of space. The second map is an M × N grid. Heidi needs to align those two maps in such a way that they overlap over some M × M section in which all cosmic objects are identical. Help Heidi by identifying where such an M × M section lies within both maps.

-----Input-----

The first line of the input contains two space-separated integers N and M (1 ≤ N ≤ 2000, 1 ≤ M ≤ 200, M ≤ N). The next N lines each contain M lower-case Latin characters (a-z), denoting the first map. Different characters correspond to different cosmic object types. The next M lines each contain N characters, describing the second map in the same format.

-----Output-----

The only line of the output should contain two space-separated integers i and j, denoting that the section of size M × M in the first map that starts at the i-th row is equal to the section of the second map that starts at the j-th column. Rows and columns are numbered starting from 1.

If there are several possible ways to align the maps, Heidi will be satisfied with any of those. It is guaranteed that a solution exists.

-----Example-----
Input
10 5
somer
andom
noise
mayth
eforc
ebewi
thyou
hctwo
again
noise
somermayth
andomeforc
noiseebewi
againthyou
noisehctwo

Output
4 6

-----Note-----

The 5-by-5 grid for the first test case looks like this:

mayth

eforc

ebewi

thyou

hctwo

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

n, m = list(map(int, input().strip().split(' ')))
mat1, mat2 = [], []
for i in range(0, n): mat1.append(tuple(input().strip()))
for i in range(0, m): mat2.append(tuple(input().strip()))
ix, jx, flg = -1, -1, 0
matr, matc = [], []
for i in range(0, n-m+1):
	si, se = i, i+m
	matr.append(hash(tuple(mat1[si:se])))
	matcur2 = []
	for c2i in range(0, m): matcur2.append(tuple(mat2[c2i][si:se]))
	matc.append(hash(tuple(matcur2)))
nx = len(matr)
ix, jx = -1, -1
for ix in range(0, nx):
	flg=0
	for jx in range(0, nx):
		if matr[ix]==matc[jx]:
			flg=1
			break
	if flg==1: break
print(str(ix+1)+" "+str(jx+1))


I found an interesting problem on https://codeforces.com/problemset/problem/958/B1:
The Resistance is trying to take control over all planets in a particular solar system. This solar system is shaped like a tree. More precisely, some planets are connected by bidirectional hyperspace tunnels in such a way that there is a path between every pair of the planets, but removing any tunnel would disconnect some of them.

The Resistance already has measures in place that will, when the time is right, enable them to control every planet that is not remote. A planet is considered to be remote if it is connected to the rest of the planets only via a single hyperspace tunnel.

How much work is there left to be done: that is, how many remote planets are there?

-----Input-----

The first line of the input contains an integer N (2 ≤ N ≤ 1000) – the number of planets in the galaxy.

The next N - 1 lines describe the hyperspace tunnels between the planets. Each of the N - 1 lines contains two space-separated integers u and v (1 ≤ u, v ≤ N) indicating that there is a bidirectional hyperspace tunnel between the planets u and v. It is guaranteed that every two planets are connected by a path of tunnels, and that each tunnel connects a different pair of planets.

-----Output-----

A single integer denoting the number of remote planets.

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

Output
3

Input
4
1 2
4 3
1 4

Output
2

-----Note-----

In the first example, only planets 2, 3 and 5 are connected by a single tunnel.

In the second example, the remote planets are 2 and 3.

Note that this problem has only two versions – easy and medium.

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

N = int(input())
src = [tuple([int(x)-1 for x in input().split()]) for i in range(N-1)]
es = [[] for i in range(N)]
for a,b in src:
    es[a].append(b)
    es[b].append(a)
ans = 0
for e in es:
    if len(e) == 1:
        ans += 1
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/958/B2:
The Resistance is trying to take control over as many planets of a particular solar system as possible. Princess Heidi is in charge of the fleet, and she must send ships to some planets in order to maximize the number of controlled planets.

The Galaxy contains N planets, connected by bidirectional hyperspace tunnels in such a way that there is a unique path between every pair of the planets.

A planet is controlled by the Resistance if there is a Resistance ship in its orbit, or if the planet lies on the shortest path between some two planets that have Resistance ships in their orbits.

Heidi has not yet made up her mind as to how many ships to use. Therefore, she is asking you to compute, for every K = 1, 2, 3, ..., N, the maximum number of planets that can be controlled with a fleet consisting of K ships.

-----Input-----

The first line of the input contains an integer N (1 ≤ N ≤ 10^5) – the number of planets in the galaxy.

The next N - 1 lines describe the hyperspace tunnels between the planets. Each of the N - 1 lines contains two space-separated integers u and v (1 ≤ u, v ≤ N) indicating that there is a bidirectional hyperspace tunnel between the planets u and v. It is guaranteed that every two planets are connected by a path of tunnels, and that each tunnel connects a different pair of planets.

-----Output-----

On a single line, print N space-separated integers. The K-th number should correspond to the maximum number of planets that can be controlled by the Resistance using a fleet of K ships.

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

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

Output
1 3 4 4

-----Note-----

Consider the first example. If K = 1, then Heidi can only send one ship to some planet and control it. However, for K ≥ 2, sending ships to planets 1 and 3 will allow the Resistance to control all planets.

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

from sys import stdin
from collections import defaultdict
import heapq

n = int(stdin.readline())
a = [[] for _ in range(n)]
for _ in range(n-1):
    e = stdin.readline().split(' ')
    u, v = int(e[0]), int(e[1])
    a[u-1].append(v-1)
    a[v-1].append(u-1)

leaves = [i for i in range(n) if len(a[i]) == 1]

def dfs_from(root):
    depth = defaultdict(int)
    child = {}
    parent = defaultdict(lambda: -1)
    stack = [root]
    visited = [False for _ in range(n)]
    while len(stack) > 0:
        crt = stack[-1]
        if visited[crt]:
            stack.pop(-1)
            if len(a[crt]) > 1:  # not a leaf
                child[crt], depth[crt] = max([(c, depth[c]+1) for c in a[crt]
                                              if c != parent[crt]],
                                             key=lambda x: x[1])
            else:
                child[crt] = -1
                depth[crt] = 0
            continue

        visited[crt] = True
        for next in a[crt]:
            if next != parent[crt]:
                stack.append(next)
                parent[next] = crt

    return depth, child

first_choice = leaves[0]
d1, child1 = dfs_from(first_choice)

root = max([(a[leaf][0], d1[a[leaf][0]]) for leaf in leaves],
           key=lambda leaf_depth: leaf_depth[1])[0]
while child1[root] != -1:
    root = child1[root]
depth, child = dfs_from(root)

solution = [1]
pq = []
for k, v in list(depth.items()):
    heapq.heappush(pq, (-v, k))

seen = [False for _ in range(n)]
seen[root] = True

while len(pq) > 0:
    _, best = heapq.heappop(pq)
    if seen[best]:
        continue
    path = []
    c = best
    s = 0
    while c != -1:
        seen[c] = True
        c = child[c]
        s = s+1
    s = s + solution[-1]
    solution.append(s)

for _ in range(n - min(len(solution), n)):
    solution.append(n)

print(' '.join([str(s) for s in solution]))


I found an interesting problem on https://codeforces.com/problemset/problem/958/C1:
Rebel spy Heidi has just obtained the plans for the Death Star from the Empire and, now on her way to safety, she is trying to break the encryption of the plans (of course they are encrypted – the Empire may be evil, but it is not stupid!). The encryption has several levels of security, and here is how the first one looks.

Heidi is presented with a screen that shows her a sequence of integers A and a positive integer p. She knows that the encryption code is a single number S, which is defined as follows:

Define the score of X to be the sum of the elements of X modulo p.

Heidi is given a sequence A that consists of N integers, and also given an integer p. She needs to split A into 2 parts such that:   Each part contains at least 1 element of A, and each part consists of contiguous elements of A.  The two parts do not overlap.  The total sum S of the scores of those two parts is maximized. This is the encryption code.

Output the sum S, which is the encryption code.

-----Input-----

The first line of the input contains two space-separated integer N and p (2 ≤ N ≤ 100 000, 2 ≤ p ≤ 10 000) – the number of elements in A, and the modulo for computing scores, respectively.

The second line contains N space-separated integers which are the elements of A. Each integer is from the interval [1, 1 000 000].

-----Output-----

Output the number S as described in the problem statement.

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

Output
16

Input
10 12
16 3 24 13 9 8 7 5 12 12

Output
13

-----Note-----

In the first example, the score is maximized if the input sequence is split into two parts as (3, 4), (7, 2). It gives the total score of $(3 + 4 \operatorname{mod} 10) +(7 + 2 \operatorname{mod} 10) = 16$.

In the second example, the score is maximized if the first part consists of the first three elements, and the second part consists of the rest. Then, the score is $(16 + 3 + 24 \operatorname{mod} 12) +(13 + 9 + 8 + 7 + 5 + 12 + 12 \operatorname{mod} 12) = 7 + 6 = 13$.

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

n, m = [int(x) for x in input().split(' ')]
numbers = [int(x) for x in input().split(' ')]

max_res = 0
total_sum = sum(numbers)
sum_thus_far = 0
for i in range(n-1):
	tmp_a = sum_thus_far + numbers[i]
	tmp_b = total_sum - tmp_a
	tmp_sum = (tmp_a % m) + (tmp_b % m)
	if tmp_sum > max_res:
		max_res = tmp_sum

print(max_res)


I found an interesting problem on https://codeforces.com/problemset/problem/958/D1:
The Rebel fleet is on the run. It consists of m ships currently gathered around a single planet. Just a few seconds ago, the vastly more powerful Empire fleet has appeared in the same solar system, and the Rebels will need to escape into hyperspace. In order to spread the fleet, the captain of each ship has independently come up with the coordinate to which that ship will jump. In the obsolete navigation system used by the Rebels, this coordinate is given as the value of an arithmetic expression of the form $\frac{a + b}{c}$.

To plan the future of the resistance movement, Princess Heidi needs to know, for each ship, how many ships are going to end up at the same coordinate after the jump. You are her only hope!

-----Input-----

The first line of the input contains a single integer m (1 ≤ m ≤ 200 000) – the number of ships. The next m lines describe one jump coordinate each, given as an arithmetic expression. An expression has the form (a+b)/c. Namely, it consists of: an opening parenthesis (, a positive integer a of up to two decimal digits, a plus sign +, a positive integer b of up to two decimal digits, a closing parenthesis ), a slash /, and a positive integer c of up to two decimal digits.

-----Output-----

Print a single line consisting of m space-separated integers. The i-th integer should be equal to the number of ships whose coordinate is equal to that of the i-th ship (including the i-th ship itself).

-----Example-----
Input
4
(99+98)/97
(26+4)/10
(12+33)/15
(5+1)/7

Output
1 2 2 1

-----Note-----

In the sample testcase, the second and the third ship will both end up at the coordinate 3.

Note that this problem has only two versions – easy and hard.

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

#codeforces.com/contest/958/problem/D1

m=int(input())
positions=[]
poscount={}
for i in range(m):
    crew=list(input())
    n=len(crew)
    i=1
    a=''
    while crew[i]!='+':
        a+=crew[i]
        i+=1
    b=''
    i+=1
    while crew[i]!=')':
        b+=crew[i]
        i+=1
    c=''
    i+=2
    while i<n:
        c+=crew[i]
        i+=1
    a=int(a)
    b=int(b)
    c=int(c)
    res=(a+b)/c
    positions.append(res)
    if res in poscount:
        poscount[res]+=1
    else:
        poscount[res]=1

ans=[]
for i in range(m):
    ans.append(poscount[positions[i]])
print(*ans,sep=' ')


I found an interesting problem on https://codeforces.com/problemset/problem/958/E1:
The Rebel fleet is afraid that the Empire might want to strike back again. Princess Heidi needs to know if it is possible to assign R Rebel spaceships to guard B bases so that every base has exactly one guardian and each spaceship has exactly one assigned base (in other words, the assignment is a perfect matching). Since she knows how reckless her pilots are, she wants to be sure that any two (straight) paths – from a base to its assigned spaceship – do not intersect in the galaxy plane (that is, in 2D), and so there is no risk of collision.

-----Input-----

The first line contains two space-separated integers R, B(1 ≤ R, B ≤ 10). For 1 ≤ i ≤ R, the i + 1-th line contains two space-separated integers x_{i} and y_{i} (|x_{i}|, |y_{i}| ≤ 10000) denoting the coordinates of the i-th Rebel spaceship. The following B lines have the same format, denoting the position of bases. It is guaranteed that no two points coincide and that no three points are on the same line.

-----Output-----

If it is possible to connect Rebel spaceships and bases so as satisfy the constraint, output Yes, otherwise output No (without quote).

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

Output
Yes

Input
2 1
1 0
2 2
3 1

Output
No

-----Note-----

For the first example, one possible way is to connect the Rebels and bases in order.

For the second example, there is no perfect matching between Rebels and bases.

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

s = input()
in1 = s.split(' ')

R = int(in1[0])
B = int(in1[1])

print('Yes' if R==B else 'No')


I found an interesting problem on https://codeforces.com/problemset/problem/958/F1:
There is unrest in the Galactic Senate. Several thousand solar systems have declared their intentions to leave the Republic. Master Heidi needs to select the Jedi Knights who will go on peacekeeping missions throughout the galaxy. It is well-known that the success of any peacekeeping mission depends on the colors of the lightsabers of the Jedi who will go on that mission.

Heidi has n Jedi Knights standing in front of her, each one with a lightsaber of one of m possible colors. She knows that for the mission to be the most effective, she needs to select some contiguous interval of knights such that there are exactly k_1 knights with lightsabers of the first color, k_2 knights with lightsabers of the second color, ..., k_{m} knights with lightsabers of the m-th color. Help her find out if this is possible.

-----Input-----

The first line of the input contains n (1 ≤ n ≤ 100) and m (1 ≤ m ≤ n). The second line contains n integers in the range {1, 2, ..., m} representing colors of the lightsabers of the subsequent Jedi Knights. The third line contains m integers k_1, k_2, ..., k_{m} (with $1 \leq \sum_{i = 1}^{m} k_{i} \leq n$) – the desired counts of lightsabers of each color from 1 to m.

-----Output-----

Output YES if an interval with prescribed color counts exists, or output NO if there is none.

-----Example-----
Input
5 2
1 1 2 2 1
1 2

Output
YES

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

n,m=list(map(int,input().split()))
a=list(map(int,input().split()))
b=list(map(int,input().split()))
c=sum(b)
d=[0]*m
for i in range(c):
    d[a[i]-1]+=1
e=0
for i in range(n-c+1):
    if i!=0:
        d[a[i-1]-1]-=1
        d[a[i+c-1]-1]+=1
    if d==b:
        e=1
        break
if e==0:
    print("NO")
else:
    print("YES")


I found an interesting problem on https://codeforces.com/problemset/problem/958/F2:
There is unrest in the Galactic Senate. Several thousand solar systems have declared their intentions to leave the Republic. Master Heidi needs to select the Jedi Knights who will go on peacekeeping missions throughout the galaxy. It is well-known that the success of any peacekeeping mission depends on the colors of the lightsabers of the Jedi who will go on that mission.

Heidi has n Jedi Knights standing in front of her, each one with a lightsaber of one of m possible colors. She knows that for the mission to be the most effective, she needs to select some contiguous interval of knights such that there are exactly k_1 knights with lightsabers of the first color, k_2 knights with lightsabers of the second color, ..., k_{m} knights with lightsabers of the m-th color.

However, since the last time, she has learned that it is not always possible to select such an interval. Therefore, she decided to ask some Jedi Knights to go on an indefinite unpaid vacation leave near certain pits on Tatooine, if you know what I mean. Help Heidi decide what is the minimum number of Jedi Knights that need to be let go before she is able to select the desired interval from the subsequence of remaining knights.

-----Input-----

The first line of the input contains n (1 ≤ n ≤ 2·10^5) and m (1 ≤ m ≤ n). The second line contains n integers in the range {1, 2, ..., m} representing colors of the lightsabers of the subsequent Jedi Knights. The third line contains m integers k_1, k_2, ..., k_{m} (with $1 \leq \sum_{i = 1}^{m} k_{i} \leq n$) – the desired counts of Jedi Knights with lightsabers of each color from 1 to m.

-----Output-----

Output one number: the minimum number of Jedi Knights that need to be removed from the sequence so that, in what remains, there is an interval with the prescribed counts of lightsaber colors. If this is not possible, output  - 1.

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

Output
1

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

n, m = list(map(int, input().split()))
c = list(map(int, input().split()))
k = list(map(int, input().split()))
p = [0] * m
c = [o - 1 for o in c]
s = sum(k)
ok = k.count(0)
i1 = 0
i2 = 0
while i2 < n and ok < m:
    p[c[i2]] += 1
    if p[c[i2]] == k[c[i2]]:
        ok += 1
    i2 += 1
if ok != m:
    print(-1)
    return
ans = i2 - i1
while i1 < n:
    p[c[i1]] -= 1
    while i2 < n and p[c[i1]] < k[c[i1]]:
        p[c[i2]] += 1
        i2 += 1
    if p[c[i1]] >= k[c[i1]]:
        ans = min(ans, i2 - i1 - 1)
    elif i2 == n:
        break
    i1 += 1
print(ans - s)


I found an interesting problem on https://codeforces.com/problemset/problem/959/A:
Mahmoud and Ehab play a game called the even-odd game. Ehab chooses his favorite integer n and then they take turns, starting from Mahmoud. In each player's turn, he has to choose an integer a and subtract it from n such that:  1 ≤ a ≤ n.  If it's Mahmoud's turn, a has to be even, but if it's Ehab's turn, a has to be odd.

If the current player can't choose any number satisfying the conditions, he loses. Can you determine the winner if they both play optimally?

-----Input-----

The only line contains an integer n (1 ≤ n ≤ 10^9), the number at the beginning of the game.

-----Output-----

Output "Mahmoud" (without quotes) if Mahmoud wins and "Ehab" (without quotes) otherwise.

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

Output
Ehab
Input
2

Output
Mahmoud

-----Note-----

In the first sample, Mahmoud can't choose any integer a initially because there is no positive even integer less than or equal to 1 so Ehab wins.

In the second sample, Mahmoud has to choose a = 2 and subtract it from n. It's Ehab's turn and n = 0. There is no positive odd integer less than or equal to 0 so Mahmoud wins.

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

n=int(input())
print('Ehab'if n%2==1 else'Mahmoud')


I found an interesting problem on https://codeforces.com/problemset/problem/959/B:
Mahmoud wants to send a message to his friend Ehab. Their language consists of n words numbered from 1 to n. Some words have the same meaning so there are k groups of words such that all the words in some group have the same meaning.

Mahmoud knows that the i-th word can be sent with cost a_{i}. For each word in his message, Mahmoud can either replace it with another word of the same meaning or leave it as it is. Can you help Mahmoud determine the minimum cost of sending the message?

The cost of sending the message is the sum of the costs of sending every word in it.

-----Input-----

The first line of input contains integers n, k and m (1 ≤ k ≤ n ≤ 10^5, 1 ≤ m ≤ 10^5) — the number of words in their language, the number of groups of words, and the number of words in Mahmoud's message respectively.

The second line contains n strings consisting of lowercase English letters of length not exceeding 20 which represent the words. It's guaranteed that the words are distinct.

The third line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) where a_{i} is the cost of sending the i-th word.

The next k lines describe the groups of words of same meaning. The next k lines each start with an integer x (1 ≤ x ≤ n) which means that there are x words in this group, followed by x integers which represent the indices of words in this group. It's guaranteed that each word appears in exactly one group.

The next line contains m space-separated words which represent Mahmoud's message. Each of these words appears in the list of language's words.

-----Output-----

The only line should contain the minimum cost to send the message after replacing some words (maybe none) with some words of the same meaning.

-----Examples-----
Input
5 4 4
i loser am the second
100 1 1 5 10
1 1
1 3
2 2 5
1 4
i am the second

Output
107
Input
5 4 4
i loser am the second
100 20 1 5 10
1 1
1 3
2 2 5
1 4
i am the second

Output
116

-----Note-----

In the first sample, Mahmoud should replace the word "second" with the word "loser" because...

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

n, k, m = list(map(int, input().split()))
w = input().split()
a = list(map(int, input().split()))
d = dict(list(zip(w, a)))

for i in range(k):
    s = list(map(int, input().split()[1:]))

    m = min(d[w[x-1]] for x in s)
    for x in s:
        d[w[x-1]] = m

print(sum(d[x] for x in input().split()))


I found an interesting problem on https://codeforces.com/problemset/problem/959/C:
Mahmoud was trying to solve the vertex cover problem on trees. The problem statement is:

Given an undirected tree consisting of n nodes, find the minimum number of vertices that cover all the edges. Formally, we need to find a set of vertices such that for each edge (u, v) that belongs to the tree, either u is in the set, or v is in the set, or both are in the set. Mahmoud has found the following algorithm:  Root the tree at node 1.  Count the number of nodes at an even depth. Let it be evenCnt.  Count the number of nodes at an odd depth. Let it be oddCnt.  The answer is the minimum between evenCnt and oddCnt.

The depth of a node in a tree is the number of edges in the shortest path between this node and the root. The depth of the root is 0.

Ehab told Mahmoud that this algorithm is wrong, but he didn't believe because he had tested his algorithm against many trees and it worked, so Ehab asked you to find 2 trees consisting of n nodes. The algorithm should find an incorrect answer for the first tree and a correct answer for the second one.

-----Input-----

The only line contains an integer n (2 ≤ n ≤ 10^5), the number of nodes in the desired trees.

-----Output-----

The output should consist of 2 independent sections, each containing a tree. The algorithm should find an incorrect answer for the tree in the first section and a correct answer for the tree in the second. If a tree doesn't exist for some section, output "-1" (without quotes) for that section only.

If the answer for a section exists, it should contain n - 1 lines, each containing 2 space-separated integers u and v (1 ≤ u, v ≤ n), which means that there's an undirected edge between node u and node v. If the given graph isn't a tree or it doesn't follow the format, you'll receive wrong answer verdict.

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

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

Output
-1
1 2

Input
8

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

-----Note-----

In the first sample, there is only 1 tree with 2...

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

def ii():
    return int(input())
def mi():
    return map(int, input().split())
def li():
    return list(mi())

n = ii()
if n < 6:
    print(-1)
else:
    t = ['1 2', '1 3', '1 4', '2 5', '2 6']
    for i in range(7, n + 1):
        t.append('1 ' + str(i))
    print('\n'.join(t))
t = []
for i in range(2, n + 1):
    t.append('1 ' + str(i))
print('\n'.join(t))


I found an interesting problem on https://codeforces.com/problemset/problem/959/D:
Mahmoud has an array a consisting of n integers. He asked Ehab to find another array b of the same length such that:

  b is lexicographically greater than or equal to a.  b_{i} ≥ 2.  b is pairwise coprime: for every 1 ≤ i < j ≤ n, b_{i} and b_{j} are coprime, i. e. GCD(b_{i}, b_{j}) = 1, where GCD(w, z) is the greatest common divisor of w and z.

Ehab wants to choose a special array so he wants the lexicographically minimal array between all the variants. Can you find it?

An array x is lexicographically greater than an array y if there exists an index i such than x_{i} > y_{i} and x_{j} = y_{j} for all 1 ≤ j < i. An array x is equal to an array y if x_{i} = y_{i} for all 1 ≤ i ≤ n.

-----Input-----

The first line contains an integer n (1 ≤ n ≤ 10^5), the number of elements in a and b.

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

-----Output-----

Output n space-separated integers, the i-th of them representing b_{i}.

-----Examples-----
Input
5
2 3 5 4 13

Output
2 3 5 7 11
Input
3
10 3 7

Output
10 3 7

-----Note-----

Note that in the second sample, the array is already pairwise coprime so we printed it.

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

MAX_NUM = 2000000

prime_str = ('2      3      5      7     11     13     17     19     23     29 '
        +   '31     37     41     43     47     53     59     61     67     71 '
        +   '73     79     83     89     97    101    103    107    109    113 '
        +  '127    131    137    139    149    151    157    163    167    173 '
        +  '179    181    191    193    197    199    211    223    227    229 '
        +  '233    239    241    251    257    263    269    271    277    281 '
        +  '283    293    307    311    313    317 '
)
prime_list = [int(p) for p in prime_str.split()]
used = [False] * MAX_NUM

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

def record(x):
    t = []
    for p in prime_list:
        if x % p == 0:
            while x % p == 0:
                x = x // p
            t.append(p)
            if x == 1:
                break
    if x != 1:
        t.append(x)

    for ti in t:
        for i in range(ti, MAX_NUM, ti):
            used[i] = True

b = []
for ai in a:
    if not used[ai]:
        b.append(ai)
        record(ai)
    else:
        temp = ai + 1
        while used[temp]:
            temp += 1
        b.append(temp)
        record(temp)
        break

temp = 2
while len(b) < len(a):
    while used[temp]:
        temp += 1
    b.append(temp)
    record(temp)

print(' '.join(str(x) for x in b))


I found an interesting problem on https://codeforces.com/problemset/problem/959/E:
Ehab is interested in the bitwise-xor operation and the special graphs. Mahmoud gave him a problem that combines both. He has a complete graph consisting of n vertices numbered from 0 to n - 1. For all 0 ≤ u < v < n, vertex u and vertex v are connected with an undirected edge that has weight $u \oplus v$ (where $\oplus$ is the bitwise-xor operation). Can you find the weight of the minimum spanning tree of that graph?

You can read about complete graphs in https://en.wikipedia.org/wiki/Complete_graph

You can read about the minimum spanning tree in https://en.wikipedia.org/wiki/Minimum_spanning_tree

The weight of the minimum spanning tree is the sum of the weights on the edges included in it.

-----Input-----

The only line contains an integer n (2 ≤ n ≤ 10^12), the number of vertices in the graph.

-----Output-----

The only line contains an integer x, the weight of the graph's minimum spanning tree.

-----Example-----
Input
4

Output
4

-----Note-----

In the first sample: [Image] The weight of the minimum spanning tree is 1+2+1=4.

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

n = int(input())

ans2 = [0]

for i in range(1, 64):
  ans2.append(ans2[i - 1] + ans2[i - 1] + pow(2, i - 1))

def ans(n):
  if n == 0:
    return 0
  else:
    length = n.bit_length() - 1
    if n == pow(2, length):
      return ans2[length]
    else:
      return ans2[length] + ans(n - pow(2, length)) + pow(2, length)
print(ans(n))


I found an interesting problem on https://codeforces.com/problemset/problem/960/A:
A has a string consisting of some number of lowercase English letters 'a'. He gives it to his friend B who appends some number of letters 'b' to the end of this string. Since both A and B like the characters 'a' and 'b', they have made sure that at this point, at least one 'a' and one 'b' exist in the string.

B now gives this string to C and he appends some number of letters 'c' to the end of the string. However, since C is a good friend of A and B, the number of letters 'c' he appends is equal to the number of 'a' or to the number of 'b' in the string. It is also possible that the number of letters 'c' equals both to the number of letters 'a' and to the number of letters 'b' at the same time.

You have a string in your hands, and you want to check if it is possible to obtain the string in this way or not. If it is possible to obtain the string, print "YES", otherwise print "NO" (without the quotes).

-----Input-----

The first and only line consists of a string $S$ ($ 1 \le |S| \le 5\,000 $). It is guaranteed that the string will only consist of the lowercase English letters 'a', 'b', 'c'.

-----Output-----

Print "YES" or "NO", according to the condition.

-----Examples-----
Input
aaabccc

Output
YES

Input
bbacc

Output
NO

Input
aabc

Output
YES

-----Note-----

Consider first example: the number of 'c' is equal to the number of 'a'.

Consider second example: although the number of 'c' is equal to the number of the 'b', the order is not correct.

Consider third example: the number of 'c' is equal to the number of 'b'.

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

from collections import Counter as Cnt

s = input()

cur = 0
while cur < len(s) and s[cur] == 'a':
	cur += 1

if cur == len(s):
	print('NO')
	return

while cur < len(s) and s[cur] == 'b':
	cur += 1

while cur < len(s) and s[cur] == 'c':
	cur += 1

if cur != len(s):
	print('NO')
	return

c = Cnt(s)
if c['a'] > 0 and c['b'] > 0 and (c['c'] == c['a'] or c['c'] == c['b']):
	print('YES')
else:
	print('NO')


I found an interesting problem on https://codeforces.com/problemset/problem/960/B:
You are given two arrays A and B, each of size n. The error, E, between these two arrays is defined $E = \sum_{i = 1}^{n}(a_{i} - b_{i})^{2}$. You have to perform exactly k_1 operations on array A and exactly k_2 operations on array B. In one operation, you have to choose one element of the array and increase or decrease it by 1.

Output the minimum possible value of error after k_1 operations on array A and k_2 operations on array B have been performed.

-----Input-----

The first line contains three space-separated integers n (1 ≤ n ≤ 10^3), k_1 and k_2 (0 ≤ k_1 + k_2 ≤ 10^3, k_1 and k_2 are non-negative) — size of arrays and number of operations to perform on A and B respectively.

Second line contains n space separated integers a_1, a_2, ..., a_{n} ( - 10^6 ≤ a_{i} ≤ 10^6) — array A.

Third line contains n space separated integers b_1, b_2, ..., b_{n} ( - 10^6 ≤ b_{i} ≤ 10^6)— array B.

-----Output-----

Output a single integer — the minimum possible value of $\sum_{i = 1}^{n}(a_{i} - b_{i})^{2}$ after doing exactly k_1 operations on array A and exactly k_2 operations on array B.

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

Output
2
Input
2 1 0
1 2
2 2

Output
0
Input
2 5 7
3 4
14 4

Output
1

-----Note-----

In the first sample case, we cannot perform any operations on A or B. Therefore the minimum possible error E = (1 - 2)^2 + (2 - 3)^2 = 2.

In the second sample case, we are required to perform exactly one operation on A. In order to minimize error, we increment the first element of A by 1. Now, A = [2, 2]. The error is now E = (2 - 2)^2 + (2 - 2)^2 = 0. This is the minimum possible error obtainable.

In the third sample case, we can increase the first element of A to 8, using the all of the 5 moves available to us. Also, the first element of B can be reduced to 8 using the 6 of the 7 available moves. Now A = [8, 4] and B = [8, 4]. The error is now E = (8 - 8)^2 + (4 - 4)^2 = 0, but we are still left with 1 move for array B. Increasing the second element of B to 5 using the left move, we get B = [8,...

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

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

k = k1 + k2

d = [abs(a[i] - b[i]) for i in range(n)]

if sum(d) > k:
    for i in range(k):
        m = max(d)
        d.remove(m)
        d.append(m - 1)

    ans = sum(x ** 2 for x in d)
    print(ans)

else:
    print((k - sum(d)) % 2)


I found an interesting problem on https://codeforces.com/problemset/problem/961/A:
You are given a following process.

There is a platform with $n$ columns. $1 \times 1$ squares are appearing one after another in some columns on this platform. If there are no squares in the column, a square will occupy the bottom row. Otherwise a square will appear at the top of the highest square of this column.

When all of the $n$ columns have at least one square in them, the bottom row is being removed. You will receive $1$ point for this, and all the squares left will fall down one row.

You task is to calculate the amount of points you will receive.

-----Input-----

The first line of input contain 2 integer numbers $n$ and $m$ ($1 \le n, m \le 1000$) — the length of the platform and the number of the squares.

The next line contain $m$ integer numbers $c_1, c_2, \dots, c_m$ ($1 \le c_i \le n$) — column in which $i$-th square will appear.

-----Output-----

Print one integer — the amount of points you will receive.

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

Output
2

-----Note-----

In the sample case the answer will be equal to $2$ because after the appearing of $6$-th square will be removed one row (counts of the squares on the platform will look like $[2~ 3~ 1]$, and after removing one row will be $[1~ 2~ 0]$).

After the appearing of $9$-th square counts will be $[2~ 3~ 1]$, and after removing one row it will look like $[1~ 2~ 0]$.

So the answer will be equal to $2$.

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

n,m = map(int,input().split())
res = [0] * n
a = list(map(int,input().split()))
for i in a:
    res[i - 1] += 1
print(min(res))


I found an interesting problem on https://codeforces.com/problemset/problem/961/B:
Your friend Mishka and you attend a calculus lecture. Lecture lasts n minutes. Lecturer tells a_{i} theorems during the i-th minute.

Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array t of Mishka's behavior. If Mishka is asleep during the i-th minute of the lecture then t_{i} will be equal to 0, otherwise it will be equal to 1. When Mishka is awake he writes down all the theorems he is being told — a_{i} during the i-th minute. Otherwise he writes nothing.

You know some secret technique to keep Mishka awake for k minutes straight. However you can use it only once. You can start using it at the beginning of any minute between 1 and n - k + 1. If you use it on some minute i then Mishka will be awake during minutes j such that $j \in [ i, i + k - 1 ]$ and will write down all the theorems lecturer tells.

You task is to calculate the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.

-----Input-----

The first line of the input contains two integer numbers n and k (1 ≤ k ≤ n ≤ 10^5) — the duration of the lecture in minutes and the number of minutes you can keep Mishka awake.

The second line of the input contains n integer numbers a_1, a_2, ... a_{n} (1 ≤ a_{i} ≤ 10^4) — the number of theorems lecturer tells during the i-th minute.

The third line of the input contains n integer numbers t_1, t_2, ... t_{n} (0 ≤ t_{i} ≤ 1) — type of Mishka's behavior at the i-th minute of the lecture.

-----Output-----

Print only one integer — the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.

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

Output
16

-----Note-----

In the sample case the better way is to use the secret technique at the beginning of the third minute. Then the number of theorems Mishka will be able to write down will be equal to 16.

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

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

result = sum(a[i] if mask[i] == 1 else 0 for i in range(n))

h = [a[i] if mask[i] == 0 else 0 for i in range(len(a))]
best_awake = sum(h[:k])
curr = best_awake
for j in range(k, n):
    curr += h[j]
    curr -= h[j - k]
    best_awake = max(best_awake, curr)
print(result + best_awake)


I found an interesting problem on https://codeforces.com/problemset/problem/961/C:
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color a_{k}, i, j; 1 being black and 0 being white.

Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.

-----Input-----

The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board.

Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.

-----Output-----

Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.

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

0

1

0

Output
1

Input
3
101
010
101

101
000
101

010
101
011

010
101
010

Output
2

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

n = int(input())

answer  = []

for k in range(4):
    white_problems = 0
    black_problems = 0
    for j in range(n):
        a = [int(i) for i in list(input())]
        for x in range(n):
            if ((a[x] == 1 and x % 2 == 0) or (a[x] == 0 and x % 2 == 1)) and j % 2 == 0:
                white_problems += 1
            if ((a[x] == 1 and x % 2 == 1) or (a[x] == 0 and x % 2 == 0)) and j % 2 == 0:
                black_problems += 1
            if ((a[x] == 1 and x % 2 == 0) or (a[x] == 0 and x % 2 == 1)) and j % 2 == 1:
                black_problems += 1
            if ((a[x] == 1 and x % 2 == 1) or (a[x] == 0 and x % 2 == 0)) and j % 2 == 1:
                white_problems += 1

    answer.append([white_problems, 0])
    answer.append([black_problems, 1])
    if k != 3:
        trash = input()

answer.sort()
black = 0
white = 0
ans = 0
for i in answer:
    if black < 2 and i[1] == 1:
        ans += i[0]
        black += 1
        continue
    if white < 2 and i[1] == 0:
        white += 1
        ans += i[0]
        continue
    if white == 2 and black == 2:
        break
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/961/D:
You are given n points on Cartesian plane. Every point is a lattice point (i. e. both of its coordinates are integers), and all points are distinct.

You may draw two straight lines (not necessarily distinct). Is it possible to do this in such a way that every point lies on at least one of these lines?

-----Input-----

The first line contains one integer n (1 ≤ n ≤ 10^5) — the number of points you are given.

Then n lines follow, each line containing two integers x_{i} and y_{i} (|x_{i}|, |y_{i}| ≤ 10^9)— coordinates of i-th point. All n points are distinct.

-----Output-----

If it is possible to draw two straight lines in such a way that each of given points belongs to at least one of these lines, print YES. Otherwise, print NO.

-----Examples-----
Input
5
0 0
0 1
1 1
1 -1
2 2

Output
YES

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

Output
NO

-----Note-----

In the first example it is possible to draw two lines, the one containing the points 1, 3 and 5, and another one containing two remaining points. [Image]

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

def iscollinear(p1, p2, p3):
    x1, y1 = p1
    x2, y2 = p2
    x3, y3 = p3
    cross = (x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1)
    ans = bool(cross)
    return not ans

def checkfortwolines(a, b, points):
    set1 = set(points)
    for i in range(n): # erase all points collinear with a, b
        if iscollinear(a, b, points[i]): set1.remove(points[i])

    if len(set1) <= 2: return True
    else:
        pts1 = list(set1)
        for i in range(len(pts1)): # check if remaining points are all collinear
            if not iscollinear(pts1[0], pts1[1], pts1[i]): return False
        return True

n = int(input())
if n <= 4: print("YES")
else:
    points = [0 for i in range(n)]
    for i in range(n):
        points[i] = tuple(map(int, input().split()))
    a = points[0]
    b = points[1]
    c = points[2]
    if checkfortwolines(a, b, points) or checkfortwolines(b, c, points) or checkfortwolines(c, a, points):
        print("YES")
    else: print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/961/E:
One day Polycarp decided to rewatch his absolute favourite episode of well-known TV series "Tufurama". He was pretty surprised when he got results only for season 7 episode 3 with his search query of "Watch Tufurama season 3 episode 7 online full hd free". This got Polycarp confused — what if he decides to rewatch the entire series someday and won't be able to find the right episodes to watch? Polycarp now wants to count the number of times he will be forced to search for an episode using some different method.

TV series have n seasons (numbered 1 through n), the i-th season has a_{i} episodes (numbered 1 through a_{i}). Polycarp thinks that if for some pair of integers x and y (x < y) exist both season x episode y and season y episode x then one of these search queries will include the wrong results. Help Polycarp to calculate the number of such pairs!

-----Input-----

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

The second line contains n integers separated by space a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — number of episodes in each season.

-----Output-----

Print one integer — the number of pairs x and y (x < y) such that there exist both season x episode y and season y episode x.

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

Output
0

Input
3
8 12 7

Output
3

Input
3
3 2 1

Output
2

-----Note-----

Possible pairs in the second example:  x = 1, y = 2 (season 1 episode 2 [Image] season 2 episode 1);  x = 2, y = 3 (season 2 episode 3 [Image] season 3 episode 2);  x = 1, y = 3 (season 1 episode 3 [Image] season 3 episode 1).

In the third example:  x = 1, y = 2 (season 1 episode 2 [Image] season 2 episode 1);  x = 1, y = 3 (season 1 episode 3 [Image] season 3 episode 1).

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

import sys

class RangeBit:
    def __init__(self, n):
        sz = 1
        while n >= sz:
            sz *= 2
        self.size = sz
        self.dataAdd = [0 for _ in range(sz)]
        self.dataMul = [0 for _ in range(sz)]

    def sum(self, i):
        assert i > 0
        add, mul, start = 0, 0, i
        while i > 0:
            add += self.dataAdd[i]
            mul += self.dataMul[i]
            i -= i & -i
        return mul * start + add

    def add(self, left, right, by):
        assert 0 < left <= right
        self._add(left, by, -by * (left - 1))
        self._add(right, -by, by * right)

    def _add(self, i, mul, add):
        assert i > 0
        while i < self.size:
            self.dataAdd[i] += add
            self.dataMul[i] += mul
            i += i & -i

n = int(input())
l = list(map(int, sys.stdin.readline().split()))

queries = []
for i in range(n):
    if min(l[i], n) >= i+2:
        queries.append((i+2, min(l[i], n), i+1))

result = 0

a = sorted(list(zip(list(range(1, n+1)), l)) + queries, key=lambda x:(-x[-1], len(x)))
ft = RangeBit(n+1)

for el in a:
    #print(el)
    if len(el) == 2: #update
        ind, val = el
        ft.add(ind, ind, 1)
    else: #query
        fr, to, val = el
        # print(fr, to, val)
        # print(ft.sum(to) - (ft.sum(fr - 1) if fr > 1 else 0))
        result += ft.sum(to) - (ft.sum(fr - 1) if fr > 1 else 0)

print(result)


I found an interesting problem on https://codeforces.com/problemset/problem/961/G:
You are given a set of n elements indexed from 1 to n. The weight of i-th element is w_{i}. The weight of some subset of a given set is denoted as $W(S) =|S|\cdot \sum_{i \in S} w_{i}$. The weight of some partition R of a given set into k subsets is $W(R) = \sum_{S \in R} W(S)$ (recall that a partition of a given set is a set of its subsets such that every element of the given set belongs to exactly one subset in partition).

Calculate the sum of weights of all partitions of a given set into exactly k non-empty subsets, and print it modulo 10^9 + 7. Two partitions are considered different iff there exist two elements x and y such that they belong to the same set in one of the partitions, and to different sets in another partition.

-----Input-----

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 2·10^5) — the number of elements and the number of subsets in each partition, respectively.

The second line contains n integers w_{i} (1 ≤ w_{i} ≤ 10^9)— weights of elements of the set.

-----Output-----

Print one integer — the sum of weights of all partitions of a given set into k non-empty subsets, taken modulo 10^9 + 7.

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

Output
160

Input
5 2
1 2 3 4 5

Output
645

-----Note-----

Possible partitions in the first sample:  {{1, 2, 3}, {4}}, W(R) = 3·(w_1 + w_2 + w_3) + 1·w_4 = 24;  {{1, 2, 4}, {3}}, W(R) = 26;  {{1, 3, 4}, {2}}, W(R) = 24;  {{1, 2}, {3, 4}}, W(R) = 2·(w_1 + w_2) + 2·(w_3 + w_4) = 20;  {{1, 3}, {2, 4}}, W(R) = 20;  {{1, 4}, {2, 3}}, W(R) = 20;  {{1}, {2, 3, 4}}, W(R) = 26;

Possible partitions in the second sample:  {{1, 2, 3, 4}, {5}}, W(R) = 45;  {{1, 2, 3, 5}, {4}}, W(R) = 48;  {{1, 2, 4, 5}, {3}}, W(R) = 51;  {{1, 3, 4, 5}, {2}}, W(R) = 54;  {{2, 3, 4, 5}, {1}}, W(R) = 57;  {{1, 2, 3}, {4, 5}}, W(R) = 36;  {{1, 2, 4}, {3, 5}}, W(R) = 37;  {{1, 2, 5}, {3, 4}}, W(R) = 38;  {{1, 3, 4}, {2, 5}}, W(R) = 38;  {{1, 3, 5}, {2, 4}}, W(R) = 39;  {{1, 4, 5}, {2, 3}}, W(R) = 40;  {{2, 3, 4}, {1, 5}}, W(R) = 39;  {{2, 3, 5}, {1, 4}}, W(R) = 40;  {{2, 4,...

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

def read_data():
    n, m = map(int, list(input().strip().split()))
    a = list(map(int, list(input().strip().split())))
    return n, m, a

def get_modinv(m):
    modinv = [-1 for _ in range(m+1)]
    modinv[1] = 1
    for i in range(2,m+1):
        modinv[i] = (-(div//i) * modinv[div%i]) % div
    return modinv

def partitions(n,k):
    if k >n :
        return 0
    val = 0
    sign = 1
    if k%2 == 1:
        sign = -1
    for i in range(k+1):
        v = (fact[k] * factinv[i] * factinv[k-i] * pow(i,n,div)) % div
        val += v * sign
        val %= div
        sign *= -1
    val *= factinv[k]
    return val % div

def solve():
    modinv = get_modinv(n+1)
    for i in range(1,n+2):
        fact.append(fact[-1]*i%div)
        factinv.append(factinv[-1] * modinv[i] % div)
    return ((partitions(n,k) + (n-1)*partitions(n-1,k))*sum(a)) % div

div = 10**9 + 7
n, k, a = read_data()
fact, factinv = [1], [1]
print(solve())


I found an interesting problem on https://codeforces.com/problemset/problem/962/A:
Polycarp has created his own training plan to prepare for the programming contests. He will train for $n$ days, all days are numbered from $1$ to $n$, beginning from the first.

On the $i$-th day Polycarp will necessarily solve $a_i$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.

Determine the index of day when Polycarp will celebrate the equator.

-----Input-----

The first line contains a single integer $n$ ($1 \le n \le 200\,000$) — the number of days to prepare for the programming contests.

The second line contains a sequence $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10\,000$), where $a_i$ equals to the number of problems, which Polycarp will solve on the $i$-th day.

-----Output-----

Print the index of the day when Polycarp will celebrate the equator.

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

Output
2

Input
6
2 2 2 2 2 2

Output
3

-----Note-----

In the first example Polycarp will celebrate the equator on the evening of the second day, because up to this day (inclusive) he will solve $4$ out of $7$ scheduled problems on four days of the training.

In the second example Polycarp will celebrate the equator on the evening of the third day, because up to this day (inclusive) he will solve $6$ out of $12$ scheduled problems on six days of the training.

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

n = int(input())

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

ss = sum(xs)

s = 0
for i in range(n):
    s += xs[i]
    if s * 2 >= ss:
        print(i+1)
        break


I found an interesting problem on https://codeforces.com/problemset/problem/962/B:
There are $n$ consecutive seat places in a railway carriage. Each place is either empty or occupied by a passenger.

The university team for the Olympiad consists of $a$ student-programmers and $b$ student-athletes. Determine the largest number of students from all $a+b$ students, which you can put in the railway carriage so that:  no student-programmer is sitting next to the student-programmer;  and no student-athlete is sitting next to the student-athlete.

In the other words, there should not be two consecutive (adjacent) places where two student-athletes or two student-programmers are sitting.

Consider that initially occupied seat places are occupied by jury members (who obviously are not students at all).

-----Input-----

The first line contain three integers $n$, $a$ and $b$ ($1 \le n \le 2\cdot10^{5}$, $0 \le a, b \le 2\cdot10^{5}$, $a + b > 0$) — total number of seat places in the railway carriage, the number of student-programmers and the number of student-athletes.

The second line contains a string with length $n$, consisting of characters "." and "*". The dot means that the corresponding place is empty. The asterisk means that the corresponding place is occupied by the jury member.

-----Output-----

Print the largest number of students, which you can put in the railway carriage so that no student-programmer is sitting next to a student-programmer and no student-athlete is sitting next to a student-athlete.

-----Examples-----
Input
5 1 1
*...*

Output
2

Input
6 2 3
*...*.

Output
4

Input
11 3 10
.*....**.*.

Output
7

Input
3 2 3
***

Output
0

-----Note-----

In the first example you can put all student, for example, in the following way: *.AB*

In the second example you can put four students, for example, in the following way: *BAB*B

In the third example you can put seven students, for example, in the following way: B*ABAB**A*B

The letter A means a student-programmer, and the letter B — student-athlete.

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

#!/usr/bin/env python3

[n, a, b] = list(map(int, input().strip().split()))
s = input().strip() + '*'

l0 = 0  # tot len of even parts
n1 = 0  # num of odd parts

i_prev = -1
while True:
	i_next = s.find('*', i_prev + 1)
	if i_next < 0:
		break
	l = i_next - i_prev - 1
	l0 += l // 2
	n1 += l % 2
	i_prev = i_next

c = min(a, b, l0)
res = 2 * c
a -= c
b -= c
l0 -= c
res += min(l0 + n1, a + b)

print (res)


I found an interesting problem on https://codeforces.com/problemset/problem/962/C:
You are given a positive integer $n$, written without leading zeroes (for example, the number 04 is incorrect).

In one operation you can delete any digit of the given integer so that the result remains a positive integer without leading zeros.

Determine the minimum number of operations that you need to consistently apply to the given integer $n$ to make from it the square of some positive integer or report that it is impossible.

An integer $x$ is the square of some positive integer if and only if $x=y^2$ for some positive integer $y$.

-----Input-----

The first line contains a single integer $n$ ($1 \le n \le 2 \cdot 10^{9}$). The number is given without leading zeroes.

-----Output-----

If it is impossible to make the square of some positive integer from $n$, print -1. In the other case, print the minimal number of operations required to do it.

-----Examples-----
Input
8314

Output
2

Input
625

Output
0

Input
333

Output
-1

-----Note-----

In the first example we should delete from $8314$ the digits $3$ and $4$. After that $8314$ become equals to $81$, which is the square of the integer $9$.

In the second example the given $625$ is the square of the integer $25$, so you should not delete anything.

In the third example it is impossible to make the square from $333$, so the answer is -1.

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

n = int(input())

s = str(n)
lst = []
t = set()
def xxx(string):
    if string[0] == '0':
        return
    x = int(string)

    if x in t:
        return
    t.add(x)

    k1 = 0
    k2 = 10 ** 6
    while k2 - k1 != 1:
        k = (k1 + k2) // 2
        if k ** 2 <= x:
            k1 = k
        else:
            k2 = k
    if k1 ** 2 == x:
        lst.append(len(str(x)))

    if len(string) == 1:
        return
    for x in range(len(string)):
        xxx(string[:x] + string[x + 1:])
    return

xxx(s)
if len(lst) == 0:
    print(-1)
else:
    print(len(s) - max(lst))


I found an interesting problem on https://codeforces.com/problemset/problem/962/D:
You are given an array of positive integers. While there are at least two equal elements, we will perform the following operation. We choose the smallest value $x$ that occurs in the array $2$ or more times. Take the first two occurrences of $x$ in this array (the two leftmost occurrences). Remove the left of these two occurrences, and the right one is replaced by the sum of this two values (that is, $2 \cdot x$).

Determine how the array will look after described operations are performed.

For example, consider the given array looks like $[3, 4, 1, 2, 2, 1, 1]$. It will be changed in the following way: $[3, 4, 1, 2, 2, 1, 1]~\rightarrow~[3, 4, 2, 2, 2, 1]~\rightarrow~[3, 4, 4, 2, 1]~\rightarrow~[3, 8, 2, 1]$.

If the given array is look like $[1, 1, 3, 1, 1]$ it will be changed in the following way: $[1, 1, 3, 1, 1]~\rightarrow~[2, 3, 1, 1]~\rightarrow~[2, 3, 2]~\rightarrow~[3, 4]$.

-----Input-----

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

The second line contains a sequence from $n$ elements $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^{9}$) — the elements of the array.

-----Output-----

In the first line print an integer $k$ — the number of elements in the array after all the performed operations. In the second line print $k$ integers — the elements of the array after all the performed operations.

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

Output
4
3 8 2 1

Input
5
1 1 3 1 1

Output
2
3 4

Input
5
10 40 20 50 30

Output
5
10 40 20 50 30

-----Note-----

The first two examples were considered in the statement.

In the third example all integers in the given array are distinct, so it will not change.

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

n=int(input().split()[0])
ns=[int(x) for x in input().split()[:n]]
ind={}
i=0
while i<n:
    ni=ns[i]
    while ni in ind:
        ns[ind[ni]]=None
        ind.pop(ni, None)
        ni*=2
    ns[i]=ni
    ind[ni]=i
    i+=1
ans=[x for x in ns if x!=None]
print(len(ans))
for i in ans:
    print(i,end=' ')


I found an interesting problem on https://codeforces.com/problemset/problem/962/E:
The cities of Byteland and Berland are located on the axis $Ox$. In addition, on this axis there are also disputed cities, which belong to each of the countries in their opinion. Thus, on the line $Ox$ there are three types of cities:  the cities of Byteland,  the cities of Berland,  disputed cities.

Recently, the project BNET has been launched — a computer network of a new generation. Now the task of the both countries is to connect the cities so that the network of this country is connected.

The countries agreed to connect the pairs of cities with BNET cables in such a way that:  If you look at the only cities of Byteland and the disputed cities, then in the resulting set of cities, any city should be reachable from any other one by one or more cables,  If you look at the only cities of Berland and the disputed cities, then in the resulting set of cities, any city should be reachable from any other one by one or more cables.

Thus, it is necessary to choose a set of pairs of cities to connect by cables in such a way that both conditions are satisfied simultaneously. Cables allow bi-directional data transfer. Each cable connects exactly two distinct cities.

The cost of laying a cable from one city to another is equal to the distance between them. Find the minimum total cost of laying a set of cables so that two subsets of cities (Byteland and disputed cities, Berland and disputed cities) are connected.

Each city is a point on the line $Ox$. It is technically possible to connect the cities $a$ and $b$ with a cable so that the city $c$ ($a < c < b$) is not connected to this cable, where $a$, $b$ and $c$ are simultaneously coordinates of the cities $a$, $b$ and $c$.

-----Input-----

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

The following $n$ lines contains an integer $x_i$ and the letter $c_i$ ($-10^{9} \le x_i \le 10^{9}$) — the coordinate of the city and its type. If the city belongs to Byteland, $c_i$ equals to 'B'. If the city belongs to...

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

from sys import stdin, stdout
input, print = stdin.readline, stdout.write
n = int(input())
r, g, b = [], [], []
ans = 0
for i in range(n):
    x, t = [i for i in input().split()]
    x = int(x)
    if t == 'P':
        g.append(x)
    elif t == 'R':
        r.append(x)
    else:
        b.append(x)

if len(g) == 0:
    if len(r):
        ans += r[-1] - r[0]
    if len(b):
        ans += b[-1] - b[0]
    print(str(ans))
    return

if not len(r):
    r.append(g[0])
if not len(b):
    b.append(g[0])
if r[0] < g[0]:
    ans += g[0] - r[0]
if b[0] < g[0]:
    ans += g[0] - b[0]
if r[-1] > g[-1]:
    ans += r[-1] - g[-1]
if b[-1] > g[-1]:
    ans += b[-1] - g[-1]
bi, ri = 0, 0

for i in range(len(g) - 1):
    while bi < len(b) - 1 and b[bi] < g[i]:
        bi += 1
    while ri < len(r) - 1 and r[ri] < g[i]:
        ri += 1
    a1, a2 = (g[i + 1] - g[i]) * 3, (g[i + 1] - g[i]) * 2
    mr, mb, cbi, cri = r[ri] - g[i], b[bi] - g[i], bi, ri

    while cbi + 1 < len(b) and b[cbi + 1] < g[i + 1]:
        mb = max(mb, b[cbi + 1] - b[cbi])
        cbi += 1
    mb = max(mb, g[i + 1] - b[cbi])
    while cri + 1 < len(r) and r[cri + 1] < g[i + 1]:
        mr = max(mr, r[cri + 1] - r[cri])
        cri += 1
    mr = max(mr, g[i + 1] - r[cri])

    if b[bi] < g[i] or b[bi] > g[i + 1]:
        a2 = 100000000000000
        a1 -= g[i + 1] - g[i]
        mb = 0
    if r[ri] < g[i] or r[ri] > g[i + 1]:
        a2 = 100000000000000
        a1 -= g[i + 1] - g[i]
        mr = 0

    ans += min(a1 - mr - mb, a2)

print(str(ans))


I found an interesting problem on https://codeforces.com/problemset/problem/963/A:
You are given two integers $a$ and $b$. Moreover, you are given a sequence $s_0, s_1, \dots, s_{n}$. All values in $s$ are integers $1$ or $-1$. It's known that sequence is $k$-periodic and $k$ divides $n+1$. In other words, for each $k \leq i \leq n$ it's satisfied that $s_{i} = s_{i - k}$.

Find out the non-negative remainder of division of $\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}$ by $10^{9} + 9$.

Note that the modulo is unusual!

-----Input-----

The first line contains four integers $n, a, b$ and $k$ $(1 \leq n \leq 10^{9}, 1 \leq a, b \leq 10^{9}, 1 \leq k \leq 10^{5})$.

The second line contains a sequence of length $k$ consisting of characters '+' and '-'.

If the $i$-th character (0-indexed) is '+', then $s_{i} = 1$, otherwise $s_{i} = -1$.

Note that only the first $k$ members of the sequence are given, the rest can be obtained using the periodicity property.

-----Output-----

Output a single integer — value of given expression modulo $10^{9} + 9$.

-----Examples-----
Input
2 2 3 3
+-+

Output
7

Input
4 1 5 1
-

Output
999999228

-----Note-----

In the first example:

$(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i})$ = $2^{2} 3^{0} - 2^{1} 3^{1} + 2^{0} 3^{2}$ = 7

In the second example:

$(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}) = -1^{4} 5^{0} - 1^{3} 5^{1} - 1^{2} 5^{2} - 1^{1} 5^{3} - 1^{0} 5^{4} = -781 \equiv 999999228 \pmod{10^{9} + 9}$.

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

def __starting_point():
	a=[int(x) for x in input().split()]
	N=a[0]
	A=a[1]
	B=a[2]
	K=a[3]
	s=input()
	mod = 1000000009
	Q = pow(B*pow(A,mod-2,mod)%mod,K,mod)
	if Q!=1:
		D = (pow(Q,(N+1)//K,mod)-1)*pow(Q-1,mod-2,mod)%mod
	else:
		D = (N+1)//K
	ans=0
	C = pow(A,N,mod)
	A=pow(A,mod-2,mod)
	for i in range(K):
		if s[i]=='+':
			ans=(ans+C*D)%mod
		else:
			ans=(ans-C*D)%mod
		C=C*B*A%mod
	print((ans%mod+mod)%mod)
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/964/A:
Let's define a split of $n$ as a nonincreasing sequence of positive integers, the sum of which is $n$.

For example, the following sequences are splits of $8$: $[4, 4]$, $[3, 3, 2]$, $[2, 2, 1, 1, 1, 1]$, $[5, 2, 1]$.

The following sequences aren't splits of $8$: $[1, 7]$, $[5, 4]$, $[11, -3]$, $[1, 1, 4, 1, 1]$.

The weight of a split is the number of elements in the split that are equal to the first element. For example, the weight of the split $[1, 1, 1, 1, 1]$ is $5$, the weight of the split $[5, 5, 3, 3, 3]$ is $2$ and the weight of the split $[9]$ equals $1$.

For a given $n$, find out the number of different weights of its splits.

-----Input-----

The first line contains one integer $n$ ($1 \leq n \leq 10^9$).

-----Output-----

Output one integer — the answer to the problem.

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

Output
4

Input
8

Output
5

Input
9

Output
5

-----Note-----

In the first sample, there are following possible weights of splits of $7$:

Weight 1: [$\textbf 7$]

Weight 2: [$\textbf 3$, $\textbf 3$, 1]

Weight 3: [$\textbf 2$, $\textbf 2$, $\textbf 2$, 1]

Weight 7: [$\textbf 1$, $\textbf 1$, $\textbf 1$, $\textbf 1$, $\textbf 1$, $\textbf 1$, $\textbf 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/964/B:
There are n incoming messages for Vasya. The i-th message is going to be received after t_{i} minutes. Each message has a cost, which equals to A initially. After being received, the cost of a message decreases by B each minute (it can become negative). Vasya can read any message after receiving it at any moment of time. After reading the message, Vasya's bank account receives the current cost of this message. Initially, Vasya's bank account is at 0.

Also, each minute Vasya's bank account receives C·k, where k is the amount of received but unread messages.

Vasya's messages are very important to him, and because of that he wants to have all messages read after T minutes.

Determine the maximum amount of money Vasya's bank account can hold after T minutes.

-----Input-----

The first line contains five integers n, A, B, C and T (1 ≤ n, A, B, C, T ≤ 1000).

The second string contains n integers t_{i} (1 ≤ t_{i} ≤ T).

-----Output-----

Output one integer  — the answer to the problem.

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

Output
20

Input
5 3 1 1 3
2 2 2 1 1

Output
15

Input
5 5 3 4 5
1 2 3 4 5

Output
35

-----Note-----

In the first sample the messages must be read immediately after receiving, Vasya receives A points for each message, n·A = 20 in total.

In the second sample the messages can be read at any integer moment.

In the third sample messages must be read at the moment T. This way Vasya has 1, 2, 3, 4 and 0 unread messages at the corresponding minutes, he gets 40 points for them. When reading messages, he receives (5 - 4·3) + (5 - 3·3) + (5 - 2·3) + (5 - 1·3) + 5 =  - 5 points. This is 35 in total.

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

n, a, b, c, t = list(map(int, input().split()))
messages = list(map(int, input().split()))

if b < c:
    money = n * a
    for m in messages:
        money += (t - m) * (c - b)
else:
    money = n * a

print(money)


I found an interesting problem on https://codeforces.com/problemset/problem/965/A:
To make a paper airplane, one has to use a rectangular piece of paper. From a sheet of standard size you can make $s$ airplanes.

A group of $k$ people decided to make $n$ airplanes each. They are going to buy several packs of paper, each of them containing $p$ sheets, and then distribute the sheets between the people. Each person should have enough sheets to make $n$ airplanes. How many packs should they buy?

-----Input-----

The only line contains four integers $k$, $n$, $s$, $p$ ($1 \le k, n, s, p \le 10^4$) — the number of people, the number of airplanes each should make, the number of airplanes that can be made using one sheet and the number of sheets in one pack, respectively.

-----Output-----

Print a single integer — the minimum number of packs they should buy.

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

Output
4

Input
5 3 100 1

Output
5

-----Note-----

In the first sample they have to buy $4$ packs of paper: there will be $12$ sheets in total, and giving $2$ sheets to each person is enough to suit everyone's needs.

In the second sample they have to buy a pack for each person as they can't share sheets.

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

from math import ceil

k, n, s, p = list(map(int, input().split()))

print(ceil(k * ceil(n / s) / p))


I found an interesting problem on https://codeforces.com/problemset/problem/965/B:
Arkady is playing Battleship. The rules of this game aren't really important.

There is a field of $n \times n$ cells. There should be exactly one $k$-decker on the field, i. e. a ship that is $k$ cells long oriented either horizontally or vertically. However, Arkady doesn't know where it is located. For each cell Arkady knows if it is definitely empty or can contain a part of the ship.

Consider all possible locations of the ship. Find such a cell that belongs to the maximum possible number of different locations of the ship.

-----Input-----

The first line contains two integers $n$ and $k$ ($1 \le k \le n \le 100$) — the size of the field and the size of the ship.

The next $n$ lines contain the field. Each line contains $n$ characters, each of which is either '#' (denotes a definitely empty cell) or '.' (denotes a cell that can belong to the ship).

-----Output-----

Output two integers — the row and the column of a cell that belongs to the maximum possible number of different locations of the ship.

If there are multiple answers, output any of them. In particular, if no ship can be placed on the field, you can output any cell.

-----Examples-----
Input
4 3
#..#
#.#.
....
.###

Output
3 2

Input
10 4
#....##...
.#...#....
..#..#..#.
...#.#....
.#..##.#..
.....#...#
...#.##...
.#...#.#..
.....#..#.
...#.#...#

Output
6 1

Input
19 6
##..............###
#......#####.....##
.....#########.....
....###########....
...#############...
..###############..
.#################.
.#################.
.#################.
.#################.
#####....##....####
####............###
####............###
#####...####...####
.#####..####..#####
...###........###..
....###########....
.........##........
#.................#

Output
1 8

-----Note-----

The picture below shows the three possible locations of the ship that contain the cell $(3, 2)$ in the first sample. [Image]

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

n, k = map(int, input().split())
board = []

for _ in range(n):
    board.append(input())

result = [None] * n

for i in range(n):
    result[i] = [0] * n

# horizontally
for r, row in enumerate(board):
    for i in range(len(board) - k + 1):
        if row[i:i+k] == '.' * k:
            for x in range(i, i + k):
                result[r][x] += 1

# print("\n".join(map(str, result)))

# vertically
for col in range(len(board)):
    for i in range(len(board) - k + 1):
        if ''.join([board[j][col] for j in range(i, i + k)]) == '.' * k:
            for x in range(i, i + k):
                result[x][col] += 1

# print("\n".join(map(str, result)))

# find max
_max = 0
max_pos = (0, 0)

for r, row in enumerate(result):
    for c, col in enumerate(row):
        if col > _max:
            max_pos = (r, c)
            _max = col

print("{} {}".format(max_pos[0] + 1, max_pos[1] + 1))


I found an interesting problem on https://codeforces.com/problemset/problem/965/C:
$k$ people want to split $n$ candies between them. Each candy should be given to exactly one of them or be thrown away.

The people are numbered from $1$ to $k$, and Arkady is the first of them. To split the candies, Arkady will choose an integer $x$ and then give the first $x$ candies to himself, the next $x$ candies to the second person, the next $x$ candies to the third person and so on in a cycle. The leftover (the remainder that is not divisible by $x$) will be thrown away.

Arkady can't choose $x$ greater than $M$ as it is considered greedy. Also, he can't choose such a small $x$ that some person will receive candies more than $D$ times, as it is considered a slow splitting.

Please find what is the maximum number of candies Arkady can receive by choosing some valid $x$.

-----Input-----

The only line contains four integers $n$, $k$, $M$ and $D$ ($2 \le n \le 10^{18}$, $2 \le k \le n$, $1 \le M \le n$, $1 \le D \le \min{(n, 1000)}$, $M \cdot D \cdot k \ge n$) — the number of candies, the number of people, the maximum number of candies given to a person at once, the maximum number of times a person can receive candies.

-----Output-----

Print a single integer — the maximum possible number of candies Arkady can give to himself.

Note that it is always possible to choose some valid $x$.

-----Examples-----
Input
20 4 5 2

Output
8

Input
30 9 4 1

Output
4

-----Note-----

In the first example Arkady should choose $x = 4$. He will give $4$ candies to himself, $4$ candies to the second person, $4$ candies to the third person, then $4$ candies to the fourth person and then again $4$ candies to himself. No person is given candies more than $2$ times, and Arkady receives $8$ candies in total.

Note that if Arkady chooses $x = 5$, he will receive only $5$ candies, and if he chooses $x = 3$, he will receive only $3 + 3 = 6$ candies as well as the second person, the third and the fourth persons will receive $3$ candies, and $2$ candies will be thrown away. He can't choose $x = 1$ nor $x = 2$ because in...

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

n,k,m,d=list(map(int,input().split()))
ans=0
for t in range(1,d+1):
    x=n//(k*t-k+1)
    if x<=m:
        ans=max(ans,t*x)
x=m
t=(n//x+k-1)//k
if t<=d:
    ans=max(ans,t*x)
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/965/D:
A lot of frogs want to cross a river. A river is $w$ units width, but frogs can only jump $l$ units long, where $l < w$. Frogs can also jump on lengths shorter than $l$. but can't jump longer. Hopefully, there are some stones in the river to help them.

The stones are located at integer distances from the banks. There are $a_i$ stones at the distance of $i$ units from the bank the frogs are currently at. Each stone can only be used once by one frog, after that it drowns in the water.

What is the maximum number of frogs that can cross the river, given that then can only jump on the stones?

-----Input-----

The first line contains two integers $w$ and $l$ ($1 \le l < w \le 10^5$) — the width of the river and the maximum length of a frog's jump.

The second line contains $w - 1$ integers $a_1, a_2, \ldots, a_{w-1}$ ($0 \le a_i \le 10^4$), where $a_i$ is the number of stones at the distance $i$ from the bank the frogs are currently at.

-----Output-----

Print a single integer — the maximum number of frogs that can cross the river.

-----Examples-----
Input
10 5
0 0 1 0 2 0 0 1 0

Output
3

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

Output
3

-----Note-----

In the first sample two frogs can use the different stones at the distance $5$, and one frog can use the stones at the distances $3$ and then $8$.

In the second sample although there are two stones at the distance $5$, that does not help. The three paths are: $0 \to 3 \to 6 \to 9 \to 10$, $0 \to 2 \to 5 \to 8 \to 10$, $0 \to 1 \to 4 \to 7 \to 10$.

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

inf = 2000000000
w, l = list(map(int, input().split()))
aa = input().split()

a = [0 for i in range(w)]
dp = [0 for i in range(w+1)]
su = [0 for i in range(w+1)]

for i in range(1, w):
    a[i] = int(aa[i-1])

for i in range(1, w):
    if i <= l :
        dp[i] = a[i]
    else :
        dp[i] = min(a[i], su[i-1] - su[i-l-1])
    su[i] = su[i-1] + dp[i]
#    print(i, ' -- ', dp[i])
res = inf

for i in range(l, w):
    res = min(res, su[i] - su[i-l])

print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/967/A:
These days Arkady works as an air traffic controller at a large airport. He controls a runway which is usually used for landings only. Thus, he has a schedule of planes that are landing in the nearest future, each landing lasts $1$ minute.

He was asked to insert one takeoff in the schedule. The takeoff takes $1$ minute itself, but for safety reasons there should be a time space between the takeoff and any landing of at least $s$ minutes from both sides.

Find the earliest time when Arkady can insert the takeoff.

-----Input-----

The first line of input contains two integers $n$ and $s$ ($1 \le n \le 100$, $1 \le s \le 60$) — the number of landings on the schedule and the minimum allowed time (in minutes) between a landing and a takeoff.

Each of next $n$ lines contains two integers $h$ and $m$ ($0 \le h \le 23$, $0 \le m \le 59$) — the time, in hours and minutes, when a plane will land, starting from current moment (i. e. the current time is $0$ $0$). These times are given in increasing order.

-----Output-----

Print two integers $h$ and $m$ — the hour and the minute from the current moment of the earliest time Arkady can insert the takeoff.

-----Examples-----
Input
6 60
0 0
1 20
3 21
5 0
19 30
23 40

Output
6 1

Input
16 50
0 30
1 20
3 0
4 30
6 10
7 50
9 30
11 10
12 50
14 30
16 10
17 50
19 30
21 10
22 50
23 59

Output
24 50

Input
3 17
0 30
1 0
12 0

Output
0 0

-----Note-----

In the first example note that there is not enough time between 1:20 and 3:21, because each landing and the takeoff take one minute.

In the second example there is no gaps in the schedule, so Arkady can only add takeoff after all landings. Note that it is possible that one should wait more than $24$ hours to insert the takeoff.

In the third example Arkady can insert the takeoff even between the first landing.

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

n,s = list(map(int,input().split(' ')))
v0 = 0
fl = False

for i in range(n):
  h,m = list(map(int,input().split(' ')))
  v = h*60+m
  if i==0 and (v-1) >= s:
    m2 = 0
    h2 = 0
    fl = True
    break
  elif (v-v0-2) // 2 >= s:
    v2 = v0+s+1
    m2 = (v2)%60
    h2 = (v2)//60
    fl = True
    break
  else:
    v0 = v
if fl:
  print(h2,m2)
else:
  m2 = (v0+s+1)%60
  h2 = (v0+s+1)//60
  print(h2,m2)


I found an interesting problem on https://codeforces.com/problemset/problem/967/B:
Arkady wants to water his only flower. Unfortunately, he has a very poor watering system that was designed for $n$ flowers and so it looks like a pipe with $n$ holes. Arkady can only use the water that flows from the first hole.

Arkady can block some of the holes, and then pour $A$ liters of water into the pipe. After that, the water will flow out from the non-blocked holes proportionally to their sizes $s_1, s_2, \ldots, s_n$. In other words, if the sum of sizes of non-blocked holes is $S$, and the $i$-th hole is not blocked, $\frac{s_i \cdot A}{S}$ liters of water will flow out of it.

What is the minimum number of holes Arkady should block to make at least $B$ liters of water flow out of the first hole?

-----Input-----

The first line contains three integers $n$, $A$, $B$ ($1 \le n \le 100\,000$, $1 \le B \le A \le 10^4$) — the number of holes, the volume of water Arkady will pour into the system, and the volume he wants to get out of the first hole.

The second line contains $n$ integers $s_1, s_2, \ldots, s_n$ ($1 \le s_i \le 10^4$) — the sizes of the holes.

-----Output-----

Print a single integer — the number of holes Arkady should block.

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

Output
1

Input
4 80 20
3 2 1 4

Output
0

Input
5 10 10
1000 1 1 1 1

Output
4

-----Note-----

In the first example Arkady should block at least one hole. After that, $\frac{10 \cdot 2}{6} \approx 3.333$ liters of water will flow out of the first hole, and that suits Arkady.

In the second example even without blocking any hole, $\frac{80 \cdot 3}{10} = 24$ liters will flow out of the first hole, that is not less than $20$.

In the third example Arkady has to block all holes except the first to make all water flow out of the first hole.

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

def main():
    [n, a, b] = [int(i) for i in input().split()]
    s = [int(i) for i in input().split()]
    sumAll = 0
    for i in range(n):
        sumAll += s[i]
    rest = s[1:]
    rest.sort(reverse=True)
    thresh = sumAll - s[0] * a / b
    i = 0
    sumBlocked = 0
    while sumBlocked < thresh:
        sumBlocked += rest[i]
        i += 1
    print(i)
def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/975/A:
In Aramic language words can only represent objects.

Words in Aramic have special properties:   A word is a root if it does not contain the same letter more than once.  A root and all its permutations represent the same object.  The root $x$ of a word $y$ is the word that contains all letters that appear in $y$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab".  Any word in Aramic represents the same object as its root.

You have an ancient script in Aramic. What is the number of different objects mentioned in the script?

-----Input-----

The first line contains one integer $n$ ($1 \leq n \leq 10^3$) — the number of words in the script.

The second line contains $n$ words $s_1, s_2, \ldots, s_n$ — the script itself. The length of each string does not exceed $10^3$.

It is guaranteed that all characters of the strings are small latin letters.

-----Output-----

Output one integer — the number of different objects mentioned in the given ancient Aramic script.

-----Examples-----
Input
5
a aa aaa ab abb

Output
2
Input
3
amer arem mrea

Output
1

-----Note-----

In the first test, there are two objects mentioned. The roots that represent them are "a","ab".

In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".

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

def ii():
    return int(input())
def mi():
    return map(int, input().split())
def li():
    return list(mi())

n = ii()
s = [frozenset(x) for x in input().split()]
s = set(s)
print(len(s))


I found an interesting problem on https://codeforces.com/problemset/problem/975/B:
Mancala is a game famous in the Middle East. It is played on a board that consists of 14 holes.  [Image]

Initially, each hole has $a_i$ stones. When a player makes a move, he chooses a hole which contains a positive number of stones. He takes all the stones inside it and then redistributes these stones one by one in the next holes in a counter-clockwise direction.

Note that the counter-clockwise order means if the player takes the stones from hole $i$, he will put one stone in the $(i+1)$-th hole, then in the $(i+2)$-th, etc. If he puts a stone in the $14$-th hole, the next one will be put in the first hole.

After the move, the player collects all the stones from holes that contain even number of stones. The number of stones collected by player is the score, according to Resli.

Resli is a famous Mancala player. He wants to know the maximum score he can obtain after one move.

-----Input-----

The only line contains 14 integers $a_1, a_2, \ldots, a_{14}$ ($0 \leq a_i \leq 10^9$) — the number of stones in each hole.

It is guaranteed that for any $i$ ($1\leq i \leq 14$) $a_i$ is either zero or odd, and there is at least one stone in the board.

-----Output-----

Output one integer, the maximum possible score after one move.

-----Examples-----
Input
0 1 1 0 0 0 0 0 0 7 0 0 0 0

Output
4

Input
5 1 1 1 1 0 0 0 0 0 0 0 0 0

Output
8

-----Note-----

In the first test case the board after the move from the hole with $7$ stones will look like 1 2 2 0 0 0 0 0 0 0 1 1 1 1. Then the player collects the even numbers and ends up with a score equal to $4$.

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

from sys import stdin, stdout
from math import factorial
from math import log10

n = 14
challengers = list(map(int, stdin.readline().split()))
ans = 0

for i in range(n):
    if not challengers[i]:
        continue

    test = challengers[:]
    cnt = test[i]
    test[i] = 0

    for j in range(i + 1, n):
        test[j] += 1
        cnt -= 1

        if cnt == 0:
            break

    value = cnt // 14
    for j in range(n):
        test[j] += value
        cnt -= value

    for j in range(cnt % 14):
        test[j] += 1

    cur_ans = 0

    for z in range(n):
        if not test[z] & 1:
            cur_ans += test[z]

    ans = max(ans, cur_ans)

stdout.write(str(ans))


I found an interesting problem on https://codeforces.com/problemset/problem/975/C:
Ivar the Boneless is a great leader. He is trying to capture Kattegat from Lagertha. The war has begun and wave after wave Ivar's warriors are falling in battle.

Ivar has $n$ warriors, he places them on a straight line in front of the main gate, in a way that the $i$-th warrior stands right after $(i-1)$-th warrior. The first warrior leads the attack.

Each attacker can take up to $a_i$ arrows before he falls to the ground, where $a_i$ is the $i$-th warrior's strength.

Lagertha orders her warriors to shoot $k_i$ arrows during the $i$-th minute, the arrows one by one hit the first still standing warrior. After all Ivar's warriors fall and all the currently flying arrows fly by, Thor smashes his hammer and all Ivar's warriors get their previous strengths back and stand up to fight again. In other words, if all warriors die in minute $t$, they will all be standing to fight at the end of minute $t$.

The battle will last for $q$ minutes, after each minute you should tell Ivar what is the number of his standing warriors.

-----Input-----

The first line contains two integers $n$ and $q$ ($1 \le n, q \leq 200\,000$) — the number of warriors and the number of minutes in the battle.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^9$) that represent the warriors' strengths.

The third line contains $q$ integers $k_1, k_2, \ldots, k_q$ ($1 \leq k_i \leq 10^{14}$), the $i$-th of them represents Lagertha's order at the $i$-th minute: $k_i$ arrows will attack the warriors.

-----Output-----

Output $q$ lines, the $i$-th of them is the number of standing warriors after the $i$-th minute.

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

Output
3
5
4
4
3

Input
4 4
1 2 3 4
9 1 10 6

Output
1
4
4
1

-----Note-----

In the first example:   after the 1-st minute, the 1-st and 2-nd warriors die.  after the 2-nd minute all warriors die (and all arrows left over are wasted), then they will be revived thus answer is 5 — all warriors are alive.  after the 3-rd minute, the 1-st warrior...

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

from bisect import bisect as bs
n, q = map(int, input().split())
a = list(map(int, input().split()))
k = list(map(int, input().split()))
tmp = 0
sumA = []
for i in range(n):
    tmp += a[i]
    sumA.append(tmp)
# print(sumA)

def bin_search(left, right, v):
    if left > right:
        return left
    mid = (left + right) // 2
    if sumA[mid] == v:
        return mid
    elif sumA[mid] < v:
        return bin_search(mid+1, right, v)
    else:
        return bin_search(left, mid-1, v)

now = 0

ansList = []

for i in range(q):
    now += k[i]
    ans_id = bs(sumA, now)
    if ans_id == n:
        now = 0
        ans_id = 0
    ansList.append(n-ans_id)

print("\n".join(map(str, ansList)))


I found an interesting problem on https://codeforces.com/problemset/problem/975/D:
Ghosts live in harmony and peace, they travel the space without any purpose other than scare whoever stands in their way.

There are $n$ ghosts in the universe, they move in the $OXY$ plane, each one of them has its own velocity that does not change in time: $\overrightarrow{V} = V_{x}\overrightarrow{i} + V_{y}\overrightarrow{j}$ where $V_{x}$ is its speed on the $x$-axis and $V_{y}$ is on the $y$-axis.

A ghost $i$ has experience value $EX_i$, which represent how many ghosts tried to scare him in his past. Two ghosts scare each other if they were in the same cartesian point at a moment of time.

As the ghosts move with constant speed, after some moment of time there will be no further scaring (what a relief!) and the experience of ghost kind $GX = \sum_{i=1}^{n} EX_i$ will never increase.

Tameem is a red giant, he took a picture of the cartesian plane at a certain moment of time $T$, and magically all the ghosts were aligned on a line of the form $y = a \cdot x + b$. You have to compute what will be the experience index of the ghost kind $GX$ in the indefinite future, this is your task for today.

Note that when Tameem took the picture, $GX$ may already be greater than $0$, because many ghosts may have scared one another at any moment between $[-\infty, T]$.

-----Input-----

The first line contains three integers $n$, $a$ and $b$ ($1 \leq n \leq 200000$, $1 \leq |a| \leq 10^9$, $0 \le |b| \le 10^9$) — the number of ghosts in the universe and the parameters of the straight line.

Each of the next $n$ lines contains three integers $x_i$, $V_{xi}$, $V_{yi}$ ($-10^9 \leq x_i \leq 10^9$, $-10^9 \leq V_{x i}, V_{y i} \leq 10^9$), where $x_i$ is the current $x$-coordinate of the $i$-th ghost (and $y_i = a \cdot x_i + b$).

It is guaranteed that no two ghosts share the same initial position, in other words, it is guaranteed that for all $(i,j)$ $x_i \neq x_j$ for $i \ne j$.

-----Output-----

Output one line: experience index of the ghost kind $GX$ in the indefinite future.

-----Examples-----
Input
4 1 1
1 -1...

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

n, A, C = list(map(int, input().split()))

def Ro(x, y):
    return A * x - y + C

huh = []

for i in range(n):
    z, x, y = list(map(int, input().split()))
    huh.append((Ro(x + z, z * A + y), x))
huh = sorted(huh)
anss = 0
c1 = 0
c2 = 0
prev = (-9999999999999, -999999999999999)
g = []

huh.append((-9999999999999, -999999999999999))
#print(huh)
for huhh in huh:
    if huhh[0] != prev[0]:
        g.append(c1)
        #print(g)
        for j in g:
            anss += (c2 - j) * j
        g = []
        c1 = 1
        c2 = 1
        prev = (huhh[0], huhh[1])
        continue
    c2 += 1
    if huhh[1] != prev[1]:
        g.append(c1)
        c1 = 0
        prev = (huhh[0], huhh[1])
    c1 += 1
print(anss)


I found an interesting problem on https://codeforces.com/problemset/problem/975/E:
Hag is a very talented person. He has always had an artist inside him but his father forced him to study mechanical engineering.

Yesterday he spent all of his time cutting a giant piece of wood trying to make it look like a goose. Anyway, his dad found out that he was doing arts rather than studying mechanics and other boring subjects. He confronted Hag with the fact that he is a spoiled son that does not care about his future, and if he continues to do arts he will cut his 25 Lira monthly allowance.

Hag is trying to prove to his dad that the wooden piece is a project for mechanics subject. He also told his dad that the wooden piece is a strictly convex polygon with $n$ vertices.

Hag brought two pins and pinned the polygon with them in the $1$-st and $2$-nd vertices to the wall. His dad has $q$ queries to Hag of two types.   $1$ $f$ $t$: pull a pin from the vertex $f$, wait for the wooden polygon to rotate under the gravity force (if it will rotate) and stabilize. And then put the pin in vertex $t$.  $2$ $v$: answer what are the coordinates of the vertex $v$.

Please help Hag to answer his father's queries.

You can assume that the wood that forms the polygon has uniform density and the polygon has a positive thickness, same in all points. After every query of the 1-st type Hag's dad tries to move the polygon a bit and watches it stabilize again.

-----Input-----

The first line contains two integers $n$ and $q$ ($3\leq n \leq 10\,000$, $1 \leq q \leq 200000$) — the number of vertices in the polygon and the number of queries.

The next $n$ lines describe the wooden polygon, the $i$-th line contains two integers $x_i$ and $y_i$ ($|x_i|, |y_i|\leq 10^8$) — the coordinates of the $i$-th vertex of the polygon. It is guaranteed that polygon is strictly convex and the vertices are given in the counter-clockwise order and all vertices are distinct.

The next $q$ lines describe the queries, one per line. Each query starts with its type $1$ or $2$. Each query of the first type continues with two integers $f$ and...

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

#!/usr/bin/env python3

from math import hypot

[n, q] = list(map(int, input().strip().split()))
xys = [tuple(map(int, input().strip().split())) for _ in range(n)]
qis = [tuple(map(int, input().strip().split())) for _ in range(q)]

dxys = [(xys[(i + 1) % n][0] - xys[i][0], xys[(i + 1) % n][1] - xys[i][1]) for i in range(n)]

S = 3 * sum((x*dy - y*dx) for (x, y), (dx, dy) in zip(xys, dxys))
Sx = sum((dx + 2*x) * (x*dy - y*dx) for (x, y), (dx, dy) in zip(xys, dxys))
Sy = sum((dy + 2*y) * (x*dy - y*dx) for (x, y), (dx, dy) in zip(xys, dxys))
#Sy = sum((2*dx*dy + 3*x*dx + 3*x*dy + 6*x*y)*dy for (x, y), (dx, dy) in zip(xys, dxys))
for p in [2, 3]:
	while S % p == Sx % p == Sy % p == 0:
		S //= p
		Sx //= p
		Sy //= p

xyms = [(S*x - Sx, S*y - Sy) for x, y in xys]
hs = [hypot(x, y) for x, y in xyms]

def to_coord(x, y):
	return (x + Sx) / S, (y + Sy) / S

hangs = (0, 1)
hang_on = None
cx, cy = 0.0, 0.0

# hang on u
def get_v(v):
	if hang_on is None:
		return xyms[v]
	else:
		ux, uy = xyms[hang_on]
		vx, vy = xyms[v]
		h = hs[hang_on]
		return ((uy * vx - ux * vy) / h, (ux * vx + uy * vy) / h)

#def ss(v1, v2):
#	return tuple(vi + vj for vi, vj in zip(v1, v2))

#def disp():
#	print ('hangs on', hang_on, 'of', hangs)
#	print ('center', to_coord(cx, cy))
#	print ({i: to_coord(*ss(get_v(i), (cx, cy))) for i in range(n)})

#disp()
for qi in qis:
	if qi[0] == 1:
		_, f, t = qi  # 1-indexation
		s = hangs[1 - hangs.index(f - 1)]
		dx, dy = get_v(s)
		cx += dx
		cy += dy - hs[s]
		hang_on = s
		hangs = (s, t - 1)
#		print ('{} --> {}'.format(f - 1, t - 1))
#		disp()
	else:
		_, v = qi  # 1-indexation
		dx, dy = get_v(v - 1)
		print(*to_coord(cx + dx, cy + dy))


I found an interesting problem on https://codeforces.com/problemset/problem/976/A:
String can be called correct if it consists of characters "0" and "1" and there are no redundant leading zeroes. Here are some examples: "0", "10", "1001".

You are given a correct string s.

You can perform two different operations on this string:   swap any pair of adjacent characters (for example, "101" $\rightarrow$ "110");  replace "11" with "1" (for example, "110" $\rightarrow$ "10").

Let val(s) be such a number that s is its binary representation.

Correct string a is less than some other correct string b iff val(a) < val(b).

Your task is to find the minimum correct string that you can obtain from the given one using the operations described above. You can use these operations any number of times in any order (or even use no operations at all).

-----Input-----

The first line contains integer number n (1 ≤ n ≤ 100) — the length of string s.

The second line contains the string s consisting of characters "0" and "1". It is guaranteed that the string s is correct.

-----Output-----

Print one string — the minimum correct string that you can obtain from the given one.

-----Examples-----
Input
4
1001

Output
100

Input
1
1

Output
1

-----Note-----

In the first example you can obtain the answer by the following sequence of operations: "1001" $\rightarrow$ "1010" $\rightarrow$ "1100" $\rightarrow$ "100".

In the second example you can't obtain smaller answer no matter what operations you use.

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

def mp():
    return map(int,input().split())
#f = open("input.txt","r")
n = int(input())
a = list(input())
if a==['0']:
    print('0')
else:
    print('1'+'0'*a.count('0'))