868_A. Bark to Unlock

As technologies develop, manufacturers are making the process of unlocking a phone as user-friendly as possible. To unlock its new phone, Arkady's pet dog Mu-mu has to bark the password once. The phone represents a password as a string of two lowercase English letters.

Mu-mu's enemy Kashtanka wants to unlock Mu-mu's phone to steal some sensible information, but it can only bark n distinct words, each of which can be represented as a string of two lowercase English letters. Kashtanka wants to bark several words (not necessarily distinct) one after another to pronounce a string containing the password as a substring. Tell if it's possible to unlock the phone in this way, or not.

Input

The first line contains two lowercase English letters — the password on the phone.

The second line contains single integer n (1 ≤ n ≤ 100) — the number of words Kashtanka knows.

The next n lines contain two lowercase English letters each, representing the words Kashtanka knows. The words are guaranteed to be distinct.

Output

Print "YES" if Kashtanka can bark several words in a line forming a string containing the password, and "NO" otherwise.

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

Examples

Input

ya
4
ah
oy
to
ha

Output

YES

Input

hp
2
ht
tp

Output

NO

Input

ah
1
ha

Output

YES

Note

In the first example the password is "ya", and Kashtanka can bark "oy" and then "ah", and then "ha" to form the string "oyahha" which contains the password. So, the answer is "YES".

In the second example Kashtanka can't produce a string containing password as a substring. Note that it can bark "ht" and then "tp" producing "http", but it doesn't contain the password "hp" as a substring.

In the third example the string "hahahaha" contains "ah" as a substring.

```python
one=input()
num=int(input())
twos=[]
for i in range(num):
  twos.append(input())

if (one in twos) or (one[::-1] in twos):
  print("YES")

else:
  flag1,flag2=False,False
  for i in range(num):
    if twos[i][0]==one[1]:
      flag1=True
    if twos[i][1]==one[0]:
      flag2=True
  if(flag1 and flag2):
    print("YES")
  else:
    print("NO")
```


893_D. Credit Card

Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.

She starts with 0 money on her account.

In the evening of i-th day a transaction ai occurs. If ai > 0, then ai bourles are deposited to Luba's account. If ai < 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.

In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.

It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be «-1».

Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!

Input

The first line contains two integers n, d (1 ≤ n ≤ 105, 1 ≤ d ≤ 109) —the number of days and the money limitation.

The second line contains n integer numbers a1, a2, ... an ( - 104 ≤ ai ≤ 104), where ai represents the transaction in i-th day.

Output

Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.

Examples

Input

5 10
-1 5 0 -5 3

Output

0

Input

3 4
-10 0 20

Output

-1

Input

5 10
-5 0 10 -11 0

Output

2

```python
#Bhargey Mehta (Sophomore)
#DA-IICT, Gandhinagar
import sys, math, queue, bisect
#sys.stdin = open("input.txt", "r")
MOD = 10**9+7
sys.setrecursionlimit(1000000)

n, d = map(int, input().split())
a = list(map(int, input().split()))
p = [0 for i in range(n)]
for i in range(n):
    p[i] = p[i-1]+a[i]
mx = [-1 for i in range(n)]
mx[-1] = p[-1]
for i in range(n-2, -1, -1):
    mx[i] = max(mx[i+1], p[i])
c = 0
ans = 0
for i in range(n):
    p[i] += c
    if p[i] > d:
        print(-1)
        exit()
    if a[i] != 0 or p[i] >= 0: continue

    av = d-(mx[i]+c)
    if -p[i] > av:
        print(-1)
        exit()
    ans += 1
    c = d-mx[i]
print(ans)
```


915_A. Garden

Luba thinks about watering her garden. The garden can be represented as a segment of length k. Luba has got n buckets, the i-th bucket allows her to water some continuous subsegment of garden of length exactly ai each hour. Luba can't water any parts of the garden that were already watered, also she can't water the ground outside the garden.

Luba has to choose one of the buckets in order to water the garden as fast as possible (as mentioned above, each hour she will water some continuous subsegment of length ai if she chooses the i-th bucket). Help her to determine the minimum number of hours she has to spend watering the garden. It is guaranteed that Luba can always choose a bucket so it is possible water the garden.

See the examples for better understanding.

Input

The first line of input contains two integer numbers n and k (1 ≤ n, k ≤ 100) — the number of buckets and the length of the garden, respectively.

The second line of input contains n integer numbers ai (1 ≤ ai ≤ 100) — the length of the segment that can be watered by the i-th bucket in one hour.

It is guaranteed that there is at least one bucket such that it is possible to water the garden in integer number of hours using only this bucket.

Output

Print one integer number — the minimum number of hours required to water the garden.

Examples

Input

3 6
2 3 5

Output

2

Input

6 7
1 2 3 4 5 6

Output

7

Note

In the first test the best option is to choose the bucket that allows to water the segment of length 3. We can't choose the bucket that allows to water the segment of length 5 because then we can't water the whole garden.

In the second test we can choose only the bucket that allows us to water the segment of length 1.

```python
def is_prime(a):
    return all(a % i for i in range(2, a))

n, k = map(int, input().split())
l = [int(x) for x in input().split()]
if is_prime(k):
    if k in l:
        print(1)
    else:
        print(k)
else:
    ll = []
    for i in range(len(l)):
        if k % l[i] == 0:
            ll.append(l[i])
    print(k // max(ll))

```


938_B. Run For Your Prize

You and your friend are participating in a TV show "Run For Your Prize".

At the start of the show n prizes are located on a straight line. i-th prize is located at position ai. Positions of all prizes are distinct. You start at position 1, your friend — at position 106 (and there is no prize in any of these two positions). You have to work as a team and collect all prizes in minimum possible time, in any order.

You know that it takes exactly 1 second to move from position x to position x + 1 or x - 1, both for you and your friend. You also have trained enough to instantly pick up any prize, if its position is equal to your current position (and the same is true for your friend). Carrying prizes does not affect your speed (or your friend's speed) at all.

Now you may discuss your strategy with your friend and decide who will pick up each prize. Remember that every prize must be picked up, either by you or by your friend.

What is the minimum number of seconds it will take to pick up all the prizes?

Input

The first line contains one integer n (1 ≤ n ≤ 105) — the number of prizes.

The second line contains n integers a1, a2, ..., an (2 ≤ ai ≤ 106 - 1) — the positions of the prizes. No two prizes are located at the same position. Positions are given in ascending order.

Output

Print one integer — the minimum number of seconds it will take to collect all prizes.

Examples

Input

3
2 3 9

Output

8

Input

2
2 999995

Output

5

Note

In the first example you take all the prizes: take the first at 1, the second at 2 and the third at 8.

In the second example you take the first prize in 1 second and your friend takes the other in 5 seconds, you do this simultaneously, so the total time is 5.

```python
input()
a=list(map(int,input().split()))
ans=0
for x in a:
    z=min(x-1,1000000-x)
    ans=max(z,ans)
print(ans)

```


963_B. Destruction of a Tree

You are given a tree (a graph with n vertices and n - 1 edges in which it's possible to reach any vertex from any other vertex using only its edges).

A vertex can be destroyed if this vertex has even degree. If you destroy a vertex, all edges connected to it are also deleted.

Destroy all vertices in the given tree or determine that it is impossible.

Input

The first line contains integer n (1 ≤ n ≤ 2·105) — number of vertices in a tree.

The second line contains n integers p1, p2, ..., pn (0 ≤ pi ≤ n). If pi ≠ 0 there is an edge between vertices i and pi. It is guaranteed that the given graph is a tree.

Output

If it's possible to destroy all vertices, print "YES" (without quotes), otherwise print "NO" (without quotes).

If it's possible to destroy all vertices, in the next n lines print the indices of the vertices in order you destroy them. If there are multiple correct answers, print any.

Examples

Input

5
0 1 2 1 2

Output

YES
1
2
3
5
4

Input

4
0 1 2 3

Output

NO

Note

In the first example at first you have to remove the vertex with index 1 (after that, the edges (1, 2) and (1, 4) are removed), then the vertex with index 2 (and edges (2, 3) and (2, 5) are removed). After that there are no edges in the tree, so you can remove remaining vertices in any order.

<image>

```python
from collections import defaultdict,deque
import sys
import bisect
import math
input=sys.stdin.readline
mod=1000000007

def bfs(root,count):
    q=deque([root])
    vis.add(root)
    while q:
        vertex=q.popleft()
        for child in graph[vertex]:
            if ans[child]==0:
                ans[child]=count+1
                count+=1
            if child not in vis:
                q.append(child)
                vis.add(child)

graph=defaultdict(list)
n=int(input())
p=[int(i) for i in input().split() if i!='\n']
if n&1:
    for i in range(n):
        if p[i]!=0:
            graph[p[i]].append(i+1)
            graph[i+1].append(p[i])
    length=[0]*(n+1)
    for i in graph:
        length[i]=len(graph[i])
    CHECK,OBSERVE=1,0
    stack=[(OBSERVE,1,0)]
    ans=[0]*(n+1)
    count=0
    while stack:
        state,vertex,parent=stack.pop()
        if state==OBSERVE:
            stack.append((CHECK,vertex,parent))
            for child in graph[vertex]:
                if child != parent:
                    stack.append((OBSERVE,child,vertex))
        else:
            if length[vertex]%2==0:
                count+=1
                ans[vertex]=count
                length[parent]-=1
    vis=set()
    bfs(1,count)
    out=[0]*(n)
    for i in range(1,n+1):
        out[ans[i]-1]=i
    print('YES')
    for i in out:
        sys.stdout.write(str(i)+'\n')
else:
    print('NO')

```


990_E. Post Lamps

Adilbek's house is located on a street which can be represented as the OX axis. This street is really dark, so Adilbek wants to install some post lamps to illuminate it. Street has n positions to install lamps, they correspond to the integer numbers from 0 to n - 1 on the OX axis. However, some positions are blocked and no post lamp can be placed there.

There are post lamps of different types which differ only by their power. When placed in position x, post lamp of power l illuminates the segment [x; x + l]. The power of each post lamp is always a positive integer number.

The post lamp shop provides an infinite amount of lamps of each type from power 1 to power k. Though each customer is only allowed to order post lamps of exactly one type. Post lamps of power l cost a_l each.

What is the minimal total cost of the post lamps of exactly one type Adilbek can buy to illuminate the entire segment [0; n] of the street? If some lamps illuminate any other segment of the street, Adilbek does not care, so, for example, he may place a lamp of power 3 in position n - 1 (even though its illumination zone doesn't completely belong to segment [0; n]).

Input

The first line contains three integer numbers n, m and k (1 ≤ k ≤ n ≤ 10^6, 0 ≤ m ≤ n) — the length of the segment of the street Adilbek wants to illuminate, the number of the blocked positions and the maximum power of the post lamp available.

The second line contains m integer numbers s_1, s_2, ..., s_m (0 ≤ s_1 < s_2 < ... s_m < n) — the blocked positions.

The third line contains k integer numbers a_1, a_2, ..., a_k (1 ≤ a_i ≤ 10^6) — the costs of the post lamps.

Output

Print the minimal total cost of the post lamps of exactly one type Adilbek can buy to illuminate the entire segment [0; n] of the street.

If illumintaing the entire segment [0; n] is impossible, print -1.

Examples

Input

6 2 3
1 3
1 2 3

Output

6

Input

4 3 4
1 2 3
1 10 100 1000

Output

1000

Input

5 1 5
0
3 3 3 3 3

Output

-1

Input

7 4 3
2 4 5 6
3 14 15

Output

-1

```python
import sys
from array import array

n, m, k = map(int, input().split())
block = list(map(int, input().split()))
a = [0] + list(map(int, input().split()))

if block and block[0] == 0:
    print(-1)
    exit()

prev = array('i', list(range(n)))
for x in block:
    prev[x] = -1

for i in range(1, n):
    if prev[i] == -1:
        prev[i] = prev[i-1]

inf = ans = 10**18

for i in range(1, k+1):
    s = 0
    cost = 0
    while True:
        cost += a[i]
        t = s+i

        if t >= n:
            break
        if prev[t] == s:
            cost = inf
            break
        s = prev[t]

    ans = min(ans, cost)

print(ans if ans < inf else -1)

```


p02613 AtCoder Beginner Contest 173 - Judge Status Summary

Takahashi is participating in a programming contest called AXC002, and he has just submitted his code to Problem A.

The problem has N test cases.

For each test case i (1\leq i \leq N), you are given a string S_i representing the verdict for that test case. Find the numbers of test cases for which the verdict is `AC`, `WA`, `TLE`, and `RE`, respectively.

See the Output section for the output format.

Constraints

* 1 \leq N \leq 10^5
* S_i is `AC`, `WA`, `TLE`, or `RE`.

Input

Input is given from Standard Input in the following format:

N
S_1
\vdots
S_N

Output

Let C_0, C_1, C_2, and C_3 be the numbers of test cases for which the verdict is `AC`, `WA`, `TLE`, and `RE`, respectively. Print the following:

AC x C_0
WA x C_1
TLE x C_2
RE x C_3

Output

Let C_0, C_1, C_2, and C_3 be the numbers of test cases for which the verdict is `AC`, `WA`, `TLE`, and `RE`, respectively. Print the following:

AC x C_0
WA x C_1
TLE x C_2
RE x C_3

Examples

Input

6
AC
TLE
AC
AC
WA
TLE

Output

AC x 3
WA x 1
TLE x 2
RE x 0

Input

10
AC
AC
AC
AC
AC
AC
AC
AC
AC
AC

Output

AC x 10
WA x 0
TLE x 0
RE x 0

```python
n=int(input())
S = []
for i in range(n):
    S.append(input())
for t in ["AC","WA","TLE","RE"]:
    print(f"{t} x {S.count(t)}")
```


p02744 Panasonic Programming Contest 2020 - String Equivalence

In this problem, we only consider strings consisting of lowercase English letters.

Strings s and t are said to be isomorphic when the following conditions are satisfied:

* |s| = |t| holds.
* For every pair i, j, one of the following holds:
* s_i = s_j and t_i = t_j.
* s_i \neq s_j and t_i \neq t_j.

For example, `abcac` and `zyxzx` are isomorphic, while `abcac` and `ppppp` are not.

A string s is said to be in normal form when the following condition is satisfied:

* For every string t that is isomorphic to s, s \leq t holds. Here \leq denotes lexicographic comparison.

For example, `abcac` is in normal form, but `zyxzx` is not since it is isomorphic to `abcac`, which is lexicographically smaller than `zyxzx`.

You are given an integer N. Print all strings of length N that are in normal form, in lexicographically ascending order.

Constraints

* 1 \leq N \leq 10
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

N

Output

Assume that there are K strings of length N that are in normal form: w_1, \ldots, w_K in lexicographical order. Output should be in the following format:

w_1
:
w_K

Output

Assume that there are K strings of length N that are in normal form: w_1, \ldots, w_K in lexicographical order. Output should be in the following format:

w_1
:
w_K

Examples

Input

1

Output

a

Input

2

Output

aa
ab

```python
a='a'
exec('a=[s+chr(c)for s in a for c in range(97,ord(max(s))+2)];'*~-int(input()))
print(*a)
```


p02879 AtCoder Beginner Contest 144 - 9x9

Having learned the multiplication table, Takahashi can multiply two integers between 1 and 9 (inclusive) together. He cannot do any other calculation.

Given are two integers A and B.

If Takahashi can calculate A \times B, print the result; if he cannot, print `-1` instead.

Constraints

* 1 \leq A \leq 20
* 1 \leq B \leq 20
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

If Takahashi can calculate A \times B, print the result; if he cannot, print `-1`.

Examples

Input

2 5

Output

10

Input

5 10

Output

-1

Input

9 9

Output

81

```python
a,b = map(int,input().split())
print(a*b) if(a<=9 and b<=9) else print(-1)

```


p03013 AtCoder Beginner Contest 129 - Typical Stairs

There is a staircase with N steps. Takahashi is now standing at the foot of the stairs, that is, on the 0-th step. He can climb up one or two steps at a time.

However, the treads of the a_1-th, a_2-th, a_3-th, \ldots, a_M-th steps are broken, so it is dangerous to set foot on those steps.

How many are there to climb up to the top step, that is, the N-th step, without setting foot on the broken steps? Find the count modulo 1\ 000\ 000\ 007.

Constraints

* 1 \leq N \leq 10^5
* 0 \leq M \leq N-1
* 1 \leq a_1 < a_2 < ... < a_M \leq N-1

Input

Input is given from Standard Input in the following format:

N M
a_1
a_2
.
.
.
a_M

Output

Print the number of ways to climb up the stairs under the condition, modulo 1\ 000\ 000\ 007.

Examples

Input

6 1
3

Output

4

Input

10 2
4
5

Output

0

Input

100 5
1
23
45
67
89

Output

608200469

```python
n,m = map(int,input().split())
a_list = [int(input()) for _ in range(m)]

dp = [1]*(n+1)

for a in a_list:
    dp[a] = 0

for i in range(2,n+1):
    if dp[i] != 0:
        dp[i] = dp[i-1] + dp[i-2]

print(dp[n]%(10**9+7))
```


p03153 KEYENCE Programming Contest 2019 - Connecting Cities

There are N cities in Republic of AtCoder. The size of the i-th city is A_{i}. Takahashi would like to build N-1 bidirectional roads connecting two cities so that any city can be reached from any other city by using these roads.

Assume that the cost of building a road connecting the i-th city and the j-th city is |i-j| \times D + A_{i} + A_{j}. For Takahashi, find the minimum possible total cost to achieve the objective.

Constraints

* 1 \leq N \leq 2 \times 10^5
* 1 \leq D \leq 10^9
* 1 \leq A_{i} \leq 10^9
* A_{i} and D are integers.

Input

Input is given from Standard Input in the following format:

N D
A_1 A_2 ... A_N

Output

Print the minimum possible total cost.

Examples

Input

3 1
1 100 1

Output

106

Input

3 1000
1 100 1

Output

2202

Input

6 14
25 171 7 1 17 162

Output

497

Input

12 5
43 94 27 3 69 99 56 25 8 15 46 8

Output

658

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

from heapq import heappush, heappop, heapify
from collections import defaultdict

"""
・最小値のある場所を調べる。左右にまたがる辺は結ばない。
・最小値の両隣は必ず最小値と結ぶ。
・結んだあと1点に縮約していく。
"""

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

A = [0] + A + [0] # 番兵

# (value<<32) + (index)
mask = (1<<32)-1
q = [(x<<32)+i for i,x in enumerate(A[1:-1],1)]
heapify(q)
removed = defaultdict(int)

cost = []
while q:
    while q:
        x = q[0]
        if not removed[x]:
            break
        heappop(q); removed[x] -= 1
    if not q:
        break
    x = heappop(q)
    val,ind = x>>32, x&mask
    L = A[ind-1]; R = A[ind+1]
    if L:
        cost.append(L+val+D)
        # Lの値を書き換える
        newL = val+D
        if L > newL:
            A[ind-1] = newL
            removed[(L<<32)+(ind-1)] += 1
            heappush(q,(newL<<32)+(ind-1))
    if R:
        cost.append(R+val+D)
        # Lの値を書き換える
        newR = val+D
        if R > newR:
            A[ind+1] = newR
            removed[(R<<32)+(ind+1)] += 1
            heappush(q,(newR<<32)+(ind+1))
    A[ind] = 0

answer = sum(cost)
print(answer)
```


p03297 AtCoder Grand Contest 026 - rng_10s

Ringo Mart, a convenience store, sells apple juice.

On the opening day of Ringo Mart, there were A cans of juice in stock in the morning. Snuke buys B cans of juice here every day in the daytime. Then, the manager checks the number of cans of juice remaining in stock every night. If there are C or less cans, D new cans will be added to the stock by the next morning.

Determine if Snuke can buy juice indefinitely, that is, there is always B or more cans of juice in stock when he attempts to buy them. Nobody besides Snuke buy juice at this store.

Note that each test case in this problem consists of T queries.

Constraints

* 1 \leq T \leq 300
* 1 \leq A, B, C, D \leq 10^{18}
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

T
A_1 B_1 C_1 D_1
A_2 B_2 C_2 D_2
:
A_T B_T C_T D_T

In the i-th query, A = A_i, B = B_i, C = C_i, D = D_i.

Output

Print T lines. The i-th line should contain `Yes` if Snuke can buy apple juice indefinitely in the i-th query; `No` otherwise.

Examples

Input

14
9 7 5 9
9 7 6 9
14 10 7 12
14 10 8 12
14 10 9 12
14 10 7 11
14 10 8 11
14 10 9 11
9 10 5 10
10 10 5 10
11 10 5 10
16 10 5 10
1000000000000000000 17 14 999999999999999985
1000000000000000000 17 15 999999999999999985

Output

No
Yes
No
Yes
Yes
No
No
Yes
No
Yes
Yes
No
No
Yes

Input

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

Output

No
No
No
No
No
No
Yes
Yes
No
No
No
No
Yes
Yes
Yes
No
No
No
Yes
Yes
Yes
No
No
No

```python
def main():
    import math

    def gcd(a, b):
        while b:
            a, b = b, a % b
        return a
    N = int(input())
    ABCD = [list(map(int, input().split())) for i in range(N)]
    for A,B,C,D in ABCD:
        # 在庫が買う本数以下 or 在庫追加が買う本数以下
        if A < B or D < B:
            print("No")
            continue

        A %= B
        # 在庫が買う本数以下になり、補給出来ない
        if C < A:
            print("No")
            continue
        if B == D:
            print("Yes")
            continue

        flag = True
        #print((B-A-1)%(D-B) ,">", (B-1)-(C+1))
        if (B-A-1)%(gcd(D,B)) <= (B-1)-(C+1):
            flag = False

        print("Yes" if flag else "No")

if __name__ == '__main__':
    main()

```


p03455 AtCoder Beginner Contest 086 - Product

AtCoDeer the deer found two positive integers, a and b. Determine whether the product of a and b is even or odd.

Constraints

* 1 ≤ a,b ≤ 10000
* a and b are integers.

Input

Input is given from Standard Input in the following format:

a b

Output

If the product is odd, print `Odd`; if it is even, print `Even`.

Examples

Input

3 4

Output

Even

Input

1 21

Output

Odd

```python
print("Odd" if sum([int(i) % 2 for i in input().split()])==2 else "Even")
```


p03616 AtCoder Regular Contest 082 - Sandglass

We have a sandglass consisting of two bulbs, bulb A and bulb B. These bulbs contain some amount of sand. When we put the sandglass, either bulb A or B lies on top of the other and becomes the upper bulb. The other bulb becomes the lower bulb.

The sand drops from the upper bulb to the lower bulb at a rate of 1 gram per second. When the upper bulb no longer contains any sand, nothing happens.

Initially at time 0, bulb A is the upper bulb and contains a grams of sand; bulb B contains X-a grams of sand (for a total of X grams).

We will turn over the sandglass at time r_1,r_2,..,r_K. Assume that this is an instantaneous action and takes no time. Here, time t refer to the time t seconds after time 0.

You are given Q queries. Each query is in the form of (t_i,a_i). For each query, assume that a=a_i and find the amount of sand that would be contained in bulb A at time t_i.

Constraints

* 1≤X≤10^9
* 1≤K≤10^5
* 1≤r_1<r_2< .. <r_K≤10^9
* 1≤Q≤10^5
* 0≤t_1<t_2< .. <t_Q≤10^9
* 0≤a_i≤X (1≤i≤Q)
* All input values are integers.

Input

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

X
K
r_1 r_2 .. r_K
Q
t_1 a_1
t_2 a_2
:
t_Q a_Q

Output

For each query, print the answer in its own line.

Examples

Input

180
3
60 120 180
3
30 90
61 1
180 180

Output

60
1
120

Input

100
1
100000
4
0 100
90 100
100 100
101 100

Output

100
10
0
0

Input

100
5
48 141 231 314 425
7
0 19
50 98
143 30
231 55
342 0
365 100
600 10

Output

19
52
91
10
58
42
100

```python
X=int(input())
K=int(input())
r=list(map(int,input().split()))
Q=int(input())
p=[tuple(map(int,input().split())) for i in range(Q)]

N=Q
L=0
R=Q-1
start=0
sign="-"

# N: 処理する区間の長さ

N0 = 2**(N-1).bit_length()
data = [0]*(2*N0)
INF = 0
# 区間[l, r+1)の値をvに書き換える
# vは(t, value)という値にする (新しい値ほどtは大きくなる)
def update(l, r, v):
    L = l + N0; R = r + N0
    while L < R:
        if R & 1:
            R -= 1
            data[R-1] += v

        if L & 1:
            data[L-1] += v
            L += 1
        L >>= 1; R >>= 1
# a_iの現在の値を取得
def query(k):
    k += N0-1
    s = INF
    while k >= 0:
        s += data[k]
        k = (k - 1) // 2
    return s

q=[]
for i in range(Q):
    t,a=p[i]
    p[i]=(a,t,i)

p.sort()
dic=[-1]*Q
for i in range(Q):
    a,t,id=p[i]
    update(i,i+1,a)
    dic[id]=i
    q.append((t,id,0))

for i in range(K):
    q.append((r[i],-1,r[i]-r[i-1]*(i>0)))

q.sort()
ans=[0]*Q
for val,id,c in q:
    if id==-1:
        if sign=="-":
            update(L,R+1,-c)
            while query(L+1)<0 and L<R:
                L+=1
            a=query(L)
            if a<0:
                update(L,L+1,-a)
            start=val
            sign="+"
        else:
            update(L,R+1,c)
            while query(R-1)>X and L<R:
                R-=1
            a=query(R)
            if a>X:
                update(R,R+1,X-a)
            start=val
            sign="-"
    else:
        pid,id=id,dic[id]
        if sign=="-":
            if id<L:
                res=max(query(L)-(val-start),0)
            elif id>R:
                res=max(query(R)-(val-start),0)
            else:
                res=max(query(id)-(val-start),0)
        else:
            if id<L:
                res=min(query(L)+(val-start),X)
            elif id>R:
                res=min(query(R)+(val-start),X)
            else:
                res=min(query(id)+(val-start),X)
        ans[pid]=res

for i in range(Q):
    print(ans[i])

```


p03774 AtCoder Beginner Contest 057 - Checkpoints

There are N students and M checkpoints on the xy-plane.
The coordinates of the i-th student (1 \leq i \leq N) is (a_i,b_i), and the coordinates of the checkpoint numbered j (1 \leq j \leq M) is (c_j,d_j).
When the teacher gives a signal, each student has to go to the nearest checkpoint measured in Manhattan distance.
The Manhattan distance between two points (x_1,y_1) and (x_2,y_2) is |x_1-x_2|+|y_1-y_2|.
Here, |x| denotes the absolute value of x.
If there are multiple nearest checkpoints for a student, he/she will select the checkpoint with the smallest index.
Which checkpoint will each student go to?

Constraints

* 1 \leq N,M \leq 50
* -10^8 \leq a_i,b_i,c_j,d_j \leq 10^8
* All input values are integers.

Input

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

N M
a_1 b_1
:
a_N b_N
c_1 d_1
:
c_M d_M

Output

Print N lines.
The i-th line (1 \leq i \leq N) should contain the index of the checkpoint for the i-th student to go.

Examples

Input

2 2
2 0
0 0
-1 0
1 0

Output

2
1

Input

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

Output

3
1
2

Input

5 5
-100000000 -100000000
-100000000 100000000
100000000 -100000000
100000000 100000000
0 0
0 0
100000000 100000000
100000000 -100000000
-100000000 100000000
-100000000 -100000000

Output

5
4
3
2
1

```python
n,m=map(int,input().split())
p=[list(map(int, input().split())) for _ in range(n)]
c=[list(map(int, input().split())) for _ in range(m)]
for i in p:
    d=[abs(i[0]-c[j][0])+abs(i[1]-c[j][1]) for j in range(len(c))]
    print(d.index(min(d))+1)
```


p03943 AtCoder Beginner Contest 047 - Fighting over Candies

Two students of AtCoder Kindergarten are fighting over candy packs.

There are three candy packs, each of which contains a, b, and c candies, respectively.

Teacher Evi is trying to distribute the packs between the two students so that each student gets the same number of candies. Determine whether it is possible.

Note that Evi cannot take candies out of the packs, and the whole contents of each pack must be given to one of the students.

Constraints

* 1 ≦ a, b, c ≦ 100

Input

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

a b c

Output

If it is possible to distribute the packs so that each student gets the same number of candies, print `Yes`. Otherwise, print `No`.

Examples

Input

10 30 20

Output

Yes

Input

30 30 100

Output

No

Input

56 25 31

Output

Yes

```python
l=sorted(list(map(int,input().split())))
print("Yes" if l[0]+l[1]==l[2] else "No")
```


p00035 Is it Convex?

4 different points on the plane Read the coordinates of $ A (x_a, y_a) $, $ B (x_b, y_b) $, $ C (x_c, y_c) $, $ D (x_d, y_d) $ and read those 4 points Create a program that outputs YES if there is no dent in the quadrangle $ ABCD $ with the coordinates as the vertices, and NO if there is a dent.

A quadrangle with a dent is a quadrangle as shown in Figure 1.

<image>

Input

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

$ x_a $, $ y_a $, $ x_b $, $ y_b $, $ x_c $, $ y_c $, $ x_d $, $ y_d $

$ x_a $, $ y_a $, $ x_b $, $ y_b $, $ x_c $, $ y_c $, $ x_d $, $ y_d $ are -100 or more and 100 or less, respectively, and are given as real numbers.

1 No more than two points can be lined up on a straight line. Also, if you connect the points in the order of input, the coordinates of the points will be input in the order of forming a quadrangle. (That is, the points are not given in the order shown in Figure 2.)

The number of datasets does not exceed 100.

Output

Print YES or NO on one line for each dataset.

Example

Input

0.0,0.0,1.0,0.0,1.0,1.0,0.0,1.0
0.0,0.0,3.0,0.0,1.0,1.0,1.0,3.0

Output

YES
NO

```python
def gai(a,b,c,d):
    S = a*d - b*c
    return(S)
while True:
    try:
        x1,y1,x2,y2,x3,y3,xp,yp  = map(float,input().split(","))
        A1,A2,B1,B2,C1,C2,D1,D2 = x1,y1,x2,y2,x3,y3,xp,yp

        if gai(x1 - x2,y1 - y2,x1 - xp,y1 - yp) < 0 and gai(x2 - x3,y2 - y3,x2 - xp,y2 - yp) < 0 and gai(x3 - x1,y3 - y1,x3 - xp,y3 - yp) < 0:
            print("NO")
        elif gai(x1 - x2,y1 - y2,x1 - xp,y1 - yp) > 0 and gai(x2 - x3,y2 - y3,x2 - xp,y2 - yp) > 0 and gai(x3 - x1,y3 - y1,x3 - xp,y3 - yp) > 0:
            print("NO")
        else:
            x1,y1,x2,y2,x3,y3,xp,yp = A1,A2,B1,B2,D1,D2,C1,C2
            if gai(x1 - x2,y1 - y2,x1 - xp,y1 - yp) < 0 and gai(x2 - x3,y2 - y3,x2 - xp,y2 - yp) < 0 and gai(x3 - x1,y3 - y1,x3 - xp,y3 - yp) < 0:
                print("NO")
            elif gai(x1 - x2,y1 - y2,x1 - xp,y1 - yp) > 0 and gai(x2 - x3,y2 - y3,x2 - xp,y2 - yp) > 0 and gai(x3 - x1,y3 - y1,x3 - xp,y3 - yp) > 0:
                print("NO")
            else:
                x1,y1,x2,y2,x3,y3,xp,yp = A1,A2,D1,D2,C1,C2,B1,B2
                if gai(x1 - x2,y1 - y2,x1 - xp,y1 - yp) < 0 and gai(x2 - x3,y2 - y3,x2 - xp,y2 - yp) < 0 and gai(x3 - x1,y3 - y1,x3 - xp,y3 - yp) < 0:
                    print("NO")
                elif gai(x1 - x2,y1 - y2,x1 - xp,y1 - yp) > 0 and gai(x2 - x3,y2 - y3,x2 - xp,y2 - yp) > 0 and gai(x3 - x1,y3 - y1,x3 - xp,y3 - yp) > 0:
                    print("NO")
                else:
                    x1,y1,x2,y2,x3,y3,xp,yp = D1,D2,B1,B2,C1,C2,A1,A2
                    if gai(x1 - x2,y1 - y2,x1 - xp,y1 - yp) < 0 and gai(x2 - x3,y2 - y3,x2 - xp,y2 - yp) < 0 and gai(x3 - x1,y3 - y1,x3 - xp,y3 - yp) < 0:
                        print("NO")
                    elif gai(x1 - x2,y1 - y2,x1 - xp,y1 - yp) > 0 and gai(x2 - x3,y2 - y3,x2 - xp,y2 - yp) > 0 and gai(x3 - x1,y3 - y1,x3 - xp,y3 - yp) > 0:
                        print("NO")
                    else:
                        print("YES")

    except EOFError:
        break
```


p00167 Bubble Sort

Sorting algorithms for sorting data are basic algorithms indispensable in computer science. For example, as shown in the figure below, the operation of "sorting the elements of an array of integer values in ascending order" is alignment.

<image>

Many alignment algorithms have been devised, but one of the basic algorithms is bubble sort. As an example, let's arrange an array of given integer values in ascending order by bubble sort.

<image>

In bubble sort, each calculation step divides the array into "sorted parts" and "unsorted parts". Initially, the entire array will be the unsorted part.

From the beginning of the unsorted part, compare the adjacent elements (green element in the figure) and swap them so that the larger value is to the right. If the two values are equal, they will not be exchanged.

<image>

Repeat this process until the end of the unsorted part (white element in the figure). Finally, add the end to the sorted part (blue element in the figure) to complete one step.

Repeat this step until the unsorted part has a length of 1.

<image>

<image>

<image>

When the length of the unsorted part becomes 1, the sorting process ends.

Now, let's create a program that takes an array of n numbers as input, sorts the numbers in ascending order from the beginning of the array by the above bubble sort procedure, and outputs the number of exchanges of the required array elements. Please give me.

Input

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

n
a1
a2
::
an

The first line gives the number n (1 ≤ n ≤ 100), and the following n lines give the i-th number ai (1 ≤ ai ≤ 1000000).

The number of datasets does not exceed 20.

Output

Outputs the number of data element exchanges (integer) for each data set on one line.

Example

Input

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

Output

7
0
3

```python
def bubble_sort(n):
    arr = [int(input()) for _ in range(n)]
    cnt = 0
    for i in range(n):
        for j in range(n-1, i, -1):
            if arr[j] < arr[j-1]:
                arr[j], arr[j-1] = arr[j-1], arr[j]
                cnt += 1
    return cnt

while True:
    n = int(input())
    if n == 0: break
    print(bubble_sort(n))

```


p00323 Metal Recycling

PCK, which recycles Aizu's precious metal, Aizunium, has a network all over the country and collects Aizunium with many collection vehicles. This company standardizes the unit of weight and number of lumps for efficient processing.

A unit called "bokko" is used for the weight of the lump. x Bocco's Aidunium weighs 2 x grams. If you compare it to a jewel, it's like a "carat." In addition, the unit called "Marugu" is used for the number of lumps. y Marg is 2y. It's like a "dozen" of items in a box. However, x and y must be integers greater than or equal to 0.

Recovery vehicle i collects ai bocco-weighted aidunium by bi-margue. The collected edunium is put into a furnace and melted to regenerate some lumps of edunium, but try to reduce the number of lumps of edunium as much as possible. At this time, the total weight of the collected Izunium and the total weight of the regenerated Izunium do not change.

Create a program that finds the result that minimizes the number of regenerated Izunium lumps given the weight of the Izunium lumps collected by the recovery vehicle in Bocco units and the number of Marg units.

Input

The input is given in the following format.

N
a1 b1
a2 b2
::
aN bN

The first line gives the number of recovery vehicles N (1 ≤ N ≤ 100000). In the next N lines, the integer ai (0 ≤ ai ≤ 100000) representing the weight in "Bocco" units and the integer bi (0 ≤ bi ≤) representing the number in "Margue" units of the mass of Aidunium collected by the recovery vehicle i. 100000) is given.

Output

The weight in Bocco units and the number in Marg units are output in ascending order of weight so that the number of lumps of Izunium obtained after regeneration is minimized.

Examples

Input

3
2 1
1 3
2 2

Output

3 0
5 0

Input

1
100000 2

Output

100002 0

```python
n = int(input())
size = 200100
total = [0 for _ in range(size)]
for _ in range(n):
  s = sum(map(int, input().split()))
  total[s] += 1

for i in range(size - 1):
  if total[i] % 2:
    print(i, 0)
  total[i + 1] += total[i] // 2

```


p00822 Weather Forecast

You are the God of Wind.

By moving a big cloud around, you can decide the weather: it invariably rains under the cloud, and the sun shines everywhere else.

But you are a benign God: your goal is to give enough rain to every field in the countryside, and sun to markets and festivals. Small humans, in their poor vocabulary, only describe this as “weather forecast”.

You are in charge of a small country, called Paccimc. This country is constituted of 4 × 4 square areas, denoted by their numbers.

<image>

Your cloud is of size 2 × 2, and may not cross the borders of the country.

You are given the schedule of markets and festivals in each area for a period of time.

On the first day of the period, it is raining in the central areas (6-7-10-11), independently of the schedule.

On each of the following days, you may move your cloud by 1 or 2 squares in one of the four cardinal directions (North, West, South, and East), or leave it in the same position. Diagonal moves are not allowed. All moves occur at the beginning of the day.

You should not leave an area without rain for a full week (that is, you are allowed at most 6 consecutive days without rain). You don’t have to care about rain on days outside the period you were given: i.e. you can assume it rains on the whole country the day before the period, and the day after it finishes.

Input

The input is a sequence of data sets, followed by a terminating line containing only a zero.

A data set gives the number N of days (no more than 365) in the period on a single line, followed by N lines giving the schedule for markets and festivals. The i-th line gives the schedule for the i-th day. It is composed of 16 numbers, either 0 or 1, 0 standing for a normal day, and 1 a market or festival day. The numbers are separated by one or more spaces.

Output

The answer is a 0 or 1 on a single line for each data set, 1 if you can satisfy everybody, 0 if there is no way to do it.

Example

Input

1
0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0
7
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 1 0 0 0 0 1 1 0 0 1
0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 1
0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0
0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0
1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1
0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0
7
0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0
0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0
0 1 0 0 0 0 0 1 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 1 0 1 0 0 0 0 1
0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0
15
0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0
0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 1 1 0 1 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0
0 0 1 1 0 0 0 0 0 1 0 0 0 0 0 0
1 1 0 0 0 0 0 0 0 0 1 0 0 1 0 0
0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0
0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0
1 0 0 1 1 0 0 0 0 1 0 1 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 1 0 1 0 1 0 0 0 0 0 0
0

Output

0
1
0
1

```python
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**13
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)

def main():
    rr = []
    mij = []
    for i in range(3):
        mi = []
        for j in range(3):
            mi.append([i*4+j,i*4+j+1,i*4+j+4,i*4+j+5])
        mij.append(mi)

    def f(n):
        a = [LI() for _ in range(n)]
        fs = set()
        def _f(i,j,d,d1,d4,d13,d16):
            if d >= n:
                return True
            key = (i,j,d,d1,d4,d13,d16)
            if key in fs:
                return False
            if i == 0:
                if j == 0:
                    d1 = d
                elif j == 2:
                    d4 = d
            elif i == 2:
                if j == 0:
                    d13 = d
                elif j == 2:
                    d16 = d
            for mm in mij[i][j]:
                if a[d][mm] > 0:
                    fs.add(key)
                    return False
            if d - min([d1,d4,d13,d16]) >= 7:
                fs.add(key)
                return False

            if _f(i,j,d+1,d1,d4,d13,d16):
                return True
            for ni in range(3):
                if i == ni:
                    continue
                if _f(ni,j,d+1,d1,d4,d13,d16):
                    return True
            for nj in range(3):
                if j == nj:
                    continue
                if _f(i,nj,d+1,d1,d4,d13,d16):
                    return True
            fs.add(key)
            return False

        if _f(1,1,0,-1,-1,-1,-1):
            return 1

        return 0

    while True:
        n = I()
        if n == 0:
            break
        rr.append(f(n))

    return '\n'.join(map(str,rr))

print(main())

```


p01086 Short Phrase

Short Phrase

A Short Phrase (aka. Tanku) is a fixed verse, inspired by Japanese poetry Tanka and Haiku. It is a sequence of words, each consisting of lowercase letters 'a' to 'z', and must satisfy the following condition:

> (The Condition for a Short Phrase)
>  The sequence of words can be divided into five sections such that the total number of the letters in the word(s) of the first section is five, that of the second is seven, and those of the rest are five, seven, and seven, respectively.

The following is an example of a Short Phrase.

>
>     do the best
>     and enjoy today
>     at acm icpc
>

In this example, the sequence of the nine words can be divided into five sections (1) "do" and "the", (2) "best" and "and", (3) "enjoy", (4) "today" and "at", and (5) "acm" and "icpc" such that they have 5, 7, 5, 7, and 7 letters in this order, respectively. This surely satisfies the condition of a Short Phrase.

Now, Short Phrase Parnassus published by your company has received a lot of contributions. By an unfortunate accident, however, some irrelevant texts seem to be added at beginnings and ends of contributed Short Phrases. Your mission is to write a program that finds the Short Phrase from a sequence of words that may have an irrelevant prefix and/or a suffix.

Input

The input consists of multiple datasets, each in the following format.

> n
>  w1
>  ...
>  wn
>

Here, n is the number of words, which is a positive integer not exceeding 40; wi is the i-th word, consisting solely of lowercase letters from 'a' to 'z'. The length of each word is between 1 and 10, inclusive. You can assume that every dataset includes a Short Phrase.

The end of the input is indicated by a line with a single zero.

Output

For each dataset, output a single line containing i where the first word of the Short Phrase is wi. When multiple Short Phrases occur in the dataset, you should output the first one.

Sample Input

9
do
the
best
and
enjoy
today
at
acm
icpc
14
oh
yes
by
far
it
is
wow
so
bad
to
me
you
know
hey
15
abcde
fghijkl
mnopq
rstuvwx
yzz
abcde
fghijkl
mnopq
rstuvwx
yz
abcde
fghijkl
mnopq
rstuvwx
yz
0

Output for the Sample Input

1
2
6

Example

Input

9
do
the
best
and
enjoy
today
at
acm
icpc
14
oh
yes
by
far
it
is
wow
so
bad
to
me
you
know
hey
15
abcde
fghijkl
mnopq
rstuvwx
yzz
abcde
fghijkl
mnopq
rstuvwx
yz
abcde
fghijkl
mnopq
rstuvwx
yz
0

Output

1
2
6

```python
tanku = [5, 7, 5, 7, 7]
while True:
  n = int(input())
  if n==0:
    break
  w = [len(input()) for i in range(n)]
  ans = 0
  for i in range(n):
    sum = 0
    k = 0
    for j in range(i, n):
      sum += w[j]
      if sum == tanku[k]:
        sum = 0
        k += 1
        if k==5:
          ans = i+1
          break
      elif sum > tanku[k]:
        break
    if ans:
      break
  print(ans)

```


p01356 Nearest Station

I have n tickets for a train with a rabbit. Each ticket is numbered from 0 to n − 1, and you can use the k ticket to go to p⋅ak + q⋅bk station.

Rabbit wants to go to the all-you-can-eat carrot shop at the station m station ahead of the current station, but wants to walk as short as possible. The stations are lined up at regular intervals. When using, how many stations can a rabbit walk to reach the store?

Input

1 ≤ n, m, a, b, p, q ≤ 1 000 000 000 000 (integer)

Output

Output the number of rabbits that can reach the store on foot at the minimum number of stations in one line.

Examples

Input

6 200 2 3 4 5

Output

1

Input

6 1 2 3 4 5

Output

1

```python
def solve():
    n,m,a,b,p,q = map(int,input().split())
    if a==1 and b==1:
        if (p+q)*n <= m:
            return m - (p+q)*n
        else:
            k = m//(p+q)
            return min(m-k*(p+q),(k+1)*(p+q)-m)
    else:
        ans = m
        for i in range(min(n-1,40),-1,-1):
            f = p*(a**i) + q*(b**i)
            if m < f:
                ans = min(ans, f-m)
            else:
                m -= f
            ans = min(ans,m)
        return ans

def main():
    print(solve())

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


p01538 Kakezan

Taro is an elementary school student who has just learned multiplication. Somehow, he likes multiplication, so when he sees numbers, he wants to multiply. He seems to like to do the following for integers greater than or equal to 0. (Processing flow)

* Procedure 1. If a certain integer n greater than or equal to 0 is a single digit in decimal notation, the process ends there. Otherwise go to step 2
* Step 2. When an integer n of 10 or more is displayed in decimal, it is possible to break it into two numbers by inserting a break between some digits (for example, 2012-> 20, 12). For possible cutting methods like this, multiply the two obtained numbers and set the largest one as the next n, and return to step 1. (For details, see "Supplementary information on step 2" below.)

Taro seems to like this process, but I can't predict how many times step 2 should be repeated, and I think it may have to be done infinitely. So I asked Taro's older brother and college student how many times this step 2 should be done for an integer n greater than or equal to 0.

Your job is to give Q integers greater than or equal to 0 N1 .. NQ, so find out how many steps 2 will be performed on each integer before the end of the process. If you need an infinite number of steps, output -1.

Supplement on step 2

You should also take into account those that have a 0 at the beginning of the digit as a result of the isolation.
For example, when n = 1024, 1 * 024, 10 * 24, and 102 * 4 are calculated as 24,240,408, respectively, so 408 is selected and this is the next n.

Constraints

> 1 ≤ Q ≤ 100
> 0 ≤ Ni ≤ 106
>

Input

> Q
> N1
> N2
> ...
> NQ
>

* Q represents the number of integers greater than or equal to 0 given
* Ni is an integer greater than or equal to 0 that Taro is interested in, and represents the i-th one.

Output

Output Q integers separated by line breaks

> R1
> R2
> ..
> RQ
>

* Ri represents the number of times step 2 is executed before the processing is completed for Ni.
* Ri is -1 if step 2 needs to be performed infinitely for Ni

Examples

Input

3
9
99
123

Output

0
2
3

Input

2
999999
1000000

Output

12
1

```python
"かけざん"
"最大のものを取得して、一桁になるまでに操作を行う回数を答える"

def kakezan(n):
    ret = 0
    str_n = str(n)
    digit_amount = len(str_n)
    for i in range(digit_amount-1):
        # print(str_n[:i+1])
        # print(str_n[i+1:])
        # print("")
        ret = max(ret, int(str_n[:i+1])*int(str_n[i+1:]))

    return ret

Q = int(input())  # 入力される整数の個数
N = [int(input()) for i in range(Q)]

for n in N:
    cnt = 0
    while n >= 10:
        n = kakezan((n))
        cnt += 1
    print(cnt)

```


p01694 Step Aerobics

Step up and down

Kazuki, commonly known as Kerr, who attends JAG University, was invited by your friend this summer to participate in the ICPC (International Collegiate Potchari Contest). ICPC is a sports contest and requires a high degree of athletic ability. However, Mr. Kerr was always in front of the computer, and he was so lacking in exercise that he was tired even if he moved a little. Therefore, Kerr decided to start an easy-to-start exercise, "stepping up and down," as the first step to achieve good results with ICPC.

As the name suggests, stepping up and down is a simple exercise that simply repeats going up and down between the step and the floor. However, in stepping up and down, the effect cannot be obtained unless the feet are raised and lowered correctly. Correct ascent and descent is the movement of the foot that satisfies either of the following two types.

* From the state where both feet are on the floor, the left foot and the right foot are raised on the stepping stone, and both feet are on the stepping stone. Either the left foot or the right foot may be raised first.
* From the state where both feet are on the platform, the left foot and the right foot are lowered to the floor, and both feet are on the floor. Either the left foot or the right foot may be lowered first.

As can be seen from the above, raising and lowering only one leg continuously from the state of being on the floor or stepping stone does not result in correct raising and lowering. In the stepping up / down movement, when any of the above correct up / down movements is satisfied, it is counted as one time, and the larger the count number, the more effective the effect can be obtained. Note that even if you don't go back and forth between the floor and the platform, it counts as one only one way.

You want your teammate, Kerr, to be as strong as possible. So you decided to write a program and check if Kerr was skipping the step up and down. Since the information of the foot that Kerr moved by going up and down the platform is given, find the number of times that he went up and down correctly. However, it is assumed that both feet are on the floor before going up and down the platform.

Input

The input consists of multiple data sets, and the number of data sets contained in one input is 150 or less. The format of each data set is as follows.

> $ n $
> $ f_1 $ $ f_2 $ ... $ f_n $

In the first line, the integer $ n $ ($ 1 \ le n \ le 100 $) representing the number of times the foot is moved is given. In the second line, $ f_i $, which is a character string representing the movement of the foot, is given in chronological order by $ n $, separated by spaces. $ f_i $ is one of the following four types of character strings.

* "lu": Raise your left foot to the platform.
* "ru": Raise your right foot to the platform.
* "ld": Lower your left foot to the floor.
* "rd": Lower your right foot to the floor.

It can be assumed that no action is input that lowers the foot on the floor or raises the foot on the platform.

The line where $ n $ is 0 indicates the end of input. Do not process this data.

Output

For each dataset, output the number of correct steps up and down in one line. Note that if you do not output a line break at the end of each line, or if you output unnecessary characters, it will be judged as an incorrect answer.

Sample Input

Four
lu ru ld rd
Four
lu ld lu ru
1
lu
Ten
ru lu ld rd ru rd ru lu lu rd ld
0

Output for Sample Input

2
1
0
Four

Example

Input

4
lu ru ld rd
4
lu ld lu ru
1
lu
10
ru lu ld rd ru rd ru lu rd ld
0

Output

2
1
0
4


p01974 Pigeonhole principle

problem

Given $ N $ different natural numbers $ a_i $. I decided to make a pair by choosing a different natural number from the given natural numbers. Output one pair that can be created with a value difference that is a multiple of $ N -1 $.

It should be noted that such a pair always exists.

Example

Input

5
1 2 4 7 10

Output

2 10

```python
N = int(input())
a = [int(x) for x in input().split()]

x, y = -1, -1

for i in range(N) :
    for j in range(N) :
        if i != j and abs(a[i] - a[j]) % (N - 1) == 0 :
            x, y = i, j

print(a[x], a[y])

```


p02260 Selection Sort

Write a program of the Selection Sort algorithm which sorts a sequence A in ascending order. The algorithm should be based on the following pseudocode:

SelectionSort(A)
1 for i = 0 to A.length-1
2     mini = i
3     for j = i to A.length-1
4         if A[j] < A[mini]
5             mini = j
6     swap A[i] and A[mini]

Note that, indices for array elements are based on 0-origin.

Your program should also print the number of swap operations defined in line 6 of the pseudocode in the case where i ≠ mini.

Constraints

1 ≤ N ≤ 100

Input

The first line of the input includes an integer N, the number of elements in the sequence.

In the second line, N elements of the sequence are given separated by space characters.

Output

The output consists of 2 lines.

In the first line, please print the sorted sequence. Two contiguous elements of the sequence should be separated by a space character.

In the second line, please print the number of swap operations.

Examples

Input

6
5 6 4 2 1 3

Output

1 2 3 4 5 6
4

Input

6
5 2 4 6 1 3

Output

1 2 3 4 5 6
3

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

indexMin = 0
count = 0

for start in range(n):
    indexMin = s[start:].index(min(s[start:])) + start
    s[start], s[indexMin] = s[indexMin], s[start]
    if start != indexMin:
        count+=1

print(*s)
print(count)

```


p02408 Finding Missing Cards

Taro is going to play a card game. However, now he has only n cards, even though there should be 52 cards (he has no Jokers).

The 52 cards include 13 ranks of each of the four suits: spade, heart, club and diamond.

Note

解説

Input

In the first line, the number of cards n (n ≤ 52) is given.

In the following n lines, data of the n cards are given. Each card is given by a pair of a character and an integer which represent its suit and rank respectively. A suit is represented by 'S', 'H', 'C' and 'D' for spades, hearts, clubs and diamonds respectively. A rank is represented by an integer from 1 to 13.

Output

Print the missing cards. The same as the input format, each card should be printed with a character and an integer separated by a space character in a line. Arrange the missing cards in the following priorities:

* Print cards of spades, hearts, clubs and diamonds in this order.
* If the suits are equal, print cards with lower ranks first.

Example

Input

47
S 10
S 11
S 12
S 13
H 1
H 2
S 6
S 7
S 8
S 9
H 6
H 8
H 9
H 10
H 11
H 4
H 5
S 2
S 3
S 4
S 5
H 12
H 13
C 1
C 2
D 1
D 2
D 3
D 4
D 5
D 6
D 7
C 3
C 4
C 5
C 6
C 7
C 8
C 9
C 10
C 11
C 13
D 9
D 10
D 11
D 12
D 13

Output

S 1
H 3
H 7
C 12
D 8

```python
n=int(input())
cs = [ (s,k) for s in ['S','H','C','D'] for k in range(1,14) ]
for _ in range(n):
    s,k=input().split()
    cs.remove((s,int(k)))
for (s, k) in cs:
    print(s, k)
```


101_C. Vectors

At a geometry lesson Gerald was given a task: to get vector B out of vector A. Besides, the teacher permitted him to perform the following operations with vector А:

  * Turn the vector by 90 degrees clockwise.
  * Add to the vector a certain vector C.

Operations could be performed in any order any number of times.

Can Gerald cope with the task?

Input

The first line contains integers x1 и y1 — the coordinates of the vector A ( - 108 ≤ x1, y1 ≤ 108). The second and the third line contain in the similar manner vectors B and C (their coordinates are integers; their absolute value does not exceed 108).

Output

Print "YES" (without the quotes) if it is possible to get vector B using the given operations. Otherwise print "NO" (without the quotes).

Examples

Input

0 0
1 1
0 1

Output

YES

Input

0 0
1 1
1 1

Output

YES

Input

0 0
1 1
2 2

Output

NO

```python
import math

def ok(xa, ya):
    x, y = xb - xa, yb - ya
    d = math.gcd(abs(xc), abs(yc))
    if xc == 0 and yc == 0:
        return x == 0 and y == 0
    if xc == 0:
        return x % yc == 0 and y % yc == 0
    if yc == 0:
        return x % xc == 0 and y % xc == 0
    if (x % d != 0) or (y % d != 0):
        return 0
    a, b, c1, c2 = xc // d, yc // d, x // d, -y // d
    if a == 0 and b == 0:
        return c1 == 0 and c2 == 0
    if (c1 * b + c2 * a) % (a * a + b * b) != 0:
        return 0
    yy = (c1 * b + c2 * a) / (a * a + b * b)
    if a == 0:
        return (c2 - a * yy) % b == 0
    else:
        return (c1 - b * yy) % a == 0

xa, ya = map(int,input().split())
xb, yb = map(int,input().split())
xc, yc = map(int,input().split())
if ok(xa, ya) or ok(-ya, xa) or ok(-xa, -ya) or ok(ya, -xa):
    print('YES')
else:
    print('NO')

```


1043_A. Elections

Awruk is taking part in elections in his school. It is the final round. He has only one opponent — Elodreip. The are n students in the school. Each student has exactly k votes and is obligated to use all of them. So Awruk knows that if a person gives a_i votes for Elodreip, than he will get exactly k - a_i votes from this person. Of course 0 ≤ k - a_i holds.

Awruk knows that if he loses his life is over. He has been speaking a lot with his friends and now he knows a_1, a_2, ..., a_n — how many votes for Elodreip each student wants to give. Now he wants to change the number k to win the elections. Of course he knows that bigger k means bigger chance that somebody may notice that he has changed something and then he will be disqualified.

So, Awruk knows a_1, a_2, ..., a_n — how many votes each student will give to his opponent. Help him select the smallest winning number k. In order to win, Awruk needs to get strictly more votes than Elodreip.

Input

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

The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 100) — the number of votes each student gives to Elodreip.

Output

Output the smallest integer k (k ≥ max a_i) which gives Awruk the victory. In order to win, Awruk needs to get strictly more votes than Elodreip.

Examples

Input

5
1 1 1 5 1

Output

5

Input

5
2 2 3 2 2

Output

5

Note

In the first example, Elodreip gets 1 + 1 + 1 + 5 + 1 = 9 votes. The smallest possible k is 5 (it surely can't be less due to the fourth person), and it leads to 4 + 4 + 4 + 0 + 4 = 16 votes for Awruk, which is enough to win.

In the second example, Elodreip gets 11 votes. If k = 4, Awruk gets 9 votes and loses to Elodreip.

```python
import math
n = int(input())
l= list(map(int,input().split()))
s = 2*sum(l)
z= s/n
p = max(l)
an = int(z+1)
print(max(p,an))
```


1107_D. Compression

You are given a binary matrix A of size n × n. Let's denote an x-compression of the given matrix as a matrix B of size n/x × n/x such that for every i ∈ [1, n], j ∈ [1, n] the condition A[i][j] = B[⌈ i/x ⌉][⌈ j/x ⌉] is met.

Obviously, x-compression is possible only if x divides n, but this condition is not enough. For example, the following matrix of size 2 × 2 does not have any 2-compression:

01  10

For the given matrix A, find maximum x such that an x-compression of this matrix is possible.

Note that the input is given in compressed form. But even though it is compressed, you'd better use fast input.

Input

The first line contains one number n (4 ≤ n ≤ 5200) — the number of rows and columns in the matrix A. It is guaranteed that n is divisible by 4.

Then the representation of matrix follows. Each of n next lines contains n/4 one-digit hexadecimal numbers (that is, these numbers can be represented either as digits from 0 to 9 or as uppercase Latin letters from A to F). Binary representation of each of these numbers denotes next 4 elements of the matrix in the corresponding row. For example, if the number B is given, then the corresponding elements are 1011, and if the number is 5, then the corresponding elements are 0101.

Elements are not separated by whitespaces.

Output

Print one number: maximum x such that an x-compression of the given matrix is possible.

Examples

Input

8
E7
E7
E7
00
00
E7
E7
E7

Output

1

Input

4
7
F
F
F

Output

1

Note

The first example corresponds to the matrix:

11100111  11100111  11100111  00000000  00000000  11100111  11100111  11100111

It is easy to see that the answer on this example is 1.

```python
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction

mod = 10 ** 9 + 7
mod1 = 998244353

# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

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

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

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

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

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

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

# -------------------game starts now----------------------------------------------------import math
class TreeNode:
    def __init__(self, k, v):
        self.key = k
        self.value = v
        self.left = None
        self.right = None
        self.parent = None
        self.height = 1
        self.num_left = 1
        self.num_total = 1

class AvlTree:

    def __init__(self):
        self._tree = None

    def add(self, k, v):
        if not self._tree:
            self._tree = TreeNode(k, v)
            return
        node = self._add(k, v)
        if node:
            self._rebalance(node)

    def _add(self, k, v):
        node = self._tree
        while node:
            if k < node.key:
                if node.left:
                    node = node.left
                else:
                    node.left = TreeNode(k, v)
                    node.left.parent = node
                    return node.left
            elif node.key < k:
                if node.right:
                    node = node.right
                else:
                    node.right = TreeNode(k, v)
                    node.right.parent = node
                    return node.right
            else:
                node.value = v
                return

    @staticmethod
    def get_height(x):
        return x.height if x else 0

    @staticmethod
    def get_num_total(x):
        return x.num_total if x else 0

    def _rebalance(self, node):

        n = node
        while n:
            lh = self.get_height(n.left)
            rh = self.get_height(n.right)
            n.height = max(lh, rh) + 1
            balance_factor = lh - rh
            n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
            n.num_left = 1 + self.get_num_total(n.left)

            if balance_factor > 1:
                if self.get_height(n.left.left) < self.get_height(n.left.right):
                    self._rotate_left(n.left)
                self._rotate_right(n)
            elif balance_factor < -1:
                if self.get_height(n.right.right) < self.get_height(n.right.left):
                    self._rotate_right(n.right)
                self._rotate_left(n)
            else:
                n = n.parent

    def _remove_one(self, node):
        """
        Side effect!!! Changes node. Node should have exactly one child
        """
        replacement = node.left or node.right
        if node.parent:
            if AvlTree._is_left(node):
                node.parent.left = replacement
            else:
                node.parent.right = replacement
            replacement.parent = node.parent
            node.parent = None
        else:
            self._tree = replacement
            replacement.parent = None
        node.left = None
        node.right = None
        node.parent = None
        self._rebalance(replacement)

    def _remove_leaf(self, node):
        if node.parent:
            if AvlTree._is_left(node):
                node.parent.left = None
            else:
                node.parent.right = None
            self._rebalance(node.parent)
        else:
            self._tree = None
        node.parent = None
        node.left = None
        node.right = None

    def remove(self, k):
        node = self._get_node(k)
        if not node:
            return
        if AvlTree._is_leaf(node):
            self._remove_leaf(node)
            return
        if node.left and node.right:
            nxt = AvlTree._get_next(node)
            node.key = nxt.key
            node.value = nxt.value
            if self._is_leaf(nxt):
                self._remove_leaf(nxt)
            else:
                self._remove_one(nxt)
            self._rebalance(node)
        else:
            self._remove_one(node)

    def get(self, k):
        node = self._get_node(k)
        return node.value if node else -1

    def _get_node(self, k):
        if not self._tree:
            return None
        node = self._tree
        while node:
            if k < node.key:
                node = node.left
            elif node.key < k:
                node = node.right
            else:
                return node
        return None

    def get_at(self, pos):
        x = pos + 1
        node = self._tree
        while node:
            if x < node.num_left:
                node = node.left
            elif node.num_left < x:
                x -= node.num_left
                node = node.right
            else:
                return (node.key, node.value)
        raise IndexError("Out of ranges")

    @staticmethod
    def _is_left(node):
        return node.parent.left and node.parent.left == node

    @staticmethod
    def _is_leaf(node):
        return node.left is None and node.right is None

    def _rotate_right(self, node):
        if not node.parent:
            self._tree = node.left
            node.left.parent = None
        elif AvlTree._is_left(node):
            node.parent.left = node.left
            node.left.parent = node.parent
        else:
            node.parent.right = node.left
            node.left.parent = node.parent
        bk = node.left.right
        node.left.right = node
        node.parent = node.left
        node.left = bk
        if bk:
            bk.parent = node
        node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
        node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
        node.num_left = 1 + self.get_num_total(node.left)

    def _rotate_left(self, node):
        if not node.parent:
            self._tree = node.right
            node.right.parent = None
        elif AvlTree._is_left(node):
            node.parent.left = node.right
            node.right.parent = node.parent
        else:
            node.parent.right = node.right
            node.right.parent = node.parent
        bk = node.right.left
        node.right.left = node
        node.parent = node.right
        node.right = bk
        if bk:
            bk.parent = node
        node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
        node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
        node.num_left = 1 + self.get_num_total(node.left)

    @staticmethod
    def _get_next(node):
        if not node.right:
            return node.parent
        n = node.right
        while n.left:
            n = n.left
        return n
avl=AvlTree()
#-----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
    def __init__(self, data, default='z', func=lambda a, b: min(a ,b)):
        """initialize the segment tree with data"""
        self._default = default
        self._func = func
        self._len = len(data)
        self._size = _size = 1 << (self._len - 1).bit_length()

        self.data = [default] * (2 * _size)
        self.data[_size:_size + self._len] = data
        for i in reversed(range(_size)):
            self.data[i] = func(self.data[i + i], self.data[i + i + 1])

    def __delitem__(self, idx):
        self[idx] = self._default

    def __getitem__(self, idx):
        return self.data[idx + self._size]

    def __setitem__(self, idx, value):
        idx += self._size
        self.data[idx] = value
        idx >>= 1
        while idx:
            self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
            idx >>= 1

    def __len__(self):
        return self._len

    def query(self, start, stop):
        if start == stop:
            return self.__getitem__(start)
        stop += 1
        start += self._size
        stop += self._size

        res = self._default
        while start < stop:
            if start & 1:
                res = self._func(res, self.data[start])
                start += 1
            if stop & 1:
                stop -= 1
                res = self._func(res, self.data[stop])
            start >>= 1
            stop >>= 1
        return res

    def __repr__(self):
        return "SegmentTree({0})".format(self.data)

# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
    def __init__(self, data, default=0, func=lambda a, b: a + b):
        """initialize the segment tree with data"""
        self._default = default
        self._func = func
        self._len = len(data)
        self._size = _size = 1 << (self._len - 1).bit_length()

        self.data = [default] * (2 * _size)
        self.data[_size:_size + self._len] = data
        for i in reversed(range(_size)):
            self.data[i] = func(self.data[i + i], self.data[i + i + 1])

    def __delitem__(self, idx):
        self[idx] = self._default

    def __getitem__(self, idx):
        return self.data[idx + self._size]

    def __setitem__(self, idx, value):
        idx += self._size
        self.data[idx] = value
        idx >>= 1
        while idx:
            self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
            idx >>= 1

    def __len__(self):
        return self._len

    def query(self, start, stop):
        if start == stop:
            return self.__getitem__(start)
        stop += 1
        start += self._size
        stop += self._size

        res = self._default
        while start < stop:
            if start & 1:
                res = self._func(res, self.data[start])
                start += 1
            if stop & 1:
                stop -= 1
                res = self._func(res, self.data[stop])
            start >>= 1
            stop >>= 1
        return res

    def __repr__(self):
        return "SegmentTree({0})".format(self.data)

# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
    def __init__(self, MOD):
        self.MOD = MOD
        self.factorials = [1, 1]
        self.invModulos = [0, 1]
        self.invFactorial_ = [1, 1]

    def calc(self, n):
        if n <= -1:
            print("Invalid argument to calculate n!")
            print("n must be non-negative value. But the argument was " + str(n))
            exit()
        if n < len(self.factorials):
            return self.factorials[n]
        nextArr = [0] * (n + 1 - len(self.factorials))
        initialI = len(self.factorials)
        prev = self.factorials[-1]
        m = self.MOD
        for i in range(initialI, n + 1):
            prev = nextArr[i - initialI] = prev * i % m
        self.factorials += nextArr
        return self.factorials[n]

    def inv(self, n):
        if n <= -1:
            print("Invalid argument to calculate n^(-1)")
            print("n must be non-negative value. But the argument was " + str(n))
            exit()
        p = self.MOD
        pi = n % p
        if pi < len(self.invModulos):
            return self.invModulos[pi]
        nextArr = [0] * (n + 1 - len(self.invModulos))
        initialI = len(self.invModulos)
        for i in range(initialI, min(p, n + 1)):
            next = -self.invModulos[p % i] * (p // i) % p
            self.invModulos.append(next)
        return self.invModulos[pi]

    def invFactorial(self, n):
        if n <= -1:
            print("Invalid argument to calculate (n^(-1))!")
            print("n must be non-negative value. But the argument was " + str(n))
            exit()
        if n < len(self.invFactorial_):
            return self.invFactorial_[n]
        self.inv(n)  # To make sure already calculated n^-1
        nextArr = [0] * (n + 1 - len(self.invFactorial_))
        initialI = len(self.invFactorial_)
        prev = self.invFactorial_[-1]
        p = self.MOD
        for i in range(initialI, n + 1):
            prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
        self.invFactorial_ += nextArr
        return self.invFactorial_[n]

class Combination:
    def __init__(self, MOD):
        self.MOD = MOD
        self.factorial = Factorial(MOD)

    def ncr(self, n, k):
        if k < 0 or n < k:
            return 0
        k = min(k, n - k)
        f = self.factorial
        return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
    if a == 1 or n == 0:
        return 1
    if n % 2 == 0:
        s = powm(a, n // 2, m)
        return s * s % m
    else:
        return a * powm(a, n - 1, m) % m

# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
    zipped_pairs = zip(list2, list1)

    z = [x for _, x in sorted(zipped_pairs)]

    return z

# --------------------------------------------------product----------------------------------------
def product(l):
    por = 1
    for i in range(len(l)):
        por *= l[i]
    return por

# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
    left = 0
    right = n - 1

    count = 0

    while (left <= right):
        mid = int((right + left)/ 2)

        # Check if middle element is
        # less than or equal to key
        if (arr[mid]<=key):
            count = mid+1
            left = mid + 1

        # If key is smaller, ignore right half
        else:
            right = mid - 1

    return count

# --------------------------------------------------binary----------------------------------------
def countdig(n):
    c = 0
    while (n > 0):
        n //= 10
        c += 1
    return c

def countGreater( arr,n, k):
    l = 0
    r = n - 1

    # Stores the index of the left most element
    # from the array which is greater than k
    leftGreater = n

    # Finds number of elements greater than k
    while (l <= r):
        m = int(l + (r - l) / 2)
        if (arr[m] >= k):
            leftGreater = m
            r = m - 1

        # If mid element is less than
        # or equal to k update l
        else:
            l = m + 1

    # Return the count of elements
    # greater than k
    return (n - leftGreater)

# --------------------------------------------------binary------------------------------------
ind=defaultdict(list)
ind['1']=[0,0,0,1]
ind['0']=[0,0,0,0]
ind['2']=[0,0,1,0]
ind['3']=[0,0,1,1]
ind ['4']=[0,1,0,0]
ind ['5']=[0,1,0,1]
ind ['6']=[0,1,1,0]
ind ['7']=[0,1,1,1]
ind ['8']=[1,0,0,0]
ind ['9']=[1,0,0,1]
ind['A']=[1,0,1,0]
ind ['B']=[1,0,1,1]
ind ['C']=[1,1,0,0]
ind ['D']=[1,1,0,1]
ind ['E']=[1,1,1,0]
ind ['F']=[1,1,1,1]
n=int(input())
l=[[] for i in range(n)]
for i in range(n):
    s=input()
    for j in s:
        for u in ind[j]:
            l[i].append(u)
a=[]
c=1
for i in range(1,n):
    f=0
    for j in range(n):
        if l[i-1][j]!=l[i][j]:
            f=1
            a.append(c)
            c=1
            break
    if f==0:
        c+=1
a.append(c)
c=1
for i in range(1,n):
    f=0
    for j in range(n):
        if l[j][i-1]!=l[j][i]:
            f=1
            a.append(c)
            c=1
            break
    if f==0:
        c+=1
a.append(c)
ans=0
for i in a:
    ans=math.gcd(i,ans)
print(ans)

```


1136_D. Nastya Is Buying Lunch

At the big break Nastya came to the school dining room. There are n pupils in the school, numbered from 1 to n. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.

Formally, there are some pairs u, v such that if the pupil with number u stands directly in front of the pupil with number v, Nastya can ask them and they will change places.

Nastya asks you to find the maximal number of places in queue she can move forward.

Input

The first line contains two integers n and m (1 ≤ n ≤ 3 ⋅ 10^{5}, 0 ≤ m ≤ 5 ⋅ 10^{5}) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second.

The second line contains n integers p_1, p_2, ..., p_n — the initial arrangement of pupils in the queue, from the queue start to its end (1 ≤ p_i ≤ n, p is a permutation of integers from 1 to n). In other words, p_i is the number of the pupil who stands on the i-th position in the queue.

The i-th of the following m lines contains two integers u_i, v_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i), denoting that the pupil with number u_i agrees to change places with the pupil with number v_i if u_i is directly in front of v_i. It is guaranteed that if i ≠ j, than v_i ≠ v_j or u_i ≠ u_j. Note that it is possible that in some pairs both pupils agree to change places with each other.

Nastya is the last person in the queue, i.e. the pupil with number p_n.

Output

Print a single integer — the number of places in queue she can move forward.

Examples

Input

2 1
1 2
1 2

Output

1

Input

3 3
3 1 2
1 2
3 1
3 2

Output

2

Input

5 2
3 1 5 4 2
5 2
5 4

Output

1

Note

In the first example Nastya can just change places with the first pupil in the queue.

Optimal sequence of changes in the second example is

  * change places for pupils with numbers 1 and 3.
  * change places for pupils with numbers 3 and 2.
  * change places for pupils with numbers 1 and 2.

The queue looks like [3, 1, 2], then [1, 3, 2], then [1, 2, 3], and finally [2, 1, 3] after these operations.

```python
import sys
import math
import bisect
from math import sqrt
def input():    return sys.stdin.readline().strip()
def iinput():   return int(input())
def rinput():   return map(int, sys.stdin.readline().strip().split())
def get_list(): return list(map(int, sys.stdin.readline().strip().split()))
mod = int(1e9)+7

n, m = rinput()
p = [0] + get_list()
d = {i:set() for i in range(1, n+1)}

for _ in range(m):
	u, v = rinput()
	d[u].add(v)

last = p[n]
target = n

for i in range(n-1, 0, -1):

	for j in range(i, target):
		if p[j+1] in d[p[j]]:
			p[j], p[j+1] = p[j+1], p[j]
		else:
			break

	if p[target]!=last:
		target -= 1

print(n-target)

# 3 1 4 5 2
```


1155_A. Reverse a Substring

You are given a string s consisting of n lowercase Latin letters.

Let's define a substring as a contiguous subsegment of a string. For example, "acab" is a substring of "abacaba" (it starts in position 3 and ends in position 6), but "aa" or "d" aren't substrings of this string. So the substring of the string s from position l to position r is s[l; r] = s_l s_{l + 1} ... s_r.

You have to choose exactly one of the substrings of the given string and reverse it (i. e. make s[l; r] = s_r s_{r - 1} ... s_l) to obtain a string that is less lexicographically. Note that it is not necessary to obtain the minimum possible string.

If it is impossible to reverse some substring of the given string to obtain a string that is less, print "NO". Otherwise print "YES" and any suitable substring.

String x is lexicographically less than string y, if either x is a prefix of y (and x ≠ y), or there exists such i (1 ≤ i ≤ min(|x|, |y|)), that x_i < y_i, and for any j (1 ≤ j < i) x_j = y_j. Here |a| denotes the length of the string a. The lexicographic comparison of strings is implemented by operator < in modern programming languages.

Input

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

The second line of the input contains the string s of length n consisting only of lowercase Latin letters.

Output

If it is impossible to reverse some substring of the given string to obtain a string which is lexicographically less, print "NO". Otherwise print "YES" and two indices l and r (1 ≤ l < r ≤ n) denoting the substring you have to reverse. If there are multiple answers, you can print any.

Examples

Input

7
abacaba

Output

YES
2 5

Input

6
aabcfg

Output

NO

Note

In the first testcase the resulting string is "aacabba".

```python
'''

                            Online Python Compiler.
                Code, Compile, Run and Debug python program online.
Write your code in this editor and press "Run" button to execute it.

'''
def main():
    n = input()
    s = input()
    for i in range(len(s)-1):
        if s[i]>s[i+1]:
            print('YES')
            print(i+1, i+2)
            return
    print('NO')

main()
```


1176_F. Destroy it!

You are playing a computer card game called Splay the Sire. Currently you are struggling to defeat the final boss of the game.

The boss battle consists of n turns. During each turn, you will get several cards. Each card has two parameters: its cost c_i and damage d_i. You may play some of your cards during each turn in some sequence (you choose the cards and the exact order they are played), as long as the total cost of the cards you play during the turn does not exceed 3. After playing some (possibly zero) cards, you end your turn, and all cards you didn't play are discarded. Note that you can use each card at most once.

Your character has also found an artifact that boosts the damage of some of your actions: every 10-th card you play deals double damage.

What is the maximum possible damage you can deal during n turns?

Input

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

Then n blocks of input follow, the i-th block representing the cards you get during the i-th turn.

Each block begins with a line containing one integer k_i (1 ≤ k_i ≤ 2 ⋅ 10^5) — the number of cards you get during i-th turn. Then k_i lines follow, each containing two integers c_j and d_j (1 ≤ c_j ≤ 3, 1 ≤ d_j ≤ 10^9) — the parameters of the corresponding card.

It is guaranteed that ∑ _{i = 1}^{n} k_i ≤ 2 ⋅ 10^5.

Output

Print one integer — the maximum damage you may deal.

Example

Input

5
3
1 6
1 7
1 5
2
1 4
1 3
3
1 10
3 5
2 3
3
1 15
2 4
1 10
1
1 100

Output

263

Note

In the example test the best course of action is as follows:

During the first turn, play all three cards in any order and deal 18 damage.

During the second turn, play both cards and deal 7 damage.

During the third turn, play the first and the third card and deal 13 damage.

During the fourth turn, play the first and the third card and deal 25 damage.

During the fifth turn, play the only card, which will deal double damage (200).

```python
import sys
import math
import cProfile

DEBUG = False
def log(s):
    if DEBUG and False:
        print(s)

def calc_dmg(num, arr):
    maximum = 0
    if num - len(arr) < 0:
        maximum = max(arr)
    return sum(arr) + maximum

if DEBUG:
    sys.stdin = open('input.txt')
    pr = cProfile.Profile()
    pr.enable()

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

dmg = [-sys.maxsize for _ in range(10)]

for i in range(n):
    log(dmg)
    cards = [_[:] for _ in [[-sys.maxsize] * 3] * 4]

    k = sys.stdin.readline()
    k = int(k)
    for _ in range(k):
        c, d = sys.stdin.readline().split()
        c = int(c)
        d = int(d)
        cards[c].append(d)
    cards[1].sort(reverse=True)
    cards[2].sort(reverse=True)
    cards[3].sort(reverse=True)
    log(cards)

    # dmg[j] = max(dmg[j],
    #              dmg[j - 1] + D(one card),
    #              dmg[j - 2] + D(two cards),
    #              dmg[j - 3] + D(three cards))
    # Plus, if 1 <= j <= 3, dmg[j] = max(dmg[j], D(cards))
    new_dmg = []
    for j in range(10):
        use1 = max(cards[1][0], cards[2][0], cards[3][0])
        use2 = max(cards[1][0] + cards[1][1],
                   cards[1][0] + cards[2][0])
        use3 = cards[1][0] + cards[1][1] + cards[1][2]

        maximum = dmg[j]
        if use1 > 0:
            maximum = max(maximum, dmg[j - 1] + calc_dmg(j, [use1]))
            if j == 1:
                maximum = max(maximum, use1)
        if use2 > 0:
            maximum = max(maximum, dmg[j - 2] +
                          calc_dmg(j, [cards[1][0], cards[1][1]]
                          if cards[1][0] + cards[1][1] == use2
                          else [cards[1][0], cards[2][0]]))
            if j == 2:
                maximum = max(maximum, use2)
        if use3 > 0:
            maximum = max(maximum, dmg[j - 3] +
                          calc_dmg(j, [cards[1][0], cards[1][1], cards[1][2]]))
            if j == 3:
                maximum = max(maximum, use3)
        new_dmg.append(maximum)
    dmg = new_dmg

log(dmg)
print(max(dmg))

if DEBUG:
    pr.disable()
    pr.print_stats()
```


1195_D2. Submarine in the Rybinsk Sea (hard edition)

This problem differs from the previous one only in the absence of the constraint on the equal length of all numbers a_1, a_2, ..., a_n.

A team of SIS students is going to make a trip on a submarine. Their target is an ancient treasure in a sunken ship lying on the bottom of the Great Rybinsk sea. Unfortunately, the students don't know the coordinates of the ship, so they asked Meshanya (who is a hereditary mage) to help them. He agreed to help them, but only if they solve his problem.

Let's denote a function that alternates digits of two numbers f(a_1 a_2 ... a_{p - 1} a_p, b_1 b_2 ... b_{q - 1} b_q), where a_1 ... a_p and b_1 ... b_q are digits of two integers written in the decimal notation without leading zeros.

In other words, the function f(x, y) alternately shuffles the digits of the numbers x and y by writing them from the lowest digits to the older ones, starting with the number y. The result of the function is also built from right to left (that is, from the lower digits to the older ones). If the digits of one of the arguments have ended, then the remaining digits of the other argument are written out. Familiarize with examples and formal definitions of the function below.

For example: $$$f(1111, 2222) = 12121212 f(7777, 888) = 7787878 f(33, 44444) = 4443434 f(555, 6) = 5556 f(111, 2222) = 2121212$$$

Formally,

  * if p ≥ q then f(a_1 ... a_p, b_1 ... b_q) = a_1 a_2 ... a_{p - q + 1} b_1 a_{p - q + 2} b_2 ... a_{p - 1} b_{q - 1} a_p b_q;
  * if p < q then f(a_1 ... a_p, b_1 ... b_q) = b_1 b_2 ... b_{q - p} a_1 b_{q - p + 1} a_2 ... a_{p - 1} b_{q - 1} a_p b_q.

Mishanya gives you an array consisting of n integers a_i, your task is to help students to calculate ∑_{i = 1}^{n}∑_{j = 1}^{n} f(a_i, a_j) modulo 998 244 353.

Input

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of elements in the array. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) — the elements of the array.

Output

Print the answer modulo 998 244 353.

Examples

Input

3
12 3 45

Output

12330

Input

2
123 456

Output

1115598

```python
from collections import Counter

n = int(input())
a = list(map(int, input().split()))
l = [len(str(i)) for i in a]
c = Counter(l)
cl = [c[i] for i in range(1,11)]
M = 998244353

pad = lambda a, d: a%d + (a - a%d) * 10

#print(a, l, c, cl)

ans = 0

for i in a:
    il = len(str(i)) # let's calculate it again to avoid zip and enumerate
    #print('processing', i, ans)
    t = i
    for p in range(10):
        #if not cl[p]: continue
        i = pad(i, 100**p)
        #print('top pad', p, 'is', i, 'there are', cl[p])
        ans = (ans + i * cl[p]) % M
    i = t # restore
    for p in range(10):
        #if not cl[p]: continue
        i = pad(i, 10 * 100**p)
        #print('bottom pad', p, 'is', i, 'there are', cl[p])
        ans = (ans + i * cl[p]) % M

print(ans)

```


1236_A. Stones

Alice is playing with some stones.

Now there are three numbered heaps of stones. The first of them contains a stones, the second of them contains b stones and the third of them contains c stones.

Each time she can do one of two operations:

  1. take one stone from the first heap and two stones from the second heap (this operation can be done only if the first heap contains at least one stone and the second heap contains at least two stones);
  2. take one stone from the second heap and two stones from the third heap (this operation can be done only if the second heap contains at least one stone and the third heap contains at least two stones).

She wants to get the maximum number of stones, but she doesn't know what to do. Initially, she has 0 stones. Can you help her?

Input

The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. Next t lines describe test cases in the following format:

Line contains three non-negative integers a, b and c, separated by spaces (0 ≤ a,b,c ≤ 100) — the number of stones in the first, the second and the third heap, respectively.

In hacks it is allowed to use only one test case in the input, so t = 1 should be satisfied.

Output

Print t lines, the answers to the test cases in the same order as in the input. The answer to the test case is the integer — the maximum possible number of stones that Alice can take after making some operations.

Example

Input

3
3 4 5
1 0 5
5 3 2

Output

9
0
6

Note

For the first test case in the first test, Alice can take two stones from the second heap and four stones from the third heap, making the second operation two times. Then she can take one stone from the first heap and two stones from the second heap, making the first operation one time. The summary number of stones, that Alice will take is 9. It is impossible to make some operations to take more than 9 stones, so the answer is 9.

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

while t>0:

    x, y, z = [int(i) for i in input().split()]

    s = 0
    f = -1
    z = z//2
    if y >= z:
        y = y - z
        s = z*2 + z
    else:
        s = y*2 + y
        f = 1

    if f == -1:
        y = y//2
        if x >= y:
            s = s + 2*y + y
        else:
            s = s + 2*x + x

    print(s)

    t-=1
```


1277_E. Two Fairs

There are n cities in Berland and some pairs of them are connected by two-way roads. It is guaranteed that you can pass from any city to any other, moving along the roads. Cities are numerated from 1 to n.

Two fairs are currently taking place in Berland — they are held in two different cities a and b (1 ≤ a, b ≤ n; a ≠ b).

Find the number of pairs of cities x and y (x ≠ a, x ≠ b, y ≠ a, y ≠ b) such that if you go from x to y you will have to go through both fairs (the order of visits doesn't matter). Formally, you need to find the number of pairs of cities x,y such that any path from x to y goes through a and b (in any order).

Print the required number of pairs. The order of two cities in a pair does not matter, that is, the pairs (x,y) and (y,x) must be taken into account only once.

Input

The first line of the input contains an integer t (1 ≤ t ≤ 4⋅10^4) — the number of test cases in the input. Next, t test cases are specified.

The first line of each test case contains four integers n, m, a and b (4 ≤ n ≤ 2⋅10^5, n - 1 ≤ m ≤ 5⋅10^5, 1 ≤ a,b ≤ n, a ≠ b) — numbers of cities and roads in Berland and numbers of two cities where fairs are held, respectively.

The following m lines contain descriptions of roads between cities. Each of road description contains a pair of integers u_i, v_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i) — numbers of cities connected by the road.

Each road is bi-directional and connects two different cities. It is guaranteed that from any city you can pass to any other by roads. There can be more than one road between a pair of cities.

The sum of the values of n for all sets of input data in the test does not exceed 2⋅10^5. The sum of the values of m for all sets of input data in the test does not exceed 5⋅10^5.

Output

Print t integers — the answers to the given test cases in the order they are written in the input.

Example

Input

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

Output

4
0
1

```python
import sys
import threading
from collections import deque

def func():
    lines = sys.stdin.readlines()
    nxt = 0
    t = int(lines[nxt])
    nxt += 1
    ans = []
    for _ in range(t):
        n,m,a,b = map(int, lines[nxt].split())
        nxt += 1
        g = [[] for _ in range(n)]
        for _ in range(m):
            u,v = map(int, lines[nxt].split())
            nxt += 1
            g[u-1].append(v-1)
            g[v-1].append(u-1)
        a -= 1
        b -= 1
        sigs = [0]*n
        sigs[a] = -1
        sigs[b] = -1
        cur_sig = 0
        inv = {}
        cnt = {}
        for i in range(n):
            if sigs[i]:
                continue
            cur_sig += 1
            cnt[cur_sig] = 1
            inv[cur_sig] = set()
            sigs[i] = cur_sig
            q = deque()
            q.append(i)
            while len(q):
                node = q.popleft()
                # if node == a:
                #     inv[cur_sig].add("A")
                # if node == b:
                #     inv[cur_sig].add("B")
                # if sigs[node]:
                #     continue
                # sigs[node] = cur_sig
                # cnt[cur_sig] += 1
                for v in g[node]:
                    if v == a:
                        inv[cur_sig].add("A")
                    if v == b:
                        inv[cur_sig].add("B")
                    if sigs[v]:
                        continue
                    sigs[v] = cur_sig
                    cnt[cur_sig] += 1
                    q.append(v)
        A = 0
        B = 0
        for k,v in inv.items():
            if v == {"A"}:
                A += cnt[k]
            if v == {"B"}:
                B += cnt[k]
        ans.append(str(A*B))
    print("\n".join(ans))

func()

```


1382_A. Common Subsequence

You are given two arrays of integers a_1,…,a_n and b_1,…,b_m.

Your task is to find a non-empty array c_1,…,c_k that is a subsequence of a_1,…,a_n, and also a subsequence of b_1,…,b_m. If there are multiple answers, find one of the smallest possible length. If there are still multiple of the smallest possible length, find any. If there are no such arrays, you should report about it.

A sequence a is a subsequence of a sequence b if a can be obtained from b by deletion of several (possibly, zero) elements. For example, [3,1] is a subsequence of [3,2,1] and [4,3,1], but not a subsequence of [1,3,3,7] and [3,10,4].

Input

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

The first line of each test case contains two integers n and m (1≤ n,m≤ 1000) — the lengths of the two arrays.

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

The third line of each test case contains m integers b_1,…,b_m (1≤ b_i≤ 1000) — the elements of the second array.

It is guaranteed that the sum of n and the sum of m across all test cases does not exceed 1000 (∑_{i=1}^t n_i, ∑_{i=1}^t m_i≤ 1000).

Output

For each test case, output "YES" if a solution exists, or "NO" otherwise.

If the answer is "YES", on the next line output an integer k (1≤ k≤ 1000) — the length of the array, followed by k integers c_1,…,c_k (1≤ c_i≤ 1000) — the elements of the array.

If there are multiple solutions with the smallest possible k, output any.

Example

Input

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

Output

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

Note

In the first test case, [4] is a subsequence of [10, 8, 6, 4] and [1, 2, 3, 4, 5]. This array has length 1, it is the smallest possible length of a subsequence of both a and b.

In the third test case, no non-empty subsequences of both [3] and [2] exist, so the answer is "NO".

```python
#!/usr/bin/env python3
import io
import os

input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline

def get_str():
    return input().decode().strip()

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

def oint():
    return int(input())

t = oint()

for _ in range(t):
    n, m = rint()
    a = set(rint())
    b = set(rint())
    c = a&b
    if c:
        print('YES')
        print(1, list(c)[0])
    else:
        print('NO')

```