1179_A. Valeriy and Deque

Recently, on the course of algorithms and data structures, Valeriy learned how to use a deque. He built a deque filled with n elements. The i-th element is a_i (i = 1, 2, …, n). He gradually takes the first two leftmost elements from the deque (let's call them A and B, respectively), and then does the following: if A > B, he writes A to the beginning and writes B to the end of the deque, otherwise, he writes to the beginning B, and A writes to the end of the deque. We call this sequence of actions an operation.

For example, if deque was [2, 3, 4, 5, 1], on the operation he will write B=3 to the beginning and A=2 to the end, so he will get [3, 4, 5, 1, 2].

The teacher of the course, seeing Valeriy, who was passionate about his work, approached him and gave him q queries. Each query consists of the singular number m_j (j = 1, 2, …, q). It is required for each query to answer which two elements he will pull out on the m_j-th operation.

Note that the queries are independent and for each query the numbers A and B should be printed in the order in which they will be pulled out of the deque.

Deque is a data structure representing a list of elements where insertion of new elements or deletion of existing elements can be made from both sides.

Input

The first line contains two integers n and q (2 ≤ n ≤ 10^5, 0 ≤ q ≤ 3 ⋅ 10^5) — the number of elements in the deque and the number of queries. The second line contains n integers a_1, a_2, ..., a_n, where a_i (0 ≤ a_i ≤ 10^9) — the deque element in i-th position. The next q lines contain one number each, meaning m_j (1 ≤ m_j ≤ 10^{18}).

Output

For each teacher's query, output two numbers A and B — the numbers that Valeriy pulls out of the deque for the m_j-th operation.

Examples

Input

5 3
1 2 3 4 5
1
2
10

Output

1 2
2 3
5 2

Input

2 0
0 0

Output

Note

Consider all 10 steps for the first test in detail:
  1. [1, 2, 3, 4, 5] — on the first operation, A and B are 1 and 2, respectively.

So, 2 we write to the beginning of the deque, and 1 — to the end.

We get the following status of the deque: [2, 3, 4, 5, 1].

  2. [2, 3, 4, 5, 1] ⇒ A = 2, B = 3.
  3. [3, 4, 5, 1, 2]
  4. [4, 5, 1, 2, 3]
  5. [5, 1, 2, 3, 4]
  6. [5, 2, 3, 4, 1]
  7. [5, 3, 4, 1, 2]
  8. [5, 4, 1, 2, 3]
  9. [5, 1, 2, 3, 4]
  10. [5, 2, 3, 4, 1] ⇒ A = 5, B = 2.

```python
import os
import sys
from io import BytesIO, IOBase

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

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

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

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

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

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

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#######################################
from collections import *
from collections import deque
from operator import itemgetter , attrgetter
from decimal import *
import bisect
import math
import heapq as hq
#import sympy
MOD=10**9 +7

def is_prime(n):
  if n == 2 or n == 3: return True
  if n < 2 or n%2 == 0: return False
  if n < 9: return True
  if n%3 == 0: return False
  r = int(n**0.5)
  # since all primes > 3 are of the form 6n ± 1
  # start with f=5 (which is prime)
  # and test f, f+2 for being prime
  # then loop by 6.
  f = 5
  while f <= r:

    if n % f == 0: return False
    if n % (f+2) == 0: return False
    f += 6
  return True

def pow(a,b,m):
    ans=1
    while b:
        if b&1:
            ans=(ans*a)%m
        b//=2
        a=(a*a)%m
    return ans
#vis=[]
#graph=[]

def ispalindrome(s):
    if s[:]==s[::-1]:
        return 1
    return 0
dp=[]
limit=[]
v=[]
def dpdfs(u,t=-1):
    dp[0][u]=0
    dp[1][u]=0
    for i in v[u]:
        if i==t:

            continue
        if dp[1][i]==-1:
            dpdfs(i,u)
        dp[0][u]+=max(abs(limit[0][u]-limit[1][i])+dp[1][i],abs(limit[0][u]-limit[0][i])+dp[0][i])
        dp[1][u] += max(abs(limit[1][u] - limit[1][i]) + dp[1][i], abs(limit[1][u] - limit[0][i]) + dp[0][i])
vis=[]
def dfs(x,f):
    pa[x]=f
    size[x]=1
    mx=0
    for y in temp[x]:
        if y==f:
            continue
        dfs(y,x)
        size[x]+=size[y]

from queue import PriorityQueue
n,q=map(int,input().split())
l=list(map(int,input().split()))
x=l.index(max(l))
temp=[]
prev=l[0]
rot=[]
for i in range(x+1,n):
    rot.append(l[i])

for i in range(x):
    temp.append([prev,l[i+1]])
    rot.append(min(prev,l[i+1]))
    prev=max(prev,l[i+1])
#print(temp,"temp")
#print(rot,"rot")
for i in range(q):
    y=int(input())
    y-=1
    if y<len(temp):
        print(*temp[y])
    else:
        print(l[x],end=" ")
        y-=x
        print(rot[y%(n-1)])

```


1197_C. Array Splitting

You are given a sorted array a_1, a_2, ..., a_n (for each index i > 1 condition a_i ≥ a_{i-1} holds) and an integer k.

You are asked to divide this array into k non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray.

Let max(i) be equal to the maximum in the i-th subarray, and min(i) be equal to the minimum in the i-th subarray. The cost of division is equal to ∑_{i=1}^{k} (max(i) - min(i)). For example, if a = [2, 4, 5, 5, 8, 11, 19] and we divide it into 3 subarrays in the following way: [2, 4], [5, 5], [8, 11, 19], then the cost of division is equal to (4 - 2) + (5 - 5) + (19 - 8) = 13.

Calculate the minimum cost you can obtain by dividing the array a into k non-empty consecutive subarrays.

Input

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 3 ⋅ 10^5).

The second line contains n integers a_1, a_2, ..., a_n ( 1 ≤ a_i ≤ 10^9, a_i ≥ a_{i-1}).

Output

Print the minimum cost you can obtain by dividing the array a into k nonempty consecutive subarrays.

Examples

Input

6 3
4 8 15 16 23 42

Output

12

Input

4 4
1 3 3 7

Output

0

Input

8 1
1 1 2 3 5 8 13 21

Output

20

Note

In the first test we can divide array a in the following way: [4, 8, 15, 16], [23], [42].

```python
n, k = map(int, input().split())
l = list(map(int, input().split()))
ll = []
for i in range(n-1):
    ll.append(l[i+1]-l[i])
ll.sort()
print(sum(ll[:n-k]))

```


1214_D. Treasure Island

All of us love treasures, right? That's why young Vasya is heading for a Treasure Island.

Treasure Island may be represented as a rectangular table n × m which is surrounded by the ocean. Let us number rows of the field with consecutive integers from 1 to n from top to bottom and columns with consecutive integers from 1 to m from left to right. Denote the cell in r-th row and c-th column as (r, c). Some of the island cells contain impassable forests, and some cells are free and passable. Treasure is hidden in cell (n, m).

Vasya got off the ship in cell (1, 1). Now he wants to reach the treasure. He is hurrying up, so he can move only from cell to the cell in next row (downwards) or next column (rightwards), i.e. from cell (x, y) he can move only to cells (x+1, y) and (x, y+1). Of course Vasya can't move through cells with impassable forests.

Evil Witch is aware of Vasya's journey and she is going to prevent him from reaching the treasure. Before Vasya's first move she is able to grow using her evil magic impassable forests in previously free cells. Witch is able to grow a forest in any number of any free cells except cells (1, 1) where Vasya got off his ship and (n, m) where the treasure is hidden.

Help Evil Witch by finding out the minimum number of cells she has to turn into impassable forests so that Vasya is no longer able to reach the treasure.

Input

First line of input contains two positive integers n, m (3 ≤ n ⋅ m ≤ 1 000 000), sizes of the island.

Following n lines contains strings s_i of length m describing the island, j-th character of string s_i equals "#" if cell (i, j) contains an impassable forest and "." if the cell is free and passable. Let us remind you that Vasya gets of his ship at the cell (1, 1), i.e. the first cell of the first row, and he wants to reach cell (n, m), i.e. the last cell of the last row.

It's guaranteed, that cells (1, 1) and (n, m) are empty.

Output

Print the only integer k, which is the minimum number of cells Evil Witch has to turn into impassable forest in order to prevent Vasya from reaching the treasure.

Examples

Input

2 2
..
..

Output

2

Input

4 4
....
#.#.
....
.#..

Output

1

Input

3 4
....
.##.
....

Output

2

Note

The following picture illustrates the island in the third example. Blue arrows show possible paths Vasya may use to go from (1, 1) to (n, m). Red illustrates one possible set of cells for the Witch to turn into impassable forest to make Vasya's trip from (1, 1) to (n, m) impossible.

<image>

```python
import sys
from io import BytesIO, IOBase
from collections import defaultdict, deque

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        import os
        self.os = os
        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
        self.BUFSIZE = 8192

    def read(self):
        while True:
            b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.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 = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.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:
            self.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")

def get_int():
    return int(input())

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

def get_int_grid(n):
    return [get_ints() for _ in range(n)]

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

def get_strs():
    return get_str().split(' ')

def flat_list(arr):
    return [item for subarr in arr for item in subarr]

def yes_no(b):
    if b:
        return "YES"
    else:
        return "NO"

def binary_search(good, left, right, delta=1, right_true=False):
    """
    Performs binary search
    ----------
    Parameters
    ----------
    :param good: Function used to perform the binary search
    :param left: Starting value of left limit
    :param right: Starting value of the right limit
    :param delta: Margin of error, defaults value of 1 for integer binary search
    :param right_true: Boolean, for whether the right limit is the true invariant
    :return: Returns the most extremal value interval [left, right] which is good function evaluates to True,
            alternatively returns False if no such value found
    """

    limits = [left, right]
    while limits[1] - limits[0] > delta:
        if delta == 1:
            mid = sum(limits) // 2
        else:
            mid = sum(limits) / 2
        if good(mid):
            limits[int(right_true)] = mid
        else:
            limits[int(~right_true)] = mid
    if good(limits[int(right_true)]):
        return limits[int(right_true)]
    else:
        return False

def prefix_sums(a):
    p = [0]
    for x in a:
        p.append(p[-1] + x)
    return p

def solve_a():
    n = get_int()
    d = get_int()
    e = get_int()
    best = float('inf')
    while n >= 0:
        best = min(best, n % d)
        n -= 5 * e
    return best

def solve_b():
    b = get_int()
    g = get_int()
    n = get_int()
    return min(b, n) - max(0, n - g) + 1

def solve_c():
    n = get_int()
    s = get_str()

    open = 0

    for idx, char in enumerate(s):
        if char == '(':
            open += 1
        else:
            open -= 1
        if open < - 1:
            return False
    return open == 0

def solve_d():
    n, m = get_ints()
    grid = [['#'] * (m + 2)]
    for row in range(n):
        grid.append(['#'] + list(get_str()) + ['#'])
    grid.append(['#'] * (m + 2))

    if n > 5 * 10 ** 5:
        for i in range(n):
            if grid[i + 1][1] == '#':
                return 0
        return 1

    if m > 5 * 10 ** 5:
        for j in range(m):
            if grid[1][j + 1] == '#':
                return 0
        return 1

    queue = deque([(1, 1)])
    vis_forward = [[0] * (m + 2) for _ in range(n + 2)]
    while queue:
        x, y = queue.popleft()
        if not vis_forward[x][y]:
            vis_forward[x][y] = 1
            if grid[x + 1][y] == '.':
                queue.append((x + 1, y))
            if grid[x][y + 1] == '.':
                queue.append((x, y + 1))

    back_queue = deque([(n, m)])
    vis_backward = [[0] * (m + 2) for _ in range(n + 2)]
    while back_queue:
        x, y = back_queue.popleft()
        if not vis_backward[x][y]:
            vis_backward[x][y] = 1
            if grid[x - 1][y] == '.':
                back_queue.append((x - 1, y))
            if grid[x][y - 1] == '.':
                back_queue.append((x, y - 1))

    score = [0] * (n + m - 1)

    if not vis_forward[n][m] or not vis_backward[1][1]:
        return 0

    for i in range(n):
        for j in range(m):
            score[i + j] += vis_forward[i + 1][j + 1] * vis_backward[i + 1][j + 1]

    if not max(score[0], score[-1]):
        return 0
    else:
        return min(2, min(score[1:-1]))

print(solve_d())
```


1255_E2. Send Boxes to Alice (Hard Version)

This is the harder version of the problem. In this version, 1 ≤ n ≤ 10^6 and 0 ≤ a_i ≤ 10^6. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems

Christmas is coming, and our protagonist, Bob, is preparing a spectacular present for his long-time best friend Alice. This year, he decides to prepare n boxes of chocolate, numbered from 1 to n. Initially, the i-th box contains a_i chocolate pieces.

Since Bob is a typical nice guy, he will not send Alice n empty boxes. In other words, at least one of a_1, a_2, …, a_n is positive. Since Alice dislikes coprime sets, she will be happy only if there exists some integer k > 1 such that the number of pieces in each box is divisible by k. Note that Alice won't mind if there exists some empty boxes.

Charlie, Alice's boyfriend, also is Bob's second best friend, so he decides to help Bob by rearranging the chocolate pieces. In one second, Charlie can pick up a piece in box i and put it into either box i-1 or box i+1 (if such boxes exist). Of course, he wants to help his friend as quickly as possible. Therefore, he asks you to calculate the minimum number of seconds he would need to make Alice happy.

Input

The first line contains a single integer n (1 ≤ n ≤ 10^6) — the number of chocolate boxes.

The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^6) — the number of chocolate pieces in the i-th box.

It is guaranteed that at least one of a_1, a_2, …, a_n is positive.

Output

If there is no way for Charlie to make Alice happy, print -1.

Otherwise, print a single integer x — the minimum number of seconds for Charlie to help Bob make Alice happy.

Examples

Input

3
4 8 5

Output

9

Input

5
3 10 2 1 5

Output

2

Input

4
0 5 15 10

Output

0

Input

1
1

Output

-1

Note

In the first example, Charlie can move all chocolate pieces to the second box. Each box will be divisible by 17.

In the second example, Charlie can move a piece from box 2 to box 3 and a piece from box 4 to box 5. Each box will be divisible by 3.

In the third example, each box is already divisible by 5.

In the fourth example, since Charlie has no available move, he cannot help Bob make Alice happy.

```python
import sys

# inf = open('input.txt', 'r')
# input = inf.readline
input = sys.stdin.readline

n = int(input())
a = list(map(int, input().split()))

def primeDivisors(num):
    sqrtNum = int(num ** 0.5) + 1
    primes = []
    if not num & 1:
        primes.append(2)
        while not num & 1:
            num >>= 1
    f = 3
    while f < sqrtNum and num > 1:
        if num % f == 0:
            primes.append(f)
            while num % f == 0:
                num //= f
        f += 2
    if num > 1:
        primes.append(num)
    return primes

def minMoves(n, a):
    num = sum(a)
    if num == 1:
        return None

    ans = float('inf')
    for p in primeDivisors(num):
        ansP = 0
        leftSum = 0
        for i in range(n):
            leftSum += a[i]
            leftSum %= p
            ansP += min(leftSum, p - leftSum)
        ans = min(ans, ansP)

    return ans

ans = minMoves(n, a)
if ans is None:
    print(-1)
else:
    print(ans)

# inf.close()

```


1279_E. New Year Permutations

Yeah, we failed to make up a New Year legend for this problem.

A permutation of length n is an array of n integers such that every integer from 1 to n appears in it exactly once.

An element y of permutation p is reachable from element x if x = y, or p_x = y, or p_{p_x} = y, and so on.

The decomposition of a permutation p is defined as follows: firstly, we have a permutation p, all elements of which are not marked, and an empty list l. Then we do the following: while there is at least one not marked element in p, we find the leftmost such element, list all elements that are reachable from it in the order they appear in p, mark all of these elements, then cyclically shift the list of those elements so that the maximum appears at the first position, and add this list as an element of l. After all elements are marked, l is the result of this decomposition.

For example, if we want to build a decomposition of p = [5, 4, 2, 3, 1, 7, 8, 6], we do the following:

  1. initially p = [5, 4, 2, 3, 1, 7, 8, 6] (bold elements are marked), l = [];
  2. the leftmost unmarked element is 5; 5 and 1 are reachable from it, so the list we want to shift is [5, 1]; there is no need to shift it, since maximum is already the first element;
  3. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1]];
  4. the leftmost unmarked element is 4, the list of reachable elements is [4, 2, 3]; the maximum is already the first element, so there's no need to shift it;
  5. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1], [4, 2, 3]];
  6. the leftmost unmarked element is 7, the list of reachable elements is [7, 8, 6]; we have to shift it, so it becomes [8, 6, 7];
  7. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1], [4, 2, 3], [8, 6, 7]];
  8. all elements are marked, so [[5, 1], [4, 2, 3], [8, 6, 7]] is the result.

The New Year transformation of a permutation is defined as follows: we build the decomposition of this permutation; then we sort all lists in decomposition in ascending order of the first elements (we don't swap the elements in these lists, only the lists themselves); then we concatenate the lists into one list which becomes a new permutation. For example, the New Year transformation of p = [5, 4, 2, 3, 1, 7, 8, 6] is built as follows:

  1. the decomposition is [[5, 1], [4, 2, 3], [8, 6, 7]];
  2. after sorting the decomposition, it becomes [[4, 2, 3], [5, 1], [8, 6, 7]];
  3. [4, 2, 3, 5, 1, 8, 6, 7] is the result of the transformation.

We call a permutation good if the result of its transformation is the same as the permutation itself. For example, [4, 3, 1, 2, 8, 5, 6, 7] is a good permutation; and [5, 4, 2, 3, 1, 7, 8, 6] is bad, since the result of transformation is [4, 2, 3, 5, 1, 8, 6, 7].

Your task is the following: given n and k, find the k-th (lexicographically) good permutation of length n.

Input

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

Then the test cases follow. Each test case is represented by one line containing two integers n and k (1 ≤ n ≤ 50, 1 ≤ k ≤ 10^{18}).

Output

For each test case, print the answer to it as follows: if the number of good permutations of length n is less than k, print one integer -1; otherwise, print the k-th good permutation on n elements (in lexicographical order).

Example

Input

5
3 3
5 15
4 13
6 8
4 2

Output

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

```python
# 1279E - New Year Permutations

# Idea:
# dp(i) --> # of good permutations of [i,n]
# cycles(m) --> # of blocks of len m ( == (m-2)! as first element is fixed)
# It is easy to test for impossibility ie.  k > dp(1)
# Another subproblem: how to compute jth smallest cycle
# getGoodPerm(n,k) uses both getCycle(b, (k/dp[n-b])) and getGoodPerm(n-b, k%dp[n-b])

# TIME LIMIT EXCEEDED

import math
from decimal import *

getcontext().prec = 50

# try to do in O(n)

# simple implementation of the union find
class DSU:
    def __init__(self, n):
        self.hash = {}
        for i in range(1, n+1):
            self.hash[i] = [i]

    def union(self, i, j):
        lst1 = self.hash[i]
        lst2 = self.hash[j]
        lst1.extend(lst2)
        for element in lst2:
            self.hash[element] = lst1

    def same_set(self, i, j):
        return j in self.hash[i]

def getKthPerm(lst, k, offset):
    if len(lst)-1 == offset:
        return True
    elif len(lst) <= offset:  # incorrect params
        return False
    else:
        n = len(lst) - offset
        #print("n,k,offset == %d, %d, %d" % (n, k, offset))
        index = (math.ceil(k/(math.factorial(n-1)))-1) + offset
        #print("index == %d" % index)
        if index >= len(lst):  # to large k
            return False

        # move element at index up front
        if index > offset:
            temp = lst[index]
            lst.pop(index)
            lst.insert(offset, temp)

        while k-math.factorial(n-1) > 0:
            k -= math.factorial(n-1)

        return getKthPerm(lst, k, offset+1)

def getKthCycle(n, k, fact):
    lst = [i-1 for i in range(n+1)]
    # num of ends that still dont have incoming link
    num_open = n

    dsu = DSU(n)
    dsu.union(1, n)
    lst[1] = n
    num_open -= 1

    pos = 2
    while pos < n:
        i = pos
        while i <= n:
            if dsu.same_set(pos, lst[i]):
                pass
            else:
                if k <= fact[num_open-2]:
                    break
                else:
                    k -= fact[num_open-2]
            i += 1

        if i == n+1:  # k is too large
            return None
        else:
            num_open -= 1

            dsu.union(pos, lst[i])

            # move the element at pos i to "pos"
            # while keeping the sorted-ness of lst
            temp = lst[i]
            j = i
            while j > pos:
                lst[j] = lst[j-1]
                j -= 1
            lst[pos] = temp

        pos += 1
    return lst[1:]

# number of cycles with n elements
def cycles(n, fact):
    if n <= 1:
        return 1
    else:
        if n-2 in fact:
            return fact[n-2]
        else:
            return math.factorial(n-2)

# number of good permutations of [i,n]
def dp(i, n, table, fact):
    if i > n:
        return 0
    elif i == n:
        return 1
    else:
        if i in table:
            return table[i]
        else:
            val = 0
            for j in range(i, n+1):
                val += dp(j+1, n, table, fact)*cycles(j-i+1, fact)
            table[i] = val
            return val

def Max(i, table, fact):
    if i in table:
        return table[i]
    else:
        if i <= 1:
            table[i] = 1
            return 1
        else:
            val = 0
            for j in range(1, i+1):
                val += Max(i-j, table, fact)*cycles(j, fact)
            table[i] = val
            return val

def getKthGoodPermutation(n, k, Max, fact):
    if Max[n] < k:  # k is too large
        return None
    if n == 1:
        if k == 1:
            return [1]
        else:
            return None

    block_len = 1
    while k - cycles(block_len, fact)*Max[n-block_len] > 0:
        k -= cycles(block_len, fact)*Max[n-block_len]
        block_len += 1

    k_block = math.ceil(Decimal(k)/Decimal(Max[n-block_len]))
    k_rem = k - (k_block - 1)*Max[n-block_len]

    new_lst = getKthCycle(block_len, k_block, fact)
    if n-block_len > 0:
        rem_lst = getKthGoodPermutation(n-block_len, k_rem, Max, fact)
        for i in range(len(rem_lst)):
            rem_lst[i] += block_len
        new_lst.extend(rem_lst)
    return new_lst

def compute_fact(n, table):
    table[0] = 1
    table[1] = 1
    x = 2
    while x <= n:
        table[x] = x*table[x-1]
        x += 1
    return

if __name__ == '__main__':
    T = int(input())
    N, K = [], []
    for _ in range(T):
        inp = input().rstrip().split(" ")
        n, k = int(inp[0]), int(inp[1])
        N.append(n)
        K.append(k)

    # prepare tables
    max_n = max(N) + 5
    fact = {}
    compute_fact(max_n, fact)

    dp_table = {}
    a = 1
    while a <= max_n:
        Max(a, dp_table, fact)
        a += 1

    j = 0
    while j < len(N):
        lst = getKthGoodPermutation(N[j], K[j], dp_table, fact)
        if lst != None:
            for i in range(len(lst)):
                lst[i] = str(lst[i])
            print(" ".join(lst))
        else:
            print("-1")
        j += 1

```


129_C. Statues

In this task Anna and Maria play a game with a very unpleasant rival. Anna and Maria are in the opposite squares of a chessboard (8 × 8): Anna is in the upper right corner, and Maria is in the lower left one. Apart from them, the board has several statues. Each statue occupies exactly one square. A square that contains a statue cannot have anything or anyone — neither any other statues, nor Anna, nor Maria.

Anna is present on the board as a figurant (she stands still and never moves), and Maria has been actively involved in the game. Her goal is — to come to Anna's square. Maria and statues move in turn, Maria moves first. During one move Maria can go to any adjacent on the side or diagonal cell in which there is no statue, or she can stay in the cell where she is. The statues during their move must go one square down simultaneously, and those statues that were in the bottom row fall from the board and are no longer appeared.

At that moment, when one of the statues is in the cell in which the Maria is, the statues are declared winners. At the moment when Maria comes into the cell where Anna has been waiting, Maria is declared the winner.

Obviously, nothing depends on the statues, so it all depends on Maria. Determine who will win, if Maria does not make a strategic error.

Input

You are given the 8 strings whose length equals 8, describing the initial position on the board. The first line represents the top row of the board, the next one — for the second from the top, and so on, the last line represents the bottom row. Each character string matches a single cell board in the appropriate row, and the characters are in the same manner as that of the corresponding cell. If the cell is empty, the corresponding character is ".". If a cell has Maria, then it is represented by character "M". If a cell has Anna, it is represented by the character "A". If a cell has a statue, then the cell is represented by character "S".

It is guaranteed that the last character of the first row is always "A", the first character of the last line is always "M". The remaining characters are "." or "S".

Output

If Maria wins, print string "WIN". If the statues win, print string "LOSE".

Examples

Input

.......A
........
........
........
........
........
........
M.......

Output

WIN

Input

.......A
........
........
........
........
........
SS......
M.......

Output

LOSE

Input

.......A
........
........
........
........
.S......
S.......
MS......

Output

LOSE

```python
from sys import stdin
from collections import *
from copy import deepcopy

def valid(i, j):
    n, m = [8] * 2
    return i > -1 and i < n and j > -1 and j < m

def str_inp(n):
    return list(reversed(list((list(stdin.readline()[:-1]) for x in range(n)))))

def check(x, y, step):
    if step + 1 < 8 and all[step + 1][x][y] == 'S' or step < 8 and all[step][x][y] == 'S':
        # print(all[step][x][y], x, y)
        return False

    return True

def print_maze(x):
    for i in range(8):
        print(*all[x][i], sep='')
    print(end='\n')

def dfs(x, y):
    stack, visit, step = [[x, y, -1]], defaultdict(int), -1

    while (stack):
        x, y, step = stack.pop()
        step += 1

        if chess[x][y] == 'A':
            exit(print('WIN'))

        st = 0

        for i in range(9):
            nx, ny = [x + dx[i], y + dy[i]]
            if i == 0:
                if step >= 8:
                    continue
                else:
                    visit[nx, ny] = 0

            if valid(nx, ny) and check(nx, ny, step) and not visit[nx, ny]:
                stack.append([nx, ny, step])
                # print(nx, ny, step, check(nx, ny, step))
                # print_maze(min(step, 7))
                visit[nx, ny] = 1
            else:
                st += 1
        # print(stack, step)
        if st == 9:
            step -= 1
            visit[x, y] = 0

dx, dy, chess = [0, -1, 0, 1, 0, 1, -1, 1, -1], [0, 0, 1, 0, -1, 1, -1, -1, 1], str_inp(8)
all, ini = [chess], [['.' for i in range(8)] for j in range(8)]

for k in range(1, 9):
    tem = deepcopy(ini)
    for i in range(8):
        for j in range(8):
            if chess[i][j] == 'S' and i - k > -1:
                tem[i - k][j] = 'S'
    all.append(tem)

dfs(0, 0)
print('LOSE')

```


1341_E. Nastya and Unexpected Guest

If the girl doesn't go to Denis, then Denis will go to the girl. Using this rule, the young man left home, bought flowers and went to Nastya.

On the way from Denis's house to the girl's house is a road of n lines. This road can't be always crossed in one green light. Foreseeing this, the good mayor decided to place safety islands in some parts of the road. Each safety island is located after a line, as well as at the beginning and at the end of the road. Pedestrians can relax on them, gain strength and wait for a green light.

Denis came to the edge of the road exactly at the moment when the green light turned on. The boy knows that the traffic light first lights up g seconds green, and then r seconds red, then again g seconds green and so on.

Formally, the road can be represented as a segment [0, n]. Initially, Denis is at point 0. His task is to get to point n in the shortest possible time.

He knows many different integers d_1, d_2, …, d_m, where 0 ≤ d_i ≤ n — are the coordinates of points, in which the safety islands are located. Only at one of these points, the boy can be at a time when the red light is on.

Unfortunately, Denis isn't always able to control himself because of the excitement, so some restrictions are imposed:

  * He must always move while the green light is on because it's difficult to stand when so beautiful girl is waiting for you. Denis can change his position by ± 1 in 1 second. While doing so, he must always stay inside the segment [0, n].
  * He can change his direction only on the safety islands (because it is safe). This means that if in the previous second the boy changed his position by +1 and he walked on a safety island, then he can change his position by ± 1. Otherwise, he can change his position only by +1. Similarly, if in the previous second he changed his position by -1, on a safety island he can change position by ± 1, and at any other point by -1.
  * At the moment when the red light is on, the boy must be on one of the safety islands. He can continue moving in any direction when the green light is on.

Denis has crossed the road as soon as his coordinate becomes equal to n.

This task was not so simple, because it's possible that it is impossible to cross the road. Since Denis has all thoughts about his love, he couldn't solve this problem and asked us to help him. Find the minimal possible time for which he can cross the road according to these rules, or find that it is impossible to do.

Input

The first line contains two integers n and m (1 ≤ n ≤ 10^6, 2 ≤ m ≤ min(n + 1, 10^4)) — road width and the number of safety islands.

The second line contains m distinct integers d_1, d_2, …, d_m (0 ≤ d_i ≤ n) — the points where the safety islands are located. It is guaranteed that there are 0 and n among them.

The third line contains two integers g, r (1 ≤ g, r ≤ 1000) — the time that the green light stays on and the time that the red light stays on.

Output

Output a single integer — the minimum time for which Denis can cross the road with obeying all the rules.

If it is impossible to cross the road output -1.

Examples

Input

15 5
0 3 7 14 15
11 11

Output

45

Input

13 4
0 3 7 13
9 9

Output

-1

Note

In the first test, the optimal route is:

  * for the first green light, go to 7 and return to 3. In this case, we will change the direction of movement at the point 7, which is allowed, since there is a safety island at this point. In the end, we will be at the point of 3, where there is also a safety island. The next 11 seconds we have to wait for the red light.
  * for the second green light reaches 14. Wait for the red light again.
  * for 1 second go to 15. As a result, Denis is at the end of the road.

In total, 45 seconds are obtained.

In the second test, it is impossible to cross the road according to all the rules.

```python
import sys
input = sys.stdin.readline
from collections import deque
from typing import List

############ ---- Input Functions ---- ############
def inp():
    return(int(input()))
def inlt():
    return(list(map(int,input().split())))
def insr():
    s = input()
    return(list(s[:len(s) - 1]))
def invr():
    return(map(int,input().split()))

def compute(n, m, g, r, A: List[int]):
    A.sort()

    WHITE = -1
    GREY = -2

    states = [[WHITE] * (g+1) for _ in range(m)]
    states[0][g] = 0
    states[0][0] = 0

    q = deque([(0, g)])

    def process_neib(ineib, gneib):
        if states[ineib][gneib] != WHITE:
            #print(f"Skipped as grey")
            return

        if ineib == m-1:
            #no need to wait there
            states[ineib][gneib] = states[index][g_left]
            #print(f"Final state dist is {states[ineib][gneib]}")

        elif gneib == 0:
            states[ineib][gneib] = states[index][g_left] + 1
            states[ineib][g] = states[ineib][gneib]
            gneib = g
            q.append((ineib, gneib))
            #print(f"appended right with distance {states[ineib][0]}")
        else:
            states[ineib][gneib] = states[index][g_left]
            q.appendleft((ineib, gneib))

    while q:
        # sit for this is known
        #print(f"Queue is {[(A[i], t) for i,t in q]}")
        index, g_left = q.popleft()
        #print(f"Popped {A[index], g_left}. Dist is {states[index][g_left]}")

        #neib = get_neib(index, g_left, A)
        #print(f"Neighbors are {[(A[i], t) for i, t in neib]}")

        if index > 0:
            # there exists a next one
            delta = A[index] - A[index-1]
            if g_left >= delta:
                process_neib(index-1, g_left-delta)

        if index < m-1:
            delta = A[index+1] - A[index]
            if g_left >= delta:
                process_neib(index+1, g_left-delta)

                #print(f"appended left with distance {states[ineib][gneib]}")

    res = float('inf')
    for g_left in range(g):
        if states[m-1][g_left] >= 0:

            res = min(res, states[m-1][g_left] * (r+g) + g-g_left)

    if res != float('inf'):
        print(res)
    else:
        print('-1')

def from_file(f):
    return f.readline

# with open('52.txt') as f:
#     input = from_file(f)
n, m = invr()
A = inlt()
g,r  = invr()
compute(n, m, g, r, A)

```


1363_E. Tree Shuffling

Ashish has a tree consisting of n nodes numbered 1 to n rooted at node 1. The i-th node in the tree has a cost a_i, and binary digit b_i is written in it. He wants to have binary digit c_i written in the i-th node in the end.

To achieve this, he can perform the following operation any number of times:

  * Select any k nodes from the subtree of any node u, and shuffle the digits in these nodes as he wishes, incurring a cost of k ⋅ a_u. Here, he can choose k ranging from 1 to the size of the subtree of u.

He wants to perform the operations in such a way that every node finally has the digit corresponding to its target.

Help him find the minimum total cost he needs to spend so that after all the operations, every node u has digit c_u written in it, or determine that it is impossible.

Input

First line contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5) denoting the number of nodes in the tree.

i-th line of the next n lines contains 3 space-separated integers a_i, b_i, c_i (1 ≤ a_i ≤ 10^9, 0 ≤ b_i, c_i ≤ 1) — the cost of the i-th node, its initial digit and its goal digit.

Each of the next n - 1 lines contain two integers u, v (1 ≤ u, v ≤ n,   u ≠ v), meaning that there is an edge between nodes u and v in the tree.

Output

Print the minimum total cost to make every node reach its target digit, and -1 if it is impossible.

Examples

Input

5
1 0 1
20 1 0
300 0 1
4000 0 0
50000 1 0
1 2
2 3
2 4
1 5

Output

4

Input

5
10000 0 1
2000 1 0
300 0 1
40 0 0
1 1 0
1 2
2 3
2 4
1 5

Output

24000

Input

2
109 0 1
205 0 1
1 2

Output

-1

Note

The tree corresponding to samples 1 and 2 are:

<image>

In sample 1, we can choose node 1 and k = 4 for a cost of 4 ⋅ 1 = 4 and select nodes {1, 2, 3, 5}, shuffle their digits and get the desired digits in every node.

In sample 2, we can choose node 1 and k = 2 for a cost of 10000 ⋅ 2, select nodes {1, 5} and exchange their digits, and similarly, choose node 2 and k = 2 for a cost of 2000 ⋅ 2, select nodes {2, 3} and exchange their digits to get the desired digits in every node.

In sample 3, it is impossible to get the desired digits, because there is no node with digit 1 initially.

```python
import sys
data = [list(map(int, line.rstrip().split())) for line in sys.stdin.readlines()]

n = data[0][0]
dic = [[] for _ in range(n+1)]
dic[1].append(0)
for u,v in data[n+1:]:
    dic[u].append(v)
    dic[v].append(u)
cost = [0]*(n+1)
cost[1] = 1000000001
father = [0]*(n+1)
now = [1]
leaf = []
gress = [0]*(n+1)
while now:
    node = now.pop()
    gress[node] = len(dic[node])
    if gress[node]==1:
        leaf.append(node)
    c = min(cost[node],data[node][0])
    for child in dic[node]:
        if child!=father[node]:
            father[child]=node
            cost[child] = c
            now.append(child)
res = 0
count = [[0,0] for _ in range(n+1)]
while leaf:
    node = leaf.pop()
    if data[node][1]==0 and data[node][2]==1:
        count[node][0]+=1
    elif data[node][1]==1 and data[node][2]==0:
        count[node][1]+=1
    if data[node][0]<cost[node]:
        t = min(count[node])
        res+=t*data[node][0]*2
        count[node][0]-=t
        count[node][1]-=t
    f = father[node]
    count[f][0]+=count[node][0]
    count[f][1]+=count[node][1]
    gress[f]-=1
    if gress[f]==1:
        leaf.append(f)
if count[0]==[0,0]:
    print(res)
else:
    print(-1)
```


1384_A. Common Prefixes

The length of the longest common prefix of two strings s = s_1 s_2 … s_n and t = t_1 t_2 … t_m is defined as the maximum integer k (0 ≤ k ≤ min(n,m)) such that s_1 s_2 … s_k equals t_1 t_2 … t_k.

Koa the Koala initially has n+1 strings s_1, s_2, ..., s_{n+1}.

For each i (1 ≤ i ≤ n) she calculated a_i — the length of the longest common prefix of s_i and s_{i+1}.

Several days later Koa found these numbers, but she couldn't remember the strings.

So Koa would like to find some strings s_1, s_2, ..., s_{n+1} which would have generated numbers a_1, a_2, ..., a_n. Can you help her?

If there are many answers print any. We can show that answer always exists for the given constraints.

Input

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

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

The second line of each test case contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 50) — the elements of a.

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

Output

For each test case:

Output n+1 lines. In the i-th line print string s_i (1 ≤ |s_i| ≤ 200), consisting of lowercase Latin letters. Length of the longest common prefix of strings s_i and s_{i+1} has to be equal to a_i.

If there are many answers print any. We can show that answer always exists for the given constraints.

Example

Input

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

Output

aeren
ari
arousal
around
ari
monogon
monogamy
monthly
kevinvu
kuroni
kurioni
korone
anton
loves
adhoc
problems

Note

In the 1-st test case one of the possible answers is s = [aeren, ari, arousal, around, ari].

Lengths of longest common prefixes are:

  * Between \color{red}{a}eren and \color{red}{a}ri → 1
  * Between \color{red}{ar}i and \color{red}{ar}ousal → 2
  * Between \color{red}{arou}sal and \color{red}{arou}nd → 4
  * Between \color{red}{ar}ound and \color{red}{ar}i → 2

```python
T = int(input())

def solve():
    N = int(input())
    A = list(map(int,input().split()))

    def next_char(c):
        if c == 'a':
            return 'b'
        return 'a'

    ans = []
    ans.append('a'*101)
    for a in A:
        lst = ans[-1]
        lst = lst[:a] + next_char(lst[a]) + lst[a+1:]
        ans.append(lst)
    for l in ans:
        print(l)
for _ in range(T):
    solve()

```


1405_B. Array Cancellation

You're given an array a of n integers, such that a_1 + a_2 + ⋅⋅⋅ + a_n = 0.

In one operation, you can choose two different indices i and j (1 ≤ i, j ≤ n), decrement a_i by one and increment a_j by one. If i < j this operation is free, otherwise it costs one coin.

How many coins do you have to spend in order to make all elements equal to 0?

Input

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

The first line of each test case contains an integer n (1 ≤ n ≤ 10^5) — the number of elements.

The next line contains n integers a_1, …, a_n (-10^9 ≤ a_i ≤ 10^9). It is given that ∑_{i=1}^n a_i = 0.

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

Output

For each test case, print the minimum number of coins we have to spend in order to make all elements equal to 0.

Example

Input

7
4
-3 5 -3 1
2
1 -1
4
-3 2 -3 4
4
-1 1 1 -1
7
-5 7 -6 -4 17 -13 4
6
-1000000000 -1000000000 -1000000000 1000000000 1000000000 1000000000
1
0

Output

3
0
4
1
8
3000000000
0

Note

Possible strategy for the first test case:

  * Do (i=2, j=3) three times (free), a = [-3, 2, 0, 1].
  * Do (i=2, j=1) two times (pay two coins), a = [-1, 0, 0, 1].
  * Do (i=4, j=1) one time (pay one coin), a = [0, 0, 0, 0].

```python
def main():
    t = int(input())
    for _ in range(t):
        n = int(input())
        alst = list(map(int, input().split()))
        ans = 0
        total = 0
        for a in alst:
            total -= a
            ans = max(ans, total)
        print(ans)

main()
```


1426_D. Non-zero Segments

Kolya got an integer array a_1, a_2, ..., a_n. The array can contain both positive and negative integers, but Kolya doesn't like 0, so the array doesn't contain any zeros.

Kolya doesn't like that the sum of some subsegments of his array can be 0. The subsegment is some consecutive segment of elements of the array.

You have to help Kolya and change his array in such a way that it doesn't contain any subsegments with the sum 0. To reach this goal, you can insert any integers between any pair of adjacent elements of the array (integers can be really any: positive, negative, 0, any by absolute value, even such a huge that they can't be represented in most standard programming languages).

Your task is to find the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0.

Input

The first line of the input contains one integer n (2 ≤ n ≤ 200 000) — the number of elements in Kolya's array.

The second line of the input contains n integers a_1, a_2, ..., a_n (-10^{9} ≤ a_i ≤ 10^{9}, a_i ≠ 0) — the description of Kolya's array.

Output

Print the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0.

Examples

Input

4
1 -5 3 2

Output

1

Input

5
4 -2 3 -9 2

Output

0

Input

9
-1 1 -1 1 -1 1 1 -1 -1

Output

6

Input

8
16 -5 -11 -15 10 5 4 -4

Output

3

Note

Consider the first example. There is only one subsegment with the sum 0. It starts in the second element and ends in the fourth element. It's enough to insert one element so the array doesn't contain any subsegments with the sum equal to zero. For example, it is possible to insert the integer 1 between second and third elements of the array.

There are no subsegments having sum 0 in the second example so you don't need to do anything.

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

def main():
    pass

# 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()

n = int(input())
arr = {0}
s = ans = 0
for i in (map(int, input().split())):
    s += i
    if s in arr:
        arr = {0, i}
        ans += 1
        s = i
    else:
        arr.add(s)
print(ans)

```


144_C. Anagram Search

A string t is called an anagram of the string s, if it is possible to rearrange letters in t so that it is identical to the string s. For example, the string "aab" is an anagram of the string "aba" and the string "aaa" is not.

The string t is called a substring of the string s if it can be read starting from some position in the string s. For example, the string "aba" has six substrings: "a", "b", "a", "ab", "ba", "aba".

You are given a string s, consisting of lowercase Latin letters and characters "?". You are also given a string p, consisting of lowercase Latin letters only. Let's assume that a string is good if you can obtain an anagram of the string p from it, replacing the "?" characters by Latin letters. Each "?" can be replaced by exactly one character of the Latin alphabet. For example, if the string p = «aba», then the string "a??" is good, and the string «?bc» is not.

Your task is to find the number of good substrings of the string s (identical substrings must be counted in the answer several times).

Input

The first line is non-empty string s, consisting of no more than 105 lowercase Latin letters and characters "?". The second line is non-empty string p, consisting of no more than 105 lowercase Latin letters. Please note that the length of the string p can exceed the length of the string s.

Output

Print the single number representing the number of good substrings of string s.

Two substrings are considered different in their positions of occurrence are different. Thus, if some string occurs several times, then it should be counted the same number of times.

Examples

Input

bb??x???
aab

Output

2

Input

ab?c
acb

Output

2

Note

Consider the first sample test. Here the string s has two good substrings: "b??" (after we replace the question marks we get "baa"), "???" (after we replace the question marks we get "baa").

Let's consider the second sample test. Here the string s has two good substrings: "ab?" ("?" can be replaced by "c"), "b?c" ("?" can be replaced by "a").

```python
s = input()
p = input()
fit = 0
cnts = {}
cntp = {}
for c in s:
    cnts[c] = cntp[c] = 0
for c in p:
    cnts[c] = cntp[c] = 0
for c in p:
    cntp[c] += 1

def extend(c):
    if c == '?':
        return
    global fit
    if cnts[c] == cntp[c]:
        fit += 1
    cnts[c] += 1

def remove(c):
    if c == '?':
        return
    global fit
    if cnts[c] == cntp[c] + 1:
        fit -= 1
    cnts[c] -= 1

if len(s) < len(p):
    print(0)
    exit(0)

ans = 0
for i in range(0, len(p)):
    extend(s[i])
if fit == 0:
    ans = 1
for i in range(0, len(s) - len(p)):
    remove(s[i])
    extend(s[i + len(p)])
    if fit == 0:
        ans += 1
print(ans)

```


1473_C. No More Inversions

You have a sequence a with n elements 1, 2, 3, ..., k - 1, k, k - 1, k - 2, ..., k - (n - k) (k ≤ n < 2k).

Let's call as inversion in a a pair of indices i < j such that a[i] > a[j].

Suppose, you have some permutation p of size k and you build a sequence b of size n in the following manner: b[i] = p[a[i]].

Your goal is to find such permutation p that the total number of inversions in b doesn't exceed the total number of inversions in a, and b is lexicographically maximum.

Small reminder: the sequence of k integers is called a permutation if it contains all integers from 1 to k exactly once.

Another small reminder: a sequence s is lexicographically smaller than another sequence t, if either s is a prefix of t, or for the first i such that s_i ≠ t_i, s_i < t_i holds (in the first position that these sequences are different, s has smaller number than t).

Input

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

The first and only line of each test case contains two integers n and k (k ≤ n < 2k; 1 ≤ k ≤ 10^5) — the length of the sequence a and its maximum.

It's guaranteed that the total sum of k over test cases doesn't exceed 10^5.

Output

For each test case, print k integers — the permutation p which maximizes b lexicographically without increasing the total number of inversions.

It can be proven that p exists and is unique.

Example

Input

4
1 1
2 2
3 2
4 3

Output

1
1 2
2 1
1 3 2

Note

In the first test case, the sequence a = [1], there is only one permutation p = [1].

In the second test case, the sequence a = [1, 2]. There is no inversion in a, so there is only one permutation p = [1, 2] which doesn't increase the number of inversions.

In the third test case, a = [1, 2, 1] and has 1 inversion. If we use p = [2, 1], then b = [p[a[1]], p[a[2]], p[a[3]]] = [2, 1, 2] and also has 1 inversion.

In the fourth test case, a = [1, 2, 3, 2], and since p = [1, 3, 2] then b = [1, 3, 2, 3]. Both a and b have 1 inversion and b is the lexicographically maximum.

```python
from collections import Counter
import string
import math
import sys
# sys.setrecursionlimit(10**6)
from fractions import Fraction
def array_int():
    return [int(i) for i in sys.stdin.readline().split()]
def vary(arrber_of_variables):
    if arrber_of_variables==1:
        return int(sys.stdin.readline())
    if arrber_of_variables>=2:
        return map(int,sys.stdin.readline().split())
def makedict(var):
    return dict(Counter(var))
testcases=vary(1)
for _ in range(testcases):
    n,k=vary(2)
    num=[i for i in range(1,k+1)]
    if n==k:
        print(*num)
    else:
        l = [i for i in range(1,2*k-n)]
        for i in range(n-k+1):
            l.append(k-i)
        print(*l)
```


1499_E. Chaotic Merge

You are given two strings x and y, both consist only of lowercase Latin letters. Let |s| be the length of string s.

Let's call a sequence a a merging sequence if it consists of exactly |x| zeros and exactly |y| ones in some order.

A merge z is produced from a sequence a by the following rules:

  * if a_i=0, then remove a letter from the beginning of x and append it to the end of z;
  * if a_i=1, then remove a letter from the beginning of y and append it to the end of z.

Two merging sequences a and b are different if there is some position i such that a_i ≠ b_i.

Let's call a string z chaotic if for all i from 2 to |z| z_{i-1} ≠ z_i.

Let s[l,r] for some 1 ≤ l ≤ r ≤ |s| be a substring of consecutive letters of s, starting from position l and ending at position r inclusive.

Let f(l_1, r_1, l_2, r_2) be the number of different merging sequences of x[l_1,r_1] and y[l_2,r_2] that produce chaotic merges. Note that only non-empty substrings of x and y are considered.

Calculate ∑ _{1 ≤ l_1 ≤ r_1 ≤ |x| \\\ 1 ≤ l_2 ≤ r_2 ≤ |y|} f(l_1, r_1, l_2, r_2). Output the answer modulo 998 244 353.

Input

The first line contains a string x (1 ≤ |x| ≤ 1000).

The second line contains a string y (1 ≤ |y| ≤ 1000).

Both strings consist only of lowercase Latin letters.

Output

Print a single integer — the sum of f(l_1, r_1, l_2, r_2) over 1 ≤ l_1 ≤ r_1 ≤ |x| and 1 ≤ l_2 ≤ r_2 ≤ |y| modulo 998 244 353.

Examples

Input

aaa
bb

Output

24

Input

code
forces

Output

1574

Input

aaaaa
aaa

Output

0

Input

justamassivetesttocheck
howwellyouhandlemodulooperations

Output

667387032

Note

In the first example there are:

  * 6 pairs of substrings "a" and "b", each with valid merging sequences "01" and "10";
  * 3 pairs of substrings "a" and "bb", each with a valid merging sequence "101";
  * 4 pairs of substrings "aa" and "b", each with a valid merging sequence "010";
  * 2 pairs of substrings "aa" and "bb", each with valid merging sequences "0101" and "1010";
  * 2 pairs of substrings "aaa" and "b", each with no valid merging sequences;
  * 1 pair of substrings "aaa" and "bb" with a valid merging sequence "01010";

Thus, the answer is 6 ⋅ 2 + 3 ⋅ 1 + 4 ⋅ 1 + 2 ⋅ 2 + 2 ⋅ 0 + 1 ⋅ 1 = 24.

```python

from bisect import *
from collections import *
from math import gcd,ceil,sqrt,floor,inf
from heapq import *
from itertools import *
from operator import add,mul,sub,xor,truediv,floordiv
from functools import *

#------------------------------------------------------------------------
import os
import sys

from io import BytesIO, IOBase
# 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")

#------------------------------------------------------------------------
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def A(n):return [0]*n
def AI(n,x): return [x]*n
def A2(n,m): return [[0]*m for i in range(n)]
def G(n): return [[] for i in range(n)]
def GP(it): return [[ch,len(list(g))] for ch,g in groupby(it)]
#------------------------------------------------------------------------

from types import GeneratorType

def bootstrap(f, stack=[]):
    def wrappedfunc(*args, **kwargs):
        if stack:
            return f(*args, **kwargs)
        else:
            to = f(*args, **kwargs)
            while True:
                if type(to) is GeneratorType:
                    stack.append(to)
                    to = next(to)
                else:
                    stack.pop()
                    if not stack:
                        break
                    to = stack[-1].send(to)
            return to

    return wrappedfunc

mod=10**9+7
farr=[1]
ifa=[]

def fact(x,mod=0):
    if mod:
        while x>=len(farr):
            farr.append(farr[-1]*len(farr)%mod)
    else:
        while x>=len(farr):
            farr.append(farr[-1]*len(farr))
    return farr[x]

def ifact(x,mod):
    global ifa
    fact(x,mod)
    ifa.append(pow(farr[-1],mod-2,mod))
    for i in range(x,0,-1):
        ifa.append(ifa[-1]*i%mod)
    ifa.reverse()

def per(i,j,mod=0):
    if i<j: return 0
    if not mod:
        return fact(i)//fact(i-j)
    return farr[i]*ifa[i-j]%mod

def com(i,j,mod=0):
    if i<j: return 0
    if not mod:
        return per(i,j)//fact(j)
    return per(i,j,mod)*ifa[j]%mod

def catalan(n):
    return com(2*n,n)//(n+1)

def isprime(n):
    for i in range(2,int(n**0.5)+1):
        if n%i==0:
            return False
    return True

def floorsum(a,b,c,n):#sum((a*i+b)//c for i in range(n+1))
    if a==0:return b//c*(n+1)
    if a>=c or b>=c: return floorsum(a%c,b%c,c,n)+b//c*(n+1)+a//c*n*(n+1)//2
    m=(a*n+b)//c
    return n*m-floorsum(c,c-b-1,a,m-1)

def inverse(a,m):
    a%=m
    if a<=1: return a
    return ((1-inverse(m,a)*m)//a)%m

def lowbit(n):
    return n&-n

class BIT:
    def __init__(self,arr):
        self.arr=arr
        self.n=len(arr)-1

    def update(self,x,v):
        while x<=self.n:
            self.arr[x]+=v
            x+=x&-x

    def query(self,x):
        ans=0
        while x:
            ans+=self.arr[x]
            x&=x-1
        return ans

class ST:
    def __init__(self,arr):#n!=0
        n=len(arr)
        mx=n.bit_length()#取不到
        self.st=[[0]*mx for i in range(n)]
        for i in range(n):
            self.st[i][0]=arr[i]
        for j in range(1,mx):
            for i in range(n-(1<<j)+1):
                self.st[i][j]=max(self.st[i][j-1],self.st[i+(1<<j-1)][j-1])
    def query(self,l,r):
        if l>r:return -inf
        s=(r+1-l).bit_length()-1
        return max(self.st[l][s],self.st[r-(1<<s)+1][s])
'''
class DSU:#容量+路径压缩
    def __init__(self,n):
        self.c=[-1]*n

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

    def find(self,x):
        if self.c[x]<0:
            return x
        self.c[x]=self.find(self.c[x])
        return self.c[x]

    def union(self,u,v):
        u,v=self.find(u),self.find(v)
        if u==v:
            return False
        if self.c[u]>self.c[v]:
            u,v=v,u
        self.c[u]+=self.c[v]
        self.c[v]=u
        return True

    def size(self,x): return -self.c[self.find(x)]'''

class UFS:#秩+路径
    def __init__(self,n):
        self.parent=[i for i in range(n)]
        self.ranks=[0]*n

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

    def union(self,u,v):
        pu,pv=self.find(u),self.find(v)
        if pu==pv:
            return False
        if self.ranks[pu]>=self.ranks[pv]:
            self.parent[pv]=pu
            if self.ranks[pv]==self.ranks[pu]:
                self.ranks[pu]+=1
        else:
            self.parent[pu]=pv

def Prime(n):
    c=0
    prime=[]
    flag=[0]*(n+1)
    for i in range(2,n+1):
        if not flag[i]:
            prime.append(i)
            c+=1
        for j in range(c):
            if i*prime[j]>n: break
            flag[i*prime[j]]=prime[j]
            if i%prime[j]==0: break
    return flag

def dij(s,graph):
    d={}
    d[s]=0
    heap=[(0,s)]
    seen=set()
    while heap:
        dis,u=heappop(heap)
        if u in seen:
            continue
        seen.add(u)
        for v,w in graph[u]:
            if v not in d or d[v]>d[u]+w:
                d[v]=d[u]+w
                heappush(heap,(d[v],v))
    return d

def bell(s,g):#bellman-Ford
    dis=AI(n,inf)
    dis[s]=0
    for i in range(n-1):
        for u,v,w in edge:
            if dis[v]>dis[u]+w:
                dis[v]=dis[u]+w
    change=A(n)
    for i in range(n):
        for u,v,w in edge:
            if dis[v]>dis[u]+w:
                dis[v]=dis[u]+w
                change[v]=1
    return dis

def lcm(a,b): return a*b//gcd(a,b)
def lis(nums):
    res=[]
    for k in nums:
        i=bisect.bisect_left(res,k)
        if i==len(res):
            res.append(k)
        else:
            res[i]=k
    return len(res)

def RP(nums):#逆序对
    n = len(nums)
    s=set(nums)
    d={}
    for i,k in enumerate(sorted(s),1):
        d[k]=i
    bi=BIT([0]*(len(s)+1))
    ans=0
    for i in range(n-1,-1,-1):
        ans+=bi.query(d[nums[i]]-1)
        bi.update(d[nums[i]],1)
    return ans

class DLN:
    def __init__(self,val):
        self.val=val
        self.pre=None
        self.next=None

def nb(i,j,n,m):
    for ni,nj in [[i+1,j],[i-1,j],[i,j-1],[i,j+1]]:
        if 0<=ni<n and 0<=nj<m:
            yield ni,nj

def topo(n):
    q=deque()
    res=[]
    for i in range(1,n+1):
        if ind[i]==0:
            q.append(i)
            res.append(i)
    while q:
        u=q.popleft()
        for v in g[u]:
            ind[v]-=1
            if ind[v]==0:
                q.append(v)
                res.append(v)
    return res

@bootstrap
def gdfs(r,p):
    if len(g[r])==1 and p!=-1:
        yield None
    for ch in g[r]:
        if ch!=p:
            yield gdfs(ch,r)
    yield None

t=1
for i in range(t):
    x=input()
    x=list(x)
    y=input()
    y=list(y)
    x=list(map(lambda ch: ord(ch)-97,x))
    y=list(map(lambda ch: ord(ch)-97,y))
    ans=0
    mod=998244353
    m,n=len(x),len(y)
    v1=[1]*(m+1)
    v2=[1]*(n+1)
    for i in range(m-2,-1,-1):
        if x[i]!=x[i+1]:
            v1[i]+=v1[i+1]
    for i in range(n-2,-1,-1):
        if y[i]!=y[i+1]:
            v2[i]+=v2[i+1]
    #print(x,y,v1,v2)
    dp=[[[0]*27 for j in range(n+1)] for i in range(m+1)]
    for i in range(m-1,-1,-1):
        for j in range(n-1,-1,-1):
            for k in range(27):
                if x[i]==k:
                    if y[j]!=k:
                        dp[i][j][k]=(dp[i][j+1][y[j]]+v1[i])%mod
                elif y[j]==k:
                    dp[i][j][k]=(dp[i+1][j][x[i]]+v2[j])%mod
                else:
                    #print(i,j,k)
                    dp[i][j][k]=(dp[i+1][j][x[i]]+dp[i][j+1][y[j]]+(x[i]!=y[j])*(v2[j]+v1[i]))%mod
    for i in range(m):
        for j in range(n):
            ans=(ans+dp[i][j][26])%mod
    print(ans)

'''
sys.setrecursionlimit(200000)
import threading
threading.stack_size(10**8)
t=threading.Thr
ead(target=main)
t.start()
t.join()
'''

'''
sys.setrecursionlimit(200000)
import threading
threading.stack_size(10**8)
t=threading.Thread(target=main)
t.start()
t.join()
'''

```


1521_C. Nastia and a Hidden Permutation

This is an interactive problem!

Nastia has a hidden permutation p of length n consisting of integers from 1 to n. You, for some reason, want to figure out the permutation. To do that, you can give her an integer t (1 ≤ t ≤ 2), two different indices i and j (1 ≤ i, j ≤ n, i ≠ j), and an integer x (1 ≤ x ≤ n - 1).

Depending on t, she will answer:

  * t = 1: max{(min{(x, p_i)}, min{(x + 1, p_j)})};
  * t = 2: min{(max{(x, p_i)}, max{(x + 1, p_j)})}.

You can ask Nastia at most ⌊ \frac {3 ⋅ n} { 2} ⌋ + 30 times. It is guaranteed that she will not change her permutation depending on your queries. Can you guess the permutation?

Input

The input consists of several test cases. In the beginning, you receive the integer T (1 ≤ T ≤ 10 000) — the number of test cases.

At the beginning of each test case, you receive an integer n (3 ≤ n ≤ 10^4) — the length of the permutation p.

It's guaranteed that the permutation is fixed beforehand and that the sum of n in one test doesn't exceed 2 ⋅ 10^4.

Interaction

To ask a question, print "? t i j x" (t = 1 or t = 2, 1 ≤ i, j ≤ n, i ≠ j, 1 ≤ x ≤ n - 1) Then, you should read the answer.

If we answer with −1 instead of a valid answer, that means you exceeded the number of queries or made an invalid query. Exit immediately after receiving −1 and you will see the Wrong Answer verdict. Otherwise, you can get an arbitrary verdict because your solution will continue to read from a closed stream.

To print the answer, print "! p_1 p_2 … p_{n} (without quotes). Note that answering doesn't count as one of the ⌊ \frac {3 ⋅ n} {2} ⌋ + 30 queries.

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

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

Hacks

To hack the solution, use the following test format.

The first line should contain a single integer T (1 ≤ T ≤ 10 000) — the number of test cases.

For each test case in the first line print a single integer n (3 ≤ n ≤ 10^4) — the length of the hidden permutation p.

In the second line print n space-separated integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n), where p is permutation.

Note that the sum of n over all test cases should not exceed 2 ⋅ 10^4.

Example

Input

2
4

3

2

5

3

Output

? 2 4 1 3

? 1 2 4 2

! 3 1 4 2

? 2 3 4 2

! 2 5 3 4 1

Note

Consider the first test case.

The hidden permutation is [3, 1, 4, 2].

We print: "? 2 4 1 3" and get back min{(max{(3, p_4}), max{(4, p_1)})} = 3.

We print: "? 1 2 4 2" and get back max{(min{(2, p_2)}, min{(3, p_4)})} = 2.

Consider the second test case.

The hidden permutation is [2, 5, 3, 4, 1].

We print: "? 2 3 4 2" and get back min{(max{(2, p_3}), max{(3, p_4)})} = 3.

```python
import math,sys
## from itertools import permutations, combinations;import heapq,random;
from collections import defaultdict,deque
import bisect as bi
def yes():print('YES')
def no():print('NO')
# sys.stdin=open('input.txt','r');sys.stdout=open('output.txt','w');
def I():return (int(sys.stdin.readline()))
def In():return(map(int,sys.stdin.readline().split()))
def Sn():return sys.stdin.readline().strip()
#sys.setrecursionlimit(1500)
def dict(a):
    d={}
    for x in a:
        if d.get(x,-1)!=-1:
            d[x]+=1
        else:
            d[x]=1
    return d
def find_gt(a, x):
    'Find leftmost value greater than x'
    i = bi.bisect_left(a, x)
    if i != len(a):
        return i
    else:
        return -1
def query(type,st,end,x):
    print('?',type,st,end,x,flush=True)

def main():
    try:
        global topi,ans
        n=I()
        d={}
        st=-1
        ans=[0]*(n+1)
        topi=n-1
        end =  n-1 if n&1==1 else n

        for i in range(0,end,2):
            query(1,i+1,i+2,topi)
            q=I()
            if q==topi:
                query(1,i+2,i+1,topi)
                x=I()
                if x==n:
                    st=i+1
                    break
            elif q==n:
                st=i+2
                break
        if st==-1:
            st=n
        ans[st]=n
        for i in range(st-1,0,-1):
            query(2,i,st,1)
            q=I()
            ans[i]=q
        for i in range(st+1,n+1):
            query(2,i,st,1)
            q=I()
            ans[i]=q
        print('!',*ans[1:],flush=True)
    except:
        pass

M = 998244353
P = 1000000007

if __name__ == '__main__':
    for _ in range(I()):main()
    # for _ in range(1):main()
#End#

#        ******************* All The Best *******************   #
```


1550_C. Manhattan Subarrays

Suppose you have two points p = (x_p, y_p) and q = (x_q, y_q). Let's denote the Manhattan distance between them as d(p, q) = |x_p - x_q| + |y_p - y_q|.

Let's say that three points p, q, r form a bad triple if d(p, r) = d(p, q) + d(q, r).

Let's say that an array b_1, b_2, ..., b_m is good if it is impossible to choose three distinct indices i, j, k such that the points (b_i, i), (b_j, j) and (b_k, k) form a bad triple.

You are given an array a_1, a_2, ..., a_n. Calculate the number of good subarrays of a. A subarray of the array a is the array a_l, a_{l + 1}, ..., a_r for some 1 ≤ l ≤ r ≤ n.

Note that, according to the definition, subarrays of length 1 and 2 are good.

Input

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

The first line of each test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of array a.

The second line of each test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9).

It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5.

Output

For each test case, print the number of good subarrays of array a.

Example

Input

3
4
2 4 1 3
5
6 9 1 9 6
2
13 37

Output

10
12
3

Note

In the first test case, it can be proven that any subarray of a is good. For example, subarray [a_2, a_3, a_4] is good since it contains only three elements and:

  * d((a_2, 2), (a_4, 4)) = |4 - 3| + |2 - 4| = 3 < d((a_2, 2), (a_3, 3)) + d((a_3, 3), (a_4, 4)) = 3 + 1 + 2 + 1 = 7;
  * d((a_2, 2), (a_3, 3)) < d((a_2, 2), (a_4, 4)) + d((a_4, 4), (a_3, 3));
  * d((a_3, 3), (a_4, 4)) < d((a_3, 3), (a_2, 2)) + d((a_2, 2), (a_4, 4));

In the second test case, for example, subarray [a_1, a_2, a_3, a_4] is not good, since it contains a bad triple (a_1, 1), (a_2, 2), (a_4, 4):

  * d((a_1, 1), (a_4, 4)) = |6 - 9| + |1 - 4| = 6;
  * d((a_1, 1), (a_2, 2)) = |6 - 9| + |1 - 2| = 4;
  * d((a_2, 2), (a_4, 4)) = |9 - 9| + |2 - 4| = 2;

So, d((a_1, 1), (a_4, 4)) = d((a_1, 1), (a_2, 2)) + d((a_2, 2), (a_4, 4)).

```python
A=[]
t=int(input())
def isg(l,r):
    for i in range(l,r+1):
        for j in range(i+1,r+1):
            for k in range(j+1,r+1):
                if(A[i]>=A[j] and A[j]>=A[k]):
                    return False
                if(A[i]<=A[j] and A[j]<=A[k]):
                    return False
    return True
for i in range(t):
    n=int(input())
    A=list(map(int,input().split()))
    ans=0;j=0
    for i in range(n):
        while(isg(j,i)==False):
            j+=1
        ans+=i-j+1
    print(ans)
```


177_A1. Good Matrix Elements

The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good:

  * Elements of the main diagonal.
  * Elements of the secondary diagonal.
  * Elements of the "middle" row — the row which has exactly <image> rows above it and the same number of rows below it.
  * Elements of the "middle" column — the column that has exactly <image> columns to the left of it and the same number of columns to the right of it.

<image> The figure shows a 5 × 5 matrix. The good elements are marked with green.

Help the Smart Beaver count the sum of good elements of the given matrix.

Input

The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix.

The input limitations for getting 30 points are:

  * 1 ≤ n ≤ 5

The input limitations for getting 100 points are:

  * 1 ≤ n ≤ 101

Output

Print a single integer — the sum of good matrix elements.

Examples

Input

3
1 2 3
4 5 6
7 8 9

Output

45

Input

5
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1

Output

17

Note

In the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.

```python

n = int(input())

gh = [0 for _ in range(n)]
arr = [gh[:] for _ in range(n) ]
visited = [gh[:] for _ in range(n)]

for i in range(n):
    a = input()
    a1 = a.split()
    for j in range(n):
        arr[i][j] = int(a1[j])

if n == 1:
    print( a)
else:
    middleR = (n - 1) // 2
    middleC = (n - 1 ) // 2
    total = 0
    for i in range(n):
        if visited[middleR][i] == 0:
            visited[middleR][i] = 1
            total += arr[middleR][i]
    #print(visited)
    for i in range(n):
        if visited[i][middleC] == 0:
            visited[i][middleC] = 1
            total += arr[i][middleC]
    #print(visited)

    for i in range(n):
        if visited[i][i] == 0:
            visited[i][i] = 1
            total += arr[i][i]
    #print(visited)
    ku = 0
    for i in range(n):
        kkt = n - 1 - i
        if visited[ku][kkt] == 0:
            visited[ku][kkt] = 1
            total += arr[ku][kkt]
        ku += 1

    #print(visited)
    print(total)

```


197_C. Lexicographically Maximum Subsequence

You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.

We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 < p2 < ... < pk ≤ |s|) a subsequence of string s = s1s2... s|s|.

String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1. Characters in lines are compared like their ASCII codes.

Input

The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.

Output

Print the lexicographically maximum subsequence of string s.

Examples

Input

ababba

Output

bbba

Input

abbcbccacbbcbaaba

Output

cccccbba

Note

Let's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).

The first sample: aBaBBA

The second sample: abbCbCCaCbbCBaaBA

```python
from collections import Counter

s = input()
c = Counter(s)

cur_char = 'z'
for ch in s:
    while c[cur_char] == 0:
        cur_char = chr(ord(cur_char) - 1)
    if ch == cur_char:
        print(cur_char, end='')
    c[ch] -= 1

```


26_C. Parquet

Once Bob decided to lay a parquet floor in his living room. The living room is of size n × m metres. Bob had planks of three types: a planks 1 × 2 meters, b planks 2 × 1 meters, and c planks 2 × 2 meters. Help Bob find out, if it is possible to parquet the living room with such a set of planks, and if it is possible, find one of the possible ways to do so. Bob doesn't have to use all the planks.

Input

The first input line contains 5 space-separated integer numbers n, m, a, b, c (1 ≤ n, m ≤ 100, 0 ≤ a, b, c ≤ 104), n and m — the living room dimensions, a, b and c — amount of planks 1 × 2, 2 × 1 и 2 × 2 respectively. It's not allowed to turn the planks.

Output

If it is not possible to parquet the room with such a set of planks, output IMPOSSIBLE. Otherwise output one of the possible ways to parquet the room — output n lines with m lower-case Latin letters each. Two squares with common sides should contain the same letters, if they belong to one and the same plank, and different letters otherwise. Different planks can be marked with one and the same letter (see examples). If the answer is not unique, output any.

Examples

Input

2 6 2 2 1

Output

aabcca
aabdda

Input

1 1 100 100 100

Output

IMPOSSIBLE

Input

4 4 10 10 10

Output

aabb
aabb
bbaa
bbaa


292_E. Copying Data

We often have to copy large volumes of information. Such operation can take up many computer resources. Therefore, in this problem you are advised to come up with a way to copy some part of a number array into another one, quickly.

More formally, you've got two arrays of integers a1, a2, ..., an and b1, b2, ..., bn of length n. Also, you've got m queries of two types:

  1. Copy the subsegment of array a of length k, starting from position x, into array b, starting from position y, that is, execute by + q = ax + q for all integer q (0 ≤ q < k). The given operation is correct — both subsegments do not touch unexistent elements.
  2. Determine the value in position x of array b, that is, find value bx.

For each query of the second type print the result — the value of the corresponding element of array b.

Input

The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 105) — the number of elements in the arrays and the number of queries, correspondingly. The second line contains an array of integers a1, a2, ..., an (|ai| ≤ 109). The third line contains an array of integers b1, b2, ..., bn (|bi| ≤ 109).

Next m lines contain the descriptions of the queries. The i-th line first contains integer ti — the type of the i-th query (1 ≤ ti ≤ 2). If ti = 1, then the i-th query means the copying operation. If ti = 2, then the i-th query means taking the value in array b. If ti = 1, then the query type is followed by three integers xi, yi, ki (1 ≤ xi, yi, ki ≤ n) — the parameters of the copying query. If ti = 2, then the query type is followed by integer xi (1 ≤ xi ≤ n) — the position in array b.

All numbers in the lines are separated with single spaces. It is guaranteed that all the queries are correct, that is, the copying borders fit into the borders of arrays a and b.

Output

For each second type query print the result on a single line.

Examples

Input

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

Output

0
3
-1
3
2
3
-1

```python
import sys
'''
SEGMENT TREE
Assign
'''
class SegmTree():
    '''
    - modify elements on interval
    - get single element
    '''
    def __init__(self, size):
        N = 1
        while N < size:
            N <<= 1
        self.N = N
        self.tree = [0] * (2*N)

    def modify_range(self, l, r, value):
        l += self.N
        r += self.N
        while l < r:
            if l & 1:
                self.tree[l] = value
                l += 1
            if r & 1:
                r -= 1
                self.tree[r] = value
            l >>= 1
            r >>= 1

    def query(self, i):
        i += self.N
        latest_change = self.tree[i]
        p = i
        while p > 1:
            p >>= 1
            latest_change = max(latest_change, self.tree[p])
        return latest_change

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

n, m = input()
a = list(input())
b = list(input())
st = SegmTree(n)
request = [None] * (m + 1)
for i in range(1, m+1):
    t, *arg = input()
    if t == 1:
        x, y, k = request[i] = arg
        st.modify_range(y-1, y-1+k, i)
    else:
        pos = arg[0] - 1
        req_id = st.query(pos)
        if req_id > 0:
            x, y, k = request[req_id]
            ans = a[x+(pos-y)]
        else:
            ans = b[pos]
        sys.stdout.write(f'{ans}\n')

# inf.close()

```


316_G1. Good Substrings

Smart Beaver recently got interested in a new word game. The point is as follows: count the number of distinct good substrings of some string s. To determine if a string is good or not the game uses rules. Overall there are n rules. Each rule is described by a group of three (p, l, r), where p is a string and l and r (l ≤ r) are integers. We’ll say that string t complies with rule (p, l, r), if the number of occurrences of string t in string p lies between l and r, inclusive. For example, string "ab", complies with rules ("ab", 1, 2) and ("aab", 0, 1), but does not comply with rules ("cd", 1, 2) and ("abab", 0, 1).

A substring s[l... r] (1 ≤ l ≤ r ≤ |s|) of string s = s1s2... s|s| (|s| is a length of s) is string slsl + 1... sr.

Consider a number of occurrences  of string t in string p as a number of pairs of integers l, r (1 ≤ l ≤ r ≤ |p|) such that p[l... r] = t.

We’ll say that string t is good if it complies with all n rules. Smart Beaver asks you to help him to write a program that can calculate the number of distinct good substrings of string s. Two substrings s[x... y] and s[z... w] are cosidered to be distinct iff s[x... y] ≠ s[z... w].

Input

The first line contains string s. The second line contains integer n. Next n lines contain the rules, one per line. Each of these lines contains a string and two integers pi, li, ri, separated by single spaces (0 ≤ li ≤ ri ≤ |pi|). It is guaranteed that all the given strings are non-empty and only contain lowercase English letters.

The input limits for scoring 30 points are (subproblem G1):

  * 0 ≤ n ≤ 10.
  * The length of string s and the maximum length of string p is  ≤ 200.

The input limits for scoring 70 points are (subproblems G1+G2):

  * 0 ≤ n ≤ 10.
  * The length of string s and the maximum length of string p is  ≤ 2000.

The input limits for scoring 100 points are (subproblems G1+G2+G3):

  * 0 ≤ n ≤ 10.
  * The length of string s and the maximum length of string p is  ≤ 50000.

Output

Print a single integer — the number of good substrings of string s.

Examples

Input

aaab
2
aa 0 0
aab 1 1

Output

3

Input

ltntlnen
3
n 0 0
ttlneenl 1 4
lelllt 1 1

Output

2

Input

a
0

Output

1

Note

There are three good substrings in the first sample test: «aab», «ab» and «b».

In the second test only substrings «e» and «t» are good.

```python

def count(p, s):
    start = 0
    c = 0
    while True:
        try:
            pos = s.index(p, start)
            c += 1
            start = pos + 1
        except ValueError:
            return c

s = input()
n = int(input())

pravs = []
for i in range(n):
    p, l, r = input().split()
    l = int(l); r = int(r)
    pravs.append((p, l, r))

var = set()
for l in range(len(s)):
    for r in range(l+1, len(s)+1):
        pods = s[l:r]
        for prav in pravs:
            if not prav[1] <= count(pods, prav[0]) <= prav[2]:
                break
        else:
            var.add(pods)

print(len(var))

```


340_C. Tourist Problem

Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are n destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The n destinations are described by a non-negative integers sequence a1, a2, ..., an. The number ak represents that the kth destination is at distance ak kilometers from the starting point. No two destinations are located in the same place.

Iahub wants to visit each destination only once. Note that, crossing through a destination is not considered visiting, unless Iahub explicitly wants to visit it at that point. Also, after Iahub visits his last destination, he doesn't come back to kilometer 0, as he stops his trip at the last destination.

The distance between destination located at kilometer x and next destination, located at kilometer y, is |x - y| kilometers. We call a "route" an order of visiting the destinations. Iahub can visit destinations in any order he wants, as long as he visits all n destinations and he doesn't visit a destination more than once.

Iahub starts writing out on a paper all possible routes and for each of them, he notes the total distance he would walk. He's interested in the average number of kilometers he would walk by choosing a route. As he got bored of writing out all the routes, he asks you to help him.

Input

The first line contains integer n (2 ≤ n ≤ 105). Next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 107).

Output

Output two integers — the numerator and denominator of a fraction which is equal to the wanted average number. The fraction must be irreducible.

Examples

Input

3
2 3 5

Output

22 3

Note

Consider 6 possible routes:

  * [2, 3, 5]: total distance traveled: |2 – 0| + |3 – 2| + |5 – 3| = 5;
  * [2, 5, 3]: |2 – 0| + |5 – 2| + |3 – 5| = 7;
  * [3, 2, 5]: |3 – 0| + |2 – 3| + |5 – 2| = 7;
  * [3, 5, 2]: |3 – 0| + |5 – 3| + |2 – 5| = 8;
  * [5, 2, 3]: |5 – 0| + |2 – 5| + |3 – 2| = 9;
  * [5, 3, 2]: |5 – 0| + |3 – 5| + |2 – 3| = 8.

The average travel distance is <image> = <image> = <image>.

```python
import math
n = int(input())
l = [int(x) for x in input().split()]
a1 = sum(l)
a2 = n
a3 = 0
temp = 0
l.sort()
for i in range(n):
    temp += l[n-i-1]
    a3-=(a1-temp)
    a3+=(n-i-1)*(l[n-i-1])

a1 = a1+a3+a3
a4 = math.gcd(a1, a2)
print(a1//a4, a2//a4)

```


387_D. George and Interesting Graph

George loves graphs. Most of all, he loves interesting graphs. We will assume that a directed graph is interesting, if it meets the following criteria:

  * The graph doesn't contain any multiple arcs;
  * There is vertex v (we'll call her the center), such that for any vertex of graph u, the graph contains arcs (u, v) and (v, u). Please note that the graph also contains loop (v, v).
  * The outdegree of all vertexes except for the center equals two and the indegree of all vertexes except for the center equals two. The outdegree of vertex u is the number of arcs that go out of u, the indegree of vertex u is the number of arcs that go in u. Please note that the graph can contain loops.

However, not everything's that simple. George got a directed graph of n vertices and m arcs as a present. The graph didn't have any multiple arcs. As George loves interesting graphs, he wants to slightly alter the presented graph and transform it into an interesting one. In one alteration he can either remove an arbitrary existing arc from the graph or add an arbitrary arc to the graph.

George wonders: what is the minimum number of changes that he needs to obtain an interesting graph from the graph he's got as a present? Help George and find the answer to the question.

Input

The first line contains two space-separated integers n and m (2 ≤ n ≤ 500, 1 ≤ m ≤ 1000) — the number of vertices and arcs in the presented graph.

Each of the next m lines contains two space-separated integers ai, bi (1 ≤ ai, bi ≤ n) — the descriptions of the graph's arcs. Pair (ai, bi) means that the graph contains an arc from vertex number ai to vertex number bi. It is guaranteed that the presented graph doesn't contain multiple arcs.

Assume that the grah vertices are numbered 1 through n.

Output

Print a single integer — the answer to George's question.

Examples

Input

3 7
1 1
2 2
3 1
1 3
3 2
2 3
3 3

Output

0

Input

3 6
1 1
2 2
3 1
3 2
2 3
3 3

Output

1

Input

3 1
2 2

Output

6

Note

For more information about directed graphs, please visit: http://en.wikipedia.org/wiki/Directed_graph

In the first sample the graph already is interesting, its center is vertex 3.

```python
# by the authority of GOD     author: manhar singh sachdev #

import os,sys
from io import BytesIO, IOBase

def matching(n,m,path):
    # Hopkrocft Karp O(EV^0.5)
    match1 = [-1]*n
    match2 = [-1]*m
    for node in range(n):
        for nei in path[node]:
            if match2[nei] == -1:
                match1[node] = nei
                match2[nei] = node
                break
    while 1:
        bfs = [node for node in range(n) if match1[node] == -1]
        depth = [-1]*n
        for node in bfs:
            depth[node] = 0

        for node in bfs:
            for nei in path[node]:
                next_node = match2[nei]
                if next_node == -1:
                    break
                if depth[next_node] == -1:
                    depth[next_node] = depth[node]+1
                    bfs.append(next_node)
            else:
                continue
            break
        else:
            break
        pointer = [len(c) for c in path]
        dfs = [node for node in range(n) if depth[node] == 0]
        while dfs:
            node = dfs[-1]
            while pointer[node]:
                pointer[node] -= 1
                nei = path[node][pointer[node]]
                next_node = match2[nei]
                if next_node == -1:
                    while nei != -1:
                        node = dfs.pop()
                        match2[nei],match1[node],nei = node,nei,match1[node]
                    break
                elif depth[node]+1 == depth[next_node]:
                    dfs.append(next_node)
                    break
            else:
                dfs.pop()
    return n-match1.count(-1)

def main():
    n,m = map(int,input().split())
    edg = [tuple(map(lambda xx:int(xx)-1,input().split())) for _ in range(m)]
    ans = float("inf")
    for centre in range(n):
        path = [[] for _ in range(n)]
        cost = 2*n-1
        extra = m
        for u,v in edg:
            if u == centre or v == centre:
                cost -= 1
                extra -= 1
            else:
                path[u].append(v)
        maxMatch = matching(n,n,path)
        extra -= maxMatch
        cost += n-1-maxMatch+extra
        ans = min(ans,cost)
    print(ans)

# Fast IO Region
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")
if __name__ == "__main__":
    main()
```


408_B. Garland

Once little Vasya read an article in a magazine on how to make beautiful handmade garland from colored paper. Vasya immediately went to the store and bought n colored sheets of paper, the area of each sheet is 1 square meter.

The garland must consist of exactly m pieces of colored paper of arbitrary area, each piece should be of a certain color. To make the garland, Vasya can arbitrarily cut his existing colored sheets into pieces. Vasya is not obliged to use all the sheets to make the garland.

Vasya wants the garland to be as attractive as possible, so he wants to maximize the total area of m pieces of paper in the garland. Calculate what the maximum total area of the pieces of paper in the garland Vasya can get.

Input

The first line contains a non-empty sequence of n (1 ≤ n ≤ 1000) small English letters ("a"..."z"). Each letter means that Vasya has a sheet of paper of the corresponding color.

The second line contains a non-empty sequence of m (1 ≤ m ≤ 1000) small English letters that correspond to the colors of the pieces of paper in the garland that Vasya wants to make.

Output

Print an integer that is the maximum possible total area of the pieces of paper in the garland Vasya wants to get or -1, if it is impossible to make the garland from the sheets he's got. It is guaranteed that the answer is always an integer.

Examples

Input

aaabbac
aabbccac

Output

6

Input

a
z

Output

-1

Note

In the first test sample Vasya can make an garland of area 6: he can use both sheets of color b, three (but not four) sheets of color a and cut a single sheet of color c in three, for example, equal pieces. Vasya can use the resulting pieces to make a garland of area 6.

In the second test sample Vasya cannot make a garland at all — he doesn't have a sheet of color z.

```python
#!/usr/bin/python
import re
import inspect
from sys import argv, exit

def rstr():
    return input()

def rstrs(splitchar=' '):
    return [i for i in input().split(splitchar)]

def rint():
    return int(input())

def rints(splitchar=' '):
    return [int(i) for i in rstrs(splitchar)]

def varnames(obj, namespace=globals()):
    return [name for name in namespace if namespace[name] is obj]

def pvar(var, override=False):
    prnt(varnames(var), var)

def prnt(*args, override=False):
    if '-v' in argv or override:
        print(*args)

# Faster IO
pq = []
def penq(s):
    if not isinstance(s, str):
        s = str(s)
    pq.append(s)

def pdump():
    s = ('\n'.join(pq)).encode()
    os.write(1, s)

if __name__ == '__main__':
    s1 = [c for c in rstr()]
    s2 = [c for c in rstr()]

    counts1 = [len([c for c in s1 if ord(c)==ch]) for ch in range(ord('a'), ord('z')+1)]
    counts2 = [len([c for c in s2 if ord(c)==ch]) for ch in range(ord('a'), ord('z')+1)]

    total = 0
    for c1, c2 in zip(counts1, counts2):
        if c2 != 0 and c1 == 0:
            print('-1')
            exit(0)
        if c2 > c1:
            ans = c1
        else:
            ans = c2
        total += ans

    print(total)

```


435_C. Cardiogram

In this problem, your task is to use ASCII graphics to paint a cardiogram.

A cardiogram is a polyline with the following corners:

<image>

That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an.

Your task is to paint a cardiogram by given sequence ai.

Input

The first line contains integer n (2 ≤ n ≤ 1000). The next line contains the sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 1000). It is guaranteed that the sum of all ai doesn't exceed 1000.

Output

Print max |yi - yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print <image> characters. Each character must equal either « / » (slash), « \ » (backslash), « » (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram.

Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.

Examples

Input

5
3 1 2 5 1

Output

      / \
   / \ /   \
  /       \
 /         \
          \ /

Input

3
1 5 1

Output

 / \
  \
   \
    \
     \ /

Note

Due to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.

http://assets.codeforces.com/rounds/435/1.txt

http://assets.codeforces.com/rounds/435/2.txt

```python
n = int(input())
a_list = list(map(int, list(str(input()).split(" "))))

out = [' '*(sum(a_list))]*2000
cur,pref_size = 1000, 0
cur_max, cur_min = 1000,1000
for k in range(n):
    for i in range(a_list[k]):
        ind = pref_size + i
        if k % 2 == 0:
            out[cur] = out[cur][:ind] + '/' + out[cur][ind+1:]
            cur += 1
        else:
            out[cur] = out[cur][:ind] + '\\' + out[cur][ind+1:]
            cur -= 1

    if k % 2 == 1:
        cur += 1
        cur_min = min(cur_min, cur)
    else:
        cur -= 1
        cur_max = max(cur_max, cur)

    pref_size += a_list[k]

for i in range(cur_max,cur_min-1,-1):
    print(out[i])

```