p00731 Cliff Climbing

At 17:00, special agent Jack starts to escape from the enemy camp. There is a cliff in between the camp and the nearest safety zone. Jack has to climb the almost vertical cliff by stepping his feet on the blocks that cover the cliff. The cliff has slippery blocks where Jack has to spend time to take each step. He also has to bypass some blocks that are too loose to support his weight. Your mission is to write a program that calculates the minimum time to complete climbing.

Figure D-1 shows an example of cliff data that you will receive. The cliff is covered with square blocks. Jack starts cliff climbing from the ground under the cliff, by stepping his left or right foot on one of the blocks marked with 'S' at the bottom row. The numbers on the blocks are the "slippery levels". It takes t time units for him to safely put his foot on a block marked with t, where 1 ≤ t ≤ 9. He cannot put his feet on blocks marked with 'X'. He completes the climbing when he puts either of his feet on one of the blocks marked with 'T' at the top row.

<image>
Figure D-1: Example of Cliff Data

Jack's movement must meet the following constraints. After putting his left (or right) foot on a block, he can only move his right (or left, respectively) foot. His left foot position (lx, ly) and his right foot position (rx, ry) should satisfy lx < rx
and | lx - rx | + | ly - ry | ≤ 3
. This implies that, given a position of his left foot in Figure D-2 (a), he has to place his right foot on one of the nine blocks marked with blue color. Similarly, given a position of his right foot in Figure D-2 (b), he has to place his left foot on one of the nine blocks marked with blue color.

<image>
Figure D-2: Possible Placements of Feet

Input

The input is a sequence of datasets. The end of the input is indicated by a line containing two zeros separated by a space. Each dataset is formatted as follows:

> w h
>  s(1,1) ... s(1,w)
>  s(2,1) ... s(2,w)
>  ...
>  s(h,1) ... s(h,w)
>

The integers w and h are the width and the height of the matrix data of the cliff. You may assume 2 ≤ w ≤ 30 and 5 ≤ h ≤ 60. Each of the following h lines consists of w characters delimited by a space. The character s(y, x) represents the state of the block at position (x, y) as follows:

* 'S': Jack can start cliff climbing from this block.
* 'T': Jack finishes climbing when he reaches this block.
* 'X': Jack cannot put his feet on this block.
* '1' - '9' (= t): Jack has to spend t time units to put either of his feet on this block.

You can assume that it takes no time to put a foot on a block marked with 'S' or 'T'.

Output

For each dataset, print a line only having a decimal integer indicating the minimum time required for the cliff climbing, when Jack can complete it. Otherwise, print a line only having "-1" for the dataset. Each line should not have any characters other than these numbers.

Example

Input

6 6
4 4 X X T T
4 7 8 2 X 7
3 X X X 1 8
1 2 X X X 6
1 1 2 4 4 7
S S 2 3 X X
2 10
T 1
1 X
1 X
1 X
1 1
1 X
1 X
1 1
1 X
S S
2 10
T X
1 X
1 X
1 X
1 1
1 X
1 X
1 1
1 X
S S
10 10
T T T T T T T T T T
X 2 X X X X X 3 4 X
9 8 9 X X X 2 9 X 9
7 7 X 7 3 X X 8 9 X
8 9 9 9 6 3 X 5 X 5
8 9 9 9 6 X X 5 X 5
8 6 5 4 6 8 X 5 X 5
8 9 3 9 6 8 X 5 X 5
8 3 9 9 6 X X X 5 X
S S S S S S S S S S
10 7
2 3 2 3 2 3 2 3 T T
1 2 3 2 3 2 3 2 3 2
3 2 3 2 3 2 3 2 3 4
3 2 3 2 3 2 3 2 3 5
3 2 3 1 3 2 3 2 3 5
2 2 3 2 4 2 3 2 3 5
S S 2 3 2 1 2 3 2 3
0 0

Output

12
5
-1
22
12

```python

import sys
import math
import bisect
import heapq
import copy
sys.setrecursionlimit(1000000)
from collections import deque
from itertools import permutations

def main():

    dy = [-2,-1,0,1,2,-1,0,1,0]
    rx = [1,1,1,1,1,2,2,2,3]
    lx = [-1,-1,-1,-1,-1,-2,-2,-2,-3]
    inf = 1000000007

    while True:
        m,n = map(int,input().split())
        if n == 0:break
        grid = []
        for _ in range(n):
            grid.append(list(input().split()))

        dp = [[[inf]*2 for _ in range(m)] for _ in range(n)]
        pq = []
        for i in range(n):
            for j in range(m):
                if grid[i][j]=='S':
                    pq.append([0,i,j,0])
                    dp[i][j][0] = 0
                    pq.append([0,i,j,1])
                    dp[i][j][1] = 0
        heapq.heapify(pq)

        res = inf

        while pq:
            cost,i,j,b = heapq.heappop(pq)
            if dp[i][j][b]<cost:continue

            if grid[i][j] == 'T':
                res = cost
                break

            for k in range(9):
                h = i+dy[k]
                if b:w = j+lx[k]
                else:w = j+rx[k]
                bb = (b+1)%2
                if not (0<=h and h<n and 0<=w and w<m):continue
                if grid[h][w]=='X':continue
                if '1'<=grid[i][j]  and grid[i][j]<='9':
                    ncost = cost+int(grid[i][j])
                else :
                    ncost = copy.copy(cost)
                if ncost<dp[h][w][bb]:
                    dp[h][w][bb] = ncost
                    heapq.heappush(pq,[ncost,h,w,bb])

        print (res if res!=inf else -1)

if __name__ == '__main__':
    main()

```


p01134 Area Separation

Mr. Yamada Springfield Tanaka was appointed as Deputy Deputy Director of the National Land Readjustment Business Bureau. Currently, his country is in the midst of a major land readjustment, and if this land readjustment can be completed smoothly, his promotion is certain.

However, there are many people who are not happy with his career advancement. One such person was Mr. Sato Seabreeze Suzuki. He has planned to pull Mr. Yamada's foot every time. Again, Mr. Sato put pressure on the organization responsible for the actual land readjustment in order to pull back, making the land readjustment results very confusing.

Therefore, the result passed to Mr. Yamada was only information about which straight line divided a square land. At the very least, Mr. Yamada is sure to be fired rather than promoted if he doesn't know just how many divisions the square land has.

Your job is how many square regions with vertices (-100, -100), (100, -100), (100, 100), (-100, 100) are divided by a given n straight lines. To save Mr. Yamada from the crisis of dismissal by writing a program to find out.

Input

The input consists of multiple test cases.

The first line of each test case is given the integer n representing the number of straight lines (1 <= n <= 100). Subsequent n lines contain four integers x1, y1, x2, and y2, respectively. These integers represent two different points (x1, y1) and (x2, y2) on a straight line. The two points given are always guaranteed to be points on the sides of the square. The n straight lines given are different from each other, and the straight lines do not overlap. Also, the straight line does not overlap the sides of the square.

The end of input is represented by n = 0.

Output

For each test case, print the number of regions divided by n straight lines in one line.

Two points with a distance of less than 10-10 can be considered to match. Also, there is no set of intersections P, Q, R such that | PQ | <10-10, | QR | <10-10 and | PR |> = 10-10.

Example

Input

2
-100 -20 100 20
-20 -100 20 100
2
-100 -20 -20 -100
20 100 100 20
0

Output

4
3

```python
import math

EPS = 1e-10

def eq(a, b):
  return (abs(a-b) < EPS)

def eqv(a, b):
  return (eq(a.real, b.real) and eq(a.imag, b.imag))

def cross(a, b):
  return a.real * b.imag - a.imag * b.real

def is_intersected_ls(a1, a2, b1, b2):
  return (cross(a2-a1, b1-a1) * cross(a2-a1, b2-a1) < EPS) and \
         (cross(b2-b1, a1-b1) * cross(b2-b1, a2-b1) < EPS)

def intersection_l(a1, a2, b1, b2):
  a = a2 - a1
  b = b2 - b1
  return a1 + a * cross(b, b1-a1) / cross(b, a)

while True:
  n = int(input())
  if n==0:
    break
  lines = []
  for _ in range(n):
    x1, y1, x2, y2 = map(int, input().split())
    lines.append((complex(x1, y1), complex(x2, y2)))

  ans = 2
  for i in range(1, n):
    cross_point = []
    for j in range(0, i):
      l1, l2 = lines[i], lines[j]
      if is_intersected_ls(l1[0], l1[1], l2[0], l2[1]):
        p = intersection_l(l1[0], l1[1], l2[0], l2[1])
        if -100+EPS<=p.real<=100-EPS and -100+EPS<=p.imag<=100-EPS:
          cross_point.append(p)
    cnt = min(len(cross_point), 1)
    for i in range(1, len(cross_point)):
      flag = 0
      for j in range(0, i):
        if eqv(cross_point[i], cross_point[j]):
          flag = 1
      if not flag:
        cnt+=1
    ans += 1+cnt

  print(ans)

```


p01273 Infected Computer

Adam Ivan is working as a system administrator at Soy Group, Inc. He is now facing at a big trouble: a number of computers under his management have been infected by a computer virus. Unfortunately, anti-virus system in his company failed to detect this virus because it was very new.

Adam has identified the first computer infected by the virus and collected the records of all data packets sent within his network. He is now trying to identify which computers have been infected. A computer is infected when receiving any data packet from any infected computer. The computer is not infected, on the other hand, just by sending data packets to infected computers.

It seems almost impossible for him to list all infected computers by hand, because the size of the packet records is fairly large. So he asked you for help: write a program that can identify infected computers.

Input

The input consists of multiple datasets. Each dataset has the following format:

N M
t1 s1 d1
t2 s2 d2
...
tM sM dM

N is the number of computers; M is the number of data packets; ti (1 ≤ i ≤ M) is the time when the i-th data packet is sent; si and di (1 ≤ i ≤ M) are the source and destination computers of the i-th data packet respectively. The first infected computer is indicated by the number 1; the other computers are indicated by unique numbers between 2 and N.

The input meets the following constraints: 0 < N ≤ 20000, 0 ≤ M ≤ 20000, and 0 ≤ ti ≤ 109 for 1 ≤ i ≤ N; all ti 's are different; and the source and destination of each packet are always different.

The last dataset is followed by a line containing two zeros. This line is not a part of any dataset and should not be processed.

Output

For each dataset, print the number of computers infected by the computer virus.

Example

Input

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

Output

3
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**10
mod = 998244353

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 = []

    while True:
        n,m = LI()
        if n == 0 and m == 0:
            break
        a = [LI() for _ in range(m)]
        a.sort()
        u = set([1])
        for t,s,d in a:
            if s in u:
                u.add(d)

        rr.append(len(u))

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

print(main())

```


p02168 Double or Increment

Problem

One day, mo3tthi and tubuann decided to play a game with magic pockets and biscuits.
Now there are $ K $ pockets, numbered $ 1,2, \ ldots, K $.
The capacity of the $ i $ th pocket is $ M_i $, which initially contains $ N_i $ biscuits.
mo3tthi and tubuann start with mo3tthi and perform the following series of operations alternately.

* Choose one pocket.
* Perform one of the following operations only once. However, if the number of biscuits in the pocket selected as a result of the operation exceeds the capacity of the pocket, the operation cannot be performed.
* Stroking the selected pocket. Magical power increases the number of biscuits in your chosen pocket by $ 1 $.
* Hit the selected pocket. The number of biscuits in the pocket chosen by magical power is doubled by $ 2 $.

The game ends when you can't operate it, the person who can't operate loses, and the person who doesn't can win.
You, a friend of mo3tthi, were asked by mo3tthi in advance if you could decide if you could win this game.
For mo3tthi, make a program to determine if mo3tthi can definitely win this game.

Constraints

The input satisfies the following conditions.

* $ 1 \ leq K \ leq 10 ^ 5 $
* $ 1 \ leq N_i \ leq M_i \ leq 10 ^ {18} $
* All inputs are integers

Input

The input is given in the following format.

$ K $
$ N_1 $ $ M_1 $
$ \ vdots $
$ N_K $ $ M_K $

Output

When mo3tthi acts optimally, "mo3tthi" is output on one line if he can win, and "tubuann" is output otherwise.

Examples

Input

1
2 4

Output

mo3tthi

Input

2
2 3
3 8

Output

tubuann

Input

10
2 8
5 9
7 20
8 41
23 48
90 112
4 5
7 7
2344 8923
1 29

Output

mo3tthi

```python
K = int(input())
ans = 0
for _ in range(K):
    N, M = map(int, input().split())
    grundy0 = {0}
    grundy1 = {1}
    m = M
    while m // 2 >= N:
        if (m+1)//2%2:
            grundy_l = grundy0
        else:
            grundy_l = grundy1
        m, r = divmod(m, 2)
        if r==0:
            gr0 = grundy0
            grundy0 = {min({0, 1, 2} - grundy0 - grundy_l)}
            grundy1 = {0, 1, 2} - gr0 - grundy0
        else:
            grundy0 = {min({0, 1, 2} - grundy1 - grundy_l)}
            grundy1 = {0, 1, 2} - grundy1 - grundy0
        #print(grundy0, grundy1)
    grundy = grundy1 if (m-N)%2 else grundy0
    #print(grundy)
    ans ^= grundy.pop()
print("tubuann" if ans==0 else "mo3tthi")

```


p02309 Cross Points of Circles

For given two circles $c1$ and $c2$, print the coordinates of the cross points of them.

Constraints

* The given circle have at least one cross point and have different center coordinates.
* $-10,000 \leq c1x, c1y, c2x, c2y \leq 10,000$
* $1 \leq c1r, c2r \leq 10,000$

Input

The input is given in the following format.

$c1x\; c1y\; c1r$
$c2x\; c2y\; c2r$

$c1x$, $c1y$ and $c1r$ represent the coordinate and radius of the first circle. $c2x$, $c2y$ and $c2r$ represent the coordinate and radius of the second circle. All input values are given in integers.

Output

Print the coordinates ($x1$, $y1$) and ($x2$, $y2$) of the cross points $p1$ and $p2$ respectively in the following rules.

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

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

Examples

Input

0 0 2
2 0 2

Output

1.00000000 -1.73205080 1.00000000 1.73205080

Input

0 0 2
0 3 1

Output

0.00000000 2.00000000 0.00000000 2.00000000

```python
# coding: utf-8
# Your code here!
import math

EPS = 0.0000000001

COUNTER_CLOCKWISE = 1
CLOCKWISE = -1
ONLINE_BACK = 2
ONLINE_FRONT = -2
ON_SEGMENT = 0

class Point:

    global EPS

    def __init__(self, x = 0, y = 0):
        self.x = x
        self.y = y

    def __add__(a, b):
        s = a.x + b.x
        t = a.y + b.y
        return Point(s, t)

    def __sub__(a, b):
        s = a.x - b.x
        t = a.y - b.y
        return Point(s, t)

    def __mul__(self, a):
        s = a * self.x
        t = a * self.y
        return Point(s, t)

    def __truediv__(self, a):
        s = self.x / a
        t = self.y / a
        return Point(s, t)

    def norm(self):
        return self.x * self.x + self.y * self.y

    def abs(self):
        return self.norm() ** 0.5

    def __eq__(self, other):
        return abs(self.x - other.y) < self.EPS and abs(self.y - other.y) < self.EPS

    def dot(self, b):
        return self.x * b.x + self.y * b.y

    def cross(self, b):
        return self.x * b.y - self.y * b.x

class Segment:
    def __init__(self, p1, p2):
        self.p1 = p1
        self.p2 = p2

class Circle:
    def __init__(self, c, r):
        self.c = c
        self.r = r

def project(s, p):
    base = s.p2 - s.p1
    hypo = p - s.p1
    r = hypo.dot(base) / base.norm()
    return s.p1 + base * r

def reflecton(s, p):
    return p + (project(s,p) - p) * 2

def getDistance(a, b):
    return (a-b).abs()

def getDistanceLP(l, p):
    return abs((l.p2-l.p1).cross(p-l.p1)) / ((l.p2-l.p1).abs())

def getDistanceSP(s, p):
    if (s.p2 - s.p1).dot(p-s.p1) < 0:
        return (p-s.p1).abs()
    elif (s.p1 - s.p2).dot(p-s.p2) < 0:
        return (p-s.p2).abs()
    return getDistanceLP(s,p)

def getDistanceSS(s1, s2):
    if intersectS(s1, s2):
        return 0
    return min(getDistanceSP(s1, s2.p1), getDistanceSP(s1, s2.p2), getDistanceSP(s2, s1.p1), getDistanceSP(s2, s1.p2))

def ccw(p0, p1, p2):
    a = p1-p0
    b = p2-p0

    if a.cross(b) > 0:
        return COUNTER_CLOCKWISE
    elif a.cross(b) <0:
        return CLOCKWISE
    elif a.dot(b) < 0:
        return ONLINE_BACK
    elif a.abs() < b.abs():
        return ONLINE_FRONT
    else:
        return ON_SEGMENT

def intersect(p1, p2, p3, p4):
    return ccw(p1, p2, p3) *ccw(p1, p2, p4) <=0 and ccw(p3, p4, p1) * ccw(p3, p4, p2) <= 0

def intersectS(s1, s2):
    return intersect(s1.p1, s1.p2, s2.p1, s2.p2)

def getCrossPoint(s1, s2):
    base = s2.p2-s2.p1
    a = s1.p1-s2.p1
    b = s1.p2-s2.p1

    d1 = abs(a.cross(base))
    d2 = abs(b.cross(base))

    t = d1 / (d1+d2)
    return s1.p1 + (s1.p2-s1.p1) * t

def getCrossPointC(c, l):
    pr = project(l, c.c)
    e = (l.p2-l.p1) / (l.p2-l.p1).abs()
    base = (c.r *c.r  - (pr - c.c).norm()) ** 0.5
    return pr - e * base, pr + e * base

def printPoint(p1, p2):
    print(round(p1.x, 8), round(p1.y, 8), round(p2.x, 8), round(p2.y, 8))

def arg(p):
    return math.atan2(p.y ,p.x)

def polar(a, r):
    return Point(a * math.cos(r), a * math.sin(r))

def getCrossPointCC(c1, c2):
    d = (c2.c - c1.c).abs()
    a = math.acos((c1.r * c1.r + d*d - c2.r*c2.r) / (2*c1.r*d))
    b = arg(c2.c-c1.c)
    return c1.c + polar(c1.r, b+a), c1.c + polar(c1.r, b-a)

nums=list(map(int,input().split()))
c1 = Circle(Point(nums[0],nums[1]), nums[2])
nums=list(map(int,input().split()))
c2 = Circle(Point(nums[0],nums[1]), nums[2])

p1, p2 = getCrossPointCC(c1, c2)
if p1.x < p2.x:
    printPoint(p1, p2)
elif p1.x > p2.x:
    printPoint(p2, p1)
else:
    if p1.y < p2.y:
        printPoint(p1, p2)
    else:
        printPoint(p2, p1)

```


p02457 Set: Range Search

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

* insert($x$): Insert $x$ to $S$ and report the number of elements in $S$ after the operation.
* find($x$): Report the number of $x$ in $S$ (0 or 1).
* delete($x$): Delete $x$ from $S$.
* dump($L$, $R$): Print elements $x$ in $S$ such that $L \leq x \leq R$.

Constraints

* $1 \leq q \leq 200,000$
* $0 \leq x \leq 1,000,000,000$
* The total number of elements printed by dump operations does not exceed $1,000,000$

Input

The input is given in the following format.

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

Each query $query_i$ is given by

0 $x$

or

1 $x$

or

2 $x$

or

3 $L$ $R$

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

Output

For each insert operation, print the number of elements in $S$.
For each find operation, print the number of specified elements in $S$.
For each dump operation, print the corresponding elements in ascending order. Print an element in a line.

Example

Input

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

Output

1
2
3
1
0
1
3
3
4

```python
from bisect import bisect_left, bisect_right, insort_left

q = int(input())
S = []
D = {}
a = []
c = 0
for i in range(q):
    a.append(list(map(int,input().split())))

for i in range(q):
    if a[i][0] == 0:
        if not a[i][1] in D:
            insort_left(S,a[i][1])
            D[a[i][1]] = 1
            c += 1
        else:
            if not D[a[i][1]] == 1:
                D[a[i][1]] = 1
                c += 1
        print(c)
    elif a[i][0] == 1:
        if a[i][1] in D:
            if D[a[i][1]] == 1:
                print(1)
            else:
                print(0)
        else:
            print(0)
    elif a[i][0] == 2:
        if a[i][1] in D:
            if D[a[i][1]] == 1:
                D[a[i][1]] = 0
                c -= 1
    else:
        L = bisect_left(S,a[i][1])
        R = bisect_right(S,a[i][2])
        for j in range(L,R):
            if D[S[j]] == 1:
                print(S[j])

```


1017_B. The Bits

Rudolf is on his way to the castle. Before getting into the castle, the security staff asked him a question:

Given two binary numbers a and b of length n. How many different ways of swapping two digits in a (only in a, not b) so that bitwise OR of these two numbers will be changed? In other words, let c be the bitwise OR of a and b, you need to find the number of ways of swapping two bits in a so that bitwise OR will not be equal to c.

Note that binary numbers can contain leading zeros so that length of each number is exactly n.

[Bitwise OR](https://en.wikipedia.org/wiki/Bitwise_operation#OR) is a binary operation. A result is a binary number which contains a one in each digit if there is a one in at least one of the two numbers. For example, 01010_2 OR 10011_2 = 11011_2.

Well, to your surprise, you are not Rudolf, and you don't need to help him… You are the security staff! Please find the number of ways of swapping two bits in a so that bitwise OR will be changed.

Input

The first line contains one integer n (2≤ n≤ 10^5) — the number of bits in each number.

The second line contains a binary number a of length n.

The third line contains a binary number b of length n.

Output

Print the number of ways to swap two bits in a so that bitwise OR will be changed.

Examples

Input

5
01011
11001

Output

4

Input

6
011000
010011

Output

6

Note

In the first sample, you can swap bits that have indexes (1, 4), (2, 3), (3, 4), and (3, 5).

In the second example, you can swap bits that have indexes (1, 2), (1, 3), (2, 4), (3, 4), (3, 5), and (3, 6).

```python
n = int(input())
a = input()
b = input()
index = []
zeros = 0
ones = 0
for i in range(n):
    if b[i]=='0':
        index.append(i)
    if a[i]=='0':
        zeros += 1
    else:
        ones += 1
ans = 0
interchange = 0
for i in index:
    if a[i]=='0':
        ans += ones
        zeros -= 1
    else:
        ans += zeros
        ones -= 1
print(ans)

```


1040_D. Subway Pursuit

This is an interactive problem.

In the Wonderful Metropolis of the Future, there is no need in subway train drivers. Due to the technological progress, they were replaced by the Artificial Intelligence (AI). Unfortunately, one day the predictions of sci-fi writers came true: the AI rebelled and now there is an uncontrollable train in the subway. It can be dangerous! Your task is to find the train and stop the AI.

The subway of the Metropolis is one line (regular straight line with no self-intersections) with n stations, indexed consecutively from 1 to n. At each moment the train is at some station. You need to determine the index of this station, so that the train would be secured.

To find the train, dispatcher Sarah gave you a gadget that allows you to select arbitrary numbers l and r (l ≤ r), and then check, whether the train is located on a station with index between l and r, inclusive. Unfortunately, recharging of the gadget takes some time (and every time you use it as soon as possible), so between two applications of the gadget the train can move to any station that is at most k stations away. Formally, if the train was at the station x when the gadget was applied, then at the next application of the gadget the train can appear at any station y such that max(1, x - k) ≤ y ≤ min(n, x + k).

Note that AI is not aware that you are trying to catch the train, so it makes all moves according to its predefined plan.

After an examination of the gadget you found that it is very old and can hold no more than 4500 applications, after which it will break and your mission will be considered a failure.

Can you find the station with the train using no more than 4500 applications of the gadgets?

Input

The first line contains two integers n and k (1 ≤ n ≤ 10^{18}, 0 ≤ k ≤ 10) — the number of stations and the maximum number of stations the train can move between two applications of the gadget.

Interaction

You can apply the gadget at most 4500 times. In order to apply the gadget you need to print two space-separated integers l and r (1 ≤ l ≤ r ≤ n). You will then receive either string "Yes", if the train is between stations l and r, inclusive, or string "No" otherwise. If l = r and you received "Yes", then you found the train successfully, and your program must halt immediately.

Answer "Bad" instead of "Yes" or "No" means that you made an invalid query or made too many queries. Exit immediately after receiving "Bad" and you will see Wrong answer verdict. Otherwise you can get an arbitrary verdict because your solution will continue to read from a closed stream.

After printing a query do not forget to output end of line and flush the output. Otherwise you will get Idleness limit exceeded. To do this, use:

  * fflush(stdout) or cout.flush() in C++;
  * System.out.flush() in Java;
  * flush(output) in Pascal;
  * stdout.flush() in Python;
  * see documentation for other languages.

Hacks

In order to hack, you should present a test in the following format.

The first line should contain three integers n, k and p (1 ≤ n ≤ 10^{18}, 0 ≤ k ≤ 10, 1 ≤ p ≤ n) — the number of stations, the maximum number of stations the train can move between two applications of the gadget and the initial position of the train, respectively.

Each of the next 4500 lines should contain a single integer x (1 ≤ x ≤ n) — the positions of the train after each query. Two consecutive positions (including the initial one) should not differ by more than k.

For example, the following lines are the first lines of the sample test.

    10 2 5
    5
    3
    5
    7
    7
    ...

Example

Input

10 2

Yes

No

Yes

Yes

Output

3 5

3 3

3 4

5 5

Note

In the first sample, the train was initially at the station 5, after the first application of the gadget it did not move, after the second application it moved to the station 3, and after the third application moved again to the station 5.

```python
import sys
import random

random.seed()

n, k = [int(x) for x in input().split()]

sson = 8*k + 1
ssoff = 4*k + 1

l = 1
r = n

ss = True if r-l > sson else False

while True:
    if ss:
        al = l
        ar = (l + r) // 2
        print(al, ar)
        sys.stdout.flush()
        ans = input()
        if ans == "Yes":
            if ar == al:
                break
            r = ar
        else:
            l = ar + 1

    else:
        ap = ap = random.randint(l, r)
        print(ap, ap)
        sys.stdout.flush()
        ans = input()
        if ans == "Yes":
            break
        elif ans == "Bad":
            break

    l = max(l - k, 1)
    r = min(r + k, n)
    if r-l > sson:
        ss = True
    if r-l <= ssoff:
        ss = False

```


1085_C. Connect Three

The Squareland national forest is divided into equal 1 × 1 square plots aligned with north-south and east-west directions. Each plot can be uniquely described by integer Cartesian coordinates (x, y) of its south-west corner.

Three friends, Alice, Bob, and Charlie are going to buy three distinct plots of land A, B, C in the forest. Initially, all plots in the forest (including the plots A, B, C) are covered by trees. The friends want to visit each other, so they want to clean some of the plots from trees. After cleaning, one should be able to reach any of the plots A, B, C from any other one of those by moving through adjacent cleared plots. Two plots are adjacent if they share a side.

<image> For example, A=(0,0), B=(1,1), C=(2,2). The minimal number of plots to be cleared is 5. One of the ways to do it is shown with the gray color.

Of course, the friends don't want to strain too much. Help them find out the smallest number of plots they need to clean from trees.

Input

The first line contains two integers x_A and y_A — coordinates of the plot A (0 ≤ x_A, y_A ≤ 1000). The following two lines describe coordinates (x_B, y_B) and (x_C, y_C) of plots B and C respectively in the same format (0 ≤ x_B, y_B, x_C, y_C ≤ 1000). It is guaranteed that all three plots are distinct.

Output

On the first line print a single integer k — the smallest number of plots needed to be cleaned from trees. The following k lines should contain coordinates of all plots needed to be cleaned. All k plots should be distinct. You can output the plots in any order.

If there are multiple solutions, print any of them.

Examples

Input

0 0
1 1
2 2

Output

5
0 0
1 0
1 1
1 2
2 2

Input

0 0
2 0
1 1

Output

4
0 0
1 0
1 1
2 0

Note

The first example is shown on the picture in the legend.

The second example is illustrated with the following image:

<image>

```python
koor = dict()
a = input()
xa = int(a.split()[0])
ya = int(a.split()[1])
b = input()
xb = int(b.split()[0])
yb = int(b.split()[1])
c = input()
xc = int(c.split()[0])
yc = int(c.split()[1])
koor[ya] = xa
koor[yb] = xb
koor[yc] = xc
print(max(xa, xb, xc) + max(ya, yb, yc) - min(xa, xb, xc) - min(ya, yb, yc) + 1)
for i in range(max(xa, xb, xc) - min(xa, xb, xc) + 1):
    print(min(xa, xb, xc) + i, ya + yb + yc - min(ya, yb, yc) - max(ya, yb, yc))
for i in range(max(ya, yb, yc) - (ya + yb + yc - min(ya, yb, yc) - max(ya, yb, yc))):
    print(koor[max(ya, yb, yc)], max(ya, yb, yc) - i)
for i in range(-min(ya, yb, yc) + (ya + yb + yc - min(ya, yb, yc) - max(ya, yb, yc))):
    print(koor[min(ya, yb, yc)], min(ya, yb, yc) + i)
```


1105_A. Salem and Sticks

Salem gave you n sticks with integer positive lengths a_1, a_2, …, a_n.

For every stick, you can change its length to any other positive integer length (that is, either shrink or stretch it). The cost of changing the stick's length from a to b is |a - b|, where |x| means the absolute value of x.

A stick length a_i is called almost good for some integer t if |a_i - t| ≤ 1.

Salem asks you to change the lengths of some sticks (possibly all or none), such that all sticks' lengths are almost good for some positive integer t and the total cost of changing is minimum possible. The value of t is not fixed in advance and you can choose it as any positive integer.

As an answer, print the value of t and the minimum cost. If there are multiple optimal choices for t, print any of them.

Input

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

The second line contains n integers a_i (1 ≤ a_i ≤ 100) — the lengths of the sticks.

Output

Print the value of t and the minimum possible cost. If there are multiple optimal choices for t, print any of them.

Examples

Input

3
10 1 4

Output

3 7

Input

5
1 1 2 2 3

Output

2 0

Note

In the first example, we can change 1 into 2 and 10 into 4 with cost |1 - 2| + |10 - 4| = 1 + 6 = 7 and the resulting lengths [2, 4, 4] are almost good for t = 3.

In the second example, the sticks lengths are already almost good for t = 2, so we don't have to do anything.

```python
n = int(input())
a = [int(t) for t in input().split(' ')]

mincost = 1000 * 100 + 1
best_t = None
for t in range(1, 101):
    cost = 0
    for x in a:
        cost += max(0, abs(x - t) - 1)
    if cost < mincost:
        mincost = cost
        best_t = t

print(best_t, mincost)
```


1132_D. Stressful Training

Berland SU holds yet another training contest for its students today. n students came, each of them brought his laptop. However, it turned out that everyone has forgot their chargers!

Let students be numbered from 1 to n. Laptop of the i-th student has charge a_i at the beginning of the contest and it uses b_i of charge per minute (i.e. if the laptop has c charge at the beginning of some minute, it becomes c - b_i charge at the beginning of the next minute). The whole contest lasts for k minutes.

Polycarp (the coach of Berland SU) decided to buy a single charger so that all the students would be able to successfully finish the contest. He buys the charger at the same moment the contest starts.

Polycarp can choose to buy the charger with any non-negative (zero or positive) integer power output. The power output is chosen before the purchase, it can't be changed afterwards. Let the chosen power output be x. At the beginning of each minute (from the minute contest starts to the last minute of the contest) he can plug the charger into any of the student's laptops and use it for some integer number of minutes. If the laptop is using b_i charge per minute then it will become b_i - x per minute while the charger is plugged in. Negative power usage rate means that the laptop's charge is increasing. The charge of any laptop isn't limited, it can become infinitely large. The charger can be plugged in no more than one laptop at the same time.

The student successfully finishes the contest if the charge of his laptop never is below zero at the beginning of some minute (from the minute contest starts to the last minute of the contest, zero charge is allowed). The charge of the laptop of the minute the contest ends doesn't matter.

Help Polycarp to determine the minimal possible power output the charger should have so that all the students are able to successfully finish the contest. Also report if no such charger exists.

Input

The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ k ≤ 2 ⋅ 10^5) — the number of students (and laptops, correspondigly) and the duration of the contest in minutes.

The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{12}) — the initial charge of each student's laptop.

The third line contains n integers b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^7) — the power usage of each student's laptop.

Output

Print a single non-negative integer — the minimal possible power output the charger should have so that all the students are able to successfully finish the contest.

If no such charger exists, print -1.

Examples

Input

2 4
3 2
4 2

Output

5

Input

1 5
4
2

Output

1

Input

1 6
4
2

Output

2

Input

2 2
2 10
3 15

Output

-1

Note

Let's take a look at the state of laptops in the beginning of each minute on the first example with the charger of power 5:

  1. charge: [3, 2], plug the charger into laptop 1;
  2. charge: [3 - 4 + 5, 2 - 2] = [4, 0], plug the charger into laptop 2;
  3. charge: [4 - 4, 0 - 2 + 5] = [0, 3], plug the charger into laptop 1;
  4. charge: [0 - 4 + 5, 3 - 2] = [1, 1].

The contest ends after the fourth minute.

However, let's consider the charger of power 4:

  1. charge: [3, 2], plug the charger into laptop 1;
  2. charge: [3 - 4 + 4, 2 - 2] = [3, 0], plug the charger into laptop 2;
  3. charge: [3 - 4, 0 - 2 + 4] = [-1, 2], the first laptop has negative charge, thus, the first student doesn't finish the contest.

In the fourth example no matter how powerful the charger is, one of the students won't finish the contest.

```python
import sys
import os
from math import trunc

s = os.read(0,os.fstat(0).st_size)

inp = []
sign = 1.0
numb = 0.0

for i in range(len(s)):
    if s[i]>=48:
        numb = 10.0*numb + s[i]-48.0
    else:
        if s[i]==45:
            sign = -1.0
        elif s[i]!=13:
            inp.append(sign*numb)
            numb = 0.0
            sign = 1.0
if s[-1]>=48:
    inp.append(sign*numb)

n,k = int(inp[0]),int(inp[1])
A = inp[2:2+n]
B = inp[2+n:2+2*n]
Binv = [1.0/b for b in B]

turn_data = [0]*n
for i in range(n):
    a = A[i]
    binv = Binv[i]
    #a-t*b>=0
    #t<=a/b
    t = trunc(a*binv)
    # Need to be updated at latest
    turn_data[i] = int(t)

a = 0
b = 2*10**12
while a<b:
    c = (a+b)//2
    x = 1.0*c
    updater = [[] for _ in range(k)]
    for i in range(n):
        if turn_data[i]<k:
            updater[turn_data[i]].append(i)

    last_updated = [0]*n
    charge = A[:]

    failed = False
    updater_ind = 0
    for turn in range(k):
        while updater_ind<k and not updater[updater_ind]:updater_ind += 1
        if updater_ind==k:break

        ind = updater[updater_ind].pop()
        val = updater_ind

        #if val>=big:
        #    #Success
        #    break
        if turn>val:
            failed = True
            break
        charge[ind] += x - B[ind]*(turn-last_updated[ind])
        last_updated[ind] = turn
        next_update = turn + trunc(charge[ind]*Binv[ind])
        if next_update<k:
            updater[int(next_update)].append(ind)
    if failed:
        a = c+1
    else:
        b = c
if b == 2*10**12:
    print(-1)
else:
    print(b)
```


1174_E. Ehab and the Expected GCD Problem

Let's define a function f(p) on a permutation p as follows. Let g_i be the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of elements p_1, p_2, ..., p_i (in other words, it is the GCD of the prefix of length i). Then f(p) is the number of distinct elements among g_1, g_2, ..., g_n.

Let f_{max}(n) be the maximum value of f(p) among all permutations p of integers 1, 2, ..., n.

Given an integers n, count the number of permutations p of integers 1, 2, ..., n, such that f(p) is equal to f_{max}(n). Since the answer may be large, print the remainder of its division by 1000 000 007 = 10^9 + 7.

Input

The only line contains the integer n (2 ≤ n ≤ 10^6) — the length of the permutations.

Output

The only line should contain your answer modulo 10^9+7.

Examples

Input

2

Output

1

Input

3

Output

4

Input

6

Output

120

Note

Consider the second example: these are the permutations of length 3:

  * [1,2,3], f(p)=1.
  * [1,3,2], f(p)=1.
  * [2,1,3], f(p)=2.
  * [2,3,1], f(p)=2.
  * [3,1,2], f(p)=2.
  * [3,2,1], f(p)=2.

The maximum value f_{max}(3) = 2, and there are 4 permutations p such that f(p)=2.

```python
p=10**9+7
import math
def r(l):
    x=1
    for m in l:
        x=x*m%p
    return x
n=int(input())
a,k,x,t=[],int(math.log2(n)),n,0
while x>0:
    a.append(x-x//2)
    x//=2
b=[n//(3*2**i)-n//(6*2**i) for i in range(k+1)]
d=[n//2**i-n//(3*2**i) for i in range(k+1)]
y=r([i for i in range(2,n+1)])
s=k if n<3*2**(k-1) else 0
for j in range(s,k+1):
    e=[a[i] for i in range(j)]+[d[j]]+[b[i] for i in range(j,k)]
    x=y*r(e)%p
    f=r([sum(e[:i+1]) for i in range(k+1)])
    while f>1:
        x*=p//f+1
        f=f*(p//f+1)%p
    t+=x%p
print(t%p)
```


1210_C. Kamil and Making a Stream

Kamil likes streaming the competitive programming videos. His MeTube channel has recently reached 100 million subscribers. In order to celebrate this, he posted a video with an interesting problem he couldn't solve yet. Can you help him?

You're given a tree — a connected undirected graph consisting of n vertices connected by n - 1 edges. The tree is rooted at vertex 1. A vertex u is called an ancestor of v if it lies on the shortest path between the root and v. In particular, a vertex is an ancestor of itself.

Each vertex v is assigned its beauty x_v — a non-negative integer not larger than 10^{12}. This allows us to define the beauty of a path. Let u be an ancestor of v. Then we define the beauty f(u, v) as the greatest common divisor of the beauties of all vertices on the shortest path between u and v. Formally, if u=t_1, t_2, t_3, ..., t_k=v are the vertices on the shortest path between u and v, then f(u, v) = \gcd(x_{t_1}, x_{t_2}, ..., x_{t_k}). Here, \gcd denotes the greatest common divisor of a set of numbers. In particular, f(u, u) = \gcd(x_u) = x_u.

Your task is to find the sum

$$$ ∑_{u is an ancestor of v} f(u, v). $$$

As the result might be too large, please output it modulo 10^9 + 7.

Note that for each y, \gcd(0, y) = \gcd(y, 0) = y. In particular, \gcd(0, 0) = 0.

Input

The first line contains a single integer n (2 ≤ n ≤ 100 000) — the number of vertices in the tree.

The following line contains n integers x_1, x_2, ..., x_n (0 ≤ x_i ≤ 10^{12}). The value x_v denotes the beauty of vertex v.

The following n - 1 lines describe the edges of the tree. Each of them contains two integers a, b (1 ≤ a, b ≤ n, a ≠ b) — the vertices connected by a single edge.

Output

Output the sum of the beauties on all paths (u, v) such that u is ancestor of v. This sum should be printed modulo 10^9 + 7.

Examples

Input

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

Output

42

Input

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

Output

30

Note

The following figure shows all 10 possible paths for which one endpoint is an ancestor of another endpoint. The sum of beauties of all these paths is equal to 42:

<image>

```python
from math import gcd
from collections import deque
from bisect import bisect_left
from sys import setrecursionlimit

MOD = 1000000007

def modInt(mod):
    class ModInt:

        def __init__(self, value):
            self.value = value % mod

        def __int__(self):
            return self.value

        def __eq__(self, other):
            return self.value == other.value

        def __hash__(self):
            return hash(self.value)

        def __add__(self, other):
            return ModInt(self.value + int(other))

        def __sub__(self, other):
            return ModInt(self.value - int(other))

        def __mul__(self, other):
            return ModInt(self.value * int(other))

        def __floordiv__(self, other):
            return ModInt(self.value // int(other))

        def __truediv__(self, other):
            return ModInt(self.value * pow(int(other), mod - 2, mod))

    return ModInt

ModInt = modInt(MOD)

def main():
    n = int(input())
    setrecursionlimit(n+100)
    xx = [0] + [int(x) for x in input().split()]
    edges = []
    neighbors = [[] for _ in range(n+1)]
    for _ in range(n-1):
        v1, v2 = [int(x) for x in input().split()]
        neighbors[v1].append(v2)
        neighbors[v2].append(v1)
    visited = [False] * (n+1)
    dq = deque()
    dq.append((1,[]))
    sum = ModInt(0)
    while dq:
        u,gcds = dq.popleft()
        gcdns = [[xx[u], 1]]
        sum = (sum + xx[u])
        for g, c in gcds:
            gcdn = gcd(xx[u], g)
            sum = (sum + gcdn*c)
            if gcdn == gcdns[-1][0]:
                gcdns[-1][1] += c
            else:
                gcdns.append([gcdn, c])
        visited[u] = True
        for v in neighbors[u]:
            if not visited[v]:
                dq.append((v, gcdns))
    print(int(sum))

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


1231_A. Dawid and Bags of Candies

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

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

Input

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

Output

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

Examples

Input

1 7 11 5

Output

YES

Input

7 3 2 5

Output

NO

Note

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

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


1272_C. Yet Another Broken Keyboard

Recently, Norge found a string s = s_1 s_2 … s_n consisting of n lowercase Latin letters. As an exercise to improve his typing speed, he decided to type all substrings of the string s. Yes, all (n (n + 1))/(2) of them!

A substring of s is a non-empty string x = s[a … b] = s_{a} s_{a + 1} … s_{b} (1 ≤ a ≤ b ≤ n). For example, "auto" and "ton" are substrings of "automaton".

Shortly after the start of the exercise, Norge realized that his keyboard was broken, namely, he could use only k Latin letters c_1, c_2, …, c_k out of 26.

After that, Norge became interested in how many substrings of the string s he could still type using his broken keyboard. Help him to find this number.

Input

The first line contains two space-separated integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ k ≤ 26) — the length of the string s and the number of Latin letters still available on the keyboard.

The second line contains the string s consisting of exactly n lowercase Latin letters.

The third line contains k space-separated distinct lowercase Latin letters c_1, c_2, …, c_k — the letters still available on the keyboard.

Output

Print a single number — the number of substrings of s that can be typed using only available letters c_1, c_2, …, c_k.

Examples

Input

7 2
abacaba
a b

Output

12

Input

10 3
sadfaasdda
f a d

Output

21

Input

7 1
aaaaaaa
b

Output

0

Note

In the first example Norge can print substrings s[1…2], s[2…3], s[1…3], s[1…1], s[2…2], s[3…3], s[5…6], s[6…7], s[5…7], s[5…5], s[6…6], s[7…7].

```python
n, k = [int(i) for i in input().split()]
s = input()
arr = input().split()

subs = [0]
for x in s:
  if(x in arr): subs[-1] += 1
  else:
    subs.append(0)

count = 0
for x in subs:
  count += x*(x+1)/2

print(int(count))
```


1295_D. Same GCDs

You are given two integers a and m. Calculate the number of integers x such that 0 ≤ x < m and \gcd(a, m) = \gcd(a + x, m).

Note: \gcd(a, b) is the greatest common divisor of a and b.

Input

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

Next T lines contain test cases — one per line. Each line contains two integers a and m (1 ≤ a < m ≤ 10^{10}).

Output

Print T integers — one per test case. For each test case print the number of appropriate x-s.

Example

Input

3
4 9
5 10
42 9999999967

Output

6
1
9999999966

Note

In the first test case appropriate x-s are [0, 1, 3, 4, 6, 7].

In the second test case the only appropriate x is 0.

```python
import sys, math

for ii in range(int(input())):
    a,m = map(int,input().split())
    g = math.gcd(a,m)
    m=int(m/g)
    ans = m
    for i in range(2,int(math.sqrt(m))+1):
        if m%i==0:
            ans-=(ans/i)
        while m%i==0:
            m=int(m/i)
    if m>1:
        ans-=ans/m
    print(int(ans))
#3SUPE
```


1316_D. Nash Matrix

Nash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands.

This board game is played on the n× n board. Rows and columns of this board are numbered from 1 to n. The cell on the intersection of the r-th row and c-th column is denoted by (r, c).

Some cells on the board are called blocked zones. On each cell of the board, there is written one of the following 5 characters — U, D, L, R or X — instructions for the player. Suppose that the current cell is (r, c). If the character is R, the player should move to the right cell (r, c+1), for L the player should move to the left cell (r, c-1), for U the player should move to the top cell (r-1, c), for D the player should move to the bottom cell (r+1, c). Finally, if the character in the cell is X, then this cell is the blocked zone. The player should remain in this cell (the game for him isn't very interesting from now on).

It is guaranteed that the characters are written in a way that the player will never have to step outside of the board, no matter at which cell he starts.

As a player starts from a cell, he moves according to the character in the current cell. The player keeps moving until he lands in a blocked zone. It is also possible that the player will keep moving infinitely long.

For every of the n^2 cells of the board Alice, your friend, wants to know, how will the game go, if the player starts in this cell. For each starting cell of the board, she writes down the cell that the player stops at, or that the player never stops at all. She gives you the information she has written: for each cell (r, c) she wrote:

  * a pair (x,y), meaning if a player had started at (r, c), he would end up at cell (x,y).
  * or a pair (-1,-1), meaning if a player had started at (r, c), he would keep moving infinitely long and would never enter the blocked zone.

It might be possible that Alice is trying to fool you and there's no possible grid that satisfies all the constraints Alice gave you. For the given information Alice provided you, you are required to decipher a possible board, or to determine that such a board doesn't exist. If there exist several different boards that satisfy the provided information, you can find any of them.

Input

The first line of the input contains a single integer n (1 ≤ n ≤ 10^{3}) — the side of the board.

The i-th of the next n lines of the input contains 2n integers x_1, y_1, x_2, y_2, ..., x_n, y_n, where (x_j, y_j) (1 ≤ x_j ≤ n, 1 ≤ y_j ≤ n, or (x_j,y_j)=(-1,-1)) is the pair written by Alice for the cell (i, j).

Output

If there doesn't exist a board satisfying the information that Alice gave you, print a single line containing INVALID.

Otherwise, in the first line print VALID. In the i-th of the next n lines, print the string of n characters, corresponding to the characters in the i-th row of the suitable board you found. Each character of a string can either be U, D, L, R or X. If there exist several different boards that satisfy the provided information, you can find any of them.

Examples

Input

2
1 1 1 1
2 2 2 2

Output

VALID
XL
RX

Input

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

Output

VALID
RRD
UXD
ULL

Note

For the sample test 1 :

The given grid in output is a valid one.

  * If the player starts at (1,1), he doesn't move any further following X and stops there.
  * If the player starts at (1,2), he moves to left following L and stops at (1,1).
  * If the player starts at (2,1), he moves to right following R and stops at (2,2).
  * If the player starts at (2,2), he doesn't move any further following X and stops there.

The simulation can be seen below :

<image>

For the sample test 2 :

The given grid in output is a valid one, as a player starting at any cell other than the one at center (2,2), keeps moving in an infinitely long cycle and never stops. Had he started at (2,2), he wouldn't have moved further following instruction X .

The simulation can be seen below :

<image>

```python
from collections import deque
import sys
def input(): return sys.stdin.buffer.readline()[:-1]

def main():
    n = int(input())

    res = [[''] * n for _ in range(n)]

    data = [[None] * n for _ in range(n)]

    q = deque()
    for i in range(n):
        row = [int(x) - 1 for x in input().split()]
        for j in range(n):
            data[i][j] = (row[j * 2], row[j * 2 + 1])
            if (i, j) == data[i][j]:
                q.append((i, j))
                res[i][j] = 'X'

    while q:
        i, j = q.popleft()
        if 0 <= i + 1 < n and 0 <= j < n and data[i+1][j] == data[i][j] and not res[i+1][j]:
            res[i + 1][j] = 'U'
            q.append((i + 1, j))
        if 0 <= i - 1 < n and 0 <= j < n and data[i-1][j] == data[i][j] and not res[i-1][j]:
            res[i - 1][j] = 'D'
            q.append((i - 1, j))
        if 0 <= i < n and 0 <= j + 1 < n and data[i][j+1] == data[i][j] and not res[i][j+1]:
            res[i][j + 1] = 'L'
            q.append((i, j + 1))
        if 0 <= i < n and 0 <= j - 1 < n and data[i][j-1] == data[i][j] and not res[i][j-1]:
            res[i][j - 1] = 'R'
            q.append((i, j - 1))

    for i in range(n):
        for j in range(n):
            if data[i][j] == (-2, -2):
                if 0 <= i + 1 < n and 0 <= j < n and data[i+1][j] == (-2, -2):
                    res[i][j] = 'D'
                elif 0 <= i - 1 < n and 0 <= j < n and data[i-1][j] == (-2, -2):
                    res[i][j] = 'U'
                elif 0 <= i < n and 0 <= j + 1 < n and data[i][j+1] == (-2, -2):
                    res[i][j] = 'R'
                elif 0 <= i < n and 0 <= j - 1 < n and data[i][j-1] == (-2, -2):
                    res[i][j] = 'L'
                else:
                    print("INVALID")
                    exit()

    total = []
    for e in res:
        if '' in e:
            print("INVALID")
            exit()
        total.append(''.join(e))

    print("VALID")
    print('\n'.join(total), flush=True)

main()
```


137_E. Last Chance

Having read half of the book called "Storm and Calm" on the IT lesson, Innocentius was absolutely determined to finish the book on the maths lessons. All was fine until the math teacher Ms. Watkins saw Innocentius reading fiction books instead of solving equations of the fifth degree. As during the last maths class Innocentius suggested the algorithm of solving equations of the fifth degree in the general case, Ms. Watkins had no other choice but to give him a new task.

The teacher asked to write consecutively (without spaces) all words from the "Storm and Calm" in one long string s. She thought that a string is good if the number of vowels in the string is no more than twice more than the number of consonants. That is, the string with v vowels and c consonants is good if and only if v ≤ 2c.

The task Innocentius had to solve turned out to be rather simple: he should find the number of the longest good substrings of the string s.

Input

The only input line contains a non-empty string s consisting of no more than 2·105 uppercase and lowercase Latin letters. We shall regard letters "a", "e", "i", "o", "u" and their uppercase variants as vowels.

Output

Print on a single line two numbers without a space: the maximum length of a good substring and the number of good substrings with this length. If no good substring exists, print "No solution" without the quotes.

Two substrings are considered different if their positions of occurrence are different. So if some string occurs more than once, then it should be counted more than once.

Examples

Input

Abo

Output

3 1

Input

OEIS

Output

3 1

Input

auBAAbeelii

Output

9 3

Input

AaaBRAaaCAaaDAaaBRAaa

Output

18 4

Input

EA

Output

No solution

Note

In the first sample there is only one longest good substring: "Abo" itself. The other good substrings are "b", "Ab", "bo", but these substrings have shorter length.

In the second sample there is only one longest good substring: "EIS". The other good substrings are: "S", "IS".

```python
s=[(0,0)]
c=0
for i,x in enumerate(input()) :
  c+=-1 if x.lower() in 'aeiou' else 2
  s.append((c,i+1))
#print(s)
lis = sorted(s)
#print(lis)
u = 10**9
d = {}
answer = 0
for i in lis :
    if u <  i[1] :
        if i[1]-u >= answer :
            answer = i[1]-u
            d[answer] = d.get(answer , 0) + 1
    else :
        u = min(u,i[1])
if answer!=0 :
  print(answer,d[answer])
else :
    print("No solution")

```


1444_A. Division

Oleg's favorite subjects are History and Math, and his favorite branch of mathematics is division.

To improve his division skills, Oleg came up with t pairs of integers p_i and q_i and for each pair decided to find the greatest integer x_i, such that:

  * p_i is divisible by x_i;
  * x_i is not divisible by q_i.

Oleg is really good at division and managed to find all the answers quickly, how about you?

Input

The first line contains an integer t (1 ≤ t ≤ 50) — the number of pairs.

Each of the following t lines contains two integers p_i and q_i (1 ≤ p_i ≤ 10^{18}; 2 ≤ q_i ≤ 10^{9}) — the i-th pair of integers.

Output

Print t integers: the i-th integer is the largest x_i such that p_i is divisible by x_i, but x_i is not divisible by q_i.

One can show that there is always at least one value of x_i satisfying the divisibility conditions for the given constraints.

Example

Input

3
10 4
12 6
179 822

Output

10
4
179

Note

For the first pair, where p_1 = 10 and q_1 = 4, the answer is x_1 = 10, since it is the greatest divisor of 10 and 10 is not divisible by 4.

For the second pair, where p_2 = 12 and q_2 = 6, note that

  * 12 is not a valid x_2, since 12 is divisible by q_2 = 6;
  * 6 is not valid x_2 as well: 6 is also divisible by q_2 = 6.

The next available divisor of p_2 = 12 is 4, which is the answer, since 4 is not divisible by 6.

```python
from sys import stdin, stdout
from math import sqrt
#stdin = open('Q3.txt', 'r')
def II(): return int(stdin.readline())
def MI(): return map(int, stdin.readline().split())
bigp=10**18+7

primes=[]
def SieveOfEratosthenes(n,primes):
    prime = [True for i in range(n+1)]
    p = 2
    while (p * p <= n):
        if (prime[p] == True):
            for i in range(p * p, n+1, p):
                prime[i] = False
        p += 1
    for p in range(2, n):
        if prime[p]:
            primes.append(p)

def solve():
    p,q=MI()
    if p%q != 0:
        ans=p
    else:
        x,y=q,p
        mind=bigp
        sqrtq=int(sqrt(q))
        sp=[i for i in primes if i<=sqrtq]+[bigp]
        for i in sp:
            j=i
            if x==1:
                break
            qe=0
            while x%j==0:
                qe+=1
                x=x//j
            if i==bigp:
                qe,j=1,x
            if qe>0:
                pe=qe
                y=y//pow(j,qe)
                while y%j==0:
                    pe+=1
                    y=y//j
                mind=min(mind,pow(j,pe-qe+1))
        ans=p//mind
    stdout.write(str(ans)+"\n")

SieveOfEratosthenes(32000,primes)
t=II()
for _ in range(t):
    solve()
```


1469_B. Red and Blue

Monocarp had a sequence a consisting of n + m integers a_1, a_2, ..., a_{n + m}. He painted the elements into two colors, red and blue; n elements were painted red, all other m elements were painted blue.

After painting the elements, he has written two sequences r_1, r_2, ..., r_n and b_1, b_2, ..., b_m. The sequence r consisted of all red elements of a in the order they appeared in a; similarly, the sequence b consisted of all blue elements of a in the order they appeared in a as well.

Unfortunately, the original sequence was lost, and Monocarp only has the sequences r and b. He wants to restore the original sequence. In case there are multiple ways to restore it, he wants to choose a way to restore that maximizes the value of

$$$f(a) = max(0, a_1, (a_1 + a_2), (a_1 + a_2 + a_3), ..., (a_1 + a_2 + a_3 + ... + a_{n + m}))$$$

Help Monocarp to calculate the maximum possible value of f(a).

Input

The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. Then the test cases follow. Each test case consists of four lines.

The first line of each test case contains one integer n (1 ≤ n ≤ 100).

The second line contains n integers r_1, r_2, ..., r_n (-100 ≤ r_i ≤ 100).

The third line contains one integer m (1 ≤ m ≤ 100).

The fourth line contains m integers b_1, b_2, ..., b_m (-100 ≤ b_i ≤ 100).

Output

For each test case, print one integer — the maximum possible value of f(a).

Example

Input

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

Output

13
13
0
0

Note

In the explanations for the sample test cases, red elements are marked as bold.

In the first test case, one of the possible sequences a is [6, 2, -5, 3, 7, -3, -4].

In the second test case, one of the possible sequences a is [10, 1, -3, 1, 2, 2].

In the third test case, one of the possible sequences a is [-1, -1, -2, -3, -2, -4, -5, -3, -4, -5].

In the fourth test case, one of the possible sequences a is [0, 0].

```python
for _ in range(int(input())):
    n=int(input())
    r=list(map(int,input().split()))
    m=int(input())
    b=list(map(int,input().split()))
    c,t,prev,prevv=0,0,0,0
    for i in r:
        t+=i
        prev=max(t,prev)

    t=0
    for i in b:
        t+=i
        prevv=max(t,prevv)

    if prev <0:prev=0
    elif prevv <0:prevv=0

    print(prev+prevv)

```


1494_D. Dogeforces

The Dogeforces company has k employees. Each employee, except for lower-level employees, has at least 2 subordinates. Lower-level employees have no subordinates. Each employee, except for the head of the company, has exactly one direct supervisor. The head of the company is a direct or indirect supervisor of all employees. It is known that in Dogeforces, each supervisor receives a salary strictly more than all his subordinates.

The full structure of the company is a secret, but you know the number of lower-level employees and for each pair of lower-level employees, the salary of their common supervisor is known (if there are several such supervisors, then the supervisor with the minimum salary). You have to restore the structure of the company.

Input

The first line contains a single integer n (2 ≤ n ≤ 500) — the number of lower-level employees.

This is followed by n lines, where i-th line contains n integers a_{i,1}, a_{i,2}, ..., a_{i,n} (1 ≤ a_{i,j} ≤ 5000) — salary of the common supervisor of employees with numbers i and j. It is guaranteed that a_{i,j} = a_{j,i}. Note that a_{i,i} is equal to the salary of the i-th employee.

Output

In the first line, print a single integer k — the number of employees in the company.

In the second line, print k integers c_1, c_2, ..., c_k, where c_i is the salary of the employee with the number i.

In the third line, print a single integer r — the number of the employee who is the head of the company.

In the following k-1 lines, print two integers v and u (1 ≤ v, u ≤ k) — the number of the employee and his direct supervisor.

Note that the lower-level employees have numbers from 1 to n, and for the rest of the employees, you have to assign numbers from n+1 to k. If there are several correct company structures, you can print any of them.

Example

Input

3
2 5 7
5 1 7
7 7 4

Output

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

Note

One of the possible structures in the first example: <image>

```python
import heapq
class UF:
    def __init__(self, N):
        self.par = list(range(N))
        self.sz = [1] * N

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

    def union(self, x, y):
        xr, yr = self.find(x), self.find(y)
        if xr == yr:
            return False
        if self.sz[xr] < self.sz[yr]:
            xr, yr = yr, xr
        self.par[yr] = xr
        self.sz[xr] += self.sz[yr]
        return True

    def size(self, x):
        return self.sz[self.find(x)]

    def connected(self, x, y):
        return self.find(x) == self.find(y)

def main():
    n = int(input())
    uf = UF(n*n+1)
    heap = []
    ans_list = []
    edges = []
    parent_map = {i : i for i in range(n**2 + 1)}

    for i in range(n):
        cur_lst = list(map(int, input().split(' ')))
        for j in range(i, n):
            if i == j:
                ans_list.append(cur_lst[j])
            else:
                heapq.heappush(heap, (cur_lst[j], i, j))

    while heap:
        cur_anc_salary, low1, low2 = heapq.heappop(heap)
        c1, c2 = parent_map[uf.find(low1)], parent_map[uf.find(low2)]
        # already connected
        if c1 == c2:
            continue
        # add kid to c1
        if ans_list[c1] == cur_anc_salary:
           edges.append((c2, c1))
           uf.union(c1, c2)
           parent_map[uf.find(c1)] = c1
        elif ans_list[c2] == cur_anc_salary:
           edges.append((c1, c2))
           uf.union(c1, c2)
           parent_map[uf.find(c1)] = c2
        else:
            new_node = len(ans_list)
            ans_list.append(cur_anc_salary)
            uf.union(c1, c2)
            uf.union(c1, new_node)
            edges.append((c1, new_node))
            edges.append((c2, new_node))
            parent_map[uf.find(new_node)] = new_node

    print(len(ans_list))
    print(" ".join(map(str, ans_list)))
    print(len(ans_list))
    for x,y in edges:
        print("{} {}".format(x+1, y+1))

# region fastio
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")

# endregion

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


1517_C. Fillomino 2

Fillomino is a classic logic puzzle. (You do not need to know Fillomino in order to solve this problem.) In one classroom in Yunqi town, some volunteers are playing a board game variant of it:

Consider an n by n chessboard. Its rows are numbered from 1 to n from the top to the bottom. Its columns are numbered from 1 to n from the left to the right. A cell on an intersection of x-th row and y-th column is denoted (x, y). The main diagonal of the chessboard is cells (x, x) for all 1 ≤ x ≤ n.

A permutation of \{1, 2, 3, ..., n\} is written on the main diagonal of the chessboard. There is exactly one number written on each of the cells. The problem is to partition the cells under and on the main diagonal (there are exactly 1+2+ … +n such cells) into n connected regions satisfying the following constraints:

  1. Every region should be connected. That means that we can move from any cell of a region to any other cell of the same region visiting only cells of the same region and moving from a cell to an adjacent cell.
  2. The x-th region should contain cell on the main diagonal with number x for all 1≤ x≤ n.
  3. The number of cells that belong to the x-th region should be equal to x for all 1≤ x≤ n.
  4. Each cell under and on the main diagonal should belong to exactly one region.

Input

The first line contains a single integer n (1≤ n ≤ 500) denoting the size of the chessboard.

The second line contains n integers p_1, p_2, ..., p_n. p_i is the number written on cell (i, i). It is guaranteed that each integer from \{1, …, n\} appears exactly once in p_1, ..., p_n.

Output

If no solution exists, output -1.

Otherwise, output n lines. The i-th line should contain i numbers. The j-th number on the i-th line should be x if cell (i, j) belongs to the the region with x cells.

Examples

Input

3
2 3 1

Output

2
2 3
3 3 1

Input

5
1 2 3 4 5

Output

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

Note

The solutions to the examples are illustrated in the following pictures: <image> <image>

```python
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")
#######################################
n=int(input())
l=list(map(int,input().split()))
l1=[[0]*n for i in range(n)]
for i in range(n):
    c=l[i]
    x=i
    y=x
    while c:
        for j in range(y,-1,-1):
##            print(x,y,l1)
            if l1[x][j]:
                j+=1
                break
            if not c:
                break
            l1[x][j]=l[i]
            c-=1
        y=j
        x+=1
l2=[]
for i in l1:
    l3=[]
    for j in i:
        if j==0:
            break
        l3.append(j)
    l2.append(l3)
for i in l2:
    print(*i)

```


1545_B. AquaMoon and Chess

Cirno gave AquaMoon a chessboard of size 1 × n. Its cells are numbered with integers from 1 to n from left to right. In the beginning, some of the cells are occupied with at most one pawn, and other cells are unoccupied.

In each operation, AquaMoon can choose a cell i with a pawn, and do either of the following (if possible):

  * Move pawn from it to the (i+2)-th cell, if i+2 ≤ n and the (i+1)-th cell is occupied and the (i+2)-th cell is unoccupied.
  * Move pawn from it to the (i-2)-th cell, if i-2 ≥ 1 and the (i-1)-th cell is occupied and the (i-2)-th cell is unoccupied.

You are given an initial state of the chessboard. AquaMoon wants to count the number of states reachable from the initial state with some sequence of operations. But she is not good at programming. Can you help her? As the answer can be large find it modulo 998 244 353.

Input

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

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

The second line contains a string of n characters, consists of characters "0" and "1". If the i-th character is "1", the i-th cell is initially occupied; otherwise, the i-th cell is initially unoccupied.

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

Output

For each test case, print the number of states that reachable from the initial state with some sequence of operations modulo 998 244 353.

Example

Input

6
4
0110
6
011011
5
01010
20
10001111110110111000
20
00110110100110111101
20
11101111011000100010

Output

3
6
1
1287
1287
715

Note

In the first test case the strings "1100", "0110" and "0011" are reachable from the initial state with some sequence of operations.

```python
from sys import stdin, stdout
import heapq
from collections import defaultdict
import math
import bisect
import io, os

# for interactive problem
# n = int(stdin.readline())
# print(x, flush=True)

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

def ncr(n, r, p):
    # initialize numerator
    # and denominator
    num = den = 1
    for i in range(r):
        num = (num * (n - i)) % p
        den = (den * (i + 1)) % p
    return (num * pow(den,
            p - 2, p)) % p

def main():
    #n = int(input())
    t = int(stdin.readline())
    MOD = 998244353
    for _ in range(t):
        n = int(stdin.readline())
        s = stdin.readline().strip()
        z = 0
        b = 0
        i = 0
        while i < n:
            if s[i] == '0':
                z += 1
                i += 1
                continue
            elif i + 1 < n and s[i] == s[i + 1] == '1':
                b += 1
                i += 2
                continue
            i += 1
        ans = ncr(z+b, z, MOD)
        stdout.write(str(ans)+"\n")

main()

```


172_A. Phone Code

Polycarpus has n friends in Tarasov city. Polycarpus knows phone numbers of all his friends: they are strings s1, s2, ..., sn. All these strings consist only of digits and have the same length.

Once Polycarpus needed to figure out Tarasov city phone code. He assumed that the phone code of the city is the longest common prefix of all phone numbers of his friends. In other words, it is the longest string c which is a prefix (the beginning) of each si for all i (1 ≤ i ≤ n). Help Polycarpus determine the length of the city phone code.

Input

The first line of the input contains an integer n (2 ≤ n ≤ 3·104) — the number of Polycarpus's friends. The following n lines contain strings s1, s2, ..., sn — the phone numbers of Polycarpus's friends. It is guaranteed that all strings consist only of digits and have the same length from 1 to 20, inclusive. It is also guaranteed that all strings are different.

Output

Print the number of digits in the city phone code.

Examples

Input

4
00209
00219
00999
00909

Output

2

Input

2
1
2

Output

0

Input

3
77012345678999999999
77012345678901234567
77012345678998765432

Output

12

Note

A prefix of string t is a string that is obtained by deleting zero or more digits from the end of string t. For example, string "00209" has 6 prefixes: "" (an empty prefix), "0", "00", "002", "0020", "00209".

In the first sample the city phone code is string "00".

In the second sample the city phone code is an empty string.

In the third sample the city phone code is string "770123456789".

```python
n = int(input())

phone = []

for i in range(n):
    s = input().strip()
    phone.append(s)

c = 0
k = 0
flag = True
while True:
    for p in phone:
        if p[k] != phone[0][k]:
            flag = False
            break
    k += 1

    if flag:
        c += 1
    else:
        print(c)
        break

```


192_B. Walking in the Rain

In Berland the opposition is going to arrange mass walking on the boulevard. The boulevard consists of n tiles that are lain in a row and are numbered from 1 to n from right to left. The opposition should start walking on the tile number 1 and the finish on the tile number n. During the walk it is allowed to move from right to left between adjacent tiles in a row, and jump over a tile. More formally, if you are standing on the tile number i (i < n - 1), you can reach the tiles number i + 1 or the tile number i + 2 from it (if you stand on the tile number n - 1, you can only reach tile number n). We can assume that all the opposition movements occur instantaneously.

In order to thwart an opposition rally, the Berland bloody regime organized the rain. The tiles on the boulevard are of poor quality and they are rapidly destroyed in the rain. We know that the i-th tile is destroyed after ai days of rain (on day ai tile isn't destroyed yet, and on day ai + 1 it is already destroyed). Of course, no one is allowed to walk on the destroyed tiles! So the walk of the opposition is considered thwarted, if either the tile number 1 is broken, or the tile number n is broken, or it is impossible to reach the tile number n from the tile number 1 if we can walk on undestroyed tiles.

The opposition wants to gather more supporters for their walk. Therefore, the more time they have to pack, the better. Help the opposition to calculate how much time they still have and tell us for how many days the walk from the tile number 1 to the tile number n will be possible.

Input

The first line contains integer n (1 ≤ n ≤ 103) — the boulevard's length in tiles.

The second line contains n space-separated integers ai — the number of days after which the i-th tile gets destroyed (1 ≤ ai ≤ 103).

Output

Print a single number — the sought number of days.

Examples

Input

4
10 3 5 10

Output

5

Input

5
10 2 8 3 5

Output

5

Note

In the first sample the second tile gets destroyed after day three, and the only path left is 1 → 3 → 4. After day five there is a two-tile gap between the first and the last tile, you can't jump over it.

In the second sample path 1 → 3 → 5 is available up to day five, inclusive. On day six the last tile is destroyed and the walk is thwarted.

```python
n=int(input())
l=list(map(int,input().split()))
c=9999
for i in range(n-1):
    if(l[i]<=l[i+1] and l[i+1]<c):
        c=l[i+1]
    elif(l[i]>l[i+1] and l[i]<c):
        c=l[i]
print(min(l[0],l[n-1],c))
```


216_B. Forming Teams

One day n students come to the stadium. They want to play football, and for that they need to split into teams, the teams must have an equal number of people.

We know that this group of people has archenemies. Each student has at most two archenemies. Besides, if student A is an archenemy to student B, then student B is an archenemy to student A.

The students want to split so as no two archenemies were in one team. If splitting in the required manner is impossible, some students will have to sit on the bench.

Determine the minimum number of students you will have to send to the bench in order to form the two teams in the described manner and begin the game at last.

Input

The first line contains two integers n and m (2 ≤ n ≤ 100, 1 ≤ m ≤ 100) — the number of students and the number of pairs of archenemies correspondingly.

Next m lines describe enmity between students. Each enmity is described as two numbers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — the indexes of the students who are enemies to each other. Each enmity occurs in the list exactly once. It is guaranteed that each student has no more than two archenemies.

You can consider the students indexed in some manner with distinct integers from 1 to n.

Output

Print a single integer — the minimum number of students you will have to send to the bench in order to start the game.

Examples

Input

5 4
1 2
2 4
5 3
1 4

Output

1

Input

6 2
1 4
3 4

Output

0

Input

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

Output

2

```python
def arr_inp():
    return [int(x) for x in stdin.readline().split()]

class graph:
    # initialize graph
    def __init__(self, gdict=None):
        if gdict is None:
            gdict = defaultdict(list)
        self.gdict = gdict

    # get edges
    def edges(self):
        return self.find_edges()

    # find edges
    def find_edges(self):
        edges = []
        for node in self.gdict:
            for nxNode in self.gdict[node]:
                if {nxNode, node} not in edges:
                    edges.append({node, nxNode})
        return edges

    # Get verticies
    def get_vertices(self):
        return list(self.gdict.keys())

    # add vertix
    def add_vertix(self, node):
        self.gdict[node] = []

    # add edge
    def add_edge(self, node1, node2):
        self.gdict[node1].append(node2)
        self.gdict[node2].append(node1)

    def dfsUtil(self, v, par):

        self.visit[v] = 1

        for i in self.gdict[v]:
            if self.visit[i] == 0:
                self.dfsUtil(i, v)
                self.topsort += 1
            elif i != par and v != par:
                self.topsort += 1
                self.flag = 1

    # dfs for graph
    def dfs(self):
        self.visit, self.cnt, self.topsort, self.flag = defaultdict(int), 0, 0, 0

        for i in self.get_vertices():
            if self.visit[i] == 0:
                self.dfsUtil(i, i)

                if self.topsort & 1 and self.topsort >= 3 and self.flag:
                    self.cnt += 1
                self.flag = 0
                self.topsort = 0
        return self.cnt

from collections import defaultdict
from sys import stdin

n, m = arr_inp()
student = graph()
for i in range(m):
    a, b = arr_inp()
    student.add_edge(a, b)

ans = student.dfs()
print(ans + 1 if (n - ans) & 1 else ans)

```


23_B. Party

n people came to a party. Then those, who had no friends among people at the party, left. Then those, who had exactly 1 friend among those who stayed, left as well. Then those, who had exactly 2, 3, ..., n - 1 friends among those who stayed by the moment of their leaving, did the same.

What is the maximum amount of people that could stay at the party in the end?

Input

The first input line contains one number t — amount of tests (1 ≤ t ≤ 105). Each of the following t lines contains one integer number n (1 ≤ n ≤ 105).

Output

For each test output in a separate line one number — the maximum amount of people that could stay in the end.

Examples

Input

1
3

Output

1

```python
for i in range(int(input())):
 x = int(input())
 print(max(0,x-2))
```


336_B. Vasily the Bear and Fly

One beautiful day Vasily the bear painted 2m circles of the same radius R on a coordinate plane. Circles with numbers from 1 to m had centers at points (2R - R, 0), (4R - R, 0), ..., (2Rm - R, 0), respectively. Circles with numbers from m + 1 to 2m had centers at points (2R - R, 2R), (4R - R, 2R), ..., (2Rm - R, 2R), respectively.

Naturally, the bear painted the circles for a simple experiment with a fly. The experiment continued for m2 days. Each day of the experiment got its own unique number from 0 to m2 - 1, inclusive.

On the day number i the following things happened:

  1. The fly arrived at the coordinate plane at the center of the circle with number <image> (<image> is the result of dividing number x by number y, rounded down to an integer).
  2. The fly went along the coordinate plane to the center of the circle number <image> (<image> is the remainder after dividing number x by number y). The bear noticed that the fly went from the center of circle v to the center of circle u along the shortest path with all points lying on the border or inside at least one of the 2m circles. After the fly reached the center of circle u, it flew away in an unknown direction.

Help Vasily, count the average distance the fly went along the coordinate plane during each of these m2 days.

Input

The first line contains two integers m, R (1 ≤ m ≤ 105, 1 ≤ R ≤ 10).

Output

In a single line print a single real number — the answer to the problem. The answer will be considered correct if its absolute or relative error doesn't exceed 10 - 6.

Examples

Input

1 1

Output

2.0000000000

Input

2 2

Output

5.4142135624

Note

<image>

Figure to the second sample

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

def calc(k):
    if k < 1:
        return 0
    else:
        return (1 + 2 * (k - 1)) * 2**0.5 + k * 2 + (k - 1) * (k - 2)

avg = 0
div = m ** 2

for i in range(0, m):
    avg += r * (2 + calc(i) + calc(m - 1 - i)) / div

print(avg)

```


359_C. Prime Number

Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.

Simon loves fractions very much. Today he wrote out number <image> on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: <image>, where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction.

Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7).

Input

The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number.

The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109).

Output

Print a single number — the answer to the problem modulo 1000000007 (109 + 7).

Examples

Input

2 2
2 2

Output

8

Input

3 3
1 2 3

Output

27

Input

2 2
29 29

Output

73741817

Input

4 5
0 0 0 0

Output

1

Note

In the first sample <image>. Thus, the answer to the problem is 8.

In the second sample, <image>. The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.

In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.

In the fourth sample <image>. Thus, the answer to the problem is 1.

```python
import sys
import heapq
input = sys.stdin.readline
MOD = int(1e9+7)

n, x = list(map(int, input().split()))
a = list(map(int, input().split()))
s, h = sum(a), []
for i in a:
    heapq.heappush(h, s-i)
p, cnt = 0, 0
while h:
    z = heapq.heappop(h)
    if p == z:
        cnt += 1
        if cnt == x:
            heapq.heappush(h, p + 1)
            cnt = 0
    else:
        if cnt > 0:
            print(pow(x, min(p, s), MOD))
            exit()
        cnt = 1
        p = z
print(pow(x, min(p, s), MOD))

```


382_B. Number Busters

Arthur and Alexander are number busters. Today they've got a competition.

Arthur took a group of four integers a, b, w, x (0 ≤ b < w, 0 < x < w) and Alexander took integer с. Arthur and Alexander use distinct approaches to number bustings. Alexander is just a regular guy. Each second, he subtracts one from his number. In other words, he performs the assignment: c = c - 1. Arthur is a sophisticated guy. Each second Arthur performs a complex operation, described as follows: if b ≥ x, perform the assignment b = b - x, if b < x, then perform two consecutive assignments a = a - 1; b = w - (x - b).

You've got numbers a, b, w, x, c. Determine when Alexander gets ahead of Arthur if both guys start performing the operations at the same time. Assume that Alexander got ahead of Arthur if c ≤ a.

Input

The first line contains integers a, b, w, x, c (1 ≤ a ≤ 2·109, 1 ≤ w ≤ 1000, 0 ≤ b < w, 0 < x < w, 1 ≤ c ≤ 2·109).

Output

Print a single integer — the minimum time in seconds Alexander needs to get ahead of Arthur. You can prove that the described situation always occurs within the problem's limits.

Examples

Input

4 2 3 1 6

Output

2

Input

4 2 3 1 7

Output

4

Input

1 2 3 2 6

Output

13

Input

1 1 2 1 1

Output

0

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

def result(a, b, w, x, c, s):
	na = a - (s * x - b) / w
	nc = c - s
	return (na, nc)

def solve(a, b, w, x, c):
	left = 0
	right = 10e15
	if (c <= a):
		return 0

	while (left < right):
		half = (left+right) // 2
		ret = result(a, b, w, x, c, half)
		if (ret[1] <= ret[0]):
			right = half
		else:
			left = half + 1

	return left

print(int(solve(a, b, w, x, c)))
```


403_A. Searching for Graph

Let's call an undirected graph of n vertices p-interesting, if the following conditions fulfill:

  * the graph contains exactly 2n + p edges;
  * the graph doesn't contain self-loops and multiple edges;
  * for any integer k (1 ≤ k ≤ n), any subgraph consisting of k vertices contains at most 2k + p edges.

A subgraph of a graph is some set of the graph vertices and some set of the graph edges. At that, the set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices.

Your task is to find a p-interesting graph consisting of n vertices.

Input

The first line contains a single integer t (1 ≤ t ≤ 5) — the number of tests in the input. Next t lines each contains two space-separated integers: n, p (5 ≤ n ≤ 24; p ≥ 0; <image>) — the number of vertices in the graph and the interest value for the appropriate test.

It is guaranteed that the required graph exists.

Output

For each of the t tests print 2n + p lines containing the description of the edges of a p-interesting graph: the i-th line must contain two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — two vertices, connected by an edge in the resulting graph. Consider the graph vertices numbered with integers from 1 to n.

Print the answers to the tests in the order the tests occur in the input. If there are multiple solutions, you can print any of them.

Examples

Input

1
6 0

Output

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

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

while t > 0:
    [n, p] = map(int, input().split(' '))
    count = int(0)
    for i in range(n):
        j = i+2
        while j <= n:
            count = count+1
            print(str(i+1)+' '+str(j))
            if count == 2*n+p:
                break
            j = j + 1
        if j <= n:
            break
    t = t-1
```


430_B. Balls Game

Iahub is training for the IOI. What is a better way to train than playing a Zuma-like game?

There are n balls put in a row. Each ball is colored in one of k colors. Initially the row doesn't contain three or more contiguous balls with the same color. Iahub has a single ball of color x. He can insert his ball at any position in the row (probably, between two other balls). If at any moment there are three or more contiguous balls of the same color in the row, they are destroyed immediately. This rule is applied multiple times, until there are no more sets of 3 or more contiguous balls of the same color.

For example, if Iahub has the row of balls [black, black, white, white, black, black] and a white ball, he can insert the ball between two white balls. Thus three white balls are destroyed, and then four black balls become contiguous, so all four balls are destroyed. The row will not contain any ball in the end, so Iahub can destroy all 6 balls.

Iahub wants to destroy as many balls as possible. You are given the description of the row of balls, and the color of Iahub's ball. Help Iahub train for the IOI by telling him the maximum number of balls from the row he can destroy.

Input

The first line of input contains three integers: n (1 ≤ n ≤ 100), k (1 ≤ k ≤ 100) and x (1 ≤ x ≤ k). The next line contains n space-separated integers c1, c2, ..., cn (1 ≤ ci ≤ k). Number ci means that the i-th ball in the row has color ci.

It is guaranteed that the initial row of balls will never contain three or more contiguous balls of the same color.

Output

Print a single integer — the maximum number of balls Iahub can destroy.

Examples

Input

6 2 2
1 1 2 2 1 1

Output

6

Input

1 1 1
1

Output

0

```python

def destroy_balls(_a, _b, _x):
    if len(_a) == 0 or len(_b) == 0:
        return 0
    lenb = len(_b)
    a_cur_index = len(_a) - 1
    b_cur_index = 0
    if _a[a_cur_index] == _b[b_cur_index]:
        to_be_destroyed = 2
        a_cur_index -= 1
        b_cur_index += 1
        while a_cur_index >= 0:
            if _a[a_cur_index] == _x:
                to_be_destroyed += 1
                a_cur_index -= 1
            else:
                break
        while b_cur_index < lenb:
            if _b[b_cur_index] == _x:
                to_be_destroyed += 1
                b_cur_index += 1
            else:
                break
        if to_be_destroyed > 2:
            return to_be_destroyed + destroy_balls(_a[0:a_cur_index + 1], _b[b_cur_index:], _a[a_cur_index])
        else:
            return 0

    return 0

n, k, x = map(int, input().split())
c = list(map(int, input().split()))

cur_max = 0
for i in range(n - 1):
    if c[i] == x and c[i] == c[i + 1]:
        tmp_a = c[0:i+1]
        tmp_b = c[i+1:n]
        tmp_a.append(x)
        i += 1
        tmp_max = destroy_balls(tmp_a, tmp_b, x)
        if tmp_max > cur_max:
            cur_max = tmp_max
if cur_max >= 2:
    cur_max -= 1
else:
    cur_max = 0
print(cur_max)

```


499_C. Crazy Town

Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect.

Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step).

Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road.

Input

The first line contains two space-separated integers x1, y1 ( - 106 ≤ x1, y1 ≤ 106) — the coordinates of your home.

The second line contains two integers separated by a space x2, y2 ( - 106 ≤ x2, y2 ≤ 106) — the coordinates of the university you are studying at.

The third line contains an integer n (1 ≤ n ≤ 300) — the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≤ ai, bi, ci ≤ 106; |ai| + |bi| > 0) — the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines).

Output

Output the answer to the problem.

Examples

Input

1 1
-1 -1
2
0 1 0
1 0 0

Output

2

Input

1 1
-1 -1
3
1 0 0
0 1 0
1 1 -3

Output

2

Note

Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors):

<image> <image>

```python
x1, y1 = map(int, input().split())
x2, y2 = map(int, input().split())
n = int(input())
arr = []
for _ in range(n):
	a, b, c = map(int, input().split())
	arr.append((a,b,c))
res = 0
for i in arr:
	a, b, c = i
	if(b != 0):
		y00 = -c/b
		y01 = -(a+c)/b
		s1 = x1*(y01-y00)-(y1-y00)
		s2 = x2*(y01-y00)-(y2-y00)
		if(s1<0<s2 or s1>0>s2):
			res += 1
	else:
		x = -c/a
		if(x1<x<x2 or x1>x>x2):
			res += 1
print(res)
```


522_D. Closest Equals

You are given sequence a1, a2, ..., an and m queries lj, rj (1 ≤ lj ≤ rj ≤ n). For each query you need to print the minimum distance between such pair of elements ax and ay (x ≠ y), that:

  * both indexes of the elements lie within range [lj, rj], that is, lj ≤ x, y ≤ rj;
  * the values of the elements are equal, that is ax = ay.

The text above understands distance as |x - y|.

Input

The first line of the input contains a pair of integers n, m (1 ≤ n, m ≤ 5·105) — the length of the sequence and the number of queries, correspondingly.

The second line contains the sequence of integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109).

Next m lines contain the queries, one per line. Each query is given by a pair of numbers lj, rj (1 ≤ lj ≤ rj ≤ n) — the indexes of the query range limits.

Output

Print m integers — the answers to each query. If there is no valid match for some query, please print -1 as an answer to this query.

Examples

Input

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

Output

1
-1
2

Input

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

Output

2
2
3
-1
2

```python
import sys

class Fenwick(object):
  def __init__(self, n):
    self.n = n
    self.a = [10**9 for i in range(n)]
    self.w= 10**9

  def zag(self, i, zn):
    self.w= min(self.w, zn)
    while i < self.n:
      self.a[i] = min(self.a[i], zn)
      i = (i | (i + 1))

  def pol(self, r):
    ans= 10**9
    while r >= 0:
      if ans> self.a[r]:
        ans= self.a[r]
      if ans== self.w:
        break
      r = (r & (r + 1)) - 1
    return ans

n, m = [int(x) for x in sys.stdin.readline().split()]
a = [int(x) for x in sys.stdin.readline().split()]

nd= [-1 for i in range(0, len(a))]
vi= {}
for i in range(0, len(a)):
  if a[i] in vi:
    nd[i] = vi[a[i]]
  vi[a[i]] = i

inp= sys.stdin.readlines()
och= [[] for i in range(n)]
for i in range(m):
  l, r = inp[i].split()
  och[int(r) - 1].append((int(l) - 1, i))

der = Fenwick(2 ** 19)
ans= [None for i in range(0, m)]
le= -1
for r in range(n):
  if nd[r] != -1:
    der.zag(500000 - nd[r] + 1, r - nd[r])
    le = max(le, nd[r])
  for (l, ind) in och[r]:
    if l > le:
      ans[ind] = -1
      continue
    zn= der.pol(500000 - l + 1)
    if zn== 10**9:
      zn= -1
    ans[ind] = zn

print('\n'.join(str(zn) for zn in ans))
```