1523_E. Crypto Lights

<image>

To monitor cryptocurrency exchange rates trader William invented a wonderful device consisting of n lights arranged in a row. The device functions in the following way:

Initially, all lights on William's device are turned off. At the beginning of a new iteration the device randomly, with a uniform distribution, picks a light that is turned off and turns it on, telling William which cryptocurrency he should invest in. After this iteration if any k consecutive lights contain more than one turned on light, then the device finishes working.

William doesn't like uncertainty, so he wants you to calculate the expected value of the number of lights that are turned on in the device after it finishes working.

Input

Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10). Description of the test cases follows.

The only line for each test case contains two integers n and k (2 ≤ k ≤ n ≤ 10^5), which are the total number of lights and the length of subsegment of lights that are being checked, respectively.

Output

For each test case print the answer, modulo 10^9+7.

Formally, let M = 10^9+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not ≡ 0 \pmod{M}. Output the integer equal to p ⋅ q^{-1} mod M. In other words, output such an integer x that 0 ≤ x < M and x ⋅ q ≡ p \pmod{M}.

Example

Input

3
3 2
15 2
40 15

Output

333333338
141946947
329622137

Note

Explanation of the first sample test case:

Let's write out all possible sequences of light toggles, which will make the device complete its operation:

  1. (1, 2) — 2 lights are turned on
  2. (1, 3, 2) — 3 lights are turned on
  3. (2, 1) — 2 lights are turned on
  4. (2, 3) — 2 lights are turned on
  5. (3, 2) — 2 lights are turned on
  6. (3, 1, 2) — 3 lights are turned on

Then the final expected value will be equal to 2/6 + 3/6 + 2/6 + 2/6 + 2/6 + 3/6 = 14/6 = 7/3.

Then the required output will be 333333338, since 333333338 ⋅ 3 ≡ 7 \pmod{10^9+7}.

```python

def divisors(M):
    d=[]
    i=1
    while M>=i**2:
        if M%i==0:
            d.append(i)
            if i**2!=M:
                d.append(M//i)
        i=i+1
    return d

def popcount(x):
    x = x - ((x >> 1) & 0x55555555)
    x = (x & 0x33333333) + ((x >> 2) & 0x33333333)
    x = (x + (x >> 4)) & 0x0f0f0f0f
    x = x + (x >> 8)
    x = x + (x >> 16)
    return x & 0x0000007f

def eratosthenes(n):
    res=[0 for i in range(n+1)]
    prime=set([])
    for i in range(2,n+1):
        if not res[i]:
            prime.add(i)
            for j in range(1,n//i+1):
                res[i*j]=1
    return prime

def factorization(n):
    res=[]
    for p in prime:
        if n%p==0:
            while n%p==0:
                n//=p
            res.append(p)
    if n!=1:
        res.append(n)
    return res

def euler_phi(n):
    res = n
    for x in range(2,n+1):
        if x ** 2 > n:
            break
        if n%x==0:
            res = res//x * (x-1)
            while n%x==0:
                n //= x
    if n!=1:
        res = res//n * (n-1)
    return res

def ind(b,n):
    res=0
    while n%b==0:
        res+=1
        n//=b
    return res

def isPrimeMR(n):
    d = n - 1
    d = d // (d & -d)
    L = [2, 3, 5, 7, 11, 13, 17]
    for a in L:
        t = d
        y = pow(a, t, n)
        if y == 1: continue
        while y != n - 1:
            y = (y * y) % n
            if y == 1 or t == n - 1: return 0
            t <<= 1
    return 1
def findFactorRho(n):
    from math import gcd
    m = 1 << n.bit_length() // 8
    for c in range(1, 99):
        f = lambda x: (x * x + c) % n
        y, r, q, g = 2, 1, 1, 1
        while g == 1:
            x = y
            for i in range(r):
                y = f(y)
            k = 0
            while k < r and g == 1:
                ys = y
                for i in range(min(m, r - k)):
                    y = f(y)
                    q = q * abs(x - y) % n
                g = gcd(q, n)
                k += m
            r <<= 1
        if g == n:
            g = 1
            while g == 1:
                ys = f(ys)
                g = gcd(abs(x - ys), n)
        if g < n:
            if isPrimeMR(g): return g
            elif isPrimeMR(n // g): return n // g
            return findFactorRho(g)
def primeFactor(n):
    i = 2
    ret = {}
    rhoFlg = 0
    while i*i <= n:
        k = 0
        while n % i == 0:
            n //= i
            k += 1
        if k: ret[i] = k
        i += 1 + i % 2
        if i == 101 and n >= 2 ** 20:
            while n > 1:
                if isPrimeMR(n):
                    ret[n], n = 1, 1
                else:
                    rhoFlg = 1
                    j = findFactorRho(n)
                    k = 0
                    while n % j == 0:
                        n //= j
                        k += 1
                    ret[j] = k

    if n > 1: ret[n] = 1
    if rhoFlg: ret = {x: ret[x] for x in sorted(ret)}
    return ret

def divisors(n):
    res = [1]
    prime = primeFactor(n)
    for p in prime:
        newres = []
        for d in res:
            for j in range(prime[p]+1):
                newres.append(d*p**j)
        res = newres
    res.sort()
    return res

def xorfactorial(num):
    if num==0:
        return 0
    elif num==1:
        return 1
    elif num==2:
        return 3
    elif num==3:
        return 0
    else:
        x=baseorder(num)
        return (2**x)*((num-2**x+1)%2)+function(num-2**x)

def xorconv(n,X,Y):
    if n==0:
        res=[(X[0]*Y[0])%mod]
        return res
    x=[X[i]+X[i+2**(n-1)] for i in range(2**(n-1))]
    y=[Y[i]+Y[i+2**(n-1)] for i in range(2**(n-1))]
    z=[X[i]-X[i+2**(n-1)] for i in range(2**(n-1))]
    w=[Y[i]-Y[i+2**(n-1)] for i in range(2**(n-1))]
    res1=xorconv(n-1,x,y)
    res2=xorconv(n-1,z,w)
    former=[(res1[i]+res2[i])*inv for i in range(2**(n-1))]
    latter=[(res1[i]-res2[i])*inv for i in range(2**(n-1))]
    former=list(map(lambda x:x%mod,former))
    latter=list(map(lambda x:x%mod,latter))
    return former+latter

def merge_sort(A,B):
    pos_A,pos_B = 0,0
    n,m = len(A),len(B)
    res = []
    while pos_A < n and pos_B < m:
        a,b = A[pos_A],B[pos_B]
        if a < b:
            res.append(a)
            pos_A += 1
        else:
            res.append(b)
            pos_B += 1
    res += A[pos_A:]
    res += B[pos_B:]
    return res

class UnionFindVerSize():
    def __init__(self, N):
        self._parent = [n for n in range(0, N)]
        self._size = [1] * N
        self.group = N

    def find_root(self, x):
        if self._parent[x] == x: return x
        self._parent[x] = self.find_root(self._parent[x])
        stack = [x]
        while self._parent[stack[-1]]!=stack[-1]:
            stack.append(self._parent[stack[-1]])
        for v in stack:
            self._parent[v] = stack[-1]
        return self._parent[x]

    def unite(self, x, y):
        gx = self.find_root(x)
        gy = self.find_root(y)
        if gx == gy: return

        self.group -= 1

        if self._size[gx] < self._size[gy]:
            self._parent[gx] = gy
            self._size[gy] += self._size[gx]
        else:
            self._parent[gy] = gx
            self._size[gx] += self._size[gy]

    def get_size(self, x):
        return self._size[self.find_root(x)]

    def is_same_group(self, x, y):
        return self.find_root(x) == self.find_root(y)

class WeightedUnionFind():
    def __init__(self,N):
        self.parent = [i for i in range(N)]
        self.size = [1 for i in range(N)]
        self.val = [0 for i in range(N)]
        self.flag = True
        self.edge = [[] for i in range(N)]

    def dfs(self,v,pv):
        stack = [(v,pv)]
        new_parent = self.parent[pv]
        while stack:
            v,pv = stack.pop()
            self.parent[v] = new_parent
            for nv,w in self.edge[v]:
                if nv!=pv:
                    self.val[nv] = self.val[v] + w
                    stack.append((nv,v))

    def unite(self,x,y,w):
        if not self.flag:
            return
        if self.parent[x]==self.parent[y]:
            self.flag = (self.val[x] - self.val[y] == w)
            return

        if self.size[self.parent[x]]>self.size[self.parent[y]]:
            self.edge[x].append((y,-w))
            self.edge[y].append((x,w))
            self.size[x] += self.size[y]
            self.val[y] = self.val[x] - w
            self.dfs(y,x)
        else:
            self.edge[x].append((y,-w))
            self.edge[y].append((x,w))
            self.size[y] += self.size[x]
            self.val[x] = self.val[y] + w
            self.dfs(x,y)

class Dijkstra():
    class Edge():
        def __init__(self, _to, _cost):
            self.to = _to
            self.cost = _cost

    def __init__(self, V):
        self.G = [[] for i in range(V)]
        self._E = 0
        self._V = V

    @property
    def E(self):
        return self._E

    @property
    def V(self):
        return self._V

    def add_edge(self, _from, _to, _cost):
        self.G[_from].append(self.Edge(_to, _cost))
        self._E += 1

    def shortest_path(self, s):
        import heapq
        que = []
        d = [10**15] * self.V
        d[s] = 0
        heapq.heappush(que, (0, s))

        while len(que) != 0:
            cost, v = heapq.heappop(que)
            if d[v] < cost: continue

            for i in range(len(self.G[v])):
                e = self.G[v][i]
                if d[e.to] > d[v] + e.cost:
                    d[e.to] = d[v] + e.cost
                    heapq.heappush(que, (d[e.to], e.to))
        return d

#Z[i]:length of the longest list starting from S[i] which is also a prefix of S
#O(|S|)
def Z_algorithm(s):
    N = len(s)
    Z_alg = [0]*N

    Z_alg[0] = N
    i = 1
    j = 0
    while i < N:
        while i+j < N and s[j] == s[i+j]:
            j += 1
        Z_alg[i] = j
        if j == 0:
            i += 1
            continue
        k = 1
        while i+k < N and k + Z_alg[k]<j:
            Z_alg[i+k] = Z_alg[k]
            k += 1
        i += k
        j -= k
    return Z_alg

class BIT():
    def __init__(self,n,mod=0):
        self.BIT = [0]*(n+1)
        self.num = n
        self.mod = mod

    def query(self,idx):
        res_sum = 0
        mod = self.mod
        while idx > 0:
            res_sum += self.BIT[idx]
            if mod:
                res_sum %= mod
            idx -= idx&(-idx)
        return res_sum

    #Ai += x O(logN)
    def update(self,idx,x):
        mod = self.mod
        while idx <= self.num:
            self.BIT[idx] += x
            if mod:
                self.BIT[idx] %= mod
            idx += idx&(-idx)
        return

class dancinglink():
    def __init__(self,n,debug=False):
        self.n = n
        self.debug = debug
        self._left = [i-1 for i in range(n)]
        self._right = [i+1 for i in range(n)]
        self.exist = [True for i in range(n)]

    def pop(self,k):
        if self.debug:
            assert self.exist[k]
        L = self._left[k]
        R = self._right[k]
        if L!=-1:
            if R!=self.n:
                self._right[L],self._left[R] = R,L
            else:
                self._right[L] = self.n
        elif R!=self.n:
            self._left[R] = -1
        self.exist[k] = False

    def left(self,idx,k=1):
        if self.debug:
            assert self.exist[idx]
        res = idx
        while k:
            res = self._left[res]
            if res==-1:
                break
            k -= 1
        return res

    def right(self,idx,k=1):
        if self.debug:
            assert self.exist[idx]
        res = idx
        while k:
            res = self._right[res]
            if res==self.n:
                break
            k -= 1
        return res

class SparseTable():
    def __init__(self,A,merge_func,ide_ele):
        N=len(A)
        n=N.bit_length()
        self.table=[[ide_ele for i in range(n)] for i in range(N)]
        self.merge_func=merge_func

        for i in range(N):
            self.table[i][0]=A[i]

        for j in range(1,n):
            for i in range(0,N-2**j+1):
                f=self.table[i][j-1]
                s=self.table[i+2**(j-1)][j-1]
                self.table[i][j]=self.merge_func(f,s)

    def query(self,s,t):
        b=t-s+1
        m=b.bit_length()-1
        return self.merge_func(self.table[s][m],self.table[t-2**m+1][m])

class BinaryTrie:
    class node:
        def __init__(self,val):
            self.left = None
            self.right = None
            self.max = val

    def __init__(self):
        self.root = self.node(-10**15)

    def append(self,key,val):
        pos = self.root
        for i in range(29,-1,-1):
            pos.max = max(pos.max,val)
            if key>>i & 1:
                if pos.right is None:
                    pos.right = self.node(val)
                    pos = pos.right
                else:
                    pos = pos.right
            else:
                if pos.left is None:
                    pos.left = self.node(val)
                    pos = pos.left
                else:
                    pos = pos.left
        pos.max = max(pos.max,val)

    def search(self,M,xor):
        res = -10**15
        pos = self.root
        for i in range(29,-1,-1):
            if pos is None:
                break

            if M>>i & 1:
                if xor>>i & 1:
                    if pos.right:
                        res = max(res,pos.right.max)
                    pos = pos.left
                else:
                    if pos.left:
                        res = max(res,pos.left.max)
                    pos = pos.right
            else:
                if xor>>i & 1:
                    pos = pos.right
                else:
                    pos = pos.left

        if pos:
            res = max(res,pos.max)
        return res

def solveequation(edge,ans,n,m):
    #edge=[[to,dire,id]...]
    x=[0]*m
    used=[False]*n
    for v in range(n):
        if used[v]:
            continue
        y = dfs(v)
        if y!=0:
            return False
    return x

    def dfs(v):
        used[v]=True
        r=ans[v]
        for to,dire,id in edge[v]:
            if used[to]:
                continue
            y=dfs(to)
            if dire==-1:
                x[id]=y
            else:
                x[id]=-y
            r+=y
        return r

class SegmentTree:
    def __init__(self, init_val, segfunc, ide_ele):
        n = len(init_val)
        self.segfunc = segfunc
        self.ide_ele = ide_ele
        self.num = 1 << (n - 1).bit_length()
        self.tree = [ide_ele] * 2 * self.num
        self.size = n
        for i in range(n):
            self.tree[self.num + i] = init_val[i]
        for i in range(self.num - 1, 0, -1):
            self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])

    def update(self, k, x):
        k += self.num
        self.tree[k] = x
        while k > 1:
            self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1])
            k >>= 1

    def query(self, l, r):
        if r==self.size:
            r = self.num

        res = self.ide_ele

        l += self.num
        r += self.num
        while l < r:
            if l & 1:
                res = self.segfunc(res, self.tree[l])
                l += 1
            if r & 1:
                res = self.segfunc(res, self.tree[r - 1])
            l >>= 1
            r >>= 1
        return res

    def bisect_l(self,l,r,x):
        l += self.num
        r += self.num
        Lmin = -1
        Rmin = -1
        while l<r:
            if l & 1:
                if self.tree[l] <= x and Lmin==-1:
                    Lmin = l
                l += 1
            if r & 1:
                if self.tree[r-1] <=x:
                    Rmin = r-1
            l >>= 1
            r >>= 1

        if Lmin != -1:
            pos = Lmin
            while pos<self.num:
                if self.tree[2 * pos] <=x:
                    pos = 2 * pos
                else:
                    pos = 2 * pos +1
            return pos-self.num
        elif Rmin != -1:
            pos = Rmin
            while pos<self.num:
                if self.tree[2 * pos] <=x:
                    pos = 2 * pos
                else:
                    pos = 2 * pos +1
            return pos-self.num
        else:
            return -1

import sys,random,bisect
from collections import deque,defaultdict
from heapq import heapify,heappop,heappush
from itertools import permutations
from math import gcd,log

input = lambda :sys.stdin.readline().rstrip()
mi = lambda :map(int,input().split())
li = lambda :list(mi())

def cmb(n, r, mod):
    if ( r<0 or r>n ):
        return 0
    r = min(r, n-r)
    return (g1[n] * g2[r] % mod) * g2[n-r] % mod

mod = 10**9 + 7
N = 10**5 + 100
g1 = [1]*(N+1)
g2 = [1]*(N+1)
inverse = [1]*(N+1)

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

def solve(N,K):
    res = 0
    pre = 1

    for i in range(1,N+1):
        pre = (pre * (N-i+1))
        pre %= mod

        tmp = cmb(N-(i-1)*(K-1),i,mod) * g1[i] % mod
        prop = g2[N] * g1[N-i] % mod

        res += (tmp * prop % mod)
        res %= mod

        end = (pre-tmp)
        res += end  * prop % mod
        res %= mod

        pre = tmp

    return res % mod

for _ in range(int(input())):
    N,K = mi()
    print(solve(N,K))

```


155_D. Colliders

By 2312 there were n Large Hadron Colliders in the inhabited part of the universe. Each of them corresponded to a single natural number from 1 to n. However, scientists did not know what activating several colliders simultaneously could cause, so the colliders were deactivated.

In 2312 there was a startling discovery: a collider's activity is safe if and only if all numbers of activated colliders are pairwise relatively prime to each other (two numbers are relatively prime if their greatest common divisor equals 1)! If two colliders with relatively nonprime numbers are activated, it will cause a global collapse.

Upon learning this, physicists rushed to turn the colliders on and off and carry out all sorts of experiments. To make sure than the scientists' quickness doesn't end with big trouble, the Large Hadron Colliders' Large Remote Control was created. You are commissioned to write the software for the remote (well, you do not expect anybody to operate it manually, do you?).

Initially, all colliders are deactivated. Your program receives multiple requests of the form "activate/deactivate the i-th collider". The program should handle requests in the order of receiving them. The program should print the processed results in the format described below.

To the request of "+ i" (that is, to activate the i-th collider), the program should print exactly one of the following responses:

  * "Success" if the activation was successful.
  * "Already on", if the i-th collider was already activated before the request.
  * "Conflict with j", if there is a conflict with the j-th collider (that is, the j-th collider is on, and numbers i and j are not relatively prime). In this case, the i-th collider shouldn't be activated. If a conflict occurs with several colliders simultaneously, you should print the number of any of them.

The request of "- i" (that is, to deactivate the i-th collider), should receive one of the following responses from the program:

  * "Success", if the deactivation was successful.
  * "Already off", if the i-th collider was already deactivated before the request.

You don't need to print quotes in the output of the responses to the requests.

Input

The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 105) — the number of colliders and the number of requests, correspondingly.

Next m lines contain numbers of requests, one per line, in the form of either "+ i" (without the quotes) — activate the i-th collider, or "- i" (without the quotes) — deactivate the i-th collider (1 ≤ i ≤ n).

Output

Print m lines — the results of executing requests in the above given format. The requests should be processed in the order, in which they are given in the input. Don't forget that the responses to the requests should be printed without quotes.

Examples

Input

10 10
+ 6
+ 10
+ 5
- 10
- 5
- 6
+ 10
+ 3
+ 6
+ 3

Output

Success
Conflict with 6
Success
Already off
Success
Success
Success
Success
Conflict with 10
Already on

Note

Note that in the sample the colliders don't turn on after the second and ninth requests. The ninth request could also receive response "Conflict with 3".

```python
n, m = map(int, input().split())

n += 1

s = [[] for i in range(n)]

for j in range(2, n, 2): s[j] = [2]

for i in range(3, n, 2):

    if s[i]: continue

    for j in range(i, n, i): s[j].append(i)

p, d, r = {}, set(), [''] * m

for j in range(m):

    t = input()

    i = int(t[2: ])

    if t[0] == '+':

        if i in d:

            r[j] = 'Already on'

            continue

        for q in s[i]:

            if q in p:

                r[j] = 'Conflict with ' + str(p[q])

                break

        else:

            r[j] = 'Success'

            d.add(i)

            for q in s[i]: p[q] = i

    else:

        if i in d:

            r[j] = 'Success'

            for q in s[i]: p.pop(q)

            d.remove(i)

        else: r[j] = 'Already off'

print('\n'.join(r))

# Made By Mostafa_Khaled
```


177_D2. Encrypting Messages

The Smart Beaver from ABBYY invented a new message encryption method and now wants to check its performance. Checking it manually is long and tiresome, so he decided to ask the ABBYY Cup contestants for help.

A message is a sequence of n integers a1, a2, ..., an. Encryption uses a key which is a sequence of m integers b1, b2, ..., bm (m ≤ n). All numbers from the message and from the key belong to the interval from 0 to c - 1, inclusive, and all the calculations are performed modulo c.

Encryption is performed in n - m + 1 steps. On the first step we add to each number a1, a2, ..., am a corresponding number b1, b2, ..., bm. On the second step we add to each number a2, a3, ..., am + 1 (changed on the previous step) a corresponding number b1, b2, ..., bm. And so on: on step number i we add to each number ai, ai + 1, ..., ai + m - 1 a corresponding number b1, b2, ..., bm. The result of the encryption is the sequence a1, a2, ..., an after n - m + 1 steps.

Help the Beaver to write a program that will encrypt messages in the described manner.

Input

The first input line contains three integers n, m and c, separated by single spaces.

The second input line contains n integers ai (0 ≤ ai < c), separated by single spaces — the original message.

The third input line contains m integers bi (0 ≤ bi < c), separated by single spaces — the encryption key.

The input limitations for getting 30 points are:

  * 1 ≤ m ≤ n ≤ 103
  * 1 ≤ c ≤ 103

The input limitations for getting 100 points are:

  * 1 ≤ m ≤ n ≤ 105
  * 1 ≤ c ≤ 103

Output

Print n space-separated integers — the result of encrypting the original message.

Examples

Input

4 3 2
1 1 1 1
1 1 1

Output

0 1 1 0

Input

3 1 5
1 2 3
4

Output

0 1 2

Note

In the first sample the encryption is performed in two steps: after the first step a = (0, 0, 0, 1) (remember that the calculations are performed modulo 2), after the second step a = (0, 1, 1, 0), and that is the answer.

```python
n, m, c = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
s, k = 0, n - m
for i in range(n):
    if i < m: s += b[i]
    a[i] = (a[i] + s) % c
    if i >= k: s -= b[i - k]
print(' '.join(str(i) for i in a))
```


222_A. Shooshuns and Sequence

One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps:

  1. Find the number that goes k-th in the current sequence and add the same number to the end of the sequence;
  2. Delete the first number of the current sequence.

The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.

Input

The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105).

The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.

Output

Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.

Examples

Input

3 2
3 1 1

Output

1

Input

3 1
3 1 1

Output

-1

Note

In the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.

In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.

```python
n,k=map(int,input().split())
l=list(map(int,input().split()))
f=l[k-1]
if l[k-1:].count(f) == n-k+1:
    r = 0
    for i in range(k-2,-1,-1):
        if l[k-1] != l[i]:
            break
        r+=1
    print(len(l[:k-1-r]))
else:
    print(-1)

```


270_E. Flawed Flow

Emuskald considers himself a master of flow algorithms. Now he has completed his most ingenious program yet — it calculates the maximum flow in an undirected graph. The graph consists of n vertices and m edges. Vertices are numbered from 1 to n. Vertices 1 and n being the source and the sink respectively.

However, his max-flow algorithm seems to have a little flaw — it only finds the flow volume for each edge, but not its direction. Help him find for each edge the direction of the flow through this edges. Note, that the resulting flow should be correct maximum flow.

More formally. You are given an undirected graph. For each it's undirected edge (ai, bi) you are given the flow volume ci. You should direct all edges in such way that the following conditions hold:

  1. for each vertex v (1 < v < n), sum of ci of incoming edges is equal to the sum of ci of outcoming edges;
  2. vertex with number 1 has no incoming edges;
  3. the obtained directed graph does not have cycles.

Input

The first line of input contains two space-separated integers n and m (2 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105), the number of vertices and edges in the graph. The following m lines contain three space-separated integers ai, bi and ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 104), which means that there is an undirected edge from ai to bi with flow volume ci.

It is guaranteed that there are no two edges connecting the same vertices; the given graph is connected; a solution always exists.

Output

Output m lines, each containing one integer di, which should be 0 if the direction of the i-th edge is ai → bi (the flow goes from vertex ai to vertex bi) and should be 1 otherwise. The edges are numbered from 1 to m in the order they are given in the input.

If there are several solutions you can print any of them.

Examples

Input

3 3
3 2 10
1 2 10
3 1 5

Output

1
0
1

Input

4 5
1 2 10
1 3 10
2 3 5
4 2 15
3 4 5

Output

0
0
1
1
0

Note

In the first test case, 10 flow units pass through path <image>, and 5 flow units pass directly from source to sink: <image>.

```python
import sys
from collections import deque

DST_VERTEX = 0
EDGE_CAP = 1
EDGE_ID = 2
EDGE_DIR = 3

def bfs(flow, graph, n, m):
    dirs = [-1 for _ in range(m)]
    q = deque()
    q.append(0)
    q_size = 1
    while q_size > 0:
        cur_node = q.popleft()
        q_size -= 1
        for i in range(len(graph[cur_node])):
            cur_id = graph[cur_node][i][EDGE_ID]
            if dirs[cur_id] == -1:
                #direction not assigned -> try to assign
                dirs[cur_id] = graph[cur_node][i][EDGE_DIR]
                cur_dst = graph[cur_node][i][DST_VERTEX]
                flow[cur_dst] -= graph[cur_node][i][EDGE_CAP]
                if cur_dst != n - 1 and flow[cur_dst] == 0:
                    q.append(cur_dst)
                    q_size += 1
    return dirs

def main():
    n, m = sys.stdin.readline().strip().split()
    n = int(n)
    m = int(m)
    flow = [0 for _ in range(n)]

    graph = [[] for _ in range(n)]
    for j in range(m):
        src, dst, cap = [int(i) for i in sys.stdin.readline().strip().split()]
        src -= 1
        dst -= 1
        graph[src].append((dst, cap, j, 0))
        graph[dst].append((src, cap, j, 1))
        flow[src] += cap
        flow[dst] += cap
    for i in range(n):
        flow[i] //= 2
    dirs = bfs(flow, graph, n, m)
    for direction in dirs:
        print(direction)

if __name__ == '__main__':
    main()
```


294_B. Shaass and Bookshelf

Shaass has n books. He wants to make a bookshelf for all his books. He wants the bookshelf's dimensions to be as small as possible. The thickness of the i-th book is ti and its pages' width is equal to wi. The thickness of each book is either 1 or 2. All books have the same page heights.

<image>

Shaass puts the books on the bookshelf in the following way. First he selects some of the books and put them vertically. Then he puts the rest of the books horizontally above the vertical books. The sum of the widths of the horizontal books must be no more than the total thickness of the vertical books. A sample arrangement of the books is depicted in the figure.

<image>

Help Shaass to find the minimum total thickness of the vertical books that we can achieve.

Input

The first line of the input contains an integer n, (1 ≤ n ≤ 100). Each of the next n lines contains two integers ti and wi denoting the thickness and width of the i-th book correspondingly, (1 ≤ ti ≤ 2, 1 ≤ wi ≤ 100).

Output

On the only line of the output print the minimum total thickness of the vertical books that we can achieve.

Examples

Input

5
1 12
1 3
2 15
2 5
2 1

Output

5

Input

3
1 10
2 1
2 4

Output

3

```python
n = int(input())

t = []
for i in range(n):
    e = list(map(int,input().split()))
    t.append(e)

size = 0
size2 = 0
for i in t:
    size += i[0]
    size2 += i[1]

matrix = [[-1000]*(size+1) for i in range(n)]
for i in range(n):
    matrix[i][0] = 0

for i in range(n):
    for j in range(1,size+1):
        if t[i][0] <= j:
            if t[i][0] == j and matrix[i-1][j] == 1000:
                matrix[i][j] = t[i][1]
            else:
                matrix[i][j] = max(matrix[i-1][j],matrix[i-1][j-t[i][0]] + t[i][1])

        else:
            matrix[i][j] = matrix[i-1][j]
    #print(matrix[i])

for i in range(1,size+1):
    if i >= size2 - matrix[-1][i]:
        print(i)
        break

```


365_B. The Fibonacci Segment

You have array a1, a2, ..., an. Segment [l, r] (1 ≤ l ≤ r ≤ n) is good if ai = ai - 1 + ai - 2, for all i (l + 2 ≤ i ≤ r).

Let's define len([l, r]) = r - l + 1, len([l, r]) is the length of the segment [l, r]. Segment [l1, r1], is longer than segment [l2, r2], if len([l1, r1]) > len([l2, r2]).

Your task is to find a good segment of the maximum length in array a. Note that a segment of length 1 or 2 is always good.

Input

The first line contains a single integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains integers: a1, a2, ..., an (0 ≤ ai ≤ 109).

Output

Print the length of the longest good segment in array a.

Examples

Input

10
1 2 3 5 8 13 21 34 55 89

Output

10

Input

5
1 1 1 1 1

Output

2

```python
import sys
n = int(input())
a = list(map(int, input().split()))
if n <= 2:
    print(n)
    sys.exit()
best = 0
mem = a[:2]
cur = 0
for i in a[2:]:
    if mem[0] + mem[1] == i:
        cur += 1
    else:
        if cur > best: best = cur
        cur = 0
    mem = mem[1:] + [i]
if cur > best: best = cur
print(best+2)

```


389_A. Fox and Number Game

Fox Ciel is playing a game with numbers now.

Ciel has n positive integers: x1, x2, ..., xn. She can do the following operation as many times as needed: select two different indexes i and j such that xi > xj hold, and then apply assignment xi = xi - xj. The goal is to make the sum of all numbers as small as possible.

Please help Ciel to find this minimal sum.

Input

The first line contains an integer n (2 ≤ n ≤ 100). Then the second line contains n integers: x1, x2, ..., xn (1 ≤ xi ≤ 100).

Output

Output a single integer — the required minimal sum.

Examples

Input

2
1 2

Output

2

Input

3
2 4 6

Output

6

Input

2
12 18

Output

12

Input

5
45 12 27 30 18

Output

15

Note

In the first example the optimal way is to do the assignment: x2 = x2 - x1.

In the second example the optimal sequence of operations is: x3 = x3 - x2, x2 = x2 - x1.

```python
from sys import stdin, stdout, stderr, setrecursionlimit
setrecursionlimit(100000)

def debug (*e):
    if not __debug__:
        print(*e, file=stderr)

def dd(*vals):
    import inspect, re
    frame = inspect.getframeinfo(inspect.stack()[1][0])
    vs = re.search("dd\((.+)\)", frame.code_context[0]).group(1).split(",")
    if vs:
        debug(",".join("{0} = {1}".format(vs[i], v) for i,v in enumerate(vals)))

def trace(f):
    def traced(*args, **kw):
        debug("calling {} with args {}, {}".format(f.__name__, args, kw))
        return f(*args, **kw)
    return traced
#@trace
#def f(x):

def read():
    return stdin.readline().rstrip()

def readarr(sep=None, maxsplit=-1):
    return read().split(sep, maxsplit)

def readint():
    return int(read())

def readia(sep=None, maxsplit=-1):
    return [int(a) for a in readarr(sep, maxsplit)]

#write(1, 2, 3, sep="-", end="!")
def write(*args, **kwargs):
    sep = kwargs.get('sep', ' ')
    end = kwargs.get('end', '\n')
    stdout.write(sep.join(str(a) for a in args) + end)

#writea([1, 2, 3], sep="-", end="!")
def writea(arr, sep=' ', end='\n'):
    stdout.write(sep.join(str(a) for a in arr) + end)

n = readint()
xs = readia()

while True:
    xs.sort()
    xs.reverse()
    for i in range(1, n):
        if xs[i-1] > xs[i]:
            xs[i-1] -= xs[i]
            break
    else:
        write(sum(xs))
        break

```


409_D. Big Data

Little Petya wanted to give an April Fools Day present to some scientists. After some hesitation he decided to give them the array that he got as a present in Codeforces Round #153 (Div.2). The scientists rejoiced at the gift and decided to put some important facts to this array. Here are the first few of the facts:

  * The highest mountain above sea level in the world is Mount Everest. Its peak rises to 8848 m.
  * The largest board game tournament consisted of 958 participants playing chapaev.
  * The largest online maths competition consisted of 12766 participants.
  * The Nile is credited as the longest river in the world. From its farthest stream in Burundi, it extends 6695 km in length.
  * While not in flood, the main stretches of the Amazon river in South America can reach widths of up to 1100 km at its widest points.
  * Angel Falls is the highest waterfall. Its greatest single drop measures 807 m.
  * The Hotel Everest View above Namche, Nepal — the village closest to Everest base camp – is at a record height of 31962 m
  * Uranium is the heaviest of all the naturally occurring elements. Its most common isotope has a nucleus containing 146 neutrons.
  * The coldest permanently inhabited place is the Siberian village of Oymyakon, where the temperature of -68°C was registered in the twentieth century.
  * The longest snake held in captivity is over 25 feet long. Its name is Medusa.
  * Colonel Meow holds the world record for longest fur on a cat — almost 134 centimeters.
  * Sea otters can have up to 10000 hairs per square inch. This is the most dense fur in the animal kingdom.
  * The largest state of USA is Alaska; its area is 663268 square miles
  * Alaska has a longer coastline than all of the other 49 U.S. States put together: it is 154103 miles long.
  * Lake Baikal is the largest freshwater lake in the world. It reaches 1642 meters in depth and contains around one-fifth of the world’s unfrozen fresh water.
  * The most colorful national flag is the one of Turkmenistan, with 106 colors.

Input

The input will contain a single integer between 1 and 16.

Output

Output a single integer.

Examples

Input

1

Output

1

Input

7

Output

0


45_A. Codecraft III

Today Vasya visited a widely known site and learned that the continuation of his favourite game Codecraft II will appear after exactly k months. He looked at the calendar and learned that at the moment is the month number s. Vasya immediately got interested in what month Codecraft III will appear. Help him understand that.

All the twelve months in Vasya's calendar are named using their usual English names: January, February, March, April, May, June, July, August, September, October, November, December.

Input

The first input line contains the name of the current month. It is guaranteed that it is a proper English name of one of twelve months. The first letter is uppercase, the rest are lowercase. The second line contains integer k (0 ≤ k ≤ 100) — the number of months left till the appearance of Codecraft III.

Output

Print starting from an uppercase letter the name of the month in which the continuation of Codeforces II will appear. The printed name must be contained in the list January, February, March, April, May, June, July, August, September, October, November, December.

Examples

Input

November
3

Output

February

Input

May
24

Output

May

```python
month = str(input())
k = int(input())

m = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
j = m.index(month)

while k != 0:
    if j == 11:
        j = 0
        k -= 1
    else:
        j += 1
        k -= 1
print(m[j])
```


529_D. Social Network

Polycarpus got an internship in one well-known social network. His test task is to count the number of unique users who have visited a social network during the day. Polycarpus was provided with information on all user requests for this time period. For each query, we know its time... and nothing else, because Polycarpus has already accidentally removed the user IDs corresponding to the requests from the database. Thus, it is now impossible to determine whether any two requests are made by the same person or by different people.

But wait, something is still known, because that day a record was achieved — M simultaneous users online! In addition, Polycarpus believes that if a user made a request at second s, then he was online for T seconds after that, that is, at seconds s, s + 1, s + 2, ..., s + T - 1. So, the user's time online can be calculated as the union of time intervals of the form [s, s + T - 1] over all times s of requests from him.

Guided by these thoughts, Polycarpus wants to assign a user ID to each request so that:

  * the number of different users online did not exceed M at any moment,
  * at some second the number of distinct users online reached value M,
  * the total number of users (the number of distinct identifiers) was as much as possible.

Help Polycarpus cope with the test.

Input

The first line contains three integers n, M and T (1 ≤ n, M ≤ 20 000, 1 ≤ T ≤ 86400) — the number of queries, the record number of online users and the time when the user was online after a query was sent. Next n lines contain the times of the queries in the format "hh:mm:ss", where hh are hours, mm are minutes, ss are seconds. The times of the queries follow in the non-decreasing order, some of them can coincide. It is guaranteed that all the times and even all the segments of type [s, s + T - 1] are within one 24-hour range (from 00:00:00 to 23:59:59).

Output

In the first line print number R — the largest possible number of distinct users. The following n lines should contain the user IDs for requests in the same order in which the requests are given in the input. User IDs must be integers from 1 to R. The requests of the same user must correspond to the same identifiers, the requests of distinct users must correspond to distinct identifiers. If there are multiple solutions, print any of them. If there is no solution, print "No solution" (without the quotes).

Examples

Input

4 2 10
17:05:53
17:05:58
17:06:01
22:39:47

Output

3
1
2
2
3

Input

1 2 86400
00:00:00

Output

No solution

Note

Consider the first sample. The user who sent the first request was online from 17:05:53 to 17:06:02, the user who sent the second request was online from 17:05:58 to 17:06:07, the user who sent the third request, was online from 17:06:01 to 17:06:10. Thus, these IDs cannot belong to three distinct users, because in that case all these users would be online, for example, at 17:06:01. That is impossible, because M = 2. That means that some two of these queries belonged to the same user. One of the correct variants is given in the answer to the sample. For it user 1 was online from 17:05:53 to 17:06:02, user 2 — from 17:05:58 to 17:06:10 (he sent the second and third queries), user 3 — from 22:39:47 to 22:39:56.

In the second sample there is only one query. So, only one user visited the network within the 24-hour period and there couldn't be two users online on the network simultaneously. (The time the user spent online is the union of time intervals for requests, so users who didn't send requests could not be online in the network.)

```python
def main():
    mode="filee"
    if mode=="file":f=open("test.txt","r")
    get = lambda :[int(x) for x in (f.readline() if mode=="file" else input()).split()]
    gets = lambda :[str(x) for x in (f.readline()[:-1] if mode=="file" else input()).split(":")]
    [n,m,t]=get()
    a=[0]*20002
    b=[0]*20002
    if n<m:
        print("No solution")
        return
    for i in range(1,1+n):
        g = gets()
        a[i] = int(g[-1]) + int(g[1])*60 + int(g[0])*3600
        [p,count,sim] = [1,0,0]
    is_solution_there=False
    for i in range(1,n+1):
        while p<i and a[i] - t + 1>a[p]:
            p+=1
            if b[p]!=b[p-1]:
                sim = max(sim-1,0)
        if a[i]<a[p]+t and sim<m:
            count+=1
            sim+=1
        if sim==m:
            is_solution_there=True
        b[i] = count
    if is_solution_there==False:
        print("No solution")
        return
    print(count)
    for i in range(1,n+1):
        print(b[i],end=' ')

    if mode=="file":f.close()

if __name__=="__main__":
    main()

```


555_A. Case of Matryoshkas

Andrewid the Android is a galaxy-famous detective. He is now investigating the case of vandalism at the exhibition of contemporary art.

The main exhibit is a construction of n matryoshka dolls that can be nested one into another. The matryoshka dolls are numbered from 1 to n. A matryoshka with a smaller number can be nested in a matryoshka with a higher number, two matryoshkas can not be directly nested in the same doll, but there may be chain nestings, for example, 1 → 2 → 4 → 5.

In one second, you can perform one of the two following operations:

  * Having a matryoshka a that isn't nested in any other matryoshka and a matryoshka b, such that b doesn't contain any other matryoshka and is not nested in any other matryoshka, you may put a in b;
  * Having a matryoshka a directly contained in matryoshka b, such that b is not nested in any other matryoshka, you may get a out of b.

According to the modern aesthetic norms the matryoshka dolls on display were assembled in a specific configuration, i.e. as several separate chains of nested matryoshkas, but the criminal, following the mysterious plan, took out all the dolls and assembled them into a single large chain (1 → 2 → ... → n). In order to continue the investigation Andrewid needs to know in what minimum time it is possible to perform this action.

Input

The first line contains integers n (1 ≤ n ≤ 105) and k (1 ≤ k ≤ 105) — the number of matryoshkas and matryoshka chains in the initial configuration.

The next k lines contain the descriptions of the chains: the i-th line first contains number mi (1 ≤ mi ≤ n), and then mi numbers ai1, ai2, ..., aimi — the numbers of matryoshkas in the chain (matryoshka ai1 is nested into matryoshka ai2, that is nested into matryoshka ai3, and so on till the matryoshka aimi that isn't nested into any other matryoshka).

It is guaranteed that m1 + m2 + ... + mk = n, the numbers of matryoshkas in all the chains are distinct, in each chain the numbers of matryoshkas follow in the ascending order.

Output

In the single line print the minimum number of seconds needed to assemble one large chain from the initial configuration.

Examples

Input

3 2
2 1 2
1 3

Output

1

Input

7 3
3 1 3 7
2 2 5
2 4 6

Output

10

Note

In the first sample test there are two chains: 1 → 2 and 3. In one second you can nest the first chain into the second one and get 1 → 2 → 3.

In the second sample test you need to disassemble all the three chains into individual matryoshkas in 2 + 1 + 1 = 4 seconds and then assemble one big chain in 6 seconds.

```python
n,k = map(int,input().split(" "))
i=0
res=k
sh=0
while i<k:
    i+=1
    mas=list(map(int,input().split(" ")))[1:]

    if mas[0]==1:
         j=0
         while j<(len(mas)-1):

             if(mas[j]+1!=mas[j+1]):
                 break
             else:
                 j+=1
         sh+=len(mas)-j-1
         res+=len(mas)-j-1
    else:
        res+=len(mas)-1
        sh+=len(mas)-1

print(sh+res-1)

```


625_B. War of the Corporations

A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.

This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.

Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.

Substring is a continuous subsequence of a string.

Input

The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.

Output

Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.

Examples

Input

intellect
tell

Output

1

Input

google
apple

Output

0

Input

sirisiri
sir

Output

2

Note

In the first sample AI's name may be replaced with "int#llect".

In the second sample Gogol can just keep things as they are.

In the third sample one of the new possible names of AI may be "s#ris#ri".

```python
a, b = input(), input()
ans = 0
index = a.find (b, 0)
while index != -1:
    ans = ans + 1
    index = a.find (b, index + len (b))
print (ans)

```


673_D. Bear and Two Paths

Bearland has n cities, numbered 1 through n. Cities are connected via bidirectional roads. Each road connects two distinct cities. No two roads connect the same pair of cities.

Bear Limak was once in a city a and he wanted to go to a city b. There was no direct connection so he decided to take a long walk, visiting each city exactly once. Formally:

  * There is no road between a and b.
  * There exists a sequence (path) of n distinct cities v1, v2, ..., vn that v1 = a, vn = b and there is a road between vi and vi + 1 for <image>.

On the other day, the similar thing happened. Limak wanted to travel between a city c and a city d. There is no road between them but there exists a sequence of n distinct cities u1, u2, ..., un that u1 = c, un = d and there is a road between ui and ui + 1 for <image>.

Also, Limak thinks that there are at most k roads in Bearland. He wonders whether he remembers everything correctly.

Given n, k and four distinct cities a, b, c, d, can you find possible paths (v1, ..., vn) and (u1, ..., un) to satisfy all the given conditions? Find any solution or print -1 if it's impossible.

Input

The first line of the input contains two integers n and k (4 ≤ n ≤ 1000, n - 1 ≤ k ≤ 2n - 2) — the number of cities and the maximum allowed number of roads, respectively.

The second line contains four distinct integers a, b, c and d (1 ≤ a, b, c, d ≤ n).

Output

Print -1 if it's impossible to satisfy all the given conditions. Otherwise, print two lines with paths descriptions. The first of these two lines should contain n distinct integers v1, v2, ..., vn where v1 = a and vn = b. The second line should contain n distinct integers u1, u2, ..., un where u1 = c and un = d.

Two paths generate at most 2n - 2 roads: (v1, v2), (v2, v3), ..., (vn - 1, vn), (u1, u2), (u2, u3), ..., (un - 1, un). Your answer will be considered wrong if contains more than k distinct roads or any other condition breaks. Note that (x, y) and (y, x) are the same road.

Examples

Input

7 11
2 4 7 3

Output

2 7 1 3 6 5 4
7 1 5 4 6 2 3

Input

1000 999
10 20 30 40

Output

-1

Note

In the first sample test, there should be 7 cities and at most 11 roads. The provided sample solution generates 10 roads, as in the drawing. You can also see a simple path of length n between 2 and 4, and a path between 7 and 3.

<image>

```python
n,k=map(int,input().split())
a,b,c,d=input().split()
if n<5 or k<n+1: print(-1)
else:
    l=list(set(map(str,range(1,n+1)))-{a,b,c,d})
    print(' '.join([a,c]+l+[d,b]+['\n']+[c,a]+l+[b,d]))
```


71_A. Way Too Long Words

Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.

Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.

This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.

Thus, "localization" will be spelt as "l10n", and "internationalization» will be spelt as "i18n".

You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.

Input

The first line contains an integer n (1 ≤ n ≤ 100). Each of the following n lines contains one word. All the words consist of lowercase Latin letters and possess the lengths of from 1 to 100 characters.

Output

Print n lines. The i-th line should contain the result of replacing of the i-th word from the input data.

Examples

Input

4
word
localization
internationalization
pneumonoultramicroscopicsilicovolcanoconiosis

Output

word
l10n
i18n
p43s

```python
n = int(input())
if 1 <= n <= 100:
    for i in range(n):
        word = input()
        if len(word) > 10:
            numWord = str(len(word[1:-1]))
            print(word[0] + numWord + word[-1])
        else:
            print(word)

```


740_C. Alyona and mex

Alyona's mother wants to present an array of n non-negative integers to Alyona. The array should be special.

Alyona is a capricious girl so after she gets the array, she inspects m of its subarrays. Subarray is a set of some subsequent elements of the array. The i-th subarray is described with two integers li and ri, and its elements are a[li], a[li + 1], ..., a[ri].

Alyona is going to find mex for each of the chosen subarrays. Among these m mexes the girl is going to find the smallest. She wants this minimum mex to be as large as possible.

You are to find an array a of n elements so that the minimum mex among those chosen by Alyona subarrays is as large as possible.

The mex of a set S is a minimum possible non-negative integer that is not in S.

Input

The first line contains two integers n and m (1 ≤ n, m ≤ 105).

The next m lines contain information about the subarrays chosen by Alyona. The i-th of these lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n), that describe the subarray a[li], a[li + 1], ..., a[ri].

Output

In the first line print single integer — the maximum possible minimum mex.

In the second line print n integers — the array a. All the elements in a should be between 0 and 109.

It is guaranteed that there is an optimal answer in which all the elements in a are between 0 and 109.

If there are multiple solutions, print any of them.

Examples

Input

5 3
1 3
2 5
4 5

Output

2
1 0 2 1 0

Input

4 2
1 4
2 4

Output

3
5 2 0 1

Note

The first example: the mex of the subarray (1, 3) is equal to 3, the mex of the subarray (2, 5) is equal to 3, the mex of the subarray (4, 5) is equal to 2 as well, thus the minumal mex among the subarrays chosen by Alyona is equal to 2.

```python
n,m=map(int,input().split())
min_val=9999999
for _ in range(m):
    y,x=map(int,input().split())
    if min_val>x-y:
        x1=x
        y1=y
        min_val=x-y
print(min_val+1)
L=[0]*n
tp=0
listNum=[]
for i in range(n):
    listNum.append(tp)
    tp+=1
    if tp>min_val:
        tp=0
for i in listNum[:-1]:
    print(i,end=' ')
print(listNum[-1])
```


764_B. Timofey and cubes

Young Timofey has a birthday today! He got kit of n cubes as a birthday present from his parents. Every cube has a number ai, which is written on it. Timofey put all the cubes in a row and went to unpack other presents.

In this time, Timofey's elder brother, Dima reordered the cubes using the following rule. Suppose the cubes are numbered from 1 to n in their order. Dima performs several steps, on step i he reverses the segment of cubes from i-th to (n - i + 1)-th. He does this while i ≤ n - i + 1.

After performing the operations Dima went away, being very proud of himself. When Timofey returned to his cubes, he understood that their order was changed. Help Timofey as fast as you can and save the holiday — restore the initial order of the cubes using information of their current location.

Input

The first line contains single integer n (1 ≤ n ≤ 2·105) — the number of cubes.

The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109), where ai is the number written on the i-th cube after Dima has changed their order.

Output

Print n integers, separated by spaces — the numbers written on the cubes in their initial order.

It can be shown that the answer is unique.

Examples

Input

7
4 3 7 6 9 1 2

Output

2 3 9 6 7 1 4

Input

8
6 1 4 2 5 6 9 2

Output

2 1 6 2 5 4 9 6

Note

Consider the first sample.

  1. At the begining row was [2, 3, 9, 6, 7, 1, 4].
  2. After first operation row was [4, 1, 7, 6, 9, 3, 2].
  3. After second operation row was [4, 3, 9, 6, 7, 1, 2].
  4. After third operation row was [4, 3, 7, 6, 9, 1, 2].
  5. At fourth operation we reverse just middle element, so nothing has changed. The final row is [4, 3, 7, 6, 9, 1, 2]. So the answer for this case is row [2, 3, 9, 6, 7, 1, 4].

```python
n=int(input())
a=list(map(int,input().split()))
i=0
temp=0
for i in range(n//2):
    if i%2==0:
        temp=a[i]
        a[i]=a[n-i-1]
        a[n-i-1]=temp
for r in a:
    print(r,end=' ')
```


809_A. Do you want a date?

Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vičkopolis.

Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to n. So the i-th hacked computer is located at the point xi. Moreover the coordinates of all computers are distinct.

Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.

Leha should calculate a sum of F(a) for all a, where a is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote A the set of all integers from 1 to n. Noora asks the hacker to find value of the expression <image>. Here F(a) is calculated as the maximum among the distances between all pairs of computers from the set a. Formally, <image>. Since the required sum can be quite large Noora asks to find it modulo 109 + 7.

Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.

Input

The first line contains one integer n (1 ≤ n ≤ 3·105) denoting the number of hacked computers.

The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) denoting the coordinates of hacked computers. It is guaranteed that all xi are distinct.

Output

Print a single integer — the required sum modulo 109 + 7.

Examples

Input

2
4 7

Output

3

Input

3
4 3 1

Output

9

Note

There are three non-empty subsets in the first sample test:<image>, <image> and <image>. The first and the second subset increase the sum by 0 and the third subset increases the sum by 7 - 4 = 3. In total the answer is 0 + 0 + 3 = 3.

There are seven non-empty subsets in the second sample test. Among them only the following subsets increase the answer: <image>, <image>, <image>, <image>. In total the sum is (4 - 3) + (4 - 1) + (3 - 1) + (4 - 1) = 9.

```python
def main():

  largemodulus = 1000000007
  maxofn = 300001
  n = 0
  answer = 0

  powersoftwo = []
  multiplier = 1

  for _ in range(maxofn):
    powersoftwo.append(multiplier)
    if multiplier >= largemodulus:
      multiplier = multiplier % largemodulus
    multiplier *= 2

  n = int(input())

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

  hacked.sort(reverse = True)

  for x in range(n):
    answer += (hacked[x] * ((powersoftwo[n-1-x]-1)-(powersoftwo[x]-1))) % largemodulus
    if answer >= largemodulus:
      answer = answer % largemodulus

  print(answer)

  return

main()
```


854_B. Maxim Buys an Apartment

Maxim wants to buy an apartment in a new house at Line Avenue of Metropolis. The house has n apartments that are numbered from 1 to n and are arranged in a row. Two apartments are adjacent if their indices differ by 1. Some of the apartments can already be inhabited, others are available for sale.

Maxim often visits his neighbors, so apartment is good for him if it is available for sale and there is at least one already inhabited apartment adjacent to it. Maxim knows that there are exactly k already inhabited apartments, but he doesn't know their indices yet.

Find out what could be the minimum possible and the maximum possible number of apartments that are good for Maxim.

Input

The only line of the input contains two integers: n and k (1 ≤ n ≤ 109, 0 ≤ k ≤ n).

Output

Print the minimum possible and the maximum possible number of apartments good for Maxim.

Example

Input

6 3

Output

1 3

Note

In the sample test, the number of good apartments could be minimum possible if, for example, apartments with indices 1, 2 and 3 were inhabited. In this case only apartment 4 is good. The maximum possible number could be, for example, if apartments with indices 1, 3 and 5 were inhabited. In this case all other apartments: 2, 4 and 6 are good.

```python
n,k=map(int,input().split())
mi=1
if k==0:
    print(0,0)
    exit()
if k==n:
    print(0,0)
    exit()
if 3*k <=n:
    ma=2*k
else:
    ma=n-k
print(mi,ma)

```


902_B. Coloring a Tree

You are given a rooted tree with n vertices. The vertices are numbered from 1 to n, the root is the vertex number 1.

Each vertex has a color, let's denote the color of vertex v by cv. Initially cv = 0.

You have to color the tree into the given colors using the smallest possible number of steps. On each step you can choose a vertex v and a color x, and then color all vectices in the subtree of v (including v itself) in color x. In other words, for every vertex u, such that the path from root to u passes through v, set cu = x.

It is guaranteed that you have to color each vertex in a color different from 0.

You can learn what a rooted tree is using the link: https://en.wikipedia.org/wiki/Tree_(graph_theory).

Input

The first line contains a single integer n (2 ≤ n ≤ 104) — the number of vertices in the tree.

The second line contains n - 1 integers p2, p3, ..., pn (1 ≤ pi < i), where pi means that there is an edge between vertices i and pi.

The third line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ n), where ci is the color you should color the i-th vertex into.

It is guaranteed that the given graph is a tree.

Output

Print a single integer — the minimum number of steps you have to perform to color the tree into given colors.

Examples

Input

6
1 2 2 1 5
2 1 1 1 1 1

Output

3

Input

7
1 1 2 3 1 4
3 3 1 1 1 2 3

Output

5

Note

The tree from the first sample is shown on the picture (numbers are vetices' indices):

<image>

On first step we color all vertices in the subtree of vertex 1 into color 2 (numbers are colors):

<image>

On seond step we color all vertices in the subtree of vertex 5 into color 1:

<image>

On third step we color all vertices in the subtree of vertex 2 into color 1:

<image>

The tree from the second sample is shown on the picture (numbers are vetices' indices):

<image>

On first step we color all vertices in the subtree of vertex 1 into color 3 (numbers are colors):

<image>

On second step we color all vertices in the subtree of vertex 3 into color 1:

<image>

On third step we color all vertices in the subtree of vertex 6 into color 2:

<image>

On fourth step we color all vertices in the subtree of vertex 4 into color 1:

<image>

On fith step we color all vertices in the subtree of vertex 7 into color 3:

<image>

```python
from queue import *

n=int(input())
parent={}
child={}
for i in range(1,n+1):
    parent[i]=0
    child[i]=[]
l=list(map(int,input().split()))
for i in range(2,n+1):
    parent[i]=l[i-2]
    child[l[i-2]].append(i)
l=list(map(int,input().split()))
color={}
for i in range(1,n+1):
    color[i]=l[i-1]

q=Queue()
q.put(1)
ans=0
while(not(q.empty())):
    e=q.get()
    c=0
    if(e==1):
        c=0
    else:
        c=color[parent[e]]
    if(c!=color[e]):
        ans+=1
    for i in child[e]:
        q.put(i)

print(ans)

```


952_F. 2 + 2 != 4

One very experienced problem writer decided to prepare a problem for April Fools Day contest. The task was very simple - given an arithmetic expression, return the result of evaluating this expression. However, looks like there is a bug in the reference solution...

Input

The only line of input data contains the arithmetic expression. The expression will contain between 2 and 10 operands, separated with arithmetic signs plus and/or minus. Each operand will be an integer between 0 and 255, inclusive.

Output

Reproduce the output of the reference solution, including the bug.

Examples

Input

8-7+6-5+4-3+2-1-0

Output

4

Input

2+2

Output

-46

Input

112-37

Output

375


99_C. Help Victoria the Wise

Vasilisa the Wise from a far away kingdom got a present from her friend Helga the Wise from a farther away kingdom. The present is a surprise box, yet Vasilisa the Wise doesn't know yet what the surprise actually is because she cannot open the box. She hopes that you can help her in that.

The box's lock is constructed like that. The box itself is represented by an absolutely perfect black cube with the identical deepening on each face (those are some foreign nanotechnologies that the far away kingdom scientists haven't dreamt of). The box is accompanied by six gems whose form matches the deepenings in the box's faces. The box can only be opened after it is correctly decorated by the gems, that is, when each deepening contains exactly one gem. Two ways of decorating the box are considered the same if they can be obtained one from the other one by arbitrarily rotating the box (note that the box is represented by a perfect nanotechnological cube)

Now Vasilisa the Wise wants to know by the given set of colors the following: in how many ways would she decorate the box in the worst case to open it? To answer this question it is useful to know that two gems of one color are indistinguishable from each other. Help Vasilisa to solve this challenging problem.

Input

The first line contains exactly 6 characters without spaces from the set {R, O, Y, G, B, V} — they are the colors of gems with which the box should be decorated.

Output

Print the required number of different ways to decorate the box.

Examples

Input

YYYYYY

Output

1

Input

BOOOOB

Output

2

Input

ROYGBV

Output

30

```python
from functools import reduce

def factorial(n):
    return reduce(lambda x, y: x*y, range(1,n+1))

colors = {
    'R' : 0,
    'O' : 0,
    'Y' : 0,
    'G' : 0,
    'B' : 0,
    'V' : 0
}

for c in list(input()):
    colors[c] += 1

amount = list(reversed(sorted([(colors[key], key) for key in colors])))

amount = [x[0] for x in amount]

if amount[0] == 6 or amount[0] == 5:
    print("1")
elif amount[0] == 4:
    print("2")
elif amount[0] == 3:
    if amount[1] == 3:
        print("2")
    elif amount[1] == 2:
        print("3")
    elif amount[1] == 1:
        print("5")
elif amount[0] == 2:
    if amount[1] == amount[2] == 2:
        print("6")
    elif amount[1] == 2:
        print("8")
    else:
        print(factorial(6) // 48)

elif amount[0] == 1:
    print(factorial(6) // 24)

```


p02540 ACL Contest 1 - Reachable Towns

There are N cities on a 2D plane. The coordinate of the i-th city is (x_i, y_i). Here (x_1, x_2, \dots, x_N) and (y_1, y_2, \dots, y_N) are both permuations of (1, 2, \dots, N).

For each k = 1,2,\dots,N, find the answer to the following question:

Rng is in City k. Rng can perform the following move arbitrarily many times:

* move to another city that has a smaller x-coordinate and a smaller y-coordinate, or a larger x-coordinate and a larger y-coordinate, than the city he is currently in.

How many cities (including City k) are reachable from City k?

Constraints

* 1 \leq N \leq 200,000
* (x_1, x_2, \dots, x_N) is a permutation of (1, 2, \dots, N).
* (y_1, y_2, \dots, y_N) is a permutation of (1, 2, \dots, N).
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
x_2 y_2
:
x_N y_N

Output

Print N lines. In i-th line print the answer to the question when k = i.

Examples

Input

4
1 4
2 3
3 1
4 2

Output

1
1
2
2

Input

7
6 4
4 3
3 5
7 1
2 7
5 2
1 6

Output

3
3
1
1
2
3
2

```python
n = int(input())
xy = []
idx = [None]*n
ys = [None]*n
ans = [None]*n
accumx = [None]*n
accumn = [None]*n
for i in range(n):
    x, y = map(int, input().split())
    idx[x-1] = i
    ys[x-1] = y-1
accumx[-1] = ys[-1]
for i in range(n-2, -1, -1):
    accumx[i] = max(accumx[i+1], ys[i])
accumn[0] = ys[0]
for i in range(1, n):
    accumn[i] = min(accumn[i-1], ys[i])

def bisect(x):
    ok = 0
    ng = n
    while abs(ok-ng)>1:
        mid = (ok+ng)//2
        if accumx[mid]>x:
            ok = mid
        else:
            ng = mid
    return ok

nowx = 0
while nowx<n:
    nxtx = nowx
    tmp = bisect(ys[nowx])
    while tmp>nxtx:
        nxtx = tmp
        tmp = bisect(accumn[nxtx])
    if nxtx<nowx:
        nxtx = nowx
    for i in range(nowx, nxtx+1):
        ans[idx[i]] = nxtx-nowx+1
    nowx = nxtx + 1
print(*ans, sep='\n')
```


p02671 AtCoder Grand Contest 044 - Strange Dance

There are 3^N people dancing in circle. We denote with 0,1,\dots, 3^{N}-1 the positions in the circle, starting from an arbitrary position and going around clockwise. Initially each position in the circle is occupied by one person.

The people are going to dance on two kinds of songs: salsa and rumba.

* When a salsa is played, the person in position i goes to position j, where j is the number obtained replacing all digits 1 with 2 and all digits 2 with 1 when reading i in base 3 (e.g., the person in position 46 goes to position 65).
* When a rumba is played, the person in position i moves to position i+1 (with the identification 3^N = 0).

You are given a string T=T_1T_2\cdots T_{|T|} such that T_i=`S` if the i-th song is a salsa and T_i=`R` if it is a rumba. After all the songs have been played, the person that initially was in position i is in position P_i. Compute the array P_0,P_1,\dots, P_{3^N-1}.

Constraints

* 1 \le N \le 12
* 1 \le |T| \le 200,000
* T contains only the characters `S` and `R`.

Input

Input is given from Standard Input in the following format:

N
T

Output

You should print on Standard Output:

P_0 P_1 \cdots P_{3^N-1}

Output

You should print on Standard Output:

P_0 P_1 \cdots P_{3^N-1}

Examples

Input

1
SRS

Output

2 0 1

Input

2
RRSRSSSSR

Output

3 8 1 0 5 7 6 2 4

Input

3
SRSRRSRRRSRRRR

Output

23 9 22 8 3 7 20 24 19 5 18 4 17 12 16 2 6 1 14 0 13 26 21 25 11 15 10

```python
n = int(input())
t = input()

new_pos = [0]
new_w = [0]*len(t)

for i in range(1, n+1):
    ith_bit = [0]*(3**i)  # ith_bit[p] : 位置 (p mod 3**i) のi番目bit
    for k in range(3):
        for l in range(3**(i-1)):
            ith_bit[k*3**(i-1)+l] = k

    pos = new_pos
    w = new_w  # 繰り上がりが起きても ith_bit を正確に捉えるため、j 曲流したあとの "222..22" の位置を把握しておく

    q = 0
    already = [0]*3**i
    new_w = [0]*len(t)

    for j in range(len(t)):
        mark = w[j]
        for k in range(3):
            cand = mark + k*3**(i-1)
            if ith_bit[cand] and (q - already[cand]) % 2:
                # "122..22", "222..22" の最上位 bit のみ Salsa を流す
                ith_bit[cand] = 3 - ith_bit[cand]
            already[cand] = q  # 位置 cand に何回 Salsa を流したか記憶しておく
            if ith_bit[cand] == 2:
                new_w[j] = cand

        if t[j] == 'S':
            q += 1
        else:
            for k in range(3):
                ith_bit[mark + k*3**(i-1)] = (ith_bit[mark + k*3**(i-1)]+1) % 3

    new_pos = [0]*(3**i)
    for j in range(3**i):
        if ith_bit[j] and (q - already[j]) % 2:
            # 全ての位置に Salsa を流す。
            # 曲の途中で "*22..22" が位置 j に訪れている場合、上で Salsa を流してしまっている。
            # その分 already[j] を引く。
            ith_bit[j] = 3-ith_bit[j]
        new_pos[j] = pos[j % 3**(i-1)] + ith_bit[j]*3**(i-1)

print(*new_pos)

```


p02800 Keyence Programming Contest 2020 - Monochromization

We have an H \times W grid, where each square is painted white or black in the initial state. Given are strings A_1, A_2, ..., A_H representing the colors of the squares in the initial state. For each pair (i, j) (1 \leq i \leq H, 1 \leq j \leq W), if the j-th character of A_i is `.`, the square at the i-th row and j-th column is painted white; if that character is `#`, that square is painted black.

Among the 2^{HW} ways for each square in the grid to be painted white or black, how many can be obtained from the initial state by performing the operations below any number of times (possibly zero) in any order? Find this count modulo 998,244,353.

* Choose one row, then paint all the squares in that row white.
* Choose one row, then paint all the squares in that row black.
* Choose one column, then paint all the squares in that column white.
* Choose one column, then paint all the squares in that column black.

Constraints

* 1 \leq H, W \leq 10
* |A_i| = W (1 \leq i \leq H)
* All strings A_i consist of `.` and `#`.
* H and W are integers.

Input

Input is given from Standard Input in the following format:

H W
A_1
A_2
\vdots
A_H

Output

Print the answer.

Examples

Input

2 2
#.
.#

Output

15

Input

2 2
.
.#

Output

15

Input

3 3
...
...
...

Output

230

Input

2 4
...
...#

Output

150

Input

6 7
.......
.......
.#.....
..#....
.#.#...
.......

Output

203949910

```python
import sys
input = sys.stdin.readline

H,W=map(int,input().split())
A=[input().strip() for i in range(H)]

mod=998244353

# factorial,facotiralの逆数を事前計算.
FACT=[1]
for i in range(1,21):
    FACT.append(FACT[-1]*i%mod)

FACT_INV=[pow(FACT[-1],mod-2,mod)]
for i in range(20,0,-1):
    FACT_INV.append(FACT_INV[-1]*i%mod)

FACT_INV.reverse()

COMBI=[[-1]*21 for i in range(21)]
def Combi(a,b):
    if COMBI[a][b]!=-1:
        return COMBI[a][b]

    if 0<=b<=a:
        COMBI[a][b]=FACT[a]*FACT_INV[b]*FACT_INV[a-b]%mod
        return COMBI[a][b]
    else:
        COMBI[a][b]=0
        return 0

M=max(H,W)+1
RA=[[-1]*M for i in range(M)]
def rect(H,W):
    if H==W==0:
        return 1
    if RA[H][W]!=-1:
        return RA[H][W]

    DP=[[[0,0] for j in range(W+1)] for i in range(H+1)] # (h,w)の最後に進んだ向きが縦/横のときの場合の数
    DP[0][0][0]=1
    DP[0][0][1]=1

    for h in range(H+1):
        for w in range(W+1):
            for nexth in range(h+1,H+1):
                DP[nexth][w][0]+=DP[h][w][1]*FACT_INV[nexth-h]
                DP[nexth][w][0]%=mod

            for nextw in range(w+1,W+1):
                DP[h][nextw][1]+=DP[h][w][0]*FACT_INV[nextw-w]
                DP[h][nextw][1]%=mod

    RA[H][W]=RA[W][H]=sum(DP[H][W])%mod*FACT[H]*FACT[W]%mod

    return RA[H][W]

CA=[[-1]*(W+1) for i in range(H+1)]
def calc(h,w):
    if CA[h][w]!=-1:
        return CA[h][w]

    RET=0

    for bh in range(h+1):
        for bw in range(w+1):
            RET+=rect(bh,w-bw)*rect(h-bh,bw)*Combi(h,bh)*Combi(w,bw)
            #print(bh,bw,w-bw,h-bh,rect(bh,w-bw),rect(h-bh,bw),Combi(h,bh),Combi(w,bw))
            RET%=mod

    CA[h][w]=RET%mod
    return CA[h][w]

for i in range(H+1):
    for j in range(W+1):
        calc(i,j)

ANS=rect(H,W)

for i in range((1<<H)-1):
    for j in range((1<<W)-1):
        okflag=1
        for h in range(H):
            if i & (1<<h)!=0:
                continue
            coinc=""
            dif=0
            for w in range(W):
                if j & (1<<w)!=0:
                    continue

                if coinc=="":
                    coinc=A[h][w]
                elif A[h][w]!=coinc:
                    dif=1
                    break

            if dif==0:
                okflag=0
                break

        if okflag==0:
            continue

        okflag=1
        for w in range(W):
            if j & (1<<w)!=0:
                continue
            coinc=""
            dif=0
            for h in range(H):
                if i & (1<<h)!=0:
                    continue

                if coinc=="":
                    coinc=A[h][w]
                elif A[h][w]!=coinc:
                    dif=1
                    break

            if dif==0:
                okflag=0
                break

        if okflag==0:
            continue

        # i, jのうち、0の部分は決定済み. 1の部分に自由度がある.
        HR=WR=0
        for h in range(H):
            if i & (1<<h)!=0:
                HR+=1
        for w in range(W):
            if j & (1<<w)!=0:
                WR+=1

        ANS+=CA[HR][WR]

        #ANS%=mod

print(ANS%mod)
```


p02936 AtCoder Beginner Contest 138 - Ki

Given is a rooted tree with N vertices numbered 1 to N. The root is Vertex 1, and the i-th edge (1 \leq i \leq N - 1) connects Vertex a_i and b_i.

Each of the vertices has a counter installed. Initially, the counters on all the vertices have the value 0.

Now, the following Q operations will be performed:

* Operation j (1 \leq j \leq Q): Increment by x_j the counter on every vertex contained in the subtree rooted at Vertex p_j.

Find the value of the counter on each vertex after all operations.

Constraints

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

Input

Input is given from Standard Input in the following format:

N Q
a_1 b_1
:
a_{N-1} b_{N-1}
p_1 x_1
:
p_Q x_Q

Output

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

Examples

Input

4 3
1 2
2 3
2 4
2 10
1 100
3 1

Output

100 110 111 110

Input

6 2
1 2
1 3
2 4
3 6
2 5
1 10
1 10

Output

20 20 20 20 20 20

```python
import sys
sys.setrecursionlimit(10**7)
input = sys.stdin.readline
n,q=map(int,input().split())
c=[[] for _ in range(n)]
for _ in range(n-1):
  a,b=map(int,input().split())
  a,b=a-1,b-1
  c[a].append(b)
  c[b].append(a)
px=[0]*n
for I in range(q):
    p,x=map(int,input().split())
    px[p-1]+=x
ans=[0]*n
def dfs(g,h=-1):
  ans[g]=ans[h]+px[g]
  for i in c[g]:
    if i==h:continue
    dfs(i,g)
dfs(0)
print(*ans)

```


p03073 AtCoder Beginner Contest 124 - Coloring Colorfully

N tiles are arranged in a row from left to right. The initial color of each tile is represented by a string S of length N.

The i-th tile from the left is painted black if the i-th character of S is `0`, and painted white if that character is `1`.

You want to repaint some of the tiles black or white, so that any two adjacent tiles have different colors.

At least how many tiles need to be repainted to satisfy the condition?

Constraints

* 1 \leq |S| \leq 10^5
* S_i is `0` or `1`.

Input

Input is given from Standard Input in the following format:

S

Output

Print the minimum number of tiles that need to be repainted to satisfy the condition.

Examples

Input

000

Output

1

Input

10010010

Output

3

Input

0

Output

0

```python
s=input();z=sum([int(s[i])==i%2 for i in range(len(s))]);print(min(z,len(s)-z))
```


p03215 Dwango Programming Contest V - Sum AND Subarrays

One day, Niwango-kun, an employee of Dwango Co., Ltd., found an integer sequence (a_1, ..., a_N) of length N. He is interested in properties of the sequence a.

For a nonempty contiguous subsequence a_l, ..., a_r (1 \leq l \leq r \leq N) of the sequence a, its beauty is defined as a_l + ... + a_r. Niwango-kun wants to know the maximum possible value of the bitwise AND of the beauties of K nonempty contiguous subsequences among all N(N+1)/2 nonempty contiguous subsequences. (Subsequences may share elements.)

Find the maximum possible value for him.

Constraints

* 2 \leq N \leq 1000
* 1 \leq a_i \leq 10^9
* 1 \leq K \leq N(N+1)/2
* All numbers given in input are integers

Input

Input is given from Standard Input in the following format:

N K
a_1 a_2 ... a_N

Output

Print the answer.

Examples

Input

4 2
2 5 2 5

Output

12

Input

8 4
9 1 8 2 7 5 6 4

Output

32

```python
import sys
input = sys.stdin.readline
n, k = map(int,input().split())
A = list(map(int,input().split()))
S = [0]
for i in range(n):
    S.append(A[i] + S[-1])
B = []
for i in range(len(S)):
    for j in range(i+1, len(S)):
        B.append(S[j] - S[i])
# B.sort()
# print(B)

ans = 0
for i in range(50, -1, -1):
    ans += 2**i
    c = 0
    for j in range(len(B)):
        if B[j] & ans == ans:
            c += 1
    # print(i, c)
    if c < k:
        ans -= 2**i
print(ans)
```


p03364 AtCoder Grand Contest 023 - Find Symmetries

Snuke has two boards, each divided into a grid with N rows and N columns. For both of these boards, the square at the i-th row from the top and the j-th column from the left is called Square (i,j).

There is a lowercase English letter written in each square on the first board. The letter written in Square (i,j) is S_{i,j}. On the second board, nothing is written yet.

Snuke will write letters on the second board, as follows:

* First, choose two integers A and B ( 0 \leq A, B < N ).
* Write one letter in each square on the second board. Specifically, write the letter written in Square ( i+A, j+B ) on the first board into Square (i,j) on the second board. Here, the k-th row is also represented as the (N+k)-th row, and the k-th column is also represented as the (N+k)-th column.

After this operation, the second board is called a good board when, for every i and j ( 1 \leq i, j \leq N ), the letter in Square (i,j) and the letter in Square (j,i) are equal.

Find the number of the ways to choose integers A and B ( 0 \leq A, B < N ) such that the second board is a good board.

Constraints

* 1 \leq N \leq 300
* S_{i,j} ( 1 \leq i, j \leq N ) is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

N
S_{1,1}S_{1,2}..S_{1,N}
S_{2,1}S_{2,2}..S_{2,N}
:
S_{N,1}S_{N,2}..S_{N,N}

Output

Print the number of the ways to choose integers A and B ( 0 \leq A, B < N ) such that the second board is a good board.

Examples

Input

2
ab
ca

Output

2

Input

4
aaaa
aaaa
aaaa
aaaa

Output

16

Input

5
abcde
fghij
klmno
pqrst
uvwxy

Output

0

```python
#023_B
n = int(input())
s = [input() * 2 for _ in range(n)]
ans = 0
for b in range(0, n):
    flg = True
    for i in range(n):
        for j in range(n):
            if s[i][b+j] != s[j][b+i]:
                flg = False
                break
    if flg:
        ans += 1

print(ans * n)
```


p03687 AtCoder Grand Contest 016 - Shrinking

Snuke can change a string t of length N into a string t' of length N - 1 under the following rule:

* For each i (1 ≤ i ≤ N - 1), the i-th character of t' must be either the i-th or (i + 1)-th character of t.

There is a string s consisting of lowercase English letters. Snuke's objective is to apply the above operation to s repeatedly so that all the characters in s are the same. Find the minimum necessary number of operations.

Constraints

* 1 ≤ |s| ≤ 100
* s consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s

Output

Print the minimum necessary number of operations to achieve the objective.

Examples

Input

serval

Output

3

Input

jackal

Output

2

Input

zzz

Output

0

Input

whbrjpjyhsrywlqjxdbrbaomnw

Output

8

```python
s = input().strip()
l = len(s)
d, a = {}, {}
for i, c in enumerate(s):
    if c in d:
        d[c] = max(d[c], i - a[c])
    else:
        d[c] = i
    a[c] = i + 1
for c, v in d.items():
    d[c] = max(v, l - a[c])
print(min(d.values()))

```


p03840 AtCoder Grand Contest 008 - Tetromino Tiling

A tetromino is a figure formed by joining four squares edge to edge. We will refer to the following seven kinds of tetromino as I-, O-, T-, J-, L-, S- and Z-tetrominos, respectively:

a60bcb8e9e8f22e3af51049eda063392.png

Snuke has many tetrominos. The number of I-, O-, T-, J-, L-, S- and Z-tetrominos in his possession are a_I, a_O, a_T, a_J, a_L, a_S and a_Z, respectively. Snuke will join K of his tetrominos to form a rectangle that is two squares tall and 2K squares wide. Here, the following rules must be followed:

* When placing each tetromino, rotation is allowed, but reflection is not.
* Each square in the rectangle must be covered by exactly one tetromino.
* No part of each tetromino may be outside the rectangle.

Snuke wants to form as large a rectangle as possible. Find the maximum possible value of K.

Constraints

* 0≤a_I,a_O,a_T,a_J,a_L,a_S,a_Z≤10^9
* a_I+a_O+a_T+a_J+a_L+a_S+a_Z≥1

Input

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

a_I a_O a_T a_J a_L a_S a_Z

Output

Print the maximum possible value of K. If no rectangle can be formed, print `0`.

Examples

Input

2 1 1 0 0 0 0

Output

3

Input

0 0 10 0 0 0 0

Output

0


p04007 AtCoder Grand Contest 004 - AND Grid

Snuke and Ciel went to a strange stationery store. Each of them got a transparent graph paper with H rows and W columns.

Snuke painted some of the cells red in his paper. Here, the cells painted red were 4-connected, that is, it was possible to traverse from any red cell to any other red cell, by moving to vertically or horizontally adjacent red cells only.

Ciel painted some of the cells blue in her paper. Here, the cells painted blue were 4-connected.

Afterwards, they precisely overlaid the two sheets in the same direction. Then, the intersection of the red cells and the blue cells appeared purple.

You are given a matrix of letters a_{ij} (1≤i≤H, 1≤j≤W) that describes the positions of the purple cells. If the cell at the i-th row and j-th column is purple, then a_{ij} is `#`, otherwise a_{ij} is `.`. Here, it is guaranteed that no outermost cell is purple. That is, if i=1, H or j = 1, W, then a_{ij} is `.`.

Find a pair of the set of the positions of the red cells and the blue cells that is consistent with the situation described. It can be shown that a solution always exists.

Constraints

* 3≤H,W≤500
* a_{ij} is `#` or `.`.
* If i=1,H or j=1,W, then a_{ij} is `.`.
* At least one of a_{ij} is `#`.

Input

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

H W
a_{11}...a_{1W}
:
a_{H1}...a_{HW}

Output

Print a pair of the set of the positions of the red cells and the blue cells that is consistent with the situation, as follows:

* The first H lines should describe the positions of the red cells.
* The following 1 line should be empty.
* The following H lines should describe the positions of the blue cells.

The description of the positions of the red or blue cells should follow the format of the description of the positions of the purple cells.

Examples

Input

5 5
.....
.#.#.
.....
.#.#.
.....

Output

.....
#####
#....
#####
.....

.###.
.#.#.
.#.#.
.#.#.
.....

Input

7 13
.............
.###.###.###.
.#.#.#...#...
.###.#...#...
.#.#.#.#.#...
.#.#.###.###.
.............

Output

.............
.###########.
.###.###.###.
.###.###.###.
.###.###.###.
.###.###.###.
.............

.............
.###.###.###.
.#.#.#...#...
.###.#...#...
.#.#.#.#.#...
.#.#########.
.............

```python
h, w = map(int, input().split())
ans1 = [['.'] * w for _ in range(h)]
ans2 = [['.'] * w for _ in range(h)]
for i in range(h):
    ans1[i][0] = '#'
    ans2[i][-1] = '#'
    if i % 2:
        for j in range(w - 1):
            ans1[i][j] = '#'
    else:
        for j in range(1, w):
            ans2[i][j] = '#'
for i in range(h):
    s = input()
    for j in range(w):
        if s[j] == '#':
            ans1[i][j] = '#'
            ans2[i][j] = '#'
for row in ans1:
    print(''.join(row))
print()
for row in ans2:
    print(''.join(row))

```


p00093 Leap Year

Create a program that outputs all leap years between the year a and year b.

The leap year conditions are as follows. However, 0 <a ≤ b <3,000. If there is no leap year in the given period, output "NA".

* The year is divisible by 4.
* However, a year divisible by 100 is not a leap year.
* However, a year divisible by 400 is a leap year.

Input

Given multiple datasets. The format of each dataset is as follows:

a b

Input ends when both a and b are 0. The number of datasets does not exceed 50.

Output

Print the year or NA for each dataset.

Insert one blank line between the datasets.

Example

Input

2001 2010
2005 2005
2001 2010
0 0

Output

2004
2008

NA

2004
2008

```python
# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0093
???????????´
"""
import sys

def is_leap(year):
    ''' ?????????????????´??? ???????????´ ???????????????True/False??§?????? '''
    if year % 400 == 0:
        return True
    elif year % 100 == 0:
        return False
    elif year % 4 == 0:
        return True
    else:
        return False

def main(args):
    is_first__dataset = True
    leap_years = []  # ???????????´????????????
    # ??????????????\???
    while True:
        start_year, end_year = [int(x) for x in input().strip().split(' ')]
        if start_year == 0 and end_year == 0:
            break
        else:
            # ???????????????
            leap_years = []
            for year in range(start_year, end_year+1):
                if is_leap(year):
                    leap_years.append(year)

        # ???????????????
        if is_first__dataset == True:
            is_first__dataset = False
        else:
            print('')  # ????????????????????????1????????????

        if len(leap_years) == 0:
            print('NA')
        else:
            print('{0}'.format('\n'.join(map(str, leap_years))))

if __name__ == '__main__':
    main(sys.argv[1:])
```


p00225 Kobutanukitsuneko

Relative B man came to A child's house. He is 3 years old and loves singing. He is singing the song "Kobutanuki Tsuneko" (written and composed by Naozumi Yamamoto), which he learned from kindergarten. In this song, the four words "kobuta," "raccoon dog," "fox," and "cat" are arranged in order, and the last and first sounds are the same. Mr. B was asked by Mr. A to tell him if he could make a similar shiritori from the words that Mr. B said.

So, in order to help Ako, from the given words, use all the words to make a shiritori in order, and then the first letter of the first word and the last letter of the last word are the same. Let's write a program that determines whether or not it can be done.

Create a program that takes n words as input, determines whether or not a shiritori can be created from those word pairs, and outputs OK if possible and NG if not.

Input

A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format:

n
word1
word2
::
wordn

The number of words n (2 ≤ n ≤ 10000) is given on the first line. The next n lines are given n words wordi (a string of up to 32 single-byte lowercase letters).

The number of datasets does not exceed 50.

Output

The judgment result is output to one line for each input data set.

Example

Input

5
apple
yellow
georgia
king
email
7
apple
yellow
georgia
king
email
wink
lucky
0

Output

NG
OK

```python
from collections import*

def searchnode(i,u,path):  #つなげるものの個数の確認
    r = 1
    u[i] = 1
#    print(u)
    for j in range(26):
        if path[(i,j)] and (not u[j]):
            r += searchnode(j,u,path)
    return r

def chrtoint(a):
    return ord(a)-ord('a')

while 1:
    n = int(input())
    if n==0:
        break
    inp=[input()for i in range(n)]
    front,back = [0]*26,[0]*26
    path = defaultdict(int)
    u = [0]*26

    for i in inp:
        front[chrtoint(i[0])] += 1
        back[chrtoint(i[-1])] += 1
        path[(chrtoint(i[0]),chrtoint(i[-1]))] += 1

#    print(path)
    if front!=back:
        print("NG")
        continue
    if sum(i!=0 for i in front) == searchnode(chrtoint(i[-1]),u,path):
        print("OK")
    else:
        print("NG")

```


p00387 Party Dress

Yae joins a journey plan, in which parties will be held several times during the itinerary. She wants to participate in all of them and will carry several dresses with her. But the number of dresses she can carry with her may be smaller than that of the party opportunities. In that case, she has to wear some of her dresses more than once.

Fashion-conscious Yae wants to avoid that. At least, she wants to reduce the maximum number of times she has to wear the same dress as far as possible.

Given the number of dresses and frequency of parties, make a program to determine how she can reduce the maximum frequency of wearing the most reused dress.

Input

The input is given in the following format.

$A$ $B$

The input line provides the number of dresses $A$ ($1 \leq A \leq 10^5$) and frequency of parties $B$ ($1 \leq B \leq 10^5$).

Output

Output the frequency she has to wear the most reused dress.

Examples

Input

3 5

Output

2

Input

25 10

Output

1

```python
n,m = list(map(int,input().split()))
print(max(m//n+(m%n != 0),1))

```


p00603 Riffle Shuffle

There are a number of ways to shuffle a deck of cards. Riffle shuffle is one such example. The following is how to perform riffle shuffle.

There is a deck of n cards. First, we divide it into two decks; deck A which consists of the top half of it and deck B of the bottom half. Deck A will have one more card when n is odd.

Next, c cards are pulled from bottom of deck A and are stacked on deck C, which is empty initially. Then c cards are pulled from bottom of deck B and stacked on deck C, likewise. This operation is repeated until deck A and B become empty. When the number of cards of deck A(B) is less than c, all cards are pulled. Finally we obtain shuffled deck C. See an example below:

- A single riffle operation where n = 9, c = 3

for given deck [0 1 2 3 4 5 6 7 8]  (right is top)

- Step 0
deck A [4 5 6 7 8]
deck B [0 1 2 3]
deck C []

- Step 1
deck A [7 8]
deck B [0 1 2 3]
deck C [4 5 6]

- Step 2
deck A [7 8]
deck B [3]
deck C [4 5 6 0 1 2]

- Step 3
deck A []
deck B [3]
deck C [4 5 6 0 1 2 7 8]

- Step 4
deck A []
deck B []
deck C [4 5 6 0 1 2 7 8 3]

shuffled deck [4 5 6 0 1 2 7 8 3]

This operation, called riffle operation, is repeated several times.

Write a program that simulates Riffle shuffle and answer which card will be finally placed on the top of the deck.

Input

The input consists of multiple data sets. Each data set starts with a line containing two positive integers n(1 ≤ n ≤ 50) and r(1 ≤ r ≤ 50); n and r are the number of cards in the deck and the number of riffle operations, respectively.

r more positive integers follow, each of which represents a riffle operation. These riffle operations are performed in the listed order. Each integer represents c, which is explained above.

The end of the input is indicated by EOF. The number of data sets is less than 100.

Output

For each data set in the input, your program should print the number of the top card after the shuffle. Assume that at the beginning the cards are numbered from 0 to n-1, from the bottom to the top. Each number should be written in a sparate line without any superfluous characters such as leading or following spaces.

Example

Input

9 1
3
9 4
1 2 3 4

Output

3
0

```python
from collections import deque
import sys

def suffle(deck, c):
    l = len(deck)
    if l % 2 == 0: mid = l//2
    else: mid = (l-1)//2
    deckA = deck[mid:]
    deckB = deck[:mid]
    deckC = []

    while(len(deckA) != 0 or len(deckB) != 0):
        deckC.extend(deckA[:c])
        deckA = deckA[c:]
        deckC.extend(deckB[:c])
        deckB = deckB[c:]

    return deckC

while(True):
    inp = sys.stdin.readline()
    if not inp: break
    deck = []
    n, r = map(int, inp[:-1].split())
    deck = [i for i in range(n)]
    c_list = map(int, sys.stdin.readline()[:-1].split())
    for c in c_list:
        deck = suffle(deck, c)

    print(deck[-1])
    #print(" ".join(map(str, deck)))
```


p00740 Next Mayor

One of the oddest traditions of the town of Gameston may be that even the town mayor of the next term is chosen according to the result of a game. When the expiration of the term of the mayor approaches, at least three candidates, including the mayor of the time, play a game of pebbles, and the winner will be the next mayor.

The rule of the game of pebbles is as follows. In what follows, n is the number of participating candidates.

Requisites     A round table, a bowl, and plenty of pebbles. Start of the Game      A number of pebbles are put into the bowl; the number is decided by the Administration Commission using some secret stochastic process. All the candidates, numbered from 0 to n-1 sit around the round table, in a counterclockwise order. Initially, the bowl is handed to the serving mayor at the time, who is numbered 0. Game Steps      When a candidate is handed the bowl and if any pebbles are in it, one pebble is taken out of the bowl and is kept, together with those already at hand, if any. If no pebbles are left in the bowl, the candidate puts all the kept pebbles, if any, into the bowl. Then, in either case, the bowl is handed to the next candidate to the right. This step is repeated until the winner is decided. End of the Game      When a candidate takes the last pebble in the bowl, and no other candidates keep any pebbles, the game ends and that candidate with all the pebbles is the winner.

A math teacher of Gameston High, through his analysis, concluded that this game will always end within a finite number of steps, although the number of required steps can be very large.

Input

The input is a sequence of datasets. Each dataset is a line containing two integers n and p separated by a single space. The integer n is the number of the candidates including the current mayor, and the integer p is the total number of the pebbles initially put in the bowl. You may assume 3 ≤ n ≤ 50 and 2 ≤ p ≤ 50.

With the settings given in the input datasets, the game will end within 1000000 (one million) steps.

The end of the input is indicated by a line containing two zeros separated by a single space.

Output

The output should be composed of lines corresponding to input datasets in the same order, each line of which containing the candidate number of the winner. No other characters should appear in the output.

Sample Input

3 2
3 3
3 50
10 29
31 32
50 2
50 50
0 0

Output for the Sample Input

1
0
1
5
30
1
13

Example

Input

3 2
3 3
3 50
10 29
31 32
50 2
50 50
0 0

Output

1
0
1
5
30
1
13

```python
while True:
  n, p = map(int, input().split())
  if n == 0:
    break
  lst = [0] * n
  ind = 0
  rest = p
  while True:
    if rest == 0:
      rest = lst[ind]
      lst[ind] = 0
    else:
      lst[ind] += 1
      rest -= 1
      if lst[ind] == p:
        print(ind)
        break
    ind = (ind + 1) % n

```