1157_E. Minimum Array

You are given two arrays a and b, both of length n. All elements of both arrays are from 0 to n-1.

You can reorder elements of the array b (if you want, you may leave the order of elements as it is). After that, let array c be the array of length n, the i-th element of this array is c_i = (a_i + b_i) \% n, where x \% y is x modulo y.

Your task is to reorder elements of the array b to obtain the lexicographically minimum possible array c.

Array x of length n is lexicographically less than array y of length n, if there exists such i (1 ≤ i ≤ n), that x_i < y_i, and for any j (1 ≤ j < i) x_j = y_j.

Input

The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a, b and c.

The second line of the input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i < n), where a_i is the i-th element of a.

The third line of the input contains n integers b_1, b_2, ..., b_n (0 ≤ b_i < n), where b_i is the i-th element of b.

Output

Print the lexicographically minimum possible array c. Recall that your task is to reorder elements of the array b and obtain the lexicographically minimum possible array c, where the i-th element of c is c_i = (a_i + b_i) \% n.

Examples

Input

4
0 1 2 1
3 2 1 1

Output

1 0 0 2

Input

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

Output

0 0 0 1 0 2 4

```python

class SegmentTree:

    @classmethod
    def all_identity(cls, operator, equality, identity, size):
        return cls(operator, equality, identity, [identity]*(2 << (size-1).bit_length()))

    @classmethod
    def from_initial_data(cls, operator, equality, identity, data):
        size = 1 << (len(data)-1).bit_length()
        temp = [identity]*(2*size)
        temp[size:size+len(data)] = data
        data = temp

        for i in reversed(range(size)):
            data[i] = operator(data[2*i],data[2*i+1])
        return cls(operator, equality, identity, data)

    def __init__(self, operator, equality, identity, data):
        if equality is None:
            equality = lambda a,b: False
        self.op = operator
        self.eq = equality
        self.id = identity
        self.data = data
        self.size = len(data)//2

    def _interval(self, a, b):
        a += self.size
        b += self.size
        ra = self.id
        rb = self.id

        data = self.data
        op = self.op
        while a < b:
            if a & 1:
                ra = op(ra,data[a])
                a += 1
            if b & 1:
                b -= 1
                rb = op(data[b],rb)
            a >>= 1
            b >>= 1
        return op(ra,rb)

    def __getitem__(self, i):
        if isinstance(i, slice):
            return self._interval(
                                    0 if i.start is None else i.start,
                                    self.size if i.stop is None else i.stop)
        elif isinstance(i, int):
            return self.data[i+self.size]

    def __setitem__(self, i, v):
        i += self.size
        data = self.data
        op = self.op
        eq = self.eq
        while i and not eq(data[i],v):
            data[i] = v
            v = op(data[i^1],v) if i & 1 else op(v,data[i^1])
            i >>= 1

    def __iter__(self):
        return self.data[self.size:]

def solve(A,B):
    from operator import eq

    N = len(B)

    counts = [0]*N
    for b in B:
        counts[b] += 1

    init_data = [i if counts[i] > 0 else N for i in range(N)]

    seg = SegmentTree.from_initial_data(min, eq, N, init_data)

    def it():
        for a in A:
            best_b = -a%N

            p = seg[best_b:]
            if p == N:
                p = seg[:best_b]
            counts[p] -= 1
            if counts[p] == 0:
                seg[p] = N
            yield (a+p)%N
    return tuple(it())

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

    res = solve(A,B)
    print(*res)

main()
```


117_B. Very Interesting Game

In a very ancient country the following game was popular. Two people play the game. Initially first player writes a string s1, consisting of exactly nine digits and representing a number that does not exceed a. After that second player looks at s1 and writes a string s2, consisting of exactly nine digits and representing a number that does not exceed b. Here a and b are some given constants, s1 and s2 are chosen by the players. The strings are allowed to contain leading zeroes.

If a number obtained by the concatenation (joining together) of strings s1 and s2 is divisible by mod, then the second player wins. Otherwise the first player wins. You are given numbers a, b, mod. Your task is to determine who wins if both players play in the optimal manner. If the first player wins, you are also required to find the lexicographically minimum winning move.

Input

The first line contains three integers a, b, mod (0 ≤ a, b ≤ 109, 1 ≤ mod ≤ 107).

Output

If the first player wins, print "1" and the lexicographically minimum string s1 he has to write to win. If the second player wins, print the single number "2".

Examples

Input

1 10 7

Output

2

Input

4 0 9

Output

1 000000001

Note

The lexical comparison of strings is performed by the < operator in modern programming languages. String x is lexicographically less than string y if exists such i (1 ≤ i ≤ 9), that xi < yi, and for any j (1 ≤ j < i) xj = yj. These strings always have length 9.

```python
a, b, m = map(int, input().split())
k = s = 10 ** 9 % m
i = 0
while k and i < a:
    i += 1
    if k < m - b: exit(print(1, str(i).zfill(9)))
    k += s
    if k >= m: k -= m
print(2)
```


1198_C. Matching vs Independent Set

You are given a graph with 3 ⋅ n vertices and m edges. You are to find a matching of n edges, or an independent set of n vertices.

A set of edges is called a matching if no two edges share an endpoint.

A set of vertices is called an independent set if no two vertices are connected with an edge.

Input

The first line contains a single integer T ≥ 1 — the number of graphs you need to process. The description of T graphs follows.

The first line of description of a single graph contains two integers n and m, where 3 ⋅ n is the number of vertices, and m is the number of edges in the graph (1 ≤ n ≤ 10^{5}, 0 ≤ m ≤ 5 ⋅ 10^{5}).

Each of the next m lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ 3 ⋅ n), meaning that there is an edge between vertices v_i and u_i.

It is guaranteed that there are no self-loops and no multiple edges in the graph.

It is guaranteed that the sum of all n over all graphs in a single test does not exceed 10^{5}, and the sum of all m over all graphs in a single test does not exceed 5 ⋅ 10^{5}.

Output

Print your answer for each of the T graphs. Output your answer for a single graph in the following format.

If you found a matching of size n, on the first line print "Matching" (without quotes), and on the second line print n integers — the indices of the edges in the matching. The edges are numbered from 1 to m in the input order.

If you found an independent set of size n, on the first line print "IndSet" (without quotes), and on the second line print n integers — the indices of the vertices in the independent set.

If there is no matching and no independent set of the specified size, print "Impossible" (without quotes).

You can print edges and vertices in any order.

If there are several solutions, print any. In particular, if there are both a matching of size n, and an independent set of size n, then you should print exactly one of such matchings or exactly one of such independent sets.

Example

Input

4
1 2
1 3
1 2
1 2
1 3
1 2
2 5
1 2
3 1
1 4
5 1
1 6
2 15
1 2
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
4 5
4 6
5 6

Output

Matching
2
IndSet
1
IndSet
2 4
Matching
1 15

Note

The first two graphs are same, and there are both a matching of size 1 and an independent set of size 1. Any of these matchings and independent sets is a correct answer.

The third graph does not have a matching of size 2, however, there is an independent set of size 2. Moreover, there is an independent set of size 5: 2 3 4 5 6. However such answer is not correct, because you are asked to find an independent set (or matching) of size exactly n.

The fourth graph does not have an independent set of size 2, but there is a matching of size 2.

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

T = int(input())
for _ in range(T):
    N, M = map(int, input().split())
    X = [[] for i in range(3*N)]
    for i in range(M):
        x, y = map(int, input().split())
        x, y = min(x,y), max(x,y)
        X[x-1].append((y-1, i+1))

    MAT = []
    IND = []
    DONE = [0] * 3*N
    for i in range(3*N):
        if DONE[i]: continue
        for j, ind in X[i]:
            if DONE[j] == 0:
                MAT.append(ind)
                DONE[i] = 1
                DONE[j] = 1
                break
        else:
            IND.append(i+1)

    if len(MAT) >= N:
        print("Matching")
        print(*MAT[:N])
    else:
        print("IndSet")
        print(*IND[:N])

```


1215_B. The Number of Products

You are given a sequence a_1, a_2, ..., a_n consisting of n non-zero integers (i.e. a_i ≠ 0).

You have to calculate two following values:

  1. the number of pairs of indices (l, r) (l ≤ r) such that a_l ⋅ a_{l + 1} ... a_{r - 1} ⋅ a_r is negative;
  2. the number of pairs of indices (l, r) (l ≤ r) such that a_l ⋅ a_{l + 1} ... a_{r - 1} ⋅ a_r is positive;

Input

The first line contains one integer n (1 ≤ n ≤ 2 ⋅ 10^{5}) — the number of elements in the sequence.

The second line contains n integers a_1, a_2, ..., a_n (-10^{9} ≤ a_i ≤ 10^{9}; a_i ≠ 0) — the elements of the sequence.

Output

Print two integers — the number of subsegments with negative product and the number of subsegments with positive product, respectively.

Examples

Input

5
5 -3 3 -1 1

Output

8 7

Input

10
4 2 -4 3 1 2 -4 3 2 3

Output

28 27

Input

5
-1 -2 -3 -4 -5

Output

9 6

```python
input()
a=list(map(int,input().split()))
q,w,e,t,y=0,0,1,0,0
for i in a:
    if e>0:
        q+=1
        if i>0:
            e=1
        else:
            e=-1
    else:
        w+=1
        if i>0:
            e=-1
        else:
            e=1
    if e>0:
        t+=q
        y+=w
    else:
        t+=w
        y+=q
print(y,t)
```


1238_D. AB-string

The string t_1t_2 ... t_k is good if each letter of this string belongs to at least one palindrome of length greater than 1.

A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.

Here are some examples of good strings:

  * t = AABBB (letters t_1, t_2 belong to palindrome t_1 ... t_2 and letters t_3, t_4, t_5 belong to palindrome t_3 ... t_5);
  * t = ABAA (letters t_1, t_2, t_3 belong to palindrome t_1 ... t_3 and letter t_4 belongs to palindrome t_3 ... t_4);
  * t = AAAAA (all letters belong to palindrome t_1 ... t_5);

You are given a string s of length n, consisting of only letters A and B.

You have to calculate the number of good substrings of string s.

Input

The first line contains one integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the length of the string s.

The second line contains the string s, consisting of letters A and B.

Output

Print one integer — the number of good substrings of string s.

Examples

Input

5
AABBB

Output

6

Input

3
AAA

Output

3

Input

7
AAABABB

Output

15

Note

In the first test case there are six good substrings: s_1 ... s_2, s_1 ... s_4, s_1 ... s_5, s_3 ... s_4, s_3 ... s_5 and s_4 ... s_5.

In the second test case there are three good substrings: s_1 ... s_2, s_1 ... s_3 and s_2 ... s_3.

```python
from sys import stdin
n = int(input())
s = stdin.read(n)
ans = n*(n-1)//2
k = 0
m = 0
for i in range(1, n):
    p = s[i-1]
    t = s[i]
    if p == t:
        k+=1
    else:
        ans -= k*(1<<m)+1
        m |= 1
        k = 0
else:
    ans -= k*m
print(ans)

```


1256_E. Yet Another Division Into Teams

There are n students at your university. The programming skill of the i-th student is a_i. As a coach, you want to divide them into teams to prepare them for the upcoming ICPC finals. Just imagine how good this university is if it has 2 ⋅ 10^5 students ready for the finals!

Each team should consist of at least three students. Each student should belong to exactly one team. The diversity of a team is the difference between the maximum programming skill of some student that belongs to this team and the minimum programming skill of some student that belongs to this team (in other words, if the team consists of k students with programming skills a[i_1], a[i_2], ..., a[i_k], then the diversity of this team is max_{j=1}^{k} a[i_j] - min_{j=1}^{k} a[i_j]).

The total diversity is the sum of diversities of all teams formed.

Your task is to minimize the total diversity of the division of students and find the optimal way to divide the students.

Input

The first line of the input contains one integer n (3 ≤ n ≤ 2 ⋅ 10^5) — the number of students.

The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the programming skill of the i-th student.

Output

In the first line print two integers res and k — the minimum total diversity of the division of students and the number of teams in your division, correspondingly.

In the second line print n integers t_1, t_2, ..., t_n (1 ≤ t_i ≤ k), where t_i is the number of team to which the i-th student belong.

If there are multiple answers, you can print any. Note that you don't need to minimize the number of teams. Each team should consist of at least three students.

Examples

Input

5
1 1 3 4 2

Output

3 1
1 1 1 1 1

Input

6
1 5 12 13 2 15

Output

7 2
2 2 1 1 2 1

Input

10
1 2 5 129 185 581 1041 1909 1580 8150

Output

7486 3
3 3 3 2 2 2 2 1 1 1

Note

In the first example, there is only one team with skills [1, 1, 2, 3, 4] so the answer is 3. It can be shown that you cannot achieve a better answer.

In the second example, there are two teams with skills [1, 2, 5] and [12, 13, 15] so the answer is 4 + 3 = 7.

In the third example, there are three teams with skills [1, 2, 5], [129, 185, 581, 1041] and [1580, 1909, 8150] so the answer is 4 + 912 + 6570 = 7486.

```python

def main():

    n=int(input())
    a=readIntArr()

    a2=[[x,i+1] for i,x in enumerate(a)] # [value, index]
    a2.sort(key=lambda x:x[0]) # sort by value asc

    dp=[inf for _ in range(n)] # dp[i] is the min diversity achievable at i
    #dp[i]=min(ai-aj+dp[j-1])=min(a[i]+(dp[j-1]-a[j]))=a[i]+dp2[i-2]
    dp2=[inf for _ in range(n)] # dp2[j] is the min dp[j-1]-a[j] so far (prefix min)
    dp2i=[-1 for _ in range(n)] # dp2i[i] stores the index where dp2[i] was previously minimised

    for i in range(2,min(n,5)):
        dp[i]=a2[i][0]-a2[0][0]

        dp2[i]=dp[i-1]-a2[i][0]
        dp2i[i]=i
        if dp2[i]>=dp2[i-1]:
            dp2i[i]=dp2i[i-1]
            dp2[i]=dp2[i-1]

    for i in range(5,n):
        dp2[i]=dp[i-1]-a2[i][0]
        dp2i[i]=i
        if dp2[i]>=dp2[i-1]:
            dp2i[i]=dp2i[i-1]
            dp2[i]=dp2[i-1]

        dp[i]=a2[i][0]+dp2[i-2]
        # print('i:{} a2[i][0]:{} dp2[i-2]:{}'.format(i,a2[i][0],dp2[i-2]))

    # print('a2:{}'.format(a2))
    # print('dp:{}'.format(dp))
    # print('dp2:{}'.format(dp2))
    # print('dp2i:{}'.format(dp2i))

    minDiversity=dp[n-1]

    groups=[]
    right=n-1
    while True:
        left=dp2i[right-2]
        if left==-1:
            left=0
        temp=[]
        for i in range(left,right+1):
            temp.append(a2[i][1])
        groups.append(temp)
        if left==0:
            break
        right=left-1

    nGroups=len(groups)

    grouping=[-1 for _ in range(n)]
    for i in range(nGroups):
        for student in groups[i]:
            grouping[student-1]=i+1

    print('{} {}'.format(minDiversity,nGroups))
    oneLineArrayPrint(grouping)

    return

import sys
# input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.

def oneLineArrayPrint(arr):
    print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
    print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
    print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
    return [int(x) for x in input().split()]
# def readFloatArr():
#     return [float(x) for x in input().split()]

def makeArr(defaultVal,dimensionArr): # eg. makeArr(0,[n,m])
    dv=defaultVal;da=dimensionArr
    if len(da)==1:return [dv for _ in range(da[0])]
    else:return [makeArr(dv,da[1:]) for _ in range(da[0])]

def queryInteractive(x,y):
    print('? {} {}'.format(x,y))
    sys.stdout.flush()
    return int(input())

def answerInteractive(ans):
    print('! {}'.format(ans))
    sys.stdout.flush()

inf=float('inf')
MOD=10**9+7

for _abc in range(1):
    main()
```


127_E. E-reader Display

After years of hard work scientists invented an absolutely new e-reader display. The new display has a larger resolution, consumes less energy and its production is cheaper. And besides, one can bend it. The only inconvenience is highly unusual management. For that very reason the developers decided to leave the e-readers' software to programmers.

The display is represented by n × n square of pixels, each of which can be either black or white. The display rows are numbered with integers from 1 to n upside down, the columns are numbered with integers from 1 to n from the left to the right. The display can perform commands like "x, y". When a traditional display fulfills such command, it simply inverts a color of (x, y), where x is the row number and y is the column number. But in our new display every pixel that belongs to at least one of the segments (x, x) - (x, y) and (y, y) - (x, y) (both ends of both segments are included) inverts a color.

For example, if initially a display 5 × 5 in size is absolutely white, then the sequence of commands (1, 4), (3, 5), (5, 1), (3, 3) leads to the following changes:

<image>

You are an e-reader software programmer and you should calculate minimal number of commands needed to display the picture. You can regard all display pixels as initially white.

Input

The first line contains number n (1 ≤ n ≤ 2000).

Next n lines contain n characters each: the description of the picture that needs to be shown. "0" represents the white color and "1" represents the black color.

Output

Print one integer z — the least number of commands needed to display the picture.

Examples

Input

5
01110
10010
10001
10011
11110

Output

4

```python
n=int(input())
T=[]
for i in range(n):
    T.append(input()[::-1])

Val=['0','1']
S=0

L1=[0]*n
C1=[0]*n
for diag in range(n-1):
    for i in range(diag+1):
        l,c=L1[i],C1[diag-i]
        if T[i][diag-i]!=Val[(l+c)%2]:
            S+=1
            L1[i]=1-l
            C1[diag-i]=1-c

L2=[0]*n
C2=[0]*n
for diag in range(n-1):
    for i in range(diag+1):
        l,c=L2[i],C2[diag-i]
        if T[n-diag+i-1][n-i-1]!=Val[(l+c)%2]:
            S+=1
            L2[i]=1-l
            C2[diag-i]=1-c

for i in range(n):
    if Val[(L1[i]+L2[i]+C1[n-i-1]+C2[n-i-1])%2]!=T[i][n-i-1]:
        S+=1

print(S)

```


1342_E. Placing Rooks

Calculate the number of ways to place n rooks on n × n chessboard so that both following conditions are met:

  * each empty cell is under attack;
  * exactly k pairs of rooks attack each other.

An empty cell is under attack if there is at least one rook in the same row or at least one rook in the same column. Two rooks attack each other if they share the same row or column, and there are no other rooks between them. For example, there are only two pairs of rooks that attack each other in the following picture:

<image> One of the ways to place the rooks for n = 3 and k = 2

Two ways to place the rooks are considered different if there exists at least one cell which is empty in one of the ways but contains a rook in another way.

The answer might be large, so print it modulo 998244353.

Input

The only line of the input contains two integers n and k (1 ≤ n ≤ 200000; 0 ≤ k ≤ (n(n - 1))/(2)).

Output

Print one integer — the number of ways to place the rooks, taken modulo 998244353.

Examples

Input

3 2

Output

6

Input

3 3

Output

0

Input

4 0

Output

24

Input

1337 42

Output

807905441

```python
import io,os
input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
import sys
def solve(n,k):
    mod=998244353
    if k==0:
        ans=1
        for i in range(1,n+1):
            ans*=i
            ans%=mod
        return ans
    if k>=n:
        return 0

    inv=lambda x: pow(x,mod-2,mod)
    Fact=[1] #階乗
    for i in range(1,n+1):
        Fact.append(Fact[i-1]*i%mod)
    Finv=[0]*(n+1) #階乗の逆元
    Finv[-1]=inv(Fact[-1])
    for i in range(n-1,-1,-1):
        Finv[i]=Finv[i+1]*(i+1)%mod
    def comb(n,r):
        if n<r:
            return 0
        return Fact[n]*Finv[r]*Finv[n-r]%mod

    m=n-k
    t=1
    ans=0
    for r in range(m,0,-1):
        ans+=t*comb(m,r)*pow(r,n,mod)
        ans%=mod
        t*=-1
    ans*=comb(n,m)*2
    ans%=mod
    return ans

def main():
    n,k=map(int,input().split())
    ans=solve(n,k)
    sys.stdout.write(str(ans)+'\n')

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


1406_C. Link Cut Centroids

Fishing Prince loves trees, and he especially loves trees with only one centroid. The tree is a connected graph without cycles.

A vertex is a centroid of a tree only when you cut this vertex (remove it and remove all edges from this vertex), the size of the largest connected component of the remaining graph is the smallest possible.

For example, the centroid of the following tree is 2, because when you cut it, the size of the largest connected component of the remaining graph is 2 and it can't be smaller.

<image>

However, in some trees, there might be more than one centroid, for example:

<image>

Both vertex 1 and vertex 2 are centroids because the size of the largest connected component is 3 after cutting each of them.

Now Fishing Prince has a tree. He should cut one edge of the tree (it means to remove the edge). After that, he should add one edge. The resulting graph after these two operations should be a tree. He can add the edge that he cut.

He wants the centroid of the resulting tree to be unique. Help him and find any possible way to make the operations. It can be proved, that at least one such way always exists.

Input

The input consists of multiple test cases. The first line contains an integer t (1≤ t≤ 10^4) — the number of test cases. The description of the test cases follows.

The first line of each test case contains an integer n (3≤ n≤ 10^5) — the number of vertices.

Each of the next n-1 lines contains two integers x, y (1≤ x,y≤ n). It means, that there exists an edge connecting vertices x and y.

It's guaranteed that the given graph is a tree.

It's guaranteed that the sum of n for all test cases does not exceed 10^5.

Output

For each test case, print two lines.

In the first line print two integers x_1, y_1 (1 ≤ x_1, y_1 ≤ n), which means you cut the edge between vertices x_1 and y_1. There should exist edge connecting vertices x_1 and y_1.

In the second line print two integers x_2, y_2 (1 ≤ x_2, y_2 ≤ n), which means you add the edge between vertices x_2 and y_2.

The graph after these two operations should be a tree.

If there are multiple solutions you can print any.

Example

Input

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

Output

1 2
1 2
1 3
2 3

Note

Note that you can add the same edge that you cut.

In the first test case, after cutting and adding the same edge, the vertex 2 is still the only centroid.

In the second test case, the vertex 2 becomes the only centroid after cutting the edge between vertices 1 and 3 and adding the edge between vertices 2 and 3.

```python
from random import choice as _choice
import sys as _sys

def main():
    t = int(input())
    for i in range(t):
        n, = _read_ints()
        graph = [set() for v in range(n)]
        for i_edge in range(n-1):
            v1, v2 = _read_ints()
            v1 -= 1
            v2 -= 1
            graph[v1].add(v2)
            graph[v2].add(v1)
        operations = find_operations_necessary_to_remain_one_centroid(graph)
        for v1, v2 in operations:
            print(v1+1, v2+1)

def _read_line():
    result = _sys.stdin.readline()
    assert result[-1] == "\n"
    return result[:-1]

def _read_ints():
    return map(int, _read_line().split(" "))

def find_operations_necessary_to_remain_one_centroid(graph):
    assert len(graph) > 2
    graph = [set(neighbors) for neighbors in graph]

    centroids = find_centroids(graph)
    assert 0 < len(centroids) <= 2

    if len(centroids) == 1:
        operation_remove = (0, tuple(graph[0])[0])
        operation_add = operation_remove

    else:
        assert len(centroids) == 2
        centroid_1, centroid_2 = centroids

        vertex_to_move = centroid_1
        forbidden_vertex = centroid_2
        while len(graph[vertex_to_move]) != 1:
            neighbors = tuple(graph[vertex_to_move])
            new_vertex_to_move = neighbors[0]
            if new_vertex_to_move == forbidden_vertex:
                new_vertex_to_move = neighbors[1]
            forbidden_vertex = vertex_to_move
            vertex_to_move = new_vertex_to_move

        vertex_to_move_parent = tuple(graph[vertex_to_move])[0]
        operation_remove = (vertex_to_move, vertex_to_move_parent)
        graph[vertex_to_move].remove(vertex_to_move_parent)
        graph[vertex_to_move_parent].remove(vertex_to_move)
        assert len(graph[vertex_to_move]) == 0

        new_parent = centroid_2
        graph[vertex_to_move].add(new_parent)
        graph[new_parent].add(vertex_to_move)

        operation_add = (vertex_to_move, new_parent)

    return operation_remove, operation_add

def find_centroids(graph):
    vertices_n = len(graph)
    vertices_values = [None] * len(graph)

    leaves = [vertex for vertex in range(len(graph)) if len(graph[vertex]) == 1]
    vertices_accumulated = [None] * len(graph)
    for leave in leaves:
        vertices_accumulated[leave] = 1
        vertices_values[leave] = vertices_n - 1

    active = set().union(*(graph[leave] for leave in leaves))
    passed = set(leaves)
    active -= passed
    while len(passed) < len(graph):
        old_active = active
        active = set()
        for vertex in old_active:
            neighbors = graph[vertex]
            neighbors_not_passed = neighbors - passed
            if len(neighbors_not_passed) > 1:
                active.add(vertex)
                continue
            vertices_accumulated[vertex] = sum(
                vertices_accumulated[neighbor] for neighbor in neighbors if neighbor in passed
            ) + 1
            components_remain_sizes = []
            for neighbor in neighbors - neighbors_not_passed:
                components_remain_sizes.append(vertices_accumulated[neighbor])
            assert len(neighbors_not_passed) <= 1
            for neighbor in neighbors_not_passed:
                components_remain_sizes.append(vertices_n - vertices_accumulated[vertex])
            vertex_value = max(components_remain_sizes)
            vertices_values[vertex] = vertex_value
            passed.add(vertex)
            active.update(neighbors_not_passed)
        active = active - passed

    centroid_value = min(vertices_values)
    centroids = [vertex for vertex, value in enumerate(vertices_values) if value == centroid_value]
    return centroids

if __name__ == '__main__':
    main()

```


1427_D. Unshuffling a Deck

You are given a deck of n cards numbered from 1 to n (not necessarily in this order in the deck). You have to sort the deck by repeating the following operation.

  * Choose 2 ≤ k ≤ n and split the deck in k nonempty contiguous parts D_1, D_2,..., D_k (D_1 contains the first |D_1| cards of the deck, D_2 contains the following |D_2| cards and so on). Then reverse the order of the parts, transforming the deck into D_k, D_{k-1}, ..., D_2, D_1 (so, the first |D_k| cards of the new deck are D_k, the following |D_{k-1}| cards are D_{k-1} and so on). The internal order of each packet of cards D_i is unchanged by the operation.

You have to obtain a sorted deck (i.e., a deck where the first card is 1, the second is 2 and so on) performing at most n operations. It can be proven that it is always possible to sort the deck performing at most n operations.

Examples of operation: The following are three examples of valid operations (on three decks with different sizes).

  * If the deck is [3 6 2 1 4 5 7] (so 3 is the first card and 7 is the last card), we may apply the operation with k=4 and D_1=[3 6], D_2=[2 1 4], D_3=[5], D_4=[7]. Doing so, the deck becomes [7 5 2 1 4 3 6].
  * If the deck is [3 1 2], we may apply the operation with k=3 and D_1=[3], D_2=[1], D_3=[2]. Doing so, the deck becomes [2 1 3].
  * If the deck is [5 1 2 4 3 6], we may apply the operation with k=2 and D_1=[5 1], D_2=[2 4 3 6]. Doing so, the deck becomes [2 4 3 6 5 1].

Input

The first line of the input contains one integer n (1≤ n≤ 52) — the number of cards in the deck.

The second line contains n integers c_1, c_2, ..., c_n — the cards in the deck. The first card is c_1, the second is c_2 and so on.

It is guaranteed that for all i=1,...,n there is exactly one j∈\{1,...,n\} such that c_j = i.

Output

On the first line, print the number q of operations you perform (it must hold 0≤ q≤ n).

Then, print q lines, each describing one operation.

To describe an operation, print on a single line the number k of parts you are going to split the deck in, followed by the size of the k parts: |D_1|, |D_2|, ... , |D_k|.

It must hold 2≤ k≤ n, and |D_i|≥ 1 for all i=1,...,k, and |D_1|+|D_2|+⋅⋅⋅ + |D_k| = n.

It can be proven that it is always possible to sort the deck performing at most n operations. If there are several ways to sort the deck you can output any of them.

Examples

Input

4
3 1 2 4

Output

2
3 1 2 1
2 1 3

Input

6
6 5 4 3 2 1

Output

1
6 1 1 1 1 1 1

Input

1
1

Output

0

Note

Explanation of the first testcase: Initially the deck is [3 1 2 4].

  * The first operation splits the deck as [(3) (1 2) (4)] and then transforms it into [4 1 2 3].
  * The second operation splits the deck as [(4) (1 2 3)] and then transforms it into [1 2 3 4].

Explanation of the second testcase: Initially the deck is [6 5 4 3 2 1].

  * The first (and only) operation splits the deck as [(6) (5) (4) (3) (2) (1)] and then transforms it into [1 2 3 4 5 6].

```python
from sys import stdin, stdout

n = int(stdin.readline())

c = [int(x) for x in stdin.readline().split()]
ops = []

turn = True

for x in range(n-1):
    newC = []
    newC2 = []
    op = []
    ind = c.index(x+1)
    if turn:
        if ind != 0:
            op.append(ind)
        op.append(n-x-ind)
        op += [1]*x
    else:
        op += [1]*x
        op.append(ind-x+1)
        if ind+1 != n:
            op.append(n-ind-1)

    ops.append([len(op)]+op)
    cur = 0
    for y in op:
        newC.append(c[cur:cur+y])
        cur += y
    for x in newC[::-1]:
        newC2 += x
    c = newC2
    #print(newC)
    #print(c)
    turn = not turn

out = []
for x in ops:
    if x[0] != 1:
        out.append(' '.join([str(y) for y in x]))
if c[0] != 1:
    out.append(' '.join([str(n)]+['1' for x in range(n)]))
print(len(out))
for x in out:
    print(x)

```


1450_D. Rating Compression

On the competitive programming platform CodeCook, every person has a rating graph described by an array of integers a of length n. You are now updating the infrastructure, so you've created a program to compress these graphs.

The program works as follows. Given an integer parameter k, the program takes the minimum of each contiguous subarray of length k in a.

More formally, for an array a of length n and an integer k, define the k-compression array of a as an array b of length n-k+1, such that $$$b_j =min_{j≤ i≤ j+k-1}a_i$$$

For example, the 3-compression array of [1, 3, 4, 5, 2] is [min\{1, 3, 4\}, min\{3, 4, 5\}, min\{4, 5, 2\}]=[1, 3, 2].

A permutation of length m is an array consisting of m distinct integers from 1 to m in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (m=3 but there is 4 in the array).

A k-compression array will make CodeCook users happy if it will be a permutation. Given an array a, determine for all 1≤ k≤ n if CodeCook users will be happy after a k-compression of this array or not.

Input

The first line contains a single integer t (1≤ t≤ 10^4) — the number of test cases.

The first line of the description of each test case contains a single integer n (1≤ n≤ 3⋅ 10^5) — the length of the array.

The second line of the description of each test case contains n integers a_1,…,a_n (1≤ a_i≤ n) — the elements of the array.

It is guaranteed, that the sum of n for all test cases does not exceed 3⋅ 10^5.

Output

For each test case, print a binary string of length n.

The k-th character of the string should be 1 if CodeCook users will be happy after a k-compression of the array a, and 0 otherwise.

Example

Input

5
5
1 5 3 4 2
4
1 3 2 1
5
1 3 3 3 2
10
1 2 3 4 5 6 7 8 9 10
3
3 3 2

Output

10111
0001
00111
1111111111
000

Note

In the first test case, a=[1, 5, 3, 4, 2].

  * The 1-compression of a is [1, 5, 3, 4, 2] and it is a permutation.
  * The 2-compression of a is [1, 3, 3, 2] and it is not a permutation, since 3 appears twice.
  * The 3-compression of a is [1, 3, 2] and it is a permutation.
  * The 4-compression of a is [1, 2] and it is a permutation.
  * The 5-compression of a is [1] and it is a permutation.

```python
from collections import deque
for iii in range(int(input())):
    d = deque()
    f = 1
    n = int(input())
    m = {i+1 : 0 for i in range(n)}
    s = map(int, input().split())
    for i in s:
        m[i]+=1
        if m[i]!=1:
            f = 0
        d.append(i)
    res = [0 for i in range(n)]
    if f:
        res[0]=1
    if m[1]:
        res[-1]=1
    for i in range(n, 2, -1):
        a = d.pop()
        if len(d):
            b = d.popleft()
        else:
            b = -2
        if a == n-i+1 and m[n-i+2] and m[n-i+1] == 1:
            d.appendleft(b)
            res[i-2]+=1
        elif b == n-i+1 and m[n-i+2] and m[n-i+1] == 1:
            d.append(a)
            res[i-2]+=1
        else:
            break
    print(*res,sep = '')
```


1474_B. Different Divisors

Positive integer x is called divisor of positive integer y, if y is divisible by x without remainder. For example, 1 is a divisor of 7 and 3 is not divisor of 8.

We gave you an integer d and asked you to find the smallest positive integer a, such that

  * a has at least 4 divisors;
  * difference between any two divisors of a is at least d.

Input

The first line contains a single integer t (1 ≤ t ≤ 3000) — the number of test cases.

The first line of each test case contains a single integer d (1 ≤ d ≤ 10000).

Output

For each test case print one integer a — the answer for this test case.

Example

Input

2
1
2

Output

6
15

Note

In the first test case, integer 6 have following divisors: [1, 2, 3, 6]. There are 4 of them and the difference between any two of them is at least 1. There is no smaller integer with at least 4 divisors.

In the second test case, integer 15 have following divisors: [1, 3, 5, 15]. There are 4 of them and the difference between any two of them is at least 2.

The answer 12 is INVALID because divisors are [1, 2, 3, 4, 6, 12]. And the difference between, for example, divisors 2 and 3 is less than d=2.

```python
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if os.path.exists('input.txt'):
    sys.stdin = open('input.txt','r')
    sys.stdout = open('output.txt','w')

# ------------------- fast io --------------------
from math import *
from itertools import * # chain,groupby,permutations,combinations
from collections import Counter
from bisect import *

"""
def prod(a, mod=10**9+7):
    ans = 1
    for each in a:
        ans = (ans * each) % mod
    return ans

def lcm(a, b): return a * b // gcd(a, b)

def binary(x, length=16):
    y = bin(x)[2:]
    return y if len(y) >= length else "0" * (length - len(y)) + y

def powerset(s):
    n=len(s)

    return chain.from_iterable(combinations(s,r) for r in range(1,n))

def binarySearch(arr,x):
    l=0
    r=len(arr)-1
    while l <= r:

        mid = l + (r - l) // 2;
        if arr[mid] == x:
            return mid
        elif arr[mid] < x:
            l = mid + 1
        else:
            r = mid - 1
    return -1

def prime(): #array of prime numbers
    arr = [1]*10000
    for i in range(10000):
        if i==0:
            arr[i]=0
        elif i==1:
            arr[i]=0
        else:
            if not arr[i]:
                continue
            j=i
            for k in range(2,10000):
                if j*k>=len(arr):
                    break
                arr[j*k]=0
    return arr

def isprime(x):
    i=2
    while i*i<=x:
        if x%i==0:
            return 0
        i+=1
    return 1

"""

#----#

def aa(): #for int
    return(int(input()))
def bb(): #for int arr
    return(list(map(int,input().split())))
def cc():  #for string
    s = input()
    return s#(list(s))
def dd(): #space seperated intege
    return(map(int,input().split()))
#----#

def isprime(x):
    i=2
    while i*i<=x:
        if x%i==0:
            return 0
        i+=1
    return 1

def solve():
    d=aa()
    n=d+1
    while not isprime(n):
        n+=1
    b=d+n
    while not isprime(b):
        b+=1

    print(min(n**3,n*b))

if __name__ == "__main__":
    t=aa()
    while(t):
        solve()
        t-=1

"""

_________            .___.__                           _________.__ __   .__                          .___                      .__
\_   ___ \  ____   __| _/|__| ____    ____            /   _____/|__|  | _|  |__ _____               __| _/____           ______ |  |   ______ ______
/    \  \/ /  _ \ / __ | |  |/    \  / ___\           \_____  \ |  |  |/ /  |  \\__  \             / __ |/  _ \          \____ \|  |  /  ___//  ___/
\     \___(  <_> ) /_/ | |  |   |  \/ /_/  >          /        \|  |    <|   Y  \/ __ \_          / /_/ (  <_> )         |  |_> >  |__\___ \ \___ \
 \______  /\____/\____ | |__|___|  /\___  /__________/_______  /|__|__|_ \___|  (____  /__________\____ |\____/__________|   __/|____/____  >____  >
        \/            \/         \//_____/_____/_____/       \/         \/    \/     \/_____/_____/    \/    /_____/_____/__|             \/     \/

"""
```


1523_D. Love-Hate

<image>

William is hosting a party for n of his trader friends. They started a discussion on various currencies they trade, but there's an issue: not all of his trader friends like every currency. They like some currencies, but not others.

For each William's friend i it is known whether he likes currency j. There are m currencies in total. It is also known that a trader may not like more than p currencies.

Because friends need to have some common topic for discussions they need to find the largest by cardinality (possibly empty) subset of currencies, such that there are at least ⌈ n/2 ⌉ friends (rounded up) who like each currency in this subset.

Input

The first line contains three integers n, m and p (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ p ≤ m ≤ 60, 1 ≤ p ≤ 15), which is the number of trader friends, the number of currencies, the maximum number of currencies each friend can like.

Each of the next n lines contain m characters. The j-th character of i-th line is 1 if friend i likes the currency j and 0 otherwise. It is guaranteed that the number of ones in each line does not exceed p.

Output

Print a string of length m, which defines the subset of currencies of the maximum size, which are liked by at least half of all friends. Currencies belonging to this subset must be signified by the character 1.

If there are multiple answers, print any.

Examples

Input

3 4 3
1000
0110
1001

Output

1000

Input

5 5 4
11001
10101
10010
01110
11011

Output

10001

Note

In the first sample test case only the first currency is liked by at least ⌈ 3/2 ⌉ = 2 friends, therefore it's easy to demonstrate that a better answer cannot be found.

In the second sample test case the answer includes 2 currencies and will be liked by friends 1, 2, and 5. For this test case there are other currencies that are liked by at least half of the friends, but using them we cannot achieve a larger subset size.

```python
#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase

def main():

    def popCount(a):
        cnt = 0
        for i in range(60):
            if a & (1 << i):
                cnt += 1
        return cnt

    n,m,p = map(int,input().split())
    person = []
    for _ in range(n):
        person.append(int(input(),base = 2))
    base = 0
    for i in range(m):
        cnt = 0
        for j in range(n):
            if person[j] & (1 << i):
                cnt += 1
        if cnt >= (n + 1) // 2:
            base |= 1 << i
    for i in range(n):
        person[i] &= base
    person.sort(reverse = True)
    keys = []
    cnt = {}
    for elem in person:
        if elem in cnt:
            cnt[elem] += 1
        else:
            cnt[elem] = 1
            keys.append(elem)
    for b in range(60):
        if base & (1 << b) == 0:
            continue
        toAdd = []
        toAddVal = []
        for key in cnt:
            if key & (1 << b):
                if key ^ (1 << b) in cnt:
                    cnt[key ^ (1 << b)] += cnt[key]
                else:
                    toAdd.append(key ^ (1 << b))
                    toAddVal.append(cnt[key])
        for i in range(len(toAdd)):
            cnt[toAdd[i]] = toAddVal[i]
    maxAns = 0
    for key in cnt:
        if cnt[key] < (n + 1) // 2:
            continue
        if popCount(maxAns) < popCount(key):
            maxAns = key
    print("0" * (m - len(bin(maxAns)) + 2) + bin(maxAns)[2:])

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

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


155_C. Hometask

Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.

Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.

Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".

Input

The first line contains a non-empty string s, consisting of lowercase Latin letters — that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105.

The next line contains integer k (0 ≤ k ≤ 13) — the number of forbidden pairs of letters.

Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.

Output

Print the single number — the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.

Examples

Input

ababa
1
ab

Output

2

Input

codeforces
2
do
cs

Output

1

Note

In the first sample you should remove two letters b.

In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.

```python
s = input() + "#"
k = int(input())
arr = [input() for _ in range(k)]
res = 0
for t in arr:
    a, b = 0, 0
    for i in range(len(s)):
        if s[i] == t[0]:
            a += 1
        elif s[i] == t[1]:
            b += 1
        else:
            if a and b:
                res += min(a, b)
            a, b = 0, 0
print(res)

```


177_D1. 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(input().split())
b = list(input().split())

sum = 0

for i in range(n):
    if i<m:
        sum = sum + int(b[i])
        sum = sum%c

    if i >= n - m + 1:
        sum = c - int(b[i-n+m-1]) + sum
        sum = sum%c

    print((int(a[i])+sum)%c,end = ' ')

```


245_F. Log Stream Analysis

You've got a list of program warning logs. Each record of a log stream is a string in this format:

"2012-MM-DD HH:MM:SS:MESSAGE" (without the quotes).

String "MESSAGE" consists of spaces, uppercase and lowercase English letters and characters "!", ".", ",", "?". String "2012-MM-DD" determines a correct date in the year of 2012. String "HH:MM:SS" determines a correct time in the 24 hour format.

The described record of a log stream means that at a certain time the record has got some program warning (string "MESSAGE" contains the warning's description).

Your task is to print the first moment of time, when the number of warnings for the last n seconds was not less than m.

Input

The first line of the input contains two space-separated integers n and m (1 ≤ n, m ≤ 10000).

The second and the remaining lines of the input represent the log stream. The second line of the input contains the first record of the log stream, the third line contains the second record and so on. Each record of the log stream has the above described format. All records are given in the chronological order, that is, the warning records are given in the order, in which the warnings appeared in the program.

It is guaranteed that the log has at least one record. It is guaranteed that the total length of all lines of the log stream doesn't exceed 5·106 (in particular, this means that the length of some line does not exceed 5·106 characters). It is guaranteed that all given dates and times are correct, and the string 'MESSAGE" in all records is non-empty.

Output

If there is no sought moment of time, print -1. Otherwise print a string in the format "2012-MM-DD HH:MM:SS" (without the quotes) — the first moment of time when the number of warnings for the last n seconds got no less than m.

Examples

Input

60 3
2012-03-16 16:15:25: Disk size is
2012-03-16 16:15:25: Network failute
2012-03-16 16:16:29: Cant write varlog
2012-03-16 16:16:42: Unable to start process
2012-03-16 16:16:43: Disk size is too small
2012-03-16 16:16:53: Timeout detected

Output

2012-03-16 16:16:43

Input

1 2
2012-03-16 23:59:59:Disk size
2012-03-17 00:00:00: Network
2012-03-17 00:00:01:Cant write varlog

Output

-1

Input

2 2
2012-03-16 23:59:59:Disk size is too sm
2012-03-17 00:00:00:Network failute dete
2012-03-17 00:00:01:Cant write varlogmysq

Output

2012-03-17 00:00:00

```python
import atexit
import io
import sys

_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER

@atexit.register
def write():
    sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())

import bisect
from datetime import datetime

def main():
    n, m = map(int, input().split())
    n -= 1

    timestamps = []
    while True:
        s = ""
        try:
            s = input()
        except:
            print(-1)
            exit(0)

        d = datetime.strptime(s[0:19], "%Y-%m-%d %H:%M:%S")
        timestamps.append(int(d.timestamp()))
        idx = bisect.bisect_left(timestamps, timestamps[-1] - n)
        if len(timestamps) - idx == m:
            print(s[0:19])
            exit(0)

if __name__ == "__main__":
    main()

```


270_D. Greenhouse Effect

Emuskald is an avid horticulturist and owns the world's longest greenhouse — it is effectively infinite in length.

Over the years Emuskald has cultivated n plants in his greenhouse, of m different plant species numbered from 1 to m. His greenhouse is very narrow and can be viewed as an infinite line, with each plant occupying a single point on that line.

Emuskald has discovered that each species thrives at a different temperature, so he wants to arrange m - 1 borders that would divide the greenhouse into m sections numbered from 1 to m from left to right with each section housing a single species. He is free to place the borders, but in the end all of the i-th species plants must reside in i-th section from the left.

Of course, it is not always possible to place the borders in such way, so Emuskald needs to replant some of his plants. He can remove each plant from its position and place it anywhere in the greenhouse (at any real coordinate) with no plant already in it. Since replanting is a lot of stress for the plants, help Emuskald find the minimum number of plants he has to replant to be able to place the borders.

Input

The first line of input contains two space-separated integers n and m (1 ≤ n, m ≤ 5000, n ≥ m), the number of plants and the number of different species. Each of the following n lines contain two space-separated numbers: one integer number si (1 ≤ si ≤ m), and one real number xi (0 ≤ xi ≤ 109), the species and position of the i-th plant. Each xi will contain no more than 6 digits after the decimal point.

It is guaranteed that all xi are different; there is at least one plant of each species; the plants are given in order "from left to the right", that is in the ascending order of their xi coordinates (xi < xi + 1, 1 ≤ i < n).

Output

Output a single integer — the minimum number of plants to be replanted.

Examples

Input

3 2
2 1
1 2.0
1 3.100

Output

1

Input

3 3
1 5.0
2 5.5
3 6.0

Output

0

Input

6 3
1 14.284235
2 17.921382
1 20.328172
3 20.842331
1 25.790145
1 27.204125

Output

2

Note

In the first test case, Emuskald can replant the first plant to the right of the last plant, so the answer is 1.

In the second test case, the species are already in the correct order, so no replanting is needed.

```python
n, m = [int(x) for x in input().split()]
d = [0 for i in range(m)]
for i in range(n):
    c, x = [x for x in input().split()]
    c = int(c)

    d[c-1] = max(d[:c])+1
print(n-max(d))

```


294_A. Shaass and Oskols

Shaass has decided to hunt some birds. There are n horizontal electricity wires aligned parallel to each other. Wires are numbered 1 to n from top to bottom. On each wire there are some oskols sitting next to each other. Oskol is the name of a delicious kind of birds in Shaass's territory. Supposed there are ai oskols sitting on the i-th wire.

<image>

Sometimes Shaass shots one of the birds and the bird dies (suppose that this bird sat at the i-th wire). Consequently all the birds on the i-th wire to the left of the dead bird get scared and jump up on the wire number i - 1, if there exists no upper wire they fly away. Also all the birds to the right of the dead bird jump down on wire number i + 1, if there exists no such wire they fly away.

Shaass has shot m birds. You're given the initial number of birds on each wire, tell him how many birds are sitting on each wire after the shots.

Input

The first line of the input contains an integer n, (1 ≤ n ≤ 100). The next line contains a list of space-separated integers a1, a2, ..., an, (0 ≤ ai ≤ 100).

The third line contains an integer m, (0 ≤ m ≤ 100). Each of the next m lines contains two integers xi and yi. The integers mean that for the i-th time Shaass shoot the yi-th (from left) bird on the xi-th wire, (1 ≤ xi ≤ n, 1 ≤ yi). It's guaranteed there will be at least yi birds on the xi-th wire at that moment.

Output

On the i-th line of the output print the number of birds on the i-th wire.

Examples

Input

5
10 10 10 10 10
5
2 5
3 13
2 12
1 13
4 6

Output

0
12
5
0
16

Input

3
2 4 1
1
2 2

Output

3
0
3

```python
n = int(input())
l = list(map(int,input().split()))
n1 = int(input())
for i in range(n1):
	x,y = map(int,input().split())
	if len(l)==1:
		l[0]=0
	elif x==1:
		l[x]+=l[x-1]-y
		l[x-1]=0
	elif x==len(l):
		l[x-2]+=y-1
		l[x-1]=0
	else:
		l[x-2]+=y-1
		l[x]+=l[x-1]-y
		l[x-1]=0
for i in l:
	print(i)
```


317_D. Game with Powers

Vasya and Petya wrote down all integers from 1 to n to play the "powers" game (n can be quite large; however, Vasya and Petya are not confused by this fact).

Players choose numbers in turn (Vasya chooses first). If some number x is chosen at the current turn, it is forbidden to choose x or all of its other positive integer powers (that is, x2, x3, ...) at the next turns. For instance, if the number 9 is chosen at the first turn, one cannot choose 9 or 81 later, while it is still allowed to choose 3 or 27. The one who cannot make a move loses.

Who wins if both Vasya and Petya play optimally?

Input

Input contains single integer n (1 ≤ n ≤ 109).

Output

Print the name of the winner — "Vasya" or "Petya" (without quotes).

Examples

Input

1

Output

Vasya

Input

2

Output

Petya

Input

8

Output

Petya

Note

In the first sample Vasya will choose 1 and win immediately.

In the second sample no matter which number Vasya chooses during his first turn, Petya can choose the remaining number and win.

```python
from sys import stdin, stdout
import math, collections
mod = 10**9+7

def isPower(n):
    if (n <= 1):
        return True
    for x in range(2, (int)(math.sqrt(n)) + 1):
        p = x
        while (p <= n):
            p = p * x
            if (p == n):
                return True

    return False
n = int(input())
arr = [0,1,2,1,4,3,2,1,5,6,2,1,8,7,5,9,8,7,3,4,7,4,2,1,10,9,3,6,11,12]
ans = arr[int(math.log(n, 2))]
s = int(math.log(n, 2))
for i in range(3, int(n**0.5)+1):
    if not isPower(i):
        ans^=arr[int(math.log(n, i))]
        s+=int(math.log(n, i))
ans^=((n-s)%2)
print("Vasya" if ans else "Petya")
```


365_A. Good Number

Let's call a number k-good if it contains all digits not exceeding k (0, ..., k). You've got a number k and an array a containing n numbers. Find out how many k-good numbers are in a (count each number every time it occurs in array a).

Input

The first line contains integers n and k (1 ≤ n ≤ 100, 0 ≤ k ≤ 9). The i-th of the following n lines contains integer ai without leading zeroes (1 ≤ ai ≤ 109).

Output

Print a single integer — the number of k-good numbers in a.

Examples

Input

10 6
1234560
1234560
1234560
1234560
1234560
1234560
1234560
1234560
1234560
1234560

Output

10

Input

2 1
1
10

Output

1

```python
import sys
x=input().split()
n=int(x[0])
k=int(x[1])
list=[]
for i in range(0,n):
    y=input()
    list.append(y)
l=0
for j in list:
    flag=1
    for z in range(0,k+1):
        if str(z) not in j:
            flag=0
            break
    if flag==1:
        l=l+1

print(l)
```


409_C. Magnum Opus

Salve, mi amice.

Et tu quidem de lapis philosophorum. Barba non facit philosophum. Labor omnia vincit. Non potest creatio ex nihilo. Necesse est partibus.

Rp:

I Aqua Fortis

I Aqua Regia

II Amalgama

VII Minium

IV Vitriol

Misce in vitro et æstus, et nil admirari. Festina lente, et nulla tenaci invia est via.

Fac et spera,

Vale,

Nicolas Flamel

Input

The first line of input contains several space-separated integers ai (0 ≤ ai ≤ 100).

Output

Print a single integer.

Examples

Input

2 4 6 8 10

Output

1

```python
b =[1,1,2,7,4]
a =list(map(int,input().split()))
ans = 100
for i in range(5):
    ans = min(a[i]//b[i],ans)
print(ans)

```


459_E. Pashmak and Graph

Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem.

You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path.

Help Pashmak, print the number of edges in the required path.

Input

The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ min(n·(n - 1), 3·105)). Then, m lines follows. The i-th line contains three space separated integers: ui, vi, wi (1 ≤ ui, vi ≤ n; 1 ≤ wi ≤ 105) which indicates that there's a directed edge with weight wi from vertex ui to vertex vi.

It's guaranteed that the graph doesn't contain self-loops and multiple edges.

Output

Print a single integer — the answer to the problem.

Examples

Input

3 3
1 2 1
2 3 1
3 1 1

Output

1

Input

3 3
1 2 1
2 3 2
3 1 3

Output

3

Input

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

Output

6

Note

In the first sample the maximum trail can be any of this trails: <image>.

In the second sample the maximum trail is <image>.

In the third sample the maximum trail is <image>.

```python
from sys import *
f = list(map(int, stdin.read().split()))

n, m = f[0], f[1]
d = [[] for i in range(100001)]

for j in range(2, len(f), 3):
    x, y, w = f[j:j + 3]
    d[w].append((y, x))

s = [0] * (n + 1)
for q in d:
    for y, k in [(y, s[x]) for y, x in q]: s[y] = max(s[y], k + 1)
print(max(s))
```


505_D. Mr. Kitayuta's Technology

Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.

Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.

Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.

Input

The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.

The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.

Output

Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.

Examples

Input

4 5
1 2
1 3
1 4
2 3
2 4

Output

3

Input

4 6
1 2
1 4
2 3
2 4
3 2
3 4

Output

4

Note

For the first sample, one of the optimal ways to construct pipes is shown in the image below:

<image>

For the second sample, one of the optimal ways is shown below:

<image>

```python
def main():
    n, m = map(int, input().split())
    n += 1
    cluster, dest, ab = list(range(n)), [0] * n, [[] for _ in range(n)]

    def root(x):
        if x != cluster[x]:
            cluster[x] = x = root(cluster[x])
        return x

    for _ in range(m):
        a, b = map(int, input().split())
        ab[a].append(b)
        dest[b] += 1
        cluster[root(a)] = root(b)
    pool = [a for a, f in enumerate(dest) if not f]
    for a in pool:
        for b in ab[a]:
            dest[b] -= 1
            if not dest[b]:
                pool.append(b)
    ab = [True] * n
    for a, f in enumerate(dest):
        if f:
            ab[root(a)] = False
    print(n - sum(f and a == c for a, c, f in zip(range(n), cluster, ab)))

if __name__ == '__main__':
    from sys import setrecursionlimit

    setrecursionlimit(100500)
    main()

```


554_E. Love Triangles

There are many anime that are about "love triangles": Alice loves Bob, and Charlie loves Bob as well, but Alice hates Charlie. You are thinking about an anime which has n characters. The characters are labeled from 1 to n. Every pair of two characters can either mutually love each other or mutually hate each other (there is no neutral state).

You hate love triangles (A-B are in love and B-C are in love, but A-C hate each other), and you also hate it when nobody is in love. So, considering any three characters, you will be happy if exactly one pair is in love (A and B love each other, and C hates both A and B), or if all three pairs are in love (A loves B, B loves C, C loves A).

You are given a list of m known relationships in the anime. You know for sure that certain pairs love each other, and certain pairs hate each other. You're wondering how many ways you can fill in the remaining relationships so you are happy with every triangle. Two ways are considered different if two characters are in love in one way but hate each other in the other. Print this count modulo 1 000 000 007.

Input

The first line of input will contain two integers n, m (3 ≤ n ≤ 100 000, 0 ≤ m ≤ 100 000).

The next m lines will contain the description of the known relationships. The i-th line will contain three integers ai, bi, ci. If ci is 1, then ai and bi are in love, otherwise, they hate each other (1 ≤ ai, bi ≤ n, ai ≠ bi, <image>).

Each pair of people will be described no more than once.

Output

Print a single integer equal to the number of ways to fill in the remaining pairs so that you are happy with every triangle modulo 1 000 000 007.

Examples

Input

3 0

Output

4

Input

4 4
1 2 1
2 3 1
3 4 0
4 1 0

Output

1

Input

4 4
1 2 1
2 3 1
3 4 0
4 1 1

Output

0

Note

In the first sample, the four ways are to:

  * Make everyone love each other
  * Make 1 and 2 love each other, and 3 hate 1 and 2 (symmetrically, we get 3 ways from this).

In the second sample, the only possible solution is to make 1 and 3 love each other and 2 and 4 hate each other.

```python
class DSU(object):
    def __init__(self, n):
        self.father = list(range(n))
        self.size = n

    def union(self, x, s):
        x = self.find(x)
        s = self.find(s)
        if x == s:
            return
        self.father[s] = x
        self.size -= 1

    def find(self, x):
        xf = self.father[x]
        if xf != x:
            self.father[x] = self.find(xf)
        return self.father[x]

def is_invalid(a, b, ds):
    return ds.find(a) == ds.find(b)

n, k = map(int, input().split())
ds = DSU(n * 2)
for i in range(k):
    first, second, color = map(int, input().split())
    first -= 1
    second -= 1
    if color == 0:
        if is_invalid(first, second, ds):
            print(0)
            exit()
        ds.union(first, second + n)
        ds.union(first + n, second)
    else:
        if is_invalid(first, second + n, ds):
            print(0)
            exit()
        ds.union(first, second)
        ds.union(first + n, second + n)

sum = 1
for i in range(ds.size // 2 - 1):
    sum = (sum * 2) % (10 ** 9 + 7)
print(sum)

```


580_D. Kefa and Dishes

When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were n dishes. Kefa knows that he needs exactly m dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible.

Kefa knows that the i-th dish gives him ai units of satisfaction. But some dishes do not go well together and some dishes go very well together. Kefa set to himself k rules of eating food of the following type — if he eats dish x exactly before dish y (there should be no other dishes between x and y), then his satisfaction level raises by c.

Of course, our parrot wants to get some maximal possible satisfaction from going to the restaurant. Help him in this hard task!

Input

The first line of the input contains three space-separated numbers, n, m and k (1 ≤ m ≤ n ≤ 18, 0 ≤ k ≤ n * (n - 1)) — the number of dishes on the menu, the number of portions Kefa needs to eat to get full and the number of eating rules.

The second line contains n space-separated numbers ai, (0 ≤ ai ≤ 109) — the satisfaction he gets from the i-th dish.

Next k lines contain the rules. The i-th rule is described by the three numbers xi, yi and ci (1 ≤ xi, yi ≤ n, 0 ≤ ci ≤ 109). That means that if you eat dish xi right before dish yi, then the Kefa's satisfaction increases by ci. It is guaranteed that there are no such pairs of indexes i and j (1 ≤ i < j ≤ k), that xi = xj and yi = yj.

Output

In the single line of the output print the maximum satisfaction that Kefa can get from going to the restaurant.

Examples

Input

2 2 1
1 1
2 1 1

Output

3

Input

4 3 2
1 2 3 4
2 1 5
3 4 2

Output

12

Note

In the first sample it is best to first eat the second dish, then the first one. Then we get one unit of satisfaction for each dish and plus one more for the rule.

In the second test the fitting sequences of choice are 4 2 1 or 2 1 4. In both cases we get satisfaction 7 for dishes and also, if we fulfill rule 1, we get an additional satisfaction 5.

```python
import os
import sys
from io import BytesIO,IOBase

def main():
    n,m,k = map(int,input().split())
    a = list(map(float,input().split()))
    tree = [[0]*n for _ in range(n)]
    for i in range(k):
        x,y,z = map(int,input().split())
        tree[x-1][y-1] = float(z)
    po = [1]
    while len(po) != n:
        po.append(po[-1]*2)
    dp = [[0]*(po[-1]*2) for _ in range(n)]
    for i in range(n):
        dp[i][po[i]] = a[i]
    for i in range(po[-1]*2):
        for j in range(n):
            if i&po[j]:
                for k in range(n):
                    if not (i&po[k]):
                        dp[k][i+po[k]] = max(dp[k][i+po[k]],dp[j][i]+a[k]+tree[j][k])
    ma = 0
    for i in range(po[-1]*2):
        if bin(i)[2:].count("1") == m:
            for j in range(n):
                ma = max(ma,dp[j][i])
    print(int(ma))

# region fastio
BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self,file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd,max(os.fstat(self._fd).st_size,BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0,2),self.buffer.write(b),self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd,max(os.fstat(self._fd).st_size,BUFSIZE))
            self.newlines = b.count(b"\n")+(not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0,2),self.buffer.write(b),self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd,self.buffer.getvalue())
            self.buffer.truncate(0),self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self,file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s:self.buffer.write(s.encode("ascii"))
        self.read = lambda:self.buffer.read().decode("ascii")
        self.readline = lambda:self.buffer.readline().decode("ascii")

sys.stdin,sys.stdout = IOWrapper(sys.stdin),IOWrapper(sys.stdout)
input = lambda:sys.stdin.readline().rstrip("\r\n")

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


602_C. The Two Routes

In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.

A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.

You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.

Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.

Input

The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively.

Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v).

You may assume that there is at most one railway connecting any two towns.

Output

Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.

Examples

Input

4 2
1 3
3 4

Output

2

Input

4 6
1 2
1 3
1 4
2 3
2 4
3 4

Output

-1

Input

5 5
4 2
3 5
4 5
5 1
1 2

Output

3

Note

In the first sample, the train can take the route <image> and the bus can take the route <image>. Note that they can arrive at town 4 at the same time.

In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.

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

dist = [0] * (n + 1)
for row in range(n + 1):
    dist[row] = [1] * (n + 1)

for i in range(m):
    a, b = map(int, input().split())
    dist[a][b] = dist[b][a] = 2

x, v, i = 3 - dist[1][n], [0] * (n + 1), 1
d = [n + 1] * (n + 1)
res =  d[1] = 0

while i != n:
    v[i] = 1
    for j in range(1, n + 1):
        if v[j] == 0 and dist[i][j] == x and d[j] > d[i] + 1:
            d[j] = d[i] + 1
    meu = n + 1

    for j in range(1, n + 1):
        if v[j] == 0 and d[j] < meu:
            meu = d[j]
            i = j

    if meu == n + 1:
        res = -1
        break

    elif i == n:
        res = d[n]
        break

print(res)

```


625_A. Guest From the Past

Kolya Gerasimov loves kefir very much. He lives in year 1984 and knows all the details of buying this delicious drink. One day, as you probably know, he found himself in year 2084, and buying kefir there is much more complicated.

Kolya is hungry, so he went to the nearest milk shop. In 2084 you may buy kefir in a plastic liter bottle, that costs a rubles, or in glass liter bottle, that costs b rubles. Also, you may return empty glass bottle and get c (c < b) rubles back, but you cannot return plastic bottles.

Kolya has n rubles and he is really hungry, so he wants to drink as much kefir as possible. There were no plastic bottles in his 1984, so Kolya doesn't know how to act optimally and asks for your help.

Input

First line of the input contains a single integer n (1 ≤ n ≤ 1018) — the number of rubles Kolya has at the beginning.

Then follow three lines containing integers a, b and c (1 ≤ a ≤ 1018, 1 ≤ c < b ≤ 1018) — the cost of one plastic liter bottle, the cost of one glass liter bottle and the money one can get back by returning an empty glass bottle, respectively.

Output

Print the only integer — maximum number of liters of kefir, that Kolya can drink.

Examples

Input

10
11
9
8

Output

2

Input

10
5
6
1

Output

2

Note

In the first sample, Kolya can buy one glass bottle, then return it and buy one more glass bottle. Thus he will drink 2 liters of kefir.

In the second sample, Kolya can buy two plastic bottle and get two liters of kefir, or he can buy one liter glass bottle, then return it and buy one plastic bottle. In both cases he will drink two liters of kefir.

```python
n=(int)(input());
a=(int)(input());
b=(int)(input());
c=(int)(input());
cnt=a;
cnt=0;
cnt1=a;
cnt1=(int)(n//a);
if (n<b):
    while (n//b>0):
        cnt+=n//b;
        n-=(n//b)*b-n//b*c;
        #print (n," ",cnt);
    #print(n//a," ",cnt," ",cnt+n//a);
    cnt+=n//a;
    print((int)(max(cnt,cnt1)));
else:
    n-=b;
    #print(n," ",b," ",c);
    #print(cnt);
    cnt+=n//(b-c);
    n%=(b-c);
    n+=b;
    #print((int)(cnt));
    while (n//b>0):
        cnt+=n//b;
        n-=(n//b)*b-n//b*c;
        #print (n," ",(int)(cnt));
    #print(n//a," ",cnt," ",cnt+n//a);
    cnt+=n//a;
    print((int)(max(cnt,cnt1)));

```


673_C. Bear and Colors

Bear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color ti.

For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the biggest number of times in the interval. In case of a tie between some colors, the one with the smallest number (index) is chosen as dominant.

There are <image> non-empty intervals in total. For each color, your task is to count the number of intervals in which this color is dominant.

Input

The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of balls.

The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ n) where ti is the color of the i-th ball.

Output

Print n integers. The i-th of them should be equal to the number of intervals where i is a dominant color.

Examples

Input

4
1 2 1 2

Output

7 3 0 0

Input

3
1 1 1

Output

6 0 0

Note

In the first sample, color 2 is dominant in three intervals:

  * An interval [2, 2] contains one ball. This ball's color is 2 so it's clearly a dominant color.
  * An interval [4, 4] contains one ball, with color 2 again.
  * An interval [2, 4] contains two balls of color 2 and one ball of color 1.

There are 7 more intervals and color 1 is dominant in all of them.

```python
def main():
    n = int(input())
    a = [int(i) for i in input().strip().split()]

    res = [0] * n

    for st in range(n):
        cnt = [0] * n
        x = 0
        y = 0
        for ed in range(st, n):
            cnt[a[ed] - 1] += 1
            if (cnt[a[ed] - 1] > x) or (cnt[a[ed] - 1] == x and a[ed] - 1 < y):
                x = cnt[a[ed] - 1]
                y = a[ed] - 1
            res[y] += 1

    print(" ".join(map(str, res)))

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


740_B. Alyona and flowers

Little Alyona is celebrating Happy Birthday! Her mother has an array of n flowers. Each flower has some mood, the mood of i-th flower is ai. The mood can be positive, zero or negative.

Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose several of the subarrays suggested by her mother. After that, each of the flowers will add to the girl's happiness its mood multiplied by the number of chosen subarrays the flower is in.

For example, consider the case when the mother has 5 flowers, and their moods are equal to 1, - 2, 1, 3, - 4. Suppose the mother suggested subarrays (1, - 2), (3, - 4), (1, 3), (1, - 2, 1, 3). Then if the girl chooses the third and the fourth subarrays then:

  * the first flower adds 1·1 = 1 to the girl's happiness, because he is in one of chosen subarrays,
  * the second flower adds ( - 2)·1 = - 2, because he is in one of chosen subarrays,
  * the third flower adds 1·2 = 2, because he is in two of chosen subarrays,
  * the fourth flower adds 3·2 = 6, because he is in two of chosen subarrays,
  * the fifth flower adds ( - 4)·0 = 0, because he is in no chosen subarrays.

Thus, in total 1 + ( - 2) + 2 + 6 + 0 = 7 is added to the girl's happiness. Alyona wants to choose such subarrays from those suggested by the mother that the value added to her happiness would be as large as possible. Help her do this!

Alyona can choose any number of the subarrays, even 0 or all suggested by her mother.

Input

The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the number of flowers and the number of subarrays suggested by the mother.

The second line contains the flowers moods — n integers a1, a2, ..., an ( - 100 ≤ ai ≤ 100).

The next m lines contain the description of the subarrays suggested by the mother. The i-th of these lines contain two integers li and ri (1 ≤ li ≤ ri ≤ n) denoting the subarray a[li], a[li + 1], ..., a[ri].

Each subarray can encounter more than once.

Output

Print single integer — the maximum possible value added to the Alyona's happiness.

Examples

Input

5 4
1 -2 1 3 -4
1 2
4 5
3 4
1 4

Output

7

Input

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

Output

16

Input

2 2
-1 -2
1 1
1 2

Output

0

Note

The first example is the situation described in the statements.

In the second example Alyona should choose all subarrays.

The third example has answer 0 because Alyona can choose none of the subarrays.

```python
I=lambda:map(int,input().split())
R=range
ans=0
n,m=I()
a=list(I())
for _ in R(m):l,r=I();ans+=max(0,sum(a[i]for i in R(l-1,r)))
print(ans)
```


764_A. Taymyr is calling you

Comrade Dujikov is busy choosing artists for Timofey's birthday and is recieving calls from Taymyr from Ilia-alpinist.

Ilia-alpinist calls every n minutes, i.e. in minutes n, 2n, 3n and so on. Artists come to the comrade every m minutes, i.e. in minutes m, 2m, 3m and so on. The day is z minutes long, i.e. the day consists of minutes 1, 2, ..., z. How many artists should be killed so that there are no artists in the room when Ilia calls? Consider that a call and a talk with an artist take exactly one minute.

Input

The only string contains three integers — n, m and z (1 ≤ n, m, z ≤ 104).

Output

Print single integer — the minimum number of artists that should be killed so that there are no artists in the room when Ilia calls.

Examples

Input

1 1 10

Output

10

Input

1 2 5

Output

2

Input

2 3 9

Output

1

Note

Taymyr is a place in the north of Russia.

In the first test the artists come each minute, as well as the calls, so we need to kill all of them.

In the second test we need to kill artists which come on the second and the fourth minutes.

In the third test — only the artist which comes on the sixth minute.

```python
from math import *
def lcm(a, b): return a*b//gcd(a, b)
n, m, z = map(int, input().split())
print(z//lcm(n, m))

```


787_C. Berzerk

Rick and Morty are playing their own version of Berzerk (which has nothing in common with the famous Berzerk game). This game needs a huge space, so they play it with a computer.

In this game there are n objects numbered from 1 to n arranged in a circle (in clockwise order). Object number 1 is a black hole and the others are planets. There's a monster in one of the planet. Rick and Morty don't know on which one yet, only that he's not initially in the black hole, but Unity will inform them before the game starts. But for now, they want to be prepared for every possible scenario.

<image>

Each one of them has a set of numbers between 1 and n - 1 (inclusive). Rick's set is s1 with k1 elements and Morty's is s2 with k2 elements. One of them goes first and the player changes alternatively. In each player's turn, he should choose an arbitrary number like x from his set and the monster will move to his x-th next object from its current position (clockwise). If after his move the monster gets to the black hole he wins.

Your task is that for each of monster's initial positions and who plays first determine if the starter wins, loses, or the game will stuck in an infinite loop. In case when player can lose or make game infinity, it more profitable to choose infinity game.

Input

The first line of input contains a single integer n (2 ≤ n ≤ 7000) — number of objects in game.

The second line contains integer k1 followed by k1 distinct integers s1, 1, s1, 2, ..., s1, k1 — Rick's set.

The third line contains integer k2 followed by k2 distinct integers s2, 1, s2, 2, ..., s2, k2 — Morty's set

1 ≤ ki ≤ n - 1 and 1 ≤ si, 1, si, 2, ..., si, ki ≤ n - 1 for 1 ≤ i ≤ 2.

Output

In the first line print n - 1 words separated by spaces where i-th word is "Win" (without quotations) if in the scenario that Rick plays first and monster is initially in object number i + 1 he wins, "Lose" if he loses and "Loop" if the game will never end.

Similarly, in the second line print n - 1 words separated by spaces where i-th word is "Win" (without quotations) if in the scenario that Morty plays first and monster is initially in object number i + 1 he wins, "Lose" if he loses and "Loop" if the game will never end.

Examples

Input

5
2 3 2
3 1 2 3

Output

Lose Win Win Loop
Loop Win Win Win

Input

8
4 6 2 3 4
2 3 6

Output

Win Win Win Win Win Win Win
Lose Win Lose Lose Win Lose Lose

```python
import queue

n = int(input())

sR = list(map(int, input().split()[1:]))
sM = list(map(int, input().split()[1:]))
s = [sR, sM]

UNK = -1
WIN = 2
LOSE = 3

A = [[UNK] * n for i in range(2)]
CNT = [[0] * n for i in range(2)]
V = [[False] * n for i in range(2)]
# ricky turn 0
# morty turn 1
A[0][0] = LOSE
A[1][0] = LOSE

Q = queue.Queue()
Q.put((0, 0))
Q.put((1, 0))

while not Q.empty():
    turn, planet = Q.get()

    prev_turn = 1 - turn
    for diff in s[prev_turn]:
        prev_planet = (n + planet - diff) % n
        if prev_planet == 0:
            continue
        if A[turn][planet] == LOSE:
            A[prev_turn][prev_planet] = WIN
        elif A[turn][planet] == WIN:
            CNT[prev_turn][prev_planet] += 1
        if CNT[prev_turn][prev_planet] == len(s[prev_turn]):
            A[prev_turn][prev_planet] = LOSE

        if A[prev_turn][prev_planet] != UNK and not V[prev_turn][prev_planet]:
            Q.put((prev_turn, prev_planet))
            V[prev_turn][prev_planet] = True

print(' '.join(["Win" if A[0][i] == WIN else "Lose" if A[0][i] == LOSE else "Loop" for i in range(1, n)]))
print(' '.join(["Win" if A[1][i] == WIN else "Lose" if A[1][i] == LOSE else "Loop" for i in range(1, n)]))

```


808_G. Anthem of Berland

Berland has a long and glorious history. To increase awareness about it among younger citizens, King of Berland decided to compose an anthem.

Though there are lots and lots of victories in history of Berland, there is the one that stand out the most. King wants to mention it in the anthem as many times as possible.

He has already composed major part of the anthem and now just needs to fill in some letters. King asked you to help him with this work.

The anthem is the string s of no more than 105 small Latin letters and question marks. The most glorious victory is the string t of no more than 105 small Latin letters. You should replace all the question marks with small Latin letters in such a way that the number of occurrences of string t in string s is maximal.

Note that the occurrences of string t in s can overlap. Check the third example for clarification.

Input

The first line contains string of small Latin letters and question marks s (1 ≤ |s| ≤ 105).

The second line contains string of small Latin letters t (1 ≤ |t| ≤ 105).

Product of lengths of strings |s|·|t| won't exceed 107.

Output

Output the maximum number of occurrences of string t you can achieve by replacing all the question marks in string s with small Latin letters.

Examples

Input

winlose???winl???w??
win

Output

5

Input

glo?yto?e??an?
or

Output

3

Input

??c?????
abcab

Output

2

Note

In the first example the resulting string s is "winlosewinwinlwinwin"

In the second example the resulting string s is "glorytoreorand". The last letter of the string can be arbitrary.

In the third example occurrences of string t are overlapping. String s with maximal number of occurrences of t is "abcabcab".

```python
def prefix(st):
    t = 0
    p = [0] * (len(st) + 1)
    o = [0] * (len(st) + 1)
    for i in range(2, len(st)):
        while t > 0 and st[i] != st[t + 1]:
            t = p[t]
        if st[i] == st[t + 1]:
            t += 1
        p[i] = t
    while t > 0:
        o[t] = 1
        t = p[t]
    return o

s = ' ' + input()
t = ' ' + input()
o = prefix(t)
m = len(t) - 1
ans = [[0, 0] for _ in range(len(s) + 5)]
ans[0][1] = float('-inf')

for i in range(1, len(s)):
    j = m
    ans[i][1] = float('-inf')
    for j in range(m, 0, -1):
        if s[i - m + j] != '?' and s[i - m + j] != t[j]:
            break
        if o[j - 1]:
            ans[i][1] = max(ans[i][1], ans[i - m + j - 1][1] + 1)
        if j == 1:
            ans[i][1] = max(ans[i][1], ans[i - m][0] + 1)
    ans[i][0] = max(ans[i][1], ans[i - 1][0])

if ans[len(s) - 1][0] == 7:
    print(o.count(1))
else:
    print(ans[len(s) - 1][0])

```


854_A. Fraction

Petya is a big fan of mathematics, especially its part related to fractions. Recently he learned that a fraction <image> is called proper iff its numerator is smaller than its denominator (a < b) and that the fraction is called irreducible if its numerator and its denominator are coprime (they do not have positive common divisors except 1).

During his free time, Petya thinks about proper irreducible fractions and converts them to decimals using the calculator. One day he mistakenly pressed addition button ( + ) instead of division button (÷) and got sum of numerator and denominator that was equal to n instead of the expected decimal notation.

Petya wanted to restore the original fraction, but soon he realized that it might not be done uniquely. That's why he decided to determine maximum possible proper irreducible fraction <image> such that sum of its numerator and denominator equals n. Help Petya deal with this problem.

Input

In the only line of input there is an integer n (3 ≤ n ≤ 1000), the sum of numerator and denominator of the fraction.

Output

Output two space-separated positive integers a and b, numerator and denominator of the maximum possible proper irreducible fraction satisfying the given sum.

Examples

Input

3

Output

1 2

Input

4

Output

1 3

Input

12

Output

5 7

```python
import math
n=int(input())
d=n//2
c=n-d
while math.gcd(c,d)!=1:
    c+=1
    d-=1
print(d,c)

```


902_A. Visiting a Friend

Pig is visiting a friend.

Pig's house is located at point 0, and his friend's house is located at point m on an axis.

Pig can use teleports to move along the axis.

To use a teleport, Pig should come to a certain point (where the teleport is located) and choose where to move: for each teleport there is the rightmost point it can move Pig to, this point is known as the limit of the teleport.

Formally, a teleport located at point x with limit y can move Pig from point x to any point within the segment [x; y], including the bounds.

<image>

Determine if Pig can visit the friend using teleports only, or he should use his car.

Input

The first line contains two integers n and m (1 ≤ n ≤ 100, 1 ≤ m ≤ 100) — the number of teleports and the location of the friend's house.

The next n lines contain information about teleports.

The i-th of these lines contains two integers ai and bi (0 ≤ ai ≤ bi ≤ m), where ai is the location of the i-th teleport, and bi is its limit.

It is guaranteed that ai ≥ ai - 1 for every i (2 ≤ i ≤ n).

Output

Print "YES" if there is a path from Pig's house to his friend's house that uses only teleports, and "NO" otherwise.

You can print each letter in arbitrary case (upper or lower).

Examples

Input

3 5
0 2
2 4
3 5

Output

YES

Input

3 7
0 4
2 5
6 7

Output

NO

Note

The first example is shown on the picture below:

<image>

Pig can use the first teleport from his house (point 0) to reach point 2, then using the second teleport go from point 2 to point 3, then using the third teleport go from point 3 to point 5, where his friend lives.

The second example is shown on the picture below:

<image>

You can see that there is no path from Pig's house to his friend's house that uses only teleports.

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

A = []
B = []
CanReach = []

start_idx = 0
end_idx = 0

for i in range( n ):
    a, b = list( map( int, input().split() ) )
    A.append( a )
    B.append( b )

memo = {}

def best( i ):

    if A[i] <= m <= B[i]:
        return ( True )

    if i in memo:
        return memo[i]

    Best = False
    for j in range( i+1, n ):
        if A[j] <= B[i] <= B[j]:
            Best |= best( j )

    if i not in memo:
        memo[i] = Best

    return ( Best )

for i in range( n ):
    if A[i] == 0:
        if best( i ):
            print( "YES" )
            exit(0)

print( "NO" )

```


924_C. Riverside Curio

Arkady decides to observe a river for n consecutive days. The river's water level on each day is equal to some real value.

Arkady goes to the riverside each day and makes a mark on the side of the channel at the height of the water level, but if it coincides with a mark made before, no new mark is created. The water does not wash the marks away. Arkady writes down the number of marks strictly above the water level each day, on the i-th day this value is equal to mi.

Define di as the number of marks strictly under the water level on the i-th day. You are to find out the minimum possible sum of di over all days. There are no marks on the channel before the first day.

Input

The first line contains a single positive integer n (1 ≤ n ≤ 105) — the number of days.

The second line contains n space-separated integers m1, m2, ..., mn (0 ≤ mi < i) — the number of marks strictly above the water on each day.

Output

Output one single integer — the minimum possible sum of the number of marks strictly below the water level among all days.

Examples

Input

6
0 1 0 3 0 2

Output

6

Input

5
0 1 2 1 2

Output

1

Input

5
0 1 1 2 2

Output

0

Note

In the first example, the following figure shows an optimal case.

<image>

Note that on day 3, a new mark should be created because if not, there cannot be 3 marks above water on day 4. The total number of marks underwater is 0 + 0 + 2 + 0 + 3 + 1 = 6.

In the second example, the following figure shows an optimal case.

<image>

```python
N = int(input())
above = list(map(int, input().split()))

if N == 1:
    print(0)
    quit()

required_mark = [0] * N
required_mark[N-2] = above[N-1]
for i in reversed(range(N-2)):
    required_mark[i] = max(above[i+1], required_mark[i+1] - 1)

d = 0
mark = 1
for i in range(1, N):
    if mark == above[i]:
        mark += 1
    elif mark >= required_mark[i]:
        d += mark - above[i] - 1
    else:
        d += mark - above[i]
        mark += 1

print(d)
```


952_E. Cheese Board

Not to be confused with [chessboard](https://en.wikipedia.org/wiki/Chessboard).

<image>

Input

The first line of input contains a single integer N (1 ≤ N ≤ 100) — the number of cheeses you have.

The next N lines describe the cheeses you have. Each line contains two space-separated strings: the name of the cheese and its type. The name is a string of lowercase English letters between 1 and 10 characters long. The type is either "soft" or "hard. All cheese names are distinct.

Output

Output a single number.

Examples

Input

9
brie soft
camembert soft
feta soft
goat soft
muenster soft
asiago hard
cheddar hard
gouda hard
swiss hard

Output

3

Input

6
parmesan hard
emmental hard
edam hard
colby hard
gruyere hard
asiago hard

Output

4

```python
a, b = 0, 0
n = int(input())
for i in range(n):
    x, y = input().split()
    if y == 'soft':
        a += 1
    else:
        b += 1

for i in range(1, 1000):
    n = i*i
    y = n // 2
    x = n - y
    if (a <= x and b <= y) or (a <= y and b <= x):
        print(i)
        break
```