I found an interesting problem on https://atcoder.jp/contests/arc068/tasks/arc068_d:
Snuke has decided to play with N cards and a deque (that is, a double-ended queue).
Each card shows an integer from 1 through N, and the deque is initially empty.
Snuke will insert the cards at the beginning or the end of the deque one at a time, in order from 1 to N.
Then, he will perform the following action N times: take out the card from the beginning or the end of the deque and eat it.
Afterwards, we will construct an integer sequence by arranging the integers written on the eaten cards, in the order they are eaten. Among the sequences that can be obtained in this way, find the number of the sequences such that the K-th element is 1. Print the answer modulo 10^{9} + 7.

-----Constraints-----
 - 1 ≦ K ≦ N ≦ 2{,}000

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

-----Output-----
Print the answer modulo 10^{9} + 7.

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

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

There is one sequence satisfying the condition: 1,2. One possible way to obtain this sequence is the following:
 - Insert both cards, 1 and 2, at the end of the deque.
 - Eat the card at the beginning of the deque twice.

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

def cmb(n, r, mod):#コンビネーションの高速計算
    if ( r<0 or r>n ):
        return 0
    r = min(r, n-r)
    return g1[n] * g2[r] * g2[n-r] % mod

mod = 10**9+7 #出力の制限
N = 5000
g1 = [1, 1] # 元テーブル
g2 = [1, 1] #逆元テーブル
inverse = [0, 1] #逆元テーブル計算用テーブル

for i in range( 2, N + 1 ):
    g1.append( ( g1[-1] * i ) % mod )
    inverse.append( ( -inverse[mod % i] * (mod//i) ) % mod )
    g2.append( (g2[-1] * inverse[-1]) % mod )

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

if N==1:
    print(1)
elif K==1:
    print(pow(2,N-2,mod))
elif K==N:
    dp=[[0 for i in range(K+1)] for j in range(K)]
    imos=[0]*(K+1)

    dp[0][K]=1
    imos[K]=1

    for i in range(1,K):
        for j in range(K-i,K+1):
            if j==K-i:
                dp[i][j]=(imos[K]-imos[j])%mod
            else:
                dp[i][j]=(dp[i-1][j]+imos[K]-imos[j])%mod
        imos=[dp[i][j] for j in range(K+1)]
        for j in range(1,K+1):
            imos[j]+=imos[j-1]
            imos[j]%=mod
    print(dp[N-1][1])
else:
    dp=[[0 for i in range(K+1)] for j in range(K)]
    imos=[0]*(K+1)

    dp[0][K]=1
    imos[K]=1

    for i in range(1,K):
        for j in range(K-i,K+1):
            if j==K-i:
                dp[i][j]=(imos[K]-imos[j])%mod
            else:
                dp[i][j]=(dp[i-1][j]+imos[K]-imos[j])%mod
        imos=[dp[i][j] for j in range(K+1)]
        for j in range(1,K+1):
            imos[j]+=imos[j-1]
            imos[j]%=mod

    ans=0
    for M in range(N-K+1,N+1):
        id=M-N+K
        ans+=dp[K-1][id]*cmb(M-2,N-K-1,mod)

    ans*=pow(2,N-K-1,mod)
    print(ans%mod)


I found an interesting problem on https://atcoder.jp/contests/arc071/tasks/arc071_d:
How many infinite sequences a_1, a_2, ... consisting of {{1, ... ,n}} satisfy the following conditions?
 - The n-th and subsequent elements are all equal. That is, if n \leq i,j, a_i = a_j.
 - For every integer i, the a_i elements immediately following the i-th element are all equal. That is, if i < j < k\leq i+a_i, a_j = a_k.
Find the count modulo 10^9+7.

-----Constraints-----
 - 1 \leq n \leq 10^6

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

-----Output-----
Print how many sequences satisfy the conditions, modulo 10^9+7.

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

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

The four sequences that satisfy the conditions are:
 - 1, 1, 1, ...
 - 1, 2, 2, ...
 - 2, 1, 1, ...
 - 2, 2, 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/arc072/tasks/arc072_a:
You are given an integer sequence of length N. The i-th term in the sequence is a_i.
In one operation, you can select a term and either increment or decrement it by one.
At least how many operations are necessary to satisfy the following conditions?
 - For every i (1≤i≤n), the sum of the terms from the 1-st through i-th term is not zero.
 - For every i (1≤i≤n-1), the sign of the sum of the terms from the 1-st through i-th term, is different from the sign of the sum of the terms from the 1-st through (i+1)-th term.

-----Constraints-----
 - 2 ≤ n ≤ 10^5
 - |a_i| ≤ 10^9
 - Each a_i is an integer.

-----Input-----
Input is given from Standard Input in the following format:
n
a_1 a_2 ... a_n

-----Output-----
Print the minimum necessary count of operations.

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

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

For example, the given sequence can be transformed into 1, -2, 2, -2 by four operations. The sums of the first one, two, three and four terms are 1, -1, 1 and -1, respectively, which satisfy the conditions.

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

n = int(input())
a = list(map(int, input().split()))
now = a[0]
if now == 0:
  ans = 1
  now = 1
else:
  ans = 0
for i in a[1:]:
  t = now + i
  if now * t >= 0:
    if now >= 0:
      ans += t + 1
      now = -1
    else:
      ans += 1 - t
      now = 1
  else:
    now = t

if a[0] >= 0:
  now = -1
  ans2 = a[0] - now
else:
  now = 1
  ans2 = now - a[0]
for i in a[1:]:
  t = now + i
  if now * t >= 0:
    if now >= 0:
      ans2 += t + 1
      now = -1
    else:
      ans2 += 1 - t
      now = 1
  else:
    now = t
ans = min(ans,ans2)
print(ans)


I found an interesting problem on https://atcoder.jp/contests/arc074/tasks/arc074_c:
There are N squares arranged in a row.
The squares are numbered 1, 2, ..., N, from left to right.
Snuke is painting each square in red, green or blue.
According to his aesthetic sense, the following M conditions must all be satisfied.
The i-th condition is:
 - There are exactly x_i different colors among squares l_i, l_i + 1, ..., r_i.
In how many ways can the squares be painted to satisfy all the conditions?
Find the count modulo 10^9+7.

-----Constraints-----
 - 1 ≤ N ≤ 300
 - 1 ≤ M ≤ 300
 - 1 ≤ l_i ≤ r_i ≤ N
 - 1 ≤ x_i ≤ 3

-----Input-----
Input is given from Standard Input in the following format:
N M
l_1 r_1 x_1
l_2 r_2 x_2
:
l_M r_M x_M

-----Output-----
Print the number of ways to paint the squares to satisfy all the conditions, modulo 10^9+7.

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

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

The six ways are:
 - RGB
 - RBG
 - GRB
 - GBR
 - BRG
 - BGR
where R, G and B correspond to red, green and blue squares, respectively.

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

import sys
input = sys.stdin.readline
import numpy as np
from collections import defaultdict

# 最後に置いたものは赤とする（3倍）
# 青、緑を最後にいつ置いたのかを持ってdp

MOD = 10 ** 9 + 7
N,M = map(int,input().split())
LRX = [[int(x) for x in input().split()] for _ in range(M)]

R_to_LX = defaultdict(list)
for l,r,x in LRX:
    R_to_LX[r].append((l,x))

# 1個目を置いた時点
for n in range(1,N+1):
    if n == 1:
        dp = np.zeros((n,n), dtype = np.int64)
        dp[0,0] = 1
    else:
        prev = dp
        dp = np.zeros((n,n), dtype = np.int64)
        # 同色
        dp[:-1,:-1] = prev
        # 青から赤に
        dp[n-1,:-1] = prev.sum(axis = 0)
        # 緑から赤に
        dp[:-1,n-1] = prev.sum(axis = 1)
    # ルール違反を除外する
    for l,x in R_to_LX[n]:
        if x == 1:
            dp[l:,:] = 0
            dp[:,l:] = 0
        elif x == 2:
            dp[l:,l:] = 0
            dp[:l,:l] = 0
        elif x == 3:
            dp[:l,:] = 0
            dp[:,:l] = 0
    dp %= MOD

answer = dp.sum() * 3 % MOD
print(answer)


I found an interesting problem on https://atcoder.jp/contests/arc074/tasks/arc074_d:
There is a pond with a rectangular shape.
The pond is divided into a grid with H rows and W columns of squares.
We will denote the square at the i-th row from the top and j-th column from the left by (i,\ j).
Some of the squares in the pond contains a lotus leaf floating on the water.
On one of those leaves, S, there is a frog trying to get to another leaf T.
The state of square (i,\ j) is given to you by a character a_{ij}, as follows:
 - . : A square without a leaf.
 - o : A square with a leaf floating on the water.
 - S : A square with the leaf S.
 - T : A square with the leaf T.
The frog will repeatedly perform the following action to get to the leaf T: "jump to a leaf that is in the same row or the same column as the leaf where the frog is currently located."
Snuke is trying to remove some of the leaves, other than S and T, so that the frog cannot get to the leaf T.
Determine whether this objective is achievable. If it is achievable, find the minimum necessary number of leaves to remove.

-----Constraints-----
 - 2 ≤ H, W ≤ 100
 - a_{ij} is ., o, S or T.
 - There is exactly one S among a_{ij}.
 - There is exactly one T among a_{ij}.

-----Input-----
Input is given from Standard Input in the following format:
H W
a_{11} ... a_{1W}
:
a_{H1} ... a_{HW}

-----Output-----
If the objective is achievable, print the minimum necessary number of leaves to remove.
Otherwise, print -1 instead.

-----Sample Input-----
3 3
S.o
.o.
o.T

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

Remove the upper-right and lower-left leaves.

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

# https://tjkendev.github.io/procon-library/python/max_flow/dinic.html
from collections import deque
class Dinic:
	def __init__(self, n):
		self.n = n
		self.g = [[] for i in range(n)]

	def add_edge(self, fr, to, cap):
		forward = [to, cap, None]
		forward[2] = backward = [fr, 0, forward]
		self.g[fr].append(forward)
		self.g[to].append(backward)

	def add_bidirectional_edge(self, v1, v2, cap1, cap2):
		edge1 = [v2, cap1, None]
		edge1[2] = edge2 = [v1, cap2, edge1]
		self.g[v1].append(edge1)
		self.g[v2].append(edge2)

	def bfs(self, s, t):
		self.level = level = [None]*self.n
		deq = deque([s])
		level[s] = 0
		g = self.g
		while deq:
			v = deq.popleft()
			lv = level[v] + 1
			for w, cap, _ in g[v]:
				if cap and level[w] is None:
					level[w] = lv
					deq.append(w)
		return level[t] is not None

	def dfs(self, v, t, f):
		if v == t:
			return f
		level = self.level
		for e in self.it[v]:
			w, cap, rev = e
			if cap and level[v] < level[w]:
				d = self.dfs(w, t, min(f, cap))
				if d:
					e[1] -= d
					rev[1] += d
					return d
		return 0

	def flow(self, s, t):
		flow = 0
		INF = 10**30
		g = self.g
		while self.bfs(s, t):
			*self.it, = map(iter, self.g)
			f = INF
			while f:
				f = self.dfs(s, t, INF)
				flow += f
		return flow

H, W = map(int, input().split())
a = [input() for _ in range(H)]
d = Dinic(H+W+2)
for i in range(H):
	for j in range(W):
		if a[i][j] == "S":
			d.add_edge(H+W, i, 10**5)
			d.add_edge(H+W, H+j, 10**5)
		elif a[i][j] == "T":
			d.add_edge(i, H+W+1, 10**5)
			d.add_edge(H+j, H+W+1, 10**5)
		elif a[i][j] == "o":
			d.add_edge(i, H+j, 1)
			d.add_edge(H+j, i, 1)
ans = d.flow(H+W, H+W+1)
if ans > 10000:
	print(-1)
else:
	print(ans)


I found an interesting problem on https://atcoder.jp/contests/arc077/tasks/arc077_c:
Snuke is buying a lamp.
The light of the lamp can be adjusted to m levels of brightness, represented by integers from 1 through m, by the two buttons on the remote control.
The first button is a "forward" button. When this button is pressed, the brightness level is increased by 1, except when the brightness level is m, in which case the brightness level becomes 1.
The second button is a "favorite" button. When this button is pressed, the brightness level becomes the favorite brightness level x, which is set when the lamp is purchased.
Snuke is thinking of setting the favorite brightness level x so that he can efficiently adjust the brightness.
He is planning to change the brightness n-1 times. In the i-th change, the brightness level is changed from a_i to a_{i+1}. The initial brightness level is a_1.
Find the number of times Snuke needs to press the buttons when x is set to minimize this number.

-----Constraints-----
 - 2 \leq n,m \leq 10^5
 - 1 \leq a_i\leq m
 - a_i \neq a_{i+1}
 - n, m and a_i are integers.

-----Input-----
Input is given from Standard Input in the following format:
n m
a_1 a_2 … a_n

-----Output-----
Print the minimum number of times Snuke needs to press the buttons.

-----Sample Input-----
4 6
1 5 1 4

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

When the favorite brightness level is set to 1, 2, 3, 4, 5 and 6, Snuke needs to press the buttons 8, 9, 7, 5, 6 and 9 times, respectively.
Thus, Snuke should set the favorite brightness level to 4.
In this case, the brightness is adjusted as follows:
 - In the first change, press the favorite button once, then press the forward button once.
 - In the second change, press the forward button twice.
 - In the third change, press the favorite button once.

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

n, m = list(map(int, input().split()))
a = [int(x) for x in input().split()]
ps = [0]*(m+2)  # 0,1,2,...,m,m+1

for i in range(n-1):
    if a[i] < a[i+1]:
        ps[a[i]+1] += 1
        ps[a[i+1]] -= 1
    else:
        ps[0] += 1
        ps[a[i+1]] -= 1
        ps[a[i]+1] += 1
        ps[m+1] -= 1

aps = [0]
for x in ps[:-1]:
    aps.append(aps[-1]+x)
aps = aps[2:]

def dist(src, tar):
    return (m+tar-src) % m

freq = [0]*m
for i, x in enumerate(a):
    if i == 0:
        continue
    freq[x-1] += dist(a[i-1], a[i])-1

ans = [0]*m
for i in range(n-1):
    ans[0] += min(dist(a[i], a[i+1]), 1+dist(1, a[i+1]))

for i in range(1, m):
    ans[i] = ans[i-1] + freq[i-1] - aps[i-1]

print((min(ans)))


I found an interesting problem on https://atcoder.jp/contests/arc080/tasks/arc080_d:
There are infinitely many cards, numbered 1, 2, 3, ...
Initially, Cards x_1, x_2, ..., x_N are face up, and the others are face down.
Snuke can perform the following operation repeatedly:
 - Select a prime p greater than or equal to 3. Then, select p consecutive cards and flip all of them.
Snuke's objective is to have all the cards face down.
Find the minimum number of operations required to achieve the objective.

-----Constraints-----
 - 1 ≤ N ≤ 100
 - 1 ≤ x_1 < x_2 < ... < x_N ≤ 10^7

-----Input-----
Input is given from Standard Input in the following format:
N
x_1 x_2 ... x_N

-----Output-----
Print the minimum number of operations required to achieve the objective.

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

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

Below is one way to achieve the objective in two operations:
 - Select p = 5 and flip Cards 1, 2, 3, 4 and 5.
 - Select p = 3 and flip Cards 1, 2 and 3.

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

import itertools
from math import sqrt
def chunk(a):
    i = 0
    res = []
    while i < len(a):
        res.append(a[i])
        while i != len(a) - 1 and a[i + 1] == a[i] + 1:
            i += 1
        res.append(a[i] + 1)
        i += 1
    return res

def augment(g, src, dest):
    o = [None] * len(g)
    q = [(src, src)]
    while q:
        w = q.pop()
        if o[w[0]] is None:
            o[w[0]] = w[1]
            for s in g[w[0]]:
                if o[s] is None:
                    q.append((s, w[0]))
    if not o[dest]:
        return False
    i = dest
    while i != src:
        g[o[i]].discard(i)
        g[i].add(o[i])
        i = o[i]
    return True

def match(a):
    l = {}
    c = 0
    matches = 0
    for i, j in a:
        if i not in l:
            l[i] = c
            c += 1
        if j not in l:
            l[j] = c
            c += 1
    L = {v: k for k, v in l.items()}
    g = [set() for i in range(len(l) + 2)]
    src = len(l)
    dest = src + 1
    for i, j in a:
        g[src].add(l[i])
        g[l[i]].add(l[j])
        g[l[j]].add(dest)
    while augment(g, src, dest):
        matches += 1
    return matches

def prime(n):
    for i in range(2, min(n, int(sqrt(n) + 7))):
        if n % i == 0:
            return False
    return n > 1

def pairs(b):
    c = []
    for i in b:
        for j in b:
            if i % 2 == 0 and j % 2 == 1 and prime(abs(i - j)):
                c.append((i, j))
    return c

n = int(input())
a = list(map(int, input().split()))
b = chunk(a)
r = match(pairs(b))
e = len(list(filter(lambda x: x % 2 == 0, b)))
o = len(b) - e
print(int(r + 2 * ((e - r) // 2 + (o - r) // 2) + 3 * ((e - r) % 2)))


I found an interesting problem on https://atcoder.jp/contests/arc081/tasks/arc081_b:
We have a board with a 2 \times N grid.
Snuke covered the board with N dominoes without overlaps.
Here, a domino can cover a 1 \times 2 or 2 \times 1 square.
Then, Snuke decided to paint these dominoes using three colors: red, cyan and green.
Two dominoes that are adjacent by side should be painted by different colors.
Here, it is not always necessary to use all three colors.
Find the number of such ways to paint the dominoes, modulo 1000000007.
The arrangement of the dominoes is given to you as two strings S_1 and S_2 in the following manner:
 - Each domino is represented by a different English letter (lowercase or uppercase).
 - The j-th character in S_i represents the domino that occupies the square at the i-th row from the top and j-th column from the left.

-----Constraints-----
 - 1 \leq N \leq 52
 - |S_1| = |S_2| = N
 - S_1 and S_2 consist of lowercase and uppercase English letters.
 - S_1 and S_2 represent a valid arrangement of dominoes.

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

-----Output-----
Print the number of such ways to paint the dominoes, modulo 1000000007.

-----Sample Input-----
3
aab
ccb

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

There are six ways as shown below:

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

import sys
from collections import deque
from copy import deepcopy
from bisect import bisect_left, bisect_right, insort_left, insort_right
from heapq import heapify, heappop, heappush
from itertools import product, permutations, combinations, combinations_with_replacement
from functools import reduce
from math import gcd, sin, cos, tan, asin, acos, atan, degrees, radians

sys.setrecursionlimit(10**6)
INF = 10**20
eps = 1.0e-20
MOD = 10**9+7

def lcm(x,y):
    return x*y//gcd(x,y)
def lgcd(l):
    return reduce(gcd,l)
def llcm(l):
    return reduce(lcm,l)
def powmod(n,i,mod=MOD):
    return pow(n,mod-1+i,mod) if i<0 else pow(n,i,mod)
def div2(x):
    return x.bit_length()
def div10(x):
    return len(str(x))-(x==0)
def intput():
    return int(input())
def mint():
    return map(int,input().split())
def lint():
    return list(map(int,input().split()))
def ilint():
    return int(input()), list(map(int,input().split()))
def judge(x, l=['Yes', 'No']):
    print(l[0] if x else l[1])
def lprint(l, sep='\n'):
    for x in l:
        print(x, end=sep)
def ston(c, c0='a'):
    return ord(c)-ord(c0)
def ntos(x, c0='a'):
    return chr(x+ord(c0))
class counter(dict):
    def __init__(self, *args):
        super().__init__(args)
    def add(self,x,d=1):
        self.setdefault(x,0)
        self[x] += d
    def list(self):
        l = []
        for k in self:
            l.extend([k]*self[k])
        return l
class comb():
    def __init__(self, n, mod=None):
        self.l = [1]
        self.n = n
        self.mod = mod
    def get(self,k):
        l,n,mod = self.l, self.n, self.mod
        k = n-k if k>n//2 else k
        while len(l)<=k:
            i = len(l)
            l.append(l[i-1]*(n+1-i)//i if mod==None else (l[i-1]*(n+1-i)*powmod(i,-1,mod))%mod)
        return l[k]
def pf(x,mode='counter'):
    C = counter()
    p = 2
    while x>1:
        k = 0
        while x%p==0:
            x //= p
            k += 1
        if k>0:
            C.add(p,k)
        p = p+2-(p==2) if p*p<x else x
    if mode=='counter':
...


I found an interesting problem on https://atcoder.jp/contests/arc082/tasks/arc082_c:
You are given N points (x_i,y_i) located on a two-dimensional plane.
Consider a subset S of the N points that forms a convex polygon.
Here, we say a set of points S forms a convex polygon when there exists a convex polygon with a positive area that has the same set of vertices as S. All the interior angles of the polygon must be strictly less than 180°.
For example, in the figure above, {A,C,E} and {B,D,E} form convex polygons; {A,C,D,E}, {A,B,C,E}, {A,B,C}, {D,E} and {} do not.
For a given set S, let n be the number of the points among the N points that are inside the convex hull of S (including the boundary and vertices). Then, we will define the score of S as 2^{n-|S|}.
Compute the scores of all possible sets S that form convex polygons, and find the sum of all those scores.
However, since the sum can be extremely large, print the sum modulo 998244353.

-----Constraints-----
 - 1≤N≤200
 - 0≤x_i,y_i<10^4 (1≤i≤N)
 - If i≠j, x_i≠x_j or y_i≠y_j.
 - x_i and y_i are integers.

-----Input-----
The 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 sum of all the scores modulo 998244353.

-----Sample Input-----
4
0 0
0 1
1 0
1 1

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

We have five possible sets as S, four sets that form triangles and one set that forms a square. Each of them has a score of 2^0=1, so the answer is 5.

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

from collections import Counter

def __starting_point():
    N = int(input())
    xy_list = [list(map(int, input().split())) for _ in range(N)]

    modulo_num = 998244353

    duplicate_list = [0] * (N + 1)
    for i in range(N):
        xi, yi = xy_list[i]
        gradient_list = []
        for j in range(N):
            xj, yj = xy_list[j]
            if xi != xj:
                gradient_list.append((yj - yi) / (xj - xi))
            elif yi != yj:
                gradient_list.append(100000)

        counter = Counter(gradient_list)
        for k in list(counter.values()):
            duplicate_list[k + 1] += 1

    ans = pow(2, N, modulo_num)
    ans -= 1
    ans -= N
    for i in range(2, N + 1):
        cnt = duplicate_list[i] // i
        ans -= cnt * (pow(2, i, modulo_num) - i - 1)
    ans = ans % modulo_num
    print(ans)

__starting_point()


I found an interesting problem on https://atcoder.jp/contests/arc083/tasks/arc083_c:
We have a tree with N vertices. Vertex 1 is the root of the tree, and the parent of Vertex i (2 \leq i \leq N) is Vertex P_i.
To each vertex in the tree, Snuke will allocate a color, either black or white, and a non-negative integer weight.
Snuke has a favorite integer sequence, X_1, X_2, ..., X_N, so he wants to allocate colors and weights so that the following condition is satisfied for all v.
 - The total weight of the vertices with the same color as v among the vertices contained in the subtree whose root is v, is X_v.
Here, the subtree whose root is v is the tree consisting of Vertex v and all of its descendants.
Determine whether it is possible to allocate colors and weights in this way.

-----Constraints-----
 - 1 \leq N \leq 1 000
 - 1 \leq P_i \leq i - 1
 - 0 \leq X_i \leq 5 000

-----Inputs-----
Input is given from Standard Input in the following format:
N
P_2 P_3 ... P_N
X_1 X_2 ... X_N

-----Outputs-----
If it is possible to allocate colors and weights to the vertices so that the condition is satisfied, print POSSIBLE; otherwise, print IMPOSSIBLE.

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

-----Sample Output-----
POSSIBLE

For example, the following allocation satisfies the condition:
 - Set the color of Vertex 1 to white and its weight to 2.
 - Set the color of Vertex 2 to black and its weight to 3.
 - Set the color of Vertex 3 to white and its weight to 2.
There are also other possible allocations.

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

import sys
input = sys.stdin.readline
import numpy as np
sys.setrecursionlimit(10**6)

N = int(input())
graph = [[] for _ in range(N+1)] # parent to child
for i,p in enumerate(input().split(),2):
    graph[int(p)].append(i)
X = [None] + [int(x) for x in input().split()]

def dfs(v):
    # None または 白、黒の2つ組を返す
    child = []
    for w in graph[v]:
        c = dfs(w)
        if c is None:
            return None
        child.append(c)
    S = sum(a+b for a,b in child)
    x = X[v]
    dp = np.zeros(x+1, dtype=np.bool) # 2択の繰り返しで作れる和
    dp[0] = 1
    for a,b in child:
        prev = dp
        dp = np.zeros_like(prev)
        if a <= x:
            dp[a:] = prev[:x+1-a]
        if b <= x:
            dp[b:] |= prev[:x+1-b]
    nz = np.nonzero(dp)[0]
    if len(nz) == 0:
        return None
    return x, S - nz[-1]

answer = 'POSSIBLE' if dfs(1) is not None else 'IMPOSSIBLE'
print(answer)


I found an interesting problem on https://atcoder.jp/contests/arc084/tasks/arc084_d:
There are N non-negative integers written on a blackboard. The i-th integer is A_i.
Takahashi can perform the following two kinds of operations any number of times in any order:
 - Select one integer written on the board (let this integer be X). Write 2X on the board, without erasing the selected integer.
 - Select two integers, possibly the same, written on the board (let these integers be X and Y). Write X XOR Y (XOR stands for bitwise xor) on the blackboard, without erasing the selected integers.
How many different integers not exceeding X can be written on the blackboard? We will also count the integers that are initially written on the board.
Since the answer can be extremely large, find the count modulo 998244353.

-----Constraints-----
 - 1 \leq N \leq 6
 - 1 \leq X < 2^{4000}
 - 1 \leq A_i < 2^{4000}(1\leq i\leq N)
 - All input values are integers.
 - X and A_i(1\leq i\leq N) are given in binary notation, with the most significant digit in each of them being 1.

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

-----Output-----
Print the number of different integers not exceeding X that can be written on the blackboard.

-----Sample Input-----
3 111
1111
10111
10010

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

Initially, 15, 23 and 18 are written on the blackboard. Among the integers not exceeding 7, four integers, 0, 3, 5 and 6, can be written.
For example, 6 can be written as follows:
 - Double 15 to write 30.
 - Take XOR of 30 and 18 to write 12.
 - Double 12 to write 24.
 - Take XOR of 30 and 24 to write 6.

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

import random

mod=998244353
N,X=input().split()
N=int(N)
A=[]
for i in range(N):
    A.append(int(input(),2))
A.sort()

a=A[-1]
M=max(len(X)-1,a.bit_length()-1)
data=[0]*(M+1)
n=a.bit_length()-1
for i in range(M-n,-1,-1):
    data[i+n]=a<<i

for i in range(0,N-1):
    a=A[i]
    flag=True
    while flag:
        n=a.bit_length()
        for j in range(n-1,-1,-1):
            a=min(a,a^data[j])
        if a!=0:
            data[a.bit_length()-1]=a
            id=a.bit_length()-1
            while data[id+1]==0:
                data[id+1]=min((data[id]<<1)^a,(data[id]<<1))
                if data[id+1]:
                    id+=1
                else:
                    flag=False
            else:
                a=data[id]<<1
        else:
            break

data2=[0]*(M+1)
for i in range(M+1):
    data2[i]=(data[i]!=0)

for i in range(1,M+1):
    data2[i]+=data2[i-1]

data2=[0]+data2

#print(data)
#print(data2)

x=0
ans=0
n=len(X)-1
for i in range(len(X)):
    if X[i]=="1":
        if x>>(n-i)&1==1:
            if data[n-i]:
                ans+=pow(2,data2[n-i],mod)
                ans%=mod
        else:
            ans+=pow(2,data2[n-i],mod)
            ans%=mod
            if data[n-i]:
                x=x^data[n-i]
            else:
                break
    else:
        if x>>(n-i)&1==1:
            if data[n-i]:
                x=x^data[n-i]
            else:
                break
        else:
            continue
else:
    ans+=1
    ans%=mod
print(ans)


I found an interesting problem on https://atcoder.jp/contests/arc085/tasks/arc085_c:
We have N gemstones labeled 1 through N.
You can perform the following operation any number of times (possibly zero).
 - Select a positive integer x, and smash all the gems labeled with multiples of x.
Then, for each i, if the gem labeled i remains without getting smashed, you will receive a_i yen (the currency of Japan).
However, a_i may be negative, in which case you will be charged money.
By optimally performing the operation, how much yen can you earn?

-----Constraints-----
 - All input values are integers.
 - 1 \leq N \leq 100
 - |a_i| \leq 10^9

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

-----Output-----
Print the maximum amount of money that can be earned.

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

-----Sample Output-----
12

It is optimal to smash Gem 3 and 6.

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

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

sys.setrecursionlimit(1000000)
mod = 1000000007

#A
def A():

    return

#B
def B():

    return

#C
def C():
    def bfs(s,g,n):
        bfs_map = [-1 for i in range(n)]
        bfs_map[s] = 0
        q = deque()
        q.append(s)
        fin = False
        while q:
            x = q.popleft()
            for y in range(n):
                if c[x][y] > 0 and bfs_map[y] < 0:
                    bfs_map[y] = bfs_map[x]+1
                    if y == g:
                        fin = True
                        break
                    q.append(y)
            if fin:
                break

        if bfs_map[g] == -1:
            return [None,0]
        path = [None for i in range(bfs_map[g]+1)]
        m = float("inf")
        path[bfs_map[g]] = g
        y = g
        for i in range(bfs_map[g])[::-1]:
            for x in range(n+1):
                if c[x][y] > 0 and bfs_map[x] == bfs_map[y]-1:
                    path[i] = x
                    if c[x][y] < m:
                        m = c[x][y]
                    y = x
                    break
        return [path,m]

    def ford_fulkerson(s,g,c,n):
        while 1:
            p,m = bfs(s,g,n)
            if not m:break
            for i in range(len(p)-1):
                c[p[i]][p[i+1]] -= m
                c[p[i+1]][p[i]] += m
        return sum(c[g])

    n = I()
    a = LI()
    e = n+2
    ma = 10**9
    c = [[0]*e for i in range(e)]
 ...


I found an interesting problem on https://atcoder.jp/contests/arc086/tasks/arc086_b:
Snuke has an integer sequence, a, of length N. The i-th element of a (1-indexed) is a_{i}.
He can perform the following operation any number of times:
 - Operation: Choose integers x and y between 1 and N (inclusive), and add a_x to a_y.
He would like to perform this operation between 0 and 2N times (inclusive) so that a satisfies the condition below. Show one such sequence of operations.
It can be proved that such a sequence of operations always exists under the constraints in this problem.
 - Condition: a_1 \leq a_2 \leq ...  \leq a_{N}

-----Constraints-----
 - 2 \leq N \leq 50
 - -10^{6} \leq a_i \leq 10^{6}
 - All input values are integers.

-----Input-----
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_{N}

-----Output-----
Let m be the number of operations in your solution. In the first line, print m.
In the i-th of the subsequent m lines, print the numbers x and y chosen in the i-th operation, with a space in between.
The output will be considered correct if m is between 0 and 2N (inclusive) and a satisfies the condition after the m operations.

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

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

 - After the first operation, a = (-2,5,4).
 - After the second operation, a = (-2,5,8), and the condition is now satisfied.

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

import sys

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

in_n = lambda: int(readline())
in_nn = lambda: list(map(int, readline().split()))
in_s = lambda: readline().rstrip().decode('utf-8')
in_nl = lambda: list(map(int, readline().split()))
in_nl2 = lambda H: [in_nl() for _ in range(H)]
in_map = lambda: [s == ord('.') for s in readline() if s != ord('\n')]
in_map2 = lambda H: [in_map() for _ in range(H)]
in_all = lambda: list(map(int, read().split()))

def main():

    N = in_n()
    A = in_nl()

    ans = []
    if abs(min(A)) < abs(max(A)):
        ma = max(A)
        ind = A.index(ma)
        for i in range(N):
            if i != ind:
                ans.append((ind + 1, i + 1))
                A[i] += A[ind]
    else:
        ma = min(A)
        ind = A.index(ma)
        for i in range(N):
            if i != ind:
                ans.append((ind + 1, i + 1))
                A[i] += A[ind]

    if min(A) >= 0:
        for i in range(N - 1):
            if A[i] > A[i + 1]:
                max_a = max(A)
                ind = A.index(max_a)
                A[i + 1] += max_a
                ans.append((ind + 1, i + 2))
    else:
        for i in range(N - 1, 0, -1):
            if A[i - 1] > A[i]:
                min_a = min(A)
                ind = A.index(min_a)
                A[i - 1] += min_a
                ans.append((ind + 1, i))

    print((len(ans)))
    for x, y in ans:
        print((x, y))

    # print(A)

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://atcoder.jp/contests/arc087/tasks/arc087_b:
A robot is put at the origin in a two-dimensional plane.
Initially, the robot is facing in the positive x-axis direction.
This robot will be given an instruction sequence s.
s consists of the following two kinds of letters, and will be executed in order from front to back.
 - F : Move in the current direction by distance 1.
 - T : Turn 90 degrees, either clockwise or counterclockwise.
The objective of the robot is to be at coordinates (x, y) after all the instructions are executed.
Determine whether this objective is achievable.

-----Constraints-----
 - s consists of F and T.
 - 1 \leq |s| \leq 8 000
 - x and y are integers.
 - |x|, |y| \leq |s|

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

-----Output-----
If the objective is achievable, print Yes; if it is not, print No.

-----Sample Input-----
FTFFTFFF
4 2

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

The objective can be achieved by, for example, turning counterclockwise in the first T and turning clockwise in the second T.

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

import sys
s=input()
x,y=map(int,input().split())
s=s+'T'
dp=[[] for i in range(2)]
t=0
buf=0
for j in range(len(s)):
    if s[j]=='T':
        break

for i in range(j,len(s)):
    if s[i]=='F':
        buf+=1
    else:
        if buf!=0:
            dp[t].append(buf)
            buf=0
        t=1-t
#print(s)
#print(dp)
xb=1<<(len(s)+j)
yb=1<<(len(s))

for i in range(len(dp[0])):
    xb=(xb<<dp[0][i])|(xb>>dp[0][i])
if xb & 1<<(len(s)+x)==0:
    print('No')
    return
for i in range(len(dp[1])):
    yb=(yb<<dp[1][i])|(yb>>dp[1][i])

if yb & 1<<(len(s)+y)==0:
    print('No')
    return
print('Yes')


I found an interesting problem on https://atcoder.jp/contests/arc088/tasks/arc088_a:
As a token of his gratitude, Takahashi has decided to give his mother an integer sequence.
The sequence A needs to satisfy the conditions below:
 - A consists of integers between X and Y (inclusive).
 - For each 1\leq i \leq |A|-1, A_{i+1} is a multiple of A_i and strictly greater than A_i.
Find the maximum possible length of the sequence.

-----Constraints-----
 - 1 \leq X \leq Y \leq 10^{18}
 - All input values are integers.

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

-----Output-----
Print the maximum possible length of the sequence.

-----Sample Input-----
3 20

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

The sequence 3,6,18 satisfies the conditions.

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

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

count = 0
while y >= x:
    count += 1
    y = y // 2
print(count)


I found an interesting problem on https://atcoder.jp/contests/arc090/tasks/arc090_d:
For a positive integer n, let us define f(n) as the number of digits in base 10.
You are given an integer S.
Count the number of the pairs of positive integers (l, r) (l \leq r) such that f(l) + f(l + 1) + ... + f(r) = S, and find the count modulo 10^9 + 7.

-----Constraints-----
 - 1 \leq S \leq 10^8

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

-----Output-----
Print the answer.

-----Sample Input-----
1

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

There are nine pairs (l, r) that satisfies the condition: (1, 1), (2, 2), ..., (9, 9).

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

#!/usr/bin/env python3
import math
import random

class Prime:
    seed_primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

    def is_prime(self, n):
        is_prime_common = self.is_prime_common(n)
        if is_prime_common is not None:
            return is_prime_common

        if n < 2000000:
            return self.is_prime_bf(n)
        else:
            return self.is_prime_mr(n)

    def is_prime_common(self, n):
        if n == 1: return False
        if n in Prime.seed_primes: return True
        if any([n % x == 0 for x in self.seed_primes]): return False

    def is_prime_bf(self, n):
        for k in range(2, int(math.sqrt(n)) + 1):
            if n % k == 0:
                return False
        return True

    def is_prime_mr(self, n):
        d = n - 1
        while d % 2 == 0:
            d //= 2

        witnesses = self.get_witnesses(n)
        #witnesses = [random.randint(1, n - 1) for _ in range(100)]

        for w in witnesses:
            t = d
            y = pow(w, t, n)

            while t != n - 1 and y != 1 and y != n - 1:
                y = (y ** 2) % n
                t *= 2

            if y != n - 1 and t % 2 == 0:
                return False

        return True

    def get_witnesses(self, num):
        def _get_range(num):
            if num < 2047:
                return 1
            if num < 1373653:
                return 2
            if num < 25326001:
                return 3
            if num < 3215031751:
                return 4
            if num < 2152302898747:
                return 5
            if num < 3474749660383:
                return 6
            if num < 341550071728321:
                return 7
            if num < 38255123056546413051:
                return 9
            return 12

        return self.seed_primes[:_get_range(num)]

    def gcd(self, a, b):
        if a < b:
            a, b = b, a
        if b == 0:
            return a
        while b:
            a, b = b, a % b
       ...


I found an interesting problem on https://atcoder.jp/contests/arc091/tasks/arc091_a:
There is a grid with infinitely many rows and columns. In this grid, there is a rectangular region with consecutive N rows and M columns, and a card is placed in each square in this region.
The front and back sides of these cards can be distinguished, and initially every card faces up.
We will perform the following operation once for each square contains a card:
 - For each of the following nine squares, flip the card in it if it exists: the target square itself and the eight squares that shares a corner or a side with the target square.
It can be proved that, whether each card faces up or down after all the operations does not depend on the order the operations are performed.
Find the number of cards that face down after all the operations.

-----Constraints-----
 - 1 \leq N,M \leq 10^9
 - All input values are integers.

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

-----Output-----
Print the number of cards that face down after all the operations.

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

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

We will flip every card in any of the four operations. Thus, after all the operations, all cards face up.

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

N, M = list(map(int, input().split()))
if N == 2 or M == 2:
    ans = 0
elif N == 1:
    ans = M - 2
elif M == 1:
    ans = N - 2
else:
    ans = (N - 2) * (M - 2)
if ans < 0:
    ans = 1
print(ans)


I found an interesting problem on https://atcoder.jp/contests/arc091/tasks/arc091_c:
Determine if there exists a sequence obtained by permuting 1,2,...,N that satisfies the following conditions:
 - The length of its longest increasing subsequence is A.
 - The length of its longest decreasing subsequence is B.
If it exists, construct one such sequence.

-----Notes-----
A subsequence of a sequence P is a sequence that can be obtained by extracting some of the elements in P without changing the order.
A longest increasing subsequence of a sequence P is a sequence with the maximum length among the subsequences of P that are monotonically increasing.
Similarly, a longest decreasing subsequence of a sequence P is a sequence with the maximum length among the subsequences of P that are monotonically decreasing.

-----Constraints-----
 - 1 \leq N,A,B \leq 3\times 10^5
 - All input values are integers.

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

-----Output-----
If there are no sequences that satisfy the conditions, print -1.
Otherwise, print N integers. The i-th integer should be the i-th element of the sequence that you constructed.

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

-----Sample Output-----
2 4 1 5 3

One longest increasing subsequence of this sequence is {2,4,5}, and one longest decreasing subsequence of it is {4,3}.

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

import sys
input = sys.stdin.readline
n, a, b = map(int,input().split())
nn = n
bb = b

if (n+b-1)//b <= a <= n+1-b:
    ANS = []
    L = [a]
    b -= 1
    n -= a
    for i in range(b):
        L.append(1)
        n -= 1
    ind = 1
    while n > 0:
        p = min(n, a-1)
        L[ind] += p
        n -= p
        ind += 1

    # print(L)

    i = nn
    for j in range(bb):
        i -= L[j]
        for k in range(L[j]):
            ANS.append(i + k + 1)

    print(*ANS)
else:
    print(-1)


I found an interesting problem on https://atcoder.jp/contests/arc091/tasks/arc091_d:
Takahashi and Aoki are playing a stone-taking game. Initially, there are N piles of stones, and the i-th pile contains A_i stones and has an associated integer K_i.
Starting from Takahashi, Takahashi and Aoki take alternate turns to perform the following operation:
 - Choose a pile. If the i-th pile is selected and there are X stones left in the pile, remove some number of stones between 1 and floor(X/K_i) (inclusive) from the pile.
The player who first becomes unable to perform the operation loses the game. Assuming that both players play optimally, determine the winner of the game.
Here, floor(x) represents the largest integer not greater than x.

-----Constraints-----
 - 1 \leq N \leq 200
 - 1 \leq A_i,K_i \leq 10^9
 - All input values are integers.

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

-----Output-----
If Takahashi will win, print Takahashi; if Aoki will win, print Aoki.

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

-----Sample Output-----
Aoki

Initially, from the first pile at most floor(5/2)=2 stones can be removed at a time, and from the second pile at most floor(3/3)=1 stone can be removed at a time.
 - If Takahashi first takes two stones from the first pile, from the first pile at most floor(3/2)=1 stone can now be removed at a time, and from the second pile at most floor(3/3)=1 stone can be removed at a time.
 - Then, if Aoki takes one stone from the second pile, from the first pile at most floor(3/2)=1 stone can be removed at a time, and from the second pile no more stones can be removed (since floor(2/3)=0).
 - Then, if Takahashi takes one stone from the first pile, from the first pile at most floor(2/2)=1 stone can now be removed at a time, and from the second pile no more stones can be removed.
 - Then, if Aoki takes one stone from the first pile, from the first pile at most floor(1/2)=0 stones can now be removed at a time, and from the second pile no more stones can be removed.
No more operation can be performed, thus Aoki wins. If Takahashi...

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

import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

def grundy(a,k):
    while 1:
        if a<k:return 0
        if a%k==0:return a//k
        once=a//k+1
        seg=a%k
        cnt=(seg+once-1)//once
        a-=cnt*once

win=0
for _ in range(II()):
    a,k=MI()
    win^=grundy(a,k)

if win:print("Takahashi")
else:print("Aoki")


I found an interesting problem on https://atcoder.jp/contests/arc092/tasks/arc092_c:
You have an integer sequence of length N: a_1, a_2, ..., a_N.
You repeatedly perform the following operation until the length of the sequence becomes 1:
 - First, choose an element of the sequence.
 - If that element is at either end of the sequence, delete the element.
 - If that element is not at either end of the sequence, replace the element with the sum of the two elements that are adjacent to it. Then, delete those two elements.
You would like to maximize the final element that remains in the sequence.
Find the maximum possible value of the final element, and the way to achieve it.

-----Constraints-----
 - All input values are integers.
 - 2 \leq N \leq 1000
 - |a_i| \leq 10^9

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

-----Output-----
 - In the first line, print the maximum possible value of the final element in the sequence.
 - In the second line, print the number of operations that you perform.
 - In the (2+i)-th line, if the element chosen in the i-th operation is the x-th element from the left in the sequence at that moment, print x.
 - If there are multiple ways to achieve the maximum value of the final element, any of them may be printed.

-----Sample Input-----
5
1 4 3 7 5

-----Sample Output-----
11
3
1
4
2

The sequence would change as follows:
 - After the first operation: 4, 3, 7, 5
 - After the second operation: 4, 3, 7
 - After the third operation: 11(4+7)

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

n = int(input())
a = list(map(int, input().split()))
mx = max(a)
a[a.index(mx)] = abs(mx)
evn = sum(max(0, i) for i in a[::2])
odd = sum(max(0, i) for i in a[1::2])
if mx < 0:
    print(mx)
else:
    print((max(evn, odd)))
oe = int(evn < odd)
res = []
beg = 0
while beg%2!=oe or a[beg]<0:
    res.append(1)
    beg += 1
end = n-1
while end%2!=oe or a[end]<0:
    res.append(end-beg+1)
    end -= 1
while beg < end:
    if a[end-2] < 0:
        res.append(end-beg-1)
    else:
        res.append(end-beg)
    end -= 2
print((len(res)))
for i in res:
    print(i)


I found an interesting problem on https://atcoder.jp/contests/arc093/tasks/arc093_b:
You are given two integers A and B.
Print a grid where each square is painted white or black that satisfies the following conditions, in the format specified in Output section:
 - Let the size of the grid be h \times w (h vertical, w horizontal). Both h and w are at most 100.
 - The set of the squares painted white is divided into exactly A connected components.
 - The set of the squares painted black is divided into exactly B connected components.
It can be proved that there always exist one or more solutions under the conditions specified in Constraints section.
If there are multiple solutions, any of them may be printed.

-----Notes-----
Two squares painted white, c_1 and c_2, are called connected when the square c_2 can be reached from the square c_1 passing only white squares by repeatedly moving up, down, left or right to an adjacent square.
A set of squares painted white, S, forms a connected component when the following conditions are met:
 - Any two squares in S are connected.
 - No pair of a square painted white that is not included in S and a square included in S is connected.
A connected component of squares painted black is defined similarly.

-----Constraints-----
 - 1 \leq A \leq 500
 - 1 \leq B \leq 500

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

-----Output-----
Output should be in the following format:
 - In the first line, print integers h and w representing the size of the grid you constructed, with a space in between.
 - Then, print h more lines. The i-th (1 \leq i \leq h) of these lines should contain a string s_i as follows:
 - If the square at the i-th row and j-th column (1 \leq j \leq w) in the grid is painted white, the j-th character in s_i should be ..
 - If the square at the i-th row and j-th column (1 \leq j \leq w) in the grid is painted black, the j-th character in s_i should be #.

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

-----Sample Output-----
3 3
##.
..#
#.#

This output corresponds to the grid below:

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


I found an interesting problem on https://atcoder.jp/contests/arc093/tasks/arc093_c:
We have an undirected weighted graph with N vertices and M edges.
The i-th edge in the graph connects Vertex U_i and Vertex V_i, and has a weight of W_i.
Additionally, you are given an integer X.
Find the number of ways to paint each edge in this graph either white or black such that the following condition is met, modulo 10^9 + 7:
 - The graph has a spanning tree that contains both an edge painted white and an edge painted black. Furthermore, among such spanning trees, the one with the smallest weight has a weight of X.
Here, the weight of a spanning tree is the sum of the weights of the edges contained in the spanning tree.

-----Constraints-----
 - 1 \leq N \leq 1 000
 - 1 \leq M \leq 2 000
 - 1 \leq U_i, V_i \leq N (1 \leq i \leq M)
 - 1 \leq W_i \leq 10^9 (1 \leq i \leq M)
 - If i \neq j, then (U_i, V_i) \neq (U_j, V_j) and (U_i, V_i) \neq (V_j, U_j).
 - U_i \neq V_i (1 \leq i \leq M)
 - The given graph is connected.
 - 1 \leq X \leq 10^{12}
 - All input values are integers.

-----Input-----
Input is given from Standard Input in the following format:
N M
X
U_1 V_1 W_1
U_2 V_2 W_2
:
U_M V_M W_M

-----Output-----
Print the answer.

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

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

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

import sys
input = sys.stdin.readline

MOD = 10 ** 9 + 7

N,M = list(map(int,input().split()))
X = int(input())
UVW = [[int(x) for x in input().split()] for _ in range(M)]
UVW.sort(key = lambda x: x[2])

root = list(range(N+1))
def find_root(x):
    y = root[x]
    if x == y:
        return x
    z = find_root(y)
    root[x] = z
    return z

# min spanning tree
tree = [set() for _ in range(N+1)]
min_tree_size = 0
for u,v,w in UVW:
    ru = find_root(u)
    rv = find_root(v)
    if ru == rv:
        continue
    root[ru] = rv
    min_tree_size += w
    tree[u].add((v,w))
    tree[v].add((u,w))

# treeにおける2頂点の間の辺の最大値を求めたい
# LCA。2^n個手前およびそこまでの最大値を覚える

parent = [[0] * 12 for _ in range(N+1)]
max_wt = [[0] * 12 for _ in range(N+1)]
depth = [0] * (N+1)

def dfs(v=1,p=0,dep=0,w=0):
    parent[v][0] = p
    depth[v] = dep
    max_wt[v][0] = w
    for n in range(1,11):
        parent[v][n] = parent[parent[v][n-1]][n-1]
        max_wt[v][n] = max(max_wt[v][n-1], max_wt[parent[v][n-1]][n-1])
    for u,w in tree[v]:
        if u == p:
            continue
        dfs(u,v,dep+1,w)

dfs()

def max_wt_between(x,y):
    # LCA しながら重みの最大値を得る
    wt = 0
    dx,dy = depth[x], depth[y]
    if dx > dy:
        x,y = y,x
        dx,dy = dy,dx
    while dy > dx:
        diff = dy - dx
        step = diff & (-diff)
        n = step.bit_length() - 1
        wt = max(wt, max_wt[y][n])
        y = parent[y][n]
        dy -= step
    if x == y:
        return wt
    step = 1 << 11
    while step:
        n = step.bit_length() - 1
        rx,ry = parent[x][n], parent[y][n]
        if rx != ry:
            wt = max(wt, max_wt[x][n], max_wt[y][n])
            x,y = rx,ry
        step >>= 1
    return max(wt, max_wt[x][0], max_wt[y][0])

# 各edgeに対して、その辺を含む最小の全域木の大きさを求める
min_size = []
for u,v,w in UVW:
    if (v,w) in tree[u]:
        min_size.append(min_tree_size)
    else:
        x = max_wt_between(u,v)
        min_size.append(min_tree_size + w - x)

sm = sum(1 if s < X else 0 for s in min_size)
eq = sum(1 if s == X else 0 for s in...


I found an interesting problem on https://atcoder.jp/contests/arc094/tasks/arc094_a:
You are given three integers A, B and C. Find the minimum number of operations required to make A, B and C all equal by repeatedly performing the following two kinds of operations in any order:
 - Choose two among A, B and C, then increase both by 1.
 - Choose one among A, B and C, then increase it by 2.
It can be proved that we can always make A, B and C all equal by repeatedly performing these operations.

-----Constraints-----
 - 0 \leq A,B,C \leq 50
 - All values in input are integers.

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

-----Output-----
Print the minimum number of operations required to make A, B and C all equal.

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

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

We can make A, B and C all equal by the following operations:
 - Increase A and C by 1. Now, A, B, C are 3, 5, 5, respectively.
 - Increase A by 2. Now, A, B, C are 5, 5, 5, respectively.

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

A, B, C = map(int, input().split())
ans = max(A, B, C)*3 - (A + B + C)
if ans % 2 == 1:
    ans += 3
print(ans // 2)


I found an interesting problem on https://atcoder.jp/contests/arc095/tasks/arc095_c:
There is an H \times W grid (H vertical, W horizontal), where each square contains a lowercase English letter.
Specifically, the letter in the square at the i-th row and j-th column is equal to the j-th character in the string S_i.
Snuke can apply the following operation to this grid any number of times:
 - Choose two different rows and swap them. Or, choose two different columns and swap them.
Snuke wants this grid to be symmetric.
That is, for any 1 \leq i \leq H and 1 \leq j \leq W, the letter in the square at the i-th row and j-th column and the letter in the square at the (H + 1 - i)-th row and (W + 1 - j)-th column should be equal.
Determine if Snuke can achieve this objective.

-----Constraints-----
 - 1 \leq H \leq 12
 - 1 \leq W \leq 12
 - |S_i| = W
 - S_i consists of lowercase English letters.

-----Input-----
Input is given from Standard Input in the following format:
H W
S_1
S_2
:
S_H

-----Output-----
If Snuke can make the grid symmetric, print YES; if he cannot, print NO.

-----Sample Input-----
2 3
arc
rac

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

If the second and third columns from the left are swapped, the grid becomes symmetric, as shown in the image below:

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

def _3():
    from collections import defaultdict

    def can_pair(s1, s2):
        l = []
        for c1, c2 in zip(s1, s2):
            c = sorted([c1, c2])
            if c in l:
                l.remove(c)
            else:
                l.append(c)

        if len(s1) % 2 == 0:
            return len(l) == 0
        else:
            if len(l) == 1:
                if l[0][0] == l[0][1]:
                    return True
            return False

    def pair_graph(s1, s2):
        N = len(s1)
        G = np.zeros([N, N])
        for i in range(N):
            for j in range(i+1, N):
                if s1[i] == s2[j] and s1[j] == s2[i]:
                    G[i, j] = 1
                    G[j, i] = 1
        return G

    import numpy as np
    H, W = list(map(int, input().split(' ')))
    S = []
    d = defaultdict(list)

    for h in range(H):
        s = input()
        S.append(s)
        d[''.join(sorted(S))].append(h)

    already_paired = np.zeros(H)

    Gs = []

    for i in range(H):
        if already_paired[i]:
            continue

        for j in range(i+1, H):
            if already_paired[j]:
                continue

            if can_pair(S[i], S[j]):
                already_paired[i] = 1
                already_paired[j] = 1
                G = pair_graph(S[i], S[j])
                Gs.append(G)
                break

    if already_paired.sum() < H - 1:
        print('NO')
        return

    elif already_paired.sum() == H - 1:
        for i in range(H):
            if already_paired[i] == 0:
                G = pair_graph(S[i], S[i])
                Gs.append(G)
                break

    G = np.array(Gs).sum(axis=0) // len(Gs)

    def is_perfect_matching(G):
        N = len(G)
        if N == 1:
            return True

        for i in range(N):
            for j in range(i+1, N):
                if G[i, j] == 1:
                    l = list(range(N))
                    l.remove(i)
                    l.remove(j)
                    if len(l) == 0:
                       ...


I found an interesting problem on https://atcoder.jp/contests/arc096/tasks/arc096_c:
In "Takahashi-ya", a ramen restaurant, basically they have one menu: "ramen", but N kinds of toppings are also offered. When a customer orders a bowl of ramen, for each kind of topping, he/she can choose whether to put it on top of his/her ramen or not. There is no limit on the number of toppings, and it is allowed to have all kinds of toppings or no topping at all. That is, considering the combination of the toppings, 2^N types of ramen can be ordered.
Akaki entered Takahashi-ya. She is thinking of ordering some bowls of ramen that satisfy both of the following two conditions:
 - Do not order multiple bowls of ramen with the exactly same set of toppings.
 - Each of the N kinds of toppings is on two or more bowls of ramen ordered.
You are given N and a prime number M. Find the number of the sets of bowls of ramen that satisfy these conditions, disregarding order, modulo M. Since she is in extreme hunger, ordering any number of bowls of ramen is fine.

-----Constraints-----
 - 2 \leq N \leq 3000
 - 10^8 \leq M \leq 10^9 + 9
 - N is an integer.
 - M is a prime number.

-----Subscores-----
 - 600 points will be awarded for passing the test set satisfying N ≤ 50.

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

-----Output-----
Print the number of the sets of bowls of ramen that satisfy the conditions, disregarding order, modulo M.

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

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

Let the two kinds of toppings be A and B. Four types of ramen can be ordered: "no toppings", "with A", "with B" and "with A, B". There are two sets of ramen that satisfy the conditions:
 - The following three ramen: "with A", "with B", "with A, B".
 - Four ramen, one for each type.

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

import numpy as np

def solve(n, m):
    def prepare(n, m):
        f = 1
        for i in range(1, n + 1):
            f = f * i % m
        fn = f
        inv = [1] * (n + 1)
        f = pow(f, m - 2, m)
        inv[n] = f
        for i in range(n, 0, -1):
            f = f * i % m
            inv[i - 1] = f
        return fn, inv

    def a_x(a, x, m):
        ret = 1
        yield ret
        for _ in range(x):
            ret = ret * a % m
            yield ret

    fn, inv = prepare(n, m)

    stir2 = np.zeros(n + 2, dtype=np.int64)
    stir2[0] = 1
    upd = np.arange(2, n + 3, dtype=np.int64)

    ex2 = [2]
    for i in range(n):
        ex2.append(ex2[-1] ** 2 % m)

    ans = 0
    si = 1

    for i in range(n+1):
        nCi = fn * inv[i] * inv[n-i] % m
        i_with = np.fromiter(a_x(pow(2, n-i, m), i, m), dtype=np.int64)
        i_on = (stir2[ :i+1] * i_with % m).sum() % m
        ans = (ans + nCi * i_on % m * ex2[n-i] % m * si) % m
        stir2[1 : i+2] = (stir2[1 : i+2] * upd[ :i+1] + stir2[ :i+1]) % m
        si *= -1

    return ans

N, M = list(map(int, input().split()))
print((solve(N, M)))


I found an interesting problem on https://atcoder.jp/contests/arc097/tasks/arc097_c:
There are 2N balls, N white and N black, arranged in a row. The integers from 1 through N are written on the white balls, one on each ball, and they are also written on the black balls, one on each ball.
The integer written on the i-th ball from the left (1 ≤ i ≤ 2N) is a_i, and the color of this ball is represented by a letter c_i.
c_i = W represents the ball is white; c_i = B represents the ball is black.
Takahashi the human wants to achieve the following objective:
 - For every pair of integers (i,j) such that 1 ≤ i < j ≤ N, the white ball with i written on it is to the left of the white ball with j written on it.
 - For every pair of integers (i,j) such that 1 ≤ i < j ≤ N, the black ball with i written on it is to the left of the black ball with j written on it.
In order to achieve this, he can perform the following operation:
 - Swap two adjacent balls.
Find the minimum number of operations required to achieve the objective.

-----Constraints-----
 - 1 ≤ N ≤ 2000
 - 1 ≤ a_i ≤ N
 - c_i = W or c_i = B.
 - If i ≠ j, (a_i,c_i) ≠ (a_j,c_j).

-----Input-----
Input is given from Standard Input in the following format:
N
c_1 a_1
c_2 a_2
:
c_{2N} a_{2N}

-----Output-----
Print the minimum number of operations required to achieve the objective.

-----Sample Input-----
3
B 1
W 2
B 3
W 1
W 3
B 2

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

The objective can be achieved in four operations, for example, as follows:
 - Swap the black 3 and white 1.
 - Swap the white 1 and white 2.
 - Swap the black 3 and white 3.
 - Swap the black 3 and black 2.

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

N = int(input())
X = [i for i in range(N+1)]
Y = [[] for _ in range(N)]
B, W = [], []
ans = 0
for i in range(2 * N):
    c, a = input().split()
    a = int(a) - 1
    if c == "B":
        X = [X[i] + 1 if i <= a else X[i] - 1 for i in range(N+1)]
        B.append(a)
        ans += len([b for b in B if b > a])
    else:
        Y[a] = X[:]
        W.append(a)
        ans += len([b for b in W if b > a])

Z = [0] * (N+1)
for y in Y:
    for i in range(N+1):
        Z[i] += y[i]
    for i in range(1, N+1):
        Z[i] = min(Z[i], Z[i-1])

ans += Z[-1]
print(ans)


I found an interesting problem on https://atcoder.jp/contests/arc098/tasks/arc098_c:
You are given an integer sequence A of length N and an integer K.
You will perform the following operation on this sequence Q times:
 - Choose a contiguous subsequence of length K, then remove the smallest element among the K elements contained in the chosen subsequence (if there are multiple such elements, choose one of them as you like).
Let X and Y be the values of the largest and smallest element removed in the Q operations. You would like X-Y to be as small as possible.
Find the smallest possible value of X-Y when the Q operations are performed optimally.

-----Constraints-----
 - 1 \leq N \leq 2000
 - 1 \leq K \leq N
 - 1 \leq Q \leq N-K+1
 - 1 \leq A_i \leq 10^9
 - All values in input are integers.

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

-----Output-----
Print the smallest possible value of X-Y.

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

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

In the first operation, whichever contiguous subsequence of length 3 we choose, the minimum element in it is 1.
Thus, the first operation removes A_3=1 and now we have A=(4,3,5,2).
In the second operation, it is optimal to choose (A_2,A_3,A_4)=(3,5,2) as the contiguous subsequence of length 3 and remove A_4=2.
In this case, the largest element removed is 2, and the smallest is 1, so their difference is 2-1=1.

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

import sys
def main():
    input = sys.stdin.readline
    N,K,Q=map(int, input().split())
    *A,=map(int, input().split())

    ans=10**10
    from heapq import heappop, heappush
    A.append(-1)
    for y in A:
        if y==-1: break
        c=[]
        t=[]
        for a in A:
            if a >= y:
                heappush(t, a)
            else:
                for _ in range(len(t)-(K-1)):
                    heappush(c, heappop(t))
                t=[]
        if len(c) < Q: continue
        x=[heappop(c) for _ in range(Q)][-1]
        ans = min(ans, x-y)
    print(ans)

def __starting_point():
    main()
__starting_point()


I found an interesting problem on https://atcoder.jp/contests/arc099/tasks/arc099_a:
There is a sequence of length N: A_1, A_2, ..., A_N. Initially, this sequence is a permutation of 1, 2, ..., N.
On this sequence, Snuke can perform the following operation:
 - Choose K consecutive elements in the sequence. Then, replace the value of each chosen element with the minimum value among the chosen elements.
Snuke would like to make all the elements in this sequence equal by repeating the operation above some number of times.
Find the minimum number of operations required.
It can be proved that, Under the constraints of this problem, this objective is always achievable.

-----Constraints-----
 - 2 \leq K \leq N \leq 100000
 - A_1, A_2, ..., A_N is a permutation of 1, 2, ..., N.

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

-----Output-----
Print the minimum number of operations required.

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

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

One optimal strategy is as follows:
 - In the first operation, choose the first, second and third elements. The sequence A becomes 1, 1, 1, 4.
 - In the second operation, choose the second, third and fourth elements. The sequence A becomes 1, 1, 1, 1.

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

N,K = map(int,input().split())
A = list(map(int,input().split()))
ind = A.index(1)
n = ind//(K-1)
if ind%(K-1):
    n += 1
m = (N-1-ind)//(K-1)
if (N-1-ind)%(K-1):
    m += 1
cmin = n+m
for i in range(max(1,ind+K-N),min(ind,K-1)+1):
    n = (ind-i)//(K-1)
    if (ind-i)%(K-1):
        n += 1
    m = (N-ind-K+i)//(K-1)
    if (N-ind-K+i)%(K-1):
        m += 1
    cnt = n+m+1
    cmin = min(cmin,cnt)
print(cmin)


I found an interesting problem on https://atcoder.jp/contests/arc100/tasks/arc100_a:
Snuke has an integer sequence A of length N.
He will freely choose an integer b.
Here, he will get sad if A_i and b+i are far from each other.
More specifically, the sadness of Snuke is calculated as follows:
 - abs(A_1 - (b+1)) + abs(A_2 - (b+2)) + ... + abs(A_N - (b+N))
Here, abs(x) is a function that returns the absolute value of x.
Find the minimum possible sadness of Snuke.

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

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

-----Output-----
Print the minimum possible sadness of Snuke.

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

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

If we choose b=0, the sadness of Snuke would be abs(2-(0+1))+abs(2-(0+2))+abs(3-(0+3))+abs(5-(0+4))+abs(5-(0+5))=2.
Any choice of b does not make the sadness of Snuke less than 2, so the answer is 2.

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

N = int(input())
A = list(map(int,input().split()))
A.insert(0,0)
B = [A[i]-i for i in range(N+1)]
B.pop(0)
B = sorted(B)
if N%2==1:
    b = B[N//2]
    cnt = 0
    for i in range(N):
        cnt += abs(B[i]-b)
else:
    b1 = B[N//2-1]
    cnt1 = 0
    for i in range(N):
        cnt1 += abs(B[i]-b1)
    b2 = B[N//2]
    cnt2 = 0
    for i in range(N):
        cnt2 += abs(B[i]-b2)
    cnt = min(cnt1,cnt2)
print(cnt)


I found an interesting problem on https://atcoder.jp/contests/arc101/tasks/arc101_c:
Let N be an even number.
There is a tree with N vertices.
The vertices are numbered 1, 2, ..., N.
For each i (1 \leq i \leq N - 1), the i-th edge connects Vertex x_i and y_i.
Snuke would like to decorate the tree with ribbons, as follows.
First, he will divide the N vertices into N / 2 pairs.
Here, each vertex must belong to exactly one pair.
Then, for each pair (u, v), put a ribbon through all the edges contained in the shortest path between u and v.
Snuke is trying to divide the vertices into pairs so that the following condition is satisfied: "for every edge, there is at least one ribbon going through it."
How many ways are there to divide the vertices into pairs, satisfying this condition?
Find the count modulo 10^9 + 7.
Here, two ways to divide the vertices into pairs are considered different when there is a pair that is contained in one of the two ways but not in the other.

-----Constraints-----
 - N is an even number.
 - 2 \leq N \leq 5000
 - 1 \leq x_i, y_i \leq N
 - The given graph is a tree.

-----Input-----
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_{N - 1} y_{N - 1}

-----Output-----
Print the number of the ways to divide the vertices into pairs, satisfying the condition, modulo 10^9 + 7.

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

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

There are three possible ways to divide the vertices into pairs, as shown below, and two satisfy the condition: the middle one and the right one.

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

import sys

sys.setrecursionlimit(5001)
MOD = 10 ** 9 + 7

n = int(input())
links = [set() for _ in range(n)]
for line in sys.stdin.readlines():
    x, y = list(map(int, line.split()))
    x -= 1
    y -= 1
    links[x].add(y)
    links[y].add(x)

double_factorial_odd = [0] * (n // 2)
prev = 1
for i in range(n // 2):
    prev = double_factorial_odd[i] = (2 * i + 1) * prev % MOD

def dfs(v, p):
    ret = [0, 1]
    for u in links[v]:
        if u == p:
            continue
        res = dfs(u, v)
        lt, ls = len(ret), len(res)
        mrg = [0] * (lt + ls - 1)
        for i in range(1 - lt % 2, lt, 2):
            c = ret[i]
            for j in range(1 - ls % 2, ls, 2):
                mrg[i + j] = (mrg[i + j] + c * res[j]) % MOD
        ret = mrg

    if len(ret) % 2 == 1:
        ret[0] = -sum(pattern * df % MOD for pattern, df in zip(ret[2::2], double_factorial_odd)) % MOD

    return ret

print((MOD - dfs(0, -1)[0]))


I found an interesting problem on https://atcoder.jp/contests/arc102/tasks/arc102_c:
Takahashi throws N dice, each having K sides with all integers from 1 to K. The dice are NOT pairwise distinguishable.
For each i=2,3,...,2K, find the following value modulo 998244353:
 - The number of combinations of N sides shown by the dice such that the sum of no two different sides is i.
Note that the dice are NOT distinguishable, that is, two combinations are considered different when there exists an integer k such that the number of dice showing k is different in those two.

-----Constraints-----
 - 1 \leq K \leq 2000
 - 2 \leq N \leq 2000
 - K and N are integers.

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

-----Output-----
Print 2K-1 integers. The t-th of them (1\leq t\leq 2K-1) should be the answer for i=t+1.

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

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

 - For i=2, the combinations (1,2,2),(1,2,3),(1,3,3),(2,2,2),(2,2,3),(2,3,3),(3,3,3) satisfy the condition, so the answer is 7.
 - For i=3, the combinations (1,1,1),(1,1,3),(1,3,3),(2,2,2),(2,2,3),(2,3,3),(3,3,3) satisfy the condition, so the answer is 7.
 - For i=4, the combinations (1,1,1),(1,1,2),(2,3,3),(3,3,3) satisfy the condition, so the answer is 4.

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

k,n = map(int,input().split())
mod = 998244353

max_n = 5000
fac, finv, inv = [0]*max_n, [0]*max_n, [0]*max_n

def comInit(max_n):
    fac[0] = fac[1] = 1
    finv[0] = finv[1] = 1
    inv[1] = 1

    for i in range(2,max_n):
      fac[i] = fac[i-1]* i% mod
      inv[i] = mod - inv[mod%i] * (mod // i) % mod
      finv[i] = finv[i-1] * inv[i] % mod

comInit(max_n)

# 二項係数の計算
def com(n,k):
    if(n < k):
        return 0
    if( (n<0) | (k < 0)):
        return 0
    return fac[n] * (finv[k] * finv[n-k] % mod) % mod

ex2 = [1]*1010
for i in range(1,1010):
    ex2[i] = (ex2[i-1]*2)%mod

ans = []
for j in range(2,k+2):
    tmp = 0
    x = (j-1)//2
    for i in range(j//2 + 1):
        comb1 = com(n+k-j,n-i)
        comb2 = (com(x,i) * ex2[i])%mod
        if(j%2==0):
            comb1 += com(n+k-j-1,n-i-1)
            comb1 %= mod
        tmp += comb1*comb2
        tmp %= mod

    ans.append(tmp)

ans2 = ans[:-1]
ans += ans2[::-1]
print('\n'.join(map(str,ans)))


I found an interesting problem on https://atcoder.jp/contests/arc104/tasks/arc104_a:
Takahashi has two integers X and Y.
He computed X + Y and X - Y, and the results were A and B, respectively.
Now he cannot remember what X and Y were. Find X and Y for him.

-----Constraints-----
 - -100 \leq A, B \leq 100
 - For the given integers A and B, there uniquely exist integers X and Y such that X + Y = A and X - Y = B.
 - All values in input are integers.

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

-----Output-----
Print X and Y.

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

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

If X = 0 and Y = 2, they match the situation: 0 + 2 = 2 and 0 - 2 = -2.

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

A, B = map(int, input().split())
print(A-(A-B)//2, (A-B)//2)


I found an interesting problem on https://atcoder.jp/contests/arc104/tasks/arc104_b:
We have a string S of length N consisting of A, T, C, and G.
Strings T_1 and T_2 of the same length are said to be complementary when, for every i (1 \leq i \leq l), the i-th character of T_1 and the i-th character of T_2 are complementary. Here, A and T are complementary to each other, and so are C and G.
Find the number of non-empty contiguous substrings T of S that satisfies the following condition:
 - There exists a string that is a permutation of T and is complementary to T.
Here, we distinguish strings that originate from different positions in S, even if the contents are the same.

-----Constraints-----
 - 1 \leq N \leq 5000
 - S consists of A, T, C, and G.

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

-----Output-----
Print the number of non-empty contiguous substrings T of S that satisfies the condition.

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

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

The following two substrings satisfy the condition:
 - GC (the 2-nd through 3-rd characters) is complementary to CG, which is a permutation of GC.
 - AGCT (the 1-st through 4-th characters) is complementary to TCGA, which is a permutation of AGCT.

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

#region Header
#!/usr/bin/env python3
# from typing import *

import sys
import io
import math
import collections
import decimal
import itertools
from queue import PriorityQueue
import bisect

def input():
    return sys.stdin.readline()[:-1]

sys.setrecursionlimit(1000000)
#endregion

# _INPUT = """10 AAATACCGCG
# """
# sys.stdin = io.StringIO(_INPUT)

# def solve(N: int, S: str) -> int:
def solve(N, S):
    # count_a = [0 for _ in range(N+1)]
    # count_g = [0 for _ in range(N+1)]
    # count_c = [0 for _ in range(N+1)]
    # count_t = [0 for _ in range(N+1)]
    # for i in range(1, N + 1):
    #     count_a[i] = count_a[i-1]
    #     count_g[i] = count_g[i-1]
    #     count_c[i] = count_c[i-1]
    #     count_t[i] = count_t[i-1]
    #     if S[i-1] == 'A':
    #         count_a[i] += 1
    #     elif S[i-1] == 'G':
    #         count_g[i] += 1
    #     elif S[i-1] == 'C':
    #         count_c[i] += 1
    #     elif S[i-1] == 'T':
    #         count_t[i] += 1

    # i文字目からj文字目までの（Aの数）=（Tの数）and（Cの数）=（Gの数）となる (i,j)
    n = 0
    for i in range(-1, N-1):
        count_a = 0
        count_g = 0
        count_c = 0
        count_t = 0
        for j in range(i+1, N):
            if S[j] == 'A':
                count_a += 1
            elif S[j] == 'G':
                count_g += 1
            elif S[j] == 'C':
                count_c += 1
            elif S[j] == 'T':
                count_t += 1
            if (count_a == count_t) and (count_c == count_g):
                n += 1

    return n

def main():
    N, S = input().split()
    N = int(N)
    a = solve(N, S)
    print(a)

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://atcoder.jp/contests/arc104/tasks/arc104_c:
There is a building with 2N floors, numbered 1, 2, \ldots, 2N from bottom to top.
The elevator in this building moved from Floor 1 to Floor 2N just once.
On the way, N persons got on and off the elevator. Each person i (1 \leq i \leq N) got on at Floor A_i and off at Floor B_i. Here, 1 \leq A_i < B_i \leq 2N, and just one person got on or off at each floor.
Additionally, because of their difficult personalities, the following condition was satisfied:
 - Let C_i (= B_i - A_i - 1) be the number of times, while Person i were on the elevator, other persons got on or off. Then, the following holds:
 - If there was a moment when both Person i and Person j were on the elevator, C_i = C_j.
We recorded the sequences A and B, but unfortunately, we have lost some of the records. If the record of A_i or B_i is lost, it will be given to you as -1.
Additionally, the remaining records may be incorrect.
Determine whether there is a pair of A and B that is consistent with the remaining records.

-----Constraints-----
 - 1 \leq N \leq 100
 - A_i = -1 or 1 \leq A_i \leq 2N.
 - B_i = -1 or 1 \leq B_i \leq 2N.
 - All values in input are integers.

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

-----Output-----
If there is a pair of A and B that is consistent with the remaining records, print Yes; otherwise, print No.

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

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

For example, if B_1 = 3, A_2 = 2, and A_3 = 5, all the requirements are met.
In this case, there is a moment when both Person 1 and Person 2 were on the elevator, which is fine since C_1 = C_2 = 1.

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

# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from fractions import Fraction
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations, accumulate
from operator import add, mul, sub, itemgetter, attrgetter

import sys
# sys.setrecursionlimit(10**6)
# readline = sys.stdin.buffer.readline
readline = sys.stdin.readline

INF = 1 << 60

def read_int():
    return int(readline())

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

def read_float():
    return float(readline())

def read_float_n():
    return list(map(float, readline().split()))

def read_str():
    return readline().strip()

def read_str_n():
    return readline().strip().split()

def ep(*args):
    print(*args, file=sys.stderr)

def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.perf_counter()
        ret = f(*args, **kwargs)
        e = time.perf_counter()

        ep(e - s, 'sec')
        return ret

    return wrap

@mt
def slv(N, AB):
    used = set()
    for a, b in AB:
        if a > 0 and b > 0 and a >= b:
            return 'No'
        if a > 0 and a in used:
            return 'No'
        else:
            used.add(a)
        if b > 0 and b in used:
            return 'No'
        else:
            used.add(b)

    AB = [(a-1, b-1) for a, b in AB]

    @lru_cache(maxsize=None)
    def f(s):
        if s == 2*N:
            return True
        for r in range(s+2, 2*N+1, 2):
            l = r - s
            l2 = l // 2
            r2 = s + l2

            used = Counter()
            for a, b in AB:
                if a >= 0 and r2 <= a < r:
                    break
                if b >= 0 and  s <= b < r2:
                    break
                if s <= a < r2 and r2 <= b < r and b - a != l2:
                    break
                if s <= a < r2:
                   ...


I found an interesting problem on https://atcoder.jp/contests/arc104/tasks/arc104_e:
Given is an integer sequence of length N: A_1, A_2, \cdots, A_N.
An integer sequence X, which is also of length N, will be chosen randomly by independently choosing X_i from a uniform distribution on the integers 1, 2, \ldots, A_i for each i (1 \leq i \leq N).
Compute the expected value of the length of the longest increasing subsequence of this sequence X, modulo 1000000007.
More formally, under the constraints of the problem, we can prove that the expected value can be represented as a rational number, that is, an irreducible fraction \frac{P}{Q}, and there uniquely exists an integer R such that R \times Q \equiv P \pmod {1000000007} and 0 \leq R < 1000000007, so print this integer R.

-----Notes-----
A subsequence of a sequence X is a sequence obtained by extracting some of the elements of X and arrange them without changing the order. The longest increasing subsequence of a sequence X is the sequence of the greatest length among the strictly increasing subsequences of X.

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

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

-----Output-----
Print the expected value modulo 1000000007.

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

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

X becomes one of the following, with probability 1/6 for each:
 - X = (1,1,1), for which the length of the longest increasing subsequence is 1;
 - X = (1,1,2), for which the length of the longest increasing subsequence is 2;
 - X = (1,1,3), for which the length of the longest increasing subsequence is 2;
 - X = (1,2,1), for which the length of the longest increasing subsequence is 2;
 - X = (1,2,2), for which the length of the longest increasing subsequence is 2;
 - X = (1,2,3), for which the length of the longest increasing subsequence is 3.
Thus, the expected value of the length of the longest increasing subsequence is (1 + 2 + 2 + 2 + 2 + 3) / 6 \equiv 2 \pmod {1000000007}.

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

from itertools import permutations
from bisect import bisect_left
inf = 10 ** 18
mod = 10 ** 9 + 7

def nCr(n, r, mod=10**9+7):
    if r < 0 or r > n:
        return 0
    res = 1
    div = 1
    r = min(r, n - r)
    for i in range(r):
        res = res * (n - i) % mod
        div = div * (i + 1) % mod
    return res * pow(div, mod-2, mod) % mod

def calc_lis(A):
    L = [A[0]]
    for a in A[1:]:
        if a > L[-1]:
            L.append(a)
        else:
            L[bisect_left(L, a)] = a
    return len(L)

def enum(N, A):
    diff = [A[0]] + [r - l for l, r in zip(A[:-1], A[1:])]
    dp = [[0] * (N + 1) for _ in range(N + 1)]
    dp[0][0] = 1
    for i in range(1, N + 1):
        for j in range(i, N + 1):
            for k in range(i - 1, j + 1):
                dp[i][j] += dp[i - 1][k] * nCr(diff[i - 1], j - k)
                dp[i][j] %= mod
    return dp[N][N]

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

    pair = [(0,)]
    for _ in range(1, N):
        nxt = []
        for p in pair:
            v = p[-1]
            nxt.append(p + (v,))
            nxt.append(p + (v+1,))
        pair = nxt

    ans = 0
    for p in pair:
        sz = p[-1] + 1
        for order in set(permutations(p)):
            arr = [inf] * sz
            for i, a in zip(order, A):
                arr[i] = min(arr[i], a)
            for i in reversed(range(sz - 1)):
                arr[i] = min(arr[i], arr[i + 1])
            ans += enum(sz, arr) * calc_lis(order)
            ans %= mod
    for a in A:
        ans *= pow(a, mod - 2, mod)
        ans %= mod
    print(ans)

main()


I found an interesting problem on https://atcoder.jp/contests/arc105/tasks/arc105_a:
Snuke has four cookies with deliciousness A, B, C, and D. He will choose one or more from those cookies and eat them. Is it possible that the sum of the deliciousness of the eaten cookies is equal to that of the remaining cookies?

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

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

-----Output-----
If it is possible that the sum of the deliciousness of the eaten cookies is equal to that of the remaining cookies, print Yes; otherwise, print No.

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

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

 - If he eats the cookies with deliciousness 1 and 4, the sum of the deliciousness of the eaten cookies will be equal to that of the remaining cookies.

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

import sys

sys.setrecursionlimit(10 ** 6)
INF = float("inf")
MOD = 10 ** 9 + 7

def input():
    return sys.stdin.readline().strip()

def main():
    A, B, C, D = list(map(int, input().split()))
    for i in range(2 ** 4):
        eat = 0
        rest = 0
        for j, x in enumerate([A, B, C, D]):
            if i & (1 << j):
                eat += x
            else:
                rest += x

        if eat == 0:
            continue

        if eat == rest:
            print("Yes")
            return
    else:
        print("No")

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://atcoder.jp/contests/arc105/tasks/arc105_b:
Snuke had N cards numbered 1 through N.
Each card has an integer written on it; written on Card i is a_i.
Snuke did the following procedure:
 - Let X and x be the maximum and minimum values written on Snuke's cards, respectively.
 - If X = x, terminate the procedure. Otherwise, replace each card on which X is written with a card on which X-x is written, then go back to step 1.
Under the constraints in this problem, it can be proved that the procedure will eventually terminate. Find the number written on all of Snuke's cards after the procedure.

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

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

-----Output-----
Print the number written on all of Snuke's cards after the procedure.

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

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

 - At the beginning of the procedure, the numbers written on Snuke's cards are (2,6,6).
 - Since x=2 and X=6, he replaces each card on which 6 is written with a card on which 4 is written.
 - Now, the numbers written on Snuke's cards are (2,4,4).
 - Since x=2 and X=4, he replaces each card on which 4 is written with a card on which 2 is written.
 - Now, the numbers written on Snuke's cards are (2,2,2).
 - Since x=2 and X=2, he terminates the procedure.

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

import math
from functools import reduce
N=int(input())
A = list(map(int, input().split()))
def gcd(*numbers):
    return reduce(math.gcd, numbers)
def gcd_list(numbers):
    return reduce(math.gcd, numbers)
print(gcd_list(A))


I found an interesting problem on https://atcoder.jp/contests/arc105/tasks/arc105_c:
There are N camels numbered 1 through N.
The weight of Camel i is w_i.
You will arrange the camels in a line and make them cross a bridge consisting of M parts.
Before they cross the bridge, you can choose their order in the line - it does not have to be Camel 1, 2, \ldots, N from front to back - and specify the distance between each adjacent pair of camels to be any non-negative real number.
The camels will keep the specified distances between them while crossing the bridge.
The i-th part of the bridge has length l_i and weight capacity v_i.
If the sum of the weights of camels inside a part (excluding the endpoints) exceeds v_i, the bridge will collapse.
Determine whether it is possible to make the camels cross the bridge without it collapsing. If it is possible, find the minimum possible distance between the first and last camels in the line in such a case.
It can be proved that the answer is always an integer, so print an integer.

-----Constraints-----
 - All values in input are integers.
 - 2 \leq N \leq 8
 - 1 \leq M \leq 10^5
 - 1 \leq w_i,l_i,v_i \leq 10^8

-----Input-----
Input is given from Standard Input in the following format:
N M
w_1 w_2 \cdots w_N
l_1 v_1
\vdots
l_M v_M

-----Output-----
If the bridge will unavoidably collapse when the camels cross the bridge, print -1.
Otherwise, print the minimum possible distance between the first and last camels in the line when the camels cross the bridge without it collapsing.

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

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

 - It is possible to make the camels cross the bridge without it collapsing by, for example, arranging them in the order 1, 3, 2 from front to back, and setting the distances between them to be 0, 10.
 - For Part 1 of the bridge, there are moments when only Camel 1 and 3 are inside the part and moments when only Camel 2 is inside the part. In both cases, the sum of the weights of camels does not exceed 4 - the weight capacity of Part 1 - so there is no collapse.
 - For Part 2 of the bridge, there are moments...

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

import itertools
import bisect

N, M = [int(n) for n in input().split()]
W = [int(n) for n in input().split()]
bridges = [[int(n) for n in input().split()] for _ in range(M)] # [length_i, load_limit_i]

# sort by load limit
bridges.sort(key=lambda x: x[1])

limits = [v for l, v in bridges]
len_rm = list(itertools.accumulate([l for l, v in bridges], max)) # running maximum
# len_rm[i]: the maximum length of the bridges whose load limit <= limits[i]

ans = -1
if max(W) <= min(limits):
    # precompute mapping
    # from: (sum of) weights, (w)
    # to: maximum part length (x) whose load limit <= w
    w2x = dict()
    for F in itertools.product([0, 1], repeat=N):
        w = sum([w for w, f in zip(W, F) if f == 1])
        if w in w2x:
            continue
        idx = bisect.bisect_left(limits, w)
        w2x[w] = 0 if idx == 0 else len_rm[idx-1]

    ans = 1000000000 # larger than maximum possible solution (7 x 10^8)
    for W_perm in itertools.permutations(W):
        lengths = [0 for _ in range(N)]
        for i in range(N):
            w_ij = W_perm[i]
            for j in range(i+1, N):
                w_ij += W_perm[j] # w_ij: total weight between i and j (inclusive)
                lengths[j] = max(lengths[j], lengths[i] + w2x[w_ij])

                # skipping trivial edges
                # even without this if-block, we can get AC
                if w_ij > limits[-1]:
                    break

        candidate = lengths[-1]
        ans = min(ans, candidate)

print(ans)


I found an interesting problem on https://atcoder.jp/contests/arc105/tasks/arc105_d:
We have N bags numbered 1 through N and N dishes numbered 1 through N.
Bag i contains a_i coins, and each dish has nothing on it initially.
Taro the first and Jiro the second will play a game against each other.
They will alternately take turns, with Taro the first going first.
In each player's turn, the player can make one of the following two moves:
 - When one or more bags contain coin(s): Choose one bag that contains coin(s) and one dish, then move all coins in the chosen bag onto the chosen dish. (The chosen dish may already have coins on it, or not.)
 - When no bag contains coins: Choose one dish with coin(s) on it, then remove one or more coins from the chosen dish.
The player who first becomes unable to make a move loses. Determine the winner of the game when the two players play optimally.
You are given T test cases. Solve each of them.

-----Constraints-----
 - All values in input are integers.
 - 1 \leq T \leq 10^5
 - 1 \leq N \leq 10^{5}
 - 1 \leq a_i \leq 10^9
 - In one input file, the sum of N does not exceed 2 \times 10^5.

-----Input-----
Input is given from Standard Input in the following format:
T
\mathrm{case}_1
\vdots
\mathrm{case}_T

Each case is in the following format:
N
a_1 a_2 \cdots a_N

-----Output-----
Print T lines. The i-th line should contain First if Taro the first wins in the i-th test case, and Second if Jiro the second wins in the test case.

-----Sample Input-----
3
1
10
2
1 2
21
476523737 103976339 266993 706803678 802362985 892644371 953855359 196462821 817301757 409460796 773943961 488763959 405483423 616934516 710762957 239829390 55474813 818352359 312280585 185800870 255245162

-----Sample Output-----
Second
First
Second

 - In test case 1, Jiro the second wins. Below is one sequence of moves that results in Jiro's win:
 - In Taro the first's turn, he can only choose Bag 1 and move the coins onto Dish 1.
 - In Jiro the second's turn, he can choose Dish 1 and remove all coins from it, making Taro fail to make a move and lose.
 - Note that when there is a bag that...

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

import sys

input = sys.stdin.readline
T = int(input())
for _ in range(T):
    N = int(input())
    A = sorted(list(map(int, input().split())))
    if N % 2 == 1:
        print('Second')
        continue
    else:
        flg = True
        for i in range(N // 2):
            flg = flg & (A.pop() == A.pop())
        if flg:
            print('Second')
        else:
            print('First')


I found an interesting problem on https://atcoder.jp/contests/arc105/tasks/arc105_e:
Given is an undirected graph G consisting of N vertices numbered 1 through N and M edges numbered 1 through M.
Edge i connects Vertex a_i and Vertex b_i bidirectionally.
G is said to be a good graph when both of the conditions below are satisfied. It is guaranteed that G is initially a good graph.
 - Vertex 1 and Vertex N are not connected.
 - There are no self-loops and no multi-edges.
Taro the first and Jiro the second will play a game against each other.
They will alternately take turns, with Taro the first going first.
In each player's turn, the player can do the following operation:
 - Operation: Choose vertices u and v, then add to G an edge connecting u and v bidirectionally.
The player whose addition of an edge results in G being no longer a good graph loses. Determine the winner of the game when the two players play optimally.
You are given T test cases. Solve each of them.

-----Constraints-----
 - All values in input are integers.
 - 1 \leq T \leq 10^5
 - 2 \leq N \leq 10^{5}
 - 0 \leq M \leq \min(N(N-1)/2,10^{5})
 - 1 \leq a_i,b_i \leq N
 - The given graph is a good graph.
 - In one input file, the sum of N and that of M do not exceed 2 \times 10^5.

-----Input-----
Input is given from Standard Input in the following format:
T
\mathrm{case}_1
\vdots
\mathrm{case}_T

Each case is in the following format:
N M
a_1 b_1
\vdots
a_M b_M

-----Output-----
Print T lines. The i-th line should contain First if Taro the first wins in the i-th test case, and Second if Jiro the second wins in the test case.

-----Sample Input-----
3
3 0
6 2
1 2
2 3
15 10
12 14
8 3
10 1
14 6
12 6
1 9
13 1
2 5
3 9
7 2

-----Sample Output-----
First
Second
First

 - In test case 1, Taro the first wins. Below is one sequence of moves that results in Taro's win:
 - In Taro the first's turn, he adds an edge connecting Vertex 1 and 2, after which the graph is still good.
 - Then, whichever two vertices Jiro the second would choose to connect with an edge, the graph would no longer be good.
 - Thus, Taro wins.

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

from collections import Counter as C
class F():
 def __init__(self,n):self.n=n;self.p=list(R(n));self.rank=[1]*n
 def f(self,x):
  if self.p[x]==x:return x
  else:self.p[x]=self.f(self.p[x]);return self.p[x]
 def T(self,x,y):
  p=self.f(x);q=self.f(y)
  if p==q:return None
  if p>q:p,q=q,p
  self.rank[p]+=self.rank[q];self.p[q]=p
I,R=input,range
for _ in R(int(I())):
 n,m=map(int,I().split());U=F(n)
 for i in R(m):a,b=map(int,I().split());U.T(a-1,b-1)
 if n%2:print("First"if(n*(n-1)//2-m)%2else"Second")
 else:
  for i in R(n):U.f(i)
  c=C(U.p);x,y=c[U.f(0)],c[U.f(n-1)];print("First"if x%2!=y%2else"First"if(n*(n-1)//2-x*y-m)%2else"Second")


I found an interesting problem on https://atcoder.jp/contests/arc106/tasks/arc106_a:
Given is an integer N.
Determine whether there is a pair of positive integers (A, B) such that 3^A + 5^B = N, and find one such pair if it exists.

-----Constraints-----
 - 1 \leq N \leq 10^{18}
 - All values in input are integers.

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

-----Output-----
If there is no pair (A, B) that satisfies the condition, print -1.
If there is such a pair, print A and B of one such pair with space in between. If there are multiple such pairs, any of them will be accepted.

-----Sample Input-----
106

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

We have 3^4 + 5^2 = 81 + 25 = 106, so (A, B) = (4, 2) satisfies the condition.

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

N=int(input())
A = 1
for a in range(1,100):
  A *= 3
  B = 1
  for b in range(1,100):
    B *= 5
    if N == A + B:
      print(a,b)
      break
  else:
    continue
  break
else:
  print(-1)