I found an interesting problem on https://atcoder.jp/contests/abc129/tasks/abc129_e:
You are given a positive integer L in base two.
How many pairs of non-negative integers (a, b) satisfy the following conditions?
 - a + b \leq L
 - a + b = a \mbox{ XOR } b
Since there can be extremely many such pairs, print the count modulo 10^9 + 7.
 What is XOR?
The XOR of integers A and B, A \mbox{ XOR } B, is defined as follows:
 - When A \mbox{ XOR } B is written in base two, the digit in the 2^k's place (k \geq 0) is 1 if either A or B, but not both, has 1 in the 2^k's place, and 0 otherwise.
For example, 3 \mbox{ XOR } 5 = 6. (In base two: 011 \mbox{ XOR } 101 = 110.)

-----Constraints-----
 - L is given in base two, without leading zeros.
 - 1 \leq L < 2^{100\ 001}

-----Input-----
Input is given from Standard Input in the following format:
L

-----Output-----
Print the number of pairs (a, b) that satisfy the conditions, modulo 10^9 + 7.

-----Sample Input-----
10

-----Sample Output-----
5

Five pairs (a, b) satisfy the conditions: (0, 0), (0, 1), (1, 0), (0, 2) and (2, 0).

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

l = list(map(int, input()))
mod = 10 ** 9 + 7

ln = len(l)
dp = [[0] * 2 for _ in range(2)]
dp[0][1] = 1

for e in l:
    dp_new = [[0] * 2 for _ in range(2)]
    for now in range(2):
        for prev in range(2):
            # same -> same
            if now == e:
                dp_new[now][1] += dp[prev][1] * (now + 1)

            # same -> small
            if now == 0 and e == 1:
                dp_new[now][0] += dp[prev][1]

            # small -> small
            dp_new[now][0] += dp[prev][0] * (now + 1)

    dp = dp_new
    for i in range(2):
        for j in range(2):
            dp[i][j] %= mod

ans = 0
for row in dp:
    ans += sum(row)
    ans %= mod

print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc129/tasks/abc129_f:
 You are given <var>Q</var> tuples of integers <var>(L_i, A_i, B_i, M_i)</var>. For each tuple, answer the following question.
There is an arithmetic progression with L terms: s_0, s_1, s_2, ... , s_{L-1}.
The initial term is A, and the common difference is B. That is, s_i = A + B \times i holds.
Consider the integer obtained by concatenating the terms written in base ten without leading zeros. For example, the sequence 3, 7, 11, 15, 19 would be concatenated into 37111519. What is the remainder when that integer is divided by M?

-----Constraints-----
 - All values in input are integers.
 - 1 \leq L, A, B < 10^{18}
 - 2 \leq M \leq 10^9
 - All terms in the arithmetic progression are less than 10^{18}.

-----Input-----
Input is given from Standard Input in the following format:
L A B M

-----Output-----
Print the remainder when the integer obtained by concatenating the terms is divided by M.

-----Sample Input-----
5 3 4 10007

-----Sample Output-----
5563

Our arithmetic progression is 3, 7, 11, 15, 19, so the answer is 37111519 mod 10007, that is, 5563.

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

import numpy as np
import math

L, A, B, M = list(map(int, input().split()))

def f(i):
    return A+B*i

def Cd(d):
    return bisect(-1, L, d+1)-bisect(-1, L, d)

def is_ok(i, d):
    return len(str(f(i))) >= d

def bisect(ng, ok, d):
    while (abs(ok - ng) > 1):
        mid = (ok + ng) // 2
        if is_ok(mid, d):
            ok = mid
        else:
            ng = mid
    return ok

def pow_mat(a, x, p=math.inf):
    ret = np.eye(a.shape[0], dtype=int)
    tmp = a
    for i in range(x.bit_length()):
        if x >> i & 1:
            ret = np.mod(ret @ tmp, p)
        tmp = np.mod(tmp @ tmp, p)
    return ret

ret = np.eye(3, dtype=int)
for d in range(1, 19):
    a = np.array([[pow(10, d, M), 0, 0],
                  [1, 1, 0],
                  [0, B, 1]], dtype=int)
    ret = np.mod(ret @ pow_mat(a, Cd(d), M), M)
print((np.mod(np.array([0, A%M, 1]) @ ret, M)[0]))


I found an interesting problem on https://atcoder.jp/contests/abc130/tasks/abc130_a:
X and A are integers between 0 and 9 (inclusive).
If X is less than A, print 0; if X is not less than A, print 10.

-----Constraints-----
 - 0 \leq X, A \leq 9
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
X A

-----Output-----
If X is less than A, print 0; if X is not less than A, print 10.

-----Sample Input-----
3 5

-----Sample Output-----
0

3 is less than 5, so we should print 0.

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

x,a = map(int,input().split())

if x < a:
    print(0)
elif x >= a:
    print(10)


I found an interesting problem on https://atcoder.jp/contests/abc130/tasks/abc130_b:
A ball will bounce along a number line, making N + 1 bounces. It will make the first bounce at coordinate D_1 = 0, and the i-th bounce (2 \leq i \leq N+1) at coordinate D_i = D_{i-1} + L_{i-1}.
How many times will the ball make a bounce where the coordinate is at most X?

-----Constraints-----
 - 1 \leq N \leq 100
 - 1 \leq L_i \leq 100
 - 1 \leq X \leq 10000
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N X
L_1 L_2 ... L_{N-1} L_N

-----Output-----
Print the number of times the ball will make a bounce where the coordinate is at most X.

-----Sample Input-----
3 6
3 4 5

-----Sample Output-----
2

The ball will make a bounce at the coordinates 0, 3, 7 and 12, among which two are less than or equal to 6.

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

from collections import defaultdict

def mapt(fn, *args):
    return tuple(map(fn, *args))

def Input():
    return mapt(int, input().split(" "))

def main():
    n, x = Input()
    l = Input()
    d = defaultdict(int)
    d[0] = 0
    ans = 0

    for i in range(1, n+1):
        d[i] = d[i-1] + l[i-1]

    for i in d.values():
        if i <= x: ans += 1

    print(ans)

main()


I found an interesting problem on https://atcoder.jp/contests/abc130/tasks/abc130_c:
There is a rectangle in a coordinate plane. The coordinates of the four vertices are (0,0), (W,0), (W,H), and (0,H).
You are given a point (x,y) which is within the rectangle or on its border. We will draw a straight line passing through (x,y) to cut the rectangle into two parts. Find the maximum possible area of the part whose area is not larger than that of the other. Additionally, determine if there are multiple ways to cut the rectangle and achieve that maximum.

-----Constraints-----
 - 1 \leq W,H \leq 10^9
 - 0\leq x\leq W
 - 0\leq y\leq H
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
W H x y

-----Output-----
Print the maximum possible area of the part whose area is not larger than that of the other, followed by 1 if there are multiple ways to cut the rectangle and achieve that maximum, and 0 otherwise.
The area printed will be judged correct when its absolute or relative error is at most 10^{-9}.

-----Sample Input-----
2 3 1 2

-----Sample Output-----
3.000000 0

The line x=1 gives the optimal cut, and no other line does.

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

W,H,x,y = map(int,input().split())
print(W*H/2,1 if int(2*x==W and 2*y==H) else 0)


I found an interesting problem on https://atcoder.jp/contests/abc130/tasks/abc130_d:
You are given a sequence of positive integers of length N, A=a_1,a_2,…,a_{N}, and an integer K.
How many contiguous subsequences of A satisfy the following condition?
 - (Condition) The sum of the elements in the contiguous subsequence is at least K.
We consider two contiguous subsequences different if they derive from different positions in A, even if they are the same in content.
Note that the answer may not fit into a 32-bit integer type.

-----Constraints-----
 - 1 \leq a_i \leq 10^5
 - 1 \leq N \leq 10^5
 - 1 \leq K \leq 10^{10}

-----Input-----
Input is given from Standard Input in the following format:
N K
a_1 a_2 ... a_N

-----Output-----
Print the number of contiguous subsequences of A that satisfy the condition.

-----Sample Input-----
4 10
6 1 2 7

-----Sample Output-----
2

The following two contiguous subsequences satisfy the condition:
 - A[1..4]=a_1,a_2,a_3,a_4, with the sum of 16
 - A[2..4]=a_2,a_3,a_4, with the sum of 10

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

n, k, *a = list(map(int, open(0).read().split()))

l = r = 0
s = 0
unko = 0
while l < n:
    while r < n and s < k:
        s += a[r]
        r += 1
    if s < k:
        break
    unko += n - r + 1
    s -= a[l]
    if l == r:
        r += 1
    l += 1
print(unko)


I found an interesting problem on https://atcoder.jp/contests/abc130/tasks/abc130_e:
You are given two integer sequences S and T of length N and M, respectively, both consisting of integers between 1 and 10^5 (inclusive).
In how many pairs of a subsequence of S and a subsequence of T do the two subsequences are the same in content?
Here the subsequence of A is a sequence obtained by removing zero or more elements from A and concatenating the remaining elements without changing the order.
For both S and T, we distinguish two subsequences if the sets of the indices of the removed elements are different, even if the subsequences are the same in content.
Since the answer can be tremendous, print the number modulo 10^9+7.

-----Constraints-----
 - 1 \leq N, M \leq 2 \times 10^3
 - The length of S is N.
 - The length of T is M.
 - 1 \leq S_i, T_i \leq 10^5
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N M
S_1 S_2 ... S_{N-1} S_{N}
T_1 T_2 ... T_{M-1} T_{M}

-----Output-----
Print the number of pairs of a subsequence of S and a subsequence of T such that the subsequences are the same in content, modulo 10^9+7.

-----Sample Input-----
2 2
1 3
3 1

-----Sample Output-----
3

S has four subsequences: (), (1), (3), (1, 3).
T has four subsequences: (), (3), (1), (3, 1).
There are 1 \times 1 pair of subsequences in which the subsequences are both (), 1 \times 1 pair of subsequences in which the subsequences are both (1), and 1 \times 1 pair of subsequences in which the subsequences are both (3), for a total of three pairs.

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

import numpy as np
N,M = map(int,input().split())
S = input().split()
T = np.array(input().split(), dtype = np.int32)
dp = np.ones(M+1, dtype = np.int64)
for s in S:
  dp[1:] = ((dp[:-1] * (T == int(s))).cumsum() + dp[1:]) % (10**9 + 7)
print(dp[M])


I found an interesting problem on https://atcoder.jp/contests/abc130/tasks/abc130_f:
There are N points in a two-dimensional plane. The initial coordinates of the i-th point are (x_i, y_i). Now, each point starts moving at a speed of 1 per second, in a direction parallel to the x- or y- axis. You are given a character d_i that represents the specific direction in which the i-th point moves, as follows:
 - If d_i = R, the i-th point moves in the positive x direction;
 - If d_i = L, the i-th point moves in the negative x direction;
 - If d_i = U, the i-th point moves in the positive y direction;
 - If d_i = D, the i-th point moves in the negative y direction.
You can stop all the points at some moment of your choice after they start moving (including the moment they start moving).
Then, let x_{max} and x_{min} be the maximum and minimum among the x-coordinates of the N points, respectively. Similarly, let y_{max} and y_{min} be the maximum and minimum among the y-coordinates of the N points, respectively.
Find the minimum possible value of (x_{max} - x_{min}) \times (y_{max} - y_{min}) and print it.

-----Constraints-----
 - 1 \leq N \leq 10^5
 - -10^8 \leq x_i,\ y_i \leq 10^8
 - x_i and y_i are integers.
 - d_i is R, L, U, or D.

-----Input-----
Input is given from Standard Input in the following format:
N
x_1 y_1 d_1
x_2 y_2 d_2
.
.
.
x_N y_N d_N

-----Output-----
Print the minimum possible value of (x_{max} - x_{min}) \times (y_{max} - y_{min}).
The output will be considered correct when its absolute or relative error from the judge's output is at most 10^{-9}.

-----Sample Input-----
2
0 3 D
3 0 L

-----Sample Output-----
0

After three seconds, the two points will meet at the origin. The value in question will be 0 at that moment.

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

import sys
input = sys.stdin.readline

INF = 10**18

N = int(input())
D = []
U = []
L = []
R = []
UD = []
LR = []
for _ in range(N):
    str_x, str_y, d = map(str, input().rstrip().split())
    x = int(str_x)
    y = int(str_y)
    if d == "U":
        U.append(y)
        UD.append(x)
    elif d == "D":
        D.append(y)
        UD.append(x)
    elif d == "L":
        L.append(x)
        LR.append(y)
    else:
        R.append(x)
        LR.append(y)

UD.sort()
LR.sort()
U.sort()
D.sort()
L.sort()
R.sort()

T = [0]
if L and R:
    T.append((L[0]-R[0])/2)
    T.append((L[-1]-R[-1])/2)
if L and UD:
    T.append(L[0]-UD[0])
    T.append(L[-1]-UD[-1])
if R and UD:
    T.append(UD[0]-R[0])
    T.append(UD[-1]-R[-1])
if U and D:
    T.append((D[0]-U[0])/2)
    T.append((D[-1]-U[-1])/2)
if U and LR:
    T.append(-U[0]+LR[0])
    T.append(-U[-1]+LR[-1])
if D and LR:
    T.append(-LR[0]+D[0])
    T.append(-LR[-1]+D[-1])

ans = INF
for t in T:
    if t < 0: continue
    l = INF
    r = -INF
    d = INF
    u = -INF
    if L:
        l = min(l, L[0]-t)
        r = max(r, L[-1]-t)
    if R:
        l = min(l, R[0]+t)
        r = max(r, R[-1]+t)
    if U:
        d = min(d, U[0]+t)
        u = max(u, U[-1]+t)
    if D:
        d = min(d, D[0]-t)
        u = max(u, D[-1]-t)
    if LR:
        d = min(d, LR[0])
        u = max(u, LR[-1])
    if UD:
        l = min(l, UD[0])
        r = max(r, UD[-1])
    ans = min(ans, (r-l)*(u-d))

print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc131/tasks/abc131_a:
The door of Snuke's laboratory is locked with a security code.
The security code is a 4-digit number. We say the security code is hard to enter when it contains two consecutive digits that are the same.
You are given the current security code S. If S is hard to enter, print Bad; otherwise, print Good.

-----Constraints-----
 - S is a 4-character string consisting of digits.

-----Input-----
Input is given from Standard Input in the following format:
S

-----Output-----
If S is hard to enter, print Bad; otherwise, print Good.

-----Sample Input-----
3776

-----Sample Output-----
Bad

The second and third digits are the same, so 3776 is hard to enter.

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

S = list(map(int,input()))

if S[0] == S[1] or S[1] == S[2]or S[2] == S[3]:
    print('Bad')
else:
    print('Good')


I found an interesting problem on https://atcoder.jp/contests/abc131/tasks/abc131_b:
You have N apples, called Apple 1, Apple 2, Apple 3, ..., Apple N. The flavor of Apple i is L+i-1, which can be negative.
You can make an apple pie using one or more of the apples. The flavor of the apple pie will be the sum of the flavors of the apples used.
You planned to make an apple pie using all of the apples, but being hungry tempts you to eat one of them, which can no longer be used to make the apple pie.
You want to make an apple pie that is as similar as possible to the one that you planned to make. Thus, you will choose the apple to eat so that the flavor of the apple pie made of the remaining N-1 apples will have the smallest possible absolute difference from the flavor of the apple pie made of all the N apples.
Find the flavor of the apple pie made of the remaining N-1 apples when you choose the apple to eat as above.
We can prove that this value is uniquely determined.

-----Constraints-----
 - 2 \leq N \leq 200
 - -100 \leq L \leq 100
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N L

-----Output-----
Find the flavor of the apple pie made of the remaining N-1 apples when you optimally choose the apple to eat.

-----Sample Input-----
5 2

-----Sample Output-----
18

The flavors of Apple 1, 2, 3, 4, and 5 are 2, 3, 4, 5, and 6, respectively. The optimal choice is to eat Apple 1, so the answer is 3+4+5+6=18.

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

n, l = list(map(int, input().split()))
s = n*(l-1) + n*(n+1)/2
c = abs(s)
j = 1
for i in range(n):
  t = s - (l+i)
  T = abs(s-t)
  if T < c:
    c = T
    j = i
ans = s -(l+j)
print((int(ans)))


I found an interesting problem on https://atcoder.jp/contests/abc131/tasks/abc131_c:
You are given four integers A, B, C, and D. Find the number of integers between A and B (inclusive) that can be evenly divided by neither C nor D.

-----Constraints-----
 - 1\leq A\leq B\leq 10^{18}
 - 1\leq C,D\leq 10^9
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
A B C D

-----Output-----
Print the number of integers between A and B (inclusive) that can be evenly divided by neither C nor D.

-----Sample Input-----
4 9 2 3

-----Sample Output-----
2

5 and 7 satisfy the condition.

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

import math

a,b,c,d=map(int,input().split())

n=b-a+1

def lcm(x, y):
    return (x * y) // math.gcd(x, y)

x=lcm(c,d)

cc=b//c-(a-1)//c
dc=b//d-(a-1)//d
xc=b//x-(a-1)//x

print(n-cc-dc+xc)


I found an interesting problem on https://atcoder.jp/contests/abc131/tasks/abc131_d:
Kizahashi, who was appointed as the administrator of ABC at National Problem Workshop in the Kingdom of AtCoder, got too excited and took on too many jobs.
Let the current time be time 0. Kizahashi has N jobs numbered 1 to N.
It takes A_i units of time for Kizahashi to complete Job i. The deadline for Job i is time B_i, and he must complete the job before or at this time.
Kizahashi cannot work on two or more jobs simultaneously, but when he completes a job, he can start working on another immediately.
Can Kizahashi complete all the jobs in time? If he can, print Yes; if he cannot, print No.

-----Constraints-----
 - All values in input are integers.
 - 1 \leq N \leq 2 \times 10^5
 - 1 \leq A_i, B_i \leq 10^9 (1 \leq i \leq N)

-----Input-----
Input is given from Standard Input in the following format:
N
A_1 B_1
.
.
.
A_N B_N

-----Output-----
If Kizahashi can complete all the jobs in time, print Yes; if he cannot, print No.

-----Sample Input-----
5
2 4
1 9
1 8
4 9
3 12

-----Sample Output-----
Yes

He can complete all the jobs in time by, for example, doing them in the following order:
 - Do Job 2 from time 0 to 1.
 - Do Job 1 from time 1 to 3.
 - Do Job 4 from time 3 to 7.
 - Do Job 3 from time 7 to 8.
 - Do Job 5 from time 8 to 11.
Note that it is fine to complete Job 3 exactly at the deadline, time 8.

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

n=int(input())
ba=[]
for i in range(n):
  a,b=map(int,input().split())
  ba.append([b,a])
ba.sort()
t=0
for i in range(n):
  t+=ba[i][1]
  if t<=ba[i][0]:
    continue
  else:
    print('No')
    return
print('Yes')


I found an interesting problem on https://atcoder.jp/contests/abc131/tasks/abc131_f:
There are N dots in a two-dimensional plane. The coordinates of the i-th dot are (x_i, y_i).
We will repeat the following operation as long as possible:
 - Choose four integers a, b, c, d (a \neq c, b \neq d) such that there are dots at exactly three of the positions (a, b), (a, d), (c, b) and (c, d), and add a dot at the remaining position.
We can prove that we can only do this operation a finite number of times. Find the maximum number of times we can do the operation.

-----Constraints-----
 - 1 \leq N \leq 10^5
 - 1 \leq x_i, y_i \leq 10^5
 - If i \neq j, x_i \neq x_j or y_i \neq y_j.
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N
x_1 y_1
:
x_N y_N

-----Output-----
Print the maximum number of times we can do the operation.

-----Sample Input-----
3
1 1
5 1
5 5

-----Sample Output-----
1

By choosing a = 1, b = 1, c = 5, d = 5, we can add a dot at (1, 5). We cannot do the operation any more, so the maximum number of operations is 1.

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

# https://drken1215.hatenablog.com/entry/2019/06/23/004700
# https://tjkendev.github.io/procon-library/python/union_find/union_find.html

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

    MX = 10 ** 5 + 10

    *p, = [r for r in range(MX * 2)]

    def root(x):
        if x == p[x]:
            return x
        p[x] = y = root(p[x])
        return y

    def unite(x, y):
        px = root(x)
        py = root(y)
        if px == py:
            return 0
        if px < py:
            p[py] = px
        else:
            p[px] = py
        return 1

    n = int(input())
    for _ in range(n):
        x, y = (int(x) - 1 for x in input().split())  # [1,)->[0,)
        unite(x, y + MX)

    xs = [0] * (MX * 2)
    ys = [0] * (MX * 2)

    for r in range(MX):
        xs[root(r)] += 1

    for r in range(MX, MX * 2):
        ys[root(r)] += 1

    ans = -n
    for r in range(MX * 2):
        ans += xs[r] * ys[r]

    print(ans)

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://atcoder.jp/contests/abc132/tasks/abc132_a:
You are given a 4-character string S consisting of uppercase English letters.
Determine if S consists of exactly two kinds of characters which both appear twice in S.

-----Constraints-----
 - The length of S is 4.
 - S consists of uppercase English letters.

-----Input-----
Input is given from Standard Input in the following format:
S

-----Output-----
If S consists of exactly two kinds of characters which both appear twice in S, print Yes; otherwise, print No.

-----Sample Input-----
ASSA

-----Sample Output-----
Yes

S consists of A and S which both appear twice in S.

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

s=input()
ans="Yes"
for i in range(4):
    if s.count(s[i])!=2:
        ans="No"
print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc132/tasks/abc132_b:
We have a permutation p = {p_1,\ p_2,\ ...,\ p_n} of {1,\ 2,\ ...,\ n}.
Print the number of elements p_i (1 < i < n) that satisfy the following condition:
 - p_i is the second smallest number among the three numbers p_{i - 1}, p_i, and p_{i + 1}.

-----Constraints-----
 - All values in input are integers.
 - 3 \leq n \leq 20
 - p is a permutation of {1,\ 2,\ ...,\ n}.

-----Input-----
Input is given from Standard Input in the following format:
n
p_1 p_2 ... p_n

-----Output-----
Print the number of elements p_i (1 < i < n) that satisfy the condition.

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

-----Sample Output-----
2

p_2 = 3 is the second smallest number among p_1 = 1, p_2 = 3, and p_3 = 5. Also, p_4 = 4 is the second smallest number among p_3 = 5, p_4 = 4, and p_5 = 2. These two elements satisfy the condition.

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

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

cnt = 0
for i in range(1,n-1):
    if min(P[i-1],P[i],P[i+1]) < P[i] and max(P[i-1],P[i],P[i+1]) > P[i]:
        cnt += 1

print(cnt)


I found an interesting problem on https://atcoder.jp/contests/abc132/tasks/abc132_c:
Takahashi made N problems for competitive programming.
The problems are numbered 1 to N, and the difficulty of Problem i is represented as an integer d_i (the higher, the harder).
He is dividing the problems into two categories by choosing an integer K, as follows:
 - A problem with difficulty K or higher will be for ARCs.
 - A problem with difficulty lower than K will be for ABCs.
How many choices of the integer K make the number of problems for ARCs and the number of problems for ABCs the same?

-----Problem Statement-----
 - 2 \leq N \leq 10^5
 - N is an even number.
 - 1 \leq d_i \leq 10^5
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N
d_1 d_2 ... d_N

-----Output-----
Print the number of choices of the integer K that make the number of problems for ARCs and the number of problems for ABCs the same.

-----Sample Input-----
6
9 1 4 4 6 7

-----Sample Output-----
2

If we choose K=5 or 6, Problem 1, 5, and 6 will be for ARCs, Problem 2, 3, and 4 will be for ABCs, and the objective is achieved.
Thus, the answer is 2.

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

n = int(input())
d = sorted(map(int, input().split()))
k1 = d[int(n/2)-1]+1
k2 = d[int(n/2)]
print(k2-k1+1)


I found an interesting problem on https://atcoder.jp/contests/abc132/tasks/abc132_d:
There are K blue balls and N-K red balls. The balls of the same color cannot be distinguished. Snuke and Takahashi are playing with these balls.
First, Snuke will arrange the N balls in a row from left to right.
Then, Takahashi will collect only the K blue balls. In one move, he can collect any number of consecutive blue balls. He will collect all the blue balls in the fewest moves possible.
How many ways are there for Snuke to arrange the N balls in a row so that Takahashi will need exactly i moves to collect all the blue balls? Compute this number modulo 10^9+7 for each i such that 1 \leq i \leq K.

-----Constraints-----
 - 1 \leq K \leq N \leq 2000

-----Input-----
Input is given from Standard Input in the following format:
N K

-----Output-----
Print K lines. The i-th line (1 \leq i \leq K) should contain the number of ways to arrange the N balls so that Takahashi will need exactly i moves to collect all the blue balls, modulo 10^9+7.

-----Sample Input-----
5 3

-----Sample Output-----
3
6
1

There are three ways to arrange the balls so that Takahashi will need exactly one move: (B, B, B, R, R), (R, B, B, B, R), and (R, R, B, B, B). (R and B stands for red and blue, respectively).
There are six ways to arrange the balls so that Takahashi will need exactly two moves: (B, B, R, B, R), (B, B, R, R, B), (R, B, B, R, B), (R, B, R, B, B), (B, R, B, B, R), and (B, R, R, B, B).
There is one way to arrange the balls so that Takahashi will need exactly three moves: (B, R, B, R, B).

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

import sys
sys.setrecursionlimit(10**7)
input = sys.stdin.readline

from operator import mul
from functools import reduce

def main():
    n, k = list(map(int, input().split()))
    modulo = 1000_000_000 + 7

    def cmb(n, r):
        if n < r:
            return 0
        r = min(n - r, r)
        if r == 0:
            return 1
        numer = reduce(mul, range(n, n - r, -1))
        denom = reduce(mul, range(1, r + 1))
        return numer // denom % modulo

    for i in range(1, k+1):
        # i分割する方法
        a = cmb(k-1, i-1)
        # 赤のボールを分割する方法
        b = cmb(n-k+1, i)
        print(a * b % modulo)

main()


I found an interesting problem on https://atcoder.jp/contests/abc132/tasks/abc132_e:
Ken loves ken-ken-pa (Japanese version of hopscotch). Today, he will play it on a directed graph G.
G consists of N vertices numbered 1 to N, and M edges. The i-th edge points from Vertex u_i to Vertex v_i.
First, Ken stands on Vertex S. He wants to reach Vertex T by repeating ken-ken-pa. In one ken-ken-pa, he does the following exactly three times: follow an edge pointing from the vertex on which he is standing.
Determine if he can reach Vertex T by repeating ken-ken-pa. If the answer is yes, find the minimum number of ken-ken-pa needed to reach Vertex T. Note that visiting Vertex T in the middle of a ken-ken-pa does not count as reaching Vertex T by repeating ken-ken-pa.

-----Constraints-----
 - 2 \leq N \leq 10^5
 - 0 \leq M \leq \min(10^5, N (N-1))
 - 1 \leq u_i, v_i \leq N(1 \leq i \leq M)
 - u_i \neq v_i (1 \leq i \leq M)
 - If i \neq j, (u_i, v_i) \neq (u_j, v_j).
 - 1 \leq S, T \leq N
 - S \neq T

-----Input-----
Input is given from Standard Input in the following format:
N M
u_1 v_1
:
u_M v_M
S T

-----Output-----
If Ken cannot reach Vertex T from Vertex S by repeating ken-ken-pa, print -1.
If he can, print the minimum number of ken-ken-pa needed to reach vertex T.

-----Sample Input-----
4 4
1 2
2 3
3 4
4 1
1 3

-----Sample Output-----
2

Ken can reach Vertex 3 from Vertex 1 in two ken-ken-pa, as follows: 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 in the first ken-ken-pa, then 4 \rightarrow 1 \rightarrow 2 \rightarrow 3 in the second ken-ken-pa. This is the minimum number of ken-ken-pa needed.

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

N,M=list(map(int,input().split()))
tree=[[] for _ in range(N)]
for _ in range(M):
    u,v=list(map(int,input().split()))
    tree[u-1].append(v-1)
S,T=list(map(int,input().split()))
s=S-1
t=T-1
ischecked=[[0]*3 for _ in range(N)]
ischecked[s][0]=1
ans=-1
q=[]
q.append([s,0])
while q:
    v,c=q.pop(0)
    if v==t and c%3==0:
        ans=c//3
        break
    for i in tree[v]:
        if ischecked[i][(c+1)%3]==0:
            q.append([i,c+1])
            ischecked[i][(c+1)%3]=1
print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc132/tasks/abc132_f:
Find the number of sequences of length K consisting of positive integers such that the product of any two adjacent elements is at most N, modulo 10^9+7.

-----Constraints-----
 - 1\leq N\leq 10^9
 - 1 2\leq K\leq 100 (fixed at 21:33 JST)
 - N and K are integers.

-----Input-----
Input is given from Standard Input in the following format:
N K

-----Output-----
Print the number of sequences, modulo 10^9+7.

-----Sample Input-----
3 2

-----Sample Output-----
5

(1,1), (1,2), (1,3), (2,1), and (3,1) satisfy the condition.

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

# coding: utf-8
import sys
import numpy as np

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

# 桁dp、√Nまでをlower、それ以降をup_range、Nをlowerで割ったものでまとめる
MOD = 10 ** 9 + 7
N, K = lr()
M = int(N ** .5)
A = np.arange(M+1, dtype=np.int64)
high_range = np.zeros(M+1, dtype=np.int64)
high_range[1:] = N // A[1:] - np.maximum(M, N // (A[1:] + 1))  # Mはlowerに入れるので0
low = np.zeros(M+1, dtype=np.int64)
high = np.zeros(M+1, dtype=np.int64)
low[1] = 1
for _ in range(K):
    prev_low = low.copy()
    prev_high = high.copy()
    prev_low_cum = prev_low.cumsum() % MOD
    prev_high_cum = prev_high.cumsum() % MOD
    low = np.zeros(M+1, dtype=np.int64)
    low[1:] += (prev_low_cum[-1] + prev_high_cum[-1])
    low[1:] -= prev_high_cum[:-1]
    high = prev_low_cum * high_range
    low %= MOD; high %= MOD

answer = (low[1:].sum() + high[1:].sum()) % MOD
print((answer % MOD))


I found an interesting problem on https://atcoder.jp/contests/abc133/tasks/abc133_a:
N of us are going on a trip, by train or taxi.
The train will cost each of us A yen (the currency of Japan).
The taxi will cost us a total of B yen.
How much is our minimum total travel expense?

-----Constraints-----
 - All values in input are integers.
 - 1 \leq N \leq 20
 - 1 \leq A \leq 50
 - 1 \leq B \leq 50

-----Input-----
Input is given from Standard Input in the following format:
N A B

-----Output-----
Print an integer representing the minimum total travel expense.

-----Sample Input-----
4 2 9

-----Sample Output-----
8

The train will cost us 4 \times 2 = 8 yen, and the taxi will cost us 9 yen, so the minimum total travel expense is 8 yen.

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


I found an interesting problem on https://atcoder.jp/contests/abc133/tasks/abc133_b:
There are N points in a D-dimensional space.
The coordinates of the i-th point are (X_{i1}, X_{i2}, ..., X_{iD}).
The distance between two points with coordinates (y_1, y_2, ..., y_D) and (z_1, z_2, ..., z_D) is \sqrt{(y_1 - z_1)^2 + (y_2 - z_2)^2 + ... + (y_D - z_D)^2}.
How many pairs (i, j) (i < j) are there such that the distance between the i-th point and the j-th point is an integer?

-----Constraints-----
 - All values in input are integers.
 - 2 \leq N \leq 10
 - 1 \leq D \leq 10
 - -20 \leq X_{ij} \leq 20
 - No two given points have the same coordinates. That is, if i \neq j, there exists k such that X_{ik} \neq X_{jk}.

-----Input-----
Input is given from Standard Input in the following format:
N D
X_{11} X_{12} ... X_{1D}
X_{21} X_{22} ... X_{2D}
\vdots
X_{N1} X_{N2} ... X_{ND}

-----Output-----
Print the number of pairs (i, j) (i < j) such that the distance between the i-th point and the j-th point is an integer.

-----Sample Input-----
3 2
1 2
5 5
-2 8

-----Sample Output-----
1

The number of pairs with an integer distance is one, as follows:
 - The distance between the first point and the second point is \sqrt{|1-5|^2 + |2-5|^2} = 5, which is an integer.
 - The distance between the second point and the third point is \sqrt{|5-(-2)|^2 + |5-8|^2} = \sqrt{58}, which is not an integer.
 - The distance between the third point and the first point is \sqrt{|-2-1|^2+|8-2|^2} = 3\sqrt{5}, which is not an integer.

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

import itertools

N,D=map(int, input().split())
X=[list(map(int, input().split())) for _ in range(N)]

combi=list(itertools.combinations([i for i in range(N)],2 ))

ans=0

for c in combi:
	temp=0
	for d in range(D):
		temp+=(X[c[0]][d]-X[c[1]][d])**2
	temp=temp**.5
	if float.is_integer(temp):ans+=1

print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc133/tasks/abc133_c:
You are given two non-negative integers L and R.
We will choose two integers i and j such that L \leq i < j \leq R.
Find the minimum possible value of (i \times j) \mbox{ mod } 2019.

-----Constraints-----
 - All values in input are integers.
 - 0 \leq L < R \leq 2 \times 10^9

-----Input-----
Input is given from Standard Input in the following format:
L R

-----Output-----
Print the minimum possible value of (i \times j) \mbox{ mod } 2019 when i and j are chosen under the given condition.

-----Sample Input-----
2020 2040

-----Sample Output-----
2

When (i, j) = (2020, 2021), (i \times j) \mbox{ mod } 2019  = 2.

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

L, R = map(int,input().split())
Dif = abs(L-R)+1
if Dif >= 2020:
    Ans = 0
else:
    Box = []
    for i in range(L,R+1):
        Box.append(i%2019)
    Box.sort()
    Ans = 2020*2020
    for i in range(len(Box)-1):
        B1 = Box[i]
        for j in range(i+1,len(Box)):
            B2 = Box[j]
            Ans = min((B1*B2)%2019, Ans)
print(Ans%2019)


I found an interesting problem on https://atcoder.jp/contests/abc133/tasks/abc133_d:
There are N mountains in a circle, called Mountain 1, Mountain 2, ..., Mountain N in clockwise order. N is an odd number.
Between these mountains, there are N dams, called Dam 1, Dam 2, ..., Dam N. Dam i (1 \leq i \leq N) is located between Mountain i and i+1 (Mountain N+1 is Mountain 1).
When Mountain i (1 \leq i \leq N) receives 2x liters of rain, Dam i-1 and Dam i each accumulates x liters of water (Dam 0 is Dam N).
One day, each of the mountains received a non-negative even number of liters of rain.
As a result, Dam i (1 \leq i \leq N) accumulated a total of A_i liters of water.
Find the amount of rain each of the mountains received. We can prove that the solution is unique under the constraints of this problem.

-----Constraints-----
 - All values in input are integers.
 - 3 \leq N \leq 10^5-1
 - N is an odd number.
 - 0 \leq A_i \leq 10^9
 - The situation represented by input can occur when each of the mountains receives a non-negative even number of liters of rain.

-----Input-----
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N

-----Output-----
Print N integers representing the number of liters of rain Mountain 1, Mountain 2, ..., Mountain N received, in this order.

-----Sample Input-----
3
2 2 4

-----Sample Output-----
4 0 4

If we assume Mountain 1, 2, and 3 received 4, 0, and 4 liters of rain, respectively, it is consistent with this input, as follows:
 - Dam 1 should have accumulated \frac{4}{2} + \frac{0}{2} = 2 liters of water.
 - Dam 2 should have accumulated \frac{0}{2} + \frac{4}{2} = 2 liters of water.
 - Dam 3 should have accumulated \frac{4}{2} + \frac{4}{2} = 4 liters of water.

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

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

tmp = 0
for i in range(N//2):
  tmp += A[2*i+1]

ans = []
if sum(A) > 2*tmp:
  ans.append(sum(A)-2*tmp)
else:
  ans.append(0)

for i in range(N-1):
  ans.append(2*A[i]-ans[-1])
print((*ans))


I found an interesting problem on https://atcoder.jp/contests/abc133/tasks/abc133_e:
You are given a tree with N vertices and N-1 edges. The vertices are numbered 1 to N, and the i-th edge connects Vertex a_i and b_i.
You have coloring materials of K colors.
For each vertex in the tree, you will choose one of the K colors to paint it, so that the following condition is satisfied:
 - If the distance between two different vertices x and y is less than or equal to two, x and y have different colors.
How many ways are there to paint the tree? Find the count modulo 1\ 000\ 000\ 007.
What is tree?
A tree is a kind of graph. For detail, please see: Wikipedia "Tree (graph theory)"

What is distance?
The distance between two vertices x and y is the minimum number of edges one has to traverse to get from x to y.

-----Constraints-----
 - 1 \leq N,K \leq 10^5
 - 1 \leq a_i,b_i \leq N
 - The given graph is a tree.

-----Input-----
Input is given from Standard Input in the following format:
N K
a_1 b_1
a_2 b_2
.
.
.
a_{N-1} b_{N-1}

-----Output-----
Print the number of ways to paint the tree, modulo 1\ 000\ 000\ 007.

-----Sample Input-----
4 3
1 2
2 3
3 4

-----Sample Output-----
6

There are six ways to paint the tree.

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

#!/usr/bin/env python3

MOD = 10 ** 9 + 7

def main():
    n, k = list(map(int, input().split()))
    adj = [[] for i in range(n)]
    for i in range(n - 1):
        a, b = list(map(int, input().split()))
        a -= 1
        b -= 1
        adj[a].append(b)
        adj[b].append(a)

    res = k
    stack = [0]
    visited = [False for i in range(n)]
    while stack:
        i = stack.pop()
        visited[i] = True
        children = [x for x in adj[i] if not visited[x]]
        res *= perm((k - 1 if i == 0 else k - 2), len(children))
        res %= MOD
        for c in children:
            stack.append(c)
    print(res)

def perm(t, s):
    res = 1
    for i in range(s):
        res *= t
        res %= MOD
        t -= 1
    return res

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://atcoder.jp/contests/abc134/tasks/abc134_a:
It is known that the area of a regular dodecagon inscribed in a circle of radius a is 3a^2.
Given an integer r, find the area of a regular dodecagon inscribed in a circle of radius r.

-----Constraints-----
 - 1 \leq r \leq 100
 - r is an integer.

-----Input-----
Input is given from Standard Input in the following format:
r

-----Output-----
Print an integer representing the area of the regular dodecagon.

-----Sample Input-----
4

-----Sample Output-----
48

The area of the regular dodecagon is 3 \times 4^2 = 48.

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


I found an interesting problem on https://atcoder.jp/contests/abc134/tasks/abc134_b:
There are N apple trees in a row. People say that one of them will bear golden apples.
We want to deploy some number of inspectors so that each of these trees will be inspected.
Each inspector will be deployed under one of the trees. For convenience, we will assign numbers from 1 through N to the trees. An inspector deployed under the i-th tree (1 \leq i \leq N) will inspect the trees with numbers between i-D and i+D (inclusive).
Find the minimum number of inspectors that we need to deploy to achieve the objective.

-----Constraints-----
 - All values in input are integers.
 - 1 \leq N \leq 20
 - 1 \leq D \leq 20

-----Input-----
Input is given from Standard Input in the following format:
N D

-----Output-----
Print the minimum number of inspectors that we need to deploy to achieve the objective.

-----Sample Input-----
6 2

-----Sample Output-----
2

We can achieve the objective by, for example, placing an inspector under Tree 3 and Tree 4.

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

N, D = map(int, input().split())

monitor, ans = 0, 0
while monitor < N:
  monitor += 2*D + 1
  ans += 1
print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc134/tasks/abc134_c:
You are given a sequence of length N: A_1, A_2, ..., A_N.
For each integer i between 1 and N (inclusive), answer the following question:
 - Find the maximum value among the N-1 elements other than A_i in the sequence.

-----Constraints-----
 - 2 \leq N \leq 200000
 - 1 \leq A_i \leq 200000
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N
A_1
:
A_N

-----Output-----
Print N lines. The i-th line (1 \leq i \leq N) should contain the maximum value among the N-1 elements other than A_i in the sequence.

-----Sample Input-----
3
1
4
3

-----Sample Output-----
4
3
4

 - The maximum value among the two elements other than A_1, that is, A_2 = 4 and A_3 = 3, is 4.
 - The maximum value among the two elements other than A_2, that is, A_1 = 1 and A_3 = 3, is 3.
 - The maximum value among the two elements other than A_3, that is, A_1 = 1 and A_2 = 4, is 4.

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

import copy

N = int(input())

ary = []
for _ in range(N):
    ary.append(int(input()))

ary_copy = copy.copy(ary)
ary_copy.sort()

max_1 = ary_copy[-1]
max_2 = ary_copy[-2]

for i in ary:
    if i == max_1:
        print(max_2)
    elif i != max_1:
        print(max_1)


I found an interesting problem on https://atcoder.jp/contests/abc134/tasks/abc134_d:
There are N empty boxes arranged in a row from left to right.
The integer i is written on the i-th box from the left (1 \leq i \leq N).
For each of these boxes, Snuke can choose either to put a ball in it or to put nothing in it.
We say a set of choices to put a ball or not in the boxes is good when the following condition is satisfied:
 - For every integer i between 1 and N (inclusive), the total number of balls contained in the boxes with multiples of i written on them is congruent to a_i modulo 2.
Does there exist a good set of choices? If the answer is yes, find one good set of choices.

-----Constraints-----
 - All values in input are integers.
 - 1 \leq N \leq 2 \times 10^5
 - a_i is 0 or 1.

-----Input-----
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N

-----Output-----
If a good set of choices does not exist, print -1.
If a good set of choices exists, print one such set of choices in the following format:
M
b_1 b_2 ... b_M

where M denotes the number of boxes that will contain a ball, and b_1,\ b_2,\ ...,\ b_M are the integers written on these boxes, in any order.

-----Sample Input-----
3
1 0 0

-----Sample Output-----
1
1

Consider putting a ball only in the box with 1 written on it.
 - There are three boxes with multiples of 1 written on them: the boxes with 1, 2, and 3. The total number of balls contained in these boxes is 1.
 - There is only one box with a multiple of 2 written on it: the box with 2. The total number of balls contained in these boxes is 0.
 - There is only one box with a multiple of 3 written on it: the box with 3. The total number of balls contained in these boxes is 0.
Thus, the condition is satisfied, so this set of choices is good.

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

n,*a=map(int,open(0).read().split())
b=[0]*(n+1)
for i in range(1,n+1)[::-1]:
 b[i]+=(sum(b[j] for j in range(i,n+1,i))+a[i-1])%2
print(sum(b))
print(*[i for i in range(n+1) if b[i]>0])


I found an interesting problem on https://atcoder.jp/contests/abc134/tasks/abc134_e:
You are given a sequence with N integers: A = \{ A_1, A_2, \cdots, A_N \}.
For each of these N integers, we will choose a color and paint the integer with that color. Here the following condition must be satisfied:
 - If A_i and A_j (i < j) are painted with the same color, A_i < A_j.
Find the minimum number of colors required to satisfy the condition.

-----Constraints-----
 - 1 \leq N \leq 10^5
 - 0 \leq A_i \leq 10^9

-----Input-----
Input is given from Standard Input in the following format:
N
A_1
:
A_N

-----Output-----
Print the minimum number of colors required to satisfy the condition.

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

-----Sample Output-----
2

We can satisfy the condition with two colors by, for example, painting 2 and 3 red and painting 1, 4, and 5 blue.

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

import sys
def input(): return sys.stdin.readline().strip()
def mapint(): return map(int, input().split())
sys.setrecursionlimit(10**9)

N = int(input())
As = [-int(input()) for _ in range(N)]

from bisect import bisect_right
lis = [1]
for a in As:
    if a>=lis[-1]:
        lis.append(a)
    else:
        lis[bisect_right(lis, a)] = a

print(len(lis))


I found an interesting problem on https://atcoder.jp/contests/abc134/tasks/abc134_f:
Let us define the oddness of a permutation p = {p_1,\ p_2,\ ...,\ p_n} of {1,\ 2,\ ...,\ n} as \sum_{i = 1}^n |i - p_i|.
Find the number of permutations of {1,\ 2,\ ...,\ n} of oddness k, modulo 10^9+7.

-----Constraints-----
 - All values in input are integers.
 - 1 \leq n \leq 50
 - 0 \leq k \leq n^2

-----Input-----
Input is given from Standard Input in the following format:
n k

-----Output-----
Print the number of permutations of {1,\ 2,\ ...,\ n} of oddness k, modulo 10^9+7.

-----Sample Input-----
3 2

-----Sample Output-----
2

There are six permutations of {1,\ 2,\ 3}. Among them, two have oddness of 2:  {2,\ 1,\ 3} and {1,\ 3,\ 2}.

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


I found an interesting problem on https://atcoder.jp/contests/abc135/tasks/abc135_a:
We have two distinct integers A and B.
Print the integer K such that |A - K| = |B - K|.
If such an integer does not exist, print IMPOSSIBLE instead.

-----Constraints-----
 - All values in input are integers.
 - 0 \leq A,\ B \leq 10^9
 - A and B are distinct.

-----Input-----
Input is given from Standard Input in the following format:
A B

-----Output-----
Print the integer K satisfying the condition.
If such an integer does not exist, print IMPOSSIBLE instead.

-----Sample Input-----
2 16

-----Sample Output-----
9

|2 - 9| = 7 and |16 - 9| = 7, so 9 satisfies the condition.

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

A, B = map(int, input().split())
if (A + B) % 2 != 0:
  print("IMPOSSIBLE")
else:
  print(int((A+B)/2))


I found an interesting problem on https://atcoder.jp/contests/abc135/tasks/abc135_b:
We have a sequence p = {p_1,\ p_2,\ ...,\ p_N} which is a permutation of {1,\ 2,\ ...,\ N}.
You can perform the following operation at most once: choose integers i and j (1 \leq i < j \leq N), and swap p_i and p_j. Note that you can also choose not to perform it.
Print YES if you can sort p in ascending order in this way, and NO otherwise.

-----Constraints-----
 - All values in input are integers.
 - 2 \leq N \leq 50
 - p is a permutation of {1,\ 2,\ ...,\ N}.

-----Input-----
Input is given from Standard Input in the following format:
N
p_1 p_2 ... p_N

-----Output-----
Print YES if you can sort p in ascending order in the way stated in the problem statement, and NO otherwise.

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

-----Sample Output-----
YES

You can sort p in ascending order by swapping p_1 and p_5.

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

N = int(input())
p = list(map(int,input().split()))

if p == sorted(p):
    print('YES')
else:
    ret = 'NO'
    is_sorted = False
    # 全通りの組み合わせをみて、昇順かどうか調べる
    for i in range(N-1):
        for j in range(i+1, N):
            # p[i]とp[j]より小さければ抜ける
            if p[i] < p[j]:
                continue
            else:
                k = p.copy()
                k[i], k[j] = k[j], k[i]

#             for l in range(N-1):
#                 if k[l+1] < k[l]:
#                     is_sorted = False
#                     break

            if k == sorted(p):
                ret = 'YES'
                is_sorted = True
                break
        if is_sorted:
            break

    print(ret)


I found an interesting problem on https://atcoder.jp/contests/abc135/tasks/abc135_c:
There are N+1 towns. The i-th town is being attacked by A_i monsters.
We have N heroes. The i-th hero can defeat monsters attacking the i-th or (i+1)-th town, for a total of at most B_i monsters.
What is the maximum total number of monsters the heroes can cooperate to defeat?

-----Constraints-----
 - All values in input are integers.
 - 1 \leq N \leq 10^5
 - 1 \leq A_i \leq 10^9
 - 1 \leq B_i \leq 10^9

-----Input-----
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_{N+1}
B_1 B_2 ... B_N

-----Output-----
Print the maximum total number of monsters the heroes can defeat.

-----Sample Input-----
2
3 5 2
4 5

-----Sample Output-----
9

If the heroes choose the monsters to defeat as follows, they can defeat nine monsters in total, which is the maximum result.
 - The first hero defeats two monsters attacking the first town and two monsters attacking the second town.
 - The second hero defeats three monsters attacking the second town and two monsters attacking the third town.

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

import bisect, collections, copy, heapq, itertools, math, string, sys
input = lambda: sys.stdin.readline().rstrip()
sys.setrecursionlimit(10**7)
INF = float('inf')
def I(): return int(input())
def F(): return float(input())
def SS(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LSS(): return input().split()

def resolve():
    N = I()
    A = LI()
    B = LI()

    ans = 0
    for i in range(N):
        ans += min(A[i], B[i])
        B[i] -= min(A[i], B[i])
        ans += min(A[i+1], B[i])
        A[i+1] -= min(A[i+1], B[i])

    print(ans)

def __starting_point():
    resolve()

__starting_point()


I found an interesting problem on https://atcoder.jp/contests/abc135/tasks/abc135_d:
Given is a string S. Each character in S is either a digit (0, ..., 9) or ?.
Among the integers obtained by replacing each occurrence of ? with a digit, how many have a remainder of 5 when divided by 13? An integer may begin with 0.
Since the answer can be enormous, print the count modulo 10^9+7.

-----Constraints-----
 - S is a string consisting of digits (0, ..., 9) and ?.
 - 1 \leq |S| \leq 10^5

-----Input-----
Input is given from Standard Input in the following format:
S

-----Output-----
Print the number of integers satisfying the condition, modulo 10^9+7.

-----Sample Input-----
??2??5

-----Sample Output-----
768

For example, 482305, 002865, and 972665 satisfy the condition.

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

# -*- coding: utf-8 -*-

R10 = list(range(10))
R13 = list(range(13))

S = input()
R = [[(M-N)*4 % 13 for N in R10] for M in R13]
AM = 10**9+7

MOD =[1]+[0]*12

for D in S:
    if D == '?':
        MOD = [sum([MOD[N] for N in M])%AM for M in R]
    else:
        C = int(D)
        MOD = [MOD[M[C]] for M in R]
    #end if
#end for

print((MOD[5]))


I found an interesting problem on https://atcoder.jp/contests/abc135/tasks/abc135_e:
Jumbo Takahashi will play golf on an infinite two-dimensional grid.
The ball is initially at the origin (0, 0), and the goal is a grid point (a point with integer coordinates) (X, Y). In one stroke, Jumbo Takahashi can perform the following operation:
 - Choose a grid point whose Manhattan distance from the current position of the ball is K, and send the ball to that point.
The game is finished when the ball reaches the goal, and the score will be the number of strokes so far. Jumbo Takahashi wants to finish the game with the lowest score possible.
Determine if the game can be finished. If the answer is yes, find one way to bring the ball to the goal with the lowest score possible.
What is Manhattan distance?
The Manhattan distance between two points (x_1, y_1) and (x_2, y_2) is defined as |x_1-x_2|+|y_1-y_2|.

-----Constraints-----
 - All values in input are integers.
 - 1 \leq K \leq 10^9
 - -10^5 \leq X, Y \leq 10^5
 - (X, Y) \neq (0, 0)

-----Input-----
Input is given from Standard Input in the following format:
K
X Y

-----Output-----
If the game cannot be finished, print -1.
If the game can be finished, print one way to bring the ball to the destination with the lowest score possible, in the following format:
s
x_1 y_1
x_2 y_2
.
.
.
x_s y_s

Here, s is the lowest score possible, and (x_i, y_i) is the position of the ball just after the i-th stroke.

-----Sample Input-----
11
-1 2

-----Sample Output-----
3
7 4
2 10
-1 2

 - The Manhattan distance between (0, 0) and (7, 4) is |0-7|+|0-4|=11.
 - The Manhattan distance between (7, 4) and (2, 10) is |7-2|+|4-10|=11.
 - The Manhattan distance between (2, 10) and (-1, 2) is |2-(-1)|+|10-2|=11.
Thus, this play is valid.
Also, there is no way to finish the game with less than three strokes.

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

k = int(input())
x, y = list(map(int, input().split()))
ans = []
if k % 2 == 0:
    if (x + y) % 2 == 1:
        print((-1))
        return
x_reverse = False
y_reverse = False
if x < 0:
    x *= -1
    x_reverse = True
if y < 0:
    y *= -1
    y_reverse = True

def app(a, b):
    nonlocal ans
    if x_reverse:
        a *= -1
    if y_reverse:
        b *= -1

    ans.append((a, b))

nowx = 0
nowy = 0

while abs(x - nowx) + abs(y - nowy) >= 2 * k:
    if abs(x - nowx) > k:
        nowx += k
    else:
        nowy += k
    app(nowx, nowy)

def ok():
    app(x, y)
    print((len(ans)))
    for a, b in ans:
        print((a, b))
    return

rest = abs(x - nowx) + abs(y - nowy)
if rest == k:
    ok()

if rest % 2 == 0:
    delta = 2 * k - rest
    assert delta % 2 == 0
    if abs(x - nowx) < abs(y - nowy):
        temp = abs(x - nowx) + delta // 2
        nowx += temp
        nowy += k - temp
    else:
        temp = abs(y - nowy) + delta // 2
        nowy += temp
        nowx += k - temp
    app(nowx, nowy)
    ok()

# 残りが奇数のときは、条件から一旦ゴールをすぎる方向に移動すれば、
# 残りの距離の偶奇が変わる。

if abs(x - nowx) < abs(y - nowy):
    nowx += k
    app(nowx, nowy)
else:
    nowy += k
    app(nowx, nowy)

x_delta = x - nowx
x_pm = x_delta // abs(x_delta)
y_delta = y - nowy
y_pm = y_delta // abs(y_delta)
if abs(x_delta) < abs(y_delta):
    delta = 2 * k - (abs(x_delta) + abs(y_delta))
    temp = abs(x - nowx) + delta // 2
    nowx += x_pm * temp
    nowy += y_pm * (k - temp)
    app(nowx, nowy)
    ok()
else:
    delta = 2 * k - (abs(x_delta) + abs(y_delta))
    temp = abs(y - nowy) + delta // 2
    nowy += y_pm * temp
    nowx += x_pm * (k - temp)
    app(nowx, nowy)
    ok()


I found an interesting problem on https://atcoder.jp/contests/abc135/tasks/abc135_f:
Given are two strings s and t consisting of lowercase English letters. Determine if the number of non-negative integers i satisfying the following condition is finite, and find the maximum value of such i if the number is finite.
 - There exists a non-negative integer j such that the concatenation of i copies of t is a substring of the concatenation of j copies of s.

-----Notes-----
 - A string a is a substring of another string b if and only if there exists an integer x (0 \leq x \leq |b| - |a|) such that, for any y (1 \leq y \leq |a|), a_y = b_{x+y} holds.
 - We assume that the concatenation of zero copies of any string is the empty string. From the definition above, the empty string is a substring of any string. Thus, for any two strings s and t, i = 0 satisfies the condition in the problem statement.

-----Constraints-----
 - 1 \leq |s| \leq 5 \times 10^5
 - 1 \leq |t| \leq 5 \times 10^5
 - s and t consist of lowercase English letters.

-----Input-----
Input is given from Standard Input in the following format:
s
t

-----Output-----
If the number of non-negative integers i satisfying the following condition is finite, print the maximum value of such i; if the number is infinite, print -1.

-----Sample Input-----
abcabab
ab

-----Sample Output-----
3

The concatenation of three copies of t, ababab, is a substring of the concatenation of two copies of s, abcabababcabab, so i = 3 satisfies the condition.
On the other hand, the concatenation of four copies of t, abababab, is not a substring of the concatenation of any number of copies of s, so i = 4 does not satisfy the condition.
Similarly, any integer greater than 4 does not satisfy the condition, either. Thus, the number of non-negative integers i satisfying the condition is finite, and the maximum value of such i is 3.

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

def z_alg(S):
    N = len(S)
    Z = [0] * N
    Z[0] = N
    i, j = 1, 0
    while i < N:
        while i + j < N and S[j] == S[i + j]:
            j += 1
        Z[i] = j
        if j == 0:
            i += 1
            continue
        k = 1
        while i + k < N and k + Z[k] < j:
            Z[i + k] = Z[k]
            k += 1
        i += k
        j -= k
    return Z

def main():
    S = input()
    T = input()
    REP_S = ''
    target_len = len(S) + len(T) - 1
    while len(REP_S) < target_len:
        REP_S += S

    # Z-algorithmでREP_S中に含まれるTの場所を調べる
    T_REP_S = T + REP_S
    z = z_alg(T_REP_S)
    location_list = list()
    for i in range(len(S)):
        if z[i + len(T)] >= len(T):
            location_list.append(i)

    # Tがなければ0を出力して終了
    if len(location_list) == 0:
        print(0)
        return

    # グラフを作り、最長パスに含まれるノード数が答え（ループがあったら-1）
    node_flag_list = [0] * len(S)
    for n in location_list:
        node_flag_list[n] = 1
    depth_list = [-1] * len(S)
    for n in location_list:
        if depth_list[n] >= 0:
            continue
        cur_node = n
        d, has_loop = 0, False
        while node_flag_list[cur_node] == 1:
            depth_list[cur_node] = d
            d += 1
            cur_node = (cur_node + len(T)) % len(S)
            if cur_node == n:
                has_loop = True
                break
        if has_loop:
            print(-1)
            return

    print(max(depth_list) + 1)

def __starting_point():
    main()
__starting_point()


I found an interesting problem on https://atcoder.jp/contests/abc136/tasks/abc136_a:
We have two bottles for holding water.
Bottle 1 can hold up to A milliliters of water, and now it contains B milliliters of water.
Bottle 2 contains C milliliters of water.
We will transfer water from Bottle 2 to Bottle 1 as much as possible.
How much amount of water will remain in Bottle 2?

-----Constraints-----
 - All values in input are integers.
 - 1 \leq B \leq A \leq 20
 - 1 \leq C \leq 20

-----Input-----
Input is given from Standard Input in the following format:
A B C

-----Output-----
Print the integer representing the amount of water, in milliliters, that will remain in Bottle 2.

-----Sample Input-----
6 4 3

-----Sample Output-----
1

We will transfer two milliliters of water from Bottle 2 to Bottle 1, and one milliliter of water will remain in Bottle 2.

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

A, B, C = map(int, input().split())

print(max(0, C-(A-B)))


I found an interesting problem on https://atcoder.jp/contests/abc136/tasks/abc136_b:
Given is an integer N. Find the number of positive integers less than or equal to N that have an odd number of digits (in base ten without leading zeros).

-----Constraints-----
 - 1 \leq N \leq 10^5

-----Input-----
Input is given from Standard Input in the following format:
N

-----Output-----
Print the number of positive integers less than or equal to N that have an odd number of digits.

-----Sample Input-----
11

-----Sample Output-----
9

Among the positive integers less than or equal to 11, nine integers have an odd number of digits: 1, 2, \ldots, 9.

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

N = int(input())
count = 0
for i in range(1,N+1):
    if len(str(i)) % 2 != 0:
        count += 1
print(count)


I found an interesting problem on https://atcoder.jp/contests/abc136/tasks/abc136_c:
There are N squares arranged in a row from left to right. The height of the i-th square from the left is H_i.
For each square, you will perform either of the following operations once:
 - Decrease the height of the square by 1.
 - Do nothing.
Determine if it is possible to perform the operations so that the heights of the squares are non-decreasing from left to right.

-----Constraints-----
 - All values in input are integers.
 - 1 \leq N \leq 10^5
 - 1 \leq H_i \leq 10^9

-----Input-----
Input is given from Standard Input in the following format:
N
H_1 H_2 ... H_N

-----Output-----
If it is possible to perform the operations so that the heights of the squares are non-decreasing from left to right, print Yes; otherwise, print No.

-----Sample Input-----
5
1 2 1 1 3

-----Sample Output-----
Yes

You can achieve the objective by decreasing the height of only the second square from the left by 1.

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

from collections import Counter
import math
import statistics
import itertools
# a,b=map(int,input().split())
b=int(input())
# c=[]
# for i in a:
#     c.append(int(i))
# A,B,C= map(int,input().split())
# f = list(map(int,input().split()))
#g = [list(map(lambda x: '{}'.format(x), list(input()))) for _ in range(a)]
# h = []
# for i in range(a):
#     h.append(list(map(int,input().split())))
# a = [[0] for _ in range(H)]#nizigen
# lis=[input() for i in range(a)]

lis = list(map(int,input().split()))
ans=lis[0]
word=0

for i in range(1,b):
    word=lis[i]
    if ans<=word:
        ans=word
        word=0
    elif ans-1 == word:
        word=0
    else:
        print("No")
        return

print("Yes")


I found an interesting problem on https://atcoder.jp/contests/abc136/tasks/abc136_d:
Given is a string S consisting of L and R.
Let N be the length of S. There are N squares arranged from left to right, and the i-th character of S from the left is written on the i-th square from the left.
The character written on the leftmost square is always R, and the character written on the rightmost square is always L.
Initially, one child is standing on each square.
Each child will perform the move below 10^{100} times:
 - Move one square in the direction specified by the character written in the square on which the child is standing. L denotes left, and R denotes right.
Find the number of children standing on each square after the children performed the moves.

-----Constraints-----
 - S is a string of length between 2 and 10^5 (inclusive).
 - Each character of S is L or R.
 - The first and last characters of S are R and L, respectively.

-----Input-----
Input is given from Standard Input in the following format:
S

-----Output-----
Print the number of children standing on each square after the children performed the moves, in order from left to right.

-----Sample Input-----
RRLRL

-----Sample Output-----
0 1 2 1 1

 - After each child performed one move, the number of children standing on each square is 0, 2, 1, 1, 1 from left to right.
 - After each child performed two moves, the number of children standing on each square is 0, 1, 2, 1, 1 from left to right.
 - After each child performed 10^{100} moves, the number of children standing on each square is 0, 1, 2, 1, 1 from left to right.

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

s = input()
v = [0 for i in range(len(s))]
r,l = 0,0
vis = [False for i in range(len(s))]

for i in range(len(s)):
  if vis[i]:
    continue
  vis[i] = True
  if s[i] == 'L':
    x = i-1
    y = i
    r,l = 0,0
    while x >= 0 and s[x] == 'R':
      r += 1
      x -= 1
    while y <= len(s)-1 and s[y] == 'L':
      vis[y] = True
      l += 1
      y += 1
    v[i-1] = l//2+(r-r//2)
    v[i] = (l-l//2)+r//2
print (*v)


I found an interesting problem on https://atcoder.jp/contests/abc136/tasks/abc136_e:
We have a sequence of N integers: A_1, A_2, \cdots, A_N.
You can perform the following operation between 0 and K times (inclusive):
 - Choose two integers i and j such that i \neq j, each between 1 and N (inclusive). Add 1 to A_i and -1 to A_j, possibly producing a negative element.
Compute the maximum possible positive integer that divides every element of A after the operations. Here a positive integer x divides an integer y if and only if there exists an integer z such that y = xz.

-----Constraints-----
 - 2 \leq N \leq 500
 - 1 \leq A_i \leq 10^6
 - 0 \leq K \leq 10^9
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N K
A_1 A_2 \cdots A_{N-1} A_{N}

-----Output-----
Print the maximum possible positive integer that divides every element of A after the operations.

-----Sample Input-----
2 3
8 20

-----Sample Output-----
7

7 will divide every element of A if, for example, we perform the following operation:
 - Choose i = 2, j = 1. A becomes (7, 21).
We cannot reach the situation where 8 or greater integer divides every element of A.

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

import sys
import numpy as np

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

def make_divisors(n): # nの約数を列挙
    divisors = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i:
                divisors.append(n//i)
    divisors.sort(reverse=True)
    return divisors

# 全ての合計の約数が答えの候補、上から可能かどうか見ていく
N, K = lr()
A = np.array(lr())
total = A.sum()
D = make_divisors(total) # 降順
for d in D:
    B = A % d
    B.sort()
    inc = d - B
    B_cum = B.cumsum()
    inc_cum = inc.cumsum()
    for i in range(N):
        x = B_cum[i]
        y = inc_cum[N-1] - inc_cum[i]
        if x > K or y > K:
            continue
        if (x+y) // 2 <= K:
            print(d); return


I found an interesting problem on https://atcoder.jp/contests/abc136/tasks/abc136_f:
We have a set S of N points in a two-dimensional plane. The coordinates of the i-th point are (x_i, y_i). The N points have distinct x-coordinates and distinct y-coordinates.
For a non-empty subset T of S, let f(T) be the number of points contained in the smallest rectangle, whose sides are parallel to the coordinate axes, that contains all the points in T. More formally, we define f(T) as follows:
 - f(T) :=  (the number of integers i (1 \leq i \leq N) such that a \leq x_i \leq b and c \leq y_i \leq d, where a, b, c, and d are the minimum x-coordinate, the maximum x-coordinate, the minimum y-coordinate, and the maximum y-coordinate of the points in T)
Find the sum of f(T) over all non-empty subset T of S. Since it can be enormous, print the sum modulo 998244353.

-----Constraints-----
 - 1 \leq N \leq 2 \times 10^5
 - -10^9 \leq x_i, y_i \leq 10^9
 - x_i \neq x_j (i \neq j)
 - y_i \neq y_j (i \neq j)
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N
x_1 y_1
:
x_N y_N

-----Output-----
Print the sum of f(T) over all non-empty subset T of S, modulo 998244353.

-----Sample Input-----
3
-1 3
2 1
3 -2

-----Sample Output-----
13

Let the first, second, and third points be P_1, P_2, and P_3, respectively. S = \{P_1, P_2, P_3\} has seven non-empty subsets, and f has the following values for each of them:
 - f(\{P_1\}) = 1
 - f(\{P_2\}) = 1
 - f(\{P_3\}) = 1
 - f(\{P_1, P_2\}) = 2
 - f(\{P_2, P_3\}) = 2
 - f(\{P_3, P_1\}) = 3
 - f(\{P_1, P_2, P_3\}) = 3
The sum of these is 13.

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

import sys
input = sys.stdin.readline
mod = 998244353

def sub(a, b):
    return (a % mod + mod - b % mod) % mod

def main():
    n, = list(map(int, input().split()))
    t = 1
    dd = [t]
    for _ in range(n):
        t=2*t%mod
        dd.append(t)

    xs, ys = [], []
    for _ in range(n):
        x, y = list(map(int, input().split()))
        xs.append(x)
        ys.append(y)

    ini = sorted(list(range(n)), key=lambda x:xs[x])
    for i, yi in enumerate(sorted(list(range(n)), key=lambda x:ys[x])):
        ys[yi] = i
    nys = [ys[i] for i in ini]

    tree = [0] * (n + 1)
    r = 0
    for i, y in enumerate(nys):
        j = y+1
        while j <= n:
            tree[j] += 1
            j += j & -j

        d = 0
        j = y
        while j > 0:
            d += tree[j]
            j -= j & -j

        c = i - d
        b = (n-1) - y - c
        a = (n-1) - b - c - d
        r = (r + sub(dd[b+c] + dd[c+d] + dd[d+a] + dd[a+b],
                dd[a] + dd[b] + dd[c] + dd[d])) % mod

    print((sub((dd[n] * n) % mod, (r+n)%mod)))
main()


I found an interesting problem on https://atcoder.jp/contests/abc137/tasks/abc137_a:
We have two integers: A and B.
Print the largest number among A + B, A - B, and A \times B.

-----Constraints-----
 - All values in input are integers.
 - -100 \leq A,\ B \leq 100

-----Input-----
Input is given from Standard Input in the following format:
A B

-----Output-----
Print the largest number among A + B, A - B, and A \times B.

-----Sample Input-----
-13 3

-----Sample Output-----
-10

The largest number among A + B = -10, A - B = -16, and A \times B = -39 is -10.

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

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

print((max(a+b,a-b,a*b)))


I found an interesting problem on https://atcoder.jp/contests/abc137/tasks/abc137_b:
There are 2000001 stones placed on a number line. The coordinates of these stones are -1000000, -999999, -999998, \ldots, 999999, 1000000.
Among them, some K consecutive stones are painted black, and the others are painted white.
Additionally, we know that the stone at coordinate X is painted black.
Print all coordinates that potentially contain a stone painted black, in ascending order.

-----Constraints-----
 - 1 \leq K \leq 100
 - 0 \leq X \leq 100
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
K X

-----Output-----
Print all coordinates that potentially contain a stone painted black, in ascending order, with spaces in between.

-----Sample Input-----
3 7

-----Sample Output-----
5 6 7 8 9

We know that there are three stones painted black, and the stone at coordinate 7 is painted black. There are three possible cases:
 - The three stones painted black are placed at coordinates 5, 6, and 7.
 - The three stones painted black are placed at coordinates 6, 7, and 8.
 - The three stones painted black are placed at coordinates 7, 8, and 9.
Thus, five coordinates potentially contain a stone painted black: 5, 6, 7, 8, and 9.

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

k, x = map(int, input().split())

y = []

for i in range((x - (k - 1)), (x + k)):
    if -1000000 < i and i < 1000000:
        y.append(i)
print(' '.join(map(str, y)))


I found an interesting problem on https://atcoder.jp/contests/abc137/tasks/abc137_c:
We will call a string obtained by arranging the characters contained in a string a in some order, an anagram of a.
For example, greenbin is an anagram of beginner. As seen here, when the same character occurs multiple times, that character must be used that number of times.
Given are N strings s_1, s_2, \ldots, s_N. Each of these strings has a length of 10 and consists of lowercase English characters. Additionally, all of these strings are distinct. Find the number of pairs of integers i, j (1 \leq i < j \leq N) such that s_i is an anagram of s_j.

-----Constraints-----
 - 2 \leq N \leq 10^5
 - s_i is a string of length 10.
 - Each character in s_i is a lowercase English letter.
 - s_1, s_2, \ldots, s_N are all distinct.

-----Input-----
Input is given from Standard Input in the following format:
N
s_1
s_2
:
s_N

-----Output-----
Print the number of pairs of integers i, j (1 \leq i < j \leq N) such that s_i is an anagram of s_j.

-----Sample Input-----
3
acornistnt
peanutbomb
constraint

-----Sample Output-----
1

s_1 = acornistnt is an anagram of s_3 = constraint. There are no other pairs i, j such that s_i is an anagram of s_j, so the answer is 1.

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

n = int(input())
s = [list(input()) for i in range(n)]
cnt_dic = {}
sum_cnt = 0

for i in range(n):
    s[i].sort()
    if str(s[i]) in cnt_dic:
        cnt_dic[str(s[i])] = cnt_dic[str(s[i])] + 1
    else:
        cnt_dic[str(s[i])] = 1

for n in cnt_dic.values():
    sum_cnt += int( n * (n-1) / 2)

print(sum_cnt)


I found an interesting problem on https://atcoder.jp/contests/abc137/tasks/abc137_d:
There are N one-off jobs available. If you take the i-th job and complete it, you will earn the reward of B_i after A_i days from the day you do it.
You can take and complete at most one of these jobs in a day.
However, you cannot retake a job that you have already done.
Find the maximum total reward that you can earn no later than M days from today.
You can already start working today.

-----Constraints-----
 - All values in input are integers.
 - 1 \leq N \leq 10^5
 - 1 \leq M \leq 10^5
 - 1 \leq A_i \leq 10^5
 - 1 \leq B_i \leq 10^4

-----Input-----
Input is given from Standard Input in the following format:
N M
A_1 B_1
A_2 B_2
\vdots
A_N B_N

-----Output-----
Print the maximum total reward that you can earn no later than M days from today.

-----Sample Input-----
3 4
4 3
4 1
2 2

-----Sample Output-----
5

You can earn the total reward of 5 by taking the jobs as follows:
 - Take and complete the first job today. You will earn the reward of 3 after four days from today.
 - Take and complete the third job tomorrow. You will earn the reward of 2 after two days from tomorrow, that is, after three days from today.

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

import heapq
N, M = list(map(int, input().split()))

AB = []
for _ in range(N):
    A, B = list(map(int, input().split()))
    AB.append((A, B))
AB = sorted(AB, key=lambda x: x[0])

hq = []
heapq.heapify(hq)  # リストhqのheap化

ans = 0
i = 0
for d in range(1, M+1):
    while i <= N-1 and AB[i][0] <= d:
        heapq.heappush(hq, -AB[i][1])  # heap化されたリストhqに要素xを追加
        i += 1
    if hq:
        ans -= heapq.heappop(hq)  # heap化されたリストhqから最小値を削除＆その最小値を出力
print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc137/tasks/abc137_e:
There is a directed graph with N vertices numbered 1 to N and M edges.
The i-th edge is directed from Vertex A_i to Vertex B_i, and there are C_i coins placed along that edge.
Additionally, there is a button on Vertex N.
We will play a game on this graph.
You start the game on Vertex 1 with zero coins, and head for Vertex N by traversing the edges while collecting coins.
It takes one minute to traverse an edge, and you can collect the coins placed along the edge each time you traverse it.
As usual in games, even if you traverse an edge once and collect the coins, the same number of coins will reappear next time you traverse that edge, which you can collect again.
When you reach Vertex N, you can end the game by pressing the button. (You can also choose to leave Vertex N without pressing the button and continue traveling.)
However, when you end the game, you will be asked to pay T \times P coins, where T is the number of minutes elapsed since the start of the game. If you have less than T \times P coins, you will have to pay all of your coins instead.
Your score will be the number of coins you have after this payment.
Determine if there exists a maximum value of the score that can be obtained. If the answer is yes, find that maximum value.

-----Constraints-----
 - 2 \leq N \leq 2500
 - 1 \leq M \leq 5000
 - 1 \leq A_i, B_i \leq N
 - 1 \leq C_i \leq 10^5
 - 0 \leq P \leq 10^5
 - All values in input are integers.
 - Vertex N can be reached from Vertex 1.

-----Input-----
Input is given from Standard Input in the following format:
N M P
A_1 B_1 C_1
:
A_M B_M C_M

-----Output-----
If there exists a maximum value of the score that can be obtained, print that maximum value; otherwise, print -1.

-----Sample Input-----
3 3 10
1 2 20
2 3 30
1 3 45

-----Sample Output-----
35

There are two ways to travel from Vertex 1 to Vertex 3:
 - Vertex 1 \rightarrow 2 \rightarrow 3: You collect 20 + 30 = 50 coins on the way. After two minutes from the start of the game, you press the button, pay 2 \times 10 = 20 coins, and you...

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

from collections import deque
import math

n,m,p = map(int, input().split())
dist  = []
edge1 = [[] for _ in range(n)]
edge2 = [[] for _ in range(n)]  # rev_edge
for _ in range(m):
    u,v,c = map(int, input().split())
    u -= 1
    v -= 1
    dist.append((u,v,(c-p)*-1))
    edge1[u].append(v)
    edge2[v].append(u)

def dfs(edges, s):
    stack = deque([s])
    used  = {s}
    while stack:
        x = stack.pop()
        for y in edges[x]:
            if y not in used:
                used.add(y)
                stack.append(y)
    return used

def bfs(edges, s):
    queue = deque([s])
    used  = {s}
    while queue:
        x = queue.popleft()
        for y in edges[x]:
            if y in used:
                continue
            used.add(y)
            queue.append(y)
    return used

def bellman(dist):  #負辺があるケースでの、スタートからゴールへの最短路を求めるアルゴ。
    cost = [float("inf")] * n
    cost[0] = 0
    for _ in range(n): #頂点の個数の分だけ回る
        updated = False
        for u,v,c in dist: #辺の個数の分だけ回る
            if cost[u] + c < cost[v]:
                cost[v] = cost[u] + c
                updated = True
    #収束しない場合は負閉路があるため無限に小さくできる。
    if updated==True:
        return -1
    else:
        return max(0, cost[n-1]*-1)

use = bfs(edge1, 0) & bfs(edge2, n-1)
dist2 = [(a,b,c) for a,b,c in dist if a in use and b in use]
print(bellman(dist2))


I found an interesting problem on https://atcoder.jp/contests/abc137/tasks/abc137_f:
Given are a prime number p and a sequence of p integers a_0, \ldots, a_{p-1} consisting of zeros and ones.
Find a polynomial of degree at most p-1, f(x) = b_{p-1} x^{p-1} + b_{p-2} x^{p-2} + \ldots + b_0, satisfying the following conditions:
 - For each i (0 \leq i \leq p-1), b_i is an integer such that 0 \leq b_i \leq p-1.
 - For each i (0 \leq i \leq p-1), f(i) \equiv a_i \pmod p.

-----Constraints-----
 - 2 \leq p \leq 2999
 - p is a prime number.
 - 0 \leq a_i \leq 1

-----Input-----
Input is given from Standard Input in the following format:
p
a_0 a_1 \ldots a_{p-1}

-----Output-----
Print b_0, b_1, \ldots, b_{p-1} of a polynomial f(x) satisfying the conditions, in this order, with spaces in between.
It can be proved that a solution always exists. If multiple solutions exist, any of them will be accepted.

-----Sample Input-----
2
1 0

-----Sample Output-----
1 1

f(x) = x + 1 satisfies the conditions, as follows:
 - f(0) = 0 + 1 = 1 \equiv 1 \pmod 2
 - f(1) = 1 + 1 = 2 \equiv 0 \pmod 2

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

import numpy as np

p = int(input())
aaa = list(map(int, input().split()))

bins = [1]
for i in range(1, p):
    bins.append(bins[-1] * (p - i) * pow(i, p - 2, p) % p)
bins = np.array(bins, dtype=np.int32)

pows_base = -np.arange(p, dtype=np.int32)
pows = np.zeros((p, p), dtype=np.int32)
pows[:, p - 1] = 1
for i in range(p - 2, -1, -1):
    pows[:, i] = pows[:, i + 1] * pows_base % p

coefs = np.zeros(p, dtype=np.int32)

for i, a in enumerate(aaa):
    if a == 0:
        continue

    coefs[0] += 1
    coefs = (coefs - bins * pows[i]) % p

print((*coefs))


I found an interesting problem on https://atcoder.jp/contests/abc138/tasks/abc138_a:
You will be given an integer a and a string s consisting of lowercase English letters as input.
Write a program that prints s if a is not less than 3200 and prints red if a is less than 3200.

-----Constraints-----
 - 2800 \leq a < 5000
 - s is a string of length between 1 and 10 (inclusive).
 - Each character of s is a lowercase English letter.

-----Input-----
Input is given from Standard Input in the following format:
a
s

-----Output-----
If a is not less than 3200, print s; if a is less than 3200, print red.

-----Sample Input-----
3200
pink

-----Sample Output-----
pink

a = 3200 is not less than 3200, so we print s = pink.

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

n=int(input())
s=input()
if n<3200:
  print("red")
else:
  print(s)


I found an interesting problem on https://atcoder.jp/contests/abc138/tasks/abc138_b:
Given is a sequence of N integers A_1, \ldots, A_N.
Find the (multiplicative) inverse of the sum of the inverses of these numbers, \frac{1}{\frac{1}{A_1} + \ldots + \frac{1}{A_N}}.

-----Constraints-----
 - 1 \leq N \leq 100
 - 1 \leq A_i \leq 1000

-----Input-----
Input is given from Standard Input in the following format:
N
A_1 A_2 \ldots A_N

-----Output-----
Print a decimal number (or an integer) representing the value of \frac{1}{\frac{1}{A_1} + \ldots + \frac{1}{A_N}}.
Your output will be judged correct when its absolute or relative error from the judge's output is at most 10^{-5}.

-----Sample Input-----
2
10 30

-----Sample Output-----
7.5

\frac{1}{\frac{1}{10} + \frac{1}{30}} = \frac{1}{\frac{4}{30}} = \frac{30}{4} = 7.5.
Printing 7.50001, 7.49999, and so on will also be accepted.

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

n = int(input())
a = list(map(float,input().split()))
ans = 0
for i in a:
    ans += 1/i
print(1/ans)


I found an interesting problem on https://atcoder.jp/contests/abc138/tasks/abc138_c:
You have a pot and N ingredients. Each ingredient has a real number parameter called value, and the value of the i-th ingredient (1 \leq i \leq N) is v_i.
When you put two ingredients in the pot, they will vanish and result in the formation of a new ingredient. The value of the new ingredient will be (x + y) / 2 where x and y are the values of the ingredients consumed, and you can put this ingredient again in the pot.
After you compose ingredients in this way N-1 times, you will end up with one ingredient. Find the maximum possible value of this ingredient.

-----Constraints-----
 - 2 \leq N \leq 50
 - 1 \leq v_i \leq 1000
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N
v_1 v_2 \ldots v_N

-----Output-----
Print a decimal number (or an integer) representing the maximum possible value of the last ingredient remaining.
Your output will be judged correct when its absolute or relative error from the judge's output is at most 10^{-5}.

-----Sample Input-----
2
3 4

-----Sample Output-----
3.5

If you start with two ingredients, the only choice is to put both of them in the pot. The value of the ingredient resulting from the ingredients of values 3 and 4 is (3 + 4) / 2 = 3.5.
Printing 3.50001, 3.49999, and so on will also be accepted.

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

N=int(input())
v=list(map(int,input().split()))

v.sort()
ans=(v[0]+v[1])/2

for i in range(2,N):
    ans=ans+v[i]
    ans/=2

print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc138/tasks/abc138_d:
Given is a rooted tree with N vertices numbered 1 to N.
The root is Vertex 1, and the i-th edge (1 \leq i \leq N - 1) connects Vertex a_i and b_i.
Each of the vertices has a counter installed. Initially, the counters on all the vertices have the value 0.
Now, the following Q operations will be performed:
 - Operation j (1 \leq j \leq Q): Increment by x_j the counter on every vertex contained in the subtree rooted at Vertex p_j.
Find the value of the counter on each vertex after all operations.

-----Constraints-----
 - 2 \leq N \leq 2 \times 10^5
 - 1 \leq Q \leq 2 \times 10^5
 - 1 \leq a_i < b_i \leq N
 - 1 \leq p_j \leq N
 - 1 \leq x_j \leq 10^4
 - The given graph is a tree.
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N Q
a_1 b_1
:
a_{N-1} b_{N-1}
p_1 x_1
:
p_Q x_Q

-----Output-----
Print the values of the counters on Vertex 1, 2, \ldots, N after all operations, in this order, with spaces in between.

-----Sample Input-----
4 3
1 2
2 3
2 4
2 10
1 100
3 1

-----Sample Output-----
100 110 111 110

The tree in this input is as follows:

Each operation changes the values of the counters on the vertices as follows:
 - Operation 1: Increment by 10 the counter on every vertex contained in the subtree rooted at Vertex 2, that is, Vertex 2, 3, 4. The values of the counters on Vertex 1, 2, 3, 4 are now 0, 10, 10, 10, respectively.
 - Operation 2: Increment by 100 the counter on every vertex contained in the subtree rooted at Vertex 1, that is, Vertex 1, 2, 3, 4. The values of the counters on Vertex 1, 2, 3, 4 are now 100, 110, 110, 110, respectively.
 - Operation 3: Increment by 1 the counter on every vertex contained in the subtree rooted at Vertex 3, that is, Vertex 3. The values of the counters on Vertex 1, 2, 3, 4 are now 100, 110, 111, 110, respectively.

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

import sys
sys.setrecursionlimit(10000000)
def main():
    n,q = list(map(int,input().split()))
    Ki = [[] for i in range(n)]
    for _ in range(n-1):
        a,b = list(map(int,input().split()))
        Ki[a-1]+=[b-1]
        Ki[b-1]+=[a-1]
    ans = [0]*n
    for _ in range(q):
        p,x = list(map(int,input().split()))
        ans[p-1]+=x
    def add(N=0,L=-1):
        for k in Ki[N]:
            if k!=L:
                ans[k]+=ans[N]
                add(k,N)
    add()
    print((' '.join([str(a) for a in ans])))

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://atcoder.jp/contests/abc138/tasks/abc138_e:
Given are two strings s and t consisting of lowercase English letters. Determine if there exists an integer i satisfying the following condition, and find the minimum such i if it exists.
 - Let s' be the concatenation of 10^{100} copies of s. t is a subsequence of the string {s'}_1{s'}_2\ldots{s'}_i (the first i characters in s').

-----Notes-----
 - A subsequence of a string a is a string obtained by deleting zero or more characters from a and concatenating the remaining characters without changing the relative order. For example, the subsequences of contest include net, c, and contest.

-----Constraints-----
 - 1 \leq |s| \leq 10^5
 - 1 \leq |t| \leq 10^5
 - s and t consists of lowercase English letters.

-----Input-----
Input is given from Standard Input in the following format:
s
t

-----Output-----
If there exists an integer i satisfying the following condition, print the minimum such i; otherwise, print -1.

-----Sample Input-----
contest
son

-----Sample Output-----
10

t = son is a subsequence of the string contestcon (the first 10 characters in s' = contestcontestcontest...), so i = 10 satisfies the condition.
On the other hand, t is not a subsequence of the string contestco (the first 9 characters in s'), so i = 9 does not satisfy the condition.
Similarly, any integer less than 9 does not satisfy the condition, either. Thus, the minimum integer i satisfying the condition is 10.

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

s=input()
t=input()
ds={}
for i in range(len(s)):
  if s[i] in ds:
    ds[s[i]].append(i+1)
  else:
    ds[s[i]]=[i+1]
n=len(s)
now=0 # mod n
ans=0
from bisect import bisect_right
for ti in t:
  if ti not in ds:
    print((-1))
    return
  tmp=bisect_right(ds[ti],now)
  if tmp==len(ds[ti]):
    get=n+ds[ti][0]
  else:
    get=ds[ti][tmp]
  ans+=get-now
  #print(now,get)
  now=(get)%n
print(ans)
#print(ds)


I found an interesting problem on https://atcoder.jp/contests/abc138/tasks/abc138_f:
Given are integers L and R. Find the number, modulo 10^9 + 7, of pairs of integers (x, y) (L \leq x \leq y \leq R) such that the remainder when y is divided by x is equal to y \mbox{ XOR } x.What is \mbox{ XOR }?

The XOR of integers A and B, A \mbox{ XOR } B, is defined as follows:

 - When A \mbox{ XOR } B is written in base two, the digit in the 2^k's place (k \geq 0) is 1 if either A or B, but not both, has 1 in the 2^k's place, and 0 otherwise.
For example, 3 \mbox{ XOR } 5 = 6. (In base two: 011 \mbox{ XOR } 101 = 110.)

-----Constraints-----
 - 1 \leq L \leq R \leq 10^{18}

-----Input-----
Input is given from Standard Input in the following format:
L R

-----Output-----
Print the number of pairs of integers (x, y) (L \leq x \leq y \leq R) satisfying the condition, modulo 10^9 + 7.

-----Sample Input-----
2 3

-----Sample Output-----
3

Three pairs satisfy the condition: (2, 2), (2, 3), and (3, 3).

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

L,R = map(int,input().split())

mod = 10**9+7
m = 64 +1
fac = [1]*m
ninv = [1]*m
finv = [1]*m
for i in range(2,m):
    fac[i] = fac[i-1]*i%mod
    ninv[i] = (-(mod//i)*ninv[mod%i])%mod
    finv[i] = finv[i-1]*ninv[i]%mod

def comb(n,k):
    return (fac[n]*finv[k]%mod)*finv[n-k]%mod

def f(N):
    if N==0:return 0
    S = bin(N)[2:]
    L = len(S)
    ret = pow(2,S.count("1")-1,mod)
    for i in range(L):
        if S[i] == "0" : continue
        c = S[:i].count("1")
        j = max(0,L-i-1)
        for k in range(j+1):
            if c+k == 0 : continue
            ret += pow(2,c+k-1,mod)*comb(j,k)
            ret %= mod
    return ret

def g(R,L):
    if L==0 : return 0
    Nr = len(bin(R))-2
    Nl = len(bin(L))-2
    if Nr!=Nl :
        R = int("1"*Nl,2)
        Nr = Nl
    ret = f(int("0"+"1"*(Nr-1),2))

    R = bin(R)[2:]
    L = bin(L)[2:]
    for i in range(Nr):
        if R[i] == "0": continue
        if i==0 : R2 = R
        else: R2 = R[:i] + "0" + "?"*(Nr-i-1)
        for j in range(Nl):
            if L[j] == "0" : continue
            if j==0 : L2 = L
            else: L2 = L[:j] + "0" + "?"*(Nl-j-1)
            tmp = 1
            for r,l in zip(R2,L2):
                if r==l=="?" : tmp *= 3
                if r=="?" and l=="0" : tmp *= 2
                if r=="1" and l=="?" : tmp *= 2
                if r=="0" and l=="1" : tmp *= 0
                tmp %= mod
            ret += tmp
    return ret

print((f(R)-g(R,L-1))%mod)


I found an interesting problem on https://atcoder.jp/contests/abc139/tasks/abc139_a:
You will be given a string S of length 3 representing the weather forecast for three days in the past.
The i-th character (1 \leq i \leq 3) of S represents the forecast for the i-th day. S, C, and R stand for sunny, cloudy, and rainy, respectively.
You will also be given a string T of length 3 representing the actual weather on those three days.
The i-th character (1 \leq i \leq 3) of S represents the actual weather on the i-th day. S, C, and R stand for sunny, cloudy, and rainy, respectively.
Print the number of days for which the forecast was correct.

-----Constraints-----
 - S and T are strings of length 3 each.
 - S and T consist of S, C, and R.

-----Input-----
Input is given from Standard Input in the following format:
S
T

-----Output-----
Print the number of days for which the forecast was correct.

-----Sample Input-----
CSS
CSR

-----Sample Output-----
2

 - For the first day, it was forecast to be cloudy, and it was indeed cloudy.
 - For the second day, it was forecast to be sunny, and it was indeed sunny.
 - For the third day, it was forecast to be sunny, but it was rainy.
Thus, the forecast was correct for two days in this case.

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

S=input()
T=input()
cnt=0
for i in range(3):
	if S[i]==T[i]:
		cnt+=1

print(cnt)


I found an interesting problem on https://atcoder.jp/contests/abc139/tasks/abc139_b:
Takahashi's house has only one socket.
Takahashi wants to extend it with some number of power strips, each with A sockets, into B or more empty sockets.
One power strip with A sockets can extend one empty socket into A empty sockets.
Find the minimum number of power strips required.

-----Constraints-----
 - All values in input are integers.
 - 2 \leq A \leq 20
 - 1 \leq B \leq 20

-----Input-----
Input is given from Standard Input in the following format:
A B

-----Output-----
Print the minimum number of power strips required.

-----Sample Input-----
4 10

-----Sample Output-----
3

3 power strips, each with 4 sockets, extend the socket into 10 empty sockets.

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


I found an interesting problem on https://atcoder.jp/contests/abc139/tasks/abc139_c:
There are N squares arranged in a row from left to right.
The height of the i-th square from the left is H_i.
You will land on a square of your choice, then repeat moving to the adjacent square on the right as long as the height of the next square is not greater than that of the current square.
Find the maximum number of times you can move.

-----Constraints-----
 - All values in input are integers.
 - 1 \leq N \leq 10^5
 - 1 \leq H_i \leq 10^9

-----Input-----
Input is given from Standard Input in the following format:
N
H_1 H_2 ... H_N

-----Output-----
Print the maximum number of times you can move.

-----Sample Input-----
5
10 4 8 7 3

-----Sample Output-----
2

By landing on the third square from the left, you can move to the right twice.

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

#-*-coding:utf-8-*-
import sys
input=sys.stdin.readline

def main():
    steps=[]
    step_data=[]
    step = int(input())
    steps=list(map(int,input().split()))
    count=0

    for idx in range(1,len(steps)):
        if steps[idx-1]>=steps[idx]:
            count+=1
        else:
            step_data.append(count)
            count=0
    step_data.append(count)
    print(max(step_data))

def __starting_point():
    main()
__starting_point()


I found an interesting problem on https://atcoder.jp/contests/abc139/tasks/abc139_d:
For an integer N, we will choose a permutation \{P_1, P_2, ..., P_N\} of \{1, 2, ..., N\}.
Then, for each i=1,2,...,N, let M_i be the remainder when i is divided by P_i.
Find the maximum possible value of M_1 + M_2 + \cdots + M_N.

-----Constraints-----
 - N is an integer satisfying 1 \leq N \leq 10^9.

-----Input-----
Input is given from Standard Input in the following format:
N

-----Output-----
Print the maximum possible value of M_1 + M_2 + \cdots + M_N.

-----Sample Input-----
2

-----Sample Output-----
1

When the permutation \{P_1, P_2\} = \{2, 1\} is chosen, M_1 + M_2 = 1 + 0 = 1.

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


I found an interesting problem on https://atcoder.jp/contests/abc139/tasks/abc139_e:
N players will participate in a tennis tournament. We will call them Player 1, Player 2, \ldots, Player N.
The tournament is round-robin format, and there will be N(N-1)/2 matches in total.
Is it possible to schedule these matches so that all of the following conditions are satisfied? If the answer is yes, also find the minimum number of days required.
 - Each player plays at most one matches in a day.
 - Each player i (1 \leq i \leq N) plays one match against Player A_{i, 1}, A_{i, 2}, \ldots, A_{i, N-1} in this order.

-----Constraints-----
 - 3 \leq N \leq 1000
 - 1 \leq A_{i, j} \leq N
 - A_{i, j} \neq i
 - A_{i, 1}, A_{i, 2}, \ldots, A_{i, N-1} are all different.

-----Input-----
Input is given from Standard Input in the following format:
N
A_{1, 1} A_{1, 2} \ldots A_{1, N-1}
A_{2, 1} A_{2, 2} \ldots A_{2, N-1}
:
A_{N, 1} A_{N, 2} \ldots A_{N, N-1}

-----Output-----
If it is possible to schedule all the matches so that all of the conditions are satisfied, print the minimum number of days required; if it is impossible, print -1.

-----Sample Input-----
3
2 3
1 3
1 2

-----Sample Output-----
3

All the conditions can be satisfied if the matches are scheduled for three days as follows:
 - Day 1: Player 1 vs Player 2
 - Day 2: Player 1 vs Player 3
 - Day 3: Player 2 vs Player 3
This is the minimum number of days required.

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

import sys
from itertools import islice
from collections import deque
read = map(int, sys.stdin.read().split())

N = next(read)
A = [deque()] + [deque(islice(read, N - 1)) for _ in range(N)]
days = 1
available_players = deque(range(1, N + 1))
next_opponent = [0] * (N + 1)
played = set()

while available_players:
    player = available_players.popleft()
    if not A[player]:
        continue

    opponent = A[player].popleft()
    if next_opponent[opponent] == player:
        available_players.append(player)
        available_players.append(opponent)
        next_opponent[player] = 0
        next_opponent[opponent] = 0
        if player in played:
            days += 1
            played = set()
        played.add(player)
        played.add(opponent)
    else:
        next_opponent[player] = opponent

for i in A:
    if len(i) > 0:
        print(-1)
        return
else:
    print(days)


I found an interesting problem on https://atcoder.jp/contests/abc139/tasks/abc139_f:
E869120 is initially standing at the origin (0, 0) in a two-dimensional plane.
He has N engines, which can be used as follows:
 - When E869120 uses the i-th engine, his X- and Y-coordinate change by x_i and y_i, respectively. In other words, if E869120 uses the i-th engine from coordinates (X, Y), he will move to the coordinates (X + x_i, Y + y_i).
 - E869120 can use these engines in any order, but each engine can be used at most once. He may also choose not to use some of the engines.
He wants to go as far as possible from the origin.
Let (X, Y) be his final coordinates. Find the maximum possible value of \sqrt{X^2 + Y^2}, the distance from the origin.

-----Constraints-----
 - 1 \leq N \leq 100
 - -1 \ 000 \ 000 \leq x_i \leq 1 \ 000 \ 000
 - -1 \ 000 \ 000 \leq y_i \leq 1 \ 000 \ 000
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
 : :
x_N y_N

-----Output-----
Print the maximum possible final distance from the origin, as a real value.
Your output is considered correct when the relative or absolute error from the true answer is at most 10^{-10}.

-----Sample Input-----
3
0 10
5 -5
-5 -5

-----Sample Output-----
10.000000000000000000000000000000000000000000000000

The final distance from the origin can be 10 if we use the engines in one of the following three ways:
 - Use Engine 1 to move to (0, 10).
 - Use Engine 2 to move to (5, -5), and then use Engine 3 to move to (0, -10).
 - Use Engine 3 to move to (-5, -5), and then use Engine 2 to move to (0, -10).
The distance cannot be greater than 10, so the maximum possible distance is 10.

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

import itertools
from math import atan2, sqrt

N = int(input())
A = [t for _ in range(N) if (t := tuple(map(int, input().split()))) != (0, 0)]

A.sort(key=lambda x: atan2(x[1], x[0]))

# 向きが同じエンジンは１つにまとめる
Ax, Ay = [], []
for _, v in itertools.groupby(A, key=lambda x: atan2(x[1], x[0])):
    sx, sy = 0, 0
    for vx, vy in v:
        sx += vx
        sy += vy
    Ax.append(sx)
    Ay.append(sy)

Nu = len(Ax)

Ax = [0] + list(itertools.accumulate(Ax * 2))
Ay = [0] + list(itertools.accumulate(Ay * 2))

ans = 0
for i in range(Nu + 1):
    for j in range(i + 1, min(i + Nu + 1, 2 * Nu + 1)):
        ans = max(ans, (Ax[j] - Ax[i]) ** 2 + (Ay[j] - Ay[i]) ** 2)

print((sqrt(ans)))