p02726 AtCoder Beginner Contest 160 - Line++

We have an undirected graph G with N vertices numbered 1 to N and N edges as follows:

* For each i=1,2,...,N-1, there is an edge between Vertex i and Vertex i+1.
* There is an edge between Vertex X and Vertex Y.

For each k=1,2,...,N-1, solve the problem below:

* Find the number of pairs of integers (i,j) (1 \leq i < j \leq N) such that the shortest distance between Vertex i and Vertex j in G is k.

Constraints

* 3 \leq N \leq 2 \times 10^3
* 1 \leq X,Y \leq N
* X+1 < Y
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X Y

Output

For each k=1, 2, ..., N-1 in this order, print a line containing the answer to the problem.

Examples

Input

5 2 4

Output

5
4
1
0

Input

3 1 3

Output

3
0

Input

7 3 7

Output

7
8
4
2
0
0

Input

10 4 8

Output

10
12
10
8
4
1
0
0
0

```python
n,x,y = map(int, input().split())
x = x-1
y = y-1

k=[0]*n

for i in range(n-1):
  for j in range(i+1,n):
    m = min(j-i,abs(x-i)+1+abs(y-j))
    k[m] += 1

for i in range(1,n):
  print(k[i])
```


p02993 AtCoder Beginner Contest 131 - Security

The door of Snuke's laboratory is locked with a security code.

The security code is a 4-digit number. We say the security code is hard to enter when it contains two consecutive digits that are the same.

You are given the current security code S. If S is hard to enter, print `Bad`; otherwise, print `Good`.

Constraints

* S is a 4-character string consisting of digits.

Input

Input is given from Standard Input in the following format:

S

Output

If S is hard to enter, print `Bad`; otherwise, print `Good`.

Examples

Input

3776

Output

Bad

Input

8080

Output

Good

Input

1333

Output

Bad

Input

0024

Output

Bad

```python
S=input()
for i in range(3):
  if S[i]==S[i+1]:
    print('Bad')
    exit(0)
print('Good')
```


p03134 Yahoo Programming Contest 2019 - Pass

There are N Snukes lining up in a row. You are given a string S of length N. The i-th Snuke from the front has two red balls if the i-th character in S is `0`; one red ball and one blue ball if the i-th character in S is `1`; two blue balls if the i-th character in S is `2`.

Takahashi has a sequence that is initially empty. Find the number of the possible sequences he may have after repeating the following procedure 2N times, modulo 998244353:

* Each Snuke who has one or more balls simultaneously chooses one of his balls and hand it to the Snuke in front of him, or hand it to Takahashi if he is the first Snuke in the row.
* Takahashi receives the ball and put it to the end of his sequence.

Constraints

* 1 \leq |S| \leq 2000
* S consists of `0`,`1` and `2`.

Note that the integer N is not directly given in input; it is given indirectly as the length of the string S.

Input

Input is given from Standard Input in the following format:

S

Output

Print the number of the possible sequences Takahashi may have after repeating the procedure 2N times, modulo 998244353.

Examples

Input

02

Output

3

Input

1210

Output

55

Input

12001021211100201020

Output

543589959

```python
s = input()
n = len(s)
red = [0]
blue = [0]
mod = 998244353
red = [-1]*(2*n)
blue = [-1]*(2*n)
cntr = 0
cntb = 0
for i in range(n):
  cntr = max(cntr,i)
  cntb = max(cntb,i)
  if s[i] == "0":
    red[cntr] = 1
    red[cntr+1] = 1
    cntr += 2
  if s[i] == "1":
    red[cntr] = 1
    cntr += 1
    blue[cntb] = 1
    cntb += 1
  if s[i] == "2":
    blue[cntb] = 1
    blue[cntb+1] = 1
    cntb += 2
for i in range(1,2*n):
  red[i] += red[i-1]
  blue[i] += blue[i-1]
dp = [[0]*(4*n+5) for i in range(2*n+1)]
dp[0][0] = 1
for i in range(1,2*n+1):
  for j in range(-blue[i-1],red[i-1]+1,1):
    dp[i][j] = (dp[i-1][j+1]+dp[i-1][j-1])%mod

print(dp[-1][red[-1]])
```


p03279 AtCoder Regular Contest 101 - Robots and Exits

There are N robots and M exits on a number line. The N + M coordinates of these are all integers and all distinct. For each i (1 \leq i \leq N), the coordinate of the i-th robot from the left is x_i. Also, for each j (1 \leq j \leq M), the coordinate of the j-th exit from the left is y_j.

Snuke can repeatedly perform the following two kinds of operations in any order to move all the robots simultaneously:

* Increment the coordinates of all the robots on the number line by 1.
* Decrement the coordinates of all the robots on the number line by 1.

Each robot will disappear from the number line when its position coincides with that of an exit, going through that exit. Snuke will continue performing operations until all the robots disappear.

When all the robots disappear, how many combinations of exits can be used by the robots? Find the count modulo 10^9 + 7. Here, two combinations of exits are considered different when there is a robot that used different exits in those two combinations.

Constraints

* 1 \leq N, M \leq 10^5
* 1 \leq x_1 < x_2 < ... < x_N \leq 10^9
* 1 \leq y_1 < y_2 < ... < y_M \leq 10^9
* All given coordinates are integers.
* All given coordinates are distinct.

Input

Input is given from Standard Input in the following format:

N M
x_1 x_2 ... x_N
y_1 y_2 ... y_M

Output

Print the number of the combinations of exits that can be used by the robots when all the robots disappear, modulo 10^9 + 7.

Examples

Input

2 2
2 3
1 4

Output

3

Input

3 4
2 5 10
1 3 7 13

Output

8

Input

4 1
1 2 4 5
3

Output

1

Input

4 5
2 5 7 11
1 3 6 9 13

Output

6

Input

10 10
4 13 15 18 19 20 21 22 25 27
1 5 11 12 14 16 23 26 29 30

Output

22

```python
from bisect import bisect
from collections import defaultdict

class Bit:
    def __init__(self, n):
        self.size = n
        self.tree = [0] * (n + 1)
        self.depth = n.bit_length()

    def sum(self, i):
        s = 0
        while i > 0:
            s += self.tree[i]
            i -= i & -i
        return s

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

    def debug_print(self):
        for i in range(1, self.size + 1):
            j = (i & -i).bit_length()
            print('  ' * j, self.tree[i])

    def lower_bound(self, x):
        sum_ = 0
        pos = 0
        for i in range(self.depth, -1, -1):
            k = pos + (1 << i)
            if k <= self.size and sum_ + self.tree[k] < x:
                sum_ += self.tree[k]
                pos += 1 << i
        return pos + 1, sum_

n, m = map(int, input().split())
xxx = list(map(int, input().split()))
yyy = list(map(int, input().split()))
ab = defaultdict(set)
coordinates = set()

for x in xxx:
    if x < yyy[0] or yyy[-1] < x:
        continue
    i = bisect(yyy, x)
    a = x - yyy[i - 1]
    b = yyy[i] - x
    ab[a].add(b)
    coordinates.add(b)

# Bitのindexは1から始まるように作っているが、"0"を取れるようにするため、全体を1ずらす
cor_dict = {b: i for i, b in enumerate(sorted(coordinates), start=2)}
cdg = cor_dict.get
bit = Bit(len(coordinates) + 1)
bit.add(1, 1)

for a in sorted(ab):
    bbb = sorted(map(cdg, ab[a]), reverse=True)
    for b in bbb:
        bit.add(b, bit.sum(b - 1))

print(bit.sum(bit.size) % (10 ** 9 + 7))

```


p03434 AtCoder Beginner Contest 088 - Card Game for Two

We have N cards. A number a_i is written on the i-th card.
Alice and Bob will play a game using these cards. In this game, Alice and Bob alternately take one card. Alice goes first.
The game ends when all the cards are taken by the two players, and the score of each player is the sum of the numbers written on the cards he/she has taken. When both players take the optimal strategy to maximize their scores, find Alice's score minus Bob's score.

Constraints

* N is an integer between 1 and 100 (inclusive).
* a_i \ (1 \leq i \leq N) is an integer between 1 and 100 (inclusive).

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 a_3 ... a_N

Output

Print Alice's score minus Bob's score when both players take the optimal strategy to maximize their scores.

Examples

Input

2
3 1

Output

2

Input

3
2 7 4

Output

5

Input

4
20 18 2 18

Output

18

```python
input()
card=sorted(map(int,input().split()))[::-1]
print(sum(card[::2])-sum(card[1::2]))
```


p03593 CODE FESTIVAL 2017 qual A - Palindromic Matrix

We have an H-by-W matrix. Let a_{ij} be the element at the i-th row from the top and j-th column from the left. In this matrix, each a_{ij} is a lowercase English letter.

Snuke is creating another H-by-W matrix, A', by freely rearranging the elements in A. Here, he wants to satisfy the following condition:

* Every row and column in A' can be read as a palindrome.

Determine whether he can create a matrix satisfying the condition.

Constraints

* 1 ≤ H, W ≤ 100
* a_{ij} is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

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

Output

If Snuke can create a matrix satisfying the condition, print `Yes`; otherwise, print `No`.

Examples

Input

3 4
aabb
aabb
aacc

Output

Yes

Input

2 2
aa
bb

Output

No

Input

5 1
t
w
e
e
t

Output

Yes

Input

2 5
abxba
abyba

Output

No

Input

1 1
z

Output

Yes

```python
from collections import Counter
H, W = map(int, input().split())
cntA = Counter()

for _ in range(H):
    cntA += Counter(list(input()))

four = (H // 2) * (W // 2)
for a, c in cntA.items():
    if four <= 0:
        break
    while c >= 4 and four > 0:
        c -= 4
        four -= 1
    cntA[a] = c

if four > 0:
    print('No')
    exit()

if H % 2 == W % 2 == 1:
    for a, c in cntA.items():
        if c % 2 == 1:
            cntA[a] -= 1
            break
    else:
        print('No')
        exit()

print('Yes' if all(c % 2 == 0 for c in cntA.values()) else 'No')

```


p03914 CODE FESTIVAL 2016 Final - Road of the King

There are N towns in Takahashi Kingdom. They are conveniently numbered 1 through N.

Takahashi the king is planning to go on a tour of inspection for M days. He will determine a sequence of towns c, and visit town c_i on the i-th day. That is, on the i-th day, he will travel from his current location to town c_i. If he is already at town c_i, he will stay at that town. His location just before the beginning of the tour is town 1, the capital. The tour ends at town c_M, without getting back to the capital.

The problem is that there is no paved road in this kingdom. He decided to resolve this issue by paving the road himself while traveling. When he travels from town a to town b, there will be a newly paved one-way road from town a to town b.

Since he cares for his people, he wants the following condition to be satisfied after his tour is over: "it is possible to travel from any town to any other town by traversing roads paved by him". How many sequences of towns c satisfy this condition?

Constraints

* 2≦N≦300
* 1≦M≦300

Input

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

N M

Output

Print the number of sequences of towns satisfying the condition, modulo 1000000007 (=10^9+7).

Examples

Input

3 3

Output

2

Input

150 300

Output

734286322

Input

300 150

Output

0

```python
mod=10**9+7

N,M=map(int,input().split())
dp=[[0 for i in range(N+1)] for j in range(N+1)]
dp[N][N]=1

for i in range(M-1,-1,-1):
    for k in range(1,N+1):
        for j in range(k,N+1):
            if j==k:
                if j<N:
                    dp[j][k]=(j*dp[j][k]+(N-j)*dp[j+1][k])%mod
                else:
                    dp[j][k]=(N*dp[j][k])%mod
            else:
                if j<N:
                    dp[j][k]=(k*dp[j][j]+(N-j)*dp[j+1][k]+(j-k)*dp[j][k])%mod
                else:
                    dp[j][k]=(k*dp[j][j]+(N-k)*dp[j][k])%mod

print(dp[1][1])

```


p00016 Treasure Hunt

When a boy was cleaning up after his grand father passing, he found an old paper:

<image>

In addition, other side of the paper says that "go ahead a number of steps equivalent to the first integer, and turn clockwise by degrees equivalent to the second integer".

His grand mother says that Sanbonmatsu was standing at the center of town. However, now buildings are crammed side by side and people can not walk along exactly what the paper says in. Your task is to write a program which hunts for the treature on the paper.

For simplicity, 1 step is equivalent to 1 meter. Input consists of several pairs of two integers d (the first integer) and t (the second integer) separated by a comma. Input ends with "0, 0". Your program should print the coordinate (x, y) of the end point. There is the treature where x meters to the east and y meters to the north from the center of town.

You can assume that d ≤ 100 and -180 ≤ t ≤ 180.

Input

A sequence of pairs of integers d and t which end with "0,0".

Output

Print the integer portion of x and y in a line respectively.

Example

Input

56,65
97,54
64,-4
55,76
42,-27
43,80
87,-86
55,-6
89,34
95,5
0,0

Output

171
-302

```python
import math

def calc(x, y, r, d, nd):
	x = x + r * math.cos(math.radians(d))
	y = y + r * math.sin(math.radians(d))
	d -= nd
	return x, y, d

x = y = 0
d = 90

while True:
	r, nd = map(int, input().split(","))
	if r == nd == 0: break
	x, y, d = calc(x, y, r, d, nd)

print(int(x))
print(int(y))
```


p00148 Candy and Class Flag

In Group C of the 3rd year, we decided to use the "class flag" used at the sports festival on November 10, 2007 at future class reunions. So, in order to decide which students to keep the "class flag", I decided to play the following game using a large amount of candy that the teacher gave me the other day.

* Each student will take one candy in the order of student number.
* If candy remains after one round, continue to take candy in order from the person with the first student number.
* The person who picks up the last candy will be the student who keeps the "class flag".

There are 39 students in the 3rd grade C class. Their student numbers are 3C01 to 3C39. For example, if you have 50 candies and everyone in the class finishes taking the first candy, you will have 11 candies left. If you take it again in student number order, the last one will be taken by the 3C11 student. That is, the 3C11 student is the student who keeps the "class flag".

Create a program that takes the number of candies as input and outputs the student number of the student who stores the "class flag".

Input

Multiple test cases are given. Each test case is given in the following format. For each test case, an integer a (1 ≤ a ≤ 10000) representing the number of candies is given on one line. Process until the end of input (EOF).

The number of datasets does not exceed 20.

Output

For each test case, output the student number (half-width alphanumeric characters) of the student who stores the "class flag" on one line.

Example

Input

50
5576
5577
5578

Output

3C11
3C38
3C39
3C01

```python
while True:

    try:
        n = int(input())
    except:
        break

    ans = n % 39
    if ans == 0:
        ans = "39"
    else:
        ans = "{0:02d}".format(ans)
    print("3C"+ans)

```


p00469 Lining up the cards

problem

Hanako is playing with n (4 ≤ n ≤ 10) cards side by side. Each card has one integer between 1 and 99. Hanako chose k cards (2 ≤ k ≤ 4) from these cards and arranged them in a horizontal row to make an integer. How many kinds of integers can Hanako make in total?

For example, consider that you are given five cards of 1, 2, 3, 13, 21 and choose three of them to make an integer. By arranging 2, 1, and 13 in this order, we can make an integer 2113. Also, by arranging 21, 1, and 3 in this order, the same integer 2113 can be created. In this way, the same integer may be created from a combination of different cards.

Given the integers written on n cards, create a program to find the number of integers that can be created by selecting k cards from them and arranging them in a horizontal row.

input

The input consists of multiple datasets. Each dataset is given in the following format.

Each dataset consists of 2 + n rows. The number of cards n (4 ≤ n ≤ 10) is written on the first line, and the number of cards to be selected k (2 ≤ k ≤ 4) is written on the second line. On the 2 + i line (1 ≤ i ≤ n), the integer from 1 to 99 written on the i-th card is written.

When both n and k are 0, it indicates the end of input. The number of data sets does not exceed 5.

output

For each data set, the number of integers that Hanako can create is output on one line.

Examples

Input

4
2
1
2
12
1
6
3
72
2
12
7
2
1
0
0

Output

7
68

Input

None

Output

None

```python
import itertools

while(True):
  n = int(input())
  k = int(input())
  if (n,k) == (0,0):
    break
  num_lis = []
  for _ in range(n):
    num_lis.append(input())
  word_list = []

  for item in list(itertools.permutations(num_lis,k)):
    word_list.append("".join(item))

  print(len(set(word_list)))

```


p00661 Time Manipulation

She is an apprentice wizard. She first learned the magic of manipulating time. And she decided to open a liquor store to earn a living. It has to do with the fact that all the inhabitants of the country where she lives love alcohol. Residents especially like sake that has been aged for many years, and its value increases proportionally with the number of years it has been aged. It's easy to imagine that 100-year-old liquor is more valuable than 50-year-old liquor. And it's also difficult to get. She used her magic to instantly make a long-aged liquor and sell it to earn money.

She priced the sake according to the number of years it was aged. For example, if you need 5 years of aging, you will have to pay 5 emers, and if you have 100 years of aging, you will have to pay 100 emers. For her, making either one uses the same magic, so there is no difference. A long-term aging order is better for her.

Since she is still immature, there are two restrictions on the magic that can be used now. She can't age sake for more than n years now. Also, there are m integers, and it is impossible for her to age sake for those and multiple years.

She is worried if she can live only by running a liquor store. She cannot predict how much income she will earn. So I decided to decide if I needed to do another job based on my expected daily income. Fortunately, she can grow vegetables, take care of pets, cook, sew, carpentry, and so on, so even if she has a small income at a liquor store, she doesn't seem to be in trouble.

It's your job to calculate the expected value of her daily income. The following three may be assumed when calculating the expected value.

Only one order can be accepted per day.
Residents do not order liquor for years that she cannot make.
The number of years of inhabitants' orders is evenly distributed.

Input

The input consists of multiple cases. Each case is given in the following format.

n m
p0 ... pm-1

Residents request liquor that has been aged for the number of years with an integer value between 1 and n.
However, no one asks for m integer pi and its multiples.

The end of the input is given with n = 0 and m = 0.

Each value meets the following conditions
2 ≤ n ≤ 2,000,000,000
1 ≤ m ≤ 20
Also, pi is guaranteed to be divisible by n.

The number of test cases does not exceed 200.

Output

Output the expected value of her daily income.
If there is no possible number of years for the resident's order, output 0 as the expected value of the answer.

The correct answer prepared by the judge and an error of 1e-5 or less are allowed as the correct answer.

Example

Input

12 3
2 3 6
12 4
1 2 3 6
0 0

Output

6.0000000000
0.0000000000

```python
# AOJ 1076 Time Manipulation
# Python3 2018.7.10 bal4u

while True:
	n, m = map(int, input().split())
	if n == 0: break
	p = list(map(int, input().split()))
	if 1 in p: n = 0
	print(n/2)

```


p00935 Decimal Sequences

Example

Input

3
3 0 1

Output

2

```python
j=''.join
u=input
n=int(u())
d=j(j(u().split())for i in[0]*(n//19+(n%19>0)))
i=0
while 1:
 if d.find(str(i))<0:
  print(i)
  exit()
 i+=1
```


p01676 Tree Reconstruction

J - Tree Reconstruction

Problem Statement

You have a directed graph. Some non-negative value is assigned on each edge of the graph. You know that the value of the graph satisfies the flow conservation law That is, for every node v, the sum of values on edges incoming to v equals to the sum of values of edges outgoing from v. For example, the following directed graph satisfies the flow conservation law.

<image>

Suppose that you choose a subset of edges in the graph, denoted by E', and then you erase all the values on edges other than E'. Now you want to recover the erased values by seeing only remaining information. Due to the flow conservation law, it may be possible to recover all the erased values. Your task is to calculate the smallest possible size for such E'.

For example, the smallest subset E' for the above graph will be green edges in the following figure. By the flow conservation law, we can recover values on gray edges.

<image>

Input

The input consists of multiple test cases. The format of each test case is as follows.

N M
s_1 t_1
...
s_M t_M

The first line contains two integers N (1 \leq N \leq 500) and M (0 \leq M \leq 3,000) that indicate the number of nodes and edges, respectively. Each of the following M lines consists of two integers s_i and t_i (1 \leq s_i, t_i \leq N). This means that there is an edge from s_i to t_i in the graph.

You may assume that the given graph is simple:

* There are no self-loops: s_i \neq t_i.
* There are no multi-edges: for all i < j, \\{s_i, t_i\\} \neq \\{s_j, t_j\\}.

Also, it is guaranteed that each component of the given graph is strongly connected. That is, for every pair of nodes v and u, if there exist a path from v to u, then there exists a path from u to v.

Note that you are NOT given information of values on edges because it does not effect the answer.

Output

For each test case, print an answer in one line.

Sample Input 1

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

Output for the Sample Input 1

5

Sample Input 2

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

Output for the Sample Input 2

3

Sample Input 3

4 4
1 2
2 1
3 4
4 3

Output for the Sample Input 3

2

Example

Input

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

Output

5

```python
from collections import deque
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve():
    N, M = map(int, readline().split())
    G = [[] for i in range(N)]
    for i in range(M):
        s, t = map(int, readline().split())
        G[s-1].append(t-1)

    used = [0]*N
    cnt = 0
    ans = 0
    for i in range(N):
        if used[i]:
            continue
        que = deque([i])
        used[i] = 1
        while que:
            v = que.popleft()
            ans += len(G[v])-1
            for w in G[v]:
                if used[w]:
                    continue
                used[w] = 1
                que.append(w)
        ans += 1
    write("%d\n" % ans)
solve()

```


p02240 Connected Components

Write a program which reads relations in a SNS (Social Network Service), and judges that given pairs of users are reachable each other through the network.

Constraints

* $2 \leq n \leq 100,000$
* $0 \leq m \leq 100,000$
* $1 \leq q \leq 10,000$

Input

In the first line, two integer $n$ and $m$ are given. $n$ is the number of users in the SNS and $m$ is the number of relations in the SNS. The users in the SNS are identified by IDs $0, 1, ..., n-1$.

In the following $m$ lines, the relations are given. Each relation is given by two integers $s$ and $t$ that represents $s$ and $t$ are friends (and reachable each other).

In the next line, the number of queries $q$ is given. In the following $q$ lines, $q$ queries are given respectively. Each query consists of two integers $s$ and $t$ separated by a space character.

Output

For each query, print "yes" if $t$ is reachable from $s$ through the social network, "no" otherwise.

Example

Input

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

Output

yes
yes
no

```python
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**6)

class LinkedList:
    def __init__(self, n):
        self.n = n
        self.ll = [[] for _ in range(self.n)]

    def link(self, u, v, direction=False):
        self.ll[u].append(v)
        if not direction:
            self.ll[v].append(u)

    def dfs(self):
        self.cc = [None] * self.n

        color = 1
        for u in range(self.n):
            if not self.cc[u]:
                self.dfs_visit(u, color)
                color += 1

    def dfs_visit(self, u, color):
        self.cc[u] = color
        for v in self.ll[u]:
            if not self.cc[v]:
                self.dfs_visit(v, color)

    def check(self, u, v):
        if self.cc[u] == self.cc[v]:
            print('yes')
        else:
            print('no')

if __name__ == '__main__':
    n, m = map(int, input().split())
    ll = LinkedList(n)

    for _ in range(m):
        u, v = map(int, input().split())
        ll.link(u, v)
    ll.dfs()

    q = int(input())
    for _ in range(q):
        u, v = map(int, input().split())
        ll.check(u, v)

```


p02386 Dice IV

Write a program which reads $n$ dices constructed in the same way as Dice I, and determines whether they are all different. For the determination, use the same way as Dice III.

Constraints

* $2 \leq n \leq 100$
* $0 \leq $ the integer assigned to a face $ \leq 100$

Input

In the first line, the number of dices $n$ is given. In the following $n$ lines, six integers assigned to the dice faces are given respectively in the same way as Dice III.

Output

Print "Yes" if given dices are all different, otherwise "No" in a line.

Examples

Input

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

Output

No

Input

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

Output

Yes

```python
ptn=[
  [1,2,3,4,5,6],
  [2,6,3,4,1,5],
  [3,6,5,2,1,4],
  [4,6,2,5,1,3],
  [5,6,4,3,1,2],
  [6,2,4,3,5,1]
]

def diffDice(orgDice, newDice):
  flg = False   # diff
  tmpDice = [0,0,0,0,0,0]
  for i in range(6):
    #newDiceをptn1で並べ替え
    for idx, j in enumerate(ptn[i]):
      tmpDice[idx] = newDice[j-1]

    if orgDice[0] != tmpDice[0] and orgDice[5] != tmpDice[5]:
      continue

    if ((orgDice[0] == tmpDice[0] and orgDice[5] != tmpDice[5]) or
     (orgDice[0] != tmpDice[0] and orgDice[5] == tmpDice[5])):
      continue

    if (
    (orgDice[1:5] == [tmpDice[1],tmpDice[2],tmpDice[3],tmpDice[4]]) or
    (orgDice[1:5] == [tmpDice[3],tmpDice[1],tmpDice[4],tmpDice[2]]) or
    (orgDice[1:5] == [tmpDice[2],tmpDice[4],tmpDice[1],tmpDice[3]]) or
    (orgDice[1:5] == [tmpDice[4],tmpDice[3],tmpDice[2],tmpDice[1]])):
      flg = True
      break
  return flg

n = int(input())
dice1 = list(input().split(" "))
flg=False
for i in range(1,n):
  dice2 = list(input().split(" "))
  flg = diffDice(dice1,dice2)
  if flg == True:
    break

if flg:
  print("No")
else:
  print("Yes")

```


1077_E. Thematic Contests

Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide.

Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.

Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:

  * number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;
  * the total number of problems in all the contests should be maximized.

Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.

Input

The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of problems Polycarp has prepared.

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

Output

Print one integer — the maximum number of problems in the set of thematic contests.

Examples

Input

18
2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10

Output

14

Input

10
6 6 6 3 6 1000000000 3 3 6 6

Output

9

Input

3
1337 1337 1337

Output

3

Note

In the first example the optimal sequence of contests is: 2 problems of the topic 1, 4 problems of the topic 2, 8 problems of the topic 10.

In the second example the optimal sequence of contests is: 3 problems of the topic 3, 6 problems of the topic 6.

In the third example you can take all the problems with the topic 1337 (the number of such problems is 3 so the answer is 3) and host a single contest.

```python
# from collections import Counter as C
# n, k_ = map(int, input().split())
# l = [*map(int, input().split())]

# c = C(l)
# d = {}
# for k, v in c.items():
#     d[v] = d.get(v, []) + [str(k)]

# ld = sorted([(k, v) for k, v in d.items()], reverse = True)

# res = []
# # print(ld)
# for e in ld:
#     res += [e[1]]
#     if e[0] * len(res) >= k_:
#         i = 0
#         while k_ > e[0] * len(res[i]):
#             print((' '.join(res[i]) + ' ') * e[0])
#             i += 1
#             k_ -= e[0] * len(res[i])
#         # if k_:
#         #     print((res[i] + ' ') * k_)
#         exit(0)

from bisect import bisect_left, bisect_right
from collections import Counter as C

n_ = int(input())
l = sorted(C(map(int, input().split())).values())
n = len(l)
i = res = 0

# print(l)

def f(x):
    i = 0
    for m in range(33):
        t = x << m
        i = bisect_left(l, t, i)
        if i == n:
            return t - x
        i += 1

res = 0
for x in range(1, n_ + 1):
    res = max(res, f(x))

print(res)
```


1119_E. Pavel and Triangles

Pavel has several sticks with lengths equal to powers of two.

He has a_0 sticks of length 2^0 = 1, a_1 sticks of length 2^1 = 2, ..., a_{n-1} sticks of length 2^{n-1}.

Pavel wants to make the maximum possible number of triangles using these sticks. The triangles should have strictly positive area, each stick can be used in at most one triangle.

It is forbidden to break sticks, and each triangle should consist of exactly three sticks.

Find the maximum possible number of triangles.

Input

The first line contains a single integer n (1 ≤ n ≤ 300 000) — the number of different lengths of sticks.

The second line contains n integers a_0, a_1, ..., a_{n-1} (1 ≤ a_i ≤ 10^9), where a_i is the number of sticks with the length equal to 2^i.

Output

Print a single integer — the maximum possible number of non-degenerate triangles that Pavel can make.

Examples

Input

5
1 2 2 2 2

Output

3

Input

3
1 1 1

Output

0

Input

3
3 3 3

Output

3

Note

In the first example, Pavel can, for example, make this set of triangles (the lengths of the sides of the triangles are listed): (2^0, 2^4, 2^4), (2^1, 2^3, 2^3), (2^1, 2^2, 2^2).

In the second example, Pavel cannot make a single triangle.

In the third example, Pavel can, for example, create this set of triangles (the lengths of the sides of the triangles are listed): (2^0, 2^0, 2^0), (2^1, 2^1, 2^1), (2^2, 2^2, 2^2).

```python
n = int(input())
a = list(map(int, input().split()))
ans = 0
last = 0
for q in range(len(a)):
    while last > 0 and a[q] >= 2:
        ans += 1
        a[q] -= 2
        last -= 1
    ans += a[q]//3
    last += a[q] % 3
print(ans)

```


1146_B. Hate "A"

Bob has a string s consisting of lowercase English letters. He defines s' to be the string after removing all "a" characters from s (keeping all other characters in the same order). He then generates a new string t by concatenating s and s'. In other words, t=s+s' (look at notes for an example).

You are given a string t. Your task is to find some s that Bob could have used to generate t. It can be shown that if an answer exists, it will be unique.

Input

The first line of input contains a string t (1 ≤ |t| ≤ 10^5) consisting of lowercase English letters.

Output

Print a string s that could have generated t. It can be shown if an answer exists, it is unique. If no string exists, print ":(" (without double quotes, there is no space between the characters).

Examples

Input

aaaaa

Output

aaaaa

Input

aacaababc

Output

:(

Input

ababacacbbcc

Output

ababacac

Input

baba

Output

:(

Note

In the first example, we have s =  "aaaaa", and s' =  "".

In the second example, no such s can work that will generate the given t.

In the third example, we have s =  "ababacac", and s' =  "bbcc", and t = s + s' =  "ababacacbbcc".

```python
s = input()
s1 = ""
a = 0
for i in s:
    if i == 'a':
        a -= -1
    else:
        s1 += i
if len(s1) % 2:
    print(":(")
    exit()
t = len(s1) // 2
ch = 1
x = len(s) - 1
for i in range(t - 1, -1, -1):
    if s1[i] != s[x]:
        ch = 0
        break
    x += -1
if ch:
    for i in range(len(s) - t): print(s[i], end = "")
else: print(":(")
```


1167_B. Lost Numbers

This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: <https://codeforces.com/blog/entry/45307>.

The jury guessed some array a consisting of 6 integers. There are 6 special numbers — 4, 8, 15, 16, 23, 42 — and each of these numbers occurs in a exactly once (so, a is some permutation of these numbers).

You don't know anything about their order, but you are allowed to ask up to 4 queries. In each query, you may choose two indices i and j (1 ≤ i, j ≤ 6, i and j are not necessarily distinct), and you will get the value of a_i ⋅ a_j in return.

Can you guess the array a?

The array a is fixed beforehand in each test, the interaction program doesn't try to adapt to your queries.

Interaction

Before submitting the answer, you may ask up to 4 queries. To ask a query, print one line in the following format: ? i j, where i and j should be two integers such that 1 ≤ i, j ≤ 6. The line should be ended with a line break character. After submitting a query, flush the output and read the answer to your query — one line containing one integer a_i ⋅ a_j. If you submit an incorrect query (or ask more than 4 queries), the answer to it will be one string 0. After receiving such an answer, your program should terminate immediately — otherwise you may receive verdict "Runtime error", "Time limit exceeded" or some other verdict instead of "Wrong answer".

To give the answer, your program should print one line ! a_1 a_2 a_3 a_4 a_5 a_6 with a line break in the end. After that, it should flush the output and terminate gracefully.

Example

Input

16
64
345
672

Output

? 1 1
? 2 2
? 3 5
? 4 6
! 4 8 15 16 23 42

Note

If you want to submit a hack for this problem, your test should contain exactly six space-separated integers a_1, a_2, ..., a_6. Each of 6 special numbers should occur exactly once in the test. The test should be ended with a line break character.

```python
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 15 18:26:08 2019

@author: Hamadeh
"""

class LLNode:
    def __init__(self, data):
        self.data = data
        self.next = None
        self.prev = None

# Class to create a Doubly Linked List
class LL:

    # Constructor for empty Doubly Linked List
    def __init__(self):
        self.head = None

    # Given a reference to the head of a list and an
    # integer, inserts a new node on the front of list
    def push(self, new_data):

        # 1. Allocates node
        # 2. Put the data in it
        new_node = LLNode(new_data)

        # 3. Make next of new node as head and
        # previous as None (already None)
        new_node.next = self.head

        # 4. change prev of head node to new_node
        if self.head is not None:
            self.head.prev = new_node

        # 5. move the head to point to the new node
        self.head = new_node

    # Given a node as prev_node, insert a new node after
    # the given node
    def insertAfter(self, prev_node, new_data):

        # 1. Check if the given prev_node is None
        if prev_node is None:
            print ("the given previous node cannot be NULL")
            return

        # 2. allocate new node
        # 3. put in the data
        new_node = LLNode(new_data)

        # 4. Make net of new node as next of prev node
        new_node.next = prev_node.next

        # 5. Make prev_node as previous of new_node
        prev_node.next = new_node

        # 6. Make prev_node ass previous of new_node
        new_node.prev = prev_node

        # 7. Change previous of new_nodes's next node
        if new_node.next is not None:
            new_node.next.prev = new_node
        return new_node

    # Given a reference to the head of DLL and integer,
    # appends a new node at the end
    def append(self, new_data):

        # 1. Allocates node
        # 2. Put in the data
        new_node = LLNode(new_data)

        # 3. This new node is going to be the last node,
        # so make next of it as None
        new_node.next = None

        # 4. If the Linked List is empty, then make the
        # new node as head
        if self.head is None:
            new_node.prev = None
            self.head = new_node
            return

        # 5. Else traverse till the last node
        last = self.head
        while(last.next is not None):
            last = last.next

        # 6. Change the next of last node
        last.next = new_node

        # 7. Make last node as previous of new node
        new_node.prev = last

        return new_node

    # This function prints contents of linked list
    # starting from the given node
    def printList(self, node):

        print ("\nTraversal in forward direction")
        while(node is not None):
            print (" % d" ,(node.data),)
            last = node
            node = node.next

        print ("\nTraversal in reverse direction")
        while(last is not None):
            print (" % d" ,(last.data),)
            last = last.prev
class cinn:
    def __init__(self):
        self.x=[]
    def cin(self,t=int):
        if(len(self.x)==0):
            a=input()
            self.x=a.split()
            self.x.reverse()
        return self.get(t)
    def get(self,t):
        return t(self.x.pop())
    def clist(self,n,t=int): #n is number of inputs, t is type to be casted
        l=[0]*n
        for i in range(n):
            l[i]=self.cin(t)
        return l
    def clist2(self,n,t1=int,t2=int,t3=int,tn=2):
        l=[0]*n
        for i in range(n):
            if(tn==2):
                a1=self.cin(t1)
                a2=self.cin(t2)
                l[i]=(a1,a2)
            elif (tn==3):
                a1=self.cin(t1)
                a2=self.cin(t2)
                a3=self.cin(t3)
                l[i]=(a1,a2,a3)
        return l
    def clist3(self,n,t1=int,t2=int,t3=int):
        return self.clist2(self,n,t1,t2,t3,3)
    def cout(self,i,ans=''):
        if(ans==''):
            print("Case #"+str(i+1)+":", end=' ')
        else:
            print("Case #"+str(i+1)+":",ans)
    def printf(self,thing):
        print(thing,end='')
    def countlist(self,l,s=0,e=None):
        if(e==None):
            e=len(l)
        dic={}
        for el in range(s,e):
            if l[el] not in dic:
                dic[l[el]]=1
            else:
                dic[l[el]]+=1
        return dic
    def talk (self,x):
        print(x,flush=True)
    def dp1(self,k):
        L=[-1]*(k)
        return L
    def dp2(self,k,kk):
        L=[-1]*(k)
        for i in range(k):
            L[i]=[-1]*kk
        return L
c=cinn();
L=[4,8,15,16,23,42]
Lans=[]
c.talk("? 1 2")
p1=c.cin()
c.talk("? 3 4")
p2=c.cin()
c.talk("? 1 5")
p3=c.cin()
c.talk("? 3 6")
p4=c.cin()
a1=0;
a2=0;
a3=0;
a4=0
a5=0
a6=0
for x in L:
    #print(p1//x, p2//x, p3//x,p4//x)
    if p1//x in L and p3//x in L and p1%x==0 and p3%x==0 and x!=p3**0.5 and x!=p1**0.5:
        a1=x
        a2=p1//x
        a5=p3//x
    if(p2//x in L and p4//x in L and p2%x==0 and p4%x==0 and x!=p2**0.5 and x!=p4**0.5):
        a3=x
        a4=p2//x
        a6=p4//x
print("!",a1,a2,a3,a4,a5,a6)

```


1185_E. Polycarp and Snakes

After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n × m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells.

Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only 26 letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed 26.

Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals 1, i.e. each snake has size either 1 × l or l × 1, where l is snake's length. Note that snakes can't bend.

When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.

Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.

Input

The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases to solve. Then t test cases follow.

The first line of the test case description contains two integers n, m (1 ≤ n,m ≤ 2000) — length and width of the checkered sheet of paper respectively.

Next n lines of test case description contain m symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell.

It is guaranteed that the total area of all sheets in one test doesn't exceed 4⋅10^6.

Output

Print the answer for each test case in the input.

In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO.

If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer k (0 ≤ k ≤ 26) — number of snakes. Then print k lines, in each line print four integers r_{1,i}, c_{1,i}, r_{2,i} and c_{2,i} — coordinates of extreme cells for the i-th snake (1 ≤ r_{1,i}, r_{2,i} ≤ n, 1 ≤ c_{1,i}, c_{2,i} ≤ m). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them.

Note that Polycarp starts drawing of snakes with an empty sheet of paper.

Examples

Input

1
5 6
...a..
..bbb.
...a..
.cccc.
...a..

Output

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

Input

3
3 3
...
...
...
4 4
..c.
adda
bbcb
....
3 5
..b..
aaaaa
..b..

Output

YES
0
YES
4
2 1 2 4
3 1 3 4
1 3 3 3
2 2 2 3
NO

Input

2
3 3
...
.a.
...
2 2
bb
cc

Output

YES
1
2 2 2 2
YES
3
1 1 1 2
1 1 1 2
2 1 2 2

```python

def naiveSolve():

    return

from collections import defaultdict
def charToInt(c): #'a'->0
    if c=='.':
        return -1
    return ord(c)-ord('a')

def main():

    t=int(input())
    allans=[]
    for _ in range(t):
        n,m=readIntArr()
        grid=[] # convert all chars to int
        for __ in range(n):
            row=list(input())
            grid.append([charToInt(c) for c in row])

        start=[None]*26
        end=[None]*26
        for i in range(n):
            for j in range(m):
                if grid[i][j]!=-1:
                    if start[grid[i][j]]==None:
                        start[grid[i][j]]=[i,j]
                    end[grid[i][j]]=[i,j]
        while start and start[-1]==None:
            start.pop()
            end.pop()
        if len(start)==0:
            allans.append(['YES'])
            allans.append([0])
            continue

        ok=True
        N=len(start)
        dr,dc=end[N-1] # dummy row and cols for unused chars
        ans=[[dr,dc,dr,dc] for __ in range(N)]
        for i in range(N):
            if start[i]==None: # unused char
                continue
            if start[i][0]!=end[i][0] and start[i][1]!=end[i][1]:
                ok=False
                break
            ans[i]=[*start[i],*end[i]]

        if ok==False:
            allans.append(['NO'])
            continue

        reconstruct=[[-1 for _z in range(m)] for __ in range(n)]
        for i in range(N):
            r1,c1,r2,c2=ans[i]
            if r1==r2:
                for col in range(c1,c2+1):
                    reconstruct[r1][col]=i
            else:
                assert c1==c2
                for row in range(r1,r2+1):
                    reconstruct[row][c1]=i

        # check
        for i in range(n):
            for j in range(m):
                if grid[i][j]!=reconstruct[i][j]:
                    ok=False

        if ok==False:
            allans.append(['NO'])
            continue

        allans.append(['YES'])
        allans.append([N])
        for a in ans:
            for j in range(4):
                a[j]+=1 # 1-index
        allans.extend(ans)

    multiLineArrayOfArraysPrint(allans)

    return

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

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

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

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

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

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

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

from math import gcd,floor,ceil
# from math import floor,ceil # for Python2

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


1204_C. Anna, Svyatoslav and Maps

The main characters have been omitted to be short.

You are given a directed unweighted graph without loops with n vertexes and a path in it (that path is not necessary simple) given by a sequence p_1, p_2, …, p_m of m vertexes; for each 1 ≤ i < m there is an arc from p_i to p_{i+1}.

Define the sequence v_1, v_2, …, v_k of k vertexes as good, if v is a subsequence of p, v_1 = p_1, v_k = p_m, and p is one of the shortest paths passing through the vertexes v_1, …, v_k in that order.

A sequence a is a subsequence of a sequence b if a can be obtained from b by deletion of several (possibly, zero or all) elements. It is obvious that the sequence p is good but your task is to find the shortest good subsequence.

If there are multiple shortest good subsequences, output any of them.

Input

The first line contains a single integer n (2 ≤ n ≤ 100) — the number of vertexes in a graph.

The next n lines define the graph by an adjacency matrix: the j-th character in the i-st line is equal to 1 if there is an arc from vertex i to the vertex j else it is equal to 0. It is guaranteed that the graph doesn't contain loops.

The next line contains a single integer m (2 ≤ m ≤ 10^6) — the number of vertexes in the path.

The next line contains m integers p_1, p_2, …, p_m (1 ≤ p_i ≤ n) — the sequence of vertexes in the path. It is guaranteed that for any 1 ≤ i < m there is an arc from p_i to p_{i+1}.

Output

In the first line output a single integer k (2 ≤ k ≤ m) — the length of the shortest good subsequence. In the second line output k integers v_1, …, v_k (1 ≤ v_i ≤ n) — the vertexes in the subsequence. If there are multiple shortest subsequences, print any. Any two consecutive numbers should be distinct.

Examples

Input

4
0110
0010
0001
1000
4
1 2 3 4

Output

3
1 2 4

Input

4
0110
0010
1001
1000
20
1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4

Output

11
1 2 4 2 4 2 4 2 4 2 4

Input

3
011
101
110
7
1 2 3 1 3 2 1

Output

7
1 2 3 1 3 2 1

Input

4
0110
0001
0001
1000
3
1 2 4

Output

2
1 4

Note

Below you can see the graph from the first example:

<image>

The given path is passing through vertexes 1, 2, 3, 4. The sequence 1-2-4 is good because it is the subsequence of the given path, its first and the last elements are equal to the first and the last elements of the given path respectively, and the shortest path passing through vertexes 1, 2 and 4 in that order is 1-2-3-4. Note that subsequences 1-4 and 1-3-4 aren't good because in both cases the shortest path passing through the vertexes of these sequences is 1-3-4.

In the third example, the graph is full so any sequence of vertexes in which any two consecutive elements are distinct defines a path consisting of the same number of vertexes.

In the fourth example, the paths 1-2-4 and 1-3-4 are the shortest paths passing through the vertexes 1 and 4.

```python
from collections import deque
n = int(input())
graph = [list(map(lambda bit: bit == '1', list(input()))) for _ in range(n)]
m = int(input())
way = list(map(lambda i: int(i) - 1, input().split()))
#print(graph)

def dfs(start):
    queue = deque([start])
    d = [-1] * n
    d[start] = 0
    while len(queue) != 0:
        u = queue[0]
        queue.popleft()
        for v in range(n):
            if graph[u][v] and d[v] == -1:
                d[v] = d[u] + 1
                queue.append(v)
    return d

minpath = list(map(dfs, range(n)))
good = [way[0]]
checkp = way[0]
for i in range(1, m):
    prev = way[i - 1]
    if minpath[checkp][way[i]] != minpath[checkp][prev] + 1:
        good.append(prev)
        checkp = prev
#print(minpath)
good.append(way[-1])
print(len(good))
print(' '.join([str(p + 1) for p in good]))

```


1221_A. 2048 Game

You are playing a variation of game 2048. Initially you have a multiset s of n integers. Every integer in this multiset is a power of two.

You may perform any number (possibly, zero) operations with this multiset.

During each operation you choose two equal integers from s, remove them from s and insert the number equal to their sum into s.

For example, if s = \{1, 2, 1, 1, 4, 2, 2\} and you choose integers 2 and 2, then the multiset becomes \{1, 1, 1, 4, 4, 2\}.

You win if the number 2048 belongs to your multiset. For example, if s = \{1024, 512, 512, 4\} you can win as follows: choose 512 and 512, your multiset turns into \{1024, 1024, 4\}. Then choose 1024 and 1024, your multiset turns into \{2048, 4\} and you win.

You have to determine if you can win this game.

You have to answer q independent queries.

Input

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

The first line of each query contains one integer n (1 ≤ n ≤ 100) — the number of elements in multiset.

The second line of each query contains n integers s_1, s_2, ..., s_n (1 ≤ s_i ≤ 2^{29}) — the description of the multiset. It is guaranteed that all elements of the multiset are powers of two.

Output

For each query print YES if it is possible to obtain the number 2048 in your multiset, and NO otherwise.

You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).

Example

Input

6
4
1024 512 64 512
1
2048
3
64 512 2
2
4096 4
7
2048 2 2048 2048 2048 2048 2048
2
2048 4096

Output

YES
YES
NO
NO
YES
YES

Note

In the first query you can win as follows: choose 512 and 512, and s turns into \{1024, 64, 1024\}. Then choose 1024 and 1024, and s turns into \{2048, 64\} and you win.

In the second query s contains 2048 initially.

```python
q=int(input())
for i in range(q):
    n=int(input())
    lst2=[]
    lst1=list(map(int,input().split()))
    for i in range(len(lst1)):
        if lst1[i]<=2048:
            lst2.append(lst1[i])
    sum1=sum(lst2)
    if sum1>=2048:
        print("YES")
    else:
        print("NO")
```


1266_B. Dice Tower

Bob is playing with 6-sided dice. A net of such standard cube is shown below.

<image>

He has an unlimited supply of these dice and wants to build a tower by stacking multiple dice on top of each other, while choosing the orientation of each dice. Then he counts the number of visible pips on the faces of the dice.

For example, the number of visible pips on the tower below is 29 — the number visible on the top is 1, from the south 5 and 3, from the west 4 and 2, from the north 2 and 4 and from the east 3 and 5.

<image>

The one at the bottom and the two sixes by which the dice are touching are not visible, so they are not counted towards total.

Bob also has t favourite integers x_i, and for every such integer his goal is to build such a tower that the number of visible pips is exactly x_i. For each of Bob's favourite integers determine whether it is possible to build a tower that has exactly that many visible pips.

Input

The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of favourite integers of Bob.

The second line contains t space-separated integers x_i (1 ≤ x_i ≤ 10^{18}) — Bob's favourite integers.

Output

For each of Bob's favourite integers, output "YES" if it is possible to build the tower, or "NO" otherwise (quotes for clarity).

Example

Input

4
29 34 19 38

Output

YES
YES
YES
NO

Note

The first example is mentioned in the problem statement.

In the second example, one can build the tower by flipping the top dice from the previous tower.

In the third example, one can use a single die that has 5 on top.

The fourth example is impossible.

```python
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 18 14:08:47 2020

@author: Varun
"""

from sys import stdin, stdout

stdin.readline()

numbers = map(int, stdin.readline().split())

def check(n):
    if n < 15:
        return False
    m = n%14
    return 1 <= m <= 6

for el in numbers:
    if check(el):
        stdout.write("YES")
    else:
        stdout.write("NO")
    stdout.write("\n")
```


1287_D. Numbers on Tree

Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i.

<image>Illustration for the second example, the first integer is a_i and the integer in parentheses is c_i

After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of c_i, but he completely forgot which integers a_i were written on the vertices.

Help him to restore initial integers!

Input

The first line contains an integer n (1 ≤ n ≤ 2000) — the number of vertices in the tree.

The next n lines contain descriptions of vertices: the i-th line contains two integers p_i and c_i (0 ≤ p_i ≤ n; 0 ≤ c_i ≤ n-1), where p_i is the parent of vertex i or 0 if vertex i is root, and c_i is the number of vertices j in the subtree of vertex i, such that a_j < a_i.

It is guaranteed that the values of p_i describe a rooted tree with n vertices.

Output

If a solution exists, in the first line print "YES", and in the second line output n integers a_i (1 ≤ a_i ≤ {10}^{9}). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all a_i are between 1 and 10^9.

If there are no solutions, print "NO".

Examples

Input

3
2 0
0 2
2 0

Output

YES
1 2 1

Input

5
0 1
1 3
2 1
3 0
2 0

Output

YES
2 3 2 1 2

```python
import sys

# inf = open('input.txt', 'r')
# reader = (line.rstrip() for line in inf)
reader = (line.rstrip() for line in sys.stdin)
input = reader.__next__

n = int(input())
cs = [0] * (n + 1)
ps = [0] * (n + 1)
children = [[] for _ in range(n+1)]
for i in range(1, n+1):
    p, c = map(int, input().split())
    ps[i] = p
    children[p].append(i)
    cs[i] = c

def sortDescendants(v):
    result = []
    pos = cs[v]
    for child in children[v]:
        result += sortDescendants(child)
    if len(result) < pos:
        print('NO')
        sys.exit()
    result.insert(pos, v)
    return result

root = children[0][0]
order = sortDescendants(root)
a = [0] * n
for i, v in enumerate(order):
    a[v - 1] = i + 1
print('YES')
print(*a)

# inf.close()

```


1307_D. Cow and Fields

Bessie is out grazing on the farm, which consists of n fields connected by m bidirectional roads. She is currently at field 1, and will return to her home at field n at the end of the day.

The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has k special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.

After the road is added, Bessie will return home on the shortest path from field 1 to field n. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him!

Input

The first line contains integers n, m, and k (2 ≤ n ≤ 2 ⋅ 10^5, n-1 ≤ m ≤ 2 ⋅ 10^5, 2 ≤ k ≤ n) — the number of fields on the farm, the number of roads, and the number of special fields.

The second line contains k integers a_1, a_2, …, a_k (1 ≤ a_i ≤ n) — the special fields. All a_i are distinct.

The i-th of the following m lines contains integers x_i and y_i (1 ≤ x_i, y_i ≤ n, x_i ≠ y_i), representing a bidirectional road between fields x_i and y_i.

It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them.

Output

Output one integer, the maximum possible length of the shortest path from field 1 to n after Farmer John installs one road optimally.

Examples

Input

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

Output

3

Input

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

Output

3

Note

The graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields 3 and 5, and the resulting shortest path from 1 to 5 is length 3.

<image>

The graph for the second example is shown below. Farmer John must add a road between fields 2 and 4, and the resulting shortest path from 1 to 5 is length 3.

<image>

```python
import sys
from collections import deque

reader = (line.rstrip() for line in sys.stdin)
input = reader.__next__

# v(G), e(G), special v
n, m, k = map(int, input().split())
a = list(map(int, input().split()))

# adjacency lists
g = [[] for _ in range(n + 1)]
for _ in range(m):
    v, to = map(int, input().split())
    g[v].append(to)
    g[to].append(v)

dist_1 = [float('inf')] * (n + 1)
s = 1  # start vertex
dist_1[s] = 0
queue = deque([s])
while queue:
    v = queue.pop()
    for to in g[v]:
        if dist_1[to] > dist_1[v] + 1:
            dist_1[to] = dist_1[v] + 1
            queue.appendleft(to)

dist_n = [float('inf')] * (n + 1)
s = n  # start vertex
dist_n[s] = 0
queue = deque([s])
while queue:
    v = queue.pop()
    for to in g[v]:
        if dist_n[to] > dist_n[v] + 1:
            dist_n[to] = dist_n[v] + 1
            queue.appendleft(to)

a.sort(key=dist_1.__getitem__)
# print(dist_1)
# print(a)
# print(dist_n)

class SegmTree():
    def __init__(self, size):
        N = 1
        while N < size:
            N <<= 1
        self.N = N
        self.tree = [-float('inf')] * (2*self.N)

    def modify(self, i, value):
        i += self.N
        self.tree[i] = value
        while i > 1:
            self.tree[i>>1] = max(self.tree[i], self.tree[i^1])
            i >>= 1

    def query_range(self, l, r):
        l += self.N
        r += self.N
        result = -float('inf')
        while l < r:
            if l & 1:
                result = max(result, self.tree[l])
                l += 1
            if r & 1:
                r -= 1
                result = max(result, self.tree[r])
            l >>= 1
            r >>= 1
        return result

st = SegmTree(n + 1)
for v in a:
    st.modify(v, dist_n[v])
longestPossible = 0
for v in a:
    st.modify(v, -float('inf'))
    dist = dist_1[v] + 1 + st.query_range(0, n + 1)
    longestPossible = max(longestPossible, dist)
shortDist = min(dist_1[n], longestPossible)

print(shortDist)

```


1330_D. Dreamoon Likes Sequences

Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS:

You are given two integers d, m, find the number of arrays a, satisfying the following constraints:

  * The length of a is n, n ≥ 1
  * 1 ≤ a_1 < a_2 < ... < a_n ≤ d
  * Define an array b of length n as follows: b_1 = a_1, ∀ i > 1, b_i = b_{i - 1} ⊕ a_i, where ⊕ is the bitwise exclusive-or (xor). After constructing an array b, the constraint b_1 < b_2 < ... < b_{n - 1} < b_n should hold.

Since the number of possible arrays may be too large, you need to find the answer modulo m.

Input

The first line contains an integer t (1 ≤ t ≤ 100) denoting the number of test cases in the input.

Each of the next t lines contains two integers d, m (1 ≤ d, m ≤ 10^9).

Note that m is not necessary the prime!

Output

For each test case, print the number of arrays a, satisfying all given constrains, modulo m.

Example

Input

10
1 1000000000
2 999999999
3 99999998
4 9999997
5 999996
6 99995
7 9994
8 993
9 92
10 1

Output

1
3
5
11
17
23
29
59
89
0

```python
t = int(input())
for _ in range(t):
	d, m = map(int, input().split())
	a = []
	i = 0
	while d > (1<<(i+1))-1:
		a.append(1<<i)
		i += 1
	a.append((1<<i) - (1<<(i+1)) + d + 1)
	#print(a)
	ans = 1
	for x in a:
		ans *= x+1
		ans %= m
	print((ans-1)%m)
```


1350_D. Orac and Medians

Slime has a sequence of positive integers a_1, a_2, …, a_n.

In one operation Orac can choose an arbitrary subsegment [l … r] of this sequence and replace all values a_l, a_{l + 1}, …, a_r to the value of median of \\{a_l, a_{l + 1}, …, a_r\}.

In this problem, for the integer multiset s, the median of s is equal to the ⌊ (|s|+1)/(2)⌋-th smallest number in it. For example, the median of \{1,4,4,6,5\} is 4, and the median of \{1,7,5,8\} is 5.

Slime wants Orac to make a_1 = a_2 = … = a_n = k using these operations.

Orac thinks that it is impossible, and he does not want to waste his time, so he decided to ask you if it is possible to satisfy the Slime's requirement, he may ask you these questions several times.

Input

The first line of the input is a single integer t: the number of queries.

The first line of each query contains two integers n\ (1≤ n≤ 100 000) and k\ (1≤ k≤ 10^9), the second line contains n positive integers a_1,a_2,...,a_n\ (1≤ a_i≤ 10^9)

The total sum of n is at most 100 000.

Output

The output should contain t lines. The i-th line should be equal to 'yes' if it is possible to make all integers k in some number of operations or 'no', otherwise. You can print each letter in lowercase or uppercase.

Example

Input

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

Output

no
yes
yes
no
yes

Note

In the first query, Orac can't turn all elements into 3.

In the second query, a_1=6 is already satisfied.

In the third query, Orac can select the complete array and turn all elements into 2.

In the fourth query, Orac can't turn all elements into 3.

In the fifth query, Orac can select [1,6] at first and then select [2,10].

```python
# Template 1.0
import sys, re, math
from collections import deque, defaultdict, Counter, OrderedDict
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, gcd
from heapq import heappush, heappop, heapify, nlargest, nsmallest
def STR(): return list(input())
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def list2d(a, b, c): return [[c] * b for i in range(a)]
def sortListWithIndex(listOfTuples, idx):   return (sorted(listOfTuples, key=lambda x: x[idx]))
def sortDictWithVal(passedDic):
    temp = sorted(passedDic.items(), key=lambda kv: (kv[1], kv[0]))
    toret = {}
    for tup in temp:
        toret[tup[0]] = tup[1]
    return toret
def sortDictWithKey(passedDic):
    return dict(OrderedDict(sorted(passedDic.items())))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

def check(idx):
    up = down = 0
    a1,a2,a3 = sorted(a[idx:idx+3])
    return (a1<=a2<=a3 and a2>=k)

t = INT()

while(t!=0):
    n,k = MAP()

    a = LIST()

    if(k in a):
        flag = 1
    else:
        flag = 0
    if(flag==1):
        for patchStart in range(n-2):
            if(check(patchStart)):
                flag = 1
                break
            else:
                flag=0
                continue

        if(n==2):
            foo = 0
            for el in a:
                if(el>=k):
                    foo+=1
            if(foo==2):
                print("yes")
            else:
                print("no")
        else:
            if (flag == 0):
                print("no")
            else:
                print("yes")

    else:
        print("no")

    t-=1
```


1393_C. Pinkie Pie Eats Patty-cakes

Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.

Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.

Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!

Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags!

Input

The first line contains a single integer T (1 ≤ T ≤ 100): the number of bags for which you need to solve the problem.

The first line of each bag description contains a single integer n (2 ≤ n ≤ 10^5): the number of patty-cakes in it. The second line of the bag description contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling.

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

Output

For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag.

Example

Input

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

Output

3
2
0
4

Note

For the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): 1, 6, 4, 7, 1, 6, 4 (in this way, the minimum distance is equal to 3).

For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): 1, 4, 6, 7, 4, 1, 6, 4 (in this way, the minimum distance is equal to 2).

```python
def solve(n,ar):

    freq = [0] * 200000

    for i in range(n):
        freq[ar[i]] += 1

    maxi = 0
    max_freq = 0

    for i in range(len(freq)):
        if maxi < freq[i]:
            maxi = max(maxi,freq[i])
            max_freq = 1

        elif freq[i] == maxi:
            max_freq += 1

    print((n-max_freq)//(maxi-1) -1)

if __name__ == '__main__':
    t = int(input())
    for _ in range(t):
        n = int(input())
        ar = list(map(int,input().split()))

        solve(n,ar)
```


1418_B. Negative Prefixes

You are given an array a, consisting of n integers.

Each position i (1 ≤ i ≤ n) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.

For example, let a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}], the underlined positions are locked. You can obtain the following arrays:

  * [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}];
  * [-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}];
  * [1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}];
  * [1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}];
  * and some others.

Let p be a sequence of prefix sums of the array a after the rearrangement. So p_1 = a_1, p_2 = a_1 + a_2, p_3 = a_1 + a_2 + a_3, ..., p_n = a_1 + a_2 + ... + a_n.

Let k be the maximum j (1 ≤ j ≤ n) such that p_j < 0. If there are no j such that p_j < 0, then k = 0.

Your goal is to rearrange the values in such a way that k is minimum possible.

Output the array a after the rearrangement such that the value k for it is minimum possible. If there are multiple answers then print any of them.

Input

The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of testcases.

Then t testcases follow.

The first line of each testcase contains a single integer n (1 ≤ n ≤ 100) — the number of elements in the array a.

The second line of each testcase contains n integers a_1, a_2, ..., a_n (-10^5 ≤ a_i ≤ 10^5) — the initial array a.

The third line of each testcase contains n integers l_1, l_2, ..., l_n (0 ≤ l_i ≤ 1), where l_i = 0 means that the position i is unlocked and l_i = 1 means that the position i is locked.

Output

Print n integers — the array a after the rearrangement. Value k (the maximum j such that p_j < 0 (or 0 if there are no such j)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones.

If there are multiple answers then print any of them.

Example

Input

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

Output

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

Note

In the first testcase you can rearrange all values however you want but any arrangement will result in k = 0. For example, for an arrangement [1, 2, 3], p=[1, 3, 6], so there are no j such that p_j < 0. Thus, k = 0.

In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.

In the third testcase the prefix sums for the printed array are p = [-8, -14, -13, -9, -5, 2, 0]. The maximum j is 5, thus k = 5. There are no arrangements such that k < 5.

In the fourth testcase p = [-4, -4, -3, 3, 6].

In the fifth testcase p = [-1, 3, 10, 2, 12, 11].

```python
import sys
from sys import stdin
import math
import fractions
#Find Set LSB = (x&(-x)), isPowerOfTwo = (x & (x-1))
def iinput():
    return int(input())
def minput():
    return map(int,input().split())
def linput():
    return list(map(int,input().split()))

def fiinput():
    return int(stdin.readline())
def fminput():
    return map(int,stdin.readline().strip().split())
def flinput():
    return list(map(int,stdin.readline().strip().split()))

for _ in range(iinput()):
    n=iinput()
    list1=linput()
    list2=linput()
    list3=[]
    for i in range(n):
        if(list2[i]==0):
            list3.append(list1[i])
    list3.sort()
    for i in range(n):
        if(list2[i]==0):
            list1[i]=list3.pop()
    print(*list1)

```


1436_A. Reorder

For a given array a consisting of n integers and a given integer m find if it is possible to reorder elements of the array a in such a way that ∑_{i=1}^{n}{∑_{j=i}^{n}{(a_j)/(j)}} equals m? It is forbidden to delete elements as well as insert new elements. Please note that no rounding occurs during division, for example, 5/2=2.5.

Input

The first line contains a single integer t — the number of test cases (1 ≤ t ≤ 100). The test cases follow, each in two lines.

The first line of a test case contains two integers n and m (1 ≤ n ≤ 100, 0 ≤ m ≤ 10^6). The second line contains integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^6) — the elements of the array.

Output

For each test case print "YES", if it is possible to reorder the elements of the array in such a way that the given formula gives the given value, and "NO" otherwise.

Example

Input

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

Output

YES
NO

Note

In the first test case one of the reorders could be [1, 2, 5]. The sum is equal to (1/1 + 2/2 + 5/3) + (2/2 + 5/3) + (5/3) = 8. The brackets denote the inner sum ∑_{j=i}^{n}{(a_j)/(j)}, while the summation of brackets corresponds to the sum over i.

```python
#import numpy as np
#import collections
#import sys
# =============================================================================
#def get_primeFactor(n):
#    res=[1]
#    x=2
#    while x*x<=n:
#        while n%x==0:
#            res.append(x)
#            n//=x
#        x+=1
#    if n>1:res.append(n)
#    return res
#
#def getFactor(n):
#    res={1,n}
#    x=2
#    while x*x<=n:
#        if n%x==0:
#            res.add(x)
#            res.add(n//x)
#        x+=1
#    return res

#for _ in range(int(input())):
#     r,b,g,w=tuple(map(int,input().split()))
#     f=tuple(filter(lambda x:x%2!=0,(r,b,g,w)))
#     if len(f)<=1 or len(f)==4:print("Yes")
#     elif len(f)==2:print("No")
#     else:
#         if w%2==0:print("Yes")
#         elif all(t!=0 for t in (r,b,g) ):print("Yes")
#         else :print("No")
#

for _ in range(int(input())):
    n,m=map(int,input().split())
    ar=map(int,input().split())
    total=sum(ar)
    if total != m:print("NO")
    else: print("YES")

```


1485_F. Copy or Prefix Sum

You are given an array of integers b_1, b_2, …, b_n.

An array a_1, a_2, …, a_n of integers is hybrid if for each i (1 ≤ i ≤ n) at least one of these conditions is true:

  * b_i = a_i, or
  * b_i = ∑_{j=1}^{i} a_j.

Find the number of hybrid arrays a_1, a_2, …, a_n. As the result can be very large, you should print the answer modulo 10^9 + 7.

Input

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

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

The second line of each test case contains n integers b_1, b_2, …, b_n (-10^9 ≤ b_i ≤ 10^9).

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

Output

For each test case, print a single integer: the number of hybrid arrays a_1, a_2, …, a_n modulo 10^9 + 7.

Example

Input

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

Output

3
8
223
1

Note

In the first test case, the hybrid arrays are [1, -2, 1], [1, -2, 2], [1, -1, 1].

In the second test case, the hybrid arrays are [1, 1, 1, 1], [1, 1, 1, 4], [1, 1, 3, -1], [1, 1, 3, 4], [1, 2, 0, 1], [1, 2, 0, 4], [1, 2, 3, -2], [1, 2, 3, 4].

In the fourth test case, the only hybrid array is [0, 0, 0, 1].


1536_B. Prinzessin der Verurteilung

I, Fischl, Prinzessin der Verurteilung, descend upon this land by the call of fate an — Oh, you are also a traveler from another world? Very well, I grant you permission to travel with me.

It is no surprise Fischl speaks with a strange choice of words. However, this time, not even Oz, her raven friend, can interpret her expressions! Maybe you can help us understand what this young princess is saying?

You are given a string of n lowercase Latin letters, the word that Fischl just spoke. You think that the MEX of this string may help you find the meaning behind this message. The MEX of the string is defined as the shortest string that doesn't appear as a contiguous substring in the input. If multiple strings exist, the lexicographically smallest one is considered the MEX. Note that the empty substring does NOT count as a valid MEX.

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

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

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

Find out what the MEX of the string is!

Input

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

The first line of each test case contains an integer n (1 ≤ n ≤ 1000) — the length of the word. The second line for each test case contains a single string of n lowercase Latin letters.

The sum of n over all test cases will not exceed 1000.

Output

For each test case, output the MEX of the string on a new line.

Example

Input

3
28
qaabzwsxedcrfvtgbyhnujmiklop
13
cleanairactbd
10
aannttoonn

Output

ac
f
b

```python
# abc = 'abcdefghijklmnopqrstuvwxy'
# test1_previous = [x + y for x in abc for y in abc if x!='m']

def nextchr(c):
    return chr(ord(c)+1)

def next(s):
    if s == '':
        ans = '.'
    elif s[-1] == 'z':
        ans = next(s[:-1]) + 'a'
    else:
        ans = s[:-1] + nextchr(s[-1])
    return ans

t = int(input())
for _ in range(t):
    # n = len(test_1)
    # a = test_1
    # print(n,a)
    n = int(input())
    a = input()

    one = []
    two = []
    three = []
    for i in range(n):
        one.append(a[i:i+1])
        if i <= n-2:
            two.append(a[i:i+2])
        if i <= n-3:
            three.append(a[i:i+3])

    one.sort()
    two.sort()
    three.sort()

    current_1 = 'a'
    current_2 = 'aa'
    current_3 = 'aaa'

    for x in one:
        if current_1 == x:
            current_1 = next(current_1)
        ans = current_1
    if current_1[0] == '.':
        for x in two:
            if current_2 == x:
                current_2 = next(current_2)
            ans = current_2

    if current_2[0] == '.':
        for x in three:
            if current_3 == x:
                current_3 = next(current_3)
        ans = current_3

    print(ans)

```


163_A. Substring and Subsequence

One day Polycarpus got hold of two non-empty strings s and t, consisting of lowercase Latin letters. Polycarpus is quite good with strings, so he immediately wondered, how many different pairs of "x y" are there, such that x is a substring of string s, y is a subsequence of string t, and the content of x and y is the same. Two pairs are considered different, if they contain different substrings of string s or different subsequences of string t. Read the whole statement to understand the definition of different substrings and subsequences.

The length of string s is the number of characters in it. If we denote the length of the string s as |s|, we can write the string as s = s1s2... s|s|.

A substring of s is a non-empty string x = s[a... b] = sasa + 1... sb (1 ≤ a ≤ b ≤ |s|). For example, "code" and "force" are substrings or "codeforces", while "coders" is not. Two substrings s[a... b] and s[c... d] are considered to be different if a ≠ c or b ≠ d. For example, if s="codeforces", s[2...2] and s[6...6] are different, though their content is the same.

A subsequence of s is a non-empty string y = s[p1p2... p|y|] = sp1sp2... sp|y| (1 ≤ p1 < p2 < ... < p|y| ≤ |s|). For example, "coders" is a subsequence of "codeforces". Two subsequences u = s[p1p2... p|u|] and v = s[q1q2... q|v|] are considered different if the sequences p and q are different.

Input

The input consists of two lines. The first of them contains s (1 ≤ |s| ≤ 5000), and the second one contains t (1 ≤ |t| ≤ 5000). Both strings consist of lowercase Latin letters.

Output

Print a single number — the number of different pairs "x y" such that x is a substring of string s, y is a subsequence of string t, and the content of x and y is the same. As the answer can be rather large, print it modulo 1000000007 (109 + 7).

Examples

Input

aa
aa

Output

5

Input

codeforces
forceofcode

Output

60

Note

Let's write down all pairs "x y" that form the answer in the first sample: "s[1...1] t[1]", "s[2...2] t[1]", "s[1...1] t[2]","s[2...2] t[2]", "s[1...2] t[1 2]".

```python
from sys import stdin
s=[ord(i)-97 for i in stdin.readline().strip()]
s1=[ord(i)-97 for i in stdin.readline().strip()]
n=len(s)
m=len(s1)
mod=1000000007
dp=[[0 for i in range(n)] for j in range(26)]
for i in range(m):
    arr=[0 for j in range(n)]
    for j in range(n):
        if s1[i]==s[j] :
            arr[j]=1
            if j>0 :
                arr[j]=(arr[j]+dp[s[j-1]][j-1])%mod
    for j in range(n):
        dp[s1[i]][j]=(arr[j] +dp[s1[i]][j]) %mod
x=0
for i in dp:
    for j in i:
        x=(x+j)%mod
print(x)

```


183_B. Zoo

The Zoo in the Grid Kingdom is represented by an infinite grid. The Zoo has n observation binoculars located at the OX axis. For each i between 1 and n, inclusive, there exists a single binocular located at the point with coordinates (i, 0). There are m flamingos in the Zoo, located at points with positive coordinates. The flamingos are currently sleeping and you can assume that they don't move.

In order to get a good view over the flamingos, each of the binoculars can be independently rotated to face any angle (not necessarily integer). Then, the binocular can be used to observe all flamingos that is located at the straight line passing through the binocular at the angle it is set. In other words, you can assign each binocular a direction corresponding to any straight line passing through the binocular, and the binocular will be able to see all flamingos located on that line.

Today, some kids from the prestigious Codeforces kindergarten went on a Field Study to the Zoo. Their teacher would like to set each binocular an angle to maximize the number of flamingos that can be seen by the binocular. The teacher is very interested in the sum of these values over all binoculars. Please help him find this sum.

Input

The first line contains two space-separated integers n and m (1 ≤ n ≤ 106, 1 ≤ m ≤ 250), denoting the number of binoculars and the number of flamingos, respectively.

Then m lines follow, the i-th line will contain two space-separated integers xi and yi (1 ≤ xi, yi ≤ 109), which means that the i-th flamingo is located at point (xi, yi).

All flamingos will be located at distinct points.

Output

Print a single integer denoting the maximum total number of flamingos that can be seen by all the binoculars.

Examples

Input

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

Output

11

Note

This picture shows the answer to the example test case.

<image>

```python
def gcd(a,b):
    if b == 0:
        return a
    return gcd(b, a % b)

def normalize_rational(num,den):
    #associate the -ve with the num or cancel -ve sign when both are -ve
    if num ^ den < 0 and num > 0 or num ^ den > 0 and num < 0:
        num = -num; den = -den
    #put it in its simplest form
    g = gcd(abs(num),abs(den))
    num //= g; den //=g
    return (num,den)

from sys import *
l = stdin.readline()
(n,m) = (int(tkn) for tkn in l.split())
xs = [0] * m; ys = [0] * m
#maxhits = [set() for i in range(n+1)]
maxhits = [1] * (n + 1)
maxhits[0] = 0
for i in range(m):
    l = stdin.readline()
    (x,y) = (int(tkn) for tkn in l.split())
    xs[i] = x; ys[i] = y
line_to_points = {}
for i in range(m):
    for j in range(m):
        #m = dy/dx; y = (dy/dx)x + c ==> y.dx = x.dy + c.dx
        #y.dx = x.dy + c'
        #c' = y.dx - x.dy
        #c' = ys[i]*dx - xs[i]*dy
        #Now, at y = 0, x = -c' / dy
        dy = ys[i] - ys[j]; dx = xs[i] - xs[j]
        if dy == 0:
            continue
        #not a special case anymore
        # if dx == 0:
            # if xs[i] > n:
                # continue
            # else:
                # count_seen_from_x = len([x for x in xs if x == xs[i]])
                # maxhits[xs[i]] = max(count_seen_from_x, maxhits[xs[i]])
        else:
            slope = normalize_rational(dy,dx)
            c_prime = ys[i]*dx - xs[i]*dy
            x_intercept = -c_prime / dy
            line = (slope,x_intercept)
            if line in line_to_points:
                #print("line: ", line)
                #print("now: ", points)
                points = line_to_points[line]
                points.add(i); points.add(j)
                #print("after addition: ", points)
                continue

            #if (i == 1 and j == 2):
            #    print(c_prime, x_intercept, dy, dx)
            if int(x_intercept) == x_intercept and x_intercept <= n and x_intercept > 0:
                points = set([i,j])
                line_to_points[line] = points
                #maxhits[int(x_intercept)] = points
                # count_on_line = 2
                # for k in range(m):
                    # if k != i and k != j and ys[k] * dx == xs[k]*dy + c_prime:
                        # count_on_line += 1
                # maxhits[int(x_intercept)] = max(count_on_line, maxhits[int(x_intercept)])
for line,points in line_to_points.items():
    x_intercept = int(line[1])
    maxhits[x_intercept] = max(maxhits[x_intercept],len(points))
#print(maxhits)
#print(sum([max(len(points),1) for points in maxhits]) - 1)
print(sum(maxhits))
```


230_C. Shifts

You are given a table consisting of n rows and m columns. Each cell of the table contains a number, 0 or 1. In one move we can choose some row of the table and cyclically shift its values either one cell to the left, or one cell to the right.

To cyclically shift a table row one cell to the right means to move the value of each cell, except for the last one, to the right neighboring cell, and to move the value of the last cell to the first cell. A cyclical shift of a row to the left is performed similarly, but in the other direction. For example, if we cyclically shift a row "00110" one cell to the right, we get a row "00011", but if we shift a row "00110" one cell to the left, we get a row "01100".

Determine the minimum number of moves needed to make some table column consist only of numbers 1.

Input

The first line contains two space-separated integers: n (1 ≤ n ≤ 100) — the number of rows in the table and m (1 ≤ m ≤ 104) — the number of columns in the table. Then n lines follow, each of them contains m characters "0" or "1": the j-th character of the i-th line describes the contents of the cell in the i-th row and in the j-th column of the table.

It is guaranteed that the description of the table contains no other characters besides "0" and "1".

Output

Print a single number: the minimum number of moves needed to get only numbers 1 in some column of the table. If this is impossible, print -1.

Examples

Input

3 6
101010
000100
100000

Output

3

Input

2 3
111
000

Output

-1

Note

In the first sample one way to achieve the goal with the least number of moves is as follows: cyclically shift the second row to the right once, then shift the third row to the left twice. Then the table column before the last one will contain only 1s.

In the second sample one can't shift the rows to get a column containing only 1s.

```python
def solve(rows):
    all_dists = [0 for _ in range(len(rows[0]))]
    for r in rows:
        dists = [len(r) for _ in r]
        if '1' not in r:
            return -1
        start = r.index('1')
        for i in range(len(r)):
            right = (i+start)%len(r) # going right
            left = (start+2*len(r)-i)%len(r) # going left
            dists[right] = 0 if r[right]=='1' else min(dists[right],dists[(i+start-1)%len(r)]+1)
            dists[left] = 0 if r[left]=='1' else min(dists[left],dists[(start+2*len(r)-i+1)%len(r)]+1)
        for i,c in enumerate(r):
            all_dists[i] += dists[i]
    return min(all_dists)

if __name__ == "__main__":
    n,m = (int(i) for i in input().split())
    rows = [input() for _ in range(n)]
    print(solve(rows))
```


256_B. Mr. Bender and Square

Mr. Bender has a digital table of size n × n, each cell can be switched on or off. He wants the field to have at least c switched on squares. When this condition is fulfilled, Mr Bender will be happy.

We'll consider the table rows numbered from top to bottom from 1 to n, and the columns — numbered from left to right from 1 to n. Initially there is exactly one switched on cell with coordinates (x, y) (x is the row number, y is the column number), and all other cells are switched off. Then each second we switch on the cells that are off but have the side-adjacent cells that are on.

For a cell with coordinates (x, y) the side-adjacent cells are cells with coordinates (x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1).

In how many seconds will Mr. Bender get happy?

Input

The first line contains four space-separated integers n, x, y, c (1 ≤ n, c ≤ 109; 1 ≤ x, y ≤ n; c ≤ n2).

Output

In a single line print a single integer — the answer to the problem.

Examples

Input

6 4 3 1

Output

0

Input

9 3 8 10

Output

2

Note

Initially the first test has one painted cell, so the answer is 0. In the second test all events will go as is shown on the figure. <image>.

```python
x, y, n, c = 0, 0, 0, 0
def suma_impares(m):
	return m * m
def suma_n(m):
	return m * (m - 1) // 2
def cnt(t):
	u, d, l, r = x + t, x - t, y - t, y + t
	suma = t ** 2 + (t + 1) ** 2
	if u > n: suma -= suma_impares(u - n)
	if d < 1: suma -= suma_impares(1 - d)
	if l < 1: suma -= suma_impares(1 - l)
	if r > n: suma -= suma_impares(r - n)
	if 1 - l > x - 1 and 1 - d > y - 1:
		suma += suma_n(2 - l - x)
	if r - n > x - 1 and 1 - d > n - y:
		suma += suma_n(r - n - x + 1)
	if 1 - l > n - x and u - n > y - 1:
		suma += suma_n(1 - l - n + x)
	if u - n > n - y and r - n > n - x:
		suma += suma_n(u - n - n + y)
	return suma

n, x, y, c = input().split()
n, x, y, c = int(n), int(x), int(y), int(c)
#for i in range(10):
#	print(i, cnt(i))
ini, fin = 0, int(1e9)
cont = int(1e9)
while cont > 0:
	m = ini
	paso = cont // 2
	m += paso
	if cnt(m) < c:
		ini = m + 1
		cont -= paso + 1
	else:
		cont = paso
print(ini)
```


27_B. Tournament

The tournament «Sleepyhead-2010» in the rapid falling asleep has just finished in Berland. n best participants from the country have participated in it. The tournament consists of games, each of them is a match between two participants. n·(n - 1) / 2 games were played during the tournament, and each participant had a match with each other participant.

The rules of the game are quite simple — the participant who falls asleep first wins. The secretary made a record of each game in the form «xi yi», where xi and yi are the numbers of participants. The first number in each pair is a winner (i.e. xi is a winner and yi is a loser). There is no draws.

Recently researches form the «Institute Of Sleep» have found that every person is characterized by a value pj — the speed of falling asleep. The person who has lower speed wins. Every person has its own value pj, constant during the life.

It is known that all participants of the tournament have distinct speeds of falling asleep. Also it was found that the secretary made records about all the games except one. You are to find the result of the missing game.

Input

The first line contains one integer n (3 ≤ n ≤ 50) — the number of participants. The following n·(n - 1) / 2 - 1 lines contain the results of the games. Each game is described in a single line by two integers xi, yi (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi и yi are the numbers of the opponents in this game. It is known that during the tournament each of the n participants played n - 1 games, one game with each other participant.

Output

Output two integers x and y — the missing record. If there are several solutions, output any of them.

Examples

Input

4
4 2
4 1
2 3
2 1
3 1

Output

4 3

```python
a = int(input())
d = {}
f = {}
for i in range(a*(a-1)//2-1):
    v, c = map(int, input().split())
    if v not in f:
        f[v] = []
    f[v].append(c)
    if v in d:
        d[v] += 1
    else:
        d[v] = 1
    if c in d:
        d[c] += 1
    else:
        d[c] = 1
s = []
m = 0
for i in range(1, a + 1):
    if d[i] > m:
         m = d[i]
for i in range(1, a + 1):
    if d[i] < m:
        s.append(i)
m = 0
for i in range(1, a + 1):
    if i not in s:
        if s[0] in f and i in f and s[1] in f:
            if i in f[s[1]] and s[0] in f[i]:
                m = 1
                s.reverse()
                break
print(*s)
```


302_A. Eugeny and Array

Eugeny has array a = a1, a2, ..., an, consisting of n integers. Each integer ai equals to -1, or to 1. Also, he has m queries:

  * Query number i is given as a pair of integers li, ri (1 ≤ li ≤ ri ≤ n).
  * The response to the query will be integer 1, if the elements of array a can be rearranged so as the sum ali + ali + 1 + ... + ari = 0, otherwise the response to the query will be integer 0.

Help Eugeny, answer all his queries.

Input

The first line contains integers n and m (1 ≤ n, m ≤ 2·105). The second line contains n integers a1, a2, ..., an (ai = -1, 1). Next m lines contain Eugene's queries. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n).

Output

Print m integers — the responses to Eugene's queries in the order they occur in the input.

Examples

Input

2 3
1 -1
1 1
1 2
2 2

Output

0
1
0

Input

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

Output

0
1
0
1
0

```python
from collections import Counter

num, cases = map(int, input().split())
arr = list(map(int, input().split()))
count = Counter(arr)
minus = count[-1]
plus = count[1]
mn = min(plus, minus)
ans = []
while cases:
    cases -= 1
    a, b = map(int, input().split())

    if (b - a + 1) % 2 != 0:
        ans.append(0)
    elif (b - a + 1) // 2 <= mn:
        ans.append(1)
    else:
        ans.append(0)

print(*ans)

```


34_E. Collisions

On a number line there are n balls. At time moment 0 for each ball the following data is known: its coordinate xi, speed vi (possibly, negative) and weight mi. The radius of the balls can be ignored.

The balls collide elastically, i.e. if two balls weighing m1 and m2 and with speeds v1 and v2 collide, their new speeds will be:

<image>.

Your task is to find out, where each ball will be t seconds after.

Input

The first line contains two integers n and t (1 ≤ n ≤ 10, 0 ≤ t ≤ 100) — amount of balls and duration of the process. Then follow n lines, each containing three integers: xi, vi, mi (1 ≤ |vi|, mi ≤ 100, |xi| ≤ 100) — coordinate, speed and weight of the ball with index i at time moment 0.

It is guaranteed that no two balls have the same coordinate initially. Also each collision will be a collision of not more than two balls (that is, three or more balls never collide at the same point in all times from segment [0;t]).

Output

Output n numbers — coordinates of the balls t seconds after. Output the numbers accurate to at least 4 digits after the decimal point.

Examples

Input

2 9
3 4 5
0 7 8

Output

68.538461538
44.538461538

Input

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

Output

-93.666666667
-74.666666667
-15.666666667

```python
class Ball:
    def __init__(self, x, v, m):
        self.v = v
        self.x = x
        self.m = m

    def move(self, time):
        self.x += self.v * time

    def collisionTime(self, other):
        if self.v == other.v:
            return float("inf")

        t = - (self.x - other.x) / (self.v - other.v)

        if t < 1e-9:
            return float("inf")
        return t

    def __str__(self):
        return "Ball(x={:.2f} v={:.2f} m={:.2f})".format(self.x, self.v, self.m)

def findFirst():
    global nBalls, balls

    minTime = float("inf")
    minPairs = []

    for i in range(nBalls):
        for j in range(i + 1, nBalls):
            time = balls[i].collisionTime(balls[j])
            if time < minTime:
                minTime = time
                minPairs = [(i, j)]
            elif abs(time - minTime) < 1e-9:
                minPairs.append((i, j))

    return minTime, minPairs

def collidePair(i, j):
    global balls

    v1 = balls[i].v
    v2 = balls[j].v

    m1 = balls[i].m
    m2 = balls[j].m

    balls[i].v = ((m1 - m2) * v1 + 2 * m2 * v2) / (m1 + m2)
    balls[j].v = ((m2 - m1) * v2 + 2 * m1 * v1) / (m1 + m2)

nBalls, maxTime = map(int, input().split())

balls = []
for i in range(nBalls):
    x, v, m = map(int, input().split())
    balls.append(Ball(x, v, m))

while True:
    time, pairs = findFirst()
    if time > maxTime:
        break

    for i in range(nBalls):
        balls[i].move(time)

    # print(time, maxTime)
    for i, j in pairs:
        collidePair(i, j)
        # print(i, balls[i], j, balls[j])
    # print()

    maxTime -= time

for ball in balls:
    ball.move(maxTime)
    print("{:.6f}".format(ball.x))

```