1447_A. Add Candies

There are n bags with candies, initially the i-th bag contains i candies. You want all the bags to contain an equal amount of candies in the end.

To achieve this, you will:

  * Choose m such that 1 ≤ m ≤ 1000

  * Perform m operations. In the j-th operation, you will pick one bag and add j candies to all bags apart from the chosen one.

Your goal is to find a valid sequence of operations after which all the bags will contain an equal amount of candies.

  * It can be proved that for the given constraints such a sequence always exists.

  * You don't have to minimize m.

  * If there are several valid sequences, you can output any.

Input

Each test contains multiple test cases.

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

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

Output

For each testcase, print two lines with your answer.

In the first line print m (1≤ m ≤ 1000) — the number of operations you want to take.

In the second line print m positive integers a_1, a_2, ..., a_m (1 ≤ a_i ≤ n), where a_j is the number of bag you chose on the j-th operation.

Example

Input

2
2
3

Output

1
2
5
3 3 3 1 2

Note

In the first case, adding 1 candy to all bags except of the second one leads to the arrangement with [2, 2] candies.

In the second case, firstly you use first three operations to add 1+2+3=6 candies in total to each bag except of the third one, which gives you [7, 8, 3]. Later, you add 4 candies to second and third bag, so you have [7, 12, 7], and 5 candies to first and third bag — and the result is [12, 12, 12].

```python
a=int(input())
for i in range(a):
    b=int(input())
    arr=[str(i) for i in range(b,1,-1)]
    arr=arr[::-1]
    print(len(arr))
    print(' '.join(arr))

```


1471_B. Strange List

You have given an array a of length n and an integer x to a brand new robot. What the robot does is the following: it iterates over the elements of the array, let the current element be q. If q is divisible by x, the robot adds x copies of the integer q/x to the end of the array, and moves on to the next element. Note that the newly added elements could be processed by the robot later. Otherwise, if q is not divisible by x, the robot shuts down.

Please determine the sum of all values of the array at the end of the process.

Input

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

The first line of each test case contains two integers n and x (1 ≤ n ≤ 10^5, 2 ≤ x ≤ 10^9) — the length of the array and the value which is used by the robot.

The next line contains integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) — the initial values in the array.

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

Output

For each test case output one integer — the sum of all elements at the end of the process.

Example

Input

2
1 2
12
4 2
4 6 8 2

Output

36
44

Note

In the first test case the array initially consists of a single element [12], and x=2. After the robot processes the first element, the array becomes [12, 6, 6]. Then the robot processes the second element, and the array becomes [12, 6, 6, 3, 3]. After the robot processes the next element, the array becomes [12, 6, 6, 3, 3, 3, 3], and then the robot shuts down, since it encounters an element that is not divisible by x = 2. The sum of the elements in the resulting array is equal to 36.

In the second test case the array initially contains integers [4, 6, 8, 2], and x=2. The resulting array in this case looks like  [4, 6, 8, 2, 2, 2, 3, 3, 4, 4, 1, 1, 1, 1, 1, 1].

```python
t=int(input())
for _ in range(t):
    n,x=[int(z) for z in input().split()]
    a=[int(x) for x in input().split()]

    minCycles=float('inf')
    minCycIdx=-1
    for i,z in enumerate(a):
        nCycles=0
        while z%x==0:
            nCycles+=1
            z//=x
        if nCycles<minCycles:
            minCycles=nCycles
            minCycIdx=i

    ans=0
    for i,z in enumerate(a):
        if i<minCycIdx:
            minCycles2=minCycles+1 #can have 1 more cycle since it comes before the min cyc index
        else:
            minCycles2=minCycles
        ans+=z
        cycCnt=0
        z2=z
        while z2%x==0 and cycCnt<minCycles2:
            ans+=z
            z2//=x
            cycCnt+=1
    print(ans)
```


1498_B. Box Fitting

You are given n rectangles, each of height 1. Each rectangle's width is a power of 2 (i. e. it can be represented as 2^x for some non-negative integer x).

You are also given a two-dimensional box of width W. Note that W may or may not be a power of 2. Moreover, W is at least as large as the width of the largest rectangle.

You have to find the smallest height of this box, such that it is able to fit all the given rectangles. It is allowed to have some empty space left in this box after fitting all the rectangles.

You cannot rotate the given rectangles to make them fit into the box. Moreover, any two distinct rectangles must not overlap, i. e., any two distinct rectangles must have zero intersection area.

See notes for visual explanation of sample input.

Input

The first line of input contains one integer t (1 ≤ t ≤ 5 ⋅ 10^3) — the number of test cases. Each test case consists of two lines.

For each test case:

  * the first line contains two integers n (1 ≤ n ≤ 10^5) and W (1 ≤ W ≤ 10^9);
  * the second line contains n integers w_1, w_2, ..., w_n (1 ≤ w_i ≤ 10^6), where w_i is the width of the i-th rectangle. Each w_i is a power of 2;
  * additionally, max_{i=1}^{n} w_i ≤ W.

The sum of n over all test cases does not exceed 10^5.

Output

Output t integers. The i-th integer should be equal to the answer to the i-th test case — the smallest height of the box.

Example

Input

2
5 16
1 2 8 4 8
6 10
2 8 8 2 2 8

Output

2
3

Note

For the first test case in the sample input, the following figure shows one way to fit the given five rectangles into the 2D box with minimum height:

<image>

In the figure above, the number inside each rectangle is its width. The width of the 2D box is 16 (indicated with arrow below). The minimum height required for the 2D box in this case is 2 (indicated on the left).

In the second test case, you can have a minimum height of three by keeping two blocks (one each of widths eight and two) on each of the three levels.

```python
from sys import stdin
from math import log2
input = lambda: stdin.readline().strip()

t = int(input())
for _ in range(t):
    n, W = map(int, input().split())
    ls = list(map(int, input().split()))
    d = []
    for i in range(20):
        d.append(0)
    for i in ls:
        d[int(log2(i))]+=1
    result = 0
    while True:
        tmp = W
        flag = False
        for i in range(19, -1, -1):
            if d[i]!=0:
                cnt = min(d[i], tmp//(2**i))
                tmp -= (2**i)*cnt
                d[i] -= cnt
                flag = True
        if not flag:
            break
        else:
            result += 1
    print(result)

```


1520_A. Do Not Be Distracted!

Polycarp has 26 tasks. Each task is designated by a capital letter of the Latin alphabet.

The teacher asked Polycarp to solve tasks in the following way: if Polycarp began to solve some task, then he must solve it to the end, without being distracted by another task. After switching to another task, Polycarp cannot return to the previous task.

Polycarp can only solve one task during the day. Every day he wrote down what task he solved. Now the teacher wants to know if Polycarp followed his advice.

For example, if Polycarp solved tasks in the following order: "DDBBCCCBBEZ", then the teacher will see that on the third day Polycarp began to solve the task 'B', then on the fifth day he got distracted and began to solve the task 'C', on the eighth day Polycarp returned to the task 'B'. Other examples of when the teacher is suspicious: "BAB", "AABBCCDDEEBZZ" and "AAAAZAAAAA".

If Polycarp solved the tasks as follows: "FFGZZZY", then the teacher cannot have any suspicions. Please note that Polycarp is not obligated to solve all tasks. Other examples of when the teacher doesn't have any suspicious: "BA", "AFFFCC" and "YYYYY".

Help Polycarp find out if his teacher might be suspicious.

Input

The first line contains an integer t (1 ≤ t ≤ 1000). Then t test cases follow.

The first line of each test case contains one integer n (1 ≤ n ≤ 50) — the number of days during which Polycarp solved tasks.

The second line contains a string of length n, consisting of uppercase Latin letters, which is the order in which Polycarp solved the tasks.

Output

For each test case output:

  * "YES", if the teacher cannot be suspicious;
  * "NO", otherwise.

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

Example

Input

5
3
ABA
11
DDBBCCCBBEZ
7
FFGZZZY
1
Z
2
AB

Output

NO
NO
YES
YES
YES

```python
def solve(task):
    unique = set(task)
    segments = 0
    prev = ' '
    for letter in task:
        if letter != prev:
            segments+=1
        prev = letter
    return "YES" if len(unique) == segments else "NO"
if __name__ == '__main__':
    T = int(input().strip())

    for _ in range(T):
        days = int(input().strip())
        tasks = input().strip()
        print(solve(tasks))
```


1547_F. Array Stabilization (GCD version)

You are given an array of positive integers a = [a_0, a_1, ..., a_{n - 1}] (n ≥ 2).

In one step, the array a is replaced with another array of length n, in which each element is the [greatest common divisor (GCD)](http://tiny.cc/tuy9uz) of two neighboring elements (the element itself and its right neighbor; consider that the right neighbor of the (n - 1)-th element is the 0-th element).

Formally speaking, a new array b = [b_0, b_1, ..., b_{n - 1}] is being built from array a = [a_0, a_1, ..., a_{n - 1}] such that b_i = \gcd(a_i, a_{(i + 1) mod n}), where \gcd(x, y) is the greatest common divisor of x and y, and x mod y is the remainder of x dividing by y. In one step the array b is built and then the array a is replaced with b (that is, the assignment a := b is taking place).

For example, if a = [16, 24, 10, 5] then b = [\gcd(16, 24), \gcd(24, 10), \gcd(10, 5), \gcd(5, 16)] = [8, 2, 5, 1]. Thus, after one step the array a = [16, 24, 10, 5] will be equal to [8, 2, 5, 1].

For a given array a, find the minimum number of steps after which all values a_i become equal (that is, a_0 = a_1 = ... = a_{n - 1}). If the original array a consists of identical elements then consider the number of steps is equal to 0.

Input

The first line contains an integer t (1 ≤ t ≤ 10^4). Then t test cases follow.

Each test case contains two lines. The first line contains an integer n (2 ≤ n ≤ 2 ⋅ 10^5) — length of the sequence a. The second line contains n integers a_0, a_1, ..., a_{n - 1} (1 ≤ a_i ≤ 10^6).

It is guaranteed that the sum of n over all test cases doesn't exceed 2 ⋅ 10^5.

Output

Print t numbers — answers for each test case.

Example

Input

5
4
16 24 10 5
4
42 42 42 42
3
4 6 4
5
1 2 3 4 5
6
9 9 27 9 9 63

Output

3
0
2
1
1

```python
#!/usr/bin/env python
#from __future__ import division, print_function
import math
import os
import sys
#from fractions import *
from sys import *
from decimal import *
from io import BytesIO, IOBase
from itertools import accumulate,combinations,permutations,combinations_with_replacement,product
from collections import *
#import timeit,time
#sys.setrecursionlimit(10**5)
#from sortedcontainers import *
M = 10 ** 9 + 7
import heapq
from bisect import *
from functools import lru_cache
from queue import PriorityQueue
# print(math.factorial(5))
if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip
# sys.setrecursionlimit(10**6)
# 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")
def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()
if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def inp(): return sys.stdin.readline().rstrip("\r\n")  # for fast input
def out(var): sys.stdout.write(str(var))  # for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
def fsep(): return map(float, inp().split())
def inpu(): return int(inp())
# -----------------------------------------------------------------
"""
def regularbracket(t):
    p = 0
    for i in t:
        if i == "(":
            p += 1
        else:
            p -= 1
        if p < 0:
            return False
    else:
        if p > 0:
            return False
        else:
            return True
# -------------------------------------------------
def binarySearchcount(arr, n, key):
    left = 0
    right = n - 1
    count = 0
    while (left <= right):
        mid = ((right + left) // 2)
        # Check if middle element is
        # less than or equal to key
        if (arr[mid] <= key):
            count = mid + 1
            left = mid + 1
        # If key is smaller, ignore right half
        else:
            right = mid - 1
    return count
#--------------------------------------------------binery search
def binarySearch(arr, n, key):
    left = 0
    right = n - 1
    while (left <= right):
        mid = ((right + left) // 2)
        if arr[mid]==key:
            return mid
        if (arr[mid] <= key):
            left = mid + 1
        # If key is smaller, ignore right half
        else:
            right = mid - 1
    return -1
#-------------------------------------------------ternary search
def ternarysearch(arr,n,key):
    l,r=0,n-1
    while(l<=r):
        mid = (-l+r)//3 + l
        mid2 = mid + (-l+r)//3
        if arr[mid]==key:
            return mid
        if arr[mid2]==key:
            return mid2
        if arr[mid]>key:
            r=mid-1
        elif arr[mid2]<key:
            l=mid2+1
        else:
            l=mid+1
            r=mid2-1
    return -1
# ------------------------------reverse string(pallindrome)
def reverse1(string):
    pp = ""
    for i in string[::-1]:
        pp += i
    if pp == string:
        return True
    return False
# --------------------------------reverse list(paindrome)
def reverse2(list1):
    l = []
    for i in list1[::-1]:
        l.append(i)
    if l == list1:
        return True
    return False

def mex(list1):
    l=0
    h=len(list1)-1
    while(l<=h):
        mid=(l+h)//2
        if list1[mid]==mid:
            l=mid+1
        else:
            h=mid-1
    return l
def sumofdigits(n):
    n = str(n)
    s1 = 0
    for i in n:
        s1 += int(i)
    return s1
def perfect_square(n):
    s = math.sqrt(n)
    if s == int(s):
        return True
    return False
# -----------------------------roman
def roman_number(x):
    if x > 15999:
        return
    value = [5000, 4000, 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
    symbol = ["F", "MF", "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
    roman = ""
    i = 0
    while x > 0:
        div = x // value[i]
        x = x % value[i]
        while div:
            roman += symbol[i]
            div -= 1
        i += 1
    return roman
def soretd(s):
    for i in range(1, len(s)):
        if s[i - 1] > s[i]:
            return False
    return True
# print(soretd("1"))
# ---------------------------
def countRhombi(h, w):
    ct = 0
    for i in range(2, h + 1, 2):
        for j in range(2, w + 1, 2):
            ct += (h - i + 1) * (w - j + 1)
    return ct
def countrhombi2(h, w):
    return ((h * h) // 4) * ((w * w) // 4)
# ---------------------------------
def binpow(a, b):
    if b == 0:
        return 1
    else:
        res = binpow(a, b // 2)
    if b % 2 != 0:
        return res * res * a
    else:
        return res * res

# -------------------------------------------------------
def binpowmodulus(a, b, M):
    if b==1:
        return a%M
    if b==0:
        return 1
    if b%2==0:
        ans=binpowmodulus(a,b//2,M)
        return (ans*ans)%(M)
    else:
        ans=binpowmodulus(a,(b-1)//2,M)
        return ((ans*a)%M * ans)%M
# -------------------------------------------------------------
def coprime_to_n(n):
    result = n
    i = 2
    while (i * i <= n):
        if (n % i == 0):
            while (n % i == 0):
                n //= i
            result -= result // i
        i += 1
    if (n > 1):
        result -= result // n
    return result

def luckynumwithequalnumberoffourandseven(x,n,a):
    if x >= n and str(x).count("4") == str(x).count("7"):
        a.append(x)
    else:
        if x < 1e12:
            luckynumwithequalnumberoffourandseven(x * 10 + 4,n,a)
            luckynumwithequalnumberoffourandseven(x * 10 + 7,n,a)
    return a
#----------------------
def luckynum(x,l,r,a):
    if x>=l and x<=r:
        a.append(x)
    if x>r:
        a.append(x)
        return a
    if x < 1e10:
            luckynum(x * 10 + 4, l,r,a)
            luckynum(x * 10 + 7, l,r,a)
    return a

def luckynuber(x, n, a):
    p = set(str(x))
    if len(p) <= 2:
        a.append(x)
    if x < n:
        luckynuber(x + 1, n, a)
    return a

# ------------------------------------------------------interactive problems
def interact(type, x):
    if type == "r":
        inp = input()
        return inp.strip()
    else:
        print(x, flush=True)
# ------------------------------------------------------------------zero at end of factorial of a number
def findTrailingZeros(n):
    # Initialize result
    count = 0

    # Keep dividing n by
    # 5 & update Count
    while (n >= 5):
        n //= 5
        count += n

    return count

# -----------------------------------------------merge sort
# Python program for implementation of MergeSort
def mergeSort(arr):
    if len(arr) > 1:
        mid = len(arr) // 2
        L = arr[:mid]
        R = arr[mid:]
        mergeSort(L)
        mergeSort(R)
        i = j = k = 0
        while i < len(L) and j < len(R):
            if L[i] < R[j]:
                arr[k] = L[i]
                i += 1
            else:
                arr[k] = R[j]
                j += 1
            k += 1
        while i < len(L):
            arr[k] = L[i]
            i += 1
            k += 1
        while j < len(R):
            arr[k] = R[j]
            j += 1
            k += 1
# -----------------------------------------------lucky number with two lucky any digits
res = set()
def solven(p, l, a, b, n):  # given number
    if p > n or l > 10:
        return
    if p > 0:
        res.add(p)
    solven(p * 10 + a, l + 1, a, b, n)
    solven(p * 10 + b, l + 1, a, b, n)
# problem
n = int(input())
for a in range(0, 10):
    for b in range(0, a):
        solve(0, 0)
print(len(res))
"""
"""
def subsetsUtil(A, subset, index, d):
    print(*subset)
    s = sum(subset)
    d.append(s)
    for i in range(index, len(A)):
        subset.append(A[i])
        subsetsUtil(A, subset, i + 1, d)
        subset.pop(-1)
    return d
def subsetSums(arr, l, r, d, sum=0):
    if l > r:
        d.append(sum)
        return
    subsetSums(arr, l + 1, r, d, sum + arr[l])
    # Subset excluding arr[l]
    subsetSums(arr, l + 1, r, d, sum)
    return d

def print_factors(x):
    factors = []
    for i in range(1, x + 1):
        if x % i == 0:
            factors.append(i)
    return (factors)
# -----------------------------------------------
def calc(X, d, ans, D):
    # print(X,d)
    if len(X) == 0:
        return
    i = X.index(max(X))
    ans[D[max(X)]] = d
    Y = X[:i]
    Z = X[i + 1:]
    calc(Y, d + 1, ans, D)
    calc(Z, d + 1, ans, D)

def generate(st, s):
    if len(s) == 0:
        return
    if s not in st:
        st.add(s)
        for i in range(len(s)):
            t = list(s).copy()
            t.remove(s[i])
            t = ''.join(t)
            generate(st, t)
    return
#=--------------------------------------------longest increasing subsequence
def largestincreasingsubsequence(A):
    l = [1]*len(A)
    for i in range(1,len(l)):
        for k in range(i):
            if A[k]<=A[i]:
                l[i]=max(l[i],l[k]+1)
    return max(l)
#----------------------------------Function to calculate Bitwise OR of sums of all subsequences
def findOR(nums, N):
    prefix_sum = 0
    result = 0
    for i in range(N):
        result |= nums[i]
        prefix_sum += nums[i]
        result |= prefix_sum
    return result
def OR(a, n):
    ans = a[0]
    for i in range(1, n):
        ans |= a[i]
        #l.append(ans)
    return ans
def toString(List):
    return ''.join(List)
# Function to print permutations of string
# This function takes three parameters:
# 1. String
# 2. Starting index of the string
# 3. Ending index of the string.
def permute(a, l, r,p):
    if l == r:
        p.append(toString(a))
    else:
        for i in range(l, r + 1):
            a[l], a[i] = a[i], a[l]
            permute(a, l + 1, r,p)
            a[l], a[i] = a[i], a[l]  # backtrack
def squareRoot(number, precision):
    start = 0
    end, ans = number, 1
    while (start <= end):
        mid = int((start + end) / 2)
        if (mid * mid == number):
            ans = mid
            break
        if (mid * mid < number):
            start = mid + 1
        else:
            end = mid - 1
    increment = 0.1
    for i in range(0, precision):
        while (ans * ans <= number):
            ans += increment
        ans = ans - increment
        increment = increment / 10
    return ans
def countRectangles(l, w):
    squareSide = math.gcd(l, w)
    return int((l * w) / (squareSide * squareSide))
# Function that count the
# total numbersProgram between L
# and R which have all the
# digit same
def count_same_digit(L, R):
    tmp = 0
    ans = 0
    n = int(math.log10(R) + 1)
    for i in range(0, n):
        # tmp has all digits as 1
        tmp = tmp * 10 + 1
        for j in range(1, 10):

            if (L <= (tmp * j) and (tmp * j) <= R):
                #print(tmp*j)
                # Increment the required count
                ans += 1
    return ans
#----------------------------------print k closest number of a number in an array
def findCrossOver(arr, low, high, x):
    # Base cases
    if (arr[high] <= x):  # x is greater than all
        return high
    if (arr[low] > x):  # x is smaller than all
        return low
    # Find the middle point
    mid = (low + high) // 2
    if (arr[mid] <= x and arr[mid + 1] > x):
        return mid
    if (arr[mid] < x):
        return findCrossOver(arr, mid + 1, high, x)
    return findCrossOver(arr, low, mid - 1, x)
def Kclosest(arr, x, k, n,ans):
    # Find the crossover point
    l = findCrossOver(arr, 0, n - 1, x)
    r = l + 1
    count = 0
    if (arr[l] == x):
        l -= 1
    #print(l)
    while (l >= 0 and r < n and count < k):
        if (x - arr[l] < arr[r] - x):
            ans.append(arr[l])
            l -= 1
        else:
            ans.append(arr[r])
            r += 1
        count += 1
    while (count < k and l >= 0):
        ans.append(arr[l])
        l -= 1
        count += 1
    while (count < k and r < n):
        ans.append(arr[r])
        r += 1
        count += 1
    return ans

def dfs(root,nodeVal,nodeConnection,visited):
    leftVal = nodeVal[root][0]
    rightVal = nodeVal[root][1]
    solution = []
    if nodeConnection[root]:
        visited.add(root)
        for i in nodeConnection[root]:
            if i not in visited:
                solution.append(dfs(i,nodeVal,nodeConnection,visited))
        leftMax = 0
        rightMax = 0
        for i in solution:
            l, r = i
            leftMax += max(abs(leftVal - l[0]) + l[1], abs(leftVal - r[0]) + r[1])
            rightMax += max(abs(rightVal - l[0]) + l[1], abs(rightVal - r[0]) + r[1])
        return ((leftVal, leftMax), (rightVal, rightMax))
    else:
        return ((leftVal, 0), (rightVal, 0))

"""
def luckynumber(x,n,a):
    if x >0:
        a.append(x)
    if x>10**9:
        return a
    else:
        if x < 1e12:
            luckynumber(x * 10 + 4,n,a)
            luckynumber(x * 10 + 7,n,a)
def lcm(a,b):
    return (a*b)//math.gcd(a,b)

def query1(l, r):
    if l >= r:
        return -1
    print('?', l + 1, r + 1)
    sys.stdout.flush()
    return int(input()) - 1
def answer(p):
    print('!', p + 1)
    sys.stdout.flush()
    exit()

#---------------------count number of primes
"""
import math
MAX = 10**5
prefix = [0] * (MAX + 1)
def buildPrefix():
    prime = [1] * (MAX + 1)
    p = 2
    while (p * p <= MAX):
        if (prime[p] == 1):
            i = p * 2
            while (i <= MAX):
                prime[i] = 0
                i += p
        p += 1
    for p in range(2, MAX + 1):
        prefix[p] = prefix[p - 1]
        if (prime[p] == 1):
            prefix[p] += 1
def query(L, R):
    return prefix[R] - prefix[L - 1]
#buildPrefix()

def maxSubArraySum(a, size):
    max_so_far = a[0]
    curr_max = a[0]
    for i in range(1, size):
        curr_max = max(a[i], curr_max + a[i])
        max_so_far = max(max_so_far, curr_max)
    return max_so_far

def solvepp(n,k):
    if n==1 and k==1:
        return 0
    mid=(2**(n-1))//2
    if k<=mid:
        return solvepp(n-1,k)
    else:
        return solvepp(n-1,k-(mid))==0

#------------------print subset of strings
def solvr(s,p):
    if len(s)==0:
        print(p,end=" ")
        return
    op1=p
    op2=p+s[0]
    s=s[1:]
    solvr(s,op1)
    solvr(s,op2)
    return
#-------------------------------------balanced paranthesis
def paranthesis(n,m,ans,l):
    if n==0 and m==0:
        print(ans)
        return
    if n!=0:
        op1=ans+"("
        paranthesis(n-1,m,op1,l)
    if m>n:
        op2=ans+")"
        paranthesis(n,m-1,op2,l)
"""
"""
class node:
    def __init__(self,data):
        self.data=data
        self.next=None
class linkedlis:
    def __init__(self):
        self.head=None
    def printlis(self):
        temp=self.head
        while(temp):
            print(temp.data,end=" ")
            temp=temp.next
    def pushfirst(self,new_data):
        new_node=node(new_data)
        new_node.next=self.head
        self.head=new_node
    def pushmid(self,previous_node,new_data):
        new_node=node(new_data)
        if previous_node==None:
            print("call pushfirst function if it is the the start otherwise raise an error.")
        new_node.next=previous_node.next
        previous_node.next=new_node
    def pushlast(self,new_data):
        new_node=node(new_data)
        if self.head==None:
            self.head=new_node
            return
        last=self.head
        while(last.next!=None):
            last=last.next
        last.next=new_node
    def delete_node(self,key):
        pass
if __name__ == '__main__':
    l=linkedlis()
    l.head= node(1)
    p = node(2)
    pp = node(4)
    l.head.next = p
    p.next = pp
    #print(l.head)
    l.pushmid(p, 3)
    l.pushlast(5)
    l.pushfirst(0)
    #l.printlis()
    #print(l.head.data)
"""

def rse(arr,n):
    stack=[]
    ans=[]
    for i in range(n-1,-1,-1):
        if len(stack)==0:
            ans.append(n)
        else:
            while(len(stack)!=0):
                if stack[-1][0]>=arr[i]:
                    stack.pop()
                else:
                    break
            if len(stack)==0:
                ans.append(n)
            else:
                ans.append(stack[-1][1])
        stack.append([arr[i],i])
    ans.reverse()
    return ans

def lse(arr,n):
    stack=[]
    ans=[]
    for i in range(n):
        if len(stack)==0:
            ans.append(-1)
        else:
            while(len(stack)!=0):
                if stack[-1][0]>=arr[i]:
                    stack.pop()
                else:
                    break
            if len(stack)==0:
                ans.append(-1)
            else:
                ans.append(stack[-1][1])
        stack.append([arr[i],i])
    return ans

def mah(arr):
    max1=0
    p=rse(arr,len(arr))
    q=lse(arr,len(arr))
    for i in range(len(arr)):
        a=(p[i]-q[i]-1)*arr[i]
        max1=max(a,max1)
    return max1
"""
def lcs(s,r):
    rr=len(r)
    ss=len(s)
    l=[[0]*(rr+1) for i in range(ss+1)]
    for i in range(1,ss+1):
        for j in range(1,rr+1):
            if s[i-1]==r[j-1]:
                l[i][j]=l[i-1][j-1]+1
            else:
                l[i][j] =max(l[i-1][j],l[i][j-1])
    return l[ss][rr]

def subsetsum(arr,sum,len):
    dp=[[False]*(sum+1) for i in range(len+1)]
    for i in range(len+1):
        dp[i][0]=True
    for i in range(1,len+1):
        for j in range(1,sum+1):
            #print(dp[i][j])
            if arr[i-1]>j:
                dp[i][j]=dp[i-1][j]
            else:
                dp[i][j]=dp[i-1][j] or dp[i-1][j-arr[i-1]]
    return dp[len][sum]
"""
"""
def matrixmincost(cost,n,m):
    dp = [[0 for x in range(m)] for x in range(n)]
    for i in range(n):
        for j in range(m):
            if i==0 and j==0:
                dp[i][j]=cost[i][j]
            elif i==0 and j!=0:
                dp[i][j]=dp[i][j-1]+cost[i][j]
            elif j==0 and i!=0:
                dp[i][j]=dp[i-1][j]+cost[i][j]
            else:
                dp[i][j] = cost[i][j] + min(dp[i-1][j],dp[i][j-1],dp[i-1][j-1])
    #print(dp)
    return dp[n-1][m-1]
"""
#--------------------------adding any number to get a number
"""
def coinchange(n,arr,len1):
    dp=[0]*(n+1)
    dp[0]=1
    for i in range(len1):
        for j in range(arr[i],n+1):
            dp[j]+=dp[j-arr[i]]
    return dp[n]
"""
"""
class Graph(object):
    def __init__(self, vertices):
        self.graph = defaultdict(list)
        self.V = vertices
    def addEdge(self, u, v):
        self.graph[u].append(v)
        self.graph[v].append(u)
    def connectedComponents(self):
        unvisited = set(range(self.V))
        queue = deque()
        count = 0
        while len(unvisited) > 0:
            count += 1
            v = next(iter(unvisited))
            unvisited.remove(v)
            queue.append(v)
            while len(queue) > 0:
                v = queue.popleft()
                for w in self.graph[v]:
                    if w in unvisited:
                        unvisited.remove(w)
                        queue.append(w)
        return count
"""
def maxSumIS(arr, n):
    msis=arr.copy()
    for i in range(1, n):
        for j in range(i):
            if (arr[i] > arr[j] and
                    msis[i] < msis[j] + arr[i]):
                msis[i] = msis[j] + arr[i]
    c=max(msis)
    p=5
    return c
#--------------------------------find the index of number in sorted array from behind
def binarysearch2(arr,target):
    lo=0
    hi=len(arr)-1
    while(lo<=hi):
        mid=(lo+hi)//2
        #print(arr[mid],arr[mid-1],mid)
        if arr[mid]==target:
            if mid!=len(arr)-1:
                if arr[mid+1]!=target:
                    return mid
                else:
                    lo+=1
            else:
                return mid
            continue
        if arr[mid]>target:
            hi=mid-1
        else:
            lo=mid+1
def ngr(arr,n):
    stack=[]
    ans=[]
    for i in range(n-1,-1,-1):
        if len(stack)==0:
            ans.append(-1)
        else:
            while(len(stack)>0):
                if stack[-1][0]<arr[i]:
                    stack.pop()
                else:
                    break
            if len(stack)==0:
                ans.append(-1)
            else:
                ans.append(stack[-1][1])
        stack.append([arr[i],i])
    ans.reverse()
    return ans

def alperm(nums, path,result):
    if not nums:
        result.add(tuple(path))
        return
    for i in range(0,len(nums)):
        alperm(nums[:i] + nums[i + 1:], path + [nums[i]],result)
    return result
#p=float("inf")
def minsum(arr,n,m,res,l):
    if n==1 and m==1:
        res+=arr[0][0]
        l.append(res)
    else:
        if n!=1:
                p=res+arr[n-1][m-1]
                minsum(arr,n-1,m,p,l)
        if m!=1:
                p=res+arr[n-1][m-1]
                minsum(arr,n,m-1,p,l)
    return min(l)

def subset(arr,n,ans,c):
    if n==0:
        print(c)
        ans.add(tuple(sorted(c)))
        return
    else:
        op=c+[arr[n-1]]
        subset(arr,n-1,ans,op)
        subset(arr,n-1,ans,c)
"""
nums=[5,2,6,1]
ret = [0] * len(nums)
sl = SortedList()
for i in range(len(nums) - 1, - 1, - 1):
    ret[i] = sl.bisect_left(nums[i])
    sl.add(nums[i])
print(ret)
"""
def catalan(n):
    if (n == 0 or n == 1):
        return 1
    catalan = [0] * (n + 1)
    catalan[0] = 1
    catalan[1] = 1
    for i in range(2, n + 1):
        for j in range(i):
            catalan[i] += catalan[j] * catalan[i - j - 1]
    return catalan[n]

def isP(p,i,j):
    if j<=i:
        return True
    if p[i]!=p[j]:
        return False
    return isP(p,i+1,j-1)
"""
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
def leftViewUtil(root, level, max1):
    if root is None:
        return
    if max1[0]<level:
        print(root.data)
        max1[0]=level
    leftViewUtil(root.left, level + 1, max1)
    leftViewUtil(root.right,level+1,max1)
def leftView(root):
    max1 =[0]
    leftViewUtil(root, 1, max1)
root = Node(10)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(7)
root.left.right = Node(8)
root.right.right = Node(15)
root.right.left = Node(12)
root.right.right.left = Node(14)
#root.left.left.right=Node(15)
max1=-1
leftView(root)
"""
"""
def find_shortest_path(graph, start, end, path=[]):
    path = path + [start]
    if start == end:
        return path
    if start not in graph:
        return None
    shortest = None
    for node in graph[start]:
        if node not in path:
            newpath = find_shortest_path(graph, node, end, path)
            if newpath:
                if not shortest or len(newpath) < len(shortest):
                    shortest = newpath
    return shortest
"""
def main():
    t=1
    t=inpu()
    for _ in range(t):
        n=inpu()
        arr=lis()
        res=0
        if len(set(arr))==1:
            print(0)
            continue
        arr+=arr
        m = 0
        for i in range(n):
            k1 = arr[i]
            k2 = arr[i + 1]
            c=0
            j=i+1
            while (k1 != k2):
                k1=math.gcd(k1, arr[j])
                k2=math.gcd(k2, arr[j + 1])
                j += 1
                c += 1
                #print(str(j)+"-------------")
            m = max(m, c)
        print(m)
if __name__ == '__main__':
    main()

```


175_C. Geometry Horse

Vasya plays the Geometry Horse.

The game goal is to destroy geometric figures of the game world. A certain number of points is given for destroying each figure depending on the figure type and the current factor value.

There are n types of geometric figures. The number of figures of type ki and figure cost ci is known for each figure type. A player gets ci·f points for destroying one figure of type i, where f is the current factor. The factor value can be an integer number from 1 to t + 1, inclusive. At the beginning of the game the factor value is equal to 1. The factor is set to i + 1 after destruction of pi (1 ≤ i ≤ t) figures, so the (pi + 1)-th figure to be destroyed is considered with factor equal to i + 1.

Your task is to determine the maximum number of points Vasya can get after he destroys all figures. Take into account that Vasya is so tough that he can destroy figures in any order chosen by him.

Input

The first line contains the only integer number n (1 ≤ n ≤ 100) — the number of figure types.

Each of the following n lines contains two integer numbers ki and ci (1 ≤ ki ≤ 109, 0 ≤ ci ≤ 1000), separated with space — the number of figures of the i-th type and the cost of one i-type figure, correspondingly.

The next line contains the only integer number t (1 ≤ t ≤ 100) — the number that describe the factor's changes.

The next line contains t integer numbers pi (1 ≤ p1 < p2 < ... < pt ≤ 1012), separated with spaces.

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

Output

Print the only number — the maximum number of points Vasya can get.

Examples

Input

1
5 10
2
3 6

Output

70

Input

2
3 8
5 10
1
20

Output

74

Note

In the first example Vasya destroys three figures first and gets 3·1·10 = 30 points. Then the factor will become equal to 2 and after destroying the last two figures Vasya will get 2·2·10 = 40 points. As a result Vasya will get 70 points.

In the second example all 8 figures will be destroyed with factor 1, so Vasya will get (3·8 + 5·10)·1 = 74 points.

```python

n = int(input())

figures = []
for _ in range(n):
    amount, cost = map(int, input().split())
    figures += [(cost, amount)]

figures.sort()

t = int(input())
T = list(map(int, input().split()))

result = 0

destructed = 0

i, j = 0, 0
while i < len(figures):
    if j < len(T) and destructed + figures[i][1] >= T[j]:
        take = T[j] - destructed
        destructed += take
        figures[i] = (figures[i][0], figures[i][1] - take)
        result += take * (j + 1) * figures[i][0]
        j += 1
    else:
        take = figures[i][1]
        destructed += take
        result += take * (j + 1) * figures[i][0]
        i += 1

print(result)

```


195_D. Analyzing Polyline

As Valeric and Valerko were watching one of the last Euro Championship games in a sports bar, they broke a mug. Of course, the guys paid for it but the barman said that he will let them watch football in his bar only if they help his son complete a programming task. The task goes like that.

Let's consider a set of functions of the following form:

<image> Let's define a sum of n functions y1(x), ..., yn(x) of the given type as function s(x) = y1(x) + ... + yn(x) for any x. It's easy to show that in this case the graph s(x) is a polyline. You are given n functions of the given type, your task is to find the number of angles that do not equal 180 degrees, in the graph s(x), that is the sum of the given functions.

Valeric and Valerko really want to watch the next Euro Championship game, so they asked you to help them.

Input

The first line contains integer n (1 ≤ n ≤ 105) — the number of functions. Each of the following n lines contains two space-separated integer numbers ki, bi ( - 109 ≤ ki, bi ≤ 109) that determine the i-th function.

Output

Print a single number — the number of angles that do not equal 180 degrees in the graph of the polyline that equals the sum of the given functions.

Examples

Input

1
1 0

Output

1

Input

3
1 0
0 2
-1 1

Output

2

Input

3
-2 -4
1 7
-5 1

Output

3

```python
from sys import stdin
from math import gcd
n = int(stdin.readline())

iset = set()

for _ in range(n):
    k,b = map(int,stdin.readline().split())
    if k!=0:
        if b==0:
            iset.add((0,1))
        else:
            x = gcd(k,b)
            if k*b>0:
                iset.add((abs(b//x),abs(k//x)))
            else:
                iset.add((-abs(b//x),abs(k//x)))

print(len(iset))

```


219_D. Choosing Capital for Treeland

The country Treeland consists of n cities, some pairs of them are connected with unidirectional roads. Overall there are n - 1 roads in the country. We know that if we don't take the direction of the roads into consideration, we can get from any city to any other one.

The council of the elders has recently decided to choose the capital of Treeland. Of course it should be a city of this country. The council is supposed to meet in the capital and regularly move from the capital to other cities (at this stage nobody is thinking about getting back to the capital from these cities). For that reason if city a is chosen a capital, then all roads must be oriented so that if we move along them, we can get from city a to any other city. For that some roads may have to be inversed.

Help the elders to choose the capital so that they have to inverse the minimum number of roads in the country.

Input

The first input line contains integer n (2 ≤ n ≤ 2·105) — the number of cities in Treeland. Next n - 1 lines contain the descriptions of the roads, one road per line. A road is described by a pair of integers si, ti (1 ≤ si, ti ≤ n; si ≠ ti) — the numbers of cities, connected by that road. The i-th road is oriented from city si to city ti. You can consider cities in Treeland indexed from 1 to n.

Output

In the first line print the minimum number of roads to be inversed if the capital is chosen optimally. In the second line print all possible ways to choose the capital — a sequence of indexes of cities in the increasing order.

Examples

Input

3
2 1
2 3

Output

0
2

Input

4
1 4
2 4
3 4

Output

2
1 2 3

```python
#More es mi pastor nada me faltara
import sys
from collections import defaultdict
from typing import NamedTuple

class EdgeNode(NamedTuple):
    vertex: int
    weight: int

class Graph:

    def __init__(self, n):
        self.graph = d = {i: [] for i in range(n + 1)}
        self.distance = [0] * (n + 1)
        self.distance[0] = sys.maxsize
        self.min_dist = sys.maxsize
        self.summation = (n * (n + 1)) / 2

    def dfs(self, root, visited=defaultdict(bool)):
        stack, path = [root], []
        rev = 0
        visited[root] = True
        while stack:
            s = stack.pop()
            visited[s] = True
            for v in self.graph[s]:
                if v[0] not in visited:
                    dist = self.distance[s] + v[1]
                    if dist < self.min_dist:
                        self.min_dist = dist
                    self.distance[v[0]] = dist
                    self.summation -= v[0]
                    if v[1] == -1:
                        rev += 1
                    path.append(s)
                    stack.append(v[0])
        return rev

    def get_min_distance(self):
        return min(self.distance)

def main():
    n = int(input())
    g = Graph(n)
    for i in range(n - 1):
        x, y = map(int, input().split())
        g.graph[x].append([y, 1])
        g.graph[y].append([x, -1])
    total_rev = g.dfs(1)
    min_distance = 0 if (g.summation > 0 and g.min_dist > 0) else g.min_dist
    print(total_rev + min_distance)
    join = ' '.join(map(str, [i for i in range(n + 1) if g.distance[i] == min_distance]))
    print(join)

main()
```


243_A. The Brand New Function

Polycarpus has a sequence, consisting of n non-negative integers: a1, a2, ..., an.

Let's define function f(l, r) (l, r are integer, 1 ≤ l ≤ r ≤ n) for sequence a as an operation of bitwise OR of all the sequence elements with indexes from l to r. Formally: f(l, r) = al | al + 1 | ... | ar.

Polycarpus took a piece of paper and wrote out the values of function f(l, r) for all l, r (l, r are integer, 1 ≤ l ≤ r ≤ n). Now he wants to know, how many distinct values he's got in the end.

Help Polycarpus, count the number of distinct values of function f(l, r) for the given sequence a.

Expression x | y means applying the operation of bitwise OR to numbers x and y. This operation exists in all modern programming languages, for example, in language C++ and Java it is marked as "|", in Pascal — as "or".

Input

The first line contains integer n (1 ≤ n ≤ 105) — the number of elements of sequence a. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 106) — the elements of sequence a.

Output

Print a single integer — the number of distinct values of function f(l, r) for the given sequence a.

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

Examples

Input

3
1 2 0

Output

4

Input

10
1 2 3 4 5 6 1 2 9 10

Output

11

Note

In the first test case Polycarpus will have 6 numbers written on the paper: f(1, 1) = 1, f(1, 2) = 3, f(1, 3) = 3, f(2, 2) = 2, f(2, 3) = 2, f(3, 3) = 0. There are exactly 4 distinct numbers among them: 0, 1, 2, 3.

```python
n, a, b = input(), set(), set()
for i in map(int, input().split()):
    b = set(i | j for j in b)
    b.add(i)
    a.update(b)
print(len(a))

```


291_A. Spyke Talks

Polycarpus is the director of a large corporation. There are n secretaries working for the corporation, each of them corresponds via the famous Spyke VoIP system during the day. We know that when two people call each other via Spyke, the Spyke network assigns a unique ID to this call, a positive integer session number.

One day Polycarpus wondered which secretaries are talking via the Spyke and which are not. For each secretary, he wrote out either the session number of his call or a 0 if this secretary wasn't talking via Spyke at that moment.

Help Polycarpus analyze these data and find out the number of pairs of secretaries that are talking. If Polycarpus has made a mistake in the data and the described situation could not have taken place, say so.

Note that the secretaries can correspond via Spyke not only with each other, but also with the people from other places. Also, Spyke conferences aren't permitted — that is, one call connects exactly two people.

Input

The first line contains integer n (1 ≤ n ≤ 103) — the number of secretaries in Polycarpus's corporation. The next line contains n space-separated integers: id1, id2, ..., idn (0 ≤ idi ≤ 109). Number idi equals the number of the call session of the i-th secretary, if the secretary is talking via Spyke, or zero otherwise.

Consider the secretaries indexed from 1 to n in some way.

Output

Print a single integer — the number of pairs of chatting secretaries, or -1 if Polycarpus's got a mistake in his records and the described situation could not have taken place.

Examples

Input

6
0 1 7 1 7 10

Output

2

Input

3
1 1 1

Output

-1

Input

1
0

Output

0

Note

In the first test sample there are two Spyke calls between secretaries: secretary 2 and secretary 4, secretary 3 and secretary 5.

In the second test sample the described situation is impossible as conferences aren't allowed.

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

l=list(map(int,input().split()))

ans=0
repeat={}
for i in l:
    if i in repeat:
        repeat[i]+=1
        if i==0:
            pass
        elif repeat[i]>2:
            ans=-1
            break
        else:
            ans+=1
    else:
        repeat[i]=1
print(ans)
```


316_D1. PE Lesson

Smart Beaver decided to be not only smart, but also a healthy beaver! And so he began to attend physical education classes at school X. In this school, physical education has a very creative teacher. One of his favorite warm-up exercises is throwing balls. Students line up. Each one gets a single ball in the beginning. The balls are numbered from 1 to n (by the demand of the inventory commission).

<image> Figure 1. The initial position for n = 5.

After receiving the balls the students perform the warm-up exercise. The exercise takes place in a few throws. For each throw the teacher chooses any two arbitrary different students who will participate in it. The selected students throw their balls to each other. Thus, after each throw the students remain in their positions, and the two balls are swapped.

<image> Figure 2. The example of a throw.

In this case there was a throw between the students, who were holding the 2-nd and the 4-th balls. Since the warm-up has many exercises, each of them can only continue for little time. Therefore, for each student we know the maximum number of throws he can participate in. For this lessons maximum number of throws will be 1 or 2.

Note that after all phases of the considered exercise any ball can end up with any student. Smart Beaver decided to formalize it and introduced the concept of the "ball order". The ball order is a sequence of n numbers that correspond to the order of balls in the line. The first number will match the number of the ball of the first from the left student in the line, the second number will match the ball of the second student, and so on. For example, in figure 2 the order of the balls was (1, 2, 3, 4, 5), and after the throw it was (1, 4, 3, 2, 5). Smart beaver knows the number of students and for each student he knows the maximum number of throws in which he can participate. And now he is wondering: what is the number of distinct ways of ball orders by the end of the exercise.

Input

The first line contains a single number n — the number of students in the line and the number of balls. The next line contains exactly n space-separated integers. Each number corresponds to a student in the line (the i-th number corresponds to the i-th from the left student in the line) and shows the number of throws he can participate in.

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

  * 1 ≤ n ≤ 10.

The input limits for scoring 70 points are (subproblems D1+D2):

  * 1 ≤ n ≤ 500.

The input limits for scoring 100 points are (subproblems D1+D2+D3):

  * 1 ≤ n ≤ 1000000.

Output

The output should contain a single integer — the number of variants of ball orders after the warm up exercise is complete. As the number can be rather large, print it modulo 1000000007 (109 + 7).

Examples

Input

5
1 2 2 1 2

Output

120

Input

8
1 2 2 1 2 1 1 2

Output

16800


339_D. Xenia and Bit Operations

Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.

Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.

Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4) →  (1 or 2 = 3, 3 or 4 = 7) →  (3 xor 7 = 4). The result is v = 4.

You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.

Input

The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai < 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi < 230) — the i-th query.

Output

Print m integers — the i-th integer denotes value v for sequence a after the i-th query.

Examples

Input

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

Output

1
3
3
3

Note

For more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation

```python
from operator import or_, xor
import sys
greg=1
#Stolen from tchr to test Xenia and Bit Operations speed.

n, m = map(int, input().split())
t = [list(map(int, input().split()))]
for i in range(n):
    t += [[(or_, xor)[i & 1](*t[i][j: j + 2]) for j in range(0, len(t[i]), 2)]]

for s in sys.stdin:
    p, b = s.split()
    p = int(p) - 1
    t[0][p] = int(b)
    for j in range(n):
        p >>= 1
        t[j + 1][p] = (or_, xor)[j & 1](*t[j][p << 1: (p << 1) + 2])
    print(t[-1][0])

```


362_A. Two Semiknights Meet

A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard.

Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count.

Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board.

Please see the test case analysis.

Input

The first line contains number t (1 ≤ t ≤ 50) — the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line.

Output

For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise.

Examples

Input

2
........
........
......#.
K..##..#
.......#
...##..#
......#.
K.......

........
........
..#.....
..#..#..
..####..
...##...
........
....K#K#

Output

YES
NO

Note

Consider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7).

On the second board the semiknights will never meet.

```python
t = int(input())
for _ in range(t):
    s = [input() for i in range(8)]
    oh = True
    flag = True
    for i in range(8):
        for j in range(8):
            if(s[i][j] == 'K'):
                if(flag):
                    pos1x = i
                    pos1y = j
                    flag = False
                else:
                    pos2x = i
                    pos2y = j
    if(pos1x % 4 == pos2x % 4) and (pos1y % 4 == pos2y % 4):
        print('YES')
    else:
        print('NO')
    if( _ < t - 1):
        k = input()

```


406_C. Graph Cutting

Little Chris is participating in a graph cutting contest. He's a pro. The time has come to test his skills to the fullest.

Chris is given a simple undirected connected graph with n vertices (numbered from 1 to n) and m edges. The problem is to cut it into edge-distinct paths of length 2. Formally, Chris has to partition all edges of the graph into pairs in such a way that the edges in a single pair are adjacent and each edge must be contained in exactly one pair.

For example, the figure shows a way Chris can cut a graph. The first sample test contains the description of this graph.

<image>

You are given a chance to compete with Chris. Find a way to cut the given graph or determine that it is impossible!

Input

The first line of input contains two space-separated integers n and m (1 ≤ n, m ≤ 105), the number of vertices and the number of edges in the graph. The next m lines contain the description of the graph's edges. The i-th line contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi), the numbers of the vertices connected by the i-th edge. It is guaranteed that the given graph is simple (without self-loops and multi-edges) and connected.

Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.

Output

If it is possible to cut the given graph into edge-distinct paths of length 2, output <image> lines. In the i-th line print three space-separated integers xi, yi and zi, the description of the i-th path. The graph should contain this path, i.e., the graph should contain edges (xi, yi) and (yi, zi). Each edge should appear in exactly one path of length 2. If there are multiple solutions, output any of them.

If it is impossible to cut the given graph, print "No solution" (without quotes).

Examples

Input

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

Output

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

Input

3 3
1 2
2 3
3 1

Output

No solution

Input

3 2
1 2
2 3

Output

1 2 3

```python
import sys

input = sys.stdin.readline
print = sys.stdout.write

def get_input():
    n, m = [int(x) for x in input().split(' ')]

    graph = [[] for _ in range(n + 1)]
    for _ in range(m):
        c1, c2 = [int(x) for x in input().split(' ')]
        graph[c1].append(c2)
        graph[c2].append(c1)

    if m % 2 != 0:
        print("No solution")
        exit(0)

    return graph

def dfs(graph):
    n = len(graph)
    w = [0] * n
    pi = [None] * n
    visited = [False] * n
    finished = [False] * n
    adjacency = [[] for _ in range(n)]

    stack = [1]
    while stack:
        current_node = stack[-1]

        if visited[current_node]:
            stack.pop()
            if finished[current_node]:
                w[current_node] = 0
                continue

            # print(current_node, adjacency[current_node])
            finished[current_node] = True
            unpair = []
            for adj in adjacency[current_node]:
                if w[adj] == 0:
                    # print('unpaired ->', adj, w[adj])
                    unpair.append(adj)
                else:
                    print(' '.join([str(current_node), str(adj), str(w[adj]), '\n']))

            while len(unpair) > 1:
                print(' '.join([str(unpair.pop()), str(current_node), str(unpair.pop()), '\n']))
            w[current_node] = unpair.pop() if unpair else 0
            continue

        visited[current_node] = True
        not_blocked_neighbors = [x for x in graph[current_node] if not visited[x]]
        stack += not_blocked_neighbors
        adjacency[current_node] = not_blocked_neighbors
        # print('stack:', stack, current_node)

# def recursive_dfs(graph):
#     n = len(graph)
#     visited = [False] * n
#     recursive_dfs_visit(graph, 1, visited)

# def recursive_dfs_visit(graph, root, visited):
#     unpair = []
#     visited[root] = True
#     adjacency = [x for x in graph[root] if not visited[x]]
#     for adj in adjacency:
#         w = recursive_dfs_visit(graph, adj, visited)
#         if w == 0:
#             unpair.append(adj)
#         else:
#             print(' '.join([str(root), str(adj), str(w), '\n']))

#     while len(unpair) > 1:
#         print(' '.join([str(unpair.pop()), str(root), str(unpair.pop()), '\n']))

#     if unpair:
#         return unpair.pop()
#     return 0

if __name__ == "__main__":
    graph = get_input()
    dfs(graph)

```


456_A. Laptops

One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality of the first laptop is higher (strictly greater) than the quality of the second laptop.

Please, check the guess of Alex. You are given descriptions of n laptops. Determine whether two described above laptops exist.

Input

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

Next n lines contain two integers each, ai and bi (1 ≤ ai, bi ≤ n), where ai is the price of the i-th laptop, and bi is the number that represents the quality of the i-th laptop (the larger the number is, the higher is the quality).

All ai are distinct. All bi are distinct.

Output

If Alex is correct, print "Happy Alex", otherwise print "Poor Alex" (without the quotes).

Examples

Input

2
1 2
2 1

Output

Happy Alex

```python
n = int(input())
for _ in range(n):
    a,b = map(int,input().split())
    if a!=b:
        print ('Happy Alex')
        exit()
print ('Poor Alex')
```


478_D. Red-Green Towers

There are r red and g green blocks for construction of the red-green tower. Red-green tower can be built following next rules:

  * Red-green tower is consisting of some number of levels;

  * Let the red-green tower consist of n levels, then the first level of this tower should consist of n blocks, second level — of n - 1 blocks, the third one — of n - 2 blocks, and so on — the last level of such tower should consist of the one block. In other words, each successive level should contain one block less than the previous one;

  * Each level of the red-green tower should contain blocks of the same color.

<image>

Let h be the maximum possible number of levels of red-green tower, that can be built out of r red and g green blocks meeting the rules above. The task is to determine how many different red-green towers having h levels can be built out of the available blocks.

Two red-green towers are considered different if there exists some level, that consists of red blocks in the one tower and consists of green blocks in the other tower.

You are to write a program that will find the number of different red-green towers of height h modulo 109 + 7.

Input

The only line of input contains two integers r and g, separated by a single space — the number of available red and green blocks respectively (0 ≤ r, g ≤ 2·105, r + g ≥ 1).

Output

Output the only integer — the number of different possible red-green towers of height h modulo 109 + 7.

Examples

Input

4 6

Output

2

Input

9 7

Output

6

Input

1 1

Output

2

Note

The image in the problem statement shows all possible red-green towers for the first sample.

```python
"""
#If FastIO not needed, used this and don't forget to strip
#import sys, math
#input = sys.stdin.readline
"""

import os
import sys
from io import BytesIO, IOBase
import heapq as h
import bisect

from types import GeneratorType
BUFSIZE = 8192
class SortedList:
    def __init__(self, iterable=[], _load=200):
        """Initialize sorted list instance."""
        values = sorted(iterable)
        self._len = _len = len(values)
        self._load = _load
        self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
        self._list_lens = [len(_list) for _list in _lists]
        self._mins = [_list[0] for _list in _lists]
        self._fen_tree = []
        self._rebuild = True

    def _fen_build(self):
        """Build a fenwick tree instance."""
        self._fen_tree[:] = self._list_lens
        _fen_tree = self._fen_tree
        for i in range(len(_fen_tree)):
            if i | i + 1 < len(_fen_tree):
                _fen_tree[i | i + 1] += _fen_tree[i]
        self._rebuild = False

    def _fen_update(self, index, value):
        """Update `fen_tree[index] += value`."""
        if not self._rebuild:
            _fen_tree = self._fen_tree
            while index < len(_fen_tree):
                _fen_tree[index] += value
                index |= index + 1

    def _fen_query(self, end):
        """Return `sum(_fen_tree[:end])`."""
        if self._rebuild:
            self._fen_build()

        _fen_tree = self._fen_tree
        x = 0
        while end:
            x += _fen_tree[end - 1]
            end &= end - 1
        return x

    def _fen_findkth(self, k):
        """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
        _list_lens = self._list_lens
        if k < _list_lens[0]:
            return 0, k
        if k >= self._len - _list_lens[-1]:
            return len(_list_lens) - 1, k + _list_lens[-1] - self._len
        if self._rebuild:
            self._fen_build()

        _fen_tree = self._fen_tree
        idx = -1
        for d in reversed(range(len(_fen_tree).bit_length())):
            right_idx = idx + (1 << d)
            if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
                idx = right_idx
                k -= _fen_tree[idx]
        return idx + 1, k

    def _delete(self, pos, idx):
        """Delete value at the given `(pos, idx)`."""
        _lists = self._lists
        _mins = self._mins
        _list_lens = self._list_lens

        self._len -= 1
        self._fen_update(pos, -1)
        del _lists[pos][idx]
        _list_lens[pos] -= 1

        if _list_lens[pos]:
            _mins[pos] = _lists[pos][0]
        else:
            del _lists[pos]
            del _list_lens[pos]
            del _mins[pos]
            self._rebuild = True

    def _loc_left(self, value):
        """Return an index pair that corresponds to the first position of `value` in the sorted list."""
        if not self._len:
            return 0, 0

        _lists = self._lists
        _mins = self._mins

        lo, pos = -1, len(_lists) - 1
        while lo + 1 < pos:
            mi = (lo + pos) >> 1
            if value <= _mins[mi]:
                pos = mi
            else:
                lo = mi

        if pos and value <= _lists[pos - 1][-1]:
            pos -= 1

        _list = _lists[pos]
        lo, idx = -1, len(_list)
        while lo + 1 < idx:
            mi = (lo + idx) >> 1
            if value <= _list[mi]:
                idx = mi
            else:
                lo = mi

        return pos, idx

    def _loc_right(self, value):
        """Return an index pair that corresponds to the last position of `value` in the sorted list."""
        if not self._len:
            return 0, 0

        _lists = self._lists
        _mins = self._mins

        pos, hi = 0, len(_lists)
        while pos + 1 < hi:
            mi = (pos + hi) >> 1
            if value < _mins[mi]:
                hi = mi
            else:
                pos = mi

        _list = _lists[pos]
        lo, idx = -1, len(_list)
        while lo + 1 < idx:
            mi = (lo + idx) >> 1
            if value < _list[mi]:
                idx = mi
            else:
                lo = mi

        return pos, idx

    def add(self, value):
        """Add `value` to sorted list."""
        _load = self._load
        _lists = self._lists
        _mins = self._mins
        _list_lens = self._list_lens

        self._len += 1
        if _lists:
            pos, idx = self._loc_right(value)
            self._fen_update(pos, 1)
            _list = _lists[pos]
            _list.insert(idx, value)
            _list_lens[pos] += 1
            _mins[pos] = _list[0]
            if _load + _load < len(_list):
                _lists.insert(pos + 1, _list[_load:])
                _list_lens.insert(pos + 1, len(_list) - _load)
                _mins.insert(pos + 1, _list[_load])
                _list_lens[pos] = _load
                del _list[_load:]
                self._rebuild = True
        else:
            _lists.append([value])
            _mins.append(value)
            _list_lens.append(1)
            self._rebuild = True

    def discard(self, value):
        """Remove `value` from sorted list if it is a member."""
        _lists = self._lists
        if _lists:
            pos, idx = self._loc_right(value)
            if idx and _lists[pos][idx - 1] == value:
                self._delete(pos, idx - 1)

    def remove(self, value):
        """Remove `value` from sorted list; `value` must be a member."""
        _len = self._len
        self.discard(value)
        if _len == self._len:
            raise ValueError('{0!r} not in list'.format(value))

    def pop(self, index=-1):
        """Remove and return value at `index` in sorted list."""
        pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
        value = self._lists[pos][idx]
        self._delete(pos, idx)
        return value

    def bisect_left(self, value):
        """Return the first index to insert `value` in the sorted list."""
        pos, idx = self._loc_left(value)
        return self._fen_query(pos) + idx

    def bisect_right(self, value):
        """Return the last index to insert `value` in the sorted list."""
        pos, idx = self._loc_right(value)
        return self._fen_query(pos) + idx

    def count(self, value):
        """Return number of occurrences of `value` in the sorted list."""
        return self.bisect_right(value) - self.bisect_left(value)

    def __len__(self):
        """Return the size of the sorted list."""
        return self._len

    def __getitem__(self, index):
        """Lookup value at `index` in sorted list."""
        pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
        return self._lists[pos][idx]

    def __delitem__(self, index):
        """Remove value at `index` from sorted list."""
        pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
        self._delete(pos, idx)

    def __contains__(self, value):
        """Return true if `value` is an element of the sorted list."""
        _lists = self._lists
        if _lists:
            pos, idx = self._loc_left(value)
            return idx < len(_lists[pos]) and _lists[pos][idx] == value
        return False

    def __iter__(self):
        """Return an iterator over the sorted list."""
        return (value for _list in self._lists for value in _list)

    def __reversed__(self):
        """Return a reverse iterator over the sorted list."""
        return (value for _list in reversed(self._lists) for value in reversed(_list))

    def __repr__(self):
        """Return string representation of sorted list."""
        return 'SortedList({0})'.format(list(self))

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

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

import collections as col
import math, string

def getInts():
    return [int(s) for s in input().split()]

def getInt():
    return int(input())

def getStrs():
    return [s for s in input().split()]

def getStr():
    return input()

def listStr():
    return list(input())

MOD = 10**9+7
mod=10**9+7
#t=int(input())
t=1
p=10**9+7
def ncr_util():

    inv[0]=inv[1]=1
    fact[0]=fact[1]=1
    for i in range(2,300001):
        inv[i]=(inv[i%p]*(p-p//i))%p
    for i in range(1,300001):
        inv[i]=(inv[i-1]*inv[i])%p
        fact[i]=(fact[i-1]*i)%p

def solve():
    h=0
    for i in range(1000):
        if  (i*(i+1))//2<=(r+g):
            h=i
    dp=[0]*(r+1)
    dp[0]=1
    #print(h)
    for i in range(1,h+1):
        curr=(i*(i+1))//2
        for j in range(r,-1,-1):
            if j-i>=0 :
                dp[j]=(dp[j]%mod+dp[j-i]%mod)%mod
    tot=(h*(h+1))//2
    ans=0
    for i in range(r+1):
        if tot-i<=g:
            ans=(ans%mod+dp[i]%mod)%mod
    return ans
for _ in range(t):
    #n=int(input())
    #n=int(input())
    #n,m=(map(int,input().split()))
    #n1=n
    #x=int(input())
    #b=int(input())
    #n,m,k=map(int,input().split())
    r,g=map(int,input().split())
    #n=int(input())
    #s=input()
    #s1=input()
    #p=input()
    #l=list(map(int,input().split()))

    #l.sort()
    #l.sort(revrese=True)
    #l2=list(map(int,input().split()))
    #l=str(n)
    #l.sort(reverse=True)
    #l2.sort(reverse=True)
    #l1.sort(reverse=True)
    print(solve())

```


5_D. Follow Traffic Rules

Everybody knows that the capital of Berland is connected to Bercouver (the Olympic capital) by a direct road. To improve the road's traffic capacity, there was placed just one traffic sign, limiting the maximum speed. Traffic signs in Berland are a bit peculiar, because they limit the speed only at that point on the road where they are placed. Right after passing the sign it is allowed to drive at any speed.

It is known that the car of an average Berland citizen has the acceleration (deceleration) speed of a km/h2, and has maximum speed of v km/h. The road has the length of l km, and the speed sign, limiting the speed to w km/h, is placed d km (1 ≤ d < l) away from the capital of Berland. The car has a zero speed at the beginning of the journey. Find the minimum time that an average Berland citizen will need to get from the capital to Bercouver, if he drives at the optimal speed.

The car can enter Bercouver at any speed.

Input

The first line of the input file contains two integer numbers a and v (1 ≤ a, v ≤ 10000). The second line contains three integer numbers l, d and w (2 ≤ l ≤ 10000; 1 ≤ d < l; 1 ≤ w ≤ 10000).

Output

Print the answer with at least five digits after the decimal point.

Examples

Input

1 1
2 1 3

Output

2.500000000000

Input

5 70
200 170 40

Output

8.965874696353

```python
"""
Codeforces
5D - Follow Traffic Rules
http://codeforces.com/contest/5/problem/D

Héctor González Belver
../07/2018
"""
import sys

def time_distance(v0, a, d):
  #quadratic equation. Time is positive ==> root with (+discriminant) in quadratic formula
  #d = v0*t + (a/2)*t^2
  return (-v0 + (v0**2 + 2*a*d)**0.5)/a

def time_accelerating(v0, v1, a):
  return (v1 - v0)/a

def time_speed(v, d):
  return d/v

def distance_travelled(v0, t, a):
  return v0*t + (a/2)*t**2

def main():
  a, v = map(int,sys.stdin.readline().strip().split())
  l, d, w = map(int,sys.stdin.readline().strip().split())

  time = 0

  time_to_d = time_distance(0, a, d)
  time_to_v = time_accelerating(0, v, a)

  if (v if time_to_v <= time_to_d else time_to_d * a) <= w:
    #Accelerating 0-v
    acceleration_time = time_to_v
    acceleration_distance = distance_travelled(0, acceleration_time, a)

    if acceleration_distance >= l:
      #Accelerating 0-?
      time = time_distance(0, a, l)
    else:
      #Accelerating 0-v
      time = acceleration_time
      #Max speed v
      time += time_speed(v, l - acceleration_distance)

  else:
    if time_to_v <= time_to_d:
      #Accelerating 0-v
      acceleration_time = time_to_v
      acceleration_distance = distance_travelled(0, acceleration_time, a)

      #Decelerating v-w
      deceleration_time = time_accelerating(v, w, -a)
      deceleration_distance = distance_travelled(v, deceleration_time, -a)

    if time_to_v > time_to_d or acceleration_distance + deceleration_distance > d:
      #Accelerating 0-w
      acceleration_time = time_accelerating(0, w, a)
      acceleration_distance = distance_travelled(0, acceleration_time, a)

      remaining_distance = d - acceleration_distance
      #Remaining distance --> Acceleration = -Deceleration ==> half remaining distance each action
      delta_time = time_distance(w, a, remaining_distance/2)
      #Accelerating 0-? and Decelerating ?-w
      time = acceleration_time + 2*delta_time
    else:
      #Accelerating 0-v
      time = time_to_v
      #Max speed v
      time += time_speed(v, d - deceleration_distance - acceleration_distance)
      #Decelerating v-w
      time += deceleration_time

    #Accelerating w-v
    acceleration_time = time_accelerating(w, v, a)
    acceleration_distance = distance_travelled(w, acceleration_time, a)
    if acceleration_distance >= l - d:
      #Accelerating w-?
      time += time_distance(w, a, l - d)
    else:
      #Accelerating w-v
      time += acceleration_time
      #Max speed v
      time += time_speed(v, l - (d + acceleration_distance))

  sys.stdout.write('{0:.5f}'.format(time) + '\n')

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


622_B. The Time

You are given the current time in 24-hour format hh:mm. Find and print the time after a minutes.

Note that you should find only the time after a minutes, see the examples to clarify the problem statement.

You can read more about 24-hour format here <https://en.wikipedia.org/wiki/24-hour_clock>.

Input

The first line contains the current time in the format hh:mm (0 ≤ hh < 24, 0 ≤ mm < 60). The hours and the minutes are given with two digits (the hours or the minutes less than 10 are given with the leading zeroes).

The second line contains integer a (0 ≤ a ≤ 104) — the number of the minutes passed.

Output

The only line should contain the time after a minutes in the format described in the input. Note that you should print exactly two digits for the hours and the minutes (add leading zeroes to the numbers if needed).

See the examples to check the input/output format.

Examples

Input

23:59
10

Output

00:09

Input

20:20
121

Output

22:21

Input

10:10
0

Output

10:10

```python
#!/usr/bin/env python3

import datetime

def main(args):
    hh, mm = list(map(int, input().split(':')))
    a = int(input())
    mm += a
    hh += (mm // 60)
    mm %= 60
    hh %= 24
    print(f"{hh:02d}:{mm:02d}")
    return 0

if __name__ == '__main__':
    import sys
    sys.exit(main(sys.argv))

```


670_D2. Magic Powder - 2

The term of this problem is the same as the previous one, the only exception — increased restrictions.

Input

The first line contains two positive integers n and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ 109) — the number of ingredients and the number of grams of the magic powder.

The second line contains the sequence a1, a2, ..., an (1 ≤ ai ≤ 109), where the i-th number is equal to the number of grams of the i-th ingredient, needed to bake one cookie.

The third line contains the sequence b1, b2, ..., bn (1 ≤ bi ≤ 109), where the i-th number is equal to the number of grams of the i-th ingredient, which Apollinaria has.

Output

Print the maximum number of cookies, which Apollinaria will be able to bake using the ingredients that she has and the magic powder.

Examples

Input

1 1000000000
1
1000000000

Output

2000000000

Input

10 1
1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000
1 1 1 1 1 1 1 1 1 1

Output

0

Input

3 1
2 1 4
11 3 16

Output

4

Input

4 3
4 3 5 6
11 12 14 20

Output

3

```python
n, k = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
l = 0
r = 10 ** 10
while r - l > 1:
    m = (r + l) // 2
    poroshok = 0
    for i in range(n):
        tr = A[i] * m - B[i]
        poroshok += max(tr, 0)
    if poroshok > k:
        r = m
    else:
        l = m
print(l)

```


696_A. Lorenzo Von Matterhorn

Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections.

<image>

Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:

1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars.

2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.

Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).

Input

The first line of input contains a single integer q (1 ≤ q ≤ 1 000).

The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u.

1 ≤ v, u ≤ 1018, v ≠ u, 1 ≤ w ≤ 109 states for every description line.

Output

For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.

Example

Input

7
1 3 4 30
1 4 1 2
1 3 6 8
2 4 3
1 6 1 40
2 3 7
2 2 4

Output

94
0
32

Note

In the example testcase:

Here are the intersections used:

<image>

  1. Intersections on the path are 3, 1, 2 and 4.
  2. Intersections on the path are 4, 2 and 1.
  3. Intersections on the path are only 3 and 6.
  4. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94.
  5. Intersections on the path are 6, 3 and 1.
  6. Intersections on the path are 3 and 7. Passing fee of the road between them is 0.
  7. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).

```python
def find_path(x,y):
	p1,p2 = [],[]
	while x!=0:
		p1.append(x)
		x = x//2
	while y!=0:
		p2.append(y)
		y = y//2
	p1 = p1[::-1]
	p2 = p2[::-1]
	# print (p1,p2)
	for i in range(min(len(p1),len(p2))):
		if p1[i]==p2[i]:
			ind = i
		else:
			break
	path = []
	for i in range(ind,len(p1)):
		path.append(p1[i])
	path = path[::-1]
	for i in range(ind+1,len(p2)):
		path.append(p2[i])

	return path

q = int(input())
cost = {}
for i in range(q):
	a = list(map(int,input().split()))
	b = find_path(a[1],a[2])
	# print (b)
	if a[0] == 1:
		w = a[-1]
		for j in range(1,len(b)):
			if (b[j],b[j-1]) not in cost:
				cost[(b[j],b[j-1])] = w
				cost[(b[j-1],b[j])] = w
			else:
				cost[(b[j],b[j-1])] += w
				cost[(b[j-1],b[j])] += w
	else:
		ans = 0
		for j in range(1,len(b)):
			if (b[j],b[j-1]) in cost:
				ans += cost[(b[j],b[j-1])]
		print (ans)

```


717_B. R3D3’s Summer Adventure

R3D3 spent some time on an internship in MDCS. After earning enough money, he decided to go on a holiday somewhere far, far away. He enjoyed suntanning, drinking alcohol-free cocktails and going to concerts of popular local bands. While listening to "The White Buttons" and their hit song "Dacan the Baker", he met another robot for whom he was sure is the love of his life. Well, his summer, at least. Anyway, R3D3 was too shy to approach his potential soulmate, so he decided to write her a love letter. However, he stumbled upon a problem. Due to a terrorist threat, the Intergalactic Space Police was monitoring all letters sent in the area. Thus, R3D3 decided to invent his own alphabet, for which he was sure his love would be able to decipher.

There are n letters in R3D3’s alphabet, and he wants to represent each letter as a sequence of '0' and '1', so that no letter’s sequence is a prefix of another letter's sequence. Since the Intergalactic Space Communications Service has lately introduced a tax for invented alphabets, R3D3 must pay a certain amount of money for each bit in his alphabet’s code (check the sample test for clarifications). He is too lovestruck to think clearly, so he asked you for help.

Given the costs c0 and c1 for each '0' and '1' in R3D3’s alphabet, respectively, you should come up with a coding for the alphabet (with properties as above) with minimum total cost.

Input

The first line of input contains three integers n (2 ≤ n ≤ 108), c0 and c1 (0 ≤ c0, c1 ≤ 108) — the number of letters in the alphabet, and costs of '0' and '1', respectively.

Output

Output a single integer — minimum possible total a cost of the whole alphabet.

Example

Input

4 1 2

Output

12

Note

There are 4 letters in the alphabet. The optimal encoding is "00", "01", "10", "11". There are 4 zeroes and 4 ones used, so the total cost is 4·1 + 4·2 = 12.

```python
import sys,heapq

#sys.stdin=open("data.txt")

input=sys.stdin.readline

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

if a<b: a,b=b,a

if b==0:

    # 1 01 001 0001 ... is optimal, plus a long series of 0's

    print((n-1)*a)

else:

    # pascal's triangle thing

    pascal=[[1]*20005]

    for i in range(20004):

        newrow=[1]

        for j in range(1,20005):

            newrow.append(newrow[-1]+pascal[-1][j])

            if newrow[-1]>n: break

        pascal.append(newrow)

    def getcom(a,b):

        # return a+b choose b

        # if larger than n, return infinite

        if len(pascal[a])>b: return pascal[a][b]

        if b==0: return 1

        if b==1: return a

        return 100000005

    # start with the null node (prefix cost 0)

    # can split a node into two other nodes with added cost c+a+b

    # new nodes have prefix costs c+a, c+b

    # want n-1 splits in total

    remain=n-1

    ans=0

    possible=[[a+b,1]]    # [c,count]

    while 1:

        # cost u, v leaves

        u,v=heapq.heappop(possible)

        while possible and possible[0][0]==u:

            v+=possible[0][1]

            heapq.heappop(possible)

        if remain<=v:

            ans+=u*remain

            break

        ans+=u*v

        remain-=v

        heapq.heappush(possible,[u+a,v])

        heapq.heappush(possible,[u+b,v])

    print(ans)

# Made By Mostafa_Khaled
```


761_C. Dasha and Password

After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length n which satisfies the following requirements:

  * There is at least one digit in the string,
  * There is at least one lowercase (small) letter of the Latin alphabet in the string,
  * There is at least one of three listed symbols in the string: '#', '*', '&'.

<image>

Considering that these are programming classes it is not easy to write the password.

For each character of the password we have a fixed string of length m, on each of these n strings there is a pointer on some character. The i-th character displayed on the screen is the pointed character in the i-th string. Initially, all pointers are on characters with indexes 1 in the corresponding strings (all positions are numbered starting from one).

During one operation Dasha can move a pointer in one string one character to the left or to the right. Strings are cyclic, it means that when we move the pointer which is on the character with index 1 to the left, it moves to the character with the index m, and when we move it to the right from the position m it moves to the position 1.

You need to determine the minimum number of operations necessary to make the string displayed on the screen a valid password.

Input

The first line contains two integers n, m (3 ≤ n ≤ 50, 1 ≤ m ≤ 50) — the length of the password and the length of strings which are assigned to password symbols.

Each of the next n lines contains the string which is assigned to the i-th symbol of the password string. Its length is m, it consists of digits, lowercase English letters, and characters '#', '*' or '&'.

You have such input data that you can always get a valid password.

Output

Print one integer — the minimum number of operations which is necessary to make the string, which is displayed on the screen, a valid password.

Examples

Input

3 4
1**2
a3*0
c4**

Output

1

Input

5 5
#*&#*
*a1c&
&q2w*
#a3c#
*&#*&

Output

3

Note

In the first test it is necessary to move the pointer of the third string to one left to get the optimal answer.

<image>

In the second test one of possible algorithms will be:

  * to move the pointer of the second symbol once to the right.
  * to move the pointer of the third symbol twice to the right.

<image>

```python
n,m=map(int,input().split())
m1,m2,m3=[m+1]*n,[m+1]*n,[m+1]*n
for i in range(n):
    s=input()
    for j, c in enumerate(s):
        z=min(j, m-j)
        if c>='0' and c<='9':
            m1[i]=min(m1[i],z)
        else:
            if c>='a' and c<='z':
                m2[i]=min(m2[i],z)
            else:
                m3[i]=min(m3[i],z)
ans=m*3
for i in range(n):
    for j in range(n):
        if i!=j:
            for p in range(n):
                if i!=p and j!=p:
                    ans=min(ans,m1[i]+m2[j]+m3[p])
print(ans)

```


784_E. Twisted Circuit

<image>

Input

The input consists of four lines, each line containing a single digit 0 or 1.

Output

Output a single digit, 0 or 1.

Example

Input

0
1
1
0

Output

0

```python
import collections as col
import itertools as its
import sys
import operator
from bisect import bisect_left, bisect_right
from copy import copy, deepcopy

class Solver:
    def __init__(self):
        pass

    def solve(self):
        a = int(input())
        b = int(input())
        c = int(input())
        d = int(input())
        l11 = a ^ b
        l12 = c | d
        l13 = b & c
        l14 = a ^ d
        l21 = l11 & l12
        l22 = l13 | l14
        print(l21 ^ l22)

if __name__ == '__main__':
    s = Solver()
    s.solve()

```


805_D. Minimum number of steps

We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings "ab" in the string and replace it with the string "bba". If we have no "ab" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo 109 + 7.

The string "ab" appears as a substring if there is a letter 'b' right after the letter 'a' somewhere in the string.

Input

The first line contains the initial string consisting of letters 'a' and 'b' only with length from 1 to 106.

Output

Print the minimum number of steps modulo 109 + 7.

Examples

Input

ab

Output

1

Input

aab

Output

3

Note

The first example: "ab"  →  "bba".

The second example: "aab"  →  "abba"  →  "bbaba"  →  "bbbbaa".

```python
def mess():
    String=input()
    count_it=0
    Counter=0

    for i in String:
        if i=='a':
            count_it = (count_it * 2) % Modulo
            count_it+=1

        elif i=='b':
            Counter+=count_it
            #count_it =(count_it* 2)%Modulo
    return Counter

if __name__ == "__main__":
    Modulo = 1000000007
    print(mess()%Modulo)
```


830_D. Singer House

It is known that passages in Singer house are complex and intertwined. Let's define a Singer k-house as a graph built by the following process: take complete binary tree of height k and add edges from each vertex to all its successors, if they are not yet present.

<image> Singer 4-house

Count the number of non-empty paths in Singer k-house which do not pass the same vertex twice. Two paths are distinct if the sets or the orders of visited vertices are different. Since the answer can be large, output it modulo 109 + 7.

Input

The only line contains single integer k (1 ≤ k ≤ 400).

Output

Print single integer — the answer for the task modulo 109 + 7.

Examples

Input

2

Output

9

Input

3

Output

245

Input

20

Output

550384565

Note

There are 9 paths in the first example (the vertices are numbered on the picture below): 1, 2, 3, 1-2, 2-1, 1-3, 3-1, 2-1-3, 3-1-2.

<image> Singer 2-house


876_A. Trip For Meal

Winnie-the-Pooh likes honey very much! That is why he decided to visit his friends. Winnie has got three best friends: Rabbit, Owl and Eeyore, each of them lives in his own house. There are winding paths between each pair of houses. The length of a path between Rabbit's and Owl's houses is a meters, between Rabbit's and Eeyore's house is b meters, between Owl's and Eeyore's house is c meters.

For enjoying his life and singing merry songs Winnie-the-Pooh should have a meal n times a day. Now he is in the Rabbit's house and has a meal for the first time. Each time when in the friend's house where Winnie is now the supply of honey is about to end, Winnie leaves that house. If Winnie has not had a meal the required amount of times, he comes out from the house and goes to someone else of his two friends. For this he chooses one of two adjacent paths, arrives to the house on the other end and visits his friend. You may assume that when Winnie is eating in one of his friend's house, the supply of honey in other friend's houses recover (most probably, they go to the supply store).

Winnie-the-Pooh does not like physical activity. He wants to have a meal n times, traveling minimum possible distance. Help him to find this distance.

Input

First line contains an integer n (1 ≤ n ≤ 100) — number of visits.

Second line contains an integer a (1 ≤ a ≤ 100) — distance between Rabbit's and Owl's houses.

Third line contains an integer b (1 ≤ b ≤ 100) — distance between Rabbit's and Eeyore's houses.

Fourth line contains an integer c (1 ≤ c ≤ 100) — distance between Owl's and Eeyore's houses.

Output

Output one number — minimum distance in meters Winnie must go through to have a meal n times.

Examples

Input

3
2
3
1

Output

3

Input

1
2
3
5

Output

0

Note

In the first test case the optimal path for Winnie is the following: first have a meal in Rabbit's house, then in Owl's house, then in Eeyore's house. Thus he will pass the distance 2 + 1 = 3.

In the second test case Winnie has a meal in Rabbit's house and that is for him. So he doesn't have to walk anywhere at all.

```python
# 876A

def main():
	n, a, b, c = int(input()), int(input()), int(input()), int(input())
	if n == 1:
		return 0
	n -= 1
	count = 0
	state = 0
	while n:
		if state == 0:
			if a > b:
				count += b
				state = 2
			else:
				count += a
				state = 1
		elif state == 1:
			if a > c:
				count += c
				state = 2
			else:
				count += a
				state = 0
		else:
			if b > c:
				count += c
				state = 1
			else:
				count += b
				state = 0
		n -= 1

	return count

if __name__ == "__main__":
	print(main())
	# input()
```