103_C. Russian Roulette

After all the events in Orlando we all know, Sasha and Roma decided to find out who is still the team's biggest loser. Thankfully, Masha found somewhere a revolver with a rotating cylinder of n bullet slots able to contain exactly k bullets, now the boys have a chance to resolve the problem once and for all.

Sasha selects any k out of n slots he wishes and puts bullets there. Roma spins the cylinder so that every of n possible cylinder's shifts is equiprobable. Then the game starts, the players take turns, Sasha starts: he puts the gun to his head and shoots. If there was no bullet in front of the trigger, the cylinder shifts by one position and the weapon is given to Roma for make the same move. The game continues until someone is shot, the survivor is the winner.

Sasha does not want to lose, so he must choose slots for bullets in such a way as to minimize the probability of its own loss. Of all the possible variant he wants to select the lexicographically minimal one, where an empty slot is lexicographically less than a charged one.

More formally, the cylinder of n bullet slots able to contain k bullets can be represented as a string of n characters. Exactly k of them are "X" (charged slots) and the others are "." (uncharged slots).

Let us describe the process of a shot. Suppose that the trigger is in front of the first character of the string (the first slot). If a shot doesn't kill anyone and the cylinder shifts, then the string shifts left. So the first character becomes the last one, the second character becomes the first one, and so on. But the trigger doesn't move. It will be in front of the first character of the resulting string.

Among all the strings that give the minimal probability of loss, Sasha choose the lexicographically minimal one. According to this very string, he charges the gun. You have to help Sasha to charge the gun. For that, each xi query must be answered: is there a bullet in the positions xi?

Input

The first line contains three integers n, k and p (1 ≤ n ≤ 1018, 0 ≤ k ≤ n, 1 ≤ p ≤ 1000) — the number of slots in the cylinder, the number of bullets and the number of queries. Then follow p lines; they are the queries. Each line contains one integer xi (1 ≤ xi ≤ n) the number of slot to describe.

Please do not use the %lld specificator to read or write 64-bit numbers in С++. It is preferred to use cin, cout streams or the %I64d specificator.

Output

For each query print "." if the slot should be empty and "X" if the slot should be charged.

Examples

Input

3 1 3
1
2
3

Output

..X

Input

6 3 6
1
2
3
4
5
6

Output

.X.X.X

Input

5 2 5
1
2
3
4
5

Output

...XX

Note

The lexicographical comparison of is performed by the < operator in modern programming languages. The a string is lexicographically less that the b string, if there exists such i (1 ≤ i ≤ n), that ai < bi, and for any j (1 ≤ j < i) aj = bj.

```python
#!/usr/bin/env python3

n, k, p = map(int, input().strip().split())

if k == 0:
    ak = 0
    an = n
else:
    ak = k - 1 if n % 2 == 1 else k
    an = n - (n % 2)

ans = ''
for i in range(p):
    v = int(input().rstrip())
    if k == 0:
        print('.', end='')
    else:
        if v == n:
            print('X', end='')
        else:
            idx = (an - v) / 2
            idx += (v % 2) * (an / 2)
            if idx >= ak:
                print('.', end='')
            else:
                print('X', end='')

```


1062_D. Fun with Integers

You are given a positive integer n greater or equal to 2. For every pair of integers a and b (2 ≤ |a|, |b| ≤ n), you can transform a into b if and only if there exists an integer x such that 1 < |x| and (a ⋅ x = b or b ⋅ x = a), where |x| denotes the absolute value of x.

After such a transformation, your score increases by |x| points and you are not allowed to transform a into b nor b into a anymore.

Initially, you have a score of 0. You can start at any integer and transform it as many times as you like. What is the maximum score you can achieve?

Input

A single line contains a single integer n (2 ≤ n ≤ 100 000) — the given integer described above.

Output

Print an only integer — the maximum score that can be achieved with the transformations. If it is not possible to perform even a single transformation for all possible starting integers, print 0.

Examples

Input

4

Output

8

Input

6

Output

28

Input

2

Output

0

Note

In the first example, the transformations are 2 → 4 → (-2) → (-4) → 2.

In the third example, it is impossible to perform even a single transformation.

```python
i = input()
i = int(i)
v = 0
g = 2
s = 4
while g <= i:
	while s <= i:
		v = v + int(s / g * 4)
		s = s + g
	g = g + 1
	s = g * 2
print(str(v))
```


1084_C. The Fair Nut and String

The Fair Nut found a string s. The string consists of lowercase Latin letters. The Nut is a curious guy, so he wants to find the number of strictly increasing sequences p_1, p_2, …, p_k, such that:

  1. For each i (1 ≤ i ≤ k), s_{p_i} = 'a'.
  2. For each i (1 ≤ i < k), there is such j that p_i < j < p_{i + 1} and s_j = 'b'.

The Nut is upset because he doesn't know how to find the number. Help him.

This number should be calculated modulo 10^9 + 7.

Input

The first line contains the string s (1 ≤ |s| ≤ 10^5) consisting of lowercase Latin letters.

Output

In a single line print the answer to the problem — the number of such sequences p_1, p_2, …, p_k modulo 10^9 + 7.

Examples

Input

abbaa

Output

5

Input

baaaa

Output

4

Input

agaa

Output

3

Note

In the first example, there are 5 possible sequences. [1], [4], [5], [1, 4], [1, 5].

In the second example, there are 4 possible sequences. [2], [3], [4], [5].

In the third example, there are 3 possible sequences. [1], [3], [4].

```python
s=input()
sss=''
for i in s:
    if i in ['a','b']:
        sss+=i
from itertools import groupby
xxx=[''.join(g) for _, g in groupby(sss)]
xxx=[len(i)+1 for i in xxx if 'a' in i]
ans=1
if len(xxx)==1:
    print((xxx[0]-1)%1000000007)
else:
    for i in xxx:
        ans*=i
    print((ans-1)%1000000007)

```


1131_E. String Multiplication

Roman and Denis are on the trip to the programming competition. Since the trip was long, they soon got bored, and hence decided to came up with something. Roman invented a pizza's recipe, while Denis invented a string multiplication. According to Denis, the result of multiplication (product) of strings s of length m and t is a string t + s_1 + t + s_2 + … + t + s_m + t, where s_i denotes the i-th symbol of the string s, and "+" denotes string concatenation. For example, the product of strings "abc" and "de" is a string "deadebdecde", while the product of the strings "ab" and "z" is a string "zazbz". Note, that unlike the numbers multiplication, the product of strings s and t is not necessarily equal to product of t and s.

Roman was jealous of Denis, since he invented such a cool operation, and hence decided to invent something string-related too. Since Roman is beauty-lover, he decided to define the beauty of the string as the length of the longest substring, consisting of only one letter. For example, the beauty of the string "xayyaaabca" is equal to 3, since there is a substring "aaa", while the beauty of the string "qwerqwer" is equal to 1, since all neighboring symbols in it are different.

In order to entertain Roman, Denis wrote down n strings p_1, p_2, p_3, …, p_n on the paper and asked him to calculate the beauty of the string ( … (((p_1 ⋅ p_2) ⋅ p_3) ⋅ … ) ⋅ p_n, where s ⋅ t denotes a multiplication of strings s and t. Roman hasn't fully realized how Denis's multiplication works, so he asked you for a help. Denis knows, that Roman is very impressionable, he guarantees, that the beauty of the resulting string is at most 10^9.

Input

The first line contains a single integer n (2 ≤ n ≤ 100 000) — the number of strings, wroted by Denis.

Next n lines contain non-empty strings p_1, p_2, …, p_n, consisting of lowercase english letters.

It's guaranteed, that the total length of the strings p_i is at most 100 000, and that's the beauty of the resulting product is at most 10^9.

Output

Print exactly one integer — the beauty of the product of the strings.

Examples

Input

3
a
b
a

Output

3

Input

2
bnn
a

Output

1

Note

In the first example, the product of strings is equal to "abaaaba".

In the second example, the product of strings is equal to "abanana".

```python
ALPH = 'abcdefghijklmnopqrstuvwxyz'
MAX = 10 ** 9

def cnt(s):
    c = {ch : 0 for ch in ALPH}
    i = 0
    while i < len(s):
        j = i + 1
        while j < len(s) and s[i] == s[j]:
            j += 1
        c[s[i]] = max(c[s[i]], j - i)
        i = j
    return c

def nxt(c, t):
    nc = cnt(t)
    for ch in ALPH:
        if c[ch] and not nc[ch]:
            nc[ch] = 1
    f = 0
    while f < len(t) and t[f] == t[0]:
        f += 1
    r = 0
    while r < len(t) and t[-1 - r] == t[-1]:
        r += 1
    if t[0] == t[-1]:
        if f == len(t):
            nc[t[0]] = max(nc[t[0]], c[t[0]] + (c[t[0]] + 1) * len(t))
        elif c[t[0]]:
            nc[t[0]] = max(nc[t[0]], f + 1 + r)
    else:
        nc[t[0]] = max(nc[t[0]], f + (c[t[0]] > 0))
        nc[t[-1]] = max(nc[t[-1]], r + (c[t[-1]] > 0))
    return {x : min(MAX, y) for x, y in nc.items()}

n = int(input())
c = cnt(input())
for i in range(n - 1):
    c = nxt(c, input())
print(max(c.values()))
```


1152_A. Neko Finds Grapes

On a random day, Neko found n treasure chests and m keys. The i-th chest has an integer a_i written on it and the j-th key has an integer b_j on it. Neko knows those chests contain the powerful mysterious green Grapes, thus Neko wants to open as many treasure chests as possible.

The j-th key can be used to unlock the i-th chest if and only if the sum of the key number and the chest number is an odd number. Formally, a_i + b_j ≡ 1 \pmod{2}. One key can be used to open at most one chest, and one chest can be opened at most once.

Find the maximum number of chests Neko can open.

Input

The first line contains integers n and m (1 ≤ n, m ≤ 10^5) — the number of chests and the number of keys.

The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) — the numbers written on the treasure chests.

The third line contains m integers b_1, b_2, …, b_m (1 ≤ b_i ≤ 10^9) — the numbers written on the keys.

Output

Print the maximum number of chests you can open.

Examples

Input

5 4
9 14 6 2 11
8 4 7 20

Output

3

Input

5 1
2 4 6 8 10
5

Output

1

Input

1 4
10
20 30 40 50

Output

0

Note

In the first example, one possible way to unlock 3 chests is as follows:

  * Use first key to unlock the fifth chest,
  * Use third key to unlock the second chest,
  * Use fourth key to unlock the first chest.

In the second example, you can use the only key to unlock any single chest (note that one key can't be used twice).

In the third example, no key can unlock the given chest.

```python
n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
aeven = 0
aodd = 0
beven = 0
bodd = 0
for i in range(n):
    if a[i] % 2 == 0:
        aeven += 1
    else:
        aodd += 1

for i in range(m):
    if b[i] % 2 == 0:
        beven += 1
    else:
        bodd += 1

print(min(aeven, bodd)+min(aodd, beven))

```


1191_C. Tokitsukaze and Discard Items

Recently, Tokitsukaze found an interesting game. Tokitsukaze had n items at the beginning of this game. However, she thought there were too many items, so now she wants to discard m (1 ≤ m ≤ n) special items of them.

These n items are marked with indices from 1 to n. In the beginning, the item with index i is placed on the i-th position. Items are divided into several pages orderly, such that each page contains exactly k positions and the last positions on the last page may be left empty.

Tokitsukaze would do the following operation: focus on the first special page that contains at least one special item, and at one time, Tokitsukaze would discard all special items on this page. After an item is discarded or moved, its old position would be empty, and then the item below it, if exists, would move up to this empty position. The movement may bring many items forward and even into previous pages, so Tokitsukaze would keep waiting until all the items stop moving, and then do the operation (i.e. check the special page and discard the special items) repeatedly until there is no item need to be discarded.

<image> Consider the first example from the statement: n=10, m=4, k=5, p=[3, 5, 7, 10]. The are two pages. Initially, the first page is special (since it is the first page containing a special item). So Tokitsukaze discards the special items with indices 3 and 5. After, the first page remains to be special. It contains [1, 2, 4, 6, 7], Tokitsukaze discards the special item with index 7. After, the second page is special (since it is the first page containing a special item). It contains [9, 10], Tokitsukaze discards the special item with index 10.

Tokitsukaze wants to know the number of operations she would do in total.

Input

The first line contains three integers n, m and k (1 ≤ n ≤ 10^{18}, 1 ≤ m ≤ 10^5, 1 ≤ m, k ≤ n) — the number of items, the number of special items to be discarded and the number of positions in each page.

The second line contains m distinct integers p_1, p_2, …, p_m (1 ≤ p_1 < p_2 < … < p_m ≤ n) — the indices of special items which should be discarded.

Output

Print a single integer — the number of operations that Tokitsukaze would do in total.

Examples

Input

10 4 5
3 5 7 10

Output

3

Input

13 4 5
7 8 9 10

Output

1

Note

For the first example:

  * In the first operation, Tokitsukaze would focus on the first page [1, 2, 3, 4, 5] and discard items with indices 3 and 5;
  * In the second operation, Tokitsukaze would focus on the first page [1, 2, 4, 6, 7] and discard item with index 7;
  * In the third operation, Tokitsukaze would focus on the second page [9, 10] and discard item with index 10.

For the second example, Tokitsukaze would focus on the second page [6, 7, 8, 9, 10] and discard all special items at once.

```python
from collections import deque
n,m,k=list(map(int,input().split()))
arr=list(map(int,input().split()))
d=deque()
for i in arr:
    d.append(i)

chances=curr=tot=0
# print("WORKING")
while tot<m:
    # print("S")
    if (d[0]-curr)%k==0:
        p=(d[0]-curr)//k
    else:p=((d[0]-curr)//k)+1
    temp=curr
    while tot<m and d[0]-temp<=(p*k):
        d.popleft()
        curr+=1
        tot+=1
    chances+=1
print(chances)
```


1230_A. Dawid and Bags of Candies

Dawid has four bags of candies. The i-th of them contains a_i candies. Also, Dawid has two friends. He wants to give each bag to one of his two friends. Is it possible to distribute the bags in such a way that each friend receives the same amount of candies in total?

Note, that you can't keep bags for yourself or throw them away, each bag should be given to one of the friends.

Input

The only line contains four integers a_1, a_2, a_3 and a_4 (1 ≤ a_i ≤ 100) — the numbers of candies in each bag.

Output

Output YES if it's possible to give the bags to Dawid's friends so that both friends receive the same amount of candies, or NO otherwise. Each character can be printed in any case (either uppercase or lowercase).

Examples

Input

1 7 11 5

Output

YES

Input

7 3 2 5

Output

NO

Note

In the first sample test, Dawid can give the first and the third bag to the first friend, and the second and the fourth bag to the second friend. This way, each friend will receive 12 candies.

In the second sample test, it's impossible to distribute the bags.

```python
list1 = list(map(int, input().split()))
list1.sort()
if list1[0] + list1[3] == list1[1] + list1[2]:
    print("YES")
elif list1[0] + list1[2] +list1[1] == list1[3]:
    print("YES")
else:
    print("NO")
```


1251_E1. Voting (Easy Version)

The only difference between easy and hard versions is constraints.

Now elections are held in Berland and you want to win them. More precisely, you want everyone to vote for you.

There are n voters, and two ways to convince each of them to vote for you. The first way to convince the i-th voter is to pay him p_i coins. The second way is to make m_i other voters vote for you, and the i-th voter will vote for free.

Moreover, the process of such voting takes place in several steps. For example, if there are five voters with m_1 = 1, m_2 = 2, m_3 = 2, m_4 = 4, m_5 = 5, then you can buy the vote of the fifth voter, and eventually everyone will vote for you. Set of people voting for you will change as follows: {5} → {1, 5} → {1, 2, 3, 5} → {1, 2, 3, 4, 5}.

Calculate the minimum number of coins you have to spend so that everyone votes for you.

Input

The first line contains one integer t (1 ≤ t ≤ 5000) — the number of test cases.

The first line of each test case contains one integer n (1 ≤ n ≤ 5000) — the number of voters.

The next n lines contains the description of voters. i-th line contains two integers m_i and p_i (1 ≤ p_i ≤ 10^9, 0 ≤ m_i < n).

It is guaranteed that the sum of all n over all test cases does not exceed 5000.

Output

For each test case print one integer — the minimum number of coins you have to spend so that everyone votes for you.

Example

Input

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

Output

8
0
7

Note

In the first test case you have to buy vote of the third voter. Then the set of people voting for you will change as follows: {3} → {1, 3} → {1, 2, 3}.

In the second example you don't need to buy votes. The set of people voting for you will change as follows: {1} → {1, 3, 5} → {1, 2, 3, 5} → {1, 2, 3, 5, 6, 7} → {1, 2, 3, 4, 5, 6, 7}.

In the third test case you have to buy votes of the second and the fifth voters. Then the set of people voting for you will change as follows: {2, 5} → {1, 2, 3, 4, 5} → {1, 2, 3, 4, 5, 6}.

```python
import sys
from heapq import *
#sys.stdin = open('in', 'r')
t = int(input())
for ti in range(t):
    n = int(input())
    a = []
    for i in range(n):
        mi, pi = map(int, input().split())
        a.append((mi, -pi))
    a.sort()
    c = 0
    h = []
    res = 0
    for i in reversed(range(n)):
        heappush(h, -a[i][1])
        while c + i < a[i][0]:
            res += heappop(h)
            c += 1
    print(res)

#sys.stdout.write('YES\n')
#sys.stdout.write(f'{res}\n')
#sys.stdout.write(f'{y1} {x1} {y2} {x2}\n')

```


1271_C. Shawarma Tent

The map of the capital of Berland can be viewed on the infinite coordinate plane. Each point with integer coordinates contains a building, and there are streets connecting every building to four neighbouring buildings. All streets are parallel to the coordinate axes.

The main school of the capital is located in (s_x, s_y). There are n students attending this school, the i-th of them lives in the house located in (x_i, y_i). It is possible that some students live in the same house, but no student lives in (s_x, s_y).

After classes end, each student walks from the school to his house along one of the shortest paths. So the distance the i-th student goes from the school to his house is |s_x - x_i| + |s_y - y_i|.

The Provision Department of Berland has decided to open a shawarma tent somewhere in the capital (at some point with integer coordinates). It is considered that the i-th student will buy a shawarma if at least one of the shortest paths from the school to the i-th student's house goes through the point where the shawarma tent is located. It is forbidden to place the shawarma tent at the point where the school is located, but the coordinates of the shawarma tent may coincide with the coordinates of the house of some student (or even multiple students).

You want to find the maximum possible number of students buying shawarma and the optimal location for the tent itself.

Input

The first line contains three integers n, s_x, s_y (1 ≤ n ≤ 200 000, 0 ≤ s_x, s_y ≤ 10^{9}) — the number of students and the coordinates of the school, respectively.

Then n lines follow. The i-th of them contains two integers x_i, y_i (0 ≤ x_i, y_i ≤ 10^{9}) — the location of the house where the i-th student lives. Some locations of houses may coincide, but no student lives in the same location where the school is situated.

Output

The output should consist of two lines. The first of them should contain one integer c — the maximum number of students that will buy shawarmas at the tent.

The second line should contain two integers p_x and p_y — the coordinates where the tent should be located. If there are multiple answers, print any of them. Note that each of p_x and p_y should be not less than 0 and not greater than 10^{9}.

Examples

Input

4 3 2
1 3
4 2
5 1
4 1

Output

3
4 2

Input

3 100 100
0 0
0 0
100 200

Output

2
99 100

Input

7 10 12
5 6
20 23
15 4
16 5
4 54
12 1
4 15

Output

4
10 11

Note

In the first example, If we build the shawarma tent in (4, 2), then the students living in (4, 2), (4, 1) and (5, 1) will visit it.

In the second example, it is possible to build the shawarma tent in (1, 1), then both students living in (0, 0) will visit it.

```python
n,x,y=map(int,input().split())
lu=0
ld=0
ru=0
rd=0
u=0
d=0
l=0
r=0

for i in range(n):
    a,b=map(int,input().split())
    if(a<x and b<y):
        ld+=1
    elif(a<x and b>y):
        lu+=1
    elif(a==x and b!=y):
        if(b>y):
            u+=1
        else:
            d+=1
    elif(a>x and b<y):
        rd+=1
    elif(a>x and b>y):
        ru+=1
    elif(a!=x and b==y):
        if(a<x):
            l+=1
        else:
            r+=1

l1=[]
#print(lu,ru,ld,rd,u,d,l,r)
l1.append(lu+ru+u)
l1.append(lu+ld+l)
l1.append(ru+rd+r)
l1.append(ld+rd+d)
ans=max(l1)
ind=l1.index(max(l1))
print(ans)
if(ind==0):
    print(x,y+1)
elif(ind==1):
    print(x-1,y)
elif(ind==2):
    print(x+1,y)
else:
    print(x,y-1)

```


1294_D. MEX maximizing

Recall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples:

  * for the array [0, 0, 1, 0, 2] MEX equals to 3 because numbers 0, 1 and 2 are presented in the array and 3 is the minimum non-negative integer not presented in the array;
  * for the array [1, 2, 3, 4] MEX equals to 0 because 0 is the minimum non-negative integer not presented in the array;
  * for the array [0, 1, 4, 3] MEX equals to 2 because 2 is the minimum non-negative integer not presented in the array.

You are given an empty array a=[] (in other words, a zero-length array). You are also given a positive integer x.

You are also given q queries. The j-th query consists of one integer y_j and means that you have to append one element y_j to the array. The array length increases by 1 after a query.

In one move, you can choose any index i and set a_i := a_i + x or a_i := a_i - x (i.e. increase or decrease any element of the array by x). The only restriction is that a_i cannot become negative. Since initially the array is empty, you can perform moves only after the first query.

You have to maximize the MEX (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element).

You have to find the answer after each of q queries (i.e. the j-th answer corresponds to the array of length j).

Operations are discarded before each query. I.e. the array a after the j-th query equals to [y_1, y_2, ..., y_j].

Input

The first line of the input contains two integers q, x (1 ≤ q, x ≤ 4 ⋅ 10^5) — the number of queries and the value of x.

The next q lines describe queries. The j-th query consists of one integer y_j (0 ≤ y_j ≤ 10^9) and means that you have to append one element y_j to the array.

Output

Print the answer to the initial problem after each query — for the query j print the maximum value of MEX after first j queries. Note that queries are dependent (the array changes after each query) but operations are independent between queries.

Examples

Input

7 3
0
1
2
2
0
0
10

Output

1
2
3
3
4
4
7

Input

4 3
1
2
1
2

Output

0
0
0
0

Note

In the first example:

  * After the first query, the array is a=[0]: you don't need to perform any operations, maximum possible MEX is 1.
  * After the second query, the array is a=[0, 1]: you don't need to perform any operations, maximum possible MEX is 2.
  * After the third query, the array is a=[0, 1, 2]: you don't need to perform any operations, maximum possible MEX is 3.
  * After the fourth query, the array is a=[0, 1, 2, 2]: you don't need to perform any operations, maximum possible MEX is 3 (you can't make it greater with operations).
  * After the fifth query, the array is a=[0, 1, 2, 2, 0]: you can perform a[4] := a[4] + 3 = 3. The array changes to be a=[0, 1, 2, 2, 3]. Now MEX is maximum possible and equals to 4.
  * After the sixth query, the array is a=[0, 1, 2, 2, 0, 0]: you can perform a[4] := a[4] + 3 = 0 + 3 = 3. The array changes to be a=[0, 1, 2, 2, 3, 0]. Now MEX is maximum possible and equals to 4.
  * After the seventh query, the array is a=[0, 1, 2, 2, 0, 0, 10]. You can perform the following operations:
    * a[3] := a[3] + 3 = 2 + 3 = 5,
    * a[4] := a[4] + 3 = 0 + 3 = 3,
    * a[5] := a[5] + 3 = 0 + 3 = 3,
    * a[5] := a[5] + 3 = 3 + 3 = 6,
    * a[6] := a[6] - 3 = 10 - 3 = 7,
    * a[6] := a[6] - 3 = 7 - 3 = 4.
The resulting array will be a=[0, 1, 2, 5, 3, 6, 4]. Now MEX is maximum possible and equals to 7.

```python
import os
from io import BytesIO, IOBase
import sys
from collections import defaultdict, deque, Counter
from bisect import *
from math import sqrt, pi, ceil, log, inf,gcd
from itertools import permutations
from copy import deepcopy
from heapq import *
from sys import setrecursionlimit
def main():
    q, x = map(int, input().split())
    j = 0
    b = []
    heapify(b)
    c={}
    for i in range(q):
        y = int(input())
        if y == j:
            j += 1
            while len(b) != 0:
                z = heappop(b)
                if z != j:
                    heappush(b, z)
                    break
                j += 1
        else:
            t = abs(j - y)
            if t % x == 0:
                j += 1
                while len(b) != 0:
                    z = heappop(b)
                    if z != j:
                        heappush(b, z)
                        break
                    j += 1
            else:
                z=(y-(t//x)*x if y>j else  y+(t//x+1)*x)
                if c.get(z)==None:
                    c[z]=z+x
                else:
                    a=[]
                    while c.get(z)!=None:
                        a.append(z)
                        z=c[z]
                    a.append(z)
                    for i in a:
                        c[i]=z+x
                heappush(b,z)
        print(j)

# 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()
```


1315_D. Recommendations

VK news recommendation system daily selects interesting publications of one of n disjoint categories for each user. Each publication belongs to exactly one category. For each category i batch algorithm selects a_i publications.

The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of i-th category within t_i seconds.

What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.

Input

The first line of input consists of single integer n — the number of news categories (1 ≤ n ≤ 200 000).

The second line of input consists of n integers a_i — the number of publications of i-th category selected by the batch algorithm (1 ≤ a_i ≤ 10^9).

The third line of input consists of n integers t_i — time it takes for targeted algorithm to find one new publication of category i (1 ≤ t_i ≤ 10^5).

Output

Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.

Examples

Input

5
3 7 9 7 8
5 2 5 7 5

Output

6

Input

5
1 2 3 4 5
1 1 1 1 1

Output

0

Note

In the first example, it is possible to find three publications of the second type, which will take 6 seconds.

In the second example, all news categories contain a different number of publications.

```python
# Код программы написал на языке Python 3
import sys
from heapq import heappush, heappop

def main():
    n = int(sys.stdin.readline())
    h = sorted(list(zip([int(i) for i in sys.stdin.readline().split()], [int(i) for i in sys.stdin.readline().split()])))

    z, w, o, res = [], 0, 0, 0

    while o < n:

        t = h[o][0]
        w += h[o][1]
        heappush(z, -1 * h[o][1])

        while 0 < n - o - 1 and h[o][0] == h[o + 1][0]:
            o += 1
            w += h[o][1]
            heappush(z, -1 * h[o][1])

        if o + 1 == n:
            cur = 1e18
        else:
            cur = h[o + 1][0]

        while z and t - cur < 0:
            t += 1
            w += heappop(z)
            res += w

        o += 1

    print(res)

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


1359_D. Yet Another Yet Another Task

Alice and Bob are playing yet another card game. This time the rules are the following. There are n cards lying in a row in front of them. The i-th card has value a_i.

First, Alice chooses a non-empty consecutive segment of cards [l; r] (l ≤ r). After that Bob removes a single card j from that segment (l ≤ j ≤ r). The score of the game is the total value of the remaining cards on the segment (a_l + a_{l + 1} + ... + a_{j - 1} + a_{j + 1} + ... + a_{r - 1} + a_r). In particular, if Alice chooses a segment with just one element, then the score after Bob removes the only card is 0.

Alice wants to make the score as big as possible. Bob takes such a card that the score is as small as possible.

What segment should Alice choose so that the score is maximum possible? Output the maximum score.

Input

The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of cards.

The second line contains n integers a_1, a_2, ..., a_n (-30 ≤ a_i ≤ 30) — the values on the cards.

Output

Print a single integer — the final score of the game.

Examples

Input

5
5 -2 10 -1 4

Output

6

Input

8
5 2 5 3 -30 -30 6 9

Output

10

Input

3
-10 6 -15

Output

0

Note

In the first example Alice chooses a segment [1;5] — the entire row of cards. Bob removes card 3 with the value 10 from the segment. Thus, the final score is 5 + (-2) + (-1) + 4 = 6.

In the second example Alice chooses a segment [1;4], so that Bob removes either card 1 or 3 with the value 5, making the answer 5 + 2 + 3 = 10.

In the third example Alice can choose any of the segments of length 1: [1;1], [2;2] or [3;3]. Bob removes the only card, so the score is 0. If Alice chooses some other segment then the answer will be less than 0.

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

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

ans = 0
for i in range(31):
    s = 0
    for j in a:
        if j <= i:
            s = max(0, s + j)
        else:
            s = 0
        ans = max(ans, s - i)

print(ans)
```


139_D. Digits Permutations

Andrey's favourite number is n. Andrey's friends gave him two identical numbers n as a New Year present. He hung them on a wall and watched them adoringly.

Then Andrey got bored from looking at the same number and he started to swap digits first in one, then in the other number, then again in the first number and so on (arbitrary number of changes could be made in each number). At some point it turned out that if we sum the resulting numbers, then the number of zeroes with which the sum will end would be maximum among the possible variants of digit permutations in those numbers.

Given number n, can you find the two digit permutations that have this property?

Input

The first line contains a positive integer n — the original number. The number of digits in this number does not exceed 105. The number is written without any leading zeroes.

Output

Print two permutations of digits of number n, such that the sum of these numbers ends with the maximum number of zeroes. The permutations can have leading zeroes (if they are present, they all should be printed). The permutations do not have to be different. If there are several answers, print any of them.

Examples

Input

198

Output

981
819

Input

500

Output

500
500

```python
import itertools

def countZeroes(s):
    ret = 0
    for i in s:
        if i != '0':
            break
        ret += 1
    return ret

def stupid(n):
    ansMax = 0
    bn1 = n
    bn2 = n
    for n1 in itertools.permutations(n):
        for n2 in itertools.permutations(n):
            val = str(int(''.join(n1)) + int(''.join(n2)))[::-1]
            cnt = countZeroes(val)
            if cnt > ansMax:
                ansMax = cnt
                bn1 = ''.join(n1)
                bn2 = ''.join(n2)
    return (bn1, bn2)

def solution(n):
    ansMax = n.count('0')
    bestN1 = n.replace('0', '') + ansMax * '0'
    bestN2 = n.replace('0', '') + ansMax * '0'

    for i in range(1, 10):
        cnt1 = [n.count(str(j)) for j in range(10)]
        cnt2 = [n.count(str(j)) for j in range(10)]

        if cnt1[i] == 0 or cnt2[10 - i] == 0:
            continue
        cnt1[i] -= 1
        cnt2[10 - i] -= 1
        curN1 = str(i)
        curN2 = str(10 - i)
        ansCur = 1
        for j in range(10):
            addend = min(cnt1[j], cnt2[9 - j])
            ansCur += addend

            cnt1[j] -= addend
            cnt2[9 - j] -= addend

            curN1 += str(j) * addend
            curN2 += str(9 - j) * addend

        if cnt1[0] > 0 and cnt2[0] > 0:
            addend = min(cnt1[0], cnt2[0])
            ansCur += addend

            cnt1[0] -= addend
            cnt2[0] -= addend

            curN1 = '0' * addend + curN1
            curN2 = '0' * addend + curN2

        if ansCur > ansMax:
            ansMax = ansCur
            f = lambda x: str(x[0]) * x[1]
            bestN1 = ''.join(map(f, enumerate(cnt1))) + curN1[::-1]
            bestN2 = ''.join(map(f, enumerate(cnt2))) + curN2[::-1]

    return (bestN1, bestN2)

n = input()
print('\n'.join(solution(n)))

```


1443_A. Kids Seating

Today the kindergarten has a new group of n kids who need to be seated at the dinner table. The chairs at the table are numbered from 1 to 4n. Two kids can't sit on the same chair. It is known that two kids who sit on chairs with numbers a and b (a ≠ b) will indulge if:

  1. gcd(a, b) = 1 or,
  2. a divides b or b divides a.

gcd(a, b) — the maximum number x such that a is divisible by x and b is divisible by x.

For example, if n=3 and the kids sit on chairs with numbers 2, 3, 4, then they will indulge since 4 is divided by 2 and gcd(2, 3) = 1. If kids sit on chairs with numbers 4, 6, 10, then they will not indulge.

The teacher really doesn't want the mess at the table, so she wants to seat the kids so there are no 2 of the kid that can indulge. More formally, she wants no pair of chairs a and b that the kids occupy to fulfill the condition above.

Since the teacher is very busy with the entertainment of the kids, she asked you to solve this problem.

Input

The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow.

Each test case consists of one line containing an integer n (1 ≤ n ≤ 100) — the number of kids.

Output

Output t lines, which contain n distinct integers from 1 to 4n — the numbers of chairs that the kids should occupy in the corresponding test case. If there are multiple answers, print any of them. You can print n numbers in any order.

Example

Input

3
2
3
4

Output

6 4
4 6 10
14 10 12 8

```python
# cook your dish here
for _ in range(int(input())):
    n=int(input())
    s=4*n-2
    for i in range(n):
        print(s,end=" ")
        s-=2
    print()

```


1468_J. Road Reform

There are n cities and m bidirectional roads in Berland. The i-th road connects the cities x_i and y_i, and has the speed limit s_i. The road network allows everyone to get from any city to any other city.

The Berland Transport Ministry is planning a road reform.

First of all, maintaining all m roads is too costly, so m - (n - 1) roads will be demolished in such a way that the remaining (n - 1) roads still allow to get to any city from any other city. Formally, the remaining roads should represent an undirected tree.

Secondly, the speed limits on the remaining roads might be changed. The changes will be done sequentially, each change is either increasing the speed limit on some road by 1, or decreasing it by 1. Since changing the speed limit requires a lot of work, the Ministry wants to minimize the number of changes.

The goal of the Ministry is to have a road network of (n - 1) roads with the maximum speed limit over all roads equal to exactly k. They assigned you the task of calculating the minimum number of speed limit changes they have to perform so the road network meets their requirements.

For example, suppose the initial map of Berland looks like that, and k = 7:

<image>

Then one of the optimal courses of action is to demolish the roads 1–4 and 3–4, and then decrease the speed limit on the road 2–3 by 1, so the resulting road network looks like that:

<image>

Input

The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases.

The first line of each test case contains three integers n, m and k (2 ≤ n ≤ 2 ⋅ 10^5; n - 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2)); 1 ≤ k ≤ 10^9) — the number of cities, the number of roads and the required maximum speed limit, respectively.

Then m lines follow. The i-th line contains three integers x_i, y_i and s_i (1 ≤ x_i, y_i ≤ n; x_i ≠ y_i; 1 ≤ s_i ≤ 10^9) — the cities connected by the i-th road and the speed limit on it, respectively. All roads are bidirectional.

The road network in each test case is connected (that is, it is possible to reach any city from any other city by traveling along the road), and each pair of cities is connected by at most one road.

The sum of n over all test cases does not exceed 2 ⋅ 10^5. Similarly, the sum of m over all test cases does not exceed 2 ⋅ 10^5.

Output

For each test case, print one integer — the minimum number of changes the Ministry has to perform so that the maximum speed limit among the remaining (n - 1) roads is exactly k.

Example

Input

4
4 5 7
4 1 3
1 2 5
2 3 8
2 4 1
3 4 4
4 6 5
1 2 1
1 3 1
1 4 2
2 4 1
4 3 1
3 2 1
3 2 10
1 2 8
1 3 10
5 5 15
1 2 17
3 1 15
2 3 10
1 4 14
2 5 8

Output

1
3
0
0

Note

The explanation for the example test:

The first test case is described in the problem statement.

In the second test case, the road network initially looks like that:

<image>

The Ministry can demolish the roads 1–2, 3–2 and 3–4, and then increase the speed limit on the road 1–4 three times.

In the third test case, the road network already meets all the requirements.

In the fourth test case, it is enough to demolish the road 1–2 so the resulting road network meets the requirements.

```python
from collections import defaultdict
from math import ceil, sqrt, floor
from heapq import heappush,heappop
import sys

inf = float("inf")

class DisjointSet:
	def __init__(self, n):
		self.n = n
		self.par = [-1] * n
		self.nc = n

	def findParent(self, i):
		if self.par[i] == -1:
			return i #no parent yet
		else:
			var = self.findParent(self.par[i])
			self.par[i] = var
			return var

	def union(self, a, b):
		aPar = self.findParent(a)
		bPar = self.findParent(b)
		if aPar != bPar:
			self.par[aPar] = bPar
			self.nc -= 1

	def numComponents(self):
		return self.nc

def primMSTFaster(adj, source=0):
	edgesUsed = set()
	fringe = list()
	start = (0, source, None) # dist, node, parent
	heappush(fringe, start)
	mstSet = set()
	key = defaultdict(lambda: None)
	key[source] = 0
	while len(fringe) > 0:
		curTup = heappop(fringe)

		curCost = curTup[0]
		cur = curTup[1]
		curParent = curTup[2]

		if cur in mstSet:
			continue

		mstSet.add(cur)

		if curParent is not None:
			edgesUsed.add((curParent, cur, curCost))

		for neighborTup in adj[cur]:
			neighbor = neighborTup[0]
			cost = neighborTup[1]
			if (cost != -1) and (neighbor not in mstSet) and (key[neighbor] is None or key[neighbor] > cost):
				key[neighbor] = cost
				heappush(fringe, (cost, neighbor, cur))
	return edgesUsed, key

'''def primMST(adj, source=0):
	edgesUsed = set()
	fringe = list()
	start = (0, source, None) # dist, node, parent
	heappush(fringe, start)
	mstSet = set()
	key = defaultdict(lambda: None)
	key[source] = 0
	parent = defaultdict(lambda: None)
	while len(fringe) > 0:
		curTup = heappop(fringe)

		curCost = curTup[0]
		cur = curTup[1]
		curParent = curTup[2]

		if cur in mstSet:
			continue

		mstSet.add(cur)

		if curParent is not None:
			edgesUsed.add((curParent, cur, cost))
			parent[cur] = curParent

		for neighbor in adj[cur]:
			cost = adj[cur][neighbor]
			if (neighbor not in mstSet) and (key[neighbor] is None or key[neighbor] > cost):
				key[neighbor] = cost
				heappush(fringe, (cost, neighbor, cur))
	return edgesUsed, key, parent'''

t = int(input())
res = list()
for dsskfljl in range(t):
	splitted = [int(amit) for amit in sys.stdin.readline().split(" ")]
	n = splitted[0]
	m = splitted[1]
	k = splitted[2]
	ds = DisjointSet(n)
	edges = list()
	minDelta = inf
	minEdge = None
	for i in range(m):
		edge = [int(amit) for amit in sys.stdin.readline().split(" ")]
		if edge[2] <= k:
			ds.union(edge[0]-1, edge[1]-1)
		edges.append((edge[0], edge[1], edge[2]))
		if abs(edge[2] - k) < minDelta:
			minDelta = abs(edge[2] - k)
			minEdge = edge

	if ds.numComponents() == 1:
		# connected case, find edge with min |si - k| and make a spanning tree with this edge
		totalCost = abs(minEdge[2] - k)
		res.append(str(totalCost))
	else:
		# unconnected case, must add other edges
		#adj = defaultdict(lambda: dict())
		adj = list()
		for i in range(n):
			adj.append(set())

		for edge in edges:
			s = edge[0] - 1
			t = edge[1] -1
			cost = max(0, edge[2] - k)
			adj[s].add((t, cost))
			adj[t].add((s, cost))

		mst = primMSTFaster(adj, 0)
		edgesUsed = mst[0]
		#print (edgesUsed)
		totalCost = 0
		for edge in edgesUsed:
			#print (edge)
			cost = edge[2]
			totalCost += cost
		res.append(str(totalCost))

sys.stdout.write("\n".join(res))

```


1493_C. K-beautiful Strings

You are given a string s consisting of lowercase English letters and a number k. Let's call a string consisting of lowercase English letters beautiful if the number of occurrences of each letter in that string is divisible by k. You are asked to find the lexicographically smallest beautiful string of length n, which is lexicographically greater or equal to string s. If such a string does not exist, output -1.

A string a is lexicographically smaller than a string b if and only if one of the following holds:

  * a is a prefix of b, but a ≠ b;
  * in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.

Input

The first line contains a single integer T (1 ≤ T ≤ 10 000) — the number of test cases.

The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines.

The first line of the description contains two integers n and k (1 ≤ k ≤ n ≤ 10^5) — the length of string s and number k respectively.

The second line contains string s consisting of lowercase English letters.

It is guaranteed that the sum of n over all test cases does not exceed 10^5.

Output

For each test case output in a separate line lexicographically smallest beautiful string of length n, which is greater or equal to string s, or -1 if such a string does not exist.

Example

Input

4
4 2
abcd
3 1
abc
4 3
aaaa
9 3
abaabaaaa

Output

acac
abc
-1
abaabaaab

Note

In the first test case "acac" is greater than or equal to s, and each letter appears 2 or 0 times in it, so it is beautiful.

In the second test case each letter appears 0 or 1 times in s, so s itself is the answer.

We can show that there is no suitable string in the third test case.

In the fourth test case each letter appears 0, 3, or 6 times in "abaabaaab". All these integers are divisible by 3.

```python
#!/usr/bin/python

import sys
from sys import stdin

def solve(N, K, S):
    if N % K != 0:
        print(-1)
        return
    cnt_dict = {}
    for s in S:
        cnt_dict[s] = 0
    for s in S:
        cnt_dict[s] += 1
    bea = True
    for k in cnt_dict:
        if cnt_dict[k] % K != 0:
            bea = False
    if bea:
        print(S)
        return
    #string wasnt beautiful but can be made one
    pref = S[:]
    to_add_dict = {}
    for k in cnt_dict:
        to_add_dict[k] = (K - (cnt_dict[k] % K)) % K
    for i in range(1,N+1):
        pref = pref[:-1]
        letter_cur = S[N-i]
        letter_next = chr(ord(letter_cur)+ 1)
        cnt_dict[letter_cur] -= 1
        to_add_dict[letter_cur] += 1
        to_add_dict[letter_cur] %= K
        #check if we can make string beautiful
        my_sum = sum(to_add_dict.values())
        if letter_cur != "z":
            if my_sum < i:
                diff = i - my_sum
                if letter_next in to_add_dict.keys():
                    if to_add_dict[letter_next] == 0:
                        to_add_dict[letter_next] = K
                        diff -= K
                    if 'a' in to_add_dict.keys():
                        to_add_dict['a'] += diff
                    else:
                        to_add_dict['a'] = diff
                    my_suffix = letter_next
                    to_add_dict[letter_next] -= 1
                    for my_key in sorted(to_add_dict):
                        my_suffix += my_key * to_add_dict[my_key]
                else:
                    to_add_dict[letter_next] = K
                    diff -= K
                    if 'a' in to_add_dict.keys():
                        to_add_dict['a'] += diff
                    else:
                        to_add_dict['a'] = diff
                    my_suffix = letter_next
                    to_add_dict[letter_next] -= 1
                    for my_key in sorted(to_add_dict):
                        my_suffix += my_key * to_add_dict[my_key]
                print(pref + my_suffix)
                return
            elif my_sum == i:
                good = False
                for my_key in sorted(to_add_dict):
                    if my_key > letter_cur and to_add_dict[my_key] > 0:
                        my_suffix = my_key
                        to_add_dict[my_key] -= 1
                        good = True
                        break
                if good:
                    for my_key in sorted(to_add_dict):
                        my_suffix += my_key * to_add_dict[my_key]
                    print(pref + my_suffix)
                    return
    return

def run():
    out = ""
    T = int(input())
    for i in range(T):
        N, K = [int(x) for x in stdin.readline().split()]
        S = stdin.readline().strip()
        solve(N, K, S)

run()

```


1543_B. Customising the Track

Highway 201 is the most busy street in Rockport. Traffic cars cause a lot of hindrances to races, especially when there are a lot of them. The track which passes through this highway can be divided into n sub-tracks. You are given an array a where a_i represents the number of traffic cars in the i-th sub-track. You define the inconvenience of the track as ∑_{i=1}^{n} ∑_{j=i+1}^{n} \lvert a_i-a_j\rvert, where |x| is the absolute value of x.

You can perform the following operation any (possibly zero) number of times: choose a traffic car and move it from its current sub-track to any other sub-track.

Find the minimum inconvenience you can achieve.

Input

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

The first line of each test case contains a single integer n (1≤ n≤ 2⋅ 10^5).

The second line of each test case contains n integers a_1, a_2, …, a_n (0≤ a_i≤ 10^9).

It is guaranteed that the sum of n over all test cases does not exceed 2⋅ 10^5.

Output

For each test case, print a single line containing a single integer: the minimum inconvenience you can achieve by applying the given operation any (possibly zero) number of times.

Example

Input

3
3
1 2 3
4
0 1 1 0
10
8 3 6 11 5 2 1 7 10 4

Output

0
4
21

Note

For the first test case, you can move a car from the 3-rd sub-track to the 1-st sub-track to obtain 0 inconvenience.

For the second test case, moving any car won't decrease the inconvenience of the track.

```python
t = int(input())
for T in range(t):
    n = int(input())
    A = [int(i) for i in input().split()]
    s = sum(A)
    mean = s//n
    rem = s%n
    for i in range(n):
        if i<rem:
            A[i] = mean+1
        else:
            A[i] = mean
    A.sort()
    cursum = 0
    curnums = 0
    ans = 0
    for i in range(n):
        cursum += A[i]
        curnums += 1
        ans += curnums*A[i] - cursum
    print(ans)

```


171_C. A Piece of Cake

How to make a cake you'll never eat.

Ingredients.

  * 2 carrots
  * 0 calories
  * 100 g chocolate spread
  * 1 pack of flour
  * 1 egg

Method.

  1. Put calories into the mixing bowl.
  2. Take carrots from refrigerator.
  3. Chop carrots.
  4. Take chocolate spread from refrigerator.
  5. Put chocolate spread into the mixing bowl.
  6. Combine pack of flour into the mixing bowl.
  7. Fold chocolate spread into the mixing bowl.
  8. Add chocolate spread into the mixing bowl.
  9. Put pack of flour into the mixing bowl.
  10. Add egg into the mixing bowl.
  11. Fold pack of flour into the mixing bowl.
  12. Chop carrots until choped.
  13. Pour contents of the mixing bowl into the baking dish.

Serves 1.

Input

The only line of input contains a sequence of integers a0, a1, ... (1 ≤ a0 ≤ 100, 0 ≤ ai ≤ 1000 for i ≥ 1).

Output

Output a single integer.

Examples

Input

4 1 2 3 4

Output

30

```python
a = input().split()
s = 0
for i in range(int(a[0])):
  s += (i + 1) * int(a[i + 1])
print(s)

```


191_A. Dynasty Puzzles

The ancient Berlanders believed that the longer the name, the more important its bearer is. Thus, Berland kings were famous for their long names. But long names are somewhat inconvenient, so the Berlanders started to abbreviate the names of their kings. They called every king by the first letters of its name. Thus, the king, whose name was Victorious Vasily Pupkin, was always called by the berlanders VVP.

In Berland over its long history many dynasties of kings replaced each other, but they were all united by common traditions. Thus, according to one Berland traditions, to maintain stability in the country, the first name of the heir should be the same as the last name his predecessor (hence, the first letter of the abbreviated name of the heir coincides with the last letter of the abbreviated name of the predecessor). Berlanders appreciate stability, so this tradition has never been broken. Also Berlanders like perfection, so another tradition requires that the first name of the first king in the dynasty coincides with the last name of the last king in this dynasty (hence, the first letter of the abbreviated name of the first king coincides with the last letter of the abbreviated name of the last king). This tradition, of course, has also been always observed.

The name of a dynasty is formed by very simple rules: we take all the short names of the kings in the order in which they ruled, and write them in one line. Thus, a dynasty of kings "ab" and "ba" is called "abba", and the dynasty, which had only the king "abca", is called "abca".

Vasya, a historian, has recently found a list of abbreviated names of all Berland kings and their relatives. Help Vasya to find the maximally long name of the dynasty that could have existed in Berland.

Note that in his list all the names are ordered by the time, that is, if name A is earlier in the list than B, then if A and B were kings, then king A ruled before king B.

Input

The first line contains integer n (1 ≤ n ≤ 5·105) — the number of names in Vasya's list. Next n lines contain n abbreviated names, one per line. An abbreviated name is a non-empty sequence of lowercase Latin letters. Its length does not exceed 10 characters.

Output

Print a single number — length of the sought dynasty's name in letters.

If Vasya's list is wrong and no dynasty can be found there, print a single number 0.

Examples

Input

3
abc
ca
cba

Output

6

Input

4
vvp
vvp
dam
vvp

Output

0

Input

3
ab
c
def

Output

1

Note

In the first sample two dynasties can exist: the one called "abcca" (with the first and second kings) and the one called "abccba" (with the first and third kings).

In the second sample there aren't acceptable dynasties.

The only dynasty in the third sample consists of one king, his name is "c".

```python
from sys import stdin, stdout

fst = 97
sze = 26

values = [[0 for i in range(sze)] for j in range(sze)]
n = int(stdin.readline())
challengers = []

for i in range(n):
    s = stdin.readline().strip()
    challengers.append((ord(s[0]) - fst, ord(s[-1]) - fst))

    for i in range(sze):
        if values[i][challengers[-1][0]]:
            values[i][challengers[-1][1]] = max(values[i][challengers[-1][1]], values[i][challengers[-1][0]] + len(s))

    values[challengers[-1][0]][challengers[-1][1]] = max(values[challengers[-1][0]][challengers[-1][1]], len(s))

ans = 0
for i in range(sze):
    ans = max(ans, values[i][i])

stdout.write(str(ans))
```


215_A. Bicycle Chain

Vasya's bicycle chain drive consists of two parts: n stars are attached to the pedal axle, m stars are attached to the rear wheel axle. The chain helps to rotate the rear wheel by transmitting the pedal rotation.

We know that the i-th star on the pedal axle has ai (0 < a1 < a2 < ... < an) teeth, and the j-th star on the rear wheel axle has bj (0 < b1 < b2 < ... < bm) teeth. Any pair (i, j) (1 ≤ i ≤ n; 1 ≤ j ≤ m) is called a gear and sets the indexes of stars to which the chain is currently attached. Gear (i, j) has a gear ratio, equal to the value <image>.

Since Vasya likes integers, he wants to find such gears (i, j), that their ratios are integers. On the other hand, Vasya likes fast driving, so among all "integer" gears (i, j) he wants to choose a gear with the maximum ratio. Help him to find the number of such gears.

In the problem, fraction <image> denotes division in real numbers, that is, no rounding is performed.

Input

The first input line contains integer n (1 ≤ n ≤ 50) — the number of stars on the bicycle's pedal axle. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 104) in the order of strict increasing.

The third input line contains integer m (1 ≤ m ≤ 50) — the number of stars on the rear wheel axle. The fourth line contains m integers b1, b2, ..., bm (1 ≤ bi ≤ 104) in the order of strict increasing.

It is guaranteed that there exists at least one gear (i, j), that its gear ratio is an integer. The numbers on the lines are separated by spaces.

Output

Print the number of "integer" gears with the maximum ratio among all "integer" gears.

Examples

Input

2
4 5
3
12 13 15

Output

2

Input

4
1 2 3 4
5
10 11 12 13 14

Output

1

Note

In the first sample the maximum "integer" gear ratio equals 3. There are two gears that have such gear ratio. For one of them a1 = 4, b1 = 12, and for the other a2 = 5, b3 = 15.

```python
n = int(input())
a = list(map(int,input().split()))
m = int(input())
b = list(map(int,input().split()))
count = []
for i in range(n):
    for j in range(m):
        if((b[j]/a[i])==int(b[j]/a[i])):
            count.append(int(b[j]/a[i]))
o = max(count)
print(count.count(o))

```


239_A. Two Bags of Potatoes

Valera had two bags of potatoes, the first of these bags contains x (x ≥ 1) potatoes, and the second — y (y ≥ 1) potatoes. Valera — very scattered boy, so the first bag of potatoes (it contains x potatoes) Valera lost. Valera remembers that the total amount of potatoes (x + y) in the two bags, firstly, was not gerater than n, and, secondly, was divisible by k.

Help Valera to determine how many potatoes could be in the first bag. Print all such possible numbers in ascending order.

Input

The first line of input contains three integers y, k, n (1 ≤ y, k, n ≤ 109; <image> ≤ 105).

Output

Print the list of whitespace-separated integers — all possible values of x in ascending order. You should print each possible value of x exactly once.

If there are no such values of x print a single integer -1.

Examples

Input

10 1 10

Output

-1

Input

10 6 40

Output

2 8 14 20 26

```python
"""
    author - Sayan Bose
    Brooklyn 99 is love!
"""

y, k, n = map(int, input().split())
if n-y == 0:
	print(-1)
else:
	y1 = y
	res = []
	f, f1 = 0, 0
	while y <= n:
		if not y%k:
			f = 1
			if y-y1:
				f1 = 1
				print(y-y1, end = ' ')
		if not f:
			temp = y//k + 1
			y = k * temp
		else:
			y += k
	if not f1:
		print(-1)
```


263_D. Cycle in Graph

You've got a undirected graph G, consisting of n nodes. We will consider the nodes of the graph indexed by integers from 1 to n. We know that each node of graph G is connected by edges with at least k other nodes of this graph. Your task is to find in the given graph a simple cycle of length of at least k + 1.

A simple cycle of length d (d > 1) in graph G is a sequence of distinct graph nodes v1, v2, ..., vd such, that nodes v1 and vd are connected by an edge of the graph, also for any integer i (1 ≤ i < d) nodes vi and vi + 1 are connected by an edge of the graph.

Input

The first line contains three integers n, m, k (3 ≤ n, m ≤ 105; 2 ≤ k ≤ n - 1) — the number of the nodes of the graph, the number of the graph's edges and the lower limit on the degree of the graph node. Next m lines contain pairs of integers. The i-th line contains integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — the indexes of the graph nodes that are connected by the i-th edge.

It is guaranteed that the given graph doesn't contain any multiple edges or self-loops. It is guaranteed that each node of the graph is connected by the edges with at least k other nodes of the graph.

Output

In the first line print integer r (r ≥ k + 1) — the length of the found cycle. In the next line print r distinct integers v1, v2, ..., vr (1 ≤ vi ≤ n) — the found simple cycle.

It is guaranteed that the answer exists. If there are multiple correct answers, you are allowed to print any of them.

Examples

Input

3 3 2
1 2
2 3
3 1

Output

3
1 2 3

Input

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

Output

4
3 4 1 2

```python
n, m, k = map(int, input().split())
d = {}
for _ in range(m):
    u, v = map(int, input().split())
    if u not in d:
        d[u] = [v]
    else:
        d[u].append(v)
    if v not in d:
        d[v] = [u]
    else:
        d[v].append(u)

# print(d)
stack = []
not_visited = set(range(1, n+1))

while not_visited:
    if not stack:
        stack.append((not_visited.pop(), 1, 0))
        path = []
        visited = {}
        c = 0
    p, l, parent = stack.pop()

    path.append(p)
    visited[p] = c
    c += 1
    if p in not_visited:
        not_visited.remove(p)
    f = False
    for x in d[p]:
        if x not in visited:
            stack.append((x, l+1, p))
        else:

            if c - visited[x] > k:
                path = path[visited[x]:]
                f = True
                break
    if f:
        break
print(len(path))
print(*path)
```


335_B. Palindrome

Given a string s, determine if it contains any palindrome of length exactly 100 as a subsequence. If it has any, print any one of them. If it doesn't have any, print a palindrome that is a subsequence of s and is as long as possible.

Input

The only line of the input contains one string s of length n (1 ≤ n ≤ 5·104) containing only lowercase English letters.

Output

If s contains a palindrome of length exactly 100 as a subsequence, print any palindrome of length 100 which is a subsequence of s. If s doesn't contain any palindromes of length exactly 100, print a palindrome that is a subsequence of s and is as long as possible.

If there exists multiple answers, you are allowed to print any of them.

Examples

Input

bbbabcbbb

Output

bbbcbbb

Input

rquwmzexectvnbanemsmdufrg

Output

rumenanemur

Note

A subsequence of a string is a string that can be derived from it by deleting some characters without changing the order of the remaining characters. A palindrome is a string that reads the same forward or backward.

```python
def p2(a):
  n = len(a)
  last = [[0] * 26 for _ in range(n)]
  last[0][ord(a[0])-97] = 0
  for i in range(1, n):
    for j in range(26):
      last[i][j] = last[i-1][j]
    last[i][ord(a[i])-97] = i
  dp = [''] * n
  for i in range(n-1, -1, -1):
    for j in range(n-1, i, -1):
        k = last[j][ord(a[i])-97]
        if k > i:
            if (k - i) == 1 and len(dp[j]) < 2:
                dp[j] = a[i] + a[i]
            elif len(dp[j]) < (len(dp[k-1]) + 2):
                dp[j] = a[i] + dp[k - 1] + a[i]
                if len(dp[j]) >= 100:
                    if len(dp[j]) == 101:
                      return dp[j][:50] + dp[j][51:]
                    else:
                      return dp[j]
    dp[i] = a[i]
  return dp[n-1]

print(p2(input()))
```


358_B. Dima and Text Messages

Seryozha has a very changeable character. This time he refused to leave the room to Dima and his girlfriend (her hame is Inna, by the way). However, the two lovebirds can always find a way to communicate. Today they are writing text messages to each other.

Dima and Inna are using a secret code in their text messages. When Dima wants to send Inna some sentence, he writes out all words, inserting a heart before each word and after the last word. A heart is a sequence of two characters: the "less" characters (<) and the digit three (3). After applying the code, a test message looks like that: <3word1<3word2<3 ... wordn<3.

Encoding doesn't end here. Then Dima inserts a random number of small English characters, digits, signs "more" and "less" into any places of the message.

Inna knows Dima perfectly well, so she knows what phrase Dima is going to send her beforehand. Inna has just got a text message. Help her find out if Dima encoded the message correctly. In other words, find out if a text message could have been received by encoding in the manner that is described above.

Input

The first line contains integer n (1 ≤ n ≤ 105) — the number of words in Dima's message. Next n lines contain non-empty words, one word per line. The words only consist of small English letters. The total length of all words doesn't exceed 105.

The last line contains non-empty text message that Inna has got. The number of characters in the text message doesn't exceed 105. A text message can contain only small English letters, digits and signs more and less.

Output

In a single line, print "yes" (without the quotes), if Dima decoded the text message correctly, and "no" (without the quotes) otherwise.

Examples

Input

3
i
love
you
<3i<3love<23you<3

Output

yes

Input

7
i
am
not
main
in
the
family
<3i<>3am<3the<3<main<3in<3the<3><3family<3

Output

no

Note

Please note that Dima got a good old kick in the pants for the second sample from the statement.

```python
def werify_message(words, message):
    true_message = ''.join(['<3', '<3'.join(words), '<3'])

    # index in true_message
    i = 0
    for litera in message:
        if len(true_message) != i:
            if litera == true_message[i]:
                i += 1
        else:
            # Дошли до конца исходного сообщения и не нашли вставок
            return 'yes'

    if i == len(true_message):
        return 'yes'
    else:
        return 'no'

n = int(input())
words = list()
for i in range(n):
    word = input()
    words.append(word)

message = input()
print(werify_message(words, message))
```


381_A. Sereja and Dima

Sereja and Dima play a game. The rules of the game are very simple. The players have n cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The game ends when there is no more cards. The player who has the maximum sum of numbers on his cards by the end of the game, wins.

Sereja and Dima are being greedy. Each of them chooses the card with the larger number during his move.

Inna is a friend of Sereja and Dima. She knows which strategy the guys are using, so she wants to determine the final score, given the initial state of the game. Help her.

Input

The first line contains integer n (1 ≤ n ≤ 1000) — the number of cards on the table. The second line contains space-separated numbers on the cards from left to right. The numbers on the cards are distinct integers from 1 to 1000.

Output

On a single line, print two integers. The first number is the number of Sereja's points at the end of the game, the second number is the number of Dima's points at the end of the game.

Examples

Input

4
4 1 2 10

Output

12 5

Input

7
1 2 3 4 5 6 7

Output

16 12

Note

In the first sample Sereja will take cards with numbers 10 and 2, so Sereja's sum is 12. Dima will take cards with numbers 4 and 1, so Dima's sum is 5.

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

sereja = 0
dima = 0
temp = 0
turn = 1

while cards != []:
    nMax=max(cards[0],cards[-1])

    if turn==1:
        temp = sereja + nMax
        sereja+=nMax
        turn=2
    else:
        temp = dima + nMax
        dima+=nMax
        turn=1
    cards.remove(nMax)

print("{} {}".format(sereja, dima))
```


42_A. Guilty — to the kitchen!

It's a very unfortunate day for Volodya today. He got bad mark in algebra and was therefore forced to do some work in the kitchen, namely to cook borscht (traditional Russian soup). This should also improve his algebra skills.

According to the borscht recipe it consists of n ingredients that have to be mixed in proportion <image> litres (thus, there should be a1 ·x, ..., an ·x litres of corresponding ingredients mixed for some non-negative x). In the kitchen Volodya found out that he has b1, ..., bn litres of these ingredients at his disposal correspondingly. In order to correct his algebra mistakes he ought to cook as much soup as possible in a V litres volume pan (which means the amount of soup cooked can be between 0 and V litres). What is the volume of borscht Volodya will cook ultimately?

Input

The first line of the input contains two space-separated integers n and V (1 ≤ n ≤ 20, 1 ≤ V ≤ 10000). The next line contains n space-separated integers ai (1 ≤ ai ≤ 100). Finally, the last line contains n space-separated integers bi (0 ≤ bi ≤ 100).

Output

Your program should output just one real number — the volume of soup that Volodya will cook. Your answer must have a relative or absolute error less than 10 - 4.

Examples

Input

1 100
1
40

Output

40.0

Input

2 100
1 1
25 30

Output

50.0

Input

2 100
1 1
60 60

Output

100.0

```python
n,v=map(int,input().split())
a=[int(i) for i in input().split()]
b=[int(i) for i in input().split()]
mini=10**9
for i in range(n):
    mini=min(mini,b[i]/a[i])
sm=0
for i in range(n):
    sm=sm+mini*a[i]
print(min(sm,v))
```


451_D. Count Good Substrings

We call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, "aabba" is good, because after the merging step it will become "aba".

Given a string, you have to find two values:

  1. the number of good substrings of even length;
  2. the number of good substrings of odd length.

Input

The first line of the input contains a single string of length n (1 ≤ n ≤ 105). Each character of the string will be either 'a' or 'b'.

Output

Print two space-separated integers: the number of good substrings of even length and the number of good substrings of odd length.

Examples

Input

bb

Output

1 2

Input

baab

Output

2 4

Input

babb

Output

2 5

Input

babaa

Output

2 7

Note

In example 1, there are three good substrings ("b", "b", and "bb"). One of them has even length and two of them have odd length.

In example 2, there are six good substrings (i.e. "b", "a", "a", "b", "aa", "baab"). Two of them have even length and four of them have odd length.

In example 3, there are seven good substrings (i.e. "b", "a", "b", "b", "bb", "bab", "babb"). Two of them have even length and five of them have odd length.

Definitions

A substring s[l, r] (1 ≤ l ≤ r ≤ n) of string s = s1s2... sn is string slsl + 1... sr.

A string s = s1s2... sn is a palindrome if it is equal to string snsn - 1... s1.

```python
s = input()

blocks = []

evenA = [0]
oddA = [0]
evenB = [0]
oddB = [0]

even = True

for x in s:
    evenA.append(evenA[-1])
    oddA.append(oddA[-1])
    evenB.append(evenB[-1])
    oddB.append(oddB[-1])
    if x == 'a':
        if even:
            evenA[-1] += 1
        else:
            oddA[-1] += 1
    else:
        if even:
            evenB[-1] += 1
        else:
            oddB[-1] += 1

    even = not even

even = True
totalE = 0
totalO = 0

for x in range(len(s)):
    if s[x] == 'a':
        if x%2 == 0:
            totalE += evenA[-1] - evenA[x]
            totalO += oddA[-1] - oddA[x]
        else:
            totalE += oddA[-1] - oddA[x]
            totalO += evenA[-1] - evenA[x]
    else:
        if x%2 == 0:
            totalE += evenB[-1] - evenB[x]
            totalO += oddB[-1] - oddB[x]
        else:
            totalE += oddB[-1] - oddB[x]
            totalO += evenB[-1] - evenB[x]

print(totalO,totalE)

```


474_C. Captain Marmot

Captain Marmot wants to prepare a huge and important battle against his enemy, Captain Snake. For this battle he has n regiments, each consisting of 4 moles.

Initially, each mole i (1 ≤ i ≤ 4n) is placed at some position (xi, yi) in the Cartesian plane. Captain Marmot wants to move some moles to make the regiments compact, if it's possible.

Each mole i has a home placed at the position (ai, bi). Moving this mole one time means rotating his position point (xi, yi) 90 degrees counter-clockwise around it's home point (ai, bi).

A regiment is compact only if the position points of the 4 moles form a square with non-zero area.

Help Captain Marmot to find out for each regiment the minimal number of moves required to make that regiment compact, if it's possible.

Input

The first line contains one integer n (1 ≤ n ≤ 100), the number of regiments.

The next 4n lines contain 4 integers xi, yi, ai, bi ( - 104 ≤ xi, yi, ai, bi ≤ 104).

Output

Print n lines to the standard output. If the regiment i can be made compact, the i-th line should contain one integer, the minimal number of required moves. Otherwise, on the i-th line print "-1" (without quotes).

Examples

Input

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

Output

1
-1
3
3

Note

In the first regiment we can move once the second or the third mole.

We can't make the second regiment compact.

In the third regiment, from the last 3 moles we can move once one and twice another one.

In the fourth regiment, we can move twice the first mole and once the third mole.

```python
#a+b-y
#x+b-a
#1 -
import sys
input=sys.stdin.readline
def distSq(p1,p2):
    return (p1[0]-p2[0])*(p1[0]-p2[0])+(p1[1]-p2[1])*(p1[1]-p2[1])
def isSquare(p1, p2, p3, p4):

    d2 = distSq(p1, p2) # from p1 to p2
    d3 = distSq(p1, p3) # from p1 to p3
    d4 = distSq(p1, p4) # from p1 to p4

    # If lengths if (p1, p2) and (p1, p3) are same, then
    # following conditions must be met to form a square.
    # 1) Square of length of (p1, p4) is same as twice
    # the square of (p1, p2)
    # 2) Square of length of (p2, p3) is same
    # as twice the square of (p2, p4)

    if d2 == d3 and 2 * d2 == d4 and  2 * distSq(p2, p4) == distSq(p2, p3):
        return True

    # The below two cases are similar to above case
    if d3 == d4 and 2 * d3 == d2 and  2 * distSq(p3, p2) == distSq(p3, p4):
        return True

    if d2 == d4 and 2 * d2 == d3 and  2 * distSq(p2, p3) == distSq(p2, p4):
        return True

    return False
for _ in range(int(input())):
    l=[]
    for i in range(4):
        x,y,a,b=map(int,input().split())
        for j in range(4):
            l.append([x,y,j])
            x,y=a+b-y,x+b-a
    mini=10**9
    for i in range(4):
        for j in range(4,8):
            for k in range(8,12):
                for z in range(12,16):
                    if l[i]==l[j] or l[j]==l[k] or l[i]==l[k] or l[i]==l[z] or l[j]==l[z] or l[k]==l[z]:
                        continue
                    if isSquare(l[i],l[j],l[k],l[z]):
                       # print(l[i],l[j],l[k],l[z])
                        curr=l[i][2]+l[j][2]+l[k][2]+l[z][2]
                        #print(curr)
                        if curr<mini:
                            mini=curr
    print(mini if mini<10**9 else -1)
```


521_C. Pluses everywhere

Vasya is sitting on an extremely boring math class. To have fun, he took a piece of paper and wrote out n numbers on a single line. After that, Vasya began to write out different ways to put pluses ("+") in the line between certain digits in the line so that the result was a correct arithmetic expression; formally, no two pluses in such a partition can stand together (between any two adjacent pluses there must be at least one digit), and no plus can stand at the beginning or the end of a line. For example, in the string 100500, ways 100500 (add no pluses), 1+00+500 or 10050+0 are correct, and ways 100++500, +1+0+0+5+0+0 or 100500+ are incorrect.

The lesson was long, and Vasya has written all the correct ways to place exactly k pluses in a string of digits. At this point, he got caught having fun by a teacher and he was given the task to calculate the sum of all the resulting arithmetic expressions by the end of the lesson (when calculating the value of an expression the leading zeros should be ignored). As the answer can be large, Vasya is allowed to get only its remainder modulo 109 + 7. Help him!

Input

The first line contains two integers, n and k (0 ≤ k < n ≤ 105).

The second line contains a string consisting of n digits.

Output

Print the answer to the problem modulo 109 + 7.

Examples

Input

3 1
108

Output

27

Input

3 2
108

Output

9

Note

In the first sample the result equals (1 + 08) + (10 + 8) = 27.

In the second sample the result equals 1 + 0 + 8 = 9.

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

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

p, d = 1, 10 ** 9 + 7

s, f = 0, [1] * n

for i in range(2, n): f[i] = (i * f[i - 1]) % d

c = lambda a, b: 0 if a > b else (f[b] * pow(f[a] * f[b - a], d - 2, d)) % d

if k:

    u = [0] * (n + 1)

    p = [1] * (n + 1)

    for i in range(n):

        u[i] = (p[i] * c(k - 1, n - 2 - i) + u[i - 1]) % d

        p[i + 1] = (10 * p[i]) % d

    for i in range(n):

        v = u[n - 2 - i] + p[n - 1 - i] * c(k, i)

        s = (s + t[i] * v) % d

else:

    for i in t: s = (s * 10 + i) % d

print(s)

# Made By Mostafa_Khaled
```


618_B. Guess the Permutation

Bob has a permutation of integers from 1 to n. Denote this permutation as p. The i-th element of p will be denoted as pi. For all pairs of distinct integers i, j between 1 and n, he wrote the number ai, j = min(pi, pj). He writes ai, i = 0 for all integer i from 1 to n.

Bob gave you all the values of ai, j that he wrote down. Your job is to reconstruct any permutation that could have generated these values. The input will be formed so that it is guaranteed that there is at least one solution that is consistent with the information given.

Input

The first line of the input will contain a single integer n (2 ≤ n ≤ 50).

The next n lines will contain the values of ai, j. The j-th number on the i-th line will represent ai, j. The i-th number on the i-th line will be 0. It's guaranteed that ai, j = aj, i and there is at least one solution consistent with the information given.

Output

Print n space separated integers, which represents a permutation that could have generated these values. If there are multiple possible solutions, print any of them.

Examples

Input

2
0 1
1 0

Output

2 1

Input

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

Output

2 5 4 1 3

Note

In the first case, the answer can be {1, 2} or {2, 1}.

In the second case, another possible answer is {2, 4, 5, 1, 3}.

```python
# from pprint import pprint

n = int(input())
a = []
for i in range(n):
    row = [int(k) for k in input().split()]
    a.append(row)

result = [0] * n
for k in range(1, n):
    # print('k=', k)
    for i in range(n):
        countK = 0
        countNonK = 0
        for j in range(n):
            if a[i][j] == k:
                countK += 1
            elif a[i][j] != 0:
                countNonK += 1
        # print('@', countK, countNonK)
        if countK > 0 and countNonK == 0:
            # print('j', j)
            result[i] = k
            for j in range(n):
                a[i][j] = 0
                a[j][i] = 0
            continue

        countK = 0
        countNonK = 0
        for j in range(n):
            if a[j][i] == k:
                countK += 1
            elif a[j][i] != 0:
                countNonK += 1
        if countK > 0 and countNonK == 0:
            # print('j#', j)
            result[i] = k
            for j in range(n):
                a[j][i] = 0
                a[i][j] = 0
    # pprint(a)
result[result.index(0)] = n

print(' '.join(str(i) for i in result))

```


638_D. Three-dimensional Turtle Super Computer

A super computer has been built in the Turtle Academy of Sciences. The computer consists of n·m·k CPUs. The architecture was the paralellepiped of size n × m × k, split into 1 × 1 × 1 cells, each cell contains exactly one CPU. Thus, each CPU can be simultaneously identified as a group of three numbers from the layer number from 1 to n, the line number from 1 to m and the column number from 1 to k.

In the process of the Super Computer's work the CPUs can send each other messages by the famous turtle scheme: CPU (x, y, z) can send messages to CPUs (x + 1, y, z), (x, y + 1, z) and (x, y, z + 1) (of course, if they exist), there is no feedback, that is, CPUs (x + 1, y, z), (x, y + 1, z) and (x, y, z + 1) cannot send messages to CPU (x, y, z).

Over time some CPUs broke down and stopped working. Such CPUs cannot send messages, receive messages or serve as intermediates in transmitting messages. We will say that CPU (a, b, c) controls CPU (d, e, f) , if there is a chain of CPUs (xi, yi, zi), such that (x1 = a, y1 = b, z1 = c), (xp = d, yp = e, zp = f) (here and below p is the length of the chain) and the CPU in the chain with number i (i < p) can send messages to CPU i + 1.

Turtles are quite concerned about the denial-proofness of the system of communication between the remaining CPUs. For that they want to know the number of critical CPUs. A CPU (x, y, z) is critical, if turning it off will disrupt some control, that is, if there are two distinctive from (x, y, z) CPUs: (a, b, c) and (d, e, f), such that (a, b, c) controls (d, e, f) before (x, y, z) is turned off and stopped controlling it after the turning off.

Input

The first line contains three integers n, m and k (1 ≤ n, m, k ≤ 100) — the dimensions of the Super Computer.

Then n blocks follow, describing the current state of the processes. The blocks correspond to the layers of the Super Computer in the order from 1 to n. Each block consists of m lines, k characters in each — the description of a layer in the format of an m × k table. Thus, the state of the CPU (x, y, z) is corresponded to the z-th character of the y-th line of the block number x. Character "1" corresponds to a working CPU and character "0" corresponds to a malfunctioning one. The blocks are separated by exactly one empty line.

Output

Print a single integer — the number of critical CPUs, that is, such that turning only this CPU off will disrupt some control.

Examples

Input

2 2 3
000
000

111
111

Output

2

Input

3 3 3
111
111
111

111
111
111

111
111
111

Output

19

Input

1 1 10
0101010101

Output

0

Note

In the first sample the whole first layer of CPUs is malfunctional. In the second layer when CPU (2, 1, 2) turns off, it disrupts the control by CPU (2, 1, 3) over CPU (2, 1, 1), and when CPU (2, 2, 2) is turned off, it disrupts the control over CPU (2, 2, 3) by CPU (2, 2, 1).

In the second sample all processors except for the corner ones are critical.

In the third sample there is not a single processor controlling another processor, so the answer is 0.

```python
def main():
    s = input().split()
    n, m, k = int(s[0]), int(s[1]), int(s[2])
    processor = []
    for x in range(n):
        for y in range(m):
            s = input()
            for z in s:
                processor.append(int(z) == 1)
        if x < n - 1:
            emptyLine = input()
    counter = 0
    mk = m * k
    nmk = n * mk
    for i in range(nmk):
        if not processor[i]:
            continue
        # back
        if i >= mk:
            if processor[i - mk]:
                # front
                if i < (nmk - mk):
                    if processor[i + mk]:
                        counter += 1
                        continue
                # right
                if (i % k) < (k - 1):
                    if processor[i + 1]:
                        if not processor[i - mk + 1]:
                            counter += 1
                            continue
                # down
                if (i % mk) < (mk - k):
                    if processor[i + k]:
                        if not processor[i - mk + k]:
                            counter += 1
                            continue
        # left
        if (i % k) > 0:
            if processor[i - 1]:
                # front
                if i < (nmk - mk):
                    if processor[i + mk]:
                        if not processor[i + mk - 1]:
                            counter += 1
                            continue
                # right
                if (i % k) < (k - 1):
                    if processor[i + 1]:
                        counter += 1
                        continue
                # down
                if (i % mk) < (mk - k):
                    if processor[i + k]:
                        if not processor[i + k - 1]:
                            counter += 1
                            continue
        # up
        if (i % mk) >= k:
            if processor[i - k]:
                # front
                if i < (nmk - mk):
                    if processor[i + mk]:
                        if not processor[i + mk - k]:
                            counter += 1
                            continue
                # right
                if (i % k) < (k - 1):
                    if processor[i + 1]:
                        if not processor[i - k + 1]:
                            counter += 1
                            continue
                # down
                if (i % mk) < (mk - k):
                    if processor[i + k]:
                        counter += 1
                        continue
    print(counter)

main()

```


690_A1. Collective Mindsets (easy)

Tonight is brain dinner night and all zombies will gather together to scarf down some delicious brains. The artful Heidi plans to crash the party, incognito, disguised as one of them. Her objective is to get away with at least one brain, so she can analyze the zombies' mindset back home and gain a strategic advantage.

They will be N guests tonight: N - 1 real zombies and a fake one, our Heidi. The living-dead love hierarchies as much as they love brains: each one has a unique rank in the range 1 to N - 1, and Heidi, who still appears slightly different from the others, is attributed the highest rank, N. Tonight there will be a chest with brains on display and every attendee sees how many there are. These will then be split among the attendees according to the following procedure:

The zombie of the highest rank makes a suggestion on who gets how many brains (every brain is an indivisible entity). A vote follows. If at least half of the attendees accept the offer, the brains are shared in the suggested way and the feast begins. But if majority is not reached, then the highest-ranked zombie is killed, and the next zombie in hierarchy has to make a suggestion. If he is killed too, then the third highest-ranked makes one, etc. (It's enough to have exactly half of the votes – in case of a tie, the vote of the highest-ranked alive zombie counts twice, and he will of course vote in favor of his own suggestion in order to stay alive.)

You should know that zombies are very greedy and sly, and they know this too – basically all zombie brains are alike. Consequently, a zombie will never accept an offer which is suboptimal for him. That is, if an offer is not strictly better than a potential later offer, he will vote against it. And make no mistake: while zombies may normally seem rather dull, tonight their intellects are perfect. Each zombie's priorities for tonight are, in descending order:

  1. survive the event (they experienced death already once and know it is no fun),
  2. get as many brains as possible.

Heidi goes first and must make an offer which at least half of the attendees will accept, and which allocates at least one brain for Heidi herself.

What is the smallest number of brains that have to be in the chest for this to be possible?

Input

The only line of input contains one integer: N, the number of attendees (1 ≤ N ≤ 109).

Output

Output one integer: the smallest number of brains in the chest which allows Heidi to take one brain home.

Examples

Input

1

Output

1

Input

4

Output

2

Note

```python
n = int(input())
print(n // 2 + n % 2)
```


712_D. Memory and Scores

Memory and his friend Lexa are competing to get higher score in one popular computer game. Memory starts with score a and Lexa starts with score b. In a single turn, both Memory and Lexa get some integer in the range [ - k;k] (i.e. one integer among  - k, - k + 1, - k + 2, ..., - 2, - 1, 0, 1, 2, ..., k - 1, k) and add them to their current scores. The game has exactly t turns. Memory and Lexa, however, are not good at this game, so they both always get a random integer at their turn.

Memory wonders how many possible games exist such that he ends with a strictly higher score than Lexa. Two games are considered to be different if in at least one turn at least one player gets different score. There are (2k + 1)2t games in total. Since the answer can be very large, you should print it modulo 109 + 7. Please solve this problem for Memory.

Input

The first and only line of input contains the four integers a, b, k, and t (1 ≤ a, b ≤ 100, 1 ≤ k ≤ 1000, 1 ≤ t ≤ 100) — the amount Memory and Lexa start with, the number k, and the number of turns respectively.

Output

Print the number of possible games satisfying the conditions modulo 1 000 000 007 (109 + 7) in one line.

Examples

Input

1 2 2 1

Output

6

Input

1 1 1 2

Output

31

Input

2 12 3 1

Output

0

Note

In the first sample test, Memory starts with 1 and Lexa starts with 2. If Lexa picks  - 2, Memory can pick 0, 1, or 2 to win. If Lexa picks  - 1, Memory can pick 1 or 2 to win. If Lexa picks 0, Memory can pick 2 to win. If Lexa picks 1 or 2, Memory cannot win. Thus, there are 3 + 2 + 1 = 6 possible games in which Memory wins.


733_C. Epidemic in Monstropolis

There was an epidemic in Monstropolis and all monsters became sick. To recover, all monsters lined up in queue for an appointment to the only doctor in the city.

Soon, monsters became hungry and began to eat each other.

One monster can eat other monster if its weight is strictly greater than the weight of the monster being eaten, and they stand in the queue next to each other. Monsters eat each other instantly. There are no monsters which are being eaten at the same moment. After the monster A eats the monster B, the weight of the monster A increases by the weight of the eaten monster B. In result of such eating the length of the queue decreases by one, all monsters after the eaten one step forward so that there is no empty places in the queue again. A monster can eat several monsters one after another. Initially there were n monsters in the queue, the i-th of which had weight ai.

For example, if weights are [1, 2, 2, 2, 1, 2] (in order of queue, monsters are numbered from 1 to 6 from left to right) then some of the options are:

  1. the first monster can't eat the second monster because a1 = 1 is not greater than a2 = 2;
  2. the second monster can't eat the third monster because a2 = 2 is not greater than a3 = 2;
  3. the second monster can't eat the fifth monster because they are not neighbors;
  4. the second monster can eat the first monster, the queue will be transformed to [3, 2, 2, 1, 2].

After some time, someone said a good joke and all monsters recovered. At that moment there were k (k ≤ n) monsters in the queue, the j-th of which had weight bj. Both sequences (a and b) contain the weights of the monsters in the order from the first to the last.

You are required to provide one of the possible orders of eating monsters which led to the current queue, or to determine that this could not happen. Assume that the doctor didn't make any appointments while monsters were eating each other.

Input

The first line contains single integer n (1 ≤ n ≤ 500) — the number of monsters in the initial queue.

The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the initial weights of the monsters.

The third line contains single integer k (1 ≤ k ≤ n) — the number of monsters in the queue after the joke.

The fourth line contains k integers b1, b2, ..., bk (1 ≤ bj ≤ 5·108) — the weights of the monsters after the joke.

Monsters are listed in the order from the beginning of the queue to the end.

Output

In case if no actions could lead to the final queue, print "NO" (without quotes) in the only line.

Otherwise print "YES" (without quotes) in the first line. In the next n - k lines print actions in the chronological order. In each line print x — the index number of the monster in the current queue which eats and, separated by space, the symbol 'L' if the monster which stays the x-th in the queue eats the monster in front of him, or 'R' if the monster which stays the x-th in the queue eats the monster behind him. After each eating the queue is enumerated again.

When one monster eats another the queue decreases. If there are several answers, print any of them.

Examples

Input

6
1 2 2 2 1 2
2
5 5

Output

YES
2 L
1 R
4 L
3 L

Input

5
1 2 3 4 5
1
15

Output

YES
5 L
4 L
3 L
2 L

Input

5
1 1 1 3 3
3
2 1 6

Output

NO

Note

In the first example, initially there were n = 6 monsters, their weights are [1, 2, 2, 2, 1, 2] (in order of queue from the first monster to the last monster). The final queue should be [5, 5]. The following sequence of eatings leads to the final queue:

  * the second monster eats the monster to the left (i.e. the first monster), queue becomes [3, 2, 2, 1, 2];
  * the first monster (note, it was the second on the previous step) eats the monster to the right (i.e. the second monster), queue becomes [5, 2, 1, 2];
  * the fourth monster eats the mosnter to the left (i.e. the third monster), queue becomes [5, 2, 3];
  * the finally, the third monster eats the monster to the left (i.e. the second monster), queue becomes [5, 5].

Note that for each step the output contains numbers of the monsters in their current order in the queue.

```python
def main():
    n = int(input())
    a = list(map(int, input().split()))
    m = int(input())
    b = list(map(int, input().split()))

    sum1, sum2 = 0, 0
    for i in a:
        sum1 += i
    for i in b:
        sum2 += i
    # validar que podemos obtener solucion
    if sum1 != sum2:
        print('NO')
        return
    # guardar instrucciones
    instructions = []
    index = 0
    for i in range(m):
        # valor a conseguir
        t = b[i]
        p1 = index
        p2 = index

        while t > 0:
            t -= a[index]
            if a[p2] < a[index]:
                p2 = index
            index += 1

        if t < 0:
            print('NO')
            return

        if p2 == p1:
            while p2 + 1 < index and a[p2] == a[p2 + 1]:
                p2 = p2 + 1

        flag = 0
        if p2 - 1 >= p1 and a[p2] > a[p2 - 1]:
            flag = 1
        elif p2 + 1 < index and a[p2] > a[p2 + 1]:
            flag = 2
        elif index - p1 == 1:
            continue

        if flag == 0:
            print('NO')
            return
        elif flag == 1:
            for x in range(p2, p1, -1):
                instructions.append('{0} L'.format(x - p1 + i + 1))
            for x in range(p2, index - 1):
                instructions.append('{0} R'.format(i + 1))
        elif flag == 2:
            for x in range(p2, index - 1):
                instructions.append('{0} R'.format(p2 - p1 + i + 1))
            for x in range(p2, p1, -1):
                instructions.append('{0} L'.format(x - p1 + i + 1))

    print('YES')
    for x in instructions:
        print(x)

main()
```


779_A. Pupils Redistribution

In Berland each high school student is characterized by academic performance — integer value between 1 and 5.

In high school 0xFF there are two groups of pupils: the group A and the group B. Each group consists of exactly n students. An academic performance of each student is known — integer value between 1 and 5.

The school director wants to redistribute students between groups so that each of the two groups has the same number of students whose academic performance is equal to 1, the same number of students whose academic performance is 2 and so on. In other words, the purpose of the school director is to change the composition of groups, so that for each value of academic performance the numbers of students in both groups are equal.

To achieve this, there is a plan to produce a series of exchanges of students between groups. During the single exchange the director selects one student from the class A and one student of class B. After that, they both change their groups.

Print the least number of exchanges, in order to achieve the desired equal numbers of students for each academic performance.

Input

The first line of the input contains integer number n (1 ≤ n ≤ 100) — number of students in both groups.

The second line contains sequence of integer numbers a1, a2, ..., an (1 ≤ ai ≤ 5), where ai is academic performance of the i-th student of the group A.

The third line contains sequence of integer numbers b1, b2, ..., bn (1 ≤ bi ≤ 5), where bi is academic performance of the i-th student of the group B.

Output

Print the required minimum number of exchanges or -1, if the desired distribution of students can not be obtained.

Examples

Input

4
5 4 4 4
5 5 4 5

Output

1

Input

6
1 1 1 1 1 1
5 5 5 5 5 5

Output

3

Input

1
5
3

Output

-1

Input

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

Output

4

```python
n = int(input())
linea = list(map(int, input().split()))
lineb = list(map(int, input().split()))
lines = linea + lineb
c1 = lines.count(1)
c2 = lines.count(2)
c3 = lines.count(3)
c4 = lines.count(4)
c5 = lines.count(5)
cc1 = linea.count(1)
cc2 = linea.count(2)
cc3 = linea.count(3)
cc4 = linea.count(4)
cc5 = linea.count(5)
if (c1 % 2 == 1 or c2 % 2 == 1 or c3 % 2 == 1 or c4 % 2 == 1 or c5 % 2 == 1):
    print(-1)
else:
    print(int(abs(c1 / 2 - cc1) + abs(c2 / 2 - cc2) + abs(c3 / 2 - cc3) + abs(c4 / 2 - cc4) + abs(c5 / 2 - cc5)) // 2)
```


825_E. Minimal Labels

You are given a directed acyclic graph with n vertices and m edges. There are no self-loops or multiple edges between any pair of vertices. Graph can be disconnected.

You should assign labels to all vertices in such a way that:

  * Labels form a valid permutation of length n — an integer sequence such that each integer from 1 to n appears exactly once in it.
  * If there exists an edge from vertex v to vertex u then labelv should be smaller than labelu.
  * Permutation should be lexicographically smallest among all suitable.

Find such sequence of labels to satisfy all the conditions.

Input

The first line contains two integer numbers n, m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105).

Next m lines contain two integer numbers v and u (1 ≤ v, u ≤ n, v ≠ u) — edges of the graph. Edges are directed, graph doesn't contain loops or multiple edges.

Output

Print n numbers — lexicographically smallest correct permutation of labels of vertices.

Examples

Input

3 3
1 2
1 3
3 2

Output

1 3 2

Input

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

Output

4 1 2 3

Input

5 4
3 1
2 1
2 3
4 5

Output

3 1 2 4 5

```python
#!/usr/local/bin/python3

from collections import defaultdict
import heapq

num_nodes, num_edges = map(int, input().split())

ins = defaultdict(set)
out = defaultdict(int)

for _ in range(num_edges):
    node_out, node_in = map(int, input().split())
    ins[node_in].add(node_out)
    out[node_out] += 1

zeros = [-node for node in range(num_nodes, 0, -1) if out[node] == 0]

final_mappings = {}
current_index = num_nodes

while current_index > 0:

    node = -heapq.heappop(zeros)
    final_mappings[node] = current_index
    current_index -= 1

    for node_out in ins[node]:
        out[node_out] -= 1
        if out[node_out] == 0:
            heapq.heappush(zeros, -node_out)

print(' '.join(str(final_mappings[node]) for node in range(1, num_nodes + 1)))

```