1015_E2. Stars Drawing (Hard Edition)

A star is a figure of the following type: an asterisk character '*' in the center of the figure and four rays (to the left, right, top, bottom) of the same positive length. The size of a star is the length of its rays. The size of a star must be a positive number (i.e. rays of length 0 are not allowed).

Let's consider empty cells are denoted by '.', then the following figures are stars:

<image> The leftmost figure is a star of size 1, the middle figure is a star of size 2 and the rightmost figure is a star of size 3.

You are given a rectangular grid of size n × m consisting only of asterisks '*' and periods (dots) '.'. Rows are numbered from 1 to n, columns are numbered from 1 to m. Your task is to draw this grid using any number of stars or find out that it is impossible. Stars can intersect, overlap or even coincide with each other. The number of stars in the output can't exceed n ⋅ m. Each star should be completely inside the grid. You can use stars of same and arbitrary sizes.

In this problem, you do not need to minimize the number of stars. Just find any way to draw the given grid with at most n ⋅ m stars.

Input

The first line of the input contains two integers n and m (3 ≤ n, m ≤ 1000) — the sizes of the given grid.

The next n lines contains m characters each, the i-th line describes the i-th row of the grid. It is guaranteed that grid consists of characters '*' and '.' only.

Output

If it is impossible to draw the given grid using stars only, print "-1".

Otherwise in the first line print one integer k (0 ≤ k ≤ n ⋅ m) — the number of stars needed to draw the given grid. The next k lines should contain three integers each — x_j, y_j and s_j, where x_j is the row index of the central star character, y_j is the column index of the central star character and s_j is the size of the star. Each star should be completely inside the grid.

Examples

Input

6 8
....*...
...**...
..*****.
...**...
....*...
........

Output

3
3 4 1
3 5 2
3 5 1

Input

5 5
.*...
****.
.****
..**.
.....

Output

3
2 2 1
3 3 1
3 4 1

Input

5 5
.*...
***..
.*...
.*...
.....

Output

-1

Input

3 3
*.*
.*.
*.*

Output

-1

Note

In the first example the output

    2
    3 4 1
    3 5 2

is also correct.

```python
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
mod = 10 ** 9 + 7
mod1 = 998244353
#sys.setrecursionlimit(300000)
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
#sys.setrecursionlimit(300000)
class FastIO(IOBase):
    newlines = 0

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

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

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

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

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

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

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

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

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

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

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

    def __len__(self):
        return self._len

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

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

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

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

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

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

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

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

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

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

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

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

    return z

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

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

    count = 0

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

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

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

    return count

# --------------------------------------------------binary----------------------------------------
def countdig(n):
    c = 0
    while (n > 0):
        n //= 10
        c += 1
    return c
def binary(x, length):
    y = bin(x)[2:]
    return y if len(y) >= length else "0" * (length - len(y)) + y

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

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

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

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

    # Return the count of elements
    # greater than k
    return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
n,m=map(int,input().split())
l=[]
tot=[]
done=[[0 for i in range(m)]for j in range(n)]
for i in range(n):
    l.append(input())
colsum=[[0 for i in range(m)]for j in range(n)]
rowsum=[[0 for i in range(m)]for j in range(n)]
col=[[0 for i in range(m)]for j in range(n)]
row=[[0 for i in range(m)]for j in range(n)]
for i in range(n):
    for j in range(m):
        if l[i][j]=='*':
            rowsum[i][j]=1
            colsum[i][j]=1
            row[i][j]=1
            col[i][j]=1
for i in range(n):
    for j in range(1,m):
        if l[i][j]=='.':
            continue
        rowsum[i][j]+=rowsum[i][j-1]
for i in range(n):
    for j in range(m-2,-1,-1):
        if l[i][j]=='.':
            continue
        row[i][j]+=row[i][j+1]
for i in range(m):
    for j in range(n-2,-1,-1):
        if l[j][i]=='.':
            continue
        col[j][i]+=col[j+1][i]
for i in range(m):
    for j in range(1,n):
        if l[j][i]=='.':
            continue
        colsum[j][i]+=colsum[j-1][i]
def check(x,y):
    i=x
    j=y
    ans=min(row[i][j],rowsum[i][j],colsum[i][j],col[i][j])-1
    if ans==0:
        return []
    return [ans]
h=[[0 for i in range(m+1)]for j in range(n)]
v=[[0 for i in range(m)]for j in range(n+1)]
for i in range(n):
    for j in range(m):
        if l[i][j]=='*':
            ans=check(i,j)
            for j1 in ans:
                tot.append([i+1,j+1,j1])
                h[i][j-j1]+=1
                h[i][j+j1+1]-=1
                v[i-j1][j]+=1
                v[i+j1+1][j]-=1
for i in range(n):
    for j in range(1,m):
        h[i][j]+=h[i][j-1]
for i in range(m):
    for j in range(1,n):
        v[j][i]+=v[j-1][i]
#print(h)
#print(v)
for i in range(n):
    for j in range(m):
        if l[i][j]=='*' and h[i][j]==0 and v[i][j]==0:
            print(-1)
            sys.exit(0)
print(len(tot))
for i in tot:
    print(*i)

```


1103_A. Grid game

You are given a 4x4 grid. You play a game — there is a sequence of tiles, each of them is either 2x1 or 1x2. Your task is to consequently place all tiles from the given sequence in the grid. When tile is placed, each cell which is located in fully occupied row or column is deleted (cells are deleted at the same time independently). You can place tile in the grid at any position, the only condition is that tiles (and tile parts) should not overlap. Your goal is to proceed all given figures and avoid crossing at any time.

Input

The only line contains a string s consisting of zeroes and ones (1 ≤ |s| ≤ 1000). Zero describes vertical tile, one describes horizontal tile.

Output

Output |s| lines — for each tile you should output two positive integers r,c, not exceeding 4, representing numbers of smallest row and column intersecting with it.

If there exist multiple solutions, print any of them.

Example

Input

010

Output

1 1
1 2
1 4

Note

Following image illustrates the example after placing all three tiles:

<image> Then the first row is deleted:  <image>


1131_A. Sea Battle

In order to make the "Sea Battle" game more interesting, Boris decided to add a new ship type to it. The ship consists of two rectangles. The first rectangle has a width of w_1 and a height of h_1, while the second rectangle has a width of w_2 and a height of h_2, where w_1 ≥ w_2. In this game, exactly one ship is used, made up of two rectangles. There are no other ships on the field.

The rectangles are placed on field in the following way:

  * the second rectangle is on top the first rectangle;
  * they are aligned to the left, i.e. their left sides are on the same line;
  * the rectangles are adjacent to each other without a gap.

See the pictures in the notes: the first rectangle is colored red, the second rectangle is colored blue.

Formally, let's introduce a coordinate system. Then, the leftmost bottom cell of the first rectangle has coordinates (1, 1), the rightmost top cell of the first rectangle has coordinates (w_1, h_1), the leftmost bottom cell of the second rectangle has coordinates (1, h_1 + 1) and the rightmost top cell of the second rectangle has coordinates (w_2, h_1 + h_2).

After the ship is completely destroyed, all cells neighboring by side or a corner with the ship are marked. Of course, only cells, which don't belong to the ship are marked. On the pictures in the notes such cells are colored green.

Find out how many cells should be marked after the ship is destroyed. The field of the game is infinite in any direction.

Input

Four lines contain integers w_1, h_1, w_2 and h_2 (1 ≤ w_1, h_1, w_2, h_2 ≤ 10^8, w_1 ≥ w_2) — the width of the first rectangle, the height of the first rectangle, the width of the second rectangle and the height of the second rectangle. You can't rotate the rectangles.

Output

Print exactly one integer — the number of cells, which should be marked after the ship is destroyed.

Examples

Input

2 1 2 1

Output

12

Input

2 2 1 2

Output

16

Note

In the first example the field looks as follows (the first rectangle is red, the second rectangle is blue, green shows the marked squares):

<image>

In the second example the field looks as:

<image>


1151_C. Problem for Nazar

Nazar, a student of the scientific lyceum of the Kingdom of Kremland, is known for his outstanding mathematical abilities. Today a math teacher gave him a very difficult task.

Consider two infinite sets of numbers. The first set consists of odd positive numbers (1, 3, 5, 7, …), and the second set consists of even positive numbers (2, 4, 6, 8, …). At the first stage, the teacher writes the first number on the endless blackboard from the first set, in the second stage — the first two numbers from the second set, on the third stage — the next four numbers from the first set, on the fourth — the next eight numbers from the second set and so on. In other words, at each stage, starting from the second, he writes out two times more numbers than at the previous one, and also changes the set from which these numbers are written out to another.

The ten first written numbers: 1, 2, 4, 3, 5, 7, 9, 6, 8, 10. Let's number the numbers written, starting with one.

The task is to find the sum of numbers with numbers from l to r for given integers l and r. The answer may be big, so you need to find the remainder of the division by 1000000007 (10^9+7).

Nazar thought about this problem for a long time, but didn't come up with a solution. Help him solve this problem.

Input

The first line contains two integers l and r (1 ≤ l ≤ r ≤ 10^{18}) — the range in which you need to find the sum.

Output

Print a single integer — the answer modulo 1000000007 (10^9+7).

Examples

Input

1 3

Output

7

Input

5 14

Output

105

Input

88005553535 99999999999

Output

761141116

Note

In the first example, the answer is the sum of the first three numbers written out (1 + 2 + 4 = 7).

In the second example, the numbers with numbers from 5 to 14: 5, 7, 9, 6, 8, 10, 12, 14, 16, 18. Their sum is 105.

```python
import math

def Solve(x):
    if x == 0:
        return 0
    stage = int(math.floor(math.log(x,2)))
    odd = math.ceil(stage/2)
    even = math.floor(stage/2)
    even_terms = 2*(pow(4,even)-1)//3
    odd_terms = (pow(4,odd)-1)//3
    total = even_terms+odd_terms

    if (stage+1)%2 == 0:
        even_terms += x-total
    else:
        odd_terms += x-total

    sum_even_terms = even_terms*(1+even_terms)
    sum_odd_terms = odd_terms*(odd_terms)

    return (sum_even_terms%1000000007+sum_odd_terms%1000000007)%1000000007

def main():
    l,r = map(int,input().split())
    print((Solve(r)-Solve(l-1))%1000000007)

main()

```


1173_B. Nauuo and Chess

Nauuo is a girl who loves playing chess.

One day she invented a game by herself which needs n chess pieces to play on a m× m chessboard. The rows and columns are numbered from 1 to m. We denote a cell on the intersection of the r-th row and c-th column as (r,c).

The game's goal is to place n chess pieces numbered from 1 to n on the chessboard, the i-th piece lies on (r_i,\,c_i), while the following rule is satisfied: for all pairs of pieces i and j, |r_i-r_j|+|c_i-c_j|≥|i-j|. Here |x| means the absolute value of x.

However, Nauuo discovered that sometimes she couldn't find a solution because the chessboard was too small.

She wants to find the smallest chessboard on which she can put n pieces according to the rules.

She also wonders how to place the pieces on such a chessboard. Can you help her?

Input

The only line contains a single integer n (1≤ n≤ 1000) — the number of chess pieces for the game.

Output

The first line contains a single integer — the minimum value of m, where m is the length of sides of the suitable chessboard.

The i-th of the next n lines contains two integers r_i and c_i (1≤ r_i,c_i≤ m) — the coordinates of the i-th chess piece.

If there are multiple answers, print any.

Examples

Input

2

Output

2
1 1
1 2

Input

4

Output

3
1 1
1 3
3 1
3 3

Note

In the first example, you can't place the two pieces on a 1×1 chessboard without breaking the rule. But you can place two pieces on a 2×2 chessboard like this:

<image>

In the second example, you can't place four pieces on a 2×2 chessboard without breaking the rule. For example, if you place the pieces like this:

<image>

then |r_1-r_3|+|c_1-c_3|=|1-2|+|1-1|=1, |1-3|=2, 1<2; and |r_1-r_4|+|c_1-c_4|=|1-2|+|1-2|=2, |1-4|=3, 2<3. It doesn't satisfy the rule.

However, on a 3×3 chessboard, you can place four pieces like this:

<image>

```python
import sys
import math
from functools import reduce

n = int(input())

m = 1
while True:
    if m * 2 <= n:
        m += 1
    else:
        break

print(m)

for x in range(m):
    print(1, x+1)

t = n - m

for _ in range(n - m):
    print(m, m - t + 1)
    t -= 1

```


122_B. Lucky Substring

Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.

One day Petya was delivered a string s, containing only digits. He needs to find a string that

  * represents a lucky number without leading zeroes,
  * is not empty,
  * is contained in s as a substring the maximum number of times.

Among all the strings for which the three conditions given above are fulfilled, Petya only needs the lexicographically minimum one. Find this string for Petya.

Input

The single line contains a non-empty string s whose length can range from 1 to 50, inclusive. The string only contains digits. The string can contain leading zeroes.

Output

In the only line print the answer to Petya's problem. If the sought string does not exist, print "-1" (without quotes).

Examples

Input

047

Output

4

Input

16

Output

-1

Input

472747

Output

7

Note

The lexicographical comparison of strings is performed by the < operator in the modern programming languages. String x is lexicographically less than string y either if x is a prefix of y, or exists such i (1 ≤ i ≤ min(|x|, |y|)), that xi < yi and for any j (1 ≤ j < i) xj = yj. Here |a| denotes the length of string a.

In the first sample three conditions are fulfilled for strings "4", "7" and "47". The lexicographically minimum one is "4".

In the second sample s has no substrings which are lucky numbers.

In the third sample the three conditions are only fulfilled for string "7".

```python
s=input()
s=s.strip('0')
four=s.count('4')
seven=s.count('7')
if '4' not in s and '7' not in s:
    print(-1)
else:
    if four>=seven:
        print('4')
    else:
        print('7')

```


1251_A. Broken Keyboard

Recently Polycarp noticed that some of the buttons of his keyboard are malfunctioning. For simplicity, we assume that Polycarp's keyboard contains 26 buttons (one for each letter of the Latin alphabet). Each button is either working fine or malfunctioning.

To check which buttons need replacement, Polycarp pressed some buttons in sequence, and a string s appeared on the screen. When Polycarp presses a button with character c, one of the following events happened:

  * if the button was working correctly, a character c appeared at the end of the string Polycarp was typing;
  * if the button was malfunctioning, two characters c appeared at the end of the string.

For example, suppose the buttons corresponding to characters a and c are working correctly, and the button corresponding to b is malfunctioning. If Polycarp presses the buttons in the order a, b, a, c, a, b, a, then the string he is typing changes as follows: a → abb → abba → abbac → abbaca → abbacabb → abbacabba.

You are given a string s which appeared on the screen after Polycarp pressed some buttons. Help Polycarp to determine which buttons are working correctly for sure (that is, this string could not appear on the screen if any of these buttons was malfunctioning).

You may assume that the buttons don't start malfunctioning when Polycarp types the string: each button either works correctly throughout the whole process, or malfunctions throughout the whole process.

Input

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

Then the test cases follow. Each test case is represented by one line containing a string s consisting of no less than 1 and no more than 500 lowercase Latin letters.

Output

For each test case, print one line containing a string res. The string res should contain all characters which correspond to buttons that work correctly in alphabetical order, without any separators or repetitions. If all buttons may malfunction, res should be empty.

Example

Input

4
a
zzaaz
ccff
cbddbb

Output

a
z

bc

```python
'''
	@judge CodeForces
	@id 1251A
	@name Broken Keyboard

	@tag Simulation
'''
from sys import stdin
from itertools import groupby

def solve(s):
	return ''.join(sorted(set(map(lambda p: str(p[0]), filter(lambda p: len(list(p[1])) & 1, groupby(s))))))

input()
for line in stdin:
	print(solve(line.strip()))
```


1313_E. Concatenation with intersection

Vasya had three strings a, b and s, which consist of lowercase English letters. The lengths of strings a and b are equal to n, the length of the string s is equal to m.

Vasya decided to choose a substring of the string a, then choose a substring of the string b and concatenate them. Formally, he chooses a segment [l_1, r_1] (1 ≤ l_1 ≤ r_1 ≤ n) and a segment [l_2, r_2] (1 ≤ l_2 ≤ r_2 ≤ n), and after concatenation he obtains a string a[l_1, r_1] + b[l_2, r_2] = a_{l_1} a_{l_1 + 1} … a_{r_1} b_{l_2} b_{l_2 + 1} … b_{r_2}.

Now, Vasya is interested in counting number of ways to choose those segments adhering to the following conditions:

  * segments [l_1, r_1] and [l_2, r_2] have non-empty intersection, i.e. there exists at least one integer x, such that l_1 ≤ x ≤ r_1 and l_2 ≤ x ≤ r_2;
  * the string a[l_1, r_1] + b[l_2, r_2] is equal to the string s.

Input

The first line contains integers n and m (1 ≤ n ≤ 500 000, 2 ≤ m ≤ 2 ⋅ n) — the length of strings a and b and the length of the string s.

The next three lines contain strings a, b and s, respectively. The length of the strings a and b is n, while the length of the string s is m.

All strings consist of lowercase English letters.

Output

Print one integer — the number of ways to choose a pair of segments, which satisfy Vasya's conditions.

Examples

Input

6 5
aabbaa
baaaab
aaaaa

Output

4

Input

5 4
azaza
zazaz
azaz

Output

11

Input

9 12
abcabcabc
xyzxyzxyz
abcabcayzxyz

Output

2

Note

Let's list all the pairs of segments that Vasya could choose in the first example:

  1. [2, 2] and [2, 5];
  2. [1, 2] and [2, 4];
  3. [5, 5] and [2, 5];
  4. [5, 6] and [3, 5];

```python
import sys, logging
logging.basicConfig(level=logging.INFO)
logging.disable(logging.INFO)

def build(S, n):
    Z = [0 for i in range(3 * n + 3)]
    #logging.info(S)
    n = len(S)
    L = 0
    R = 0
    Z[0] = n
    for i in range(1, n):
        if(i > R):
            L = R = i
            while(R < n and S[R] == S[R - L]):
                R += 1
            Z[i] = R - L
            R -= 1
        else:
            k = i - L
            if(Z[k] < R - i + 1):
                Z[i] = Z[k]
            else:
                L = i
                while(R < n and S[R] == S[R - L]):
                    R += 1
                Z[i] = R - L
                R -= 1
    return Z

def update1(n, x, val):
    while(x <= n + 1):
        bit1[x] += val
        x += x & -x

def get1(n, x):
    ans = 0
    while(x > 0):
        ans += bit1[x]
        x -= x & -x
    return ans

def update2(n, x, val):
    while(x <= n + 1):
        bit2[x] += val
        x += x & -x

def get2(n, x):
    ans = 0
    while(x > 0):
        ans += bit2[x]
        x -= x & -x
    return ans

def process(n, m, fa, fb):
    r2 = int(1)
    ans = 0
    for l1 in range(1, n + 1):
        while(r2 <= min(n, l1 + m - 2)):
            update1(n, m - fb[r2] + 1, 1)
            update2(n, m - fb[r2] + 1, fb[r2] - m + 1)
            r2 += 1
        ans += get1(n, fa[l1] + 1) * fa[l1] + get2(n, fa[l1] + 1)
        update1(n, m - fb[l1] + 1, -1)
        update2(n, m - fb[l1] + 1, m - 1 - fb[l1])
    print(ans)

def main():
    n, m = map(int, sys.stdin.readline().split())
    a = sys.stdin.readline()
    b = sys.stdin.readline()
    s = sys.stdin.readline()
    a = a[:(len(a) - 1)]
    b = b[:(len(b) - 1)]
    s = s[:(len(s) - 1)]
    fa = build(s + a, n)
    kb = build(s[::-1] + b[::-1], n)
    fb = [0 for k in range(n + 2)]
    for i in range(m, m + n):
        fa[i - m + 1] = fa[i]
        if(fa[i - m + 1] >= m):
            fa[i - m + 1] = m - 1
        fb[m + n - i] = kb[i]
        if(fb[m + n - i] >= m):
            fb[m + n - i] = m - 1
    logging.info(fa[1:(n + 1)])
    logging.info(fb[1:(n + 1)])
    process(n, m, fa, fb)

bit1 = [0 for i in range(500004)]
bit2 = [0 for i in range(500004)]

if __name__ == "__main__":
    try:
        sys.stdin = open('input.txt', 'r')
        sys.stdout = open('output.txt', 'w')
    except:
        pass
    main()
```


1336_C. Kaavi and Magic Spell

Kaavi, the mysterious fortune teller, deeply believes that one's fate is inevitable and unavoidable. Of course, she makes her living by predicting others' future. While doing divination, Kaavi believes that magic spells can provide great power for her to see the future.

<image>

Kaavi has a string T of length m and all the strings with the prefix T are magic spells. Kaavi also has a string S of length n and an empty string A.

During the divination, Kaavi needs to perform a sequence of operations. There are two different operations:

  * Delete the first character of S and add it at the front of A.
  * Delete the first character of S and add it at the back of A.

Kaavi can perform no more than n operations. To finish the divination, she wants to know the number of different operation sequences to make A a magic spell (i.e. with the prefix T). As her assistant, can you help her? The answer might be huge, so Kaavi only needs to know the answer modulo 998 244 353.

Two operation sequences are considered different if they are different in length or there exists an i that their i-th operation is different.

A substring is a contiguous sequence of characters within a string. A prefix of a string S is a substring of S that occurs at the beginning of S.

Input

The first line contains a string S of length n (1 ≤ n ≤ 3000).

The second line contains a string T of length m (1 ≤ m ≤ n).

Both strings contain only lowercase Latin letters.

Output

The output contains only one integer — the answer modulo 998 244 353.

Examples

Input

abab
ba

Output

12

Input

defineintlonglong
signedmain

Output

0

Input

rotator
rotator

Output

4

Input

cacdcdbbbb
bdcaccdbbb

Output

24

Note

The first test:

<image>

The red ones are the magic spells. In the first operation, Kaavi can either add the first character "a" at the front or the back of A, although the results are the same, they are considered as different operations. So the answer is 6×2=12.


1358_F. Tasty Cookie

Oh, no!

The coronavirus has caught you, and now you're sitting in a dark cellar, with tied legs (but not hands). You have a delicious cookie, a laptop in front of you, and your ideal development environment is open. The coronavirus convinces you to solve the following problem.

You are given two arrays A and B of size n. You can do operations of two types with array A:

  * Reverse array A. That is the array [A_1,\ A_2,\ …,\ A_n] transformes into [A_n,\ A_{n-1},\ …,\ A_1].
  * Replace A with an array of its prefix sums. That is, the array [A_1,\ A_2,\ …,\ A_n] goes to [A_1,\ (A_1+A_2),\ …,\ (A_1+A_2+…+A_n)].

You need to understand if you can get an array B from the array A. If it is possible, you will have to restore the order of these operations by minimizing the number of operations of the second type. Fortunately, the coronavirus is good today, so he has allowed you not to restore actions if the minimum number of second type operations is more than 2⋅ 10^5. But coronavirus resents you, so if you restore the answer, the total number of operations should not exceed 5⋅ 10^5.

Solve this problem and get the cookie, or the coronavirus will extend the quarantine for five years and make the whole economy collapse!

Input

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

The second line contains n integers A_1, A_2, …, A_n (1 ≤ A_i ≤ 10 ^ {12}).

The third line contains n integers B_1, B_2, …, B_n (1 ≤ B_i ≤ 10 ^ {12}).

Output

If you cannot get B from the A array, print "IMPOSSIBLE" (without quotes) on a single line.

If the minimum number of operations of the second type exceeds 2⋅ 10^5, print "BIG" (without quotes). In the second line print the number of operations of the second type, that needs to be applied to get array B from A.

Otherwise, in the first line print "SMALL" (without quotes). In the second line print the total number of operations of the first and second types m ≤ 5⋅ 10^5 (it is guaranteed that in this case there is such a sequence of actions). In the third line print a line of length m, consisting of characters 'R"and 'P' (without quotes).

The i-th character should be 'R', if the i-th action is of the first type, and should be 'P', otherwise.

If there are several such sequences, you can print any of them.

You can print each character in the uppercase or in the lowercase.

Examples

Input

2
5 7
5 7

Output

SMALL
0

Input

2
1 1
300000 1

Output

BIG
299999

Input

2
10 1
13 14

Output

SMALL
6
RPPPRP

Input

3
1 2 1
2 1 2

Output

IMPOSSIBLE

Note

In the first example, the arrays A and B already equal, so the number of required operations =0.

In the second example, we need to replace A with the prefix sums 299999 times and then reverse the array. Since 299999>2⋅ 10^5, there is no need to restore the answer.

In the fourth example, you cannot get B from the A.

```python
import sys

int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

def main():
    n=II()
    aa=LI()
    raa=aa[::-1]
    bb=LI()
    if n==1:
        if aa==bb:
            print("SMALL")
            print(0)
        else:
            print("IMPOSSIBLE")
        exit()
    if n==2:
        mna=min(aa)
        cntp=0
        x,y=bb
        if x>y:x,y=y,x
        while mna<x:
            c=y//x
            cntp+=c
            y-=c*x
            if x>y:x,y=y,x
        d=y-max(aa)
        if mna!=x or d%x:
            print("IMPOSSIBLE")
            exit()
        cntp+=d//x
        if cntp>200000:
            print("BIG")
            print(cntp)
            exit()
    ans=""
    cntp=0
    while 1:
        if aa==bb:
            if cntp > 200000:
                print("BIG")
                print(cntp)
            else:
                print("SMALL")
                print(len(ans))
                if ans:print(ans[::-1])
            exit()
        if raa==bb:
            if cntp > 200000:
                print("BIG")
                print(cntp)
            else:
                ans+="R"
                print("SMALL")
                print(len(ans))
                if ans:print(ans[::-1])
            exit()
        if bb[0]<=bb[-1]:
            if cntp<=200000:ans+="P"
            cntp+=1
            for i in range(n-2,-1,-1):
                bb[i+1]-=bb[i]
                if bb[i+1]<=0:
                    print("IMPOSSIBLE")
                    exit()
        else:
            if cntp<=200000:ans+="R"
            bb.reverse()

main()
```


1379_B. Dubious Cyrpto

Pasha loves to send strictly positive integers to his friends. Pasha cares about security, therefore when he wants to send an integer n, he encrypts it in the following way: he picks three integers a, b and c such that l ≤ a,b,c ≤ r, and then he computes the encrypted value m = n ⋅ a + b - c.

Unfortunately, an adversary intercepted the values l, r and m. Is it possible to recover the original values of a, b and c from this information? More formally, you are asked to find any values of a, b and c such that

  * a, b and c are integers,
  * l ≤ a, b, c ≤ r,
  * there exists a strictly positive integer n, such that n ⋅ a + b - c = m.

Input

The first line contains the only integer t (1 ≤ t ≤ 20) — the number of test cases. The following t lines describe one test case each.

Each test case consists of three integers l, r and m (1 ≤ l ≤ r ≤ 500 000, 1 ≤ m ≤ 10^{10}). The numbers are such that the answer to the problem exists.

Output

For each test case output three integers a, b and c such that, l ≤ a, b, c ≤ r and there exists a strictly positive integer n such that n ⋅ a + b - c = m. It is guaranteed that there is at least one possible solution, and you can output any possible combination if there are multiple solutions.

Example

Input

2
4 6 13
2 3 1

Output

4 6 5
2 2 3

Note

In the first example n = 3 is possible, then n ⋅ 4 + 6 - 5 = 13 = m. Other possible solutions include: a = 4, b = 5, c = 4 (when n = 3); a = 5, b = 4, c = 6 (when n = 3); a = 6, b = 6, c = 5 (when n = 2); a = 6, b = 5, c = 4 (when n = 2).

In the second example the only possible case is n = 1: in this case n ⋅ 2 + 2 - 3 = 1 = m. Note that, n = 0 is not possible, since in that case n is not a strictly positive integer.

```python
#!/usr/local/bin/python3
"""
Given l, r, m, you know that
m = n*a + b - c
for some l <= a,b,c <= r, and n is an integer.
Can you find a,b,c? (any value is fine)

Examples
l,r,m = 10,20,90
    Choose 10 <= a,b,c <= 20 s.t.
    90 = n*a + b - c
    a=10,b=10,c=10,n=9

l,r,m = 8,9,95
    Choose 8 <= a,b,c <= 9
    try a=8,b=8,c=8:
        9*9+8-8

Observations:
We just need to find one value (any value)

Is it always possible? The problem statement doesn't say anything other than
    "it's guaranteed that there is at least one possible solution"
    Maybe that means that it's always possible to find one?
        No, l,r,m = 8,9,95 doesn't work.
        Oh, "the numbers are such that the answer to the problem exists"
    - So the answer is NO

- What are the conditions for which the answer to this problem exists?
    - If there exists a number d (l<=d<=r) s.t. m%d == 0, then we can
    pick a=d, b=l, c=l, so it's always possible.
        - The following line of logic doesn't quite make sense to me.
            - Let's say an n exists.
                - When can we reach numbers n' s.t. m % n' == 1?
                    - If r - l >= 1, then we can pick a=m//n, b=l+1, c=l
                - Generally, we can reach numbers n' s.t. m % n' == k by picking
                a=m//n, b=l+k, c=l.
                    - This requries r-l>=k.

    - What if there's a number d (l<=n<=r) s.t. for n=the smallest value for which d*n>=m, (d*n)%m == 1?
        - Then, we can pick a=d,b=l,c=l+1
        - a*n+b-c = a*d+l-l-1 = a*d-1 = n + 1 - 1 = n
        - This requires r-l >= 1

    - This works for picking a, and b>c
        - In general, if we have a number d (l<=d<=r) s.t. for n=the smallest value for which d*n>=m, (d*n)%m == k
            - Then, we pick a=d,b=l,c=l+k
            - Then, a*n+b-c = d*n+l-l-k = d*n-k = n + k - k = n.
            - This requires r-l >= k

            - Is this a sufficient condition for determining if a solution exists?
                - If it were, we have this solution:
                    - for each d in [l,r]:
                        - find an n s.t. (n*d)%m <= r-l:
                            If we found one, then break out of the outer for loop and set
                            d and n.
                    - if found:
                        pick a=d, b=l, c=l+(n*d)%m

                - Let's try to prove this is sufficient:
                    Suppose is some a,b,c in [l,r] s.t. for some integer N, m = N*a + b - c
                    Let's say there existed no d in [l,r] s.t. for n=the smallest value for which d*n>=m, (d*n)%m <= r-l.
                    N*a+b-c=m
                    Then, (N*a+b-c)%m = 0.
                    => (N*a)%m = abs(c-b) <= r-l (l <= c,b <= r)
                    This is a contradiction (a is in [l,r])
    - What if m == 1?
        m = n*a + b - c
    - Then, we just pick (l, l, abs(2*l-m))

Solution:
- for each d in [l,r]:
    - find n=the smallest value for which d*n>=m s.t. (n*d)%m <= r-l:
- if found:
    pick a=d, b=l, c=l+(n*d)%m

(a*b)%m = (a%m*b%m)%m
"""
import math

# d = 6
# m = 100
# for n in range(1,100):
#     k = (d*n)%m
#     print(n,d,k)
def check(l,r,m,a,b,c):
    # print(l <= min(a,b,c) <= r)
    # print(l <= max(a,b,c) <= r)
    # print((m-b+c)%a == 0)
    # print((m-b+c),a)
    assert (
        l <= min(a,b,c) <= r and
        l <= max(a,b,c) <= r and
        (m-b+c)%a == 0
    )

# from lesterlib import lesterutil
# @lesterutil.lesterlog()
def brute(l,r,m):
    # if m == 1:
    #     return (l, l, abs(2*l-m))

    # I missed this case during my first analysis.
    if m <= r-l:
        return (l, l, abs(2*l-m))

    for d in range(l,r+1):
        if m%d == 0:
            return (d,l,l)
        n=m//d

        # print(d, n, n*d, (-n*d)%m, r-l)
        # I missed this case during my first analysis.
        if (-n*d)%m <= r-l:
            # print('A')
            return (d,l+(-n*d)%m,l)

        # print(d, n, m-n*d)
        # if l <= m-n*d <= r:
        #     return (d, l+n*d, r)
        if n*d < m:
            n += 1
        # print(d, n, n*d, (n*d)%m, (-n*d)%m, r-l)
        if (n*d)%m <= r-l:
            # print('B')
            return (d,l,l+(n*d)%m)
    return None

def main():
    t = int(input())
    for _ in range(t):
        l,r,m = [int(x) for x in input().split()]
        #CHANGE
        result = brute(l,r,m)
        # check(l,r,m,*result)
        print(' '.join(str(x) for x in result))
main()
```


1399_F. Yet Another Segments Subset

You are given n segments on a coordinate axis OX. The i-th segment has borders [l_i; r_i]. All points x, for which l_i ≤ x ≤ r_i holds, belong to the i-th segment.

Your task is to choose the maximum by size (the number of segments) subset of the given set of segments such that each pair of segments in this subset either non-intersecting or one of them lies inside the other one.

Two segments [l_i; r_i] and [l_j; r_j] are non-intersecting if they have no common points. For example, segments [1; 2] and [3; 4], [1; 3] and [5; 5] are non-intersecting, while segments [1; 2] and [2; 3], [1; 2] and [2; 2] are intersecting.

The segment [l_i; r_i] lies inside the segment [l_j; r_j] if l_j ≤ l_i and r_i ≤ r_j. For example, segments [2; 2], [2, 3], [3; 4] and [2; 4] lie inside the segment [2; 4], while [2; 5] and [1; 4] are not.

You have to answer t independent test cases.

Input

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

The first line of the test case contains one integer n (1 ≤ n ≤ 3000) — the number of segments. The next n lines describe segments. The i-th segment is given as two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ 2 ⋅ 10^5), where l_i is the left border of the i-th segment and r_i is the right border of the i-th segment.

Additional constraint on the input: there are no duplicates in the list of segments.

It is guaranteed that the sum of n does not exceed 3000 (∑ n ≤ 3000).

Output

For each test case, print the answer: the maximum possible size of the subset of the given set of segments such that each pair of segments in this subset either non-intersecting or one of them lies inside the other one.

Example

Input

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

Output

3
4
2
7

```python
def f(sl):
    sl.sort(key=lambda s:(s[1],-s[0]))
    tl  = sorted(list(set([s[0] for s in sl] + [s[1] for s in sl])))
    cd  = {tl[i]:i for i in range(len(tl))}
    csl = [[] for i in range(len(tl))]
    for s0,s1 in sl:
        csl[cd[s1]].append(cd[s0])
    # start dp!
    n   = len(tl)
    dp  = [[len(csl[0])]] #dp[0][0]=1 or 0
    for r in range(1,len(tl)):
        dp.append([i for i in dp[-1]]+[0])
        for l in csl[r]:  #use this to update all before!
            dp[r][l] += 1
            for x in range(l-1,-1,-1):    #use this
                dp[r][x] = max(dp[r][x],dp[r][l]+dp[l-1][x])    #x<l
    return dp[-1][0]

T = int(input())
for i in range(T):
    n  =  int(input())
    ll = [list(map(int,input().split())) for _ in range(n)]
    print(f(ll))

```


1442_C. Graph Transpositions

You are given a directed graph of n vertices and m edges. Vertices are numbered from 1 to n. There is a token in vertex 1.

The following actions are allowed:

  * Token movement. To move the token from vertex u to vertex v if there is an edge u → v in the graph. This action takes 1 second.
  * Graph transposition. To transpose all the edges in the graph: replace each edge u → v by an edge v → u. This action takes increasingly more time: k-th transposition takes 2^{k-1} seconds, i.e. the first transposition takes 1 second, the second one takes 2 seconds, the third one takes 4 seconds, and so on.

The goal is to move the token from vertex 1 to vertex n in the shortest possible time. Print this time modulo 998 244 353.

Input

The first line of input contains two integers n, m (1 ≤ n, m ≤ 200 000).

The next m lines contain two integers each: u, v (1 ≤ u, v ≤ n; u ≠ v), which represent the edges of the graph. It is guaranteed that all ordered pairs (u, v) are distinct.

It is guaranteed that it is possible to move the token from vertex 1 to vertex n using the actions above.

Output

Print one integer: the minimum required time modulo 998 244 353.

Examples

Input

4 4
1 2
2 3
3 4
4 1

Output

2

Input

4 3
2 1
2 3
4 3

Output

10

Note

The first example can be solved by transposing the graph and moving the token to vertex 4, taking 2 seconds.

The best way to solve the second example is the following: transpose the graph, move the token to vertex 2, transpose the graph again, move the token to vertex 3, transpose the graph once more and move the token to vertex 4.

```python
# region fastio  # from https://codeforces.com/contest/1333/submission/75948789
import sys, io, os

BUFSIZE = 8192

class FastIO(io.IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = io.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(io.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")

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()

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

from heapq import heappush, heappop
mod = 998244353
N, M = map(int, input().split())
E1 = [[] for _ in range(N)]
E2 = [[] for _ in range(N)]
for _ in range(M):
    u, v = map(int, input().split())
    u -= 1
    v -= 1
    E1[u].append(v)
    E2[v].append(u)

# コスト、転倒回数(5bit)、ノード(18bit)

mask1 = (1<<23) - 1
mask2 = (1<<18) - 1

# ダイクストラ法
inf = 1<<62
dist = [inf] * (1<<23)
start = 0
dist[start] = 0
q = [start]
while q:
    v = heappop(q)
    dist_v = v >> 23
    v &= mask1
    n_trans = v >> 18
    v_node = v & mask2
    if v_node == N-1:
        print(dist_v % mod)
        exit()
    if n_trans > 20:
        break
    if dist[v] != dist_v:
        continue

    for u_node in (E1[v_node] if n_trans&1==0 else E2[v_node]):
        u = n_trans<<18 | u_node
        dist_u = dist_v + 1
        if dist_u < dist[u]:
            dist[u] = dist_u
            heappush(q, dist_u<<23 | u)
    u = n_trans+1<<18 | v_node
    dist_u = dist_v + (1<<n_trans)
    if dist_u < dist[u]:
        dist[u] = dist_u
        heappush(q, dist_u<<23 | u)

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

# 転倒回数、移動回数(18bit)、ノード(19bit)

mask1 = (1<<37) - 1
mask2 = (1<<19) - 1
mask3 = (1<<18)-1
REV = 1<<18

dist = [inf] * (1<<19)
start = 0
dist[start] = 0
q = [start]
while q:
    v = heappop(q)
    dist_v = v >> 19
    n_trans = dist_v >> 18
    v &= mask2
    v_node = v & mask3
    if v_node == N-1:
        ans = pow(2, n_trans, mod) - 1 + (dist_v&mask3)
        print(ans)
        exit()
    rev = v & REV
    if dist[v] != dist_v:
        continue
    for u_node in (E1[v_node] if n_trans&1==0 else E2[v_node]):
        u = rev | u_node
        dist_u = dist_v + 1
        if dist_u < dist[u]:
            dist[u] = dist_u
            heappush(q, dist_u<<19 | u)
    u = v ^ REV
    dist_u = dist_v + (1<<18)
    if dist_u < dist[u]:
        dist[u] = dist_u
        heappush(q, dist_u<<19 | u)

assert False

```


1468_E. Four Segments

Monocarp wants to draw four line segments on a sheet of paper. He wants the i-th segment to have its length equal to a_i (1 ≤ i ≤ 4). These segments can intersect with each other, and each segment should be either horizontal or vertical.

Monocarp wants to draw the segments in such a way that they enclose a rectangular space, and the area of that rectangular space should be maximum possible.

For example, if Monocarp wants to draw four segments with lengths 1, 2, 3 and 4, he can do it the following way:

<image> Here, Monocarp has drawn segments AB (with length 1), CD (with length 2), BC (with length 3) and EF (with length 4). He got a rectangle ABCF with area equal to 3 that is enclosed by the segments.

Calculate the maximum area of a rectangle Monocarp can enclose with four segments.

Input

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

Each test case consists of a single line containing four integers a_1, a_2, a_3, a_4 (1 ≤ a_i ≤ 10^4) — the lengths of the segments Monocarp wants to draw.

Output

For each test case, print one integer — the maximum area of a rectangle Monocarp can enclose with four segments (it can be shown that the answer is always an integer).

Example

Input

4
1 2 3 4
5 5 5 5
3 1 4 1
100 20 20 100

Output

3
25
3
2000

Note

The first test case of the example is described in the statement.

For the second test case, Monocarp can draw the segments AB, BC, CD and DA as follows:

<image> Here, Monocarp has drawn segments AB (with length 5), BC (with length 5), CD (with length 5) and DA (with length 5). He got a rectangle ABCD with area equal to 25 that is enclosed by the segments.

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

while (t):

	a = list(map(int,input().split()))
	a.sort()
	print(a[0]*a[2])
	t -= 1
```


1492_D. Genius's Gambit

You are given three integers a, b, k.

Find two binary integers x and y (x ≥ y) such that

  1. both x and y consist of a zeroes and b ones;
  2. x - y (also written in binary form) has exactly k ones.

You are not allowed to use leading zeros for x and y.

Input

The only line contains three integers a, b, and k (0 ≤ a; 1 ≤ b; 0 ≤ k ≤ a + b ≤ 2 ⋅ 10^5) — the number of zeroes, ones, and the number of ones in the result.

Output

If it's possible to find two suitable integers, print "Yes" followed by x and y in base-2.

Otherwise print "No".

If there are multiple possible answers, print any of them.

Examples

Input

4 2 3

Output

Yes
101000
100001

Input

3 2 1

Output

Yes
10100
10010

Input

3 2 5

Output

No

Note

In the first example, x = 101000_2 = 2^5 + 2^3 = 40_{10}, y = 100001_2 = 2^5 + 2^0 = 33_{10}, 40_{10} - 33_{10} = 7_{10} = 2^2 + 2^1 + 2^0 = 111_{2}. Hence x-y has 3 ones in base-2.

In the second example, x = 10100_2 = 2^4 + 2^2 = 20_{10}, y = 10010_2 = 2^4 + 2^1 = 18, x - y = 20 - 18 = 2_{10} = 10_{2}. This is precisely one 1.

In the third example, one may show, that it's impossible to find an answer.

```python
#tests = int(input())
#for t in range(tests):
#n = int(input())

a, b, k = list(map(int, input().split()))

if a == 0 and k!=0:
    print('No')
elif k ==0:
    print('Yes')
    print('1'*b + '0'*a)
    print('1'*b + '0'*a)
elif b==1 or k > (a+b-2):
    print('No')
else:
    shift = a+b-2-k
    print('Yes')
    ans_1 = ['1' for _ in range(b)] + ['0' for _ in range(a)]
    ans_2 = ['1'] + ['0'] + ['1' for _ in range(b-2)] + ['0' for _ in range(a-1)] + ['1']
    if shift <= (a-1):
        ans_2 = ['1'] + ['0'] + ['1' for _ in range(b-2)] + ['0' for _ in range(a-1-shift)] + ['1'] + ['0' for _ in range(shift)]
    else:
        ans_2 = ['1'] + ['1' for _ in range(shift-(a-1))] + ['0'] + ['1' for _ in range(b-2 -(shift-(a-1)))] + ['1'] + ['0' for _ in range(a-1)]
    print(''.join(ans_1))
    print(''.join(ans_2))

#    print(bin(int(''.join(ans_1),2)-int(''.join(ans_2),2)).count('1'))
```


1515_E. Phoenix and Computers

There are n computers in a row, all originally off, and Phoenix wants to turn all of them on. He will manually turn on computers one at a time. At any point, if computer i-1 and computer i+1 are both on, computer i (2 ≤ i ≤ n-1) will turn on automatically if it is not already on. Note that Phoenix cannot manually turn on a computer that already turned on automatically.

If we only consider the sequence of computers that Phoenix turns on manually, how many ways can he turn on all the computers? Two sequences are distinct if either the set of computers turned on manually is distinct, or the order of computers turned on manually is distinct. Since this number may be large, please print it modulo M.

Input

The first line contains two integers n and M (3 ≤ n ≤ 400; 10^8 ≤ M ≤ 10^9) — the number of computers and the modulo. It is guaranteed that M is prime.

Output

Print one integer — the number of ways to turn on the computers modulo M.

Examples

Input

3 100000007

Output

6

Input

4 100000007

Output

20

Input

400 234567899

Output

20914007

Note

In the first example, these are the 6 orders in which Phoenix can turn on all computers:

  * [1,3]. Turn on computer 1, then 3. Note that computer 2 turns on automatically after computer 3 is turned on manually, but we only consider the sequence of computers that are turned on manually.
  * [3,1]. Turn on computer 3, then 1.
  * [1,2,3]. Turn on computer 1, 2, then 3.
  * [2,1,3]
  * [2,3,1]
  * [3,2,1]

```python
#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase

def main():
    n, MOD = map(int, input().split())
    factorial = [1]
    for i in range(2, n + 1):
        factorial.append(factorial[-1] * i % MOD)
    for i in range(len(factorial)):
        factorial[i] = pow(factorial[i], MOD - 2, MOD)
    DP = []
    for i in range(n):
        DP.append([0] * n)
    for i in range(n):
        DP[i][0] = pow(2, i, MOD) * factorial[i]
        for j in range(1, i // 2 + 1):
            for k in range(0, i - 1):
                DP[i][j] += DP[k][j - 1] * pow(2, i - k - 2, MOD) * factorial[i - k - 2]
            DP[i][j] %= MOD
    ans = 0
    for i in range(len(factorial)):
        factorial[i] = pow(factorial[i], MOD - 2, MOD)
    for i in range(n):
        ans += DP[n - 1][i] * factorial[n - i - 1]
    print(ans % MOD)

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

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

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

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

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

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

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

# endregion

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


1542_D. Priority Queue

You are given a sequence A, where its elements are either in the form + x or -, where x is an integer.

For such a sequence S where its elements are either in the form + x or -, define f(S) as follows:

  * iterate through S's elements from the first one to the last one, and maintain a multiset T as you iterate through it.
  * for each element, if it's in the form + x, add x to T; otherwise, erase the smallest element from T (if T is empty, do nothing).
  * after iterating through all S's elements, compute the sum of all elements in T. f(S) is defined as the sum.

The sequence b is a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For all A's subsequences B, compute the sum of f(B), modulo 998 244 353.

Input

The first line contains an integer n (1≤ n≤ 500) — the length of A.

Each of the next n lines begins with an operator + or -. If the operator is +, then it's followed by an integer x (1≤ x<998 244 353). The i-th line of those n lines describes the i-th element in A.

Output

Print one integer, which is the answer to the problem, modulo 998 244 353.

Examples

Input

4
-
+ 1
+ 2
-

Output

16

Input

15
+ 2432543
-
+ 4567886
+ 65638788
-
+ 578943
-
-
+ 62356680
-
+ 711111
-
+ 998244352
-
-

Output

750759115

Note

In the first example, the following are all possible pairs of B and f(B):

  * B= {}, f(B)=0.
  * B= {-}, f(B)=0.
  * B= {+ 1, -}, f(B)=0.
  * B= {-, + 1, -}, f(B)=0.
  * B= {+ 2, -}, f(B)=0.
  * B= {-, + 2, -}, f(B)=0.
  * B= {-}, f(B)=0.
  * B= {-, -}, f(B)=0.
  * B= {+ 1, + 2}, f(B)=3.
  * B= {+ 1, + 2, -}, f(B)=2.
  * B= {-, + 1, + 2}, f(B)=3.
  * B= {-, + 1, + 2, -}, f(B)=2.
  * B= {-, + 1}, f(B)=1.
  * B= {+ 1}, f(B)=1.
  * B= {-, + 2}, f(B)=2.
  * B= {+ 2}, f(B)=2.

The sum of these values is 16.

```python
MOD = 998244353

def solve():
    n = int(input())
    ans = 0
    arr = []
    for i in range(n):
        a = list(input().split())
        if len(a) == 2:
            arr.append(int(a[1]))
        else:
            arr.append(0)
    for cur in range(n):
        if arr[cur]:
            dp = [0] * (n+1)
            dp[0] = 1
            for j, a in enumerate(arr):
                if j == cur:
                    dp = [0] + dp[:n]
                elif a == 0:
                    dp[0] = (2*dp[0]+dp[1]) % MOD
                    for i in range(1, n):
                        dp[i] = (dp[i]+dp[i+1]) % MOD
                elif a < arr[cur] or (a == arr[cur] and j < cur):
                    if j < cur:
                        for i in range(n, 0, -1):
                            dp[i] = (dp[i-1]+dp[i]) % MOD
                    else:
                        for i in range(n, 1, -1):
                            dp[i] = (dp[i-1]+dp[i]) % MOD
                        dp[0] = dp[0] * 2 % MOD
                else:
                    dp = [d*2%MOD for d in dp]
            ans = (ans+(sum(dp)-dp[0])*arr[cur]) % MOD
    return ans

import sys
input = lambda: sys.stdin.readline().rstrip()
print(solve())

```


16_D. Logging

The main server of Gomble company received a log of one top-secret process, the name of which can't be revealed. The log was written in the following format: «[date:time]: message», where for each «[date:time]» value existed not more than 10 lines. All the files were encoded in a very complicated manner, and only one programmer — Alex — managed to decode them. The code was so complicated that Alex needed four weeks to decode it. Right after the decoding process was finished, all the files were deleted. But after the files deletion, Alex noticed that he saved the recordings in format «[time]: message». So, information about the dates was lost. However, as the lines were added into the log in chronological order, it's not difficult to say if the recordings could appear during one day or not. It is possible also to find the minimum amount of days during which the log was written.

So, to make up for his mistake Alex has to find the minimum amount of days covered by the log. Note that Alex doesn't have to find the minimum amount of days between the beginning and the end of the logging, he has to find the minimum amount of dates in which records could be done. (See Sample test 2 for further clarifications).

We should remind you that the process made not more than 10 recordings in a minute. Consider that a midnight belongs to coming day.

Input

The first input line contains number n (1 ≤ n ≤ 100). The following n lines contain recordings in format «[time]: message», where time is given in format «hh:mm x.m.». For hh two-digit numbers from 01 to 12 are used, for mm two-digit numbers from 00 to 59 are used, and x is either character «a» or character «p». A message is a non-empty sequence of Latin letters and/or spaces, it doesn't start or end with a space. The length of each message doesn't exceed 20.

Output

Output one number — the minimum amount of days covered by the log.

Examples

Input

5
[05:00 a.m.]: Server is started
[05:00 a.m.]: Rescan initialized
[01:13 p.m.]: Request processed
[01:10 p.m.]: Request processed
[11:40 p.m.]: Rescan completed

Output

2

Input

3
[09:00 a.m.]: User logged in
[08:00 a.m.]: User logged in
[07:00 a.m.]: User logged in

Output

3

Note

Formally the 12-hour time format is described at:

  * http://en.wikipedia.org/wiki/12-hour_clock.

The problem authors recommend you to look through these descriptions before you start with the problem.

```python
from sys import stdin

lines = int(stdin.readline())

days = 1

count = 0

h1 = 0
m1 = 0

for x in range(lines):
  log = stdin.readline().strip()
  hour = int(log[1:3])
  if hour == 12:
    hour = 0
  if log[7] =='p':
    hour += 12
  minute = int(log[4:6])
  #print(hour,minute)
  #print(h1,m1)
  if hour < h1 or hour == h1 and minute < m1:
    days += 1
    count = 1
  elif hour == h1 and minute == m1:
    count += 1
    if count == 11:
      count = 1
      days += 1
  else:
    count = 1
  h1 = hour
  m1 = minute

print(days)

```


190_B. Surrounded

So, the Berland is at war with its eternal enemy Flatland again, and Vasya, an accountant, was assigned to fulfil his duty to the nation.

Right now the situation in Berland is dismal — their both cities are surrounded! The armies of flatlanders stand on the borders of circles, the circles' centers are in the surrounded cities. At any moment all points of the flatland ring can begin to move quickly in the direction of the city — that's the strategy the flatlanders usually follow when they besiege cities.

The berlanders are sure that they can repel the enemy's attack if they learn the exact time the attack starts. For that they need to construct a radar that would register any movement at the distance of at most r from it. Thus, we can install a radar at such point, that at least one point of the enemy ring will be in its detecting range (that is, at a distance of at most r). Then the radar can immediately inform about the enemy's attack.

Due to the newest technologies, we can place a radar at any point without any problems. But the problem is that the berlanders have the time to make only one radar. Besides, the larger the detection radius (r) is, the more the radar costs.

That's why Vasya's task (that is, your task) is to find the minimum possible detection radius for the radar. In other words, your task is to find the minimum radius r (r ≥ 0) such, that a radar with radius r can be installed at some point and it can register the start of the movements of both flatland rings from that point.

In this problem you can consider the cities as material points, the attacking enemy rings - as circles with centers in the cities, the radar's detection range — as a disk (including the border) with the center at the point where the radar is placed.

Input

The input files consist of two lines. Each line represents the city and the flatland ring that surrounds it as three space-separated integers xi, yi, ri (|xi|, |yi| ≤ 104; 1 ≤ ri ≤ 104) — the city's coordinates and the distance from the city to the flatlanders, correspondingly.

It is guaranteed that the cities are located at different points.

Output

Print a single real number — the minimum detection radius of the described radar. The answer is considered correct if the absolute or relative error does not exceed 10 - 6.

Examples

Input

0 0 1
6 0 3

Output

1.000000000000000

Input

-10 10 3
10 -10 3

Output

11.142135623730951

Note

The figure below shows the answer to the first sample. In this sample the best decision is to put the radar at point with coordinates (2, 0).

<image>

The figure below shows the answer for the second sample. In this sample the best decision is to put the radar at point with coordinates (0, 0).

<image>

```python
import sys
import math
a,b,c=map(int,sys.stdin.readline().split())
d,e,f=map(int,sys.stdin.readline().split())
ds=math.sqrt((a-d)**2+(b-e)**2)
if ds>=c+f:
	print((ds-c-f)/2)
elif ds<=abs(c-f):
	print((abs(c-f)-ds)/2)
else:
	print(0)
```


214_B. Hometask

Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?

You are given a set of digits, your task is to find the maximum integer that you can make from these digits. The made number must be divisible by 2, 3, 5 without a residue. It is permitted to use not all digits from the set, it is forbidden to use leading zeroes.

Each digit is allowed to occur in the number the same number of times it occurs in the set.

Input

A single line contains a single integer n (1 ≤ n ≤ 100000) — the number of digits in the set. The second line contains n digits, the digits are separated by a single space.

Output

On a single line print the answer to the problem. If such number does not exist, then you should print -1.

Examples

Input

1
0

Output

0

Input

11
3 4 5 4 5 3 5 3 4 4 0

Output

5554443330

Input

8
3 2 5 1 5 2 2 3

Output

-1

Note

In the first sample there is only one number you can make — 0. In the second sample the sought number is 5554443330. In the third sample it is impossible to make the required number.

```python
def hometask(arr):
    n="0"
    if arr.count(0)==0:
        return -1
    arr.remove(0)
    ans=[]
    arr=sorted(arr,reverse=True)
    while arr :
        c=sum(arr)%3
        if c==0:
            break
        flag=True
        for i in range(len(arr)-1,-1,-1):
            if arr[i]%3==c:
                arr.pop(i)
                flag=False
                break
        if flag==True:
            for i in range(len(arr) - 1, -1, -1):
                if arr[i] % 3 != 0:
                    arr.pop(i)
                    flag = False
                    break
            for i in range(len(arr) - 1, -1, -1):
                if arr[i] % 3 != 0:
                    arr.pop(i)
                    flag = False
                    break

    if arr==[] or arr[0]==0:
        return "0"
    ans="".join(map(str, sorted(arr, reverse=True)))
    return ans+n

a=input()
lst=list(map(int,input().strip().split()))
print(hometask(lst))

```


238_B. Boring Partition

This problem is the most boring one you've ever seen.

Given a sequence of integers a1, a2, ..., an and a non-negative integer h, our goal is to partition the sequence into two subsequences (not necessarily consist of continuous elements). Each element of the original sequence should be contained in exactly one of the result subsequences. Note, that one of the result subsequences can be empty.

Let's define function f(ai, aj) on pairs of distinct elements (that is i ≠ j) in the original sequence. If ai and aj are in the same subsequence in the current partition then f(ai, aj) = ai + aj otherwise f(ai, aj) = ai + aj + h.

Consider all possible values of the function f for some partition. We'll call the goodness of this partiotion the difference between the maximum value of function f and the minimum value of function f.

Your task is to find a partition of the given sequence a that have the minimal possible goodness among all possible partitions.

Input

The first line of input contains integers n and h (2 ≤ n ≤ 105, 0 ≤ h ≤ 108). In the second line there is a list of n space-separated integers representing a1, a2, ..., an (0 ≤ ai ≤ 108).

Output

The first line of output should contain the required minimum goodness.

The second line describes the optimal partition. You should print n whitespace-separated integers in the second line. The i-th integer is 1 if ai is in the first subsequence otherwise it should be 2.

If there are several possible correct answers you are allowed to print any of them.

Examples

Input

3 2
1 2 3

Output

1
1 2 2

Input

5 10
0 1 0 2 1

Output

3
2 2 2 2 2

Note

In the first sample the values of f are as follows: f(1, 2) = 1 + 2 + 2 = 5, f(1, 3) = 1 + 3 + 2 = 6 and f(2, 3) = 2 + 3 = 5. So the difference between maximum and minimum values of f is 1.

In the second sample the value of h is large, so it's better for one of the sub-sequences to be empty.

```python
#https://codeforces.com/problemset/problem/238/B
n, h  = map(int, input().split())
a     = list(map(int, input().split()))
b     = [[x, i] for i, x in enumerate(a)]
b     = sorted(b, key=lambda x:x[0])

def solve(a, n, h):
    if n == 2:
        return 0, [1, 1]

    min_  = (a[-1][0] + a[-2][0]) - (a[0][0] + a[1][0])

    # move a[0] to 2th-group
    min_2 = max(a[-1][0] + a[-2][0], a[-1][0] + a[0][0] + h) - min(a[0][0] + a[1][0] +h, a[1][0] + a[2][0])

    ans = [1] * n
    if min_2 < min_:
        min_   = min_2
        ans[a[0][1]] = 2

    return min_, ans

min_, ans = solve(b, n, h)
print(min_)
print(' '.join([str(x) for x in ans]))

#5 10
#0 1 0 2 1

#3 2
#1 2 3
```


262_E. Maxim and Matrix

Maxim loves to fill in a matrix in a special manner. Here is a pseudocode of filling in a matrix of size (m + 1) × (m + 1):

<image>

Maxim asks you to count, how many numbers m (1 ≤ m ≤ n) are there, such that the sum of values in the cells in the row number m + 1 of the resulting matrix equals t.

Expression (x xor y) means applying the operation of bitwise excluding "OR" to numbers x and y. The given operation exists in all modern programming languages. For example, in languages C++ and Java it is represented by character "^", in Pascal — by "xor".

Input

A single line contains two integers n and t (1 ≤ n, t ≤ 1012, t ≤ n + 1).

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

Output

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

Examples

Input

1 1

Output

1

Input

3 2

Output

1

Input

3 3

Output

0

Input

1000000000000 1048576

Output

118606527258

```python
def comb(n, r):
    if r > n or r < 0:
        return 0
    r = min(r, n-r)
    result = 1
    for i in range(1, r+1):
        result = result*(n+1-i)//i
    return result

def F(n, t):
    if t == 0:
        return 1
    elif n == 0:
        return 0
    elif n == 1:
        return int(t == 1)
    m = len(bin(n)) - 3
    return F(n-(1 << m), t-1) + comb(m, t)

n, t = map(int, input().strip().split())
T = len(bin(t)) - 3
if (1 << T) != t:
    print(0)
else:
    print(F(n+1, T+1) - int(t == 1))

```


334_C. Secrets

Gerald has been selling state secrets at leisure. All the secrets cost the same: n marks. The state which secrets Gerald is selling, has no paper money, only coins. But there are coins of all positive integer denominations that are powers of three: 1 mark, 3 marks, 9 marks, 27 marks and so on. There are no coins of other denominations. Of course, Gerald likes it when he gets money without the change. And all buyers respect him and try to give the desired sum without change, if possible. But this does not always happen.

One day an unlucky buyer came. He did not have the desired sum without change. Then he took out all his coins and tried to give Gerald a larger than necessary sum with as few coins as possible. What is the maximum number of coins he could get?

The formal explanation of the previous paragraph: we consider all the possible combinations of coins for which the buyer can not give Gerald the sum of n marks without change. For each such combination calculate the minimum number of coins that can bring the buyer at least n marks. Among all combinations choose the maximum of the minimum number of coins. This is the number we want.

Input

The single line contains a single integer n (1 ≤ n ≤ 1017).

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

Output

In a single line print an integer: the maximum number of coins the unlucky buyer could have paid with.

Examples

Input

1

Output

1

Input

4

Output

2

Note

In the first test case, if a buyer has exactly one coin of at least 3 marks, then, to give Gerald one mark, he will have to give this coin. In this sample, the customer can not have a coin of one mark, as in this case, he will be able to give the money to Gerald without any change.

In the second test case, if the buyer had exactly three coins of 3 marks, then, to give Gerald 4 marks, he will have to give two of these coins. The buyer cannot give three coins as he wants to minimize the number of coins that he gives.

```python

n = int(input())

res = 1
x = 1
while x <= n:
  if n%x != 0:
    res = max(res, (n+x-1)//x)
  x *= 3
print(res)

```


357_C. Knight Tournament

Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.

As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:

  * There are n knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to n.
  * The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament.
  * After the i-th fight among all participants of the fight only one knight won — the knight number xi, he continued participating in the tournament. Other knights left the tournament.
  * The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament.

You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.

Write the code that calculates for each knight, the name of the knight that beat him.

Input

The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ 3·105) — the number of knights and the number of fights. Each of the following m lines contains three integers li, ri, xi (1 ≤ li < ri ≤ n; li ≤ xi ≤ ri) — the description of the i-th fight.

It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.

Output

Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0.

Examples

Input

4 3
1 2 1
1 3 3
1 4 4

Output

3 1 4 0

Input

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

Output

0 8 4 6 4 8 6 1

Note

Consider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won.

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

p, d = [0] * (n + 2), list(range(1, n + 3))

for i in range(m):

    l, r, x = map(int, input().split())

    while l < x:

        if p[l]:

            k = d[l]

            d[l] = x

            l = k

        else:

            d[l], p[l] = x, x

            l += 1

    l += 1

    r += 1

    while p[r]: r = d[r]

    while l < r:

        if p[l]:

            k = d[l]

            d[l] = r

            l = k

        else:

            d[l], p[l] = r, x

            l += 1

print(' '.join(map(str, p[1: -1])))

# Made By Mostafa_Khaled
```


401_A. Vanya and Cards

Vanya loves playing. He even has a special set of cards to play with. Each card has a single integer. The number on the card can be positive, negative and can even be equal to zero. The only limit is, the number on each card doesn't exceed x in the absolute value.

Natasha doesn't like when Vanya spends a long time playing, so she hid all of his cards. Vanya became sad and started looking for the cards but he only found n of them. Vanya loves the balance, so he wants the sum of all numbers on found cards equal to zero. On the other hand, he got very tired of looking for cards. Help the boy and say what is the minimum number of cards does he need to find to make the sum equal to zero?

You can assume that initially Vanya had infinitely many cards with each integer number from  - x to x.

Input

The first line contains two integers: n (1 ≤ n ≤ 1000) — the number of found cards and x (1 ≤ x ≤ 1000) — the maximum absolute value of the number on a card. The second line contains n space-separated integers — the numbers on found cards. It is guaranteed that the numbers do not exceed x in their absolute value.

Output

Print a single number — the answer to the problem.

Examples

Input

3 2
-1 1 2

Output

1

Input

2 3
-2 -2

Output

2

Note

In the first sample, Vanya needs to find a single card with number -2.

In the second sample, Vanya needs to find two cards with number 2. He can't find a single card with the required number as the numbers on the lost cards do not exceed 3 in their absolute value.

```python
inp = input().split(' ')
n = int(inp[0])
x = int(inp[1])

su = 0
inp = input().split(' ')
for i in inp:
   su += int(i)

count = 0
while su!=0:
     count += 1
     if su > 0:
         su += max(-x, -su)
     else:
         su += min(x, -su)

print(count)
```


429_B. Working out

Summer is coming! It's time for Iahub and Iahubina to work out, as they both want to look hot at the beach. The gym where they go is a matrix a with n lines and m columns. Let number a[i][j] represents the calories burned by performing workout at the cell of gym in the i-th line and the j-th column.

Iahub starts with workout located at line 1 and column 1. He needs to finish with workout a[n][m]. After finishing workout a[i][j], he can go to workout a[i + 1][j] or a[i][j + 1]. Similarly, Iahubina starts with workout a[n][1] and she needs to finish with workout a[1][m]. After finishing workout from cell a[i][j], she goes to either a[i][j + 1] or a[i - 1][j].

There is one additional condition for their training. They have to meet in exactly one cell of gym. At that cell, none of them will work out. They will talk about fast exponentiation (pretty odd small talk) and then both of them will move to the next workout.

If a workout was done by either Iahub or Iahubina, it counts as total gain. Please plan a workout for Iahub and Iahubina such as total gain to be as big as possible. Note, that Iahub and Iahubina can perform workouts with different speed, so the number of cells that they use to reach meet cell may differs.

Input

The first line of the input contains two integers n and m (3 ≤ n, m ≤ 1000). Each of the next n lines contains m integers: j-th number from i-th line denotes element a[i][j] (0 ≤ a[i][j] ≤ 105).

Output

The output contains a single number — the maximum total gain possible.

Examples

Input

3 3
100 100 100
100 1 100
100 100 100

Output

800

Note

Iahub will choose exercises a[1][1] → a[1][2] → a[2][2] → a[3][2] → a[3][3]. Iahubina will choose exercises a[3][1] → a[2][1] → a[2][2] → a[2][3] → a[1][3].

```python
# -*- coding:utf-8 -*-

"""

created by shuangquan.huang at 1/7/20

"""

import collections
import time
import os
import sys
import bisect
import heapq
from typing import List

def solve(N, M, A):
    dpa = [[0 for _ in range(M+2)] for _ in range(N+2)]
    dpb = [[0 for _ in range(M+2)] for _ in range(N+2)]
    dpc = [[0 for _ in range(M+2)] for _ in range(N+2)]
    dpd = [[0 for _ in range(M+2)] for _ in range(N+2)]

    for r in range(1, N+1):
        for c in range(1, M + 1):
            dpa[r][c] = max(dpa[r-1][c], dpa[r][c-1]) + A[r][c]

    for r in range(N, 0, -1):
        for c in range(M, 0, -1):
            dpb[r][c] = max(dpb[r+1][c], dpb[r][c+1]) + A[r][c]

    for r in range(N, 0, -1):
        for c in range(1, M+1):
            dpc[r][c] = max(dpc[r+1][c], dpc[r][c-1]) + A[r][c]

    for r in range(1, N+1):
        for c in range(M, 0, -1):
            dpd[r][c] = max(dpd[r-1][c], dpd[r][c+1]) + A[r][c]

    ans = 0
    for r in range(2, N):
        for c in range(2, M):
            a = dpa[r][c-1] + dpb[r][c+1] + dpc[r+1][c] + dpd[r-1][c]
            b = dpc[r][c-1] + dpd[r][c+1] + dpa[r-1][c] + dpb[r+1][c]
            ans = max(ans, a, b)

    return ans

N, M = map(int, input().split())
A = [[0 for _ in range(M+2)]]
for i in range(N):
    row = [0] + [int(x) for x in input().split()] + [0]
    A.append(row)
A.append([0 for _ in range(M+2)])

print(solve(N, M, A))
```


450_E. Jzzhu and Apples

Jzzhu has picked n apples from his big apple tree. All the apples are numbered from 1 to n. Now he wants to sell them to an apple store.

Jzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be greater than 1. Of course, each apple can be part of at most one group.

Jzzhu wonders how to get the maximum possible number of groups. Can you help him?

Input

A single integer n (1 ≤ n ≤ 105), the number of the apples.

Output

The first line must contain a single integer m, representing the maximum number of groups he can get. Each of the next m lines must contain two integers — the numbers of apples in the current group.

If there are several optimal answers you can print any of them.

Examples

Input

6

Output

2
6 3
2 4

Input

9

Output

3
9 3
2 4
6 8

Input

2

Output

0

```python
import math
apples=int(input())
if apples<=3:
    print(0)
else:
    halfpr=int(apples/2)
    def primes(n):
        primeslistsa=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37,
                     41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83,
                     89, 97, 101, 103, 107, 109, 113, 127, 131,
                     137, 139, 149, 151, 157, 163, 167, 173, 179,
                     181, 191, 193, 197, 199, 211, 223, 227, 229,
                     233, 239, 241, 251, 257, 263, 269, 271, 277,
                     281, 283, 293, 307, 311, 313, 317]
        yesnoprime=[False, False]+[True]*(n-1)
        t=0
        while primeslistsa[t+1]<=int(math.sqrt(n)):
            t+=1
        for x in range(t+1):
            for sa in range(2, int(n/primeslistsa[x]+1)):
                yesnoprime[primeslistsa[x]*sa]=False
        return yesnoprime

    primeslist=primes(halfpr)
    totallist=[False]*(apples+1)
    applepairs=[]
    for prime in range(len(primeslist)-1, 1, -1):
        if primeslist[prime]:
            numprimes=int(apples/prime)
            primesx=[int(i*prime) for i in range(1, numprimes+1) if not totallist[i*prime]]
            if len(primesx)%2==1:
                primesx.remove(2*prime)
            for pr in primesx:
                 applepairs.append(pr)
                 totallist[pr]=True
    print(int(len(applepairs)/2))
    for t in range(int(len(applepairs)/2)):
        print(applepairs[2*t], applepairs[2*t+1])

```


497_B. Tennis Game

Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.

To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.

Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?

Input

The first line contains a single integer n — the length of the sequence of games (1 ≤ n ≤ 105).

The second line contains n space-separated integers ai. If ai = 1, then the i-th serve was won by Petya, if ai = 2, then the i-th serve was won by Gena.

It is not guaranteed that at least one option for numbers s and t corresponds to the given record.

Output

In the first line print a single number k — the number of options for numbers s and t.

In each of the following k lines print two integers si and ti — the option for numbers s and t. Print the options in the order of increasing si, and for equal si — in the order of increasing ti.

Examples

Input

5
1 2 1 2 1

Output

2
1 3
3 1

Input

4
1 1 1 1

Output

3
1 4
2 2
4 1

Input

4
1 2 1 2

Output

0

Input

8
2 1 2 1 1 1 1 1

Output

3
1 6
2 3
6 1

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

line = input().split()
lst = []
for num in line:
    lst.append(int(num))

cnt1 = [0]
cnt2 = [0]
c1 = 0
c2 = 0

for num in lst:
    if num == 1:
        c1 += 1
        cnt1.append(c2)
    else:
        c2 += 1
        cnt2.append(c1)

w = lst[n - 1]
ans = []
c1 = len(cnt1)
c2 = len(cnt2)
for t in range(n, 0, -1):
    s1 = 0
    s2 = 0
    i1 = 0
    i2 = 0
    l = 1
    while i1 < c1 and i2 < c2:
        if i1 + t >= c1 and i2 + t >= c2:
            if l == 1 and l == w and i1 + 1 == c1 and s1 > s2:
                ans.append((s1, t))
            elif l == 2 and l == w and i2 + 1 == c2 and s2 > s1:
                ans.append((s2, t))
            break
        elif i2 + t >= c2:
            s1 += 1
            l = 1
            i1 += t
            i2 = cnt1[i1]
        elif i1 + t >= c1:
            s2 += 1
            l = 2
            i2 += t
            i1 = cnt2[i2]
        else:
            if cnt1[i1 + t] < i2 + t:
                s1 += 1
                l = 1
                i1 += t
                i2 = cnt1[i1]
            else:
                s2 += 1
                l = 2
                i2 += t
                i1 = cnt2[i2]

ans.sort()

print(int(len(ans)))
for line in ans:
    print(str(line[0]) + ' ' + str(line[1]))

```


548_A. Mike and Fax

While Mike was walking in the subway, all the stuff in his back-bag dropped on the ground. There were several fax messages among them. He concatenated these strings in some order and now he has string s.

<image>

He is not sure if this is his own back-bag or someone else's. He remembered that there were exactly k messages in his own bag, each was a palindrome string and all those strings had the same length.

He asked you to help him and tell him if he has worn his own back-bag. Check if the given string s is a concatenation of k palindromes of the same length.

Input

The first line of input contains string s containing lowercase English letters (1 ≤ |s| ≤ 1000).

The second line contains integer k (1 ≤ k ≤ 1000).

Output

Print "YES"(without quotes) if he has worn his own back-bag or "NO"(without quotes) otherwise.

Examples

Input

saba
2

Output

NO

Input

saddastavvat
2

Output

YES

Note

Palindrome is a string reading the same forward and backward.

In the second sample, the faxes in his back-bag can be "saddas" and "tavvat".

```python
def isPalindrome(t):
    for i in range(len(t)//2):
        if t[i] != t[len(t)-i-1]:
            return False
    return True
s = input()
k = int(input())
if len(s) % k:
    print('NO')
else:
    t = len(s)//k
    for i in range(k):
        if not isPalindrome(s[i*t: i*t+t]):
            print('NO')
            break
    else:
        print('YES')

```


574_C. Bear and Poker

Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are n players (including Limak himself) and right now all of them have bids on the table. i-th of them has bid with size ai dollars.

Each player can double his bid any number of times and triple his bid any number of times. The casino has a great jackpot for making all bids equal. Is it possible that Limak and his friends will win a jackpot?

Input

First line of input contains an integer n (2 ≤ n ≤ 105), the number of players.

The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 109) — the bids of players.

Output

Print "Yes" (without the quotes) if players can make their bids become equal, or "No" otherwise.

Examples

Input

4
75 150 75 50

Output

Yes

Input

3
100 150 250

Output

No

Note

In the first sample test first and third players should double their bids twice, second player should double his bid once and fourth player should both double and triple his bid.

It can be shown that in the second sample test there is no way to make all bids equal.

```python
n = int(input())
arr = [int(x) for x in input().split()]
for i in range(n):
    while arr[i]%2==0:
        arr[i]/=2
    while arr[i]%3==0:
        arr[i]/=3
print("Yes" if all(arr[0]==arr[i] for i in range(n))else "No")
```


596_A. Wilbur and Swimming Pool

After making bad dives into swimming pools, Wilbur wants to build a swimming pool in the shape of a rectangle in his backyard. He has set up coordinate axes, and he wants the sides of the rectangle to be parallel to them. Of course, the area of the rectangle must be positive. Wilbur had all four vertices of the planned pool written on a paper, until his friend came along and erased some of the vertices.

Now Wilbur is wondering, if the remaining n vertices of the initial rectangle give enough information to restore the area of the planned swimming pool.

Input

The first line of the input contains a single integer n (1 ≤ n ≤ 4) — the number of vertices that were not erased by Wilbur's friend.

Each of the following n lines contains two integers xi and yi ( - 1000 ≤ xi, yi ≤ 1000) —the coordinates of the i-th vertex that remains. Vertices are given in an arbitrary order.

It's guaranteed that these points are distinct vertices of some rectangle, that has positive area and which sides are parallel to the coordinate axes.

Output

Print the area of the initial rectangle if it could be uniquely determined by the points remaining. Otherwise, print  - 1.

Examples

Input

2
0 0
1 1

Output

1

Input

1
1 1

Output

-1

Note

In the first sample, two opposite corners of the initial rectangle are given, and that gives enough information to say that the rectangle is actually a unit square.

In the second sample there is only one vertex left and this is definitely not enough to uniquely define the area.

```python
def judgeTwoPoints( pa , pb ):
    if pa[0] != pb[0] and pa[1] != pb[1]:
        #print( "ok!" , pa , pb , abs( pa[0] - pb[0] ) * abs( pa[1] - pb[1] ) )
        return abs( pa[0] - pb[0] ) * abs( pa[1] - pb[1] )
    else:
        return -1

def solve( pts , n ):
    if n == 1:
        return -1

    pts.sort()
    if n == 2:
        return judgeTwoPoints( pts[0] , pts[1] )
    if n == 3:
        resa = judgeTwoPoints( pts[0] , pts[1] )
        resb = judgeTwoPoints( pts[1] , pts[2] )
        resc = judgeTwoPoints( pts[0] , pts[2] )
        return max( resa , resb , resc )

    return judgeTwoPoints( pts[1] , pts[2] )

if __name__ == "__main__":
    n = int( input() )
    pts = []
    for _ in range(n):
        pts.append( tuple([int(x) for x in input().split()]) )

    #print( pts )
    print( solve( pts , n ) )
```


617_C. Watering Flowers

A flowerbed has many flowers and two fountains.

You can adjust the water pressure and set any values r1(r1 ≥ 0) and r2(r2 ≥ 0), giving the distances at which the water is spread from the first and second fountain respectively. You have to set such r1 and r2 that all the flowers are watered, that is, for each flower, the distance between the flower and the first fountain doesn't exceed r1, or the distance to the second fountain doesn't exceed r2. It's OK if some flowers are watered by both fountains.

You need to decrease the amount of water you need, that is set such r1 and r2 that all the flowers are watered and the r12 + r22 is minimum possible. Find this minimum value.

Input

The first line of the input contains integers n, x1, y1, x2, y2 (1 ≤ n ≤ 2000,  - 107 ≤ x1, y1, x2, y2 ≤ 107) — the number of flowers, the coordinates of the first and the second fountain.

Next follow n lines. The i-th of these lines contains integers xi and yi ( - 107 ≤ xi, yi ≤ 107) — the coordinates of the i-th flower.

It is guaranteed that all n + 2 points in the input are distinct.

Output

Print the minimum possible value r12 + r22. Note, that in this problem optimal answer is always integer.

Examples

Input

2 -1 0 5 3
0 2
5 2

Output

6

Input

4 0 0 5 0
9 4
8 3
-1 0
1 4

Output

33

Note

The first sample is (r12 = 5, r22 = 1): <image> The second sample is (r12 = 1, r22 = 32): <image>

```python
f = lambda: map(int, input().split())
n, a, b, c, d = f()
t = []
for i in range(n):
    x, y = f()
    t.append(((x - a) ** 2 + (y - b) ** 2, (x - c) ** 2 + (y - d) ** 2))
t.sort()
s = 8e14
q = 0
for u, v in reversed(t):
    s = min(s, u + q)
    q = max(q, v)
print(min(s, q))
```


637_D. Running with Obstacles

A sportsman starts from point xstart = 0 and runs to point with coordinate xfinish = m (on a straight line). Also, the sportsman can jump — to jump, he should first take a run of length of not less than s meters (in this case for these s meters his path should have no obstacles), and after that he can jump over a length of not more than d meters. Running and jumping is permitted only in the direction from left to right. He can start andfinish a jump only at the points with integer coordinates in which there are no obstacles. To overcome some obstacle, it is necessary to land at a point which is strictly to the right of this obstacle.

On the way of an athlete are n obstacles at coordinates x1, x2, ..., xn. He cannot go over the obstacles, he can only jump over them. Your task is to determine whether the athlete will be able to get to the finish point.

Input

The first line of the input containsd four integers n, m, s and d (1 ≤ n ≤ 200 000, 2 ≤ m ≤ 109, 1 ≤ s, d ≤ 109) — the number of obstacles on the runner's way, the coordinate of the finishing point, the length of running before the jump and the maximum length of the jump, correspondingly.

The second line contains a sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ m - 1) — the coordinates of the obstacles. It is guaranteed that the starting and finishing point have no obstacles, also no point can have more than one obstacle, The coordinates of the obstacles are given in an arbitrary order.

Output

If the runner cannot reach the finishing point, print in the first line of the output "IMPOSSIBLE" (without the quotes).

If the athlete can get from start to finish, print any way to do this in the following format:

  * print a line of form "RUN X>" (where "X" should be a positive integer), if the athlete should run for "X" more meters;
  * print a line of form "JUMP Y" (where "Y" should be a positive integer), if the sportsman starts a jump and should remain in air for "Y" more meters.

All commands "RUN" and "JUMP" should strictly alternate, starting with "RUN", besides, they should be printed chronologically. It is not allowed to jump over the finishing point but it is allowed to land there after a jump. The athlete should stop as soon as he reaches finish.

Examples

Input

3 10 1 3
3 4 7

Output

RUN 2
JUMP 3
RUN 1
JUMP 2
RUN 2

Input

2 9 2 3
6 4

Output

IMPOSSIBLE

```python
n,m,s,d=map(int,input().split())
x=list(map(int,input().split()))+[m+s+1]
x.sort()
cur=l=0
ans=[]
while l<m:
  r=min(x[cur]-1,m)
  ans.append(("RUN",r-l))
  if r==m:
    break
  if r-l<s:
    print("IMPOSSIBLE")
    exit()
  t=x[cur]+1
  while x[cur+1]-1-t<s:
    cur+=1
    t=x[cur]+1
  if t-r>d:
    print("IMPOSSIBLE")
    exit()
  ans.append(("JUMP",t-r))
  l=t
  cur+=1
for aa in ans:
  print(*aa)
```