762_D. Maximum path

You are given a rectangular table 3 × n. Each cell contains an integer. You can move from one cell to another if they share a side.

Find such path from the upper left cell to the bottom right cell of the table that doesn't visit any of the cells twice, and the sum of numbers written in the cells of this path is maximum possible.

Input

The first line contains an integer n (1 ≤ n ≤ 105) — the number of columns in the table.

Next three lines contain n integers each — the description of the table. The j-th number in the i-th line corresponds to the cell aij ( - 109 ≤ aij ≤ 109) of the table.

Output

Output the maximum sum of numbers on a path from the upper left cell to the bottom right cell of the table, that doesn't visit any of the cells twice.

Examples

Input

3
1 1 1
1 -1 1
1 1 1

Output

7

Input

5
10 10 10 -1 -1
-1 10 10 10 10
-1 10 10 10 10

Output

110

Note

The path for the first example:

<image>

The path for the second example:

<image>


807_E. Prairie Partition

It can be shown that any positive integer x can be uniquely represented as x = 1 + 2 + 4 + ... + 2k - 1 + r, where k and r are integers, k ≥ 0, 0 < r ≤ 2k. Let's call that representation prairie partition of x.

For example, the prairie partitions of 12, 17, 7 and 1 are:

12 = 1 + 2 + 4 + 5,

17 = 1 + 2 + 4 + 8 + 2,

7 = 1 + 2 + 4,

1 = 1.

Alice took a sequence of positive integers (possibly with repeating elements), replaced every element with the sequence of summands in its prairie partition, arranged the resulting numbers in non-decreasing order and gave them to Borys. Now Borys wonders how many elements Alice's original sequence could contain. Find all possible options!

Input

The first line contains a single integer n (1 ≤ n ≤ 105) — the number of numbers given from Alice to Borys.

The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1012; a1 ≤ a2 ≤ ... ≤ an) — the numbers given from Alice to Borys.

Output

Output, in increasing order, all possible values of m such that there exists a sequence of positive integers of length m such that if you replace every element with the summands in its prairie partition and arrange the resulting numbers in non-decreasing order, you will get the sequence given in the input.

If there are no such values of m, output a single integer -1.

Examples

Input

8
1 1 2 2 3 4 5 8

Output

2

Input

6
1 1 1 2 2 2

Output

2 3

Input

5
1 2 4 4 4

Output

-1

Note

In the first example, Alice could get the input sequence from [6, 20] as the original sequence.

In the second example, Alice's original sequence could be either [4, 5] or [3, 3, 3].

```python
from collections import Counter
from math import log2

powers = [2 ** p for p in range(64)]

def can():
    near = Counter()
    for num in set(nums):
        p = int(log2(num))
        near[p] += nums[num]
    seq_cp = seqs - Counter()
    for num in set(near):
        cnt = near[num]
        while cnt != 0 and num < 64:
            dif = min(cnt, seq_cp[powers[num]])
            cnt -= dif
            seq_cp[powers[num]] -= dif
            num += 1
        if cnt > 0:
            return False
    return True

n = int(input())

seq = list(map(int, input().split()))
cnt = Counter(seq)
nums = Counter(seq)

seqs = Counter()
cur_cnt = cnt[1]
cur_pow = 1
while cur_cnt != 0:
    nums[cur_pow] -= cur_cnt
    cur_pow *= 2
    if cur_cnt > cnt[cur_pow]:
        seqs[cur_pow // 2] = cur_cnt - cnt[cur_pow]
        cur_cnt = cnt[cur_pow]

for num in set(nums):
    addition = nums[num]
    nums[num] = 0
    nums[2 ** int(log2(num))] += addition

# remove elements with zero count
nums -= Counter()
seqs -= Counter()

cur_len = sum(seqs[num] for num in set(seqs))
res = []
cur_pow = 1

while can():
    res.append(cur_len)
    while seqs[cur_pow] == 0 and cur_pow <= 2 ** 63:
        cur_pow *= 2
    if cur_pow > 2 ** 63:
        break
    other_pow = 1
    while other_pow <= cur_pow:
        nums[other_pow] += 1
        other_pow *= 2
    seqs[cur_pow] -= 1
    cur_len -= 1

print(-1 if len(res) == 0 else ' '.join(map(str, reversed(res))))

```


852_G. Bathroom terminal

Smith wakes up at the side of a dirty, disused bathroom, his ankle chained to pipes. Next to him is tape-player with a hand-written message "Play Me". He finds a tape in his own back pocket. After putting the tape in the tape-player, he sees a key hanging from a ceiling, chained to some kind of a machine, which is connected to the terminal next to him. After pressing a Play button a rough voice starts playing from the tape:

"Listen up Smith. As you can see, you are in pretty tough situation and in order to escape, you have to solve a puzzle.

You are given N strings which represent words. Each word is of the maximum length L and consists of characters 'a'-'e'. You are also given M strings which represent patterns. Pattern is a string of length  ≤ L and consists of characters 'a'-'e' as well as the maximum 3 characters '?'. Character '?' is an unknown character, meaning it can be equal to any character 'a'-'e', or even an empty character. For each pattern find the number of words that matches with the given pattern. After solving it and typing the result in the terminal, the key will drop from the ceiling and you may escape. Let the game begin."

Help Smith escape.

Input

The first line of input contains two integers N and M (1 ≤ N ≤ 100 000, 1 ≤ M ≤ 5000), representing the number of words and patterns respectively.

The next N lines represent each word, and after those N lines, following M lines represent each pattern. Each word and each pattern has a maximum length L (1 ≤ L ≤ 50). Each pattern has no more that three characters '?'. All other characters in words and patters are lowercase English letters from 'a' to 'e'.

Output

Output contains M lines and each line consists of one integer, representing the number of words that match the corresponding pattern.

Example

Input

3 1
abc
aec
ac
a?c

Output

3

Note

If we switch '?' with 'b', 'e' and with empty character, we get 'abc', 'aec' and 'ac' respectively.

```python
import sys
from itertools import product
from collections import defaultdict
r=sys.stdin.readline
N,M=map(int,r().split())
words=defaultdict(int)
tb=['a','b','c','d','e']
st=set()
cnt=0
res=""
def dfs(u):
    global res,cnt
    if u==l:
        if res in st:
            return
        if words[res]>0: cnt+=words[res]
        st.add(res)
        return
    if pattern[u]=='?':
        for i in range(6):
            if i!=5:res+=tb[i]
            dfs(u+1)
            if i!=5:res=res[:-1]
    else:
        res+=pattern[u]
        dfs(u+1)
        res=res[:-1]
for _ in range(N):
    word=r().strip()
    words[word]+=1
for _ in range(M):
    cnt=0
    st.clear()
    pattern=r().strip()
    l=len(pattern)
    res=""
    dfs(0)
    print(cnt)

```


877_B. Nikita and string

One day Nikita found the string containing letters "a" and "b" only.

Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b".

Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get?

Input

The first line contains a non-empty string of length not greater than 5 000 containing only lowercase English letters "a" and "b".

Output

Print a single integer — the maximum possible size of beautiful string Nikita can get.

Examples

Input

abba

Output

4

Input

bab

Output

2

Note

It the first sample the string is already beautiful.

In the second sample he needs to delete one of "b" to make it beautiful.

```python
s=input()
n=len(s)
prefa=[0]*(n)
prefb=[0]*(n)
prefa[0]=(s[0]=='a')
prefb[0]=(s[0]=='b')
c=0
for i in range(1,n):
  prefa[i]=prefa[i-1]+(s[i]=='a')
  prefb[i]=prefb[i-1]+(s[i]=='b')

ans1,ans=0,0
prefa=[0]+prefa
prefb=[0]+prefb
for i in range(n+1):
  for j in range(i,n+1):
    ans1=(prefa[n]-prefa[j])+(prefb[j]-prefb[i])+(prefa[i])
    if ans1>ans:ans=ans1
print(ans)

```


900_C. Remove Extra One

You are given a permutation p of length n. Remove one element from permutation to make the number of records the maximum possible.

We remind that in a sequence of numbers a1, a2, ..., ak the element ai is a record if for every integer j (1 ≤ j < i) the following holds: aj < ai.

Input

The first line contains the only integer n (1 ≤ n ≤ 105) — the length of the permutation.

The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ n) — the permutation. All the integers are distinct.

Output

Print the only integer — the element that should be removed to make the number of records the maximum possible. If there are multiple such elements, print the smallest one.

Examples

Input

1
1

Output

1

Input

5
5 1 2 3 4

Output

5

Note

In the first example the only element can be removed.

```python
a=int(input())
b=[]
for i in range(a+1):
    b.append(0)
fir=0
sec=0
for i in (input().split(' ')):
    j=int(i)
    if j>fir:
        sec=fir
        fir=j
        b[j]=1
    elif j>sec:
        sec=j
        b[fir]-=1
ans=1
for i in range(1,a+1):
    if b[i]<b[ans]:
        ans=i
print(ans)

```


923_A. Primal Sport

Alice and Bob begin their day with a quick game. They first choose a starting number X0 ≥ 3 and try to reach one million by the process described below.

Alice goes first and then they take alternating turns. In the i-th turn, the player whose turn it is selects a prime number smaller than the current number, and announces the smallest multiple of this prime number that is not smaller than the current number.

Formally, he or she selects a prime p < Xi - 1 and then finds the minimum Xi ≥ Xi - 1 such that p divides Xi. Note that if the selected prime p already divides Xi - 1, then the number does not change.

Eve has witnessed the state of the game after two turns. Given X2, help her determine what is the smallest possible starting number X0. Note that the players don't necessarily play optimally. You should consider all possible game evolutions.

Input

The input contains a single integer X2 (4 ≤ X2 ≤ 106). It is guaranteed that the integer X2 is composite, that is, is not prime.

Output

Output a single integer — the minimum possible X0.

Examples

Input

14

Output

6

Input

20

Output

15

Input

8192

Output

8191

Note

In the first test, the smallest possible starting number is X0 = 6. One possible course of the game is as follows:

  * Alice picks prime 5 and announces X1 = 10
  * Bob picks prime 7 and announces X2 = 14.

In the second case, let X0 = 15.

  * Alice picks prime 2 and announces X1 = 16
  * Bob picks prime 5 and announces X2 = 20.

```python
x = int(input())
lp = [0 for x in range(x+1)]
for i in range(2, x+1):
    if(lp[i]==0):
        for j in range(i*2, x+1, i):
            lp[j] = i
    lp[i] = i - lp[i] + 1
p = x
for i in range(lp[x], x+1):
    p = min(p, lp[i])
print(p)

```


950_C. Zebras

Oleg writes down the history of the days he lived. For each day he decides if it was good or bad. Oleg calls a non-empty sequence of days a zebra, if it starts with a bad day, ends with a bad day, and good and bad days are alternating in it. Let us denote bad days as 0 and good days as 1. Then, for example, sequences of days 0, 010, 01010 are zebras, while sequences 1, 0110, 0101 are not.

Oleg tells you the story of days he lived in chronological order in form of string consisting of 0 and 1. Now you are interested if it is possible to divide Oleg's life history into several subsequences, each of which is a zebra, and the way it can be done. Each day must belong to exactly one of the subsequences. For each of the subsequences, days forming it must be ordered chronologically. Note that subsequence does not have to be a group of consecutive days.

Input

In the only line of input data there is a non-empty string s consisting of characters 0 and 1, which describes the history of Oleg's life. Its length (denoted as |s|) does not exceed 200 000 characters.

Output

If there is a way to divide history into zebra subsequences, in the first line of output you should print an integer k (1 ≤ k ≤ |s|), the resulting number of subsequences. In the i-th of following k lines first print the integer li (1 ≤ li ≤ |s|), which is the length of the i-th subsequence, and then li indices of days forming the subsequence. Indices must follow in ascending order. Days are numbered starting from 1. Each index from 1 to n must belong to exactly one subsequence. If there is no way to divide day history into zebra subsequences, print -1.

Subsequences may be printed in any order. If there are several solutions, you may print any of them. You do not have to minimize nor maximize the value of k.

Examples

Input

0010100

Output

3
3 1 3 4
3 2 5 6
1 7

Input

111

Output

-1

```python
s = input()
arr, zero, one = [], [], []
for i in range(len(s)):
    if s[i] == '0':
        if one:
            idx = one.pop()
            arr[idx].append(i + 1)
            zero.append(idx)
        else:
            zero.append(len(arr))
            arr.append([i + 1])
    else:
        if not zero:break
        idx = zero.pop()
        one.append(idx)
        arr[idx].append(i + 1)
if arr and zero and not one:
    print(len(arr))
    for x in zero:
        print(len(arr[x]), end=' ')
        print(*arr[x])
else:print(-1)
```


978_F. Mentors

In BerSoft n programmers work, the programmer i is characterized by a skill r_i.

A programmer a can be a mentor of a programmer b if and only if the skill of the programmer a is strictly greater than the skill of the programmer b (r_a > r_b) and programmers a and b are not in a quarrel.

You are given the skills of each programmers and a list of k pairs of the programmers, which are in a quarrel (pairs are unordered). For each programmer i, find the number of programmers, for which the programmer i can be a mentor.

Input

The first line contains two integers n and k (2 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ k ≤ min(2 ⋅ 10^5, (n ⋅ (n - 1))/(2))) — total number of programmers and number of pairs of programmers which are in a quarrel.

The second line contains a sequence of integers r_1, r_2, ..., r_n (1 ≤ r_i ≤ 10^{9}), where r_i equals to the skill of the i-th programmer.

Each of the following k lines contains two distinct integers x, y (1 ≤ x, y ≤ n, x ≠ y) — pair of programmers in a quarrel. The pairs are unordered, it means that if x is in a quarrel with y then y is in a quarrel with x. Guaranteed, that for each pair (x, y) there are no other pairs (x, y) and (y, x) in the input.

Output

Print n integers, the i-th number should be equal to the number of programmers, for which the i-th programmer can be a mentor. Programmers are numbered in the same order that their skills are given in the input.

Examples

Input

4 2
10 4 10 15
1 2
4 3

Output

0 0 1 2

Input

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

Output

5 4 0 5 3 3 9 0 2 5

Note

In the first example, the first programmer can not be mentor of any other (because only the second programmer has a skill, lower than first programmer skill, but they are in a quarrel). The second programmer can not be mentor of any other programmer, because his skill is minimal among others. The third programmer can be a mentor of the second programmer. The fourth programmer can be a mentor of the first and of the second programmers. He can not be a mentor of the third programmer, because they are in a quarrel.

```python
from bisect import *
n, k = map(int, input().split())
r = list(map(int, input().split()))
s = sorted(r)
l = [0] * n
for i in range(n):
  l[i] = bisect_left(s, r[i])
for i in range(k):
    x, y = map(int, input().split())
    x -= 1
    y -= 1
    if r[x] < r[y]:
        l[y] -= 1
    elif r[x] > r[y]:
        l[x] -= 1
print(*l)

```


p02662 AtCoder Beginner Contest 169 - Knapsack for All Subsets

Given are a sequence of N positive integers A_1, A_2, \ldots, A_N and another positive integer S.
For a non-empty subset T of the set \\{1, 2, \ldots , N \\}, let us define f(T) as follows:

* f(T) is the number of different non-empty subsets \\{x_1, x_2, \ldots , x_k \\} of T such that A_{x_1}+A_{x_2}+\cdots +A_{x_k} = S.

Find the sum of f(T) over all 2^N-1 subsets T of \\{1, 2, \ldots , N \\}. Since the sum can be enormous, print it modulo 998244353.

Constraints

* All values in input are integers.
* 1 \leq N \leq 3000
* 1 \leq S \leq 3000
* 1 \leq A_i \leq 3000

Input

Input is given from Standard Input in the following format:

N S
A_1 A_2 ... A_N

Output

Print the sum of f(T) modulo 998244353.

Examples

Input

3 4
2 2 4

Output

6

Input

5 8
9 9 9 9 9

Output

0

Input

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

Output

3296

```python
N, S = map(int, input().split())
A = list(map(int, input().split()))
mod = 998244353
L = [[0 for i in range(S+1)] for j in range(N+1)]
L[0][0] = 1
for j, a in enumerate(A):
  for i in range(S+1):
    if i < a:
      L[j+1][i] = (2 * L[j][i]) % mod
    else:
      L[j+1][i] = (2 * L[j][i] + L[j][i-a]) % mod
print(L[N][S])
```


p02791 AtCoder Beginner Contest 152 - Low Elements

Given is a permutation P_1, \ldots, P_N of 1, \ldots, N. Find the number of integers i (1 \leq i \leq N) that satisfy the following condition:

* For any integer j (1 \leq j \leq i), P_i \leq P_j.

Constraints

* 1 \leq N \leq 2 \times 10^5
* P_1, \ldots, P_N is a permutation of 1, \ldots, N.
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
P_1 ... P_N

Output

Print the number of integers i that satisfy the condition.

Examples

Input

5
4 2 5 1 3

Output

3

Input

4
4 3 2 1

Output

4

Input

6
1 2 3 4 5 6

Output

1

Input

8
5 7 4 2 6 8 1 3

Output

4

Input

1
1

Output

1

```python
N=int(input())
ans=0
champ=10**6
for p in list(map(int,input().split())):
    if p<champ:
        ans+=1
        champ=p

print(ans)
```


p02927 Japanese Student Championship 2019 Qualification - Takahashi Calendar

Today is August 24, one of the five Product Days in a year.

A date m-d (m is the month, d is the date) is called a Product Day when d is a two-digit number, and all of the following conditions are satisfied (here d_{10} is the tens digit of the day and d_1 is the ones digit of the day):

* d_1 \geq 2
* d_{10} \geq 2
* d_1 \times d_{10} = m

Takahashi wants more Product Days, and he made a new calendar called Takahashi Calendar where a year consists of M month from Month 1 to Month M, and each month consists of D days from Day 1 to Day D.

In Takahashi Calendar, how many Product Days does a year have?

Constraints

* All values in input are integers.
* 1 \leq M \leq 100
* 1 \leq D \leq 99

Input

Input is given from Standard Input in the following format:

M D

Output

Print the number of Product Days in a year in Takahashi Calender.

Examples

Input

15 40

Output

10

Input

12 31

Output

5

Input

1 1

Output

0

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

ans = 0
for i in range(22, d+1):
    d10 = i // 10
    d1 = i - d10 * 10
    if d10 > 1 and d1 > 1 and d10 * d1 <= m:
        ans += 1
print(ans)

```


p03062 AtCoder Beginner Contest 125 - Flipping Signs

There are N integers, A_1, A_2, ..., A_N, arranged in a row in this order.

You can perform the following operation on this integer sequence any number of times:

Operation: Choose an integer i satisfying 1 \leq i \leq N-1. Multiply both A_i and A_{i+1} by -1.

Let B_1, B_2, ..., B_N be the integer sequence after your operations.

Find the maximum possible value of B_1 + B_2 + ... + B_N.

Constraints

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

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible value of B_1 + B_2 + ... + B_N.

Examples

Input

3
-10 5 -4

Output

19

Input

5
10 -4 -8 -11 3

Output

30

Input

11
-1000000000 1000000000 -1000000000 1000000000 -1000000000 0 1000000000 -1000000000 1000000000 -1000000000 1000000000

Output

10000000000

```python
N = int(input())
A = list(map(int, input().split()))
B = sorted(map(abs, A))
if sum(x < 0 for x in A) % 2 == 0:
    print(sum(B))
else:
    print(sum(B[1:])-B[0])
```


p03206 AtCoder Beginner Contest 115 - Christmas Eve Eve Eve

In some other world, today is December D-th.

Write a program that prints `Christmas` if D = 25, `Christmas Eve` if D = 24, `Christmas Eve Eve` if D = 23 and `Christmas Eve Eve Eve` if D = 22.

Constraints

* 22 \leq D \leq 25
* D is an integer.

Input

Input is given from Standard Input in the following format:

D

Output

Print the specified string (case-sensitive).

Examples

Input

25

Output

Christmas

Input

22

Output

Christmas Eve Eve Eve

```python
D = int(input())
a = "Christmas"
print(a + " Eve"*(25-D))
```


p03353 AtCoder Beginner Contest 097 - K-th Substring

You are given a string s. Among the different substrings of s, print the K-th lexicographically smallest one.

A substring of s is a string obtained by taking out a non-empty contiguous part in s. For example, if s = `ababc`, `a`, `bab` and `ababc` are substrings of s, while `ac`, `z` and an empty string are not. Also, we say that substrings are different when they are different as strings.

Let X = x_{1}x_{2}...x_{n} and Y = y_{1}y_{2}...y_{m} be two distinct strings. X is lexicographically larger than Y if and only if Y is a prefix of X or x_{j} > y_{j} where j is the smallest integer such that x_{j} \neq y_{j}.

Constraints

* 1 ≤ |s| ≤ 5000
* s consists of lowercase English letters.
* 1 ≤ K ≤ 5
* s has at least K different substrings.

Input

Input is given from Standard Input in the following format:

s
K

Output

Print the K-th lexicographically smallest substring of K.

Examples

Input

aba
4

Output

b

Input

atcoderandatcodeer
5

Output

andat

Input

z
1

Output

z

```python
s = input()
K = int(input())
d = set()

for l in range(1, K+1):
    for i in range(len(s)+1-l):
        d |= {s[i:i+l]}

print(sorted(list(d))[K-1])
```


p03675 AtCoder Regular Contest 077 - pushpush

You are given an integer sequence of length n, a_1, ..., a_n. Let us consider performing the following n operations on an empty sequence b.

The i-th operation is as follows:

1. Append a_i to the end of b.
2. Reverse the order of the elements in b.

Find the sequence b obtained after these n operations.

Constraints

* 1 \leq n \leq 2\times 10^5
* 0 \leq a_i \leq 10^9
* n and a_i are integers.

Input

Input is given from Standard Input in the following format:

n
a_1 a_2 ... a_n

Output

Print n integers in a line with spaces in between. The i-th integer should be b_i.

Examples

Input

4
1 2 3 4

Output

4 2 1 3

Input

3
1 2 3

Output

3 1 2

Input

1
1000000000

Output

1000000000

Input

6
0 6 7 6 7 0

Output

0 6 6 0 7 7

```python
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

from collections import deque

N,*A = map(int,read().split())

B = deque()
reverse = False
for x in A:
    if reverse:
        B.appendleft(x)
    else:
        B.append(x)
    reverse = not reverse

B = list(B)
if reverse:
    B = B[::-1]

print(' '.join(map(str,B)))
```


p03829 AtCoder Beginner Contest 052 - Walk and Teleport

There are N towns on a line running east-west. The towns are numbered 1 through N, in order from west to east. Each point on the line has a one-dimensional coordinate, and a point that is farther east has a greater coordinate value. The coordinate of town i is X_i.

You are now at town 1, and you want to visit all the other towns. You have two ways to travel:

* Walk on the line. Your fatigue level increases by A each time you travel a distance of 1, regardless of direction.

* Teleport to any location of your choice. Your fatigue level increases by B, regardless of the distance covered.

Find the minimum possible total increase of your fatigue level when you visit all the towns in these two ways.

Constraints

* All input values are integers.
* 2≤N≤10^5
* 1≤X_i≤10^9
* For all i(1≤i≤N-1), X_i<X_{i+1}.
* 1≤A≤10^9
* 1≤B≤10^9

Input

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

N A B
X_1 X_2 ... X_N

Output

Print the minimum possible total increase of your fatigue level when you visit all the towns.

Examples

Input

4 2 5
1 2 5 7

Output

11

Input

7 1 100
40 43 45 105 108 115 124

Output

84

Input

7 1 2
24 35 40 68 72 99 103

Output

12

```python
N,A,B = map(int,input().split())
X = [int(x) for x in input().split()]

ans = 0
for i in range(1,N):
	d = X[i]-X[i-1]
	ans += min(A*d, B)
print(ans)
```


p03996 CODE FESTIVAL 2016 qual A - LRU Puzzle

There are N arrays. The length of each array is M and initially each array contains integers (1，2，...，M) in this order.

Mr. Takahashi has decided to perform Q operations on those N arrays. For the i-th (1≤i≤Q) time, he performs the following operation.

* Choose an arbitrary array from the N arrays and move the integer a_i (1≤a_i≤M) to the front of that array. For example, after performing the operation on a_i=2 and the array (5，4，3，2，1), this array becomes (2，5，4，3，1).

Mr. Takahashi wants to make N arrays exactly the same after performing the Q operations. Determine if it is possible or not.

Constraints

* 2≤N≤10^5
* 2≤M≤10^5
* 1≤Q≤10^5
* 1≤a_i≤M

Input

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

N M
Q
a_1 a_2 ... a_Q

Output

Print `Yes` if it is possible to make N arrays exactly the same after performing the Q operations. Otherwise, print `No`.

Examples

Input

2 2
3
2 1 2

Output

Yes

Input

3 2
3
2 1 2

Output

No

Input

2 3
3
3 2 1

Output

Yes

Input

3 3
6
1 2 2 3 3 3

Output

No

```python
def reads(offset = 0):
	return [int(i) - offset for i in input().split(' ')]
def Judge(vector):
	length = len(vector)-1
	for i in range(length):
		if(vector[i] > vector[i+1]):
			return 0
	return 1
(N, M) = reads()
Q = int(input())
A = reads(1)
pos = [-1] * M
pat = []
freq = [0] * (M+1)
freq[0] = N
found = set()
counter = 0
for i in A[::-1]:
	if (i not in found):
		pat.append(i)
		found.add(i)
		pos[i] = counter
		counter += 1
		if(counter == M):
			break
for i in range(M):
	if (pos[i] == -1):
		pat.append(i)
for i in A[::-1]:
	temp = pos[i]
	if (freq[temp] > 0):
		freq[temp] -= 1
		freq[temp+1] += 1
start = M
for i in range(M):
	if (freq[i] != 0):
		start = i
		break
print("Yes") if Judge(pat[start:]) else print("No")
```


p00084 Search Engine

Internet search engines, such as Google, automatically sort and categorize web pages around the world to create a huge database. It also parses the search keywords entered by the user and creates an inquiry statement for database search.

In each case, complicated processing is performed to realize efficient search, but for the time being, all the basics are cutting out words from sentences.

So, please try to cut out the word from the sentence. This time, we will target English sentences with clear word breaks as follows.

* Target text: English text of 1024 characters or less, not including line breaks
* Delimiter: All are half-width characters, only spaces, periods, and commas.
* Words to cut out: Words with 3 to 6 letters (ignore words with 2 or less letters or 7 or more letters)

input

An English sentence consisting of delimiters and alphanumeric characters is given on one line (all half-width characters).

output

Please output the words separated by one space character (half-width) on one line.

Examples

Input

Rain, rain, go to Spain.

Output

Rain rain Spain

Input

Win today's preliminary contest and be qualified to visit University of Aizu.

Output

Win and visit Aizu

```python
print(' '.join([x for x in input().replace('.',' ').replace(',',' ').split() if 3 <= len(x) <= 6]))

```


p00216 Cutting Down Water Bills

Mr. Matsudaira is always careful about eco-friendliness in his life. Last month's water charge was 4280 yen, which exceeded the usual target of 4000 yen, so we have been trying to save water this month. How much have you saved on your water bill compared to last month?

Enter this month's water usage w [m3] and create a program that outputs how much water charges you have saved compared to last month's water charges of 4280 yen.

The water charge is calculated as follows.

(Water charge) = (Basic charge) + (Charge based on water volume)

The charge based on the amount of water is calculated according to the amount used as shown in the table below.

Stage | Water volume | Price
--- | --- | ---
1st stage charge | Up to 10 [m3] | Basic charge 1150 yen
Second stage fee | 10 [m3] Excess up to 20 [m3] | 125 yen per [m3]
Third stage charge | 20 [m3] Excess up to 30 [m3] | 140 yen per [m3]
4th stage charge | 30 [m3] excess | 160 yen per [m3]

For example, if the amount of water used is 40 [m3], the basic charge is 1150 yen (1st stage) + 10 [m3] x 125 yen (2nd stage) + 10 [m3] x 140 yen (3rd stage) + 10 [ m3] x 160 yen (4th stage) = 5400 yen.

Input

A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of -1.

For each dataset, an integer w (0 ≤ w ≤ 100) representing the amount of water used this month is given on one line.

The number of datasets does not exceed 200.

Output

For each input dataset, the difference from last month's water charges is output on one line.

Example

Input

29
40
0
-1

Output

620
-1120
3130


p00376 Red Dragonfly

It’s still hot every day, but September has already come. It’s autumn according to the calendar. Looking around, I see two red dragonflies at rest on the wall in front of me. It’s autumn indeed.

When two red dragonflies’ positional information as measured from the end of the wall is given, make a program to calculate the distance between their heads.

Input

The input is given in the following format.

$x_1$ $x_2$

The input line provides dragonflies’ head positions $x_1$ and $x_2$ ($0 \leq x_1, x_2 \leq 100$) as integers.

Output

Output the distance between the two red dragonflies in a line.

Examples

Input

20 30

Output

10

Input

50 25

Output

25

Input

25 25

Output

0

```python
a,b =map(int,(input().split()))

print(abs(a-b))

```


p00594 What Color Is The Universe?

On a clear night, a boy, Campanella looked up at the sky, there were many stars which have different colors such as red, yellow, green, blue, purple, etc. He was watching the stars and just lost track of time. Presently, he wondered,

|  <image>
---|---

"There are many stars in the space. What color is the universe if I look up it from outside?"

Until he found the answer to this question, he couldn't sleep. After a moment's thought, he proposed a hypothesis,

"When I observe the stars in the sky, if more than half of the stars have the same color, that is the color of the universe."

He has collected data of stars in the universe after consistently observing them. However, when he try to count the number of star, he was in bed sick with a cold. You decided to help him by developing a program to identify the color of the universe.

You are given an array A. Let |A| be the number of element in A, and let Nm be the number of m in A. For example, if A = {3, 1, 2, 3, 3, 1, 5, 3}, |A| = 8, N3 = 4, N1 = 2, N5 = 1. Your program have to find m such that:

Nm > (|A| / 2 )

If there is no such m, you also have to report the fact. There is no such m for the above example, but for a array A = {5, 2, 5, 3, 4, 5, 5}, 5 is the answer.

Input

There are several test cases. For each test case, in the first line |A| is given. In the next line, there will be |A| integers. The integers are less than 231 and |A| < 1,000,000. The input terminate with a line which contains single 0.

Output

For each test case, output m in a line. If there is no answer, output "NO COLOR" in a line.

Example

Input

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

Output

NO COLOR
5

```python
while True:
    num=int(input())
    if num==0:
        break
    stars=sorted(input().split())
    if stars.count(stars[num//2]) > num/2 :
        print(stars[num//2])
    else:
        print("NO COLOR")
```


p00730 Cut the Cake

Today is the birthday of Mr. Bon Vivant, who is known as one of the greatest patissiers in the world. Those who are invited to his birthday party are gourmets from around the world. They are eager to see and eat his extremely creative cakes. Now a large box-shaped cake is being carried into the party. It is not beautifully decorated and looks rather simple, but it must be delicious beyond anyone's imagination. Let us cut it into pieces with a knife and serve them to the guests attending the party.

The cake looks rectangular, viewing from above (Figure C-1). As exemplified in Figure C-2, the cake will iteratively be cut into pieces, where on each cut exactly a single piece is cut into two smaller pieces. Each cut surface must be orthogonal to the bottom face and must be orthogonal or parallel to a side face. So, every piece shall be rectangular looking from above and every side face vertical.

<image>

Figure C-1: The top view of the cake
<image>

Figure C-2: Cutting the cake into pieces

Piece sizes in Figure C-2 vary significantly and it may look unfair, but you don't have to worry. Those guests who would like to eat as many sorts of cakes as possible often prefer smaller pieces. Of course, some prefer larger ones.

Your mission of this problem is to write a computer program that simulates the cutting process of the cake and reports the size of each piece.

Input

The input is a sequence of datasets, each of which is of the following format.

> n  w  d
>  p1  s1
>  ...
>  pn  sn
>

The first line starts with an integer n that is between 0 and 100 inclusive. It is the number of cuts to be performed. The following w and d in the same line are integers between 1 and 100 inclusive. They denote the width and depth of the cake, respectively. Assume in the sequel that the cake is placed so that w and d are the lengths in the east-west and north-south directions, respectively.

Each of the following n lines specifies a single cut, cutting one and only one piece into two. pi is an integer between 1 and i inclusive and is the identification number of the piece that is the target of the i-th cut. Note that, just before the i-th cut, there exist exactly i pieces. Each piece in this stage has a unique identification number that is one of 1, 2, ..., i and is defined as follows:

* The earlier a piece was born, the smaller its identification number is.
* Of the two pieces born at a time by the same cut, the piece with the smaller area (looking from above) has the smaller identification number. If their areas are the same, you may define as you like the order between them, since your choice in this case has no influence on the final answer.

Note that identification numbers are adjusted after each cut.

si is an integer between 1 and 1000 inclusive and specifies the starting point of the i-th cut. From the northwest corner of the piece whose identification number is pi, you can reach the starting point by traveling si in the clockwise direction around the piece. You may assume that the starting point determined in this way cannot be any one of the four corners of the piece. The i-th cut surface is orthogonal to the side face on which the starting point exists.

The end of the input is indicated by a line with three zeros.

Output

For each dataset, print in a line the areas looking from above of all the pieces that exist upon completion of the n cuts specified in the dataset. They should be in ascending order and separated by a space. When multiple pieces have the same area, print it as many times as the number of the pieces.

Example

Input

3 5 6
1 18
2 19
1 2
3 4 1
1 1
2 1
3 1
0 2 5
0 0 0

Output

4 4 6 16
1 1 1 1
10

```python
while True:
	dic = {}
	n,w,d = map(int,input().split(" "))
	if n == 0 and w == 0 and d == 0:
		break
	dic[1] = (w,d)
	for i in range(n):
		p,s = map(int,input().split(" "))
		W,H = dic[p]
		for j in range(p,i+1):
			dic[j] = dic[j+1]
		cycle = 2*(H+W)
		s %= cycle
		if s < W or ((H+W) < s and s < (W+H+W)):
			if W < s:
				s -= (H+W)
			dic[i+1] = (min(s,W-s),H)
			dic[i+2] = (max(s,W-s),H)

		elif (W < s and s < (H+W)) or ((W+H+W) < s):
			if s > (H+W):
				s -= (W+H+W)
			else:
				s -= W
			dic[i+1] = (W,min(s,H-s))
			dic[i+2] = (W,max(s,H-s))

	sq = list(dic.values())
	sq.sort(key=lambda x:x[0]*x[1])
	for i in range(len(sq)-1):
		print(sq[i][0]*sq[i][1],end=" ")
	print(sq[len(sq)-1][0]*sq[len(sq)-1][1])

```


p00870 Search of Concatenated Strings

The amount of information on the World Wide Web is growing quite rapidly. In this information explosion age, we must survive by accessing only the Web pages containing information relevant to our own needs. One of the key technologies for this purpose is keyword search. By using well-known search engines, we can easily access those pages containing useful information about the topic we want to know.

There are many variations in keyword search problems. If a single string is searched in a given text, the problem is quite easy. If the pattern to be searched consists of multiple strings, or is given by some powerful notation such as regular expressions, the task requires elaborate algorithms to accomplish efficiently.

In our problem, a number of strings (element strings) are given, but they are not directly searched for. Concatenations of all the element strings in any order are the targets of the search here.

For example, consider three element strings aa, b and ccc are given. In this case, the following six concatenated strings are the targets of the search, i.e. they should be searched in the text.

aabccc
aacccb
baaccc
bcccaa
cccaab
cccbaa

The text may contain several occurrences of these strings. You are requested to count the number of occurrences of these strings, or speaking more precisely, the number of positions of occurrences in the text.

Two or more concatenated strings may be identical. In such cases, it is necessary to consider subtle aspects of the above problem statement. For example, if two element strings are x and xx, the string xxx is an occurrence of both the concatenation of x and xx and that of xx and x. Since the number of positions of occurrences should be counted, this case is counted as one, not two.

Two occurrences may overlap. For example, the string xxxx has occurrences of the concatenation xxx in two different positions. This case is counted as two.

Input

The input consists of a number of datasets, each giving a set of element strings and a text. The format of a dataset is as follows.

n m
e1
e2
.
.
.
en
t1
t2
.
.
.
tm

The first line contains two integers separated by a space. n is the number of element strings. m is the number of lines used to represent the text. n is between 1 and 12, inclusive.

Each of the following n lines gives an element string. The length (number of characters) of an element string is between 1 and 20, inclusive. The last m lines as a whole give the text. Since it is not desirable to have a very long line, the text is separated into m lines by newlines, but these newlines should be ignored. They are not parts of the text. The length of each of these lines (not including the newline) is between 1 and 100, inclusive. The length of the text is between 1 and 5000, inclusive.

The element strings and the text do not contain characters other than lowercase letters.

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

CAUTION! Although the sample input contains only small datasets, note that 12! × 5000 is far larger than 231 .

Output

For each dataset in the input, one line containing the number of matched positions should be output. An output line should not contain extra characters.

Example

Input

3 1
aa
b
ccc
aabccczbaacccbaazaabbcccaa
3 1
a
b
c
cbbcbcbabaacabccaccbaacbccbcaaaccccbcbcbbcacbaacccaccbbcaacbbabbabaccc
3 4
aaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
0 0

Output

5
12
197

```python
from collections import deque
import sys
readline = sys.stdin.readline
write = sys.stdout.write

def solve():
    N, M = map(int, readline().split())
    if N == M == 0:
        return False
    ca = ord('a')
    E = [list(map(lambda x: ord(x)-ca, readline().strip())) for i in range(N)]
    F = "".join(readline().strip() for i in range(M))
    L = sum(map(len, E))
    MOD = 10**9 + 9; base = 37
    ALL = (1 << N) - 1; bALL = (1 << (1 << N)) - 1
    pw = [1]*(L+1)
    for i in range(L):
        pw[i+1] = pw[i] * base % MOD
    V = [0]*N; P = [0]*N; K = [0]*N
    S = [0]*N
    for i in range(N):
        v = 0
        for c in E[i]:
            v = (v * base + c) % MOD
        V[i] = v
        K[i] = len(E[i])
        P[i] = pw[K[i]]
        r = bALL
        for s in range(ALL + 1):
            if s & (1 << i):
                r ^= 1 << s
        S[i] = r

    A = len(F)
    dp = [1] * (A+1)
    H = [0]*(A+1)
    ans = s = 0
    for i in range(A):
        H[i+1] = s = (s * base + (ord(F[i]) - ca)) % MOD
        r = 1
        for j in range(N):
            if K[j] <= i+1 and (s - H[i+1 - K[j]] * P[j]) % MOD == V[j]:
                r |= (dp[i+1 - K[j]] & S[j]) << (1 << j)
        dp[i+1] = r
        if r & (1 << ALL):
            ans += 1
    write("%d\n" % ans)
    return True
while solve():
    ...

```


p01133 Dragon Fantasy

Peace, which was supposed to last forever, suddenly ended. The Demon King, who had been sealed long ago, has finally revived. But when the world was about to be covered in darkness, a brave man appeared. The hero then set out on a journey to collect legendary crystals scattered around the world. Legend has it that if you can collect all the crystals, you can summon the legendary dragon god who can fulfill any wish. With the help of the dragon god, it should be possible to defeat the Demon King.

Crystals are scattered all over the world. The hero needs to collect them one by one by his own hands. This is because if someone other than the hero gets the crystal, it may be stolen by the Demon King's minions. A hero can travel only one Euclidean distance per day.

But there is one serious problem here. The Demon King constantly disperses the darkness of the miasma, and the place contaminated with the miasma turns into a land of death that no one can enter. Even a brave man cannot enter the place. Furthermore, since the miasma spreads concentrically with time, the area where the hero can move decreases with the passage of time. Miasma has been confirmed to spread by an Euclidean distance of 1 per day. And the hero cannot take the crystal on the boundary line. We also know that the newly resurrected Demon King will not move to store power.

The hero must get the crystal as soon as possible. But if it's not possible to get all the crystals, you'll have to think of another way. Therefore, I would like you to create a program to find out if you can get all the crystals from the initial position of the hero, the place where the demon king was resurrected, and the position where the crystals exist.

By the way, the brave does not get tired. And I don't sleep. Keep moving and collect crystals until you collect all the crystals and save the world! !!

Input

The input consists of multiple test cases. The first line of each test case gives the five integers n (0 <n <= 20), hx, hy, dx, and dy. n is the number of crystals, (hx, hy) is the position of the hero at the moment the Demon King was resurrected, and (dx, dy) is the position where the Demon King was resurrected. The n lines that follow are given the two integers cx, cy, that represent the position of each crystal. Input ends when n = hx = hy = dx = dy = 0, which is not included in the test case.

All coordinates given in the input are guaranteed to be integers with an absolute value of 1000 or less.

Output

For each test case, output "YES" if you can collect all the crystals, and "NO" if not.

Example

Input

2 0 0 10 10
1 1
4 4
2 0 0 10 10
1 1
6 6
2 0 0 10 10
1 1
5 5
0 0 0 0 0

Output

YES
NO
NO

```python
def solve():
    from math import sqrt
    from sys import stdin
    f_i = stdin

    def dfs(point, remain, elapsed):
        if not remain:
            return True

        next_c = set()
        for c in remain:
            new_elapsed = elapsed + adj[point][c]
            if new_elapsed >= from_d[c]:
                return False
            next_c.add((c, new_elapsed))

        for c, new_elapsed in next_c:
            remain.remove(c)
            if dfs(c, remain, new_elapsed):
                return True
            remain.add(c)

        return False

    while True:
        n, hx, hy, dx, dy = map(int, f_i.readline().split())
        if n == 0:
            break

        C = [tuple(map(int, f_i.readline().split())) for i in range(n)]
        from_d = tuple(sqrt((cx - dx) ** 2 + (cy - dy) ** 2) for cx, cy in C)
        C.append((hx, hy))
        adj = tuple(tuple(sqrt((px - qx) ** 2 + (py - qy) ** 2) for qx, qy in C) for px, py in C)

        if dfs(n, set(range(n)), 0):
            print("YES")
        else:
            print("NO")

solve()

```


p01442 Mysterious Maze

A robot in a two-dimensional maze again. The maze has an entrance and an exit this time, though.

Just as in the previous problem, the maze is made up of H × W grid cells, its upper side faces north, and each cell is either empty or wall. Unlike the previous, on the other hand, one of the empty cells is connected to the entrance and another to the exit.

The robot is rather complex - there is some control, but not full. It is associated with a controller that has two buttons, namely forward and turn. The forward button moves the robot forward to the next cell, if possible. The robot can not move into a wall nor outside the maze. The turn button turns the robot as programmed. Here the program is a finite sequence of N commands, each of which is either 'L' (indicating a left turn) or 'R' (a right turn). The first turn follows the first command; the second turn follows the second command; similar for the following turns. The turn button stops working once the commands are exhausted; the forward button still works in such a case though. The robot always turns by 90 degrees at once.

The robot is initially put on the entrance cell, directed to the north. Your mission is to determine whether it can reach the exit cell if controlled properly.

Input

The input is a sequence of datasets. Each dataset is formatted as follows.

H W N
s1 ... sN
c1,1c1,2...c1,W
...
cH,1cH,2...cH,W

The first line of a dataset contains three integers H, W and N (1 ≤ H, W ≤ 1,000, 1 ≤ N ≤ 1,000,000).

The second line contains a program of N commands.

Each of the following H lines contains exactly W characters. Each of these characters represents a cell of the maze. "." indicates empty, "#" indicates a wall, "S" indicates an entrance, and "G" indicates an exit. There is exactly one entrance cell and one exit cell.

The end of input is indicated by a line with three zeros.

Output

For each dataset, output whether the robot can reach the exit in a line: "Yes" if it can or "No" otherwise (without quotes).

Examples

Input

2 2 1
L
G.
#S
2 2 2
RR
G.
.S
3 3 6
LLLLLL
G#.
...
.#S
0 0 0

Output

Yes
No
Yes

Input

2 2 1
L
G.
S
2 2 2
RR
G.
.S
3 3 6
LLLLLL
G#.
...
.#S
0 0 0

Output

Yes
No
Yes

```python
from heapq import heappush, heappop
import sys
readline = sys.stdin.readline
write = sys.stdout.write

dd = ((-1, 0), (0, -1), (1, 0), (0, 1))

def solve():
    H, W, N = map(int, readline().split())
    if H == 0:
        return False
    S = readline().strip()
    C = [[0]*W for i in range(H)]
    sx = sy = gx = gy = 0
    for i in range(H):
        s = readline().strip()
        for j, c in enumerate(s):
            if c in '#.':
                C[i][j] = (c == '#')
            elif c == 'S':
                sx = j; sy = i
            else:
                gx = j; gy = i
    S0 = [1]*(N+1)
    cur = 1
    for i in range(N):
        if S[i] == 'L':
            cur = (cur - 1) % 4
        else:
            cur = (cur + 1) % 4
        S0[i+1] = cur
    d = [N+1]*4
    D = [None]*(N+1)
    for i in range(N, -1, -1):
        d[S0[i]] = i
        D[i] = d[:]

    T = [[N+1]*W for i in range(H)]
    T[sy][sx] = 0
    que = [(0, sx, sy)]
    while que:
        cost, x, y = heappop(que)
        if T[y][x] < cost:
            continue
        d = D[cost]
        for k in range(4):
            dx, dy = dd[k]; n_cost = d[k]
            nx = x + dx; ny = y + dy
            if not 0 <= nx < W or not 0 <= ny < H or C[ny][nx]:
                continue
            if n_cost < T[ny][nx]:
                T[ny][nx] = n_cost
                heappush(que, (n_cost, nx, ny))
    print("Yes" if T[gy][gx] < N+1 else "No")
    return True
while solve():
    ...

```


p02025 Angel Relief

K: Relief (Angel Relief)

Tenma, an angel, decides to save a city.

The city has a rectangular shape divided into north-south $ H $ parcels x east-west $ W $ parcels, with houses in each parcel.

The $ X $ th section from the north and the $ Y $ th section from the west are represented by $ (X, Y) $.

The house in parcel $ (i, j) $ is inhabited by $ A_ {i, j} $ people.

Tenshin chooses a rectangular area whose sides are parallel or vertical to north-south or east-west, and rescues all the people living in it one by one.

Tenshin does this for every possible rectangle.

Find the total number of times Tenma-san rescues people.

input

The integers $ H, W $ are given on the first line, separated by blanks.

Of the following $ H $ lines, the integers $ A_ {i, 1}, A_ {i, 2}, A_ {i, 3}, \ dots, A_ {i, W} $ are blank on the $ i $ line. Given as a delimiter.

output

Output the total number of times Tenma-san rescues people.

Constraint

* $ H, W $ are integers between $ 1 $ and $ 500 $
* $ A_ {i, j} $ are all integers greater than or equal to $ 1 $ and less than or equal to $ 9 $.

Input example 1

twenty two
1 2
4 8

Output example 1

60

For example, if you choose a rectangular area with $ (1, 1) $ in the upper left and $ (2, 2) $ in the lower right, you will rescue $ 15 $ people there one by one, so a total of $ 15 $ times. Relief.

$ 1, 2, 3, 4, 5, 8, 10, 12, 15 $ relief for each of the $ 9 $ rectangular areas, for a total of $ 60 $.

Input example 2

twenty three
one two Three
4 5 6

Output example 2

140

Example

Input

2 2
1 2
4 8

Output

60

```python
def f(): return map(int,input().split())
h,w=f();print(sum([sum([(x+1)*(w-x)*v for x,v in enumerate(f())])*(y+1)*(h-y)for y in range(h)]))

```


p02308 Cross Points of a Circle and a Line

For given a circle $c$ and a line $l$, print the coordinates of the cross points of them.

Constraints

* $p1$ and $p2$ are different
* The circle and line have at least one cross point
* $1 \leq q \leq 1,000$
* $-10,000 \leq cx, cy, x1, y1, x2, y2 \leq 10,000$
* $1 \leq r \leq 10,000$

Input

The input is given in the following format.

$cx\; cy\; r$
$q$
$Line_1$
$Line_2$
:
$Line_q$

In the first line, the center coordinate of the circle and its radius are given by $cx$, $cy$ and $r$. In the second line, the number of queries $q$ is given.

In the following $q$ lines, as queries, $Line_i$ are given ($1 \leq i \leq q$) in the following format.

$x_1\; y_1\; x_2\; y_2$

Each line is represented by two points $p1$ and $p2$ which the line crosses. The coordinate of $p1$ and $p2$ are given by ($x1$, $y1$) and ($x2$, $y2$) respectively. All input values are given in integers.

Output

For each query, print the coordinates of the cross points in the following rules.

* If there is one cross point, print two coordinates with the same values.
* Print the coordinate with smaller $x$ first. In case of a tie, print the coordinate with smaller $y$ first.

The output values should be in a decimal fraction with an error less than 0.000001.

Example

Input

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

Output

1.00000000 1.00000000 3.00000000 1.00000000
3.00000000 1.00000000 3.00000000 1.00000000


p02456 Set: Delete

For a set $S$ of integers, perform a sequence of the following operations. Note that each value in $S$ must be unique.

* insert($x$): Insert $x$ to $S$ and report the number of elements in $S$ after the operation.
* find($x$): Report the number of $x$ in $S$ (0 or 1).
* delete($x$): Delete $x$ from $S$.

Constraints

* $1 \leq q \leq 200,000$
* $0 \leq x \leq 1,000,000,000$

Input

The input is given in the following format.

$q$
$query_1$
$query_2$
:
$query_q$

Each query $query_i$ is given by

0 $x$

or

1 $x$

or

2 $x$

where the first digits 0, 1 and 2 represent insert, find and delete operations respectively.

Output

For each insert operation, print the number of elements in $S$.
For each find operation, print the number of specified elements in $S$.

Example

Input

8
0 1
0 2
0 3
2 2
1 1
1 2
1 3
0 2

Output

1
2
3
1
0
1
3

```python
q = int(input())
s = set()
for i in range(q):
    x, y = map(int, input().split())
    if x == 0:
        s.add(y)
        print(len(s))
    elif x == 1:
        print(1) if y in s else print(0)
    else:
        s.discard(y)

```


1011_F. Mars rover

Natasha travels around Mars in the Mars rover. But suddenly it broke down, namely — the logical scheme inside it. The scheme is an undirected tree (connected acyclic graph) with a root in the vertex 1, in which every leaf (excluding root) is an input, and all other vertices are logical elements, including the root, which is output. One bit is fed to each input. One bit is returned at the output.

There are four types of logical elements: [AND](https://en.wikipedia.org/wiki/Logical_conjunction) (2 inputs), [OR](https://en.wikipedia.org/wiki/Logical_disjunction) (2 inputs), [XOR](https://en.wikipedia.org/wiki/Exclusive_or) (2 inputs), [NOT](https://en.wikipedia.org/wiki/Negation) (1 input). Logical elements take values from their direct descendants (inputs) and return the result of the function they perform. Natasha knows the logical scheme of the Mars rover, as well as the fact that only one input is broken. In order to fix the Mars rover, she needs to change the value on this input.

For each input, determine what the output will be if Natasha changes this input.

Input

The first line contains a single integer n (2 ≤ n ≤ 10^6) — the number of vertices in the graph (both inputs and elements).

The i-th of the next n lines contains a description of i-th vertex: the first word "AND", "OR", "XOR", "NOT" or "IN" (means the input of the scheme) is the vertex type. If this vertex is "IN", then the value of this input follows (0 or 1), otherwise follow the indices of input vertices of this element: "AND", "OR", "XOR" have 2 inputs, whereas "NOT" has 1 input. The vertices are numbered from one.

It is guaranteed that input data contains a correct logical scheme with an output produced by the vertex 1.

Output

Print a string of characters '0' and '1' (without quotes) — answers to the problem for each input in the ascending order of their vertex indices.

Example

Input

10
AND 9 4
IN 1
IN 1
XOR 6 5
AND 3 7
IN 0
NOT 10
IN 1
IN 1
AND 2 8

Output

10110

Note

The original scheme from the example (before the input is changed):

<image>

Green indicates bits '1', yellow indicates bits '0'.

If Natasha changes the input bit 2 to 0, then the output will be 1.

If Natasha changes the input bit 3 to 0, then the output will be 0.

If Natasha changes the input bit 6 to 1, then the output will be 1.

If Natasha changes the input bit 8 to 0, then the output will be 1.

If Natasha changes the input bit 9 to 0, then the output will be 0.

```python
AND = "AND"
OR = "OR"
XOR = "XOR"
NOT = "NOT"
IN = "IN"

OPS = {
    AND: AND,
    OR: OR,
    XOR: XOR,
    NOT: NOT,
}

class Node:
    def __init__(self, num):
        self.num = num
        self.op = None
        self.parent = None
        self.input_1 = None
        self.input_2 = None
        self.orig_value = None
        self.root_value_if_changed = None

    @property
    def children(self):
        if self.op == IN:
            return []
        elif self.op == NOT:
            return [self.input_1]
        else:
            return [self.input_1, self.input_2]

    def can_compute(self):
        if self.op == IN:
            return True

        if self.op == NOT:
            return self.input_1.orig_value is not None

        return self.input_1.orig_value is not None and self.input_2.orig_value is not None

    def compute(self):
        if self.op == IN:
            return self.orig_value

        assert self.can_compute()

        if self.op == NOT:
            return not self.input_1.orig_value
        elif self.op == AND:
            return self.input_1.orig_value and self.input_2.orig_value
        elif self.op == OR:
            return self.input_1.orig_value or self.input_2.orig_value
        else:
            return self.input_1.orig_value != self.input_2.orig_value

    def set_input(self, a):
        self.input_1 = a
        a.parent = self

    def set_inputs(self, a, b):
        self.input_1 = a
        self.input_2 = b

        a.parent = self
        b.parent = self

def compute_orig_values(root):
    stack = [root]

    while len(stack) > 0:
        node: Node = stack[-1]

        if node.can_compute():
            node.orig_value = node.compute()
            stack.pop()
        else:
            stack.extend(node.children)

def compute_if_change(root: Node):
    def comp_if_changed(node: Node):
        if node is root:
            return not node.orig_value

        orig = node.orig_value
        node.orig_value = not node.orig_value
        res = node.parent.compute()
        node.orig_value = orig

        if res == node.parent.orig_value:
            return root.orig_value
        else:
            return node.parent.root_value_if_changed

    stack = [root]

    while len(stack) > 0:
        node: Node = stack.pop()

        node.root_value_if_changed = comp_if_changed(node)

        stack.extend(node.children)

def main():
    import sys

    n = int(sys.stdin.readline())

    nodes = {i: Node(i) for i in range(1, n + 1)}
    assert len(nodes) == n

    for i in range(1, n + 1):
        toks = sys.stdin.readline().strip().split(" ")

        node = nodes[i]

        if len(toks) == 2:
            if toks[0] == IN:
                node.op = IN
                node.orig_value = toks[1] == "1"
            else:
                node.op = NOT
                node.set_input(nodes[int(toks[1])])
        else:
            node.op = OPS[toks[0]]
            a, b = map(int, toks[1:])
            a = nodes[a]
            b = nodes[b]

            node.set_inputs(a, b)

    root: Node = nodes[1]

    compute_orig_values(root)
    compute_if_change(root)

    ret = []

    for i in range(1, n + 1):
        node = nodes[i]

        if node.op == IN:
            ret.append(int(node.root_value_if_changed))

    ret = "".join(str(x) for x in ret)
    print(ret)

if __name__ == '__main__':
    main()

```


105_A. Transmigration

In Disgaea as in most role-playing games, characters have skills that determine the character's ability to use certain weapons or spells. If the character does not have the necessary skill, he cannot use it. The skill level is represented as an integer that increases when you use this skill. Different character classes are characterized by different skills.

Unfortunately, the skills that are uncommon for the given character's class are quite difficult to obtain. To avoid this limitation, there is the so-called transmigration.

Transmigration is reincarnation of the character in a new creature. His soul shifts to a new body and retains part of his experience from the previous life.

As a result of transmigration the new character gets all the skills of the old character and the skill levels are reduced according to the k coefficient (if the skill level was equal to x, then after transmigration it becomes equal to [kx], where [y] is the integral part of y). If some skill's levels are strictly less than 100, these skills are forgotten (the character does not have them any more). After that the new character also gains the skills that are specific for his class, but are new to him. The levels of those additional skills are set to 0.

Thus, one can create a character with skills specific for completely different character classes via transmigrations. For example, creating a mage archer or a thief warrior is possible.

You are suggested to solve the following problem: what skills will the character have after transmigration and what will the levels of those skills be?

Input

The first line contains three numbers n, m and k — the number of skills the current character has, the number of skills specific for the class into which the character is going to transmigrate and the reducing coefficient respectively; n and m are integers, and k is a real number with exactly two digits after decimal point (1 ≤ n, m ≤ 20, 0.01 ≤ k ≤ 0.99).

Then follow n lines, each of which describes a character's skill in the form "name exp" — the skill's name and the character's skill level: name is a string and exp is an integer in range from 0 to 9999, inclusive.

Then follow m lines each of which contains names of skills specific for the class, into which the character transmigrates.

All names consist of lowercase Latin letters and their lengths can range from 1 to 20 characters, inclusive. All character's skills have distinct names. Besides the skills specific for the class into which the player transmigrates also have distinct names.

Output

Print on the first line number z — the number of skills the character will have after the transmigration. Then print z lines, on each of which print a skill's name and level, separated by a single space. The skills should be given in the lexicographical order.

Examples

Input

5 4 0.75
axe 350
impaler 300
ionize 80
megafire 120
magicboost 220
heal
megafire
shield
magicboost

Output

6
axe 262
heal 0
impaler 225
magicboost 165
megafire 0
shield 0

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

ESP = 1e-7
n, m, k = input().rstrip().split()
n, m, k = int(n), int(m), float(k)
cur = {}
for i in range(n):
    skill, exp = input().rstrip().split()
    exp = int(int(exp) * k + ESP)
    if exp >= 100:
        cur[skill] = exp

for i in range(m):
    skill = input().rstrip()
    cur.setdefault(skill, 0)

print(len(cur))
for k in sorted(cur.keys()):
    print(k, cur[k])

```


1081_B. Farewell Party

Chouti and his classmates are going to the university soon. To say goodbye to each other, the class has planned a big farewell party in which classmates, teachers and parents sang and danced.

Chouti remembered that n persons took part in that party. To make the party funnier, each person wore one hat among n kinds of weird hats numbered 1, 2, … n. It is possible that several persons wore hats of the same kind. Some kinds of hats can remain unclaimed by anyone.

After the party, the i-th person said that there were a_i persons wearing a hat differing from his own.

It has been some days, so Chouti forgot all about others' hats, but he is curious about that. Let b_i be the number of hat type the i-th person was wearing, Chouti wants you to find any possible b_1, b_2, …, b_n that doesn't contradict with any person's statement. Because some persons might have a poor memory, there could be no solution at all.

Input

The first line contains a single integer n (1 ≤ n ≤ 10^5), the number of persons in the party.

The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ n-1), the statements of people.

Output

If there is no solution, print a single line "Impossible".

Otherwise, print "Possible" and then n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ n).

If there are multiple answers, print any of them.

Examples

Input

3
0 0 0

Output

Possible
1 1 1

Input

5
3 3 2 2 2

Output

Possible
1 1 2 2 2

Input

4
0 1 2 3

Output

Impossible

Note

In the answer to the first example, all hats are the same, so every person will say that there were no persons wearing a hat different from kind 1.

In the answer to the second example, the first and the second person wore the hat with type 1 and all other wore a hat of type 2.

So the first two persons will say there were three persons with hats differing from their own. Similarly, three last persons will say there were two persons wearing a hat different from their own.

In the third example, it can be shown that no solution exists.

In the first and the second example, other possible configurations are possible.

```python
import math, sys
from fractions import *

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

def main():
    n = int(input())
    a = mp()
    cnt = [0] * (n + 1)
    for i in a:
        cnt[i] += 1
    k = 1
    ans = [[] for i in range(n + 1)]
    for i in range(n + 1):
        if cnt[i] == 0:
            continue
        while True:
            if cnt[i] + i >= n:
                ans[i].append([n - i, k])
                cnt[i] -= n - i
                k += 1
            elif cnt[i]:
                print('Impossible')
                return
            else:
                break
    # print(*ans, sep = '\n')
    print('Possible')
    for i in a:
        # print(ans[i])
        if ans[i][-1][0] == 0:
            ans[i].pop()
        print(ans[i][-1][1], end = ' ')
        ans[i][-1][0] -= 1

deb = 0
if deb:
    file = open('input.txt', 'w')
else:
    input = sys.stdin.readline

main()
```


1100_B. Build a Contest

Arkady coordinates rounds on some not really famous competitive programming platform. Each round features n problems of distinct difficulty, the difficulties are numbered from 1 to n.

To hold a round Arkady needs n new (not used previously) problems, one for each difficulty. As for now, Arkady creates all the problems himself, but unfortunately, he can't just create a problem of a desired difficulty. Instead, when he creates a problem, he evaluates its difficulty from 1 to n and puts it into the problems pool.

At each moment when Arkady can choose a set of n new problems of distinct difficulties from the pool, he holds a round with these problems and removes them from the pool. Arkady always creates one problem at a time, so if he can hold a round after creating a problem, he immediately does it.

You are given a sequence of problems' difficulties in the order Arkady created them. For each problem, determine whether Arkady held the round right after creating this problem, or not. Initially the problems pool is empty.

Input

The first line contains two integers n and m (1 ≤ n, m ≤ 10^5) — the number of difficulty levels and the number of problems Arkady created.

The second line contains m integers a_1, a_2, …, a_m (1 ≤ a_i ≤ n) — the problems' difficulties in the order Arkady created them.

Output

Print a line containing m digits. The i-th digit should be 1 if Arkady held the round after creation of the i-th problem, and 0 otherwise.

Examples

Input

3 11
2 3 1 2 2 2 3 2 2 3 1

Output

00100000001

Input

4 8
4 1 3 3 2 3 3 3

Output

00001000

Note

In the first example Arkady held the round after the first three problems, because they are of distinct difficulties, and then only after the last problem.

```python
diff, prob = [int(x) for x in input().split()]
probs = [int(x) for x in input().split()]

counts = {}
comp = {}
num = 0
for i in range(diff):
    counts[i + 1] = 0
    comp[i + 1] = False

for p in probs:
    counts[p] += 1
    if comp[p] == False:
        num += 1
        comp[p] = True
        if (num == diff):
            num = 0
            for i in range(diff):
                counts[i + 1] -= 1
                if counts[i + 1] == 0:
                    comp[i + 1] = False
                else:
                    num += 1
            print("1", end="")
        else:
            print("0", end="")
    else:
        print("0", end="")
print("")

```


1121_F. Compress String

Suppose you are given a string s of length n consisting of lowercase English letters. You need to compress it using the smallest possible number of coins.

To compress the string, you have to represent s as a concatenation of several non-empty strings: s = t_{1} t_{2} … t_{k}. The i-th of these strings should be encoded with one of the two ways:

  * if |t_{i}| = 1, meaning that the current string consists of a single character, you can encode it paying a coins;
  * if t_{i} is a substring of t_{1} t_{2} … t_{i - 1}, then you can encode it paying b coins.

A string x is a substring of a string y if x can be obtained from y by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.

So your task is to calculate the minimum possible number of coins you need to spend in order to compress the given string s.

Input

The first line contains three positive integers, separated by spaces: n, a and b (1 ≤ n, a, b ≤ 5000) — the length of the string, the cost to compress a one-character string and the cost to compress a string that appeared before.

The second line contains a single string s, consisting of n lowercase English letters.

Output

Output a single integer — the smallest possible number of coins you need to spend to compress s.

Examples

Input

3 3 1
aba

Output

7

Input

4 1 1
abcd

Output

4

Input

4 10 1
aaaa

Output

12

Note

In the first sample case, you can set t_{1} = 'a', t_{2} = 'b', t_{3} = 'a' and pay 3 + 3 + 1 = 7 coins, since t_{3} is a substring of t_{1}t_{2}.

In the second sample, you just need to compress every character by itself.

In the third sample, you set t_{1} = t_{2} = 'a', t_{3} = 'aa' and pay 10 + 1 + 1 = 12 coins, since t_{2} is a substring of t_{1} and t_{3} is a substring of t_{1} t_{2}.

```python
import sys

sys.setrecursionlimit(10 ** 8)
n, a, b = map(int,input().split())
s = input()

def calc(j):
    if (j >= n): return 0
    if (dp[j] != -1): return dp[j]
    dp[j] = a + calc(j + 1)

    lo = j
    hi = n
    farthest = -1
    # finding best string to reach from a given j such that it eist before i using binary search
    while (lo < hi):
        mid = (lo + hi) // 2
        if (s[j:mid + 1] in s[0:j]):
            farthest = mid
            lo = mid + 1
        else:
            hi = mid
    if (farthest != -1): dp[j] = min(dp[j], b + calc(farthest + 1))
    return dp[j]

dp = [-1 for i in range(n + 5)]
print(calc(0))
```


1207_F. Remainder Problem

You are given an array a consisting of 500000 integers (numbered from 1 to 500000). Initially all elements of a are zero.

You have to process two types of queries to this array:

  * 1 x y — increase a_x by y;
  * 2 x y — compute ∑_{i ∈ R(x, y)} a_i, where R(x, y) is the set of all integers from 1 to 500000 which have remainder y modulo x.

Can you process all the queries?

Input

The first line contains one integer q (1 ≤ q ≤ 500000) — the number of queries.

Then q lines follow, each describing a query. The i-th line contains three integers t_i, x_i and y_i (1 ≤ t_i ≤ 2). If t_i = 1, then it is a query of the first type, 1 ≤ x_i ≤ 500000, and -1000 ≤ y_i ≤ 1000. If t_i = 2, then it it a query of the second type, 1 ≤ x_i ≤ 500000, and 0 ≤ y_i < x_i.

It is guaranteed that there will be at least one query of type 2.

Output

For each query of type 2 print one integer — the answer to it.

Example

Input

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

Output

4
4
0

```python
import sys
n = 500001
sqrt = int(0.75 * n**0.5)

data = [0]*(n)
ans = [[]]
# out = []
for i in range(1, sqrt):
    ans.append([0]*i)
j = int(sys.stdin.readline())
qus = sys.stdin.readlines()
for qu in qus:
    q = [int(i) for i in qu.split()]
    if q[0] == 1:
        x = q[1]
        y = q[2]
        data[x] += y
        for i in range(1, sqrt):
            ans[i][x%i] += y
    else:
        if q[1] < sqrt:
            sys.stdout.write(str(ans[q[1]][q[2]]))

        else:
            sm = 0
            for i in range(q[2], n, q[1]):
                sm += data[i]
            sys.stdout.write(str(sm))
            # out.append(str(sm))

            #out.append(str(sum([data[i] for i in range(q[2], n, q[1])])))
        sys.stdout.write("\n")

# sys.stdout.write('\n'.join(out) + '\n')
```


124_B. Permutations

You are given n k-digit integers. You have to rearrange the digits in the integers so that the difference between the largest and the smallest number was minimum. Digits should be rearranged by the same rule in all integers.

Input

The first line contains integers n and k — the number and digit capacity of numbers correspondingly (1 ≤ n, k ≤ 8). Next n lines contain k-digit positive integers. Leading zeroes are allowed both in the initial integers and the integers resulting from the rearranging of digits.

Output

Print a single number: the minimally possible difference between the largest and the smallest number after the digits are rearranged in all integers by the same rule.

Examples

Input

6 4
5237
2753
7523
5723
5327
2537

Output

2700

Input

3 3
010
909
012

Output

3

Input

7 5
50808
36603
37198
44911
29994
42543
50156

Output

20522

Note

In the first sample, if we rearrange the digits in numbers as (3,1,4,2), then the 2-nd and the 4-th numbers will equal 5237 and 2537 correspondingly (they will be maximum and minimum for such order of digits).

In the second sample, if we swap the second digits and the first ones, we get integers 100, 99 and 102.

```python
import sys

data = sys.stdin.read().split()
data_ptr = 0

def data_next():
    global data_ptr, data
    data_ptr += 1
    return data[data_ptr - 1]

N = int(data_next())
K = int(data_next())

arr = []
for i in range(N):
    arr.append(list(data_next()));

perm = []
for i in range(K):
    perm.append(str(i))

def next_perm():
    global perm, arr
    for i in reversed(range(len(perm) - 1)):
        if perm[i] < perm[i + 1]:
            break
    else:
        return False
    for j in reversed(range(i + 1, len(perm))):
        if perm[i] < perm[j]:
            break
    perm[i], perm[j] = perm[j], perm[i]
    perm[i + 1:] = reversed(perm[i + 1:])
    for k in range(len(arr)):
        arr[k][i], arr[k][j] = arr[k][j], arr[k][i]
        arr[k][i + 1:] = reversed(arr[k][i + 1:])
    return True

ans = 1000000000
while True:
    ans = min(ans, int("".join(max(arr))) - int("".join(min(arr))))
    if (not(next_perm())):
        break

print(ans)

```


1311_A. Add Odd or Subtract Even

You are given two positive integers a and b.

In one move, you can change a in the following way:

  * Choose any positive odd integer x (x > 0) and replace a with a+x;
  * choose any positive even integer y (y > 0) and replace a with a-y.

You can perform as many such operations as you want. You can choose the same numbers x and y in different moves.

Your task is to find the minimum number of moves required to obtain b from a. It is guaranteed that you can always obtain b from a.

You have to answer t independent test cases.

Input

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

Then t test cases follow. Each test case is given as two space-separated integers a and b (1 ≤ a, b ≤ 10^9).

Output

For each test case, print the answer — the minimum number of moves required to obtain b from a if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain b from a.

Example

Input

5
2 3
10 10
2 4
7 4
9 3

Output

1
0
2
2
1

Note

In the first test case, you can just add 1.

In the second test case, you don't need to do anything.

In the third test case, you can add 1 two times.

In the fourth test case, you can subtract 4 and add 1.

In the fifth test case, you can just subtract 6.

```python
for i in range(int(input())):
    a,b=map(int,input().split())

    if a==b:
        print(0)
    elif a<b:
        if (b-a)%2==0:
            print(2)
        else:
            print(1)
    elif a>b:
        if (a-b)%2==0:
            print(1)
        else:
            print(2)
```


1333_E. Road to 1600

Egor wants to achieve a rating of 1600 points on the well-known chess portal ChessForces and he needs your help!

Before you start solving the problem, Egor wants to remind you how the chess pieces move. Chess rook moves along straight lines up and down, left and right, as many squares as it wants. And when it wants, it can stop. The queen walks in all directions vertically and diagonally at any distance. You can see the examples below.

<image>

To reach the goal, Egor should research the next topic:

There is an N × N board. Each cell of the board has a number from 1 to N ^ 2 in it and numbers in all cells are distinct.

In the beginning, some chess figure stands in the cell with the number 1. Note that this cell is already considered as visited. After that every move is determined by the following rules:

  1. Among all not visited yet cells to which the figure can get in one move, it goes to the cell that has minimal number.
  2. If all accessible cells were already visited and some cells are not yet visited, then the figure is teleported to the not visited cell that has minimal number. If this step happens, the piece pays a fee of 1 vun.
  3. If all cells are already visited, the process is stopped.

Egor should find an N × N board on which the rook pays strictly less vuns than the queen during the round with this numbering. Help him to find such N × N numbered board, or tell that it doesn't exist.

Input

The only line contains one integer N — the size of the board, 1≤ N ≤ 500.

Output

The output should contain N lines.

In i-th line output N numbers — numbers on the i-th row of the board. All numbers from 1 to N × N must be used exactly once.

On your board rook must pay strictly less vuns than the queen.

If there are no solutions, print -1.

If there are several solutions, you can output any of them.

Examples

Input

1

Output

-1

Input

4

Output

4 3 6 12
7 5 9 15
14 1 11 10
13 8 16 2

Note

In case we have 1 × 1 board, both rook and queen do not have a chance to pay fees.

In second sample rook goes through cells 1 → 3 → 4 → 6 → 9 → 5 → 7 → 13 → 2 → 8 → 16 → 11 → 10 → 12 → 15 → (1 vun) → 14.

Queen goes through 1 → 3 → 4 → 2 → 5 → 6 → 9 → 7 → 13 → 8 → 11 → 10 → 12 → 15 → (1 vun) → 14 → (1 vun) → 16.

As a result rook pays 1 vun and queen pays 2 vuns.

```python
from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush,heappop
import math
from collections import *
from functools import reduce,cmp_to_key
import sys
input = sys.stdin.readline

M = mod = 998244353
def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))
def inv_mod(n):return pow(n, mod - 2, mod)

def li():return [int(i) for i in input().rstrip('\n').split()]
def st():return input().rstrip('\n')
def val():return int(input().rstrip('\n'))
def li2():return [i for i in input().rstrip('\n')]
def li3():return [int(i) for i in input().rstrip('\n')]

n = val()
l = [[0]*n for i in range(n)]

if n < 3:
    print(-1)
    exit()

curr = 0
def givecurr():
    global curr
    curr += 1
    return curr

up = [[5,4,1],[3,2,9],[8,6,7]]
down = [[7,6,8],[9,2,3],[1,4,5]]

totleft = n**2 - 9

i = n - 1
takeup = j = 0

while totleft:
    while i >= 0 and j >= 0 and l[i][j] == 0:
        l[i][j] = givecurr()
        totleft -= 1
        i -= 1
    i += 1
    j += 1
    while j < n:
        l[i][j] = givecurr()
        totleft -= 1
        j += 1
    j = n - 1
    i += 1
    if not totleft:
        takeup = 1
        break
    while j>=0 and l[i][j] == 0:
        l[i][j] = givecurr()
        totleft -= 1
        j -= 1

    j += 1
    i += 1

    while i < n:
        l[i][j] = givecurr()
        totleft -= 1
        i += 1
    i = n - 1
    j += 1

for i in range(3):
    for j in range(3):
        l[i + n - 3][j + n - 3] = curr + (up[i][j] if takeup else down[i][j])

for i in l:
    print(*i)
```


1354_B. Ternary String

You are given a string s such that each its character is either 1, 2, or 3. You have to choose the shortest contiguous substring of s such that it contains each of these three characters at least once.

A contiguous substring of string s is a string that can be obtained from s by removing some (possibly zero) characters from the beginning of s and some (possibly zero) characters from the end of s.

Input

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

Each test case consists of one line containing the string s (1 ≤ |s| ≤ 200000). It is guaranteed that each character of s is either 1, 2, or 3.

The sum of lengths of all strings in all test cases does not exceed 200000.

Output

For each test case, print one integer — the length of the shortest contiguous substring of s containing all three types of characters at least once. If there is no such substring, print 0 instead.

Example

Input

7
123
12222133333332
112233
332211
12121212
333333
31121

Output

3
3
4
4
0
0
4

Note

Consider the example test:

In the first test case, the substring 123 can be used.

In the second test case, the substring 213 can be used.

In the third test case, the substring 1223 can be used.

In the fourth test case, the substring 3221 can be used.

In the fifth test case, there is no character 3 in s.

In the sixth test case, there is no character 1 in s.

In the seventh test case, the substring 3112 can be used.

```python
import math
from sys import stdin,stdout
def L():
    return list(map(int,stdin.readline().split())) #For array input
def Si():
    return sorted(list(map(int,stdin.readline().split()))) #For sorted array
def In():
    return map(int,stdin.readline().split()) #For multiple input
def I():
    return stdin.readline() #For single input
def main():
    for i in range(int(I())):
        s=str(I())
        n1=-1
        n2=-1
        n3=-1
        m=len(s)
        for i in range(m):
            if(s[i]=="1"):
                n1=i
            elif(s[i]=="2"):
                n2=i
            elif(s[i]=="3"):
                n3=i
            if(n1!=-1 and n2!=-1 and n3!=-1 ):
                m=min( m, ( max(n1,n2,n3)-min(n1,n2,n3)+1) )
        print(m if (n1!=-1 and n2!=-1 and n3!=-1) else 0)

if __name__ == "__main__" :
    main()

```


1373_G. Pawns

You are given a chessboard consisting of n rows and n columns. Rows are numbered from bottom to top from 1 to n. Columns are numbered from left to right from 1 to n. The cell at the intersection of the x-th column and the y-th row is denoted as (x, y). Furthermore, the k-th column is a special column.

Initially, the board is empty. There are m changes to the board. During the i-th change one pawn is added or removed from the board. The current board is good if we can move all pawns to the special column by the followings rules:

  * Pawn in the cell (x, y) can be moved to the cell (x, y + 1), (x - 1, y + 1) or (x + 1, y + 1);
  * You can make as many such moves as you like;
  * Pawns can not be moved outside the chessboard;
  * Each cell can not contain more than one pawn.

The current board may not always be good. To fix it, you can add new rows to the board. New rows are added at the top, i. e. they will have numbers n+1, n+2, n+3, ....

After each of m changes, print one integer — the minimum number of rows which you have to add to make the board good.

Input

The first line contains three integers n, k and m (1 ≤ n, m ≤ 2 ⋅ 10^5; 1 ≤ k ≤ n) — the size of the board, the index of the special column and the number of changes respectively.

Then m lines follow. The i-th line contains two integers x and y (1 ≤ x, y ≤ n) — the index of the column and the index of the row respectively. If there is no pawn in the cell (x, y), then you add a pawn to this cell, otherwise — you remove the pawn from this cell.

Output

After each change print one integer — the minimum number of rows which you have to add to make the board good.

Example

Input

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

Output

0
1
2
2
1

```python
import collections
import math
n, k, m = [int(i) for i in input().split()]
l = math.ceil((math.log(2*n) / math.log(2)))
p = 2 ** l
# print(p)
memo = [0] * (2 * p)
allres = [0] * (2 * p)

exist = set()
for _i in range(m):
    x, y = [int(i) for i in input().split()]
    l = abs(x - k) + y
    index = l + p
    if (x, y) in exist:
        exist.remove((x, y))
        while index != 0:
            memo[index] -= 1
            index = index // 2
    else:
        exist.add((x, y))
        while index != 0:
            memo[index] += 1
            index = index // 2
    index = (l + p) // 2
    allres[l+p] = l + memo[l + p] - 1
    if memo[l + p] == 0:
        allres[l+p] = 0
    while index != 0:
        allres[index] = max(allres[index * 2] + memo[index * 2 + 1], allres[index * 2 + 1])
        index = index // 2
    # print('i', _i + 1, exist, allres, memo)

    print (max(allres[1] - n, 0))

```


1397_A. Juggling Letters

You are given n strings s_1, s_2, …, s_n consisting of lowercase Latin letters.

In one operation you can remove a character from a string s_i and insert it to an arbitrary position in a string s_j (j may be equal to i). You may perform this operation any number of times. Is it possible to make all n strings equal?

Input

The first line contains t (1 ≤ t ≤ 10): the number of test cases.

The first line of each test case contains a single integer n (1 ≤ n ≤ 1000): the number of strings.

n lines follow, the i-th line contains s_i (1 ≤ \lvert s_i \rvert ≤ 1000).

The sum of lengths of all strings in all test cases does not exceed 1000.

Output

If it is possible to make the strings equal, print "YES" (without quotes).

Otherwise, print "NO" (without quotes).

You can output each character in either lowercase or uppercase.

Example

Input

4
2
caa
cbb
3
cba
cba
cbb
4
ccab
cbac
bca
acbcc
4
acb
caf
c
cbafc

Output

YES
NO
YES
NO

Note

In the first test case, you can do the following:

  * Remove the third character of the first string and insert it after the second character of the second string, making the two strings "ca" and "cbab" respectively.
  * Remove the second character of the second string and insert it after the second character of the first string, making both strings equal to "cab".

In the second test case, it is impossible to make all n strings equal.

```python
for _ in range(int(input())):
	#n,k=map(int,input().split())
  ll=[0]*26
  n=int(input())
  bool=True
  for _ in range(n):
    s=input()
    pp=set(s)
    for c in pp:
      cc=s.count(c)
      ll[ord(c)-97]+=cc
   # print(ll)

  for x in ll:
    if x%n!=0 :
      bool=False

  if bool == True :
     print('YES')
  else:
     print('NO')
```


1420_C1. Pokémon Army (easy version)

This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.

Pikachu is a cute and friendly pokémon living in the wild pikachu herd.

But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.

First, Andrew counted all the pokémon — there were exactly n pikachu. The strength of the i-th pokémon is equal to a_i, and all these numbers are distinct.

As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array b from k indices such that 1 ≤ b_1 < b_2 < ... < b_k ≤ n, and his army will consist of pokémons with forces a_{b_1}, a_{b_2}, ..., a_{b_k}.

The strength of the army is equal to the alternating sum of elements of the subsequence; that is, a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + ....

Andrew is experimenting with pokémon order. He performs q operations. In i-th operation Andrew swaps l_i-th and r_i-th pokémon.

Note: q=0 in this version of the task.

Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.

Help Andrew and the pokémon, or team R will realize their tricky plan!

Input

Each test contains multiple test cases.

The first line contains one positive integer t (1 ≤ t ≤ 10^3) denoting the number of test cases. Description of the test cases follows.

The first line of each test case contains two integers n and q (1 ≤ n ≤ 3 ⋅ 10^5, q = 0) denoting the number of pokémon and number of operations respectively.

The second line contains n distinct positive integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) denoting the strengths of the pokémon.

i-th of the last q lines contains two positive integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) denoting the indices of pokémon that were swapped in the i-th operation.

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

Output

For each test case, print q+1 integers: the maximal strength of army before the swaps and after each swap.

Example

Input

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

Output

3
2
9

Note

In third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be 5−3+7=9.

```python
import sys
from collections import defaultdict as dc
import math
from bisect import bisect, bisect_left,bisect_right
input=sys.stdin.readline
for _ in range(int(input())):
    n,x=map(int,input().split())
    l=list(map(int,input().split()))
    f=0
    a=0
    b=0
    i=0
    while(i<n):
        if f==0:
            t=l[i]
            q=1
            for j in range(i+1,n):
                b+=1
                if l[j]<l[j-1]:
                    break
                else:
                    t=max(t,l[j])
                    q+=1
            a+=t
            i+=q
            f=1
        else:
            t=l[i]
            q=1
            for j in range(i+1,n):
                b+=1
                if l[j]>l[j-1]:
                    break
                else:
                    t=min(t,l[j])
                    q+=1
            if i+q==n:
                break
            else:
                a-=t
                i+=q
                f=0
    print(a)

```


1439_A2. Binary Table (Hard Version)

This is the hard version of the problem. The difference between the versions is in the number of possible operations that can be made. You can make hacks if and only if you solved both versions of the problem.

You are given a binary table of size n × m. This table consists of symbols 0 and 1.

You can make such operation: select 3 different cells that belong to one 2 × 2 square and change the symbols in these cells (change 0 to 1 and 1 to 0).

Your task is to make all symbols in the table equal to 0. You are allowed to make at most nm operations. You don't need to minimize the number of operations.

It can be proved, that it is always possible.

Input

The first line contains a single integer t (1 ≤ t ≤ 5000) — the number of test cases. The next lines contain descriptions of test cases.

The first line of the description of each test case contains two integers n, m (2 ≤ n, m ≤ 100).

Each of the next n lines contains a binary string of length m, describing the symbols of the next row of the table.

It is guaranteed, that the sum of nm for all test cases does not exceed 20000.

Output

For each test case print the integer k (0 ≤ k ≤ nm) — the number of operations.

In the each of the next k lines print 6 integers x_1, y_1, x_2, y_2, x_3, y_3 (1 ≤ x_1, x_2, x_3 ≤ n, 1 ≤ y_1, y_2, y_3 ≤ m) describing the next operation. This operation will be made with three cells (x_1, y_1), (x_2, y_2), (x_3, y_3). These three cells should be different. These three cells should belong to some 2 × 2 square.

Example

Input

5
2 2
10
11
3 3
011
101
110
4 4
1111
0110
0110
1111
5 5
01011
11001
00010
11011
10000
2 3
011
101

Output

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

Note

In the first test case, it is possible to make only one operation with cells (1, 1), (2, 1), (2, 2). After that, all symbols will be equal to 0.

In the second test case:

  * operation with cells (2, 1), (3, 1), (3, 2). After it the table will be:

    011
    001
    000

  * operation with cells (1, 2), (1, 3), (2, 3). After it the table will be:

    000
    000
    000

In the fifth test case:

  * operation with cells (1, 3), (2, 2), (2, 3). After it the table will be:

    010
    110

  * operation with cells (1, 2), (2, 1), (2, 2). After it the table will be:

    000
    000

```python
from sys import stdin
input = stdin.readline
mp = lambda : map(int,input().split())
it = lambda: int(input())
for _ in range(it()):
	a,b = mp()
	t = [list(map(int,list(input().strip()))) for i in range(a)]
	# print(t)
	saare =[]
	for i in range(a-2):
		for j in range(b):
			if t[i][j]==1:
				if j!=b-1:
					t[i][j]=1-t[i][j]
					t[i+1][j]=1-t[i+1][j]
					t[i+1][j+1]=1-t[i+1][j+1]
					saare.append([i,j,i+1,j,i+1,j+1])
				else:
					t[i][j]=1-t[i][j]
					t[i+1][j]= 1- t[i+1][j]
					t[i+1][j-1]=1 - t[i+1][j-1]
					saare.append([i,j,i+1,j,i+1,j-1])
	ls2 =a-2
	ls = a-1
	for k in range(b-2):
		if t[ls2][k]==t[ls][k]==0:
			continue
		elif t[ls2][k]==t[ls][k]==1 :
			if t[ls2][k+1]:
				saare.append([ls,k,ls2,k,ls2,k+1])
				t[ls2][k]=1-t[ls2][k]
				t[ls][k]=1-t[ls][k]
				t[ls2][k+1]=1-t[ls2][k+1]
			else:
				saare.append([ls2,k,ls,k,ls,k+1])
				t[ls2][k]=1-t[ls2][k]
				t[ls][k]=1-t[ls][k]
				t[ls][k+1]=1-t[ls][k+1]
		elif t[ls2][k]==1:
			saare.append([ls2,k,ls2,k+1,ls,k+1])
			t[ls2][k]=1-t[ls2][k]
			t[ls2][k+1]=1-t[ls2][k+1]
			t[ls][k+1]=1-t[ls][k+1]
		else:
			saare.append([ls,k,ls,k+1,ls2,k+1])
			t[ls][k]=1-t[ls][k]
			t[ls][k+1]=1-t[ls][k+1]
			t[ls2][k+1]=1-t[ls2][k+1]
	st = str(t[ls2][b-2]) + str(t[ls2][b-1])+str(t[ls][b-2]) + str(t[ls][b-1])
	if st =="0000":
		pass
	elif st =="0001":
		saare.append([ls,b-2,ls,b-1,ls2,b-1])
		saare.append([ls,b-1,ls2,b-1,ls2,b-2])
		saare.append([ls,b-1,ls,b-2,ls2,b-2])
	elif st =="0010":
		saare.append([ls2,b-2,ls,b-2,ls,b-1])
		saare.append([ls,b-2,ls,b-1,ls2,b-1])
		saare.append([ls,b-2,ls2,b-2,ls2,b-1])
	elif st =="0100":
		saare.append([ls2,b-2,ls2,b-1,ls,b-1])
		saare.append([ls2,b-1,ls,b-1,ls,b-2])
		saare.append([ls2,b-1,ls2,b-2,ls,b-2])
	elif st =="1000":
		saare.append([ls2,b-1,ls2,b-2,ls,b-2])
		saare.append([ls2,b-2,ls,b-2,ls,b-1])
		saare.append([ls2,b-2,ls2,b-1,ls,b-1])
	elif st=="0011":
		saare.append([ls,b-2,ls,b-1,ls2,b-1])
		saare.append([ls2,b-2,ls2,b-1,ls,b-1])
		saare.append([ls2,b-1,ls,b-1,ls,b-2])
		saare.append([ls2,b-1,ls2,b-2,ls,b-2])
	elif st=="0101":
		saare.append([ls2,b-1,ls,b-1,ls,b-2])
		saare.append([ls2,b-2,ls,b-2,ls,b-1])
		saare.append([ls,b-2,ls,b-1,ls2,b-1])
		saare.append([ls,b-2,ls2,b-2,ls2,b-1])
	elif st =="0110":
		saare.append([ls2,b-1,ls,b-1,ls,b-2])
		saare.append([ls,b-2,ls,b-1,ls2,b-1])
		saare.append([ls,b-1,ls2,b-1,ls2,b-2])
		saare.append([ls,b-1,ls,b-2,ls2,b-2])
	elif st=="0111":
		saare.append([ls2,b-1,ls,b-1,ls,b-2])
	elif st=="1001":
		saare.append([ls2,b-2,ls,b-2,ls,b-1])
		saare.append([ls2,b-2,ls,b-2,ls,b-1])
		saare.append([ls,b-2,ls,b-1,ls2,b-1])
		saare.append([ls,b-2,ls2,b-2,ls2,b-1])
	elif st=="1010":
		saare.append([ls2,b-2,ls,b-2,ls,b-1])
		saare.append([ls,b-2,ls,b-1,ls2,b-1])
		saare.append([ls,b-1,ls2,b-1,ls2,b-2])
		saare.append([ls,b-1,ls,b-2,ls2,b-2])
	elif st =="1011":
		saare.append([ls2,b-2,ls,b-2,ls,b-1])
	elif st=="1100":
		saare.append([ls2,b-2,ls2,b-1,ls,b-1])
		saare.append([ls,b-2,ls,b-1,ls2,b-1])
		saare.append([ls,b-1,ls2,b-1,ls2,b-2])
		saare.append([ls,b-1,ls,b-2,ls2,b-2])
	elif st=="1101":
		saare.append([ls2,b-2,ls2,b-1,ls,b-1])
	elif st =="1110":
		saare.append([ls,b-2,ls2,b-2,ls2,b-1])
	elif st=="1111":
		saare.append([ls,b-2,ls2,b-2,ls2,b-1])
		saare.append([ls,b-2,ls,b-1,ls2,b-1])
		saare.append([ls,b-1,ls2,b-1,ls2,b-2])
		saare.append([ls,b-1,ls,b-2,ls2,b-2])

	print(len(saare))
	for i in saare:
		print(*list(map(lambda x: x+1,i)))
```


1466_A. Bovine Dilemma

Argus was charged with guarding Io, which is not an ordinary cow. Io is quite an explorer, and she wanders off rather frequently, making Argus' life stressful. So the cowherd decided to construct an enclosed pasture for Io.

There are n trees growing along the river, where Argus tends Io. For this problem, the river can be viewed as the OX axis of the Cartesian coordinate system, and the n trees as points with the y-coordinate equal 0. There is also another tree growing in the point (0, 1).

Argus will tie a rope around three of the trees, creating a triangular pasture. Its exact shape doesn't matter to Io, but its area is crucial to her. There may be many ways for Argus to arrange the fence, but only the ones which result in different areas of the pasture are interesting for Io. Calculate the number of different areas that her pasture may have. Note that the pasture must have nonzero area.

Input

The input consists of multiple test cases. The first line contains an integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow, each one is described in two lines.

In the first line of each test case there is a single integer n (1 ≤ n ≤ 50) denoting the number of trees growing along the river. Next line contains n distinct integers x_1 < x_2 < … < x_{n - 1} < x_n (1 ≤ x_i ≤ 50), the x-coordinates of trees growing along the river.

Output

In a single line output an integer, the number of different nonzero areas that triangles with trees as vertices may have.

Example

Input

8
4
1 2 4 5
3
1 3 5
3
2 6 8
2
1 2
1
50
5
3 4 5 6 8
3
1 25 26
6
1 2 4 8 16 32

Output

4
2
3
1
0
5
3
15

Note

In the first test case, we have 6 non-degenerate triangles with the following areas: 0.5, 0.5, 1, 1.5, 1.5 and 2. The pasture can have 4 different areas, and thus 4 is the answer.

In the second test case, we have 3 non-degenerate triangles with the following areas: 1, 1 and 2. The pasture can have 2 different areas, so 2 is the answer.

The following two drawings present the situation in the second test case. The blue triangles in the first drawing have area 1. The red triangle in the second drawing has area 2.

<image>

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

############ ---- Input Functions ---- ############
def inp():
    return (int(input()))

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

def insr():
    s = input()
    return (list(s[:len(s) - 1]))

def invr():
    return (map(int, input().split()))

###################################################

def solve(n, ass):
    if n == 1:
        return 0
    s = set()
    for i in range(n):
        for j in range(i):
            s.add(ass[i]-ass[j])
    return len(s)

for _ in range(inp()):
    n = inp()
    ass = inlt()
    print(solve(n, ass))

```