Input:
def dist(a, b):

    return min(

        abs(a - b),

        abs(a - x) + 1 + abs(y - b),

        abs(a - y) + 1 + abs(x - b)

    )

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

x -= 1

y -= 1

d = [0] * n

for j in range(n):

    for i in range(j):

        d[dist(i, j)] += 1

it = iter(d)

next(it)

print(*it, sep='\n')

def main():

    N, X, Y = map(int, input().split())

    X -= 1

    Y -= 1

    ans = [0] * N

    for j in range(N):

        for i in range(j):

            d = min(

                j - i,

                abs(j - X) + 1 + abs(Y - i),

                abs(j - Y) + 1 + abs(X - i)

            )

            ans[d] += 1

    print(*ans[1:], sep='\n')

if __name__ == '__main__':

    main()

def dist(a, b):
    return min(abs(a - b), abs(a - x) + 1 + abs(y - b), abs(a - y) + 1 + abs(x - b))

n, x, y = map(int, input().split())
x -= 1
y -= 1
d = [0] * n
for j in range(n):
    for i in range(j):
        d[dist(i, j)] += 1
it = iter(d)
next(it)
print(*it, sep="\n")

def main():
    N, X, Y = map(int, input().split())
    X -= 1
    Y -= 1
    ans = [0] * N
    for j in range(N):
        for i in range(j):
            d = min(j - i, abs(j - X) + 1 + abs(Y - i), abs(j - Y) + 1 + abs(X - i))
            ans[d] += 1
    print(*ans[1:], sep="\n")

if __name__ == "__main__":
    main()

-    return min(abs(a - b), abs(a - x) + 1 + abs(y - b), abs(a - y) + 1 + abs(x - b))

+    N, X, Y = map(int, input().split())

+            d = min(j - i, abs(j - X) + 1 + abs(Y - i), abs(j - Y) + 1 + abs(X - i))


Input:
import itertools

from collections import deque,defaultdict,Counter

from itertools import accumulate

import bisect

from heapq import heappop,heappush

from fractions import gcd

from copy import deepcopy

import math

import queue

#import numpy as np

#import sympy as syp(素因数分解とか)

Mod = 1000000007

import sys

input = sys.stdin.readline

sys.setrecursionlimit(1000000)

def sieve_of_eratosthenes(n):

    if not isinstance(n,int):

        raise TypeError("n is not int")

    if n<2:

        raise ValueError("n is not effective")

    prime = [1]*(n+1)

    for i in range(2,int(math.sqrt(n))+1):

        if prime[i] == 1:

            for j in range(2*i,n+1):

                if j%i == 0:

                    prime[j] = 0

    res = []

    for i in range(2,n+1):

        if prime[i] == 1:

            res.append(i)

    return res

def factorial(i):

    if i == 1:

        return 1

    else:

        return i*factorial(i-1)

class UnionFind:

    def __init__(self,n):

        self.parent = [i for i in range(n+1)]

        self.rank = [0 for i in range(n+1)]

    def findroot(self,x):

        if x == self.parent[x]:

            return x

        else:

            y = self.parent[x]

            y = self.findroot(self.parent[x])

            return y

    def union(self,x,y):

        px = self.findroot(x)

        py = self.findroot(y)

        if px < py:

            self.parent[py] = px

        else:

            self.parent[px] = py

    def same_group_or_no(self,x,y):

        return self.findroot(x) == self.findroot(y)

def main(): #startline--------------------------------------------

    n = int(eval(input()))

    h = list(map(int,input().split()))

    dp = [0]*n

    dp[1] = abs(h[1]-h[0])

    for i in range(1,n-1):

        dp[i+1] = min(dp[i]+abs(h[i+1]-h[i]),dp[i-1]+abs(h[i+1]-h[i-1]))

    print((dp[n-1]))

if __name__ == "__main__":

    main() #endline===============================================

import itertools

from collections import deque,defaultdict,Counter

from itertools import accumulate

import bisect

from heapq import heappop,heappush,heapify

from fractions import gcd

from copy import deepcopy

import math

import queue

import numpy as np

#import sympy as syp(素因数分解とか)

Mod = 1000000007

import sys

sys.setrecursionlimit(100000)

def sieve_of_eratosthenes(n):

    if not isinstance(n,int):

        raise TypeError("n is not int")

    if n<2:

        raise ValueError("n is not effective")

    prime = [1]*(n+1)

    for i in range(2,int(math.sqrt(n))+1):

        if prime[i] == 1:

            for j in range(2*i,n+1):

                if j%i == 0:

                    prime[j] = 0

    res = []

    for i in range(2,n+1):

        if prime[i] == 1:

            res.append(i)

    return res

class UnionFind:

    def __init__(self,n):

        self.parent = [i for i in range(n+1)]

        self.rank = [0 for i in range(n+1)]

    def findroot(self,x):

        if x == self.parent[x]:

            return x

        else:

            y = self.parent[x]

            y = self.findroot(self.parent[x])

            return y

    def union(self,x,y):

        px = self.findroot(x)

        py = self.findroot(y)

        if px < py:

            self.parent[py] = px

        else:

            self.parent[px] = py

    def same_group_or_no(self,x,y):

        return self.findroot(x) == self.findroot(y)

def main(): #startline-------------------------------------------

    n = int(eval(input()))

    h = list(map(int,input().split()))

    dp = [0]*(n)

    dp[1] = abs(h[1]-h[0])

    for i in range(2,n):

        dp[i] = min(dp[i-1]+abs(h[i]-h[i-1]),dp[i-2]+abs(h[i]-h[i-2]))

    print((dp[n-1]))

if __name__ == "__main__":

    main() #endline===============================================

import itertools
from collections import deque, defaultdict, Counter
from itertools import accumulate
import bisect
from heapq import heappop, heappush
from fractions import gcd
from copy import deepcopy
import math
import queue

# import numpy as np
# import sympy as syp(素因数分解とか)
Mod = 1000000007
import sys

input = sys.stdin.readline
sys.setrecursionlimit(1000000)

def sieve_of_eratosthenes(n):
    if not isinstance(n, int):
        raise TypeError("n is not int")
    if n < 2:
        raise ValueError("n is not effective")
    prime = [1] * (n + 1)
    for i in range(2, int(math.sqrt(n)) + 1):
        if prime[i] == 1:
            for j in range(2 * i, n + 1):
                if j % i == 0:
                    prime[j] = 0
    res = []
    for i in range(2, n + 1):
        if prime[i] == 1:
            res.append(i)
    return res

def factorial(i):
    if i == 1:
        return 1
    else:
        return i * factorial(i - 1)

class UnionFind:
    def __init__(self, n):
        self.parent = [i for i in range(n + 1)]
        self.rank = [0 for i in range(n + 1)]

    def findroot(self, x):
        if x == self.parent[x]:
            return x
        else:
            y = self.parent[x]
            y = self.findroot(self.parent[x])
            return y

    def union(self, x, y):
        px = self.findroot(x)
        py = self.findroot(y)
        if px < py:
            self.parent[py] = px
        else:
            self.parent[px] = py

    def same_group_or_no(self, x, y):
        return self.findroot(x) == self.findroot(y)

def main():  # startline--------------------------------------------
    n = int(eval(input()))
    h = list(map(int, input().split()))
    dp = [0] * n
    dp[1] = abs(h[1] - h[0])
    for i in range(1, n - 1):
        dp[i + 1] = min(
            dp[i] + abs(h[i + 1] - h[i]), dp[i - 1] + abs(h[i + 1] - h[i - 1])
        )
    print((dp[n - 1]))

if __name__ == "__main__":
    main()  # endline===============================================

import itertools
from collections import deque, defaultdict, Counter
from itertools import accumulate
import bisect
from heapq import heappop, heappush, heapify
from fractions import gcd
from copy import deepcopy
import math
import queue
import numpy as np

# import sympy as syp(素因数分解とか)
Mod = 1000000007
import sys

sys.setrecursionlimit(100000)

def sieve_of_eratosthenes(n):
    if not isinstance(n, int):
        raise TypeError("n is not int")
    if n < 2:
        raise ValueError("n is not effective")
    prime = [1] * (n + 1)
    for i in range(2, int(math.sqrt(n)) + 1):
        if prime[i] == 1:
            for j in range(2 * i, n + 1):
                if j % i == 0:
                    prime[j] = 0
    res = []
    for i in range(2, n + 1):
        if prime[i] == 1:
            res.append(i)
    return res

class UnionFind:
    def __init__(self, n):
        self.parent = [i for i in range(n + 1)]
        self.rank = [0 for i in range(n + 1)]

    def findroot(self, x):
        if x == self.parent[x]:
            return x
        else:
            y = self.parent[x]
            y = self.findroot(self.parent[x])
            return y

    def union(self, x, y):
        px = self.findroot(x)
        py = self.findroot(y)
        if px < py:
            self.parent[py] = px
        else:
            self.parent[px] = py

    def same_group_or_no(self, x, y):
        return self.findroot(x) == self.findroot(y)

def main():  # startline-------------------------------------------
    n = int(eval(input()))
    h = list(map(int, input().split()))
    dp = [0] * (n)
    dp[1] = abs(h[1] - h[0])
    for i in range(2, n):
        dp[i] = min(dp[i - 1] + abs(h[i] - h[i - 1]), dp[i - 2] + abs(h[i] - h[i - 2]))
    print((dp[n - 1]))

if __name__ == "__main__":
    main()  # endline===============================================

+from heapq import heappop, heappush, heapify


Input:
N,M = list(map(int,input().split()))

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

XY = [tuple(map(int,input().split())) for i in range(M)]

class UnionFind:

    def __init__(self,N):

        self.parent = [i for i in range(N)]

        self.rank = [0] * N

        self.count = 0

    def root(self,a):

        if self.parent[a] == a:

            return a

        else:

            self.parent[a] = self.root(self.parent[a])

            return self.parent[a]

    def is_same(self,a,b):

        return self.root(a) == self.root(b)

    def unite(self,a,b):

        ra = self.root(a)

        rb = self.root(b)

        if ra == rb: return

        if self.rank[ra] < self.rank[rb]:

            self.parent[ra] = rb

        else:

            self.parent[rb] = ra

            if self.rank[ra] == self.rank[rb]: self.rank[ra] += 1

        self.count += 1

uf = UnionFind(N)

for x,y in XY:

    if uf.is_same(x,y): continue

    uf.unite(x,y)

for i in range(N):

    uf.root(i)

c = N - uf.count

if c==1:

    print((0))

    exit()

ex = c-2

if c+ex > N:

    print('Impossible')

    exit()

from collections import defaultdict

d = defaultdict(lambda: [])

for i,a in enumerate(A):

    r = uf.root(i)

    d[r].append(a)

ans = 0

hq = []

for k in list(d.keys()):

    s = sorted(d[k])

    ans += s[0]

    for v in s[1:]:

        hq.append(v)

import heapq

heapq.heapify(hq)

for _ in range(ex):

    v = heapq.heappop(hq)

    ans += v

print(ans)

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

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

XY = [tuple(map(int,input().split())) for i in range(M)]

if M==N-1:

    print((0))

    exit()

class UnionFind:

    def __init__(self,N):

        self.parent = [i for i in range(N)]

        self._size = [1] * N

        self.count = 0

    def root(self,a):

        if self.parent[a] == a:

            return a

        else:

            self.parent[a] = self.root(self.parent[a])

            return self.parent[a]

    def is_same(self,a,b):

        return self.root(a) == self.root(b)

    def unite(self,a,b):

        ra = self.root(a)

        rb = self.root(b)

        if ra == rb: return

        if self._size[ra] < self._size[rb]: ra,rb = rb,ra

        self._size[ra] += self._size[rb]

        self.parent[rb] = ra

        self.count += 1

    def size(self,a):

        return self._size[self.root(a)]

uf = UnionFind(N)

for x,y in XY:

    if uf.is_same(x,y): continue

    uf.unite(x,y)

for i in range(N):

    uf.root(i)

from collections import defaultdict

dic = defaultdict(lambda: set())

for i in range(N):

    dic[uf.root(i)].add(i)

need = (len(dic)-1)*2

if need > N:

    print('Impossible')

    exit()

ans = used = 0

import heapq

hq = []

heapq.heapify(hq)

for r,vs in list(dic.items()):

    mini = -1

    mina = 10**9+1

    for i in vs:

        if A[i] < mina:

            mina = A[i]

            mini = i

    ans += mina

    used += 1

    for i in vs:

        if i==mini: continue

        heapq.heappush(hq, A[i])

for _ in range(need - used):

    ans += heapq.heappop(hq)

print(ans)

N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
XY = [tuple(map(int, input().split())) for i in range(M)]

class UnionFind:
    def __init__(self, N):
        self.parent = [i for i in range(N)]
        self.rank = [0] * N
        self.count = 0

    def root(self, a):
        if self.parent[a] == a:
            return a
        else:
            self.parent[a] = self.root(self.parent[a])
            return self.parent[a]

    def is_same(self, a, b):
        return self.root(a) == self.root(b)

    def unite(self, a, b):
        ra = self.root(a)
        rb = self.root(b)
        if ra == rb:
            return
        if self.rank[ra] < self.rank[rb]:
            self.parent[ra] = rb
        else:
            self.parent[rb] = ra
            if self.rank[ra] == self.rank[rb]:
                self.rank[ra] += 1
        self.count += 1

uf = UnionFind(N)
for x, y in XY:
    if uf.is_same(x, y):
        continue
    uf.unite(x, y)
for i in range(N):
    uf.root(i)
c = N - uf.count
if c == 1:
    print((0))
    exit()
ex = c - 2
if c + ex > N:
    print("Impossible")
    exit()
from collections import defaultdict

d = defaultdict(lambda: [])
for i, a in enumerate(A):
    r = uf.root(i)
    d[r].append(a)
ans = 0
hq = []
for k in list(d.keys()):
    s = sorted(d[k])
    ans += s[0]
    for v in s[1:]:
        hq.append(v)
import heapq

heapq.heapify(hq)
for _ in range(ex):
    v = heapq.heappop(hq)
    ans += v
print(ans)

N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
XY = [tuple(map(int, input().split())) for i in range(M)]
if M == N - 1:
    print((0))
    exit()

class UnionFind:
    def __init__(self, N):
        self.parent = [i for i in range(N)]
        self._size = [1] * N
        self.count = 0

    def root(self, a):
        if self.parent[a] == a:
            return a
        else:
            self.parent[a] = self.root(self.parent[a])
            return self.parent[a]

    def is_same(self, a, b):
        return self.root(a) == self.root(b)

    def unite(self, a, b):
        ra = self.root(a)
        rb = self.root(b)
        if ra == rb:
            return
        if self._size[ra] < self._size[rb]:
            ra, rb = rb, ra
        self._size[ra] += self._size[rb]
        self.parent[rb] = ra
        self.count += 1

    def size(self, a):
        return self._size[self.root(a)]

uf = UnionFind(N)
for x, y in XY:
    if uf.is_same(x, y):
        continue
    uf.unite(x, y)
for i in range(N):
    uf.root(i)
from collections import defaultdict

dic = defaultdict(lambda: set())
for i in range(N):
    dic[uf.root(i)].add(i)
need = (len(dic) - 1) * 2
if need > N:
    print("Impossible")
    exit()
ans = used = 0
import heapq

hq = []
heapq.heapify(hq)
for r, vs in list(dic.items()):
    mini = -1
    mina = 10**9 + 1
    for i in vs:
        if A[i] < mina:
            mina = A[i]
            mini = i
    ans += mina
    used += 1
    for i in vs:
        if i == mini:
            continue
        heapq.heappush(hq, A[i])
for _ in range(need - used):
    ans += heapq.heappop(hq)
print(ans)

-        if self.rank[ra] < self.rank[rb]:

-            if self.rank[ra] == self.rank[rb]:

+        if self._size[ra] < self._size[rb]:

+        self._size[ra] += self._size[rb]

+        return self._size[self.root(a)]


Input:
s=eval(input())

q=int(eval(input()))

head=''

foot=''

a=0

for i in range(q):

  t=eval(input())

  if t=='1':

    a=a^1

  else:

    t, f, c = list(map(str, t.split()))

    f=int(f)

    if (f^a)&1==0:

      foot+=c

    else:

      head=c+head

s=head+s+foot

if a==1:

  s=s[::-1]

print(s)

s=eval(input())

q=int(eval(input()))

head=''

foot=''

a=0

for i in range(q):

  t=eval(input())

  if t=='1':

    a=a^1

  else:

    t, f, c = list(map(str, t.split()))

    f=int(f)

    if (f^a)&1==0:

      foot+=c

    else:

      head+=c

s=head[::-1]+s+foot

if a==1:

  s=s[::-1]

print(s)

s = eval(input())
q = int(eval(input()))
head = ""
foot = ""
a = 0
for i in range(q):
    t = eval(input())
    if t == "1":
        a = a ^ 1
    else:
        t, f, c = list(map(str, t.split()))
        f = int(f)
        if (f ^ a) & 1 == 0:
            foot += c
        else:
            head = c + head
s = head + s + foot
if a == 1:
    s = s[::-1]
print(s)

s = eval(input())
q = int(eval(input()))
head = ""
foot = ""
a = 0
for i in range(q):
    t = eval(input())
    if t == "1":
        a = a ^ 1
    else:
        t, f, c = list(map(str, t.split()))
        f = int(f)
        if (f ^ a) & 1 == 0:
            foot += c
        else:
            head += c
s = head[::-1] + s + foot
if a == 1:
    s = s[::-1]
print(s)

-            head = c + head
-s = head + s + foot
+            head += c
+s = head[::-1] + s + foot


Input:
#coding:utf-8

import sys,os

from collections import defaultdict, deque

from fractions import gcd

from math import ceil, floor

sys.setrecursionlimit(10**6)

write = sys.stdout.write

dbg = (lambda *something: print(*something)) if 'TERM_PROGRAM' in os.environ else lambda *x: 0

def main(given=sys.stdin.readline):

    input = lambda: given().rstrip()

    LMIIS = lambda: list(map(int,input().split()))

    II = lambda: int(input())

    XLMIIS = lambda x: [LMIIS() for _ in range(x)]

    YN = lambda c : print('Yes') if c else print('No')

    MOD = 10**9+7

    H,W,K = LMIIS()

    from itertools import accumulate

    S = [list(accumulate(map(int,input()))) for _ in range(H)]

    def divide(pattern):

        lenP = len(pattern)

        divided = [0]*lenP

        count = lenP - 1

        for i in range(lenP):

            if K < pattern[i][0]:

                return H+W

        for i in range(1,W):

            # print('divided=',divided)

            for j in range(lenP):

                if K < pattern[j][i] - divided[j]:

                    for l in range(lenP):

                        divided[l] = pattern[l][i-1]

                    count += 1

                    break

        # print('count=',count)

        return count

    ans = H+W

    for i in range(2**H):

        pattern = []

        line = [0] * W

        for j in range(H):

            for k in range(W):

                line[k] += S[j][k]

            if 2**j & i:

                pattern.append(line)

                line = [0] * W

        pattern.append(line)

        # print(pattern)

        ans = min(divide(pattern),ans)

    print(ans)

    return

if __name__ == '__main__':

    main()

H,W,K = list(map(int,input().split()))

from itertools import accumulate

S = [list(accumulate(list(map(int,eval(input()))))) for _ in range(H)]

def divide(pattern):

    lenP = len(pattern)

    divided = [0]*lenP

    count = lenP - 1

    for i in range(lenP):

        if K < pattern[i][0]:

            return H+W

    for i in range(1,W):

        for j in range(lenP):

            if K < pattern[j][i] - divided[j]:

                for l in range(lenP):

                    divided[l] = pattern[l][i-1]

                count += 1

                break

    return count

ans = H+W

for i in range(2**H):

    pattern = []

    line = [0] * W

    for j in range(H):

        for k in range(W):

            line[k] += S[j][k]

        if 2**j & i:

            pattern.append(line)

            line = [0] * W

    pattern.append(line)

    ans = min(divide(pattern),ans)

print(ans)

# coding:utf-8
import sys, os
from collections import defaultdict, deque
from fractions import gcd
from math import ceil, floor

sys.setrecursionlimit(10**6)
write = sys.stdout.write
dbg = (
    (lambda *something: print(*something))
    if "TERM_PROGRAM" in os.environ
    else lambda *x: 0
)

def main(given=sys.stdin.readline):
    input = lambda: given().rstrip()
    LMIIS = lambda: list(map(int, input().split()))
    II = lambda: int(input())
    XLMIIS = lambda x: [LMIIS() for _ in range(x)]
    YN = lambda c: print("Yes") if c else print("No")
    MOD = 10**9 + 7
    H, W, K = LMIIS()
    from itertools import accumulate

    S = [list(accumulate(map(int, input()))) for _ in range(H)]

    def divide(pattern):
        lenP = len(pattern)
        divided = [0] * lenP
        count = lenP - 1
        for i in range(lenP):
            if K < pattern[i][0]:
                return H + W
        for i in range(1, W):
            # print('divided=',divided)
            for j in range(lenP):
                if K < pattern[j][i] - divided[j]:
                    for l in range(lenP):
                        divided[l] = pattern[l][i - 1]
                    count += 1
                    break
        # print('count=',count)
        return count

    ans = H + W
    for i in range(2**H):
        pattern = []
        line = [0] * W
        for j in range(H):
            for k in range(W):
                line[k] += S[j][k]
            if 2**j & i:
                pattern.append(line)
                line = [0] * W
        pattern.append(line)
        # print(pattern)
        ans = min(divide(pattern), ans)
    print(ans)
    return

if __name__ == "__main__":
    main()

H, W, K = list(map(int, input().split()))
from itertools import accumulate

S = [list(accumulate(list(map(int, eval(input()))))) for _ in range(H)]

def divide(pattern):
    lenP = len(pattern)
    divided = [0] * lenP
    count = lenP - 1
    for i in range(lenP):
        if K < pattern[i][0]:
            return H + W
    for i in range(1, W):
        for j in range(lenP):
            if K < pattern[j][i] - divided[j]:
                for l in range(lenP):
                    divided[l] = pattern[l][i - 1]
                count += 1
                break
    return count

ans = H + W
for i in range(2**H):
    pattern = []
    line = [0] * W
    for j in range(H):
        for k in range(W):
            line[k] += S[j][k]
        if 2**j & i:
            pattern.append(line)
            line = [0] * W
    pattern.append(line)
    ans = min(divide(pattern), ans)
print(ans)

-from collections import defaultdict, deque

+H, W, K = list(map(int, input().split()))

-    (lambda *something: print(*something))

+S = [list(accumulate(list(map(int, eval(input()))))) for _ in range(H)]

-    LMIIS = lambda: list(map(int, input().split()))

-    XLMIIS = lambda x: [LMIIS() for _ in range(x)]

-    YN = lambda c: print("Yes") if c else print("No")

-    S = [list(accumulate(map(int, input()))) for _ in range(H)]

-            # print('divided=',divided)

-                if K < pattern[j][i] - divided[j]:

-                    for l in range(lenP):

-                        divided[l] = pattern[l][i - 1]

-        ans = min(divide(pattern), ans)

+            if K < pattern[j][i] - divided[j]:

+                    divided[l] = pattern[l][i - 1]


Input:
S = eval(input())

ans = [0] * len(S)

# R と Lを別々に考える

cnt = 0

for i in range(len(S) - 1):

    if S[i] == "R":

        cnt += 1

        if S[i + 1] == "L":

            ans[i] += (cnt + 1) // 2

            ans[i + 1] += cnt // 2

    else:

        cnt = 0

cnt = 0

for i in range(len(S) - 1, 0, -1):

    if S[i] == "L":

        cnt += 1

        if S[i - 1] == "R":

            ans[i] += (cnt + 1) // 2

            ans[i - 1] += cnt // 2

    else:

        cnt = 0

print((*ans))

import sys

sys.setrecursionlimit(10 ** 6)

INF = float("inf")

MOD = 10 ** 9 + 7

def input():

    return sys.stdin.readline().strip()

def main():

    S = input().replace("LR", "L R")

    S = S.split()

    ans = []

    for s in S:

        N = len(s)

        tmp = [0] * N

        cnt = 0

        for i in range(N):

            if s[i] == "R":

                cnt += 1

            else:

                break

        tmp[i] += cnt // 2

        tmp[i - 1] += (cnt + 1) // 2

        cnt = N - cnt

        tmp[i] += (cnt + 1) // 2

        tmp[i - 1] += cnt // 2

        ans += tmp

    print(*ans, sep=" ")

if __name__ == "__main__":

    main()

import sys

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

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

def main():
    S = input().replace("LR", "L R")
    S = S.split()
    ans = []
    for s in S:
        N = len(s)
        tmp = [0] * N
        cnt = 0
        for i in range(N):
            if s[i] == "R":
                cnt += 1
            else:
                break
        tmp[i] += cnt // 2
        tmp[i - 1] += (cnt + 1) // 2
        cnt = N - cnt
        tmp[i] += (cnt + 1) // 2
        tmp[i - 1] += cnt // 2
        ans += tmp
    print(*ans, sep=" ")

if __name__ == "__main__":
    main()

-# R と Lを別々に考える

+    return sys.stdin.readline().strip()


Input:
from fractions import gcd

class SegmentTree():

    _data = []

    _offset = 0

    _size = 0

    def __init__(self, size):

        _size = size

        t = 1

        while t <= size:

            t *= 2

        self._offset = t - 1

        self._data = [0] * (t * 2 - 1)

    def update_all(self, iterable):

        self._data[self._offset:self._offset+self._size] = iterable

        for i in range(self._offset - 1, -1, -1):

            self._data[i] = gcd(self._data[i * 2 + 1], self._data[i * 2 + 2])

    def update(self, index, value):

        i = self._offset + index

        self._data[i] = value

        while i >= 1:

            i = (i - 1) // 2

            self._data[i] = gcd(self._data[i * 2 + 1], self._data[i * 2 + 2])

    def query(self, start, stop):

        result = 0

        l = start + self._offset

        r = stop + self._offset

        while l < r:

            if l & 1 == 0:

                result = gcd(result, self._data[l])

            if r & 1 == 0:

                result = gcd(result, self._data[r - 1])

            l = l // 2

            r = (r - 1) // 2

        return result

N = int(eval(input()))

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

st = SegmentTree(N)

st.update_all(A)

result = st.query(1, N)

for i in range(1, N - 1):

    result = max(result, gcd(st.query(0, i), st.query(i + 1, N)))

result = max(result, st.query(0, N - 1))

print(result)

# Sparse table (GCD)

from math import gcd

class SparseTable():

    _data = None

    _lookup = None

    _f = None

    def __init__(self, a):

        data = []

        lookup = []

        f = gcd

        b = 0

        while (1 << b) <= len(a):

            b += 1

        for _ in range(b):

            data.append([0] * (1 << b))

        data[0][:len(a)] = a

        for i in range(1, b):

            j = 0

            di = data[i]

            di1 = data[i - 1]

            while j + (1 << i) <= (1 << b):

                di[j] = f(di1[j], di1[j + (1 << (i - 1))])

                j += 1

        lookup = [0] * (len(a) + 1)

        for i in range(2, len(lookup)):

            lookup[i] = lookup[i >> 1] + 1

        self._data = data

        self._lookup = lookup

        self._f = f

    def query(self, start, stop):

        b = self._lookup[stop - start]

        db = self._data[b]

        return self._f(db[start], db[stop - (1 << b)])

N = int(eval(input()))

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

st = SparseTable(A)

result = st.query(1, N)

for i in range(1, N - 1):

    result = max(result, gcd(st.query(0, i), st.query(i + 1, N)))

result = max(result, st.query(0, N - 1))

print(result)

from fractions import gcd

class SegmentTree:
    _data = []
    _offset = 0
    _size = 0

    def __init__(self, size):
        _size = size
        t = 1
        while t <= size:
            t *= 2
        self._offset = t - 1
        self._data = [0] * (t * 2 - 1)

    def update_all(self, iterable):
        self._data[self._offset : self._offset + self._size] = iterable
        for i in range(self._offset - 1, -1, -1):
            self._data[i] = gcd(self._data[i * 2 + 1], self._data[i * 2 + 2])

    def update(self, index, value):
        i = self._offset + index
        self._data[i] = value
        while i >= 1:
            i = (i - 1) // 2
            self._data[i] = gcd(self._data[i * 2 + 1], self._data[i * 2 + 2])

    def query(self, start, stop):
        result = 0
        l = start + self._offset
        r = stop + self._offset
        while l < r:
            if l & 1 == 0:
                result = gcd(result, self._data[l])
            if r & 1 == 0:
                result = gcd(result, self._data[r - 1])
            l = l // 2
            r = (r - 1) // 2
        return result

N = int(eval(input()))
A = list(map(int, input().split()))
st = SegmentTree(N)
st.update_all(A)
result = st.query(1, N)
for i in range(1, N - 1):
    result = max(result, gcd(st.query(0, i), st.query(i + 1, N)))
result = max(result, st.query(0, N - 1))
print(result)

# Sparse table (GCD)
from math import gcd

class SparseTable:
    _data = None
    _lookup = None
    _f = None

    def __init__(self, a):
        data = []
        lookup = []
        f = gcd
        b = 0
        while (1 << b) <= len(a):
            b += 1
        for _ in range(b):
            data.append([0] * (1 << b))
        data[0][: len(a)] = a
        for i in range(1, b):
            j = 0
            di = data[i]
            di1 = data[i - 1]
            while j + (1 << i) <= (1 << b):
                di[j] = f(di1[j], di1[j + (1 << (i - 1))])
                j += 1
        lookup = [0] * (len(a) + 1)
        for i in range(2, len(lookup)):
            lookup[i] = lookup[i >> 1] + 1
        self._data = data
        self._lookup = lookup
        self._f = f

    def query(self, start, stop):
        b = self._lookup[stop - start]
        db = self._data[b]
        return self._f(db[start], db[stop - (1 << b)])

N = int(eval(input()))
A = list(map(int, input().split()))
st = SparseTable(A)
result = st.query(1, N)
for i in range(1, N - 1):
    result = max(result, gcd(st.query(0, i), st.query(i + 1, N)))
result = max(result, st.query(0, N - 1))
print(result)

-        self._data[self._offset : self._offset + self._size] = iterable

-        for i in range(self._offset - 1, -1, -1):

-            self._data[i] = gcd(self._data[i * 2 + 1], self._data[i * 2 + 2])

+        for i in range(2, len(lookup)):

+            lookup[i] = lookup[i >> 1] + 1

-                result = gcd(result, self._data[l])

-                result = gcd(result, self._data[r - 1])

+        return self._f(db[start], db[stop - (1 << b)])


Input:
import sys, re

from collections import deque, defaultdict, Counter

from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees#, log2

from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby

from operator import itemgetter, mul

from copy import deepcopy

from string import ascii_lowercase, ascii_uppercase, digits

from bisect import bisect, bisect_left, insort, insort_left

from fractions import gcd

from heapq import heappush, heappop

from functools import reduce

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

def INT(): return int(eval(input()))

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

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

def ZIP(n): return list(zip(*(MAP() for _ in range(n))))

sys.setrecursionlimit(10 ** 9)

INF = float('inf')

mod = 10**9 + 7

#from decimal import *

N = INT()

AB = [LIST() for _ in range(N)]

AB.extend([[0, INF], [INF, 0]])

AB.sort(key = lambda x:x[0])

ans = 0

for i in range(1, N+2):

	ans += min(AB[i][0]-AB[i-1][0], AB[i-1][1]-AB[i][1])

print(ans)

import sys, re

from collections import deque, defaultdict, Counter

from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees#, log2

from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby

from operator import itemgetter, mul

from copy import deepcopy

from string import ascii_lowercase, ascii_uppercase, digits

from bisect import bisect, bisect_left, insort, insort_left

from fractions import gcd

from heapq import heappush, heappop

from functools import reduce

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

def INT(): return int(eval(input()))

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

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

def ZIP(n): return list(zip(*(MAP() for _ in range(n))))

sys.setrecursionlimit(10 ** 9)

INF = float('inf')

mod = 10**9 + 7

#from decimal import *

N = INT()

AB = [LIST() for _ in range(N)]

AB.sort(key = lambda x: x[0])

print((AB[-1][0] + AB[-1][1]))

import sys, re
from collections import deque, defaultdict, Counter
from math import (
    ceil,
    sqrt,
    hypot,
    factorial,
    pi,
    sin,
    cos,
    tan,
    asin,
    acos,
    atan,
    radians,
    degrees,
)  # , log2
from itertools import (
    accumulate,
    permutations,
    combinations,
    combinations_with_replacement,
    product,
    groupby,
)
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce

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

def INT():
    return int(eval(input()))

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

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

def ZIP(n):
    return list(zip(*(MAP() for _ in range(n))))

sys.setrecursionlimit(10**9)
INF = float("inf")
mod = 10**9 + 7
# from decimal import *
N = INT()
AB = [LIST() for _ in range(N)]
AB.extend([[0, INF], [INF, 0]])
AB.sort(key=lambda x: x[0])
ans = 0
for i in range(1, N + 2):
    ans += min(AB[i][0] - AB[i - 1][0], AB[i - 1][1] - AB[i][1])
print(ans)

import sys, re
from collections import deque, defaultdict, Counter
from math import (
    ceil,
    sqrt,
    hypot,
    factorial,
    pi,
    sin,
    cos,
    tan,
    asin,
    acos,
    atan,
    radians,
    degrees,
)  # , log2
from itertools import (
    accumulate,
    permutations,
    combinations,
    combinations_with_replacement,
    product,
    groupby,
)
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce

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

def INT():
    return int(eval(input()))

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

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

def ZIP(n):
    return list(zip(*(MAP() for _ in range(n))))

sys.setrecursionlimit(10**9)
INF = float("inf")
mod = 10**9 + 7
# from decimal import *
N = INT()
AB = [LIST() for _ in range(N)]
AB.sort(key=lambda x: x[0])
print((AB[-1][0] + AB[-1][1]))


Input:
n = int(eval(input()))

words = {}

anagrams = 0

for i in range(n):

    word = "".join(sorted(eval(input())))

    if word not in words:

        words[word] = 1

    else:

        anagrams += words[word]

        words[word] += 1

print(anagrams)

# ソートした状態で文字を読み込んで、アナグラムの文字と出てくる回数を取得する

# あるアナグラム文字がn回出てくるならば、ペアの選び方はnC2で、n*(n-1)/2

# 全てのアナグラム文字に関して足し合わせ

import collections

n = int(eval(input()))

# ソートして文字読み込み

s_sorted = [''.join(sorted(eval(input()))) for i in range(n)]

# アナグラム文字列と出現回数を取得

anagram_list = collections.Counter(s_sorted)

count = 0

# 出現回数のリストからペアの選び方を計算して、足し合わせ

for i in list(anagram_list.values()):

    count += i*(i-1)//2

print(count)

# ソートした状態で文字を読み込んで、アナグラムの文字と出てくる回数を取得する
# あるアナグラム文字がn回出てくるならば、ペアの選び方はnC2で、n*(n-1)/2
# 全てのアナグラム文字に関して足し合わせ
import collections

n = int(eval(input()))
# ソートして文字読み込み
s_sorted = ["".join(sorted(eval(input()))) for i in range(n)]
# アナグラム文字列と出現回数を取得
anagram_list = collections.Counter(s_sorted)
count = 0
# 出現回数のリストからペアの選び方を計算して、足し合わせ
for i in list(anagram_list.values()):
    count += i * (i - 1) // 2
print(count)

+# ソートした状態で文字を読み込んで、アナグラムの文字と出てくる回数を取得する

+# あるアナグラム文字がn回出てくるならば、ペアの選び方はnC2で、n*(n-1)/2

+# 全てのアナグラム文字に関して足し合わせ

-    word = "".join(sorted(eval(input())))

+# ソートして文字読み込み

+s_sorted = ["".join(sorted(eval(input()))) for i in range(n)]

+# アナグラム文字列と出現回数を取得

+# 出現回数のリストからペアの選び方を計算して、足し合わせ


Input:
from collections import Counter

N = int(eval(input()))

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

E = []

O = []

for k in range(N):

    if k%2 == 0:

        E.append(a[k])

    else:

        O.append(a[k])

e = Counter(E).most_common()

o = Counter(O).most_common()

if e[0][0] != o[0][0]:

    print((N-e[0][1]-o[0][1]))

else:

    if len(e) >= 2 and len(o) >= 2:

        print((N-e[0][1]-max(e[1][1],o[1][1])))

    elif len(e) >= 2 and len(o) == 1:

        print((N//2-e[1][1]))

    elif len(e) == 1 and len(o) >= 2:

        print((N//2-o[1][1]))

    else:

        print((N//2))

from collections import Counter

n = int(eval(input()))

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

e = [a[k] for k in range(0,n,2)]

o = [a[k] for k in range(1,n,2)]

C = Counter(e).most_common()

D = Counter(o).most_common()

if C[0][0] != D[0][0]:

    print((n-C[0][1]-D[0][1]))

else:

    if len(C) == len(D) == 1:

        print((n//2))

    elif len(C) == 1 and len(D) > 1:

        print((n-C[0][1]-D[1][1]))

    elif len(D) == 1 and len(C) > 1:

        print((n-D[0][1]-C[1][1]))

    else:

        print((n-max(D[0][1]+C[1][1],C[0][1]+D[1][1])))

from collections import Counter

N = int(eval(input()))
a = list(map(int, input().split()))
E = []
O = []
for k in range(N):
    if k % 2 == 0:
        E.append(a[k])
    else:
        O.append(a[k])
e = Counter(E).most_common()
o = Counter(O).most_common()
if e[0][0] != o[0][0]:
    print((N - e[0][1] - o[0][1]))
else:
    if len(e) >= 2 and len(o) >= 2:
        print((N - e[0][1] - max(e[1][1], o[1][1])))
    elif len(e) >= 2 and len(o) == 1:
        print((N // 2 - e[1][1]))
    elif len(e) == 1 and len(o) >= 2:
        print((N // 2 - o[1][1]))
    else:
        print((N // 2))

from collections import Counter

n = int(eval(input()))
a = list(map(int, input().split()))
e = [a[k] for k in range(0, n, 2)]
o = [a[k] for k in range(1, n, 2)]
C = Counter(e).most_common()
D = Counter(o).most_common()
if C[0][0] != D[0][0]:
    print((n - C[0][1] - D[0][1]))
else:
    if len(C) == len(D) == 1:
        print((n // 2))
    elif len(C) == 1 and len(D) > 1:
        print((n - C[0][1] - D[1][1]))
    elif len(D) == 1 and len(C) > 1:
        print((n - D[0][1] - C[1][1]))
    else:
        print((n - max(D[0][1] + C[1][1], C[0][1] + D[1][1])))


Input:
import sys

readline = sys.stdin.readline

def dfs(root):

    visited = [False] * n

    queue = [(0, root)]

    longest = (-1, -1)

    while queue:

        total_weight, node = queue.pop()

        if visited[node]: continue

        visited[node] = True

        longest = max(longest, (total_weight, node))

        queue.extend((total_weight + w, t) for w, t in edges[node] if not visited[t])

    return longest

n = int(readline())

edges = [set() for _ in range(n)]

for _ in range(n - 1):

    s, t, w = list(map(int, readline().split()))

    edges[s].add((w, t))

    edges[t].add((w, s))

_, ln = dfs(0)

ld, _ = dfs(ln)

print(ld)

import sys

readline = sys.stdin.readline

def dfs(root):

    visited = [False] * n

    queue = [(0, root)]

    longest = (-1, -1)

    while queue:

        total_weight, node = queue.pop()

        if visited[node]: continue

        visited[node] = True

        longest = max(longest, (total_weight, node))

        queue += [(total_weight + w, t) for w, t in edges[node] if not visited[t]]

    return longest

n = int(readline())

edges = [set() for _ in range(n)]

for _ in range(n - 1):

    s, t, w = list(map(int, readline().split()))

    edges[s].add((w, t))

    edges[t].add((w, s))

_, ln = dfs(0)

ld, _ = dfs(ln)

print(ld)

-        queue.extend((total_weight + w, t) for w, t in edges[node] if not visited[t])

+        queue += [(total_weight + w, t) for w, t in edges[node] if not visited[t]]


Input:
import sys

cnt = 0

def merge_sort(a, left, right):

	if left + 1 < right:

		mid = int(left + (right - left) / 2)

		merge_sort(a, left, mid)

		merge_sort(a, mid, right)

		merge(a, left, mid, right)

def merge(a, left, mid, right):

	n1 = mid - left

	n2 = right - mid

	L = a[left:left+n1]

	R = a[mid:mid+n2]

	L.append(sys.maxsize)

	R.append(sys.maxsize)

	i = j = 0

	tmp = n1

	for k in range(left, right):

		if L[i] <= R[j]:

			if R[j] != sys.maxsize:

				tmp -= 1

			a[k] = L[i]

			i += 1

		else:

			if L[i] != sys.maxsize:

				global cnt

				cnt += tmp

			a[k] = R[j]

			j += 1

n = int(eval(input()))

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

merge_sort(a, 0, len(a))

print(cnt)

import sys

cnt = 0

def merge_sort(a, left, right):

	if left + 1 < right:

		mid = int(left + (right - left) / 2)

		merge_sort(a, left, mid)

		merge_sort(a, mid, right)

		merge(a, left, mid, right)

def merge(a, left, mid, right):

	n1 = mid - left

	n2 = right - mid

	L = a[left:left + n1]

	R = a[mid:mid + n2]

	L.append(sys.maxsize)

	R.append(sys.maxsize)

	i = j = 0

	for k in range(left, right):

		if L[i] <= R[j]:

			a[k] = L[i]

			i += 1

		else:

			if L[i] != sys.maxsize:

				global cnt

				cnt += n1 - i

			a[k] = R[j]

			j += 1

n = int(eval(input()))

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

merge_sort(a, 0, len(a))

print(cnt)

import sys

cnt = 0

def merge_sort(a, left, right):
    if left + 1 < right:
        mid = int(left + (right - left) / 2)
        merge_sort(a, left, mid)
        merge_sort(a, mid, right)
        merge(a, left, mid, right)

def merge(a, left, mid, right):
    n1 = mid - left
    n2 = right - mid
    L = a[left : left + n1]
    R = a[mid : mid + n2]
    L.append(sys.maxsize)
    R.append(sys.maxsize)
    i = j = 0
    tmp = n1
    for k in range(left, right):
        if L[i] <= R[j]:
            if R[j] != sys.maxsize:
                tmp -= 1
            a[k] = L[i]
            i += 1
        else:
            if L[i] != sys.maxsize:
                global cnt
                cnt += tmp
            a[k] = R[j]
            j += 1

n = int(eval(input()))
a = list(map(int, input().split()))
merge_sort(a, 0, len(a))
print(cnt)

import sys

cnt = 0

def merge_sort(a, left, right):
    if left + 1 < right:
        mid = int(left + (right - left) / 2)
        merge_sort(a, left, mid)
        merge_sort(a, mid, right)
        merge(a, left, mid, right)

def merge(a, left, mid, right):
    n1 = mid - left
    n2 = right - mid
    L = a[left : left + n1]
    R = a[mid : mid + n2]
    L.append(sys.maxsize)
    R.append(sys.maxsize)
    i = j = 0
    for k in range(left, right):
        if L[i] <= R[j]:
            a[k] = L[i]
            i += 1
        else:
            if L[i] != sys.maxsize:
                global cnt
                cnt += n1 - i
            a[k] = R[j]
            j += 1

n = int(eval(input()))
a = list(map(int, input().split()))
merge_sort(a, 0, len(a))
print(cnt)

-    tmp = n1
-            if R[j] != sys.maxsize:
-                tmp -= 1
-                cnt += tmp
+                cnt += n1 - i


Input:
import sys

input = sys.stdin.readline

if __name__ == "__main__":

    a,b = input().split()

    ai = int(a)

    bf = round(float(b)*100)

    print((ai*bf//100))

import sys

input = sys.stdin.readline

if __name__ == "__main__":

    a,b = input().split()

    print((int(a) * round(float(b)*100)//100))

import sys

input = sys.stdin.readline
if __name__ == "__main__":
    a, b = input().split()
    ai = int(a)
    bf = round(float(b) * 100)
    print((ai * bf // 100))

import sys

input = sys.stdin.readline
if __name__ == "__main__":
    a, b = input().split()
    print((int(a) * round(float(b) * 100) // 100))


Input:
def prepare(n):

    global MOD

    modFacts = [0] * (n + 1)

    modFacts[0] = 1

    for i in range(n):

        modFacts[i + 1] = (modFacts[i] * (i + 1)) % MOD

    invs = [1] * (n + 1)

    invs[n] = pow(modFacts[n], MOD - 2, MOD)

    for i in range(n, 1, -1):

        invs[i - 1] = (invs[i] * i) % MOD

    return modFacts, invs

MOD = 10 ** 9 + 7

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

modFacts, invs = prepare(max(N, M))

ans = 0

for i in range(N + 1):

    cnt = (modFacts[N] * invs[i] * invs[N - i]) % MOD

    cnt *= (modFacts[M] * invs[M - i]) % MOD

    cnt %= MOD

    cnt *= pow(modFacts[M - i] * invs[(M - i) - (N - i)], 2, MOD)

    cnt %= MOD

    ans += pow(-1, i) * cnt

    ans %= MOD

print(ans)

MOD = 10 ** 9 + 7

def prepare(n):

    global MOD

    modFacts = [0] * (n + 1)

    modFacts[0] = 1

    for i in range(n):

        modFacts[i + 1] = (modFacts[i] * (i + 1)) % MOD

    invs = [1] * (n + 1)

    invs[n] = pow(modFacts[n], MOD - 2, MOD)

    for i in range(n, 1, -1):

        invs[i - 1] = (invs[i] * i) % MOD

    return modFacts, invs

def comb(n, r):

    global MOD, modFacts, invs

    return (modFacts[n] * invs[n - r] * invs[r]) % MOD

def perm(n, r):

    global MOD, modFacts, invs

    return (modFacts[n] * invs[n - r]) % MOD

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

modFacts, invs = prepare(M)

ans = 0

flag = 1

for i in range(N + 1):

    a = comb(N, i)

    b = perm(M, i)

    c = pow(perm(M - i, N - i), 2, MOD)

    cnt = (a * b * c) % MOD

    ans = (ans + flag * cnt) % MOD

    flag *= -1

print(ans)

def prepare(n):
    global MOD
    modFacts = [0] * (n + 1)
    modFacts[0] = 1
    for i in range(n):
        modFacts[i + 1] = (modFacts[i] * (i + 1)) % MOD
    invs = [1] * (n + 1)
    invs[n] = pow(modFacts[n], MOD - 2, MOD)
    for i in range(n, 1, -1):
        invs[i - 1] = (invs[i] * i) % MOD
    return modFacts, invs

MOD = 10**9 + 7
N, M = list(map(int, input().split()))
modFacts, invs = prepare(max(N, M))
ans = 0
for i in range(N + 1):
    cnt = (modFacts[N] * invs[i] * invs[N - i]) % MOD
    cnt *= (modFacts[M] * invs[M - i]) % MOD
    cnt %= MOD
    cnt *= pow(modFacts[M - i] * invs[(M - i) - (N - i)], 2, MOD)
    cnt %= MOD
    ans += pow(-1, i) * cnt
    ans %= MOD
print(ans)

MOD = 10**9 + 7

def prepare(n):
    global MOD
    modFacts = [0] * (n + 1)
    modFacts[0] = 1
    for i in range(n):
        modFacts[i + 1] = (modFacts[i] * (i + 1)) % MOD
    invs = [1] * (n + 1)
    invs[n] = pow(modFacts[n], MOD - 2, MOD)
    for i in range(n, 1, -1):
        invs[i - 1] = (invs[i] * i) % MOD
    return modFacts, invs

def comb(n, r):
    global MOD, modFacts, invs
    return (modFacts[n] * invs[n - r] * invs[r]) % MOD

def perm(n, r):
    global MOD, modFacts, invs
    return (modFacts[n] * invs[n - r]) % MOD

N, M = list(map(int, input().split()))
modFacts, invs = prepare(M)
ans = 0
flag = 1
for i in range(N + 1):
    a = comb(N, i)
    b = perm(M, i)
    c = pow(perm(M - i, N - i), 2, MOD)
    cnt = (a * b * c) % MOD
    ans = (ans + flag * cnt) % MOD
    flag *= -1
print(ans)

+    return (modFacts[n] * invs[n - r] * invs[r]) % MOD

+    return (modFacts[n] * invs[n - r]) % MOD

-    cnt = (modFacts[N] * invs[i] * invs[N - i]) % MOD

-    cnt *= (modFacts[M] * invs[M - i]) % MOD

-    cnt *= pow(modFacts[M - i] * invs[(M - i) - (N - i)], 2, MOD)

+    c = pow(perm(M - i, N - i), 2, MOD)


Input:
import sys

def gcd(a, b):

    while b:

        a, b = b, a%b

    return a

n=int(eval(input()))

al=input().split()

al_i = [int(s) for s in al]

if (n == 2):

   print((max(al_i[0],al_i[1])))

   sys.exit()

fg = [0] * n

bg = [0] * n

for x in range(n):

   if (x == 0):

       fg[0] = al_i[0]

       y = 1

   else:

      while y <= x:

         fg[y] = gcd(fg[y-1], al_i[y])

         y += 1

for x in range(n):

   if (x == 0):

      bg[0] = al_i[n-1]

      y = 1

   else:

      while y <= x:

         bg[y] = gcd(bg[y-1], al_i[n-1-y])

         y += 1

m = 0

gm = 0

for x in range(n):

   if (x == 0):

      g = bg[n-2]

   elif (x == n-1):

      g = fg[n-2]

   else:

      g = gcd(fg[x-1],bg[n-2-x])

   if (g > gm):

      gm = g

print(gm)

def gcd(a, b):

    while b:

        a, b = b, a%b

    return a

n=int(eval(input()))

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

fg = [0] * n

bg = [0] * n

fg[0] = al[0]

bg[0] = al[n-1]

for x in range(1,n):

    fg[x] = gcd(fg[x-1], al[x])

    bg[x] = gcd(bg[x-1], al[n-1-x])

gm = max(bg[n-2], fg[n-2])

for x in range(1,n-1):

   g = gcd(fg[x-1],bg[n-2-x])

   if (g > gm):

      gm = g

print(gm)

import sys

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

n = int(eval(input()))
al = input().split()
al_i = [int(s) for s in al]
if n == 2:
    print((max(al_i[0], al_i[1])))
    sys.exit()
fg = [0] * n
bg = [0] * n
for x in range(n):
    if x == 0:
        fg[0] = al_i[0]
        y = 1
    else:
        while y <= x:
            fg[y] = gcd(fg[y - 1], al_i[y])
            y += 1
for x in range(n):
    if x == 0:
        bg[0] = al_i[n - 1]
        y = 1
    else:
        while y <= x:
            bg[y] = gcd(bg[y - 1], al_i[n - 1 - y])
            y += 1
m = 0
gm = 0
for x in range(n):
    if x == 0:
        g = bg[n - 2]
    elif x == n - 1:
        g = fg[n - 2]
    else:
        g = gcd(fg[x - 1], bg[n - 2 - x])
    if g > gm:
        gm = g
print(gm)

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

n = int(eval(input()))
al = [int(x) for x in input().split()]
fg = [0] * n
bg = [0] * n
fg[0] = al[0]
bg[0] = al[n - 1]
for x in range(1, n):
    fg[x] = gcd(fg[x - 1], al[x])
    bg[x] = gcd(bg[x - 1], al[n - 1 - x])
gm = max(bg[n - 2], fg[n - 2])
for x in range(1, n - 1):
    g = gcd(fg[x - 1], bg[n - 2 - x])
    if g > gm:
        gm = g
print(gm)


Input:
n = int(eval(input()))

h = tuple(int(i) for i in input().split())

x, y = 0, abs(h[0]-h[1])

for i in range(2, n):

    v = min(x+abs(h[i-2]-h[i]), y+abs(h[i-1]-h[i]))

    x, y = y, v

print(y)

n = int(eval(input()))

h = tuple(map(int, input().split()))

x, y = 0, abs(h[0]-h[1])

for i in range(2, n):

    d1 = x+abs(h[i-2]-h[i])

    d2 = y+abs(h[i-1]-h[i])

    x, y = y, d1 if d1 < d2 else d2

print(y)

n = int(eval(input()))
h = tuple(int(i) for i in input().split())
x, y = 0, abs(h[0] - h[1])
for i in range(2, n):
    v = min(x + abs(h[i - 2] - h[i]), y + abs(h[i - 1] - h[i]))
    x, y = y, v
print(y)

n = int(eval(input()))
h = tuple(map(int, input().split()))
x, y = 0, abs(h[0] - h[1])
for i in range(2, n):
    d1 = x + abs(h[i - 2] - h[i])
    d2 = y + abs(h[i - 1] - h[i])
    x, y = y, d1 if d1 < d2 else d2
print(y)

-h = tuple(int(i) for i in input().split())


Input:
H, W = list(map(int,input().split()))

S = [eval(input()) for _ in range(H)]

for i in range(H):

  rs = ''

  for j in range(W):

    if(S[i][j] == '#'):

      rs += '#'

    else:

      tmp = 0

      for s in S[max(0, i-1): min(H, i+2)]:

        tmp += s[max(0, j-1): min(W, j+2)].count('#')

      rs += str(tmp)

  print(rs)

H, W = list(map(int, input().split()))
S = [eval(input()) for _ in range(H)]
for i in range(H):
    rs = ""
    for j in range(W):
        if S[i][j] == "#":
            rs += "#"
        else:
            tmp = 0
            for s in S[max(0, i - 1) : min(H, i + 2)]:
                tmp += s[max(0, j - 1) : min(W, j + 2)].count("#")
            rs += str(tmp)
    print(rs)

H, W = list(map(int, input().split()))
S = [eval(input()) for _ in range(H)]
result = [[0 for _ in range(W + 1)] for _ in range(H + 1)]
for i in range(H):
    for j in range(W):
        if S[i][j] == "#":
            result[i][j] = "#"
            if result[i - 1][j - 1] != "#":
                result[i - 1][j - 1] += 1
            if result[i - 1][j] != "#":
                result[i - 1][j] += 1
            if result[i - 1][j + 1] != "#":
                result[i - 1][j + 1] += 1
            if result[i][j - 1] != "#":
                result[i][j - 1] += 1
            if result[i][j + 1] != "#":
                result[i][j + 1] += 1
            if result[i + 1][j - 1] != "#":
                result[i + 1][j - 1] += 1
            if result[i + 1][j] != "#":
                result[i + 1][j] += 1
            if result[i + 1][j + 1] != "#":
                result[i + 1][j + 1] += 1
for r in result[:-1]:
    print(("".join(list(map(str, r[:W])))))

+result = [[0 for _ in range(W + 1)] for _ in range(H + 1)]

-            for s in S[max(0, i - 1) : min(H, i + 2)]:

+    print(("".join(list(map(str, r[:W])))))


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

abcd = [[*list(map(int,input().split()))] for _ in range(q)]

from itertools import *

ans = 0

for A in combinations_with_replacement(list(range(1, m+1)), n): # nHr

    now = sum(d if A[b-1] - A[a-1] == c else 0 for a,b,c,d in abcd)

    ans = max(ans, now)

print(ans)

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

abcd = [[*list(map(int,input().split()))] for _ in range(q)]

def dfs(A=[1]): # A:1 origin

    if n+1 <= len(A):

        return sum(d if A[b]-A[a]==c else 0 for a,b,c,d in abcd)

    A.append(A[-1])

    ret = 0

    while A[-1] <= m:

        ret = max(ret, dfs(A))

        A[-1] += 1

    A.pop()

    return ret

ans = dfs()

print(ans)

n, m, q = list(map(int, input().split()))
abcd = [[*list(map(int, input().split()))] for _ in range(q)]
from itertools import *

ans = 0
for A in combinations_with_replacement(list(range(1, m + 1)), n):  # nHr
    now = sum(d if A[b - 1] - A[a - 1] == c else 0 for a, b, c, d in abcd)
    ans = max(ans, now)
print(ans)

n, m, q = list(map(int, input().split()))
abcd = [[*list(map(int, input().split()))] for _ in range(q)]

def dfs(A=[1]):  # A:1 origin
    if n + 1 <= len(A):
        return sum(d if A[b] - A[a] == c else 0 for a, b, c, d in abcd)
    A.append(A[-1])
    ret = 0
    while A[-1] <= m:
        ret = max(ret, dfs(A))
        A[-1] += 1
    A.pop()
    return ret

ans = dfs()
print(ans)

-for A in combinations_with_replacement(list(range(1, m + 1)), n):  # nHr

-    now = sum(d if A[b - 1] - A[a - 1] == c else 0 for a, b, c, d in abcd)

+        return sum(d if A[b] - A[a] == c else 0 for a, b, c, d in abcd)


Input:
from decimal import Decimal

def waru(N,num):

  cnt = 0

  while N%num==0:

    N //= num

    cnt += 1

  return cnt

def solve():

  N = int(eval(input()))

  num = [[0]*101 for _ in range(101)]

  lis = [0]*N

  for i in range(N):

    a = int(Decimal(eval(input()))*10**9)

    two,five = waru(a,2)-9,waru(a,5)-9

    two -= 50

    five -= 50

    num[two][five] += 1

    lis[i] = [two,five]

  cum2 = [[0]*101 for _ in range(101)]

  for i in range(99,-1,-1):

    for j in range(99,-1,-1):

      cum2[i][j] = cum2[i+1][j]+cum2[i][j+1]-cum2[i+1][j+1]+num[i][j]

  ans = 0

  for i in range(N):

    two,five = lis[i]

    two2,five2 = -(two+50)-50,-(five+50)-50

    ans += cum2[two2][five2]

    if two+50>=0 and five+50>=0:

      ans -= 1

  return ans//2

print((solve()))

from decimal import Decimal

def waru(N,num):

  cnt = 0

  while N%num==0:

    N //= num

    cnt += 1

  return cnt

def solve():

  N = int(eval(input()))

  num = [[0]*101 for _ in range(101)]

  lis = [0]*N

  for i in range(N):

    a = eval(input())

    b = a.split(".")

    if len(b)==1:

        a = int(a)*(10**9)

    else:

        a = int(b[0] + b[1] + (9-len(b[1]))*"0")

    two,five = waru(a,2)-9,waru(a,5)-9

    two -= 50

    five -= 50

    num[two][five] += 1

    lis[i] = [two,five]

  cum2 = [[0]*101 for _ in range(101)]

  for i in range(99,-1,-1):

    for j in range(99,-1,-1):

      cum2[i][j] = cum2[i+1][j]+cum2[i][j+1]-cum2[i+1][j+1]+num[i][j]

  ans = 0

  for i in range(N):

    two,five = lis[i]

    two2,five2 = -(two+50)-50,-(five+50)-50

    ans += cum2[two2][five2]

    if two+50>=0 and five+50>=0:

      ans -= 1

  return ans//2

print((solve()))

from decimal import Decimal

def waru(N, num):
    cnt = 0
    while N % num == 0:
        N //= num
        cnt += 1
    return cnt

def solve():
    N = int(eval(input()))
    num = [[0] * 101 for _ in range(101)]
    lis = [0] * N
    for i in range(N):
        a = int(Decimal(eval(input())) * 10**9)
        two, five = waru(a, 2) - 9, waru(a, 5) - 9
        two -= 50
        five -= 50
        num[two][five] += 1
        lis[i] = [two, five]
    cum2 = [[0] * 101 for _ in range(101)]
    for i in range(99, -1, -1):
        for j in range(99, -1, -1):
            cum2[i][j] = (
                cum2[i + 1][j] + cum2[i][j + 1] - cum2[i + 1][j + 1] + num[i][j]
            )
    ans = 0
    for i in range(N):
        two, five = lis[i]
        two2, five2 = -(two + 50) - 50, -(five + 50) - 50
        ans += cum2[two2][five2]
        if two + 50 >= 0 and five + 50 >= 0:
            ans -= 1
    return ans // 2

print((solve()))

from decimal import Decimal

def waru(N, num):
    cnt = 0
    while N % num == 0:
        N //= num
        cnt += 1
    return cnt

def solve():
    N = int(eval(input()))
    num = [[0] * 101 for _ in range(101)]
    lis = [0] * N
    for i in range(N):
        a = eval(input())
        b = a.split(".")
        if len(b) == 1:
            a = int(a) * (10**9)
        else:
            a = int(b[0] + b[1] + (9 - len(b[1])) * "0")
        two, five = waru(a, 2) - 9, waru(a, 5) - 9
        two -= 50
        five -= 50
        num[two][five] += 1
        lis[i] = [two, five]
    cum2 = [[0] * 101 for _ in range(101)]
    for i in range(99, -1, -1):
        for j in range(99, -1, -1):
            cum2[i][j] = (
                cum2[i + 1][j] + cum2[i][j + 1] - cum2[i + 1][j + 1] + num[i][j]
            )
    ans = 0
    for i in range(N):
        two, five = lis[i]
        two2, five2 = -(two + 50) - 50, -(five + 50) - 50
        ans += cum2[two2][five2]
        if two + 50 >= 0 and five + 50 >= 0:
            ans -= 1
    return ans // 2

print((solve()))

-        a = int(Decimal(eval(input())) * 10**9)


Input:
f = lambda : list(map(int, input().split()))

n, m = f()

ll = [[0]*n for i in range(m)]

for i in range(m):

  _, *t = f()

  for j in t:

    ll[i][j-1] = 1

lp = list(f())

import itertools as it

ans = 0

for p in it.product([0,1], repeat=n):

  if lp == [sum(a*b for a, b in zip(p,l))%2 for l in ll]:

    ans += 1

print(ans)

f=lambda:list(map(int,input().split()))

n,m=f()

ll=[[0]*n for _ in range(m)]

for l in ll:

  k,*s=f()

  for i in s: l[i-1]=1

p=list(f())

import itertools as it

print((sum(all(sum(a*b for a,b in zip(l,t))%2==p[i] for i,l in enumerate(ll)) for t in it.product([0,1],repeat=n))))

f = lambda: list(map(int, input().split()))
n, m = f()
ll = [[0] * n for i in range(m)]
for i in range(m):
    _, *t = f()
    for j in t:
        ll[i][j - 1] = 1
lp = list(f())
import itertools as it

ans = 0
for p in it.product([0, 1], repeat=n):
    if lp == [sum(a * b for a, b in zip(p, l)) % 2 for l in ll]:
        ans += 1
print(ans)

f = lambda: list(map(int, input().split()))
n, m = f()
ll = [[0] * n for _ in range(m)]
for l in ll:
    k, *s = f()
    for i in s:
        l[i - 1] = 1
p = list(f())
import itertools as it

print(
    (
        sum(
            all(sum(a * b for a, b in zip(l, t)) % 2 == p[i] for i, l in enumerate(ll))
            for t in it.product([0, 1], repeat=n)
        )
    )
)

-    if lp == [sum(a * b for a, b in zip(p, l)) % 2 for l in ll]:

+            all(sum(a * b for a, b in zip(l, t)) % 2 == p[i] for i, l in enumerate(ll))

+            for t in it.product([0, 1], repeat=n)


Input:
import heapq

n=int(eval(input()))

arr=list(map(int,input().split()))

arr=sorted(arr,reverse=True)

ans=0

q=[]

heapq.heappush(q,-arr[0])

for i in range(1,n):

  tmp=heapq.heappop(q)

  tmp*=-1

  ans+=tmp

  heapq.heappush(q,-arr[i])

  heapq.heappush(q,-arr[i])

print(ans)

n=int(eval(input()))

arr=list(map(int,input().split()))

arr=sorted(arr,reverse=True)

ans=0

for i in range(1,n):

  ans+=arr[i//2]

print(ans)

import heapq

n = int(eval(input()))
arr = list(map(int, input().split()))
arr = sorted(arr, reverse=True)
ans = 0
q = []
heapq.heappush(q, -arr[0])
for i in range(1, n):
    tmp = heapq.heappop(q)
    tmp *= -1
    ans += tmp
    heapq.heappush(q, -arr[i])
    heapq.heappush(q, -arr[i])
print(ans)

n = int(eval(input()))
arr = list(map(int, input().split()))
arr = sorted(arr, reverse=True)
ans = 0
for i in range(1, n):
    ans += arr[i // 2]
print(ans)

-import heapq
-q = []
-heapq.heappush(q, -arr[0])
-    tmp = heapq.heappop(q)
-    tmp *= -1
-    ans += tmp
-    heapq.heappush(q, -arr[i])
-    heapq.heappush(q, -arr[i])
+    ans += arr[i // 2]


Input:
N = int(eval(input()))

src = list(map(int,input().split()))

asc = None

ans = 1

for i in range(N-1):

    d = src[i+1] - src[i]

    if d == 0: continue

    if asc is None:

        asc = d > 0

    elif (asc and d < 0) or (not asc and d > 0):

        ans += 1

        asc = None

print(ans)

N = int(eval(input()))

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

ans = 1

up = None

for a,b in zip(A,A[1:]):

    if a==b: continue

    if a<b:

        if up is None:

            up = True

        elif not up:

            ans += 1

            up = None

    else:

        if up is None:

            up = False

        elif up:

            ans += 1

            up = None

print(ans)

N = int(eval(input()))
src = list(map(int, input().split()))
asc = None
ans = 1
for i in range(N - 1):
    d = src[i + 1] - src[i]
    if d == 0:
        continue
    if asc is None:
        asc = d > 0
    elif (asc and d < 0) or (not asc and d > 0):
        ans += 1
        asc = None
print(ans)

N = int(eval(input()))
A = list(map(int, input().split()))
ans = 1
up = None
for a, b in zip(A, A[1:]):
    if a == b:
        continue
    if a < b:
        if up is None:
            up = True
        elif not up:
            ans += 1
            up = None
    else:
        if up is None:
            up = False
        elif up:
            ans += 1
            up = None
print(ans)

-    elif (asc and d < 0) or (not asc and d > 0):


Input:
import sys

import os

def main():

    if os.getenv("LOCAL"):

        sys.stdin = open("input.txt", "r")

    N = int(sys.stdin.readline().rstrip())

    ret = float('inf')

    for i in range(1, 10000000):

        q, mod = divmod(N, i)

        if mod == 0:

            j = N // i

            ret = min(ret, ((j-1)+(i-1)))

    print(ret)

if __name__ == '__main__':

    main()

import sys

import os

import math

def main():

    if os.getenv("LOCAL"):

        sys.stdin = open("input.txt", "r")

    N = int(sys.stdin.readline().rstrip())

    max = int(math.sqrt(N) + 1)

    ret = float('inf')

    for i in range(1, max):

        q, mod = divmod(N, i)

        if mod == 0:

            j = N // i

            ret = min(ret, ((j-1)+(i-1)))

    print(ret)

if __name__ == '__main__':

    main()

import sys
import os

def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")
    N = int(sys.stdin.readline().rstrip())
    ret = float("inf")
    for i in range(1, 10000000):
        q, mod = divmod(N, i)
        if mod == 0:
            j = N // i
            ret = min(ret, ((j - 1) + (i - 1)))
    print(ret)

if __name__ == "__main__":
    main()

import sys
import os
import math

def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")
    N = int(sys.stdin.readline().rstrip())
    max = int(math.sqrt(N) + 1)
    ret = float("inf")
    for i in range(1, max):
        q, mod = divmod(N, i)
        if mod == 0:
            j = N // i
            ret = min(ret, ((j - 1) + (i - 1)))
    print(ret)

if __name__ == "__main__":
    main()

+import math
+    max = int(math.sqrt(N) + 1)
-    for i in range(1, 10000000):
+    for i in range(1, max):


Input:
if __name__ == '__main__':

    x = abs(int(eval(input())))

    s = 0

    for i in range(0,10 ** 9):

        if s > x:

            print((i - 1))

            break

        elif s == x:

            print((i - 1))

            break

        s += i

if __name__ == '__main__':

    x = abs(int(eval(input())))

    s = 0

    for i in range(0,10 ** 9):

        if s >= x:

            print((i - 1))

            break

        s += i

if __name__ == "__main__":
    x = abs(int(eval(input())))
    s = 0
    for i in range(0, 10**9):
        if s > x:
            print((i - 1))
            break
        elif s == x:
            print((i - 1))
            break
        s += i

if __name__ == "__main__":
    x = abs(int(eval(input())))
    s = 0
    for i in range(0, 10**9):
        if s >= x:
            print((i - 1))
            break
        s += i

-        if s > x:
-            print((i - 1))
-            break
-        elif s == x:
+        if s >= x:


Input:
import sys

init = ''.join(sys.stdin.read().split())

generated_state = {init: 0}

def bfs(root):

    s = 0

    configure = [root]

    while '123456780' not in configure:

        q = iter(configure)

        configure = []

        s += 1

        for c in q:

            i = c.find('0')

            if 0 <= i <= 5:

                t = str.maketrans('0' + c[i+3], c[i+3] + '0')

                t_c = c.translate(t)

                if t_c not in generated_state:

                    generated_state[t_c] = s

                    configure.append(t_c)

            if i >= 3:

                t = str.maketrans('0' + c[i-3], c[i-3] + '0')

                t_c = c.translate(t)

                if t_c not in generated_state:

                    generated_state[t_c] = s

                    configure.append(t_c)

            if i == 0 or i == 1 or i == 3 or i == 4 or i == 6 or i == 7:

                t = str.maketrans('0' + c[i+1], c[i+1] + '0')

                t_c = c.translate(t)

                if t_c not in generated_state:

                    generated_state[t_c] = s

                    configure.append(t_c)

            if i == 1 or i == 2 or i == 4 or i == 5 or i == 7 or i == 8:

                t = str.maketrans('0' + c[i-1], c[i-1] + '0')

                t_c = c.translate(t)

                if t_c not in generated_state:

                    generated_state[t_c] = s

                    configure.append(t_c)

            if '123456780' in generated_state:

                break

    print(s)

bfs(init)

import sys

init = ''.join(sys.stdin.read().split())

# Bidirectional search using breadth-first search

def solve(start, goal):

    if start == goal:

        return 0

    generated_state = {start: 0, goal: 1}   # 0: foreward, 1: backward

    step = {start: 0, goal: 0}

    s = 0

    c_d = [(start, 0), (goal, 1)] # configure and direction

    while True:

        q = iter(c_d)

        c_d = []

        s += 1

        for c, d in q:

            i = c.find('0')

            if 0 <= i <= 5:

                t = str.maketrans('0' + c[i+3], c[i+3] + '0')

                t_c = c.translate(t)

                if t_c in generated_state:

                    if generated_state[t_c] != d:

                        return s + step[t_c]

                else:

                    generated_state[t_c] = d

                    step[t_c] = s

                    c_d.append((t_c, d))

            if i >= 3:

                t = str.maketrans('0' + c[i-3], c[i-3] + '0')

                t_c = c.translate(t)

                if t_c in generated_state:

                    if generated_state[t_c] != d:

                        return s + step[t_c]

                else:

                    generated_state[t_c] = d

                    step[t_c] = s

                    c_d.append((t_c, d))

            if i == 0 or i == 1 or i == 3 or i == 4 or i == 6 or i == 7:

                t = str.maketrans('0' + c[i+1], c[i+1] + '0')

                t_c = c.translate(t)

                if t_c in generated_state:

                    if generated_state[t_c] != d:

                        return s + step[t_c]

                else:

                    generated_state[t_c] = d

                    step[t_c] = s

                    c_d.append((t_c, d))

            if i == 1 or i == 2 or i == 4 or i == 5 or i == 7 or i == 8:

                t = str.maketrans('0' + c[i-1], c[i-1] + '0')

                t_c = c.translate(t)

                if t_c in generated_state:

                    if generated_state[t_c] != d:

                        return s + step[t_c]

                else:

                    generated_state[t_c] = d

                    step[t_c] = s

                    c_d.append((t_c, d))

print((solve(init, '123456780')))

import sys

init = "".join(sys.stdin.read().split())
generated_state = {init: 0}

def bfs(root):
    s = 0
    configure = [root]
    while "123456780" not in configure:
        q = iter(configure)
        configure = []
        s += 1
        for c in q:
            i = c.find("0")
            if 0 <= i <= 5:
                t = str.maketrans("0" + c[i + 3], c[i + 3] + "0")
                t_c = c.translate(t)
                if t_c not in generated_state:
                    generated_state[t_c] = s
                    configure.append(t_c)
            if i >= 3:
                t = str.maketrans("0" + c[i - 3], c[i - 3] + "0")
                t_c = c.translate(t)
                if t_c not in generated_state:
                    generated_state[t_c] = s
                    configure.append(t_c)
            if i == 0 or i == 1 or i == 3 or i == 4 or i == 6 or i == 7:
                t = str.maketrans("0" + c[i + 1], c[i + 1] + "0")
                t_c = c.translate(t)
                if t_c not in generated_state:
                    generated_state[t_c] = s
                    configure.append(t_c)
            if i == 1 or i == 2 or i == 4 or i == 5 or i == 7 or i == 8:
                t = str.maketrans("0" + c[i - 1], c[i - 1] + "0")
                t_c = c.translate(t)
                if t_c not in generated_state:
                    generated_state[t_c] = s
                    configure.append(t_c)
            if "123456780" in generated_state:
                break
    print(s)

bfs(init)

import sys

init = "".join(sys.stdin.read().split())
# Bidirectional search using breadth-first search
def solve(start, goal):
    if start == goal:
        return 0
    generated_state = {start: 0, goal: 1}  # 0: foreward, 1: backward
    step = {start: 0, goal: 0}
    s = 0
    c_d = [(start, 0), (goal, 1)]  # configure and direction
    while True:
        q = iter(c_d)
        c_d = []
        s += 1
        for c, d in q:
            i = c.find("0")
            if 0 <= i <= 5:
                t = str.maketrans("0" + c[i + 3], c[i + 3] + "0")
                t_c = c.translate(t)
                if t_c in generated_state:
                    if generated_state[t_c] != d:
                        return s + step[t_c]
                else:
                    generated_state[t_c] = d
                    step[t_c] = s
                    c_d.append((t_c, d))
            if i >= 3:
                t = str.maketrans("0" + c[i - 3], c[i - 3] + "0")
                t_c = c.translate(t)
                if t_c in generated_state:
                    if generated_state[t_c] != d:
                        return s + step[t_c]
                else:
                    generated_state[t_c] = d
                    step[t_c] = s
                    c_d.append((t_c, d))
            if i == 0 or i == 1 or i == 3 or i == 4 or i == 6 or i == 7:
                t = str.maketrans("0" + c[i + 1], c[i + 1] + "0")
                t_c = c.translate(t)
                if t_c in generated_state:
                    if generated_state[t_c] != d:
                        return s + step[t_c]
                else:
                    generated_state[t_c] = d
                    step[t_c] = s
                    c_d.append((t_c, d))
            if i == 1 or i == 2 or i == 4 or i == 5 or i == 7 or i == 8:
                t = str.maketrans("0" + c[i - 1], c[i - 1] + "0")
                t_c = c.translate(t)
                if t_c in generated_state:
                    if generated_state[t_c] != d:
                        return s + step[t_c]
                else:
                    generated_state[t_c] = d
                    step[t_c] = s
                    c_d.append((t_c, d))

print((solve(init, "123456780")))

+# Bidirectional search using breadth-first search

+    generated_state = {start: 0, goal: 1}  # 0: foreward, 1: backward

-    while "123456780" not in configure:

+    c_d = [(start, 0), (goal, 1)]  # configure and direction

-                if t_c not in generated_state:

-                    generated_state[t_c] = s

-                    configure.append(t_c)

+                if t_c in generated_state:

+                    if generated_state[t_c] != d:

+                        return s + step[t_c]

+                    generated_state[t_c] = d

+                    c_d.append((t_c, d))

-                if t_c not in generated_state:

-                    generated_state[t_c] = s

-                    configure.append(t_c)

+                if t_c in generated_state:

+                    if generated_state[t_c] != d:

+                        return s + step[t_c]

+                    generated_state[t_c] = d

+                    c_d.append((t_c, d))

-                if t_c not in generated_state:

-                    generated_state[t_c] = s

-                    configure.append(t_c)

+                if t_c in generated_state:

+                    if generated_state[t_c] != d:

+                        return s + step[t_c]

+                    generated_state[t_c] = d

+                    c_d.append((t_c, d))

-                if t_c not in generated_state:

-                    generated_state[t_c] = s

-                    configure.append(t_c)

-            if "123456780" in generated_state:

+                if t_c in generated_state:

+                    if generated_state[t_c] != d:

+                        return s + step[t_c]

+                    generated_state[t_c] = d

+                    c_d.append((t_c, d))


Input:
n=int(eval(input()))

a=[[int(i)for i in input().split()]for i in range(n)]

import itertools as it

li=list(it.permutations(list(range(n))))

total=0

for i in li:

    tmp=0

    for j in range(n-1):

        x1,x2=a[i[j]][0],a[i[j+1]][0]

        y1,y2=a[i[j]][1],a[i[j+1]][1]

        tmp=(x1-x2)**2+(y1-y2)**2

        total+=tmp**0.5

print((total/len(li)))

n=int(eval(input()))

a=[[int(i) for i in input().split()] for i in range(n)]

import itertools

import math

pe=itertools.permutations(list(range(n)))

pe=list(pe)

ans=0

for i in pe:

    tmp=0

    for j in range(n-1):

        tmp+=((a[i[j]][0]-a[i[j+1]][0])**2+(a[i[j]][1]-a[i[j+1]][1])**2)**0.5

    ans+=tmp

print((ans/math.factorial(n)))

n = int(eval(input()))
a = [[int(i) for i in input().split()] for i in range(n)]
import itertools as it

li = list(it.permutations(list(range(n))))
total = 0
for i in li:
    tmp = 0
    for j in range(n - 1):
        x1, x2 = a[i[j]][0], a[i[j + 1]][0]
        y1, y2 = a[i[j]][1], a[i[j + 1]][1]
        tmp = (x1 - x2) ** 2 + (y1 - y2) ** 2
        total += tmp**0.5
print((total / len(li)))

n = int(eval(input()))
a = [[int(i) for i in input().split()] for i in range(n)]
import itertools
import math

pe = itertools.permutations(list(range(n)))
pe = list(pe)
ans = 0
for i in pe:
    tmp = 0
    for j in range(n - 1):
        tmp += (
            (a[i[j]][0] - a[i[j + 1]][0]) ** 2 + (a[i[j]][1] - a[i[j + 1]][1]) ** 2
        ) ** 0.5
    ans += tmp
print((ans / math.factorial(n)))


Input:
import sys

sys.setrecursionlimit(4100000)

import math

import itertools

INF = float('inf')

from heapq import heapify, heappop, heappush

def main():

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

    tmp = set(list(range(a,b+1))) & set(list(range(c, d+1)))

    print((max(0, len(tmp)-1)))

if __name__ == '__main__':

    main()

import sys

sys.setrecursionlimit(4100000)

import math

import itertools

INF = float('inf')

from heapq import heapify, heappop, heappush

def main():

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

    print((max(0, min(b,d)-max(a,c))))

if __name__ == '__main__':

    main()

import sys

sys.setrecursionlimit(4100000)
import math
import itertools

INF = float("inf")
from heapq import heapify, heappop, heappush

def main():
    a, b, c, d = list(map(int, input().split()))
    tmp = set(list(range(a, b + 1))) & set(list(range(c, d + 1)))
    print((max(0, len(tmp) - 1)))

if __name__ == "__main__":
    main()

import sys

sys.setrecursionlimit(4100000)
import math
import itertools

INF = float("inf")
from heapq import heapify, heappop, heappush

def main():
    a, b, c, d = list(map(int, input().split()))
    print((max(0, min(b, d) - max(a, c))))

if __name__ == "__main__":
    main()

-    tmp = set(list(range(a, b + 1))) & set(list(range(c, d + 1)))

+    print((max(0, min(b, d) - max(a, c))))


Input:
n=int(eval(input()))

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

r=[]

def f(s,k):

    if k>=0:

        global r

        r+=[s]

        f(s+A[k-1],k-1)

        f(s,k-1)

f(0,n)

eval(input())

for e in map(int,input().split()):print((['no','yes'][e in r]))

n=int(eval(input()))

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

r=set()

def f(s,k):

    if k>=0:

        global r

        r.add(s)

        f(s+A[k-1],k-1)

        f(s,k-1)

f(0,n)

eval(input())

for e in map(int,input().split()):print((['no','yes'][e in r]))

n = int(eval(input()))
A = list(map(int, input().split()))
r = []

def f(s, k):
    if k >= 0:
        global r
        r += [s]
        f(s + A[k - 1], k - 1)
        f(s, k - 1)

f(0, n)
eval(input())
for e in map(int, input().split()):
    print((["no", "yes"][e in r]))

n = int(eval(input()))
A = list(map(int, input().split()))
r = set()

def f(s, k):
    if k >= 0:
        global r
        r.add(s)
        f(s + A[k - 1], k - 1)
        f(s, k - 1)

f(0, n)
eval(input())
for e in map(int, input().split()):
    print((["no", "yes"][e in r]))


Input:
N = int(eval(input()))

print(((N+1)>>1))

N = int(eval(input()))
print(((N + 1) >> 1))


Input:
from collections import Counter

n = int(eval(input()))

s = []

for _ in range(n):

    s.append(int(eval(input())))

cnt = Counter([0, s[0]])

if len(s) > 1:

    for si in s[1:]:

        tmp = Counter([])

        for k,v in list(cnt.items()):

            tmp[k + si] = v

        cnt += tmp

key_list = sorted(list(cnt.keys()), reverse=True)

for k in key_list:

    if k == 0:

        print(k)

        break

    elif k%10 == 0:

        continue

    print(k)

    break

n = int(eval(input()))

s = []

for _ in range(n):

    s.append(int(eval(input())))

total = sum(s)

if total % 10 != 0:

    print(total)

else:

    s.sort()

    min_s = total

    for si in s:

        if si % 10 != 0:

            min_s = si

            break

    print((total - min_s))

from collections import Counter

n = int(eval(input()))
s = []
for _ in range(n):
    s.append(int(eval(input())))
cnt = Counter([0, s[0]])
if len(s) > 1:
    for si in s[1:]:
        tmp = Counter([])
        for k, v in list(cnt.items()):
            tmp[k + si] = v
        cnt += tmp
key_list = sorted(list(cnt.keys()), reverse=True)
for k in key_list:
    if k == 0:
        print(k)
        break
    elif k % 10 == 0:
        continue
    print(k)
    break

-key_list = sorted(list(cnt.keys()), reverse=True)


Input:
import sys

if sys.argv[-1] == 'ONLINE_JUDGE':

    import os, zlib, base64

    open('solve.pyx', 'wb').write(zlib.decompress(base64.b85decode("c$`&I!ES>v480@q58h!atm#yy9VRsPBOM1P1R4zjN;6H{*Uu)DfG;HPJ=@O?ts4jEja1J!?~Lt0nPD28hd~cF?bD=Xf%^5=(LPV;u<v!hiYAA)(~D@S(wK4OJMGmKogksHzD*O==oaXBc{y{`Fr`W8luZIog@8c76Wq+79@~t>c^(s~w9Rs`V`us@O@LyhqyPmKoCExGHNA#n5phT&7e`qhVbc=x4zF(|NT=~DGF(lOmEsIX(ws;WNT>a`v!FJ<dX0^CY!`6vkLphstf|Ghyk}ydX1u!R@-5#rU}V$73K#^S;7N@DFW7-)le`q#WIVQ`14Bv66J?Y)d#Z|jv4v55U(V)=(H7F+#YVNjas$(d2oDv=a<|rbybt=wdP8t{s)KuoJIX!8-F$@Ra>r_}w?$<gs;x7Jk!>Cy;51zfTT$iwsPi>V!e5yk9-B{lpk>lD|KRh>h5")))

    os.system('cythonize -i -3 -b solve.pyx')

import solve

import sys

if sys.argv[-1] == 'ONLINE_JUDGE':

    import os, zlib, base64

    open('solve.pyx', 'wb').write(zlib.decompress(base64.b85decode("c${TY%Wi`(5WFMt58Fc(Xq*VD9x7D&BPj>l7_bTkIj*Ai>${5yulNExGoBr<UD>{aRttH)I;%|$Qg=gd9dxR@Di;P73FNP9dUGDQ<!!6lSu|K~YBh-_ms0mLUn?gYZW#)-aa9<|QdNMzm)C?=0Ye!0PSL>Nlrr!HyueleslJL(9LLK>v^G%;rmuCIg#qB2DZxNO4vB|vjcygBlZci;a!M4%3#=<-KH%*=17Q{aUKnzd7$r^Mh?)~>JZY8tu?FNSSF3obEX4)B&4>QOg%{W&$?iM3r$#)#@1-i<G$3Tv!!YO=a7HK93>>2bH|?5DKSQZ$O1|v2Wz}2I=r-M5)Wxd_@vZhgv>n8k$Q*}~?$i?{b`*|*!&44o)o(qXPyC2tN78cW$sb`#As%5$;I{B+f6Pb!JtGS5K99vu#l*|yora61crqIw#8`%bf6>w5x%@H*ya+t$KlVq{`2")))

    os.system('cythonize -i -3 -b solve.pyx')

import solve

import sys

if sys.argv[-1] == "ONLINE_JUDGE":
    import os, zlib, base64

    open("solve.pyx", "wb").write(
        zlib.decompress(
            base64.b85decode(
                "c$`&I!ES>v480@q58h!atm#yy9VRsPBOM1P1R4zjN;6H{*Uu)DfG;HPJ=@O?ts4jEja1J!?~Lt0nPD28hd~cF?bD=Xf%^5=(LPV;u<v!hiYAA)(~D@S(wK4OJMGmKogksHzD*O==oaXBc{y{`Fr`W8luZIog@8c76Wq+79@~t>c^(s~w9Rs`V`us@O@LyhqyPmKoCExGHNA#n5phT&7e`qhVbc=x4zF(|NT=~DGF(lOmEsIX(ws;WNT>a`v!FJ<dX0^CY!`6vkLphstf|Ghyk}ydX1u!R@-5#rU}V$73K#^S;7N@DFW7-)le`q#WIVQ`14Bv66J?Y)d#Z|jv4v55U(V)=(H7F+#YVNjas$(d2oDv=a<|rbybt=wdP8t{s)KuoJIX!8-F$@Ra>r_}w?$<gs;x7Jk!>Cy;51zfTT$iwsPi>V!e5yk9-B{lpk>lD|KRh>h5"
            )
        )
    )
    os.system("cythonize -i -3 -b solve.pyx")
import solve

import sys

if sys.argv[-1] == "ONLINE_JUDGE":
    import os, zlib, base64

    open("solve.pyx", "wb").write(
        zlib.decompress(
            base64.b85decode(
                "c${TY%Wi`(5WFMt58Fc(Xq*VD9x7D&BPj>l7_bTkIj*Ai>${5yulNExGoBr<UD>{aRttH)I;%|$Qg=gd9dxR@Di;P73FNP9dUGDQ<!!6lSu|K~YBh-_ms0mLUn?gYZW#)-aa9<|QdNMzm)C?=0Ye!0PSL>Nlrr!HyueleslJL(9LLK>v^G%;rmuCIg#qB2DZxNO4vB|vjcygBlZci;a!M4%3#=<-KH%*=17Q{aUKnzd7$r^Mh?)~>JZY8tu?FNSSF3obEX4)B&4>QOg%{W&$?iM3r$#)#@1-i<G$3Tv!!YO=a7HK93>>2bH|?5DKSQZ$O1|v2Wz}2I=r-M5)Wxd_@vZhgv>n8k$Q*}~?$i?{b`*|*!&44o)o(qXPyC2tN78cW$sb`#As%5$;I{B+f6Pb!JtGS5K99vu#l*|yora61crqIw#8`%bf6>w5x%@H*ya+t$KlVq{`2"
            )
        )
    )
    os.system("cythonize -i -3 -b solve.pyx")
import solve

-                "c$`&I!ES>v480@q58h!atm#yy9VRsPBOM1P1R4zjN;6H{*Uu)DfG;HPJ=@O?ts4jEja1J!?~Lt0nPD28hd~cF?bD=Xf%^5=(LPV;u<v!hiYAA)(~D@S(wK4OJMGmKogksHzD*O==oaXBc{y{`Fr`W8luZIog@8c76Wq+79@~t>c^(s~w9Rs`V`us@O@LyhqyPmKoCExGHNA#n5phT&7e`qhVbc=x4zF(|NT=~DGF(lOmEsIX(ws;WNT>a`v!FJ<dX0^CY!`6vkLphstf|Ghyk}ydX1u!R@-5#rU}V$73K#^S;7N@DFW7-)le`q#WIVQ`14Bv66J?Y)d#Z|jv4v55U(V)=(H7F+#YVNjas$(d2oDv=a<|rbybt=wdP8t{s)KuoJIX!8-F$@Ra>r_}w?$<gs;x7Jk!>Cy;51zfTT$iwsPi>V!e5yk9-B{lpk>lD|KRh>h5"

+                "c${TY%Wi`(5WFMt58Fc(Xq*VD9x7D&BPj>l7_bTkIj*Ai>${5yulNExGoBr<UD>{aRttH)I;%|$Qg=gd9dxR@Di;P73FNP9dUGDQ<!!6lSu|K~YBh-_ms0mLUn?gYZW#)-aa9<|QdNMzm)C?=0Ye!0PSL>Nlrr!HyueleslJL(9LLK>v^G%;rmuCIg#qB2DZxNO4vB|vjcygBlZci;a!M4%3#=<-KH%*=17Q{aUKnzd7$r^Mh?)~>JZY8tu?FNSSF3obEX4)B&4>QOg%{W&$?iM3r$#)#@1-i<G$3Tv!!YO=a7HK93>>2bH|?5DKSQZ$O1|v2Wz}2I=r-M5)Wxd_@vZhgv>n8k$Q*}~?$i?{b`*|*!&44o)o(qXPyC2tN78cW$sb`#As%5$;I{B+f6Pb!JtGS5K99vu#l*|yora61crqIw#8`%bf6>w5x%@H*ya+t$KlVq{`2"


Input:
N, T, *AB = list(map(int, open(0).read().split()))

dp = [0] * (T + max(AB[::2]))

for w, v in sorted(zip(*[iter(AB)] * 2)):

    for i in reversed(list(range(T))):

        dp[i + w] = max(dp[i + w], dp[i] + v)

print((max(dp)))

def main():

    N, T, *AB = list(map(int, open(0).read().split()))

    dp = [0] * (T + max(AB[::2]))

    for w, v in sorted(zip(*[iter(AB)] * 2)):

        for i in reversed(list(range(T))):

            dp[i + w] = max(dp[i + w], dp[i] + v)

    print((max(dp)))

main()

-N, T, *AB = list(map(int, open(0).read().split()))

-for w, v in sorted(zip(*[iter(AB)] * 2)):

-        dp[i + w] = max(dp[i + w], dp[i] + v)

+    N, T, *AB = list(map(int, open(0).read().split()))

+    for w, v in sorted(zip(*[iter(AB)] * 2)):

+        for i in reversed(list(range(T))):

+            dp[i + w] = max(dp[i + w], dp[i] + v)


Input:
code = r"""

# distutils: language=c++

# distutils: include_dirs=/home/contestant/.local/lib/python3.8/site-packages/numpy/core/include

from libcpp cimport *

from libcpp.vector cimport vector

cdef extern from "/opt/atcoder-stl/atcoder/dsu.hpp" namespace "atcoder":

    cdef cppclass dsu:

        dsu()

        dsu(int n)

        int merge(int a, int b)

        bool same(int a, int b)

        int leader(int a)

        int size(int a)

        vector[vector[int]] groups()

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

cdef dsu uf = dsu(N)

for _ in range(Q):

    t, u, v = map(int, input().split())

    if t == 0:

        uf.merge(u, v)

    else:

        if uf.same(u, v):

            print(1)

        else:

            print(0)

"""

import os

import sys

if sys.argv[-1] == 'ONLINE_JUDGE':

    open('solve.pyx', 'w').write(code)

    os.system('cythonize -i -3 -b solve.pyx')

import solve

code = r"""

# distutils: language=c++

# distutils: include_dirs=/home/contestant/.local/lib/python3.8/site-packages/numpy/core/include

from libcpp cimport *

from libcpp.vector cimport vector

cdef extern from "/opt/atcoder-stl/atcoder/dsu.hpp" namespace "atcoder":

    cdef cppclass dsu:

        dsu()

        dsu(int n)

        int merge(int a, int b)

        bool same(int a, int b)

        int leader(int a)

        int size(int a)

        vector[vector[int]] groups()

import sys

input = sys.stdin.buffer.readline

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

cdef dsu uf = dsu(N)

for _ in range(Q):

    t, u, v = map(int, input().split())

    if t == 0:

        uf.merge(u, v)

    else:

        if uf.same(u, v):

            print(1)

        else:

            print(0)

"""

import os

import sys

if sys.argv[-1] == 'ONLINE_JUDGE':

    open('solve.pyx', 'w').write(code)

    os.system('cythonize -i -3 -b solve.pyx')

import solve

code = r"""
# distutils: language=c++
# distutils: include_dirs=/home/contestant/.local/lib/python3.8/site-packages/numpy/core/include
from libcpp cimport *
from libcpp.vector cimport vector
cdef extern from "/opt/atcoder-stl/atcoder/dsu.hpp" namespace "atcoder":
    cdef cppclass dsu:
        dsu()
        dsu(int n)
        int merge(int a, int b)
        bool same(int a, int b)
        int leader(int a)
        int size(int a)
        vector[vector[int]] groups()
N, Q = map(int, input().split())
cdef dsu uf = dsu(N)
for _ in range(Q):
    t, u, v = map(int, input().split())
    if t == 0:
        uf.merge(u, v)
    else:
        if uf.same(u, v):
            print(1)
        else:
            print(0)
"""
import os
import sys

if sys.argv[-1] == "ONLINE_JUDGE":
    open("solve.pyx", "w").write(code)
    os.system("cythonize -i -3 -b solve.pyx")
import solve

code = r"""
# distutils: language=c++
# distutils: include_dirs=/home/contestant/.local/lib/python3.8/site-packages/numpy/core/include
from libcpp cimport *
from libcpp.vector cimport vector
cdef extern from "/opt/atcoder-stl/atcoder/dsu.hpp" namespace "atcoder":
    cdef cppclass dsu:
        dsu()
        dsu(int n)
        int merge(int a, int b)
        bool same(int a, int b)
        int leader(int a)
        int size(int a)
        vector[vector[int]] groups()
import sys
input = sys.stdin.buffer.readline
N, Q = map(int, input().split())
cdef dsu uf = dsu(N)
for _ in range(Q):
    t, u, v = map(int, input().split())
    if t == 0:
        uf.merge(u, v)
    else:
        if uf.same(u, v):
            print(1)
        else:
            print(0)
"""
import os
import sys

if sys.argv[-1] == "ONLINE_JUDGE":
    open("solve.pyx", "w").write(code)
    os.system("cythonize -i -3 -b solve.pyx")
import solve

+import sys
+input = sys.stdin.buffer.readline


Input:
N = int(eval(input()))

ans = N * (N + 1) * (N + 2) // 6

for _ in range(N - 1):

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

    if u > v:

        u, v = v, u

    ans -= u * (N + 1 - v)

print(ans)

import sys

input = sys.stdin.readline

N = int(eval(input()))

ans = N * (N + 1) * (N + 2) // 6

for _ in range(N - 1):

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

    if u > v:

        u, v = v, u

    ans -= u * (N + 1 - v)

print(ans)

+import sys
+
+input = sys.stdin.readline


Input:
def main():

    N=int(input())

    edge = [[]for _ in range(N)]

    for _ in range(N-1):

        u,v,w = map(int,input().split())

        u,v = u-1,v-1

        edge[u].append((v,w))

        edge[v].append((u,w))

    color = [-1]*N

    color[0]=0

    stack = [(0,0)]

    while stack:

        v,col = stack.pop()

        for to,dist in edge[v]:

            if color[to]!=-1:

                continue

            c = (col+dist)%2  # 色

            color[to] = c

            stack.append((to,c))

    print(*color,sep="\n")

if __name__ == '__main__':

    main()

import sys

input = sys.stdin.readline

def main():

    N=int(input())

    edge = [[]for _ in range(N)]

    for _ in range(N-1):

        u,v,w = map(int,input().split())

        u,v = u-1,v-1

        edge[u].append((v,w))

        edge[v].append((u,w))

    color = [-1]*N

    color[0]=0

    stack = [(0,0)]

    while stack:

        v,col = stack.pop()

        for to,dist in edge[v]:

            if color[to]!=-1:

                continue

            c = (col+dist)%2  # 色

            color[to] = c

            stack.append((to,c))

    print(*color,sep="\n")

if __name__ == '__main__':

    main()

import sys

input = sys.stdin.readline

def main():
    N = int(input())
    edge = [[] for _ in range(N)]
    for _ in range(N - 1):
        u, v, w = map(int, input().split())
        u, v = u - 1, v - 1
        edge[u].append((v, w))
        edge[v].append((u, w))
    color = [-1] * N
    color[0] = 0
    stack = [(0, 0)]
    while stack:
        v, col = stack.pop()
        for to, dist in edge[v]:
            if color[to] != -1:
                continue
            c = (col + dist) % 2  # 色
            color[to] = c
            stack.append((to, c))
    print(*color, sep="\n")

if __name__ == "__main__":
    main()

+import sys
+
+input = sys.stdin.readline
+
+


Input:
n = int(eval(input()))

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

x = 0

M = a[0]

if n != 1:

    for i in range(n - 1):

        if M > a[i + 1]:

            x += (M - a[i + 1])

        else:

            M = a[i + 1]

print(x)

n = int(eval(input()))

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

x = 0

h = a[0]

for i in range(n):

    if a[i] > h:

        h = a[i]

    else:

        x += (h - a[i])

print(x)

n = int(eval(input()))
a = list(map(int, input().split()))
x = 0
M = a[0]
if n != 1:
    for i in range(n - 1):
        if M > a[i + 1]:
            x += M - a[i + 1]
        else:
            M = a[i + 1]
print(x)

n = int(eval(input()))
a = list(map(int, input().split()))
x = 0
h = a[0]
for i in range(n):
    if a[i] > h:
        h = a[i]
    else:
        x += h - a[i]
print(x)


Input:
N=int(input())

A=[int(i) for i in input().split()]

a=sum(A)//2#sumx

P=[0]*(N+1)

Q=[0]*(N+1)

for i in range(1,N+1):

    if i%2==1:

        P[i]+=P[i-1]+A[i-1]

        Q[i] += Q[i - 1]

    else:

        Q[i]+=Q[i-1]+A[i-1]

        P[i] += P[i - 1]

#print(a,P,Q)

ans=[]

for i in range(1,N+1):

    x=0

    if i%2==1:

        x+=P[N]-P[i-1]

        x+=Q[i]-Q[0]

    else:

        x += Q[N] - Q[i - 1]

        x += P[i] - P[0]

    print(2*(x-a),end=' ')

    #ans.append(2*(x-a))

#print(ans,end=' ')


Input:
X,Y,Z=list(map(int,input().split()))

ans=0

K=Z

while(True):

    if K+Y+Z>X:

        break

    K+=Y+Z

    ans+=1

print(ans)

X,Y,Z=list(map(int,input().split()))

A=X-Z

ans=A//(Y+Z)

print(ans)

X, Y, Z = list(map(int, input().split()))
ans = 0
K = Z
while True:
    if K + Y + Z > X:
        break
    K += Y + Z
    ans += 1
print(ans)

X, Y, Z = list(map(int, input().split()))
A = X - Z
ans = A // (Y + Z)
print(ans)

-ans = 0
-K = Z
-while True:
-    if K + Y + Z > X:
-        break
-    K += Y + Z
-    ans += 1
+A = X - Z
+ans = A // (Y + Z)


Input:
#DFS

from collections import deque

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

G = [[] for _ in range(N)]

for i in range(M):

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

  G[a-1].append(b-1)

  G[b-1].append(a-1)

stack = deque([(0, 0)])

visited = [0] * N

depth = 0

ans = 0

while stack:

  now, depth = stack.pop()

  if depth == N-1:

    ans += 1

    continue

  visited[depth] = now

  for nxt in G[now]:

    if nxt not in visited[:depth+1]:

      stack.append((nxt, depth+1))

print(ans)

#順列全探索

from itertools import permutations

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

G = [[0]*N for _ in range(N)]

for i in range(M):

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

  G[a-1][b-1] = 1

  G[b-1][a-1] = 1

perms = permutations(list(range(1, N)))

ans = 0

for perm in perms:

  now = 0

  for v in perm:

    if G[now][v] == 0:

      break

    now = v

  else:

    ans += 1

print(ans)

# DFS
from collections import deque

N, M = list(map(int, input().split()))
G = [[] for _ in range(N)]
for i in range(M):
    a, b = list(map(int, input().split()))
    G[a - 1].append(b - 1)
    G[b - 1].append(a - 1)
stack = deque([(0, 0)])
visited = [0] * N
depth = 0
ans = 0
while stack:
    now, depth = stack.pop()
    if depth == N - 1:
        ans += 1
        continue
    visited[depth] = now
    for nxt in G[now]:
        if nxt not in visited[: depth + 1]:
            stack.append((nxt, depth + 1))
print(ans)

# 順列全探索
from itertools import permutations

N, M = list(map(int, input().split()))
G = [[0] * N for _ in range(N)]
for i in range(M):
    a, b = list(map(int, input().split()))
    G[a - 1][b - 1] = 1
    G[b - 1][a - 1] = 1
perms = permutations(list(range(1, N)))
ans = 0
for perm in perms:
    now = 0
    for v in perm:
        if G[now][v] == 0:
            break
        now = v
    else:
        ans += 1
print(ans)

+perms = permutations(list(range(1, N)))

-        if nxt not in visited[: depth + 1]:

-            stack.append((nxt, depth + 1))


Input:
n=int(input())

a=[]

for i,j in enumerate(map(int,input().split())):

    a.append([j,i])

a.sort(reverse=True)

now=0

nx=0

ans=[0]*n

cnt=0

idx=10**6

while now<n:

    while nx<n and a[now][0]==a[nx][0]:

        idx=min(idx,a[nx][1])

        cnt+=1

        nx+=1

    if nx==n:

        ans[idx]+=cnt*a[now][0]

    else:

        ans[idx]+=(a[now][0]-a[nx][0])*cnt

    now=nx

for i in range(n):

    print(ans[i])

from collections import defaultdict

class BIT():

    def __init__(self,size):

        self.size=size

        self.node=[0]*(size+1)

    def sum(self,idx):

        ret=0

        while idx>0:

            ret+=self.node[idx]

            idx-=idx&(-idx)

        return ret

    def add(self,idx,x):

        while idx<=self.size:

            self.node[idx]+=x

            idx+=idx&(-idx)

n=int(input())

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

check=[]

d=defaultdict(int)

li=set([])

now=0

for i in range(n):

    if now<a[i]:

        now=a[i]

        check.append(i)

    d[a[i]]+=1

    li.add(a[i])

li=sorted(list(li))

b=[0]*(n+5)

i=0

idx=dict()

for key in li:

    b[i]=d[key]

    idx[key]=i

    i+=1

ans=[0]*(n+1)

for i in range(len(check)-2,-1,-1):

    cnt=0

    for j in range(idx[a[check[i]]]+1,idx[a[check[i+1]]]+1):

        ans[check[i+1]]+=b[j]*(li[j]-a[check[i]])

        cnt+=b[j]

    b[idx[a[check[i]]]]+=cnt

for i in range(1,n):

    if a[0]<a[i]:

        a[i]=a[0]

ans[0]=sum(a)

for i in range(n):

    print(ans[i])

n = int(input())
a = []
for i, j in enumerate(map(int, input().split())):
    a.append([j, i])
a.sort(reverse=True)
now = 0
nx = 0
ans = [0] * n
cnt = 0
idx = 10**6
while now < n:
    while nx < n and a[now][0] == a[nx][0]:
        idx = min(idx, a[nx][1])
        cnt += 1
        nx += 1
    if nx == n:
        ans[idx] += cnt * a[now][0]
    else:
        ans[idx] += (a[now][0] - a[nx][0]) * cnt
    now = nx
for i in range(n):
    print(ans[i])

from collections import defaultdict

class BIT:
    def __init__(self, size):
        self.size = size
        self.node = [0] * (size + 1)

    def sum(self, idx):
        ret = 0
        while idx > 0:
            ret += self.node[idx]
            idx -= idx & (-idx)
        return ret

    def add(self, idx, x):
        while idx <= self.size:
            self.node[idx] += x
            idx += idx & (-idx)

n = int(input())
a = list(map(int, input().split()))
check = []
d = defaultdict(int)
li = set([])
now = 0
for i in range(n):
    if now < a[i]:
        now = a[i]
        check.append(i)
    d[a[i]] += 1
    li.add(a[i])
li = sorted(list(li))
b = [0] * (n + 5)
i = 0
idx = dict()
for key in li:
    b[i] = d[key]
    idx[key] = i
    i += 1
ans = [0] * (n + 1)
for i in range(len(check) - 2, -1, -1):
    cnt = 0
    for j in range(idx[a[check[i]]] + 1, idx[a[check[i + 1]]] + 1):
        ans[check[i + 1]] += b[j] * (li[j] - a[check[i]])
        cnt += b[j]
    b[idx[a[check[i]]]] += cnt
for i in range(1, n):
    if a[0] < a[i]:
        a[i] = a[0]
ans[0] = sum(a)
for i in range(n):
    print(ans[i])

-for i, j in enumerate(map(int, input().split())):

-    while nx < n and a[now][0] == a[nx][0]:

+for i in range(len(check) - 2, -1, -1):

+    for j in range(idx[a[check[i]]] + 1, idx[a[check[i + 1]]] + 1):

+        ans[check[i + 1]] += b[j] * (li[j] - a[check[i]])


Input:
def c_takahashi_information(C):

    a = [min(C[0]), min(C[1]), min(C[2])]

    tmp = [[C[i][j] - a[i] for j in range(3)] for i in range(3)]

    b = list(map(list, set(map(tuple, tmp))))

    for bb in b:

        f = True

        for i in range(3):

            for j in range(3):

                if a[i] + bb[j] != C[i][j]:

                    f = False

                    break

            if not f:

                break

        if f:

            return 'Yes'

    return 'No'

C = [[int(i) for i in input().split()] for j in range(3)]

print((c_takahashi_information(C)))

def c_takahashi_information(C):

    b = [C[0][i] - 0 for i in range(3)]

    a = [0] + [C[i][0] - b[0] for i in range(1, 3)]  # a_1=0と仮定してよい

    for i in range(3):

        for j in range(3):

            if a[i] + b[j] != C[i][j]:

                return 'No'

    return 'Yes'

C = [[int(i) for i in input().split()] for j in range(3)]

print((c_takahashi_information(C)))

def c_takahashi_information(C):
    a = [min(C[0]), min(C[1]), min(C[2])]
    tmp = [[C[i][j] - a[i] for j in range(3)] for i in range(3)]
    b = list(map(list, set(map(tuple, tmp))))
    for bb in b:
        f = True
        for i in range(3):
            for j in range(3):
                if a[i] + bb[j] != C[i][j]:
                    f = False
                    break
            if not f:
                break
        if f:
            return "Yes"
    return "No"

C = [[int(i) for i in input().split()] for j in range(3)]
print((c_takahashi_information(C)))

def c_takahashi_information(C):
    b = [C[0][i] - 0 for i in range(3)]
    a = [0] + [C[i][0] - b[0] for i in range(1, 3)]  # a_1=0と仮定してよい
    for i in range(3):
        for j in range(3):
            if a[i] + b[j] != C[i][j]:
                return "No"
    return "Yes"

C = [[int(i) for i in input().split()] for j in range(3)]
print((c_takahashi_information(C)))

-    tmp = [[C[i][j] - a[i] for j in range(3)] for i in range(3)]

-    b = list(map(list, set(map(tuple, tmp))))

+    b = [C[0][i] - 0 for i in range(3)]


Input:
pqr = list(map(int, input().split()))

pqr.sort()

print((sum(pqr[:2])))

nums = list(map(int, input().split()))

nums.sort()

print((sum(nums[:2])))